hexsha
stringlengths 40
40
| repo
stringlengths 5
114
| path
stringlengths 4
295
| license
listlengths 1
10
| language
stringclasses 5
values | identifier
stringlengths 1
116
| original_docstring
stringlengths 133
7.85k
| docstring
stringlengths 7
2.1k
| docstring_tokens
listlengths 3
399
| code
stringlengths 350
22.6k
| code_tokens
listlengths 20
3.22k
| short_docstring
stringlengths 0
1.32k
| short_docstring_tokens
listlengths 0
359
| comment
listlengths 0
1.22k
| parameters
listlengths 0
13
| docstring_params
dict | has_error
bool 1
class | ast_depth
int64 13
29
| code_length
int64 151
3k
| original_docstring_length
int64 76
449
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c7c6bbec7bccdcea77997534b5c34f2fdae4e67d
|
racoq/TESRAC
|
evosuite/runtime/src/main/java/org/evosuite/runtime/testdata/FileSystemHandling.java
|
[
"Apache-2.0"
] |
Java
|
FileSystemHandling
|
/**
* This class is used create files as test data
* in the test cases.
*
* <p>
* The methods in this class are the main ones that are going
* to be used in the generated JUnit files to manipulate
* the virtual file system.
* Note: if SUT takes as input a {@code File}, then it can happen
* that mock {@code java.io} objects manipulating the VFS will appear in the test
* cases.
*
* @author arcuri
*
*/
|
This class is used create files as test data
in the test cases.
The methods in this class are the main ones that are going
to be used in the generated JUnit files to manipulate
the virtual file system.
Note: if SUT takes as input a File, then it can happen
that mock java.io objects manipulating the VFS will appear in the test
cases.
@author arcuri
|
[
"This",
"class",
"is",
"used",
"create",
"files",
"as",
"test",
"data",
"in",
"the",
"test",
"cases",
".",
"The",
"methods",
"in",
"this",
"class",
"are",
"the",
"main",
"ones",
"that",
"are",
"going",
"to",
"be",
"used",
"in",
"the",
"generated",
"JUnit",
"files",
"to",
"manipulate",
"the",
"virtual",
"file",
"system",
".",
"Note",
":",
"if",
"SUT",
"takes",
"as",
"input",
"a",
"File",
"then",
"it",
"can",
"happen",
"that",
"mock",
"java",
".",
"io",
"objects",
"manipulating",
"the",
"VFS",
"will",
"appear",
"in",
"the",
"test",
"cases",
".",
"@author",
"arcuri"
] |
public class FileSystemHandling {
/**
* Append a string to the given file.
* If the file does not exist, it will be created.
*
* @return
*/
public static boolean appendStringToFile(EvoSuiteFile file, String value){
if(file==null || value==null){
return false;
}
return appendDataToFile(file,value.getBytes());
}
/**
* Append a string to the given file, and then move cursor
* to the next line.
* If the file does not exist, it will be created.
*
* @return
*/
public static boolean appendLineToFile(EvoSuiteFile file, String line){
if(file==null || line==null){
return false;
}
return appendStringToFile(file, line + "\n");
}
/**
* Append a byte array to the given file.
* If the file does not exist, it will be created.
*
* @param data
* @return
*/
public static boolean appendDataToFile(EvoSuiteFile file, byte[] data){
if(file==null || data==null){
return false;
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(file.getPath());
//can we write to it?
if(target!=null && (target.isFolder() || !target.isWritePermission())){
return false;
}
if(target==null){
//if it does not exist, let's create it
boolean created = VirtualFileSystem.getInstance().createFile(file.getPath());
if(!created){
return false;
}
target = VirtualFileSystem.getInstance().findFSObject(file.getPath());
assert target != null;
}
VFile vf = (VFile) target;
vf.writeBytes(data, 0, data.length);
return true;
}
public static boolean createFolder(EvoSuiteFile file){
if(file==null){
return false;
}
return VirtualFileSystem.getInstance().createFolder(file.getPath());
}
/**
* Set read/write/execute permissions to the given file
*
* @param file
* @param isReadable
* @param isWritable
* @param isExecutable
* @return
*/
public static boolean setPermissions(EvoSuiteFile file, boolean isReadable, boolean isWritable, boolean isExecutable){
if(file==null){
return false;
}
FSObject target = VirtualFileSystem.getInstance().findFSObject(file.getPath());
if(target == null){
return false;
}
target.setExecutePermission(isReadable);
target.setWritePermission(isWritable);
target.setExecutePermission(isExecutable);
return true;
}
/**
* All operations on the given {@code file} will throw an IOException if that
* appears in their method signature
*
* @param file
* @return
*/
public static boolean shouldThrowIOException(EvoSuiteFile file){
if(file==null){
return false;
}
return VirtualFileSystem.getInstance().setShouldThrowIOException(file);
}
/**
* All operations in the entire VFS will throw an IOException if that
* appears in their method signature
*/
public static boolean shouldAllThrowIOExceptions(){
return VirtualFileSystem.getInstance().setShouldAllThrowIOExceptions();
}
}
|
[
"public",
"class",
"FileSystemHandling",
"{",
"/**\r\n\t * Append a string to the given file.\r\n\t * If the file does not exist, it will be created.\r\n\t * \r\n\t * @return\r\n\t */",
"public",
"static",
"boolean",
"appendStringToFile",
"(",
"EvoSuiteFile",
"file",
",",
"String",
"value",
")",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"value",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"appendDataToFile",
"(",
"file",
",",
"value",
".",
"getBytes",
"(",
")",
")",
";",
"}",
"/**\r\n\t * Append a string to the given file, and then move cursor\r\n\t * to the next line.\r\n\t * If the file does not exist, it will be created.\r\n\t * \r\n\t * @return\r\n\t */",
"public",
"static",
"boolean",
"appendLineToFile",
"(",
"EvoSuiteFile",
"file",
",",
"String",
"line",
")",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"line",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"appendStringToFile",
"(",
"file",
",",
"line",
"+",
"\"",
"\\n",
"\"",
")",
";",
"}",
"/**\r\n\t * Append a byte array to the given file.\r\n\t * If the file does not exist, it will be created.\r\n\t * \r\n\t * @param data\r\n\t * @return\r\n\t */",
"public",
"static",
"boolean",
"appendDataToFile",
"(",
"EvoSuiteFile",
"file",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"data",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"FSObject",
"target",
"=",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"findFSObject",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"target",
"!=",
"null",
"&&",
"(",
"target",
".",
"isFolder",
"(",
")",
"||",
"!",
"target",
".",
"isWritePermission",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"boolean",
"created",
"=",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"createFile",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"!",
"created",
")",
"{",
"return",
"false",
";",
"}",
"target",
"=",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"findFSObject",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"assert",
"target",
"!=",
"null",
";",
"}",
"VFile",
"vf",
"=",
"(",
"VFile",
")",
"target",
";",
"vf",
".",
"writeBytes",
"(",
"data",
",",
"0",
",",
"data",
".",
"length",
")",
";",
"return",
"true",
";",
"}",
"public",
"static",
"boolean",
"createFolder",
"(",
"EvoSuiteFile",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"createFolder",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"}",
"/**\r\n\t * Set read/write/execute permissions to the given file\r\n\t * \r\n\t * @param file\r\n\t * @param isReadable\r\n\t * @param isWritable\r\n\t * @param isExecutable\r\n\t * @return\r\n\t */",
"public",
"static",
"boolean",
"setPermissions",
"(",
"EvoSuiteFile",
"file",
",",
"boolean",
"isReadable",
",",
"boolean",
"isWritable",
",",
"boolean",
"isExecutable",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"FSObject",
"target",
"=",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"findFSObject",
"(",
"file",
".",
"getPath",
"(",
")",
")",
";",
"if",
"(",
"target",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"target",
".",
"setExecutePermission",
"(",
"isReadable",
")",
";",
"target",
".",
"setWritePermission",
"(",
"isWritable",
")",
";",
"target",
".",
"setExecutePermission",
"(",
"isExecutable",
")",
";",
"return",
"true",
";",
"}",
"/**\r\n\t * All operations on the given {@code file} will throw an IOException if that\r\n\t * appears in their method signature\r\n\t * \r\n\t * @param file\r\n\t * @return\r\n\t */",
"public",
"static",
"boolean",
"shouldThrowIOException",
"(",
"EvoSuiteFile",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"return",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"setShouldThrowIOException",
"(",
"file",
")",
";",
"}",
"/**\r\n\t * All operations in the entire VFS will throw an IOException if that\r\n\t * appears in their method signature\r\n\t */",
"public",
"static",
"boolean",
"shouldAllThrowIOExceptions",
"(",
")",
"{",
"return",
"VirtualFileSystem",
".",
"getInstance",
"(",
")",
".",
"setShouldAllThrowIOExceptions",
"(",
")",
";",
"}",
"}"
] |
This class is used create files as test data
in the test cases.
|
[
"This",
"class",
"is",
"used",
"create",
"files",
"as",
"test",
"data",
"in",
"the",
"test",
"cases",
"."
] |
[
"//can we write to it?\r",
"//if it does not exist, let's create it\r"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 742
| 109
|
d5304cffc03bc59fd73a2150a43e7bbf88dc7e6e
|
dolittle/DotNET.Runtime
|
Source/Services/ReverseCalls/WrappedAsyncStreamWriter.cs
|
[
"MIT"
] |
C#
|
WrappedAsyncStreamWriter
|
/// <summary>
/// Represents a thread-safe wrapper of <see cref="IAsyncStreamWriter{TServerMessage}"/> that also exposes special handling of ping messages and records metrics.
/// </summary>
/// <typeparam name="TClientMessage">Type of the <see cref="IMessage">messages</see> that is sent from the Client to the Runtime.</typeparam>
/// <typeparam name="TServerMessage">Type of the <see cref="IMessage">messages</see> that is sent from the Runtime to the Client.</typeparam>
/// <typeparam name="TConnectArguments">Type of the arguments that are sent along with the initial Connect call.</typeparam>
/// <typeparam name="TConnectResponse">Type of the response that is received after the initial Connect call.</typeparam>
/// <typeparam name="TRequest">Type of the requests sent from the Runtime to the Client.</typeparam>
/// <typeparam name="TResponse">Type of the responses sent from the Client to the Runtime.</typeparam>
|
Represents a thread-safe wrapper of that also exposes special handling of ping messages and records metrics.
|
[
"Represents",
"a",
"thread",
"-",
"safe",
"wrapper",
"of",
"that",
"also",
"exposes",
"special",
"handling",
"of",
"ping",
"messages",
"and",
"records",
"metrics",
"."
] |
public class WrappedAsyncStreamWriter<TClientMessage, TServerMessage, TConnectArguments, TConnectResponse, TRequest, TResponse> : IAsyncStreamWriter<TServerMessage>, IDisposable
where TClientMessage : IMessage, new()
where TServerMessage : IMessage, new()
where TConnectArguments : class
where TConnectResponse : class
where TRequest : class
where TResponse : class
{
readonly RequestId _requestId;
readonly IAsyncStreamWriter<TServerMessage> _originalStream;
readonly IConvertReverseCallMessages<TClientMessage, TServerMessage, TConnectArguments, TConnectResponse, TRequest, TResponse> _messageConverter;
readonly IMetricsCollector _metrics;
readonly ILogger _logger;
readonly CancellationToken _cancellationToken;
readonly SemaphoreSlim _writeLock = new(1);
bool _disposed;
public WrappedAsyncStreamWriter(
RequestId requestId,
IAsyncStreamWriter<TServerMessage> originalStream,
IConvertReverseCallMessages<TClientMessage, TServerMessage, TConnectArguments, TConnectResponse, TRequest, TResponse> messageConverter,
IMetricsCollector metrics,
ILogger logger,
CancellationToken cancellationToken)
{
_requestId = requestId;
_originalStream = originalStream;
_messageConverter = messageConverter;
_metrics = metrics;
_logger = logger;
_cancellationToken = cancellationToken;
}
public WriteOptions WriteOptions
{
get => _originalStream.WriteOptions;
set => _originalStream.WriteOptions = value;
}
public async Task WriteAsync(TServerMessage message)
{
_logger.WritingMessage(_requestId, typeof(TServerMessage));
_cancellationToken.ThrowIfCancellationRequested();
if (!_writeLock.Wait(0))
{
var stopwatch = Stopwatch.StartNew();
_metrics.IncrementPendingStreamWrites();
_logger.WritingMessageBlockedByAnotherWrite(_requestId, typeof(TServerMessage));
await _writeLock.WaitAsync(_cancellationToken).ConfigureAwait(false);
try
{
stopwatch.Stop();
_metrics.DecrementPendingStreamWrites();
_metrics.AddToTotalStreamWriteWaitTime(stopwatch.Elapsed);
_logger.WritingMessageUnblockedAfter(_requestId, typeof(TServerMessage), stopwatch.Elapsed);
}
catch
{ }
}
try
{
_cancellationToken.ThrowIfCancellationRequested();
var stopwatch = Stopwatch.StartNew();
await _originalStream.WriteAsync(message).ConfigureAwait(false);
stopwatch.Stop();
var messageSize = message.CalculateSize();
_metrics.AddToTotalStreamWriteTime(stopwatch.Elapsed);
_metrics.IncrementTotalStreamWrites();
_metrics.IncrementTotalStreamWriteBytes(messageSize);
_logger.WroteMessage(_requestId, stopwatch.Elapsed, messageSize);
}
finally
{
_writeLock.Release();
}
}
public void MaybeWritePing()
{
_logger.WritingPing(_requestId);
_cancellationToken.ThrowIfCancellationRequested();
if (!_writeLock.Wait(0))
{
_logger.WritingPingSkipped(_requestId);
return;
}
try
{
var ping = new Ping();
var message = new TServerMessage();
_messageConverter.SetPing(message, ping);
var stopwatch = Stopwatch.StartNew();
_originalStream.WriteAsync(message).GetAwaiter().GetResult();
stopwatch.Stop();
var messageSize = message.CalculateSize();
_metrics.AddToTotalStreamWriteTime(stopwatch.Elapsed);
_metrics.IncrementTotalStreamWrites();
_metrics.IncrementTotalStreamWriteBytes(messageSize);
_metrics.IncrementTotalPingsSent();
_logger.WrotePing(_requestId, stopwatch.Elapsed);
}
finally
{
_writeLock.Release();
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_logger.DisposingWrappedAsyncStreamWriter(_requestId);
_writeLock.Wait();
_writeLock.Dispose();
_logger.DisposedWrappedAsyncStreamWriter(_requestId);
}
_disposed = true;
}
}
|
[
"public",
"class",
"WrappedAsyncStreamWriter",
"<",
"TClientMessage",
",",
"TServerMessage",
",",
"TConnectArguments",
",",
"TConnectResponse",
",",
"TRequest",
",",
"TResponse",
">",
":",
"IAsyncStreamWriter",
"<",
"TServerMessage",
">",
",",
"IDisposable",
"where",
"TClientMessage",
":",
"IMessage",
",",
"new",
"(",
")",
"where",
"TServerMessage",
":",
"IMessage",
",",
"new",
"(",
")",
"where",
"TConnectArguments",
":",
"class",
"where",
"TConnectResponse",
":",
"class",
"where",
"TRequest",
":",
"class",
"where",
"TResponse",
":",
"class",
"{",
"readonly",
"RequestId",
"_requestId",
";",
"readonly",
"IAsyncStreamWriter",
"<",
"TServerMessage",
">",
"_originalStream",
";",
"readonly",
"IConvertReverseCallMessages",
"<",
"TClientMessage",
",",
"TServerMessage",
",",
"TConnectArguments",
",",
"TConnectResponse",
",",
"TRequest",
",",
"TResponse",
">",
"_messageConverter",
";",
"readonly",
"IMetricsCollector",
"_metrics",
";",
"readonly",
"ILogger",
"_logger",
";",
"readonly",
"CancellationToken",
"_cancellationToken",
";",
"readonly",
"SemaphoreSlim",
"_writeLock",
"=",
"new",
"(",
"1",
")",
";",
"bool",
"_disposed",
";",
"public",
"WrappedAsyncStreamWriter",
"(",
"RequestId",
"requestId",
",",
"IAsyncStreamWriter",
"<",
"TServerMessage",
">",
"originalStream",
",",
"IConvertReverseCallMessages",
"<",
"TClientMessage",
",",
"TServerMessage",
",",
"TConnectArguments",
",",
"TConnectResponse",
",",
"TRequest",
",",
"TResponse",
">",
"messageConverter",
",",
"IMetricsCollector",
"metrics",
",",
"ILogger",
"logger",
",",
"CancellationToken",
"cancellationToken",
")",
"{",
"_requestId",
"=",
"requestId",
";",
"_originalStream",
"=",
"originalStream",
";",
"_messageConverter",
"=",
"messageConverter",
";",
"_metrics",
"=",
"metrics",
";",
"_logger",
"=",
"logger",
";",
"_cancellationToken",
"=",
"cancellationToken",
";",
"}",
"public",
"WriteOptions",
"WriteOptions",
"{",
"get",
"=>",
"_originalStream",
".",
"WriteOptions",
";",
"set",
"=>",
"_originalStream",
".",
"WriteOptions",
"=",
"value",
";",
"}",
"public",
"async",
"Task",
"WriteAsync",
"(",
"TServerMessage",
"message",
")",
"{",
"_logger",
".",
"WritingMessage",
"(",
"_requestId",
",",
"typeof",
"(",
"TServerMessage",
")",
")",
";",
"_cancellationToken",
".",
"ThrowIfCancellationRequested",
"(",
")",
";",
"if",
"(",
"!",
"_writeLock",
".",
"Wait",
"(",
"0",
")",
")",
"{",
"var",
"stopwatch",
"=",
"Stopwatch",
".",
"StartNew",
"(",
")",
";",
"_metrics",
".",
"IncrementPendingStreamWrites",
"(",
")",
";",
"_logger",
".",
"WritingMessageBlockedByAnotherWrite",
"(",
"_requestId",
",",
"typeof",
"(",
"TServerMessage",
")",
")",
";",
"await",
"_writeLock",
".",
"WaitAsync",
"(",
"_cancellationToken",
")",
".",
"ConfigureAwait",
"(",
"false",
")",
";",
"try",
"{",
"stopwatch",
".",
"Stop",
"(",
")",
";",
"_metrics",
".",
"DecrementPendingStreamWrites",
"(",
")",
";",
"_metrics",
".",
"AddToTotalStreamWriteWaitTime",
"(",
"stopwatch",
".",
"Elapsed",
")",
";",
"_logger",
".",
"WritingMessageUnblockedAfter",
"(",
"_requestId",
",",
"typeof",
"(",
"TServerMessage",
")",
",",
"stopwatch",
".",
"Elapsed",
")",
";",
"}",
"catch",
"{",
"}",
"}",
"try",
"{",
"_cancellationToken",
".",
"ThrowIfCancellationRequested",
"(",
")",
";",
"var",
"stopwatch",
"=",
"Stopwatch",
".",
"StartNew",
"(",
")",
";",
"await",
"_originalStream",
".",
"WriteAsync",
"(",
"message",
")",
".",
"ConfigureAwait",
"(",
"false",
")",
";",
"stopwatch",
".",
"Stop",
"(",
")",
";",
"var",
"messageSize",
"=",
"message",
".",
"CalculateSize",
"(",
")",
";",
"_metrics",
".",
"AddToTotalStreamWriteTime",
"(",
"stopwatch",
".",
"Elapsed",
")",
";",
"_metrics",
".",
"IncrementTotalStreamWrites",
"(",
")",
";",
"_metrics",
".",
"IncrementTotalStreamWriteBytes",
"(",
"messageSize",
")",
";",
"_logger",
".",
"WroteMessage",
"(",
"_requestId",
",",
"stopwatch",
".",
"Elapsed",
",",
"messageSize",
")",
";",
"}",
"finally",
"{",
"_writeLock",
".",
"Release",
"(",
")",
";",
"}",
"}",
"public",
"void",
"MaybeWritePing",
"(",
")",
"{",
"_logger",
".",
"WritingPing",
"(",
"_requestId",
")",
";",
"_cancellationToken",
".",
"ThrowIfCancellationRequested",
"(",
")",
";",
"if",
"(",
"!",
"_writeLock",
".",
"Wait",
"(",
"0",
")",
")",
"{",
"_logger",
".",
"WritingPingSkipped",
"(",
"_requestId",
")",
";",
"return",
";",
"}",
"try",
"{",
"var",
"ping",
"=",
"new",
"Ping",
"(",
")",
";",
"var",
"message",
"=",
"new",
"TServerMessage",
"(",
")",
";",
"_messageConverter",
".",
"SetPing",
"(",
"message",
",",
"ping",
")",
";",
"var",
"stopwatch",
"=",
"Stopwatch",
".",
"StartNew",
"(",
")",
";",
"_originalStream",
".",
"WriteAsync",
"(",
"message",
")",
".",
"GetAwaiter",
"(",
")",
".",
"GetResult",
"(",
")",
";",
"stopwatch",
".",
"Stop",
"(",
")",
";",
"var",
"messageSize",
"=",
"message",
".",
"CalculateSize",
"(",
")",
";",
"_metrics",
".",
"AddToTotalStreamWriteTime",
"(",
"stopwatch",
".",
"Elapsed",
")",
";",
"_metrics",
".",
"IncrementTotalStreamWrites",
"(",
")",
";",
"_metrics",
".",
"IncrementTotalStreamWriteBytes",
"(",
"messageSize",
")",
";",
"_metrics",
".",
"IncrementTotalPingsSent",
"(",
")",
";",
"_logger",
".",
"WrotePing",
"(",
"_requestId",
",",
"stopwatch",
".",
"Elapsed",
")",
";",
"}",
"finally",
"{",
"_writeLock",
".",
"Release",
"(",
")",
";",
"}",
"}",
"public",
"void",
"Dispose",
"(",
")",
"{",
"Dispose",
"(",
"true",
")",
";",
"GC",
".",
"SuppressFinalize",
"(",
"this",
")",
";",
"}",
"protected",
"virtual",
"void",
"Dispose",
"(",
"bool",
"disposing",
")",
"{",
"if",
"(",
"_disposed",
")",
"{",
"return",
";",
"}",
"if",
"(",
"disposing",
")",
"{",
"_logger",
".",
"DisposingWrappedAsyncStreamWriter",
"(",
"_requestId",
")",
";",
"_writeLock",
".",
"Wait",
"(",
")",
";",
"_writeLock",
".",
"Dispose",
"(",
")",
";",
"_logger",
".",
"DisposedWrappedAsyncStreamWriter",
"(",
"_requestId",
")",
";",
"}",
"_disposed",
"=",
"true",
";",
"}",
"}"
] |
Represents a thread-safe wrapper of that also exposes special handling of ping messages and records metrics.
|
[
"Represents",
"a",
"thread",
"-",
"safe",
"wrapper",
"of",
"that",
"also",
"exposes",
"special",
"handling",
"of",
"ping",
"messages",
"and",
"records",
"metrics",
"."
] |
[
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"WrappedAsyncStreamWriter{TClientMessage, TServerMessage, TConnectArguments, TConnectResponse, TRequest, TResponse}\"/> class.",
"/// </summary>",
"/// <param name=\"requestId\">The request id for the gRPC method call.</param>",
"/// <param name=\"originalStream\">The original gRPC stream writer to wrap.</param>",
"/// <param name=\"messageConverter\">The message converter to use to create ping messages.</param>",
"/// <param name=\"metrics\">The metrics collector to use for metrics about reverse call stream writes.</param>",
"/// <param name=\"logger\">The logger to use.</param>",
"/// <param name=\"cancellationToken\">A cancellation token to use for cancelling pending and future writes.</param>",
"/// <inheritdoc/>",
"/// <summary>",
"/// Writes a message asynchronously, blocking until previous writes have been completed.",
"/// </summary>",
"/// <param name=\"message\">The message to be written. Cannot be null.</param>",
"/// <returns>A task that will complete when the message is sent.</returns>",
"/// <summary>",
"/// Writes a ping message synchronously if another write operation is not in progress.",
"/// </summary>",
"/// <inheritdoc/>"
] |
[
{
"param": "IDisposable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IDisposable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Type of the messages",
"docstring_tokens": [
"Type",
"of",
"the",
"messages"
]
},
{
"identifier": "typeparam",
"docstring": "Type of the messages",
"docstring_tokens": [
"Type",
"of",
"the",
"messages"
]
},
{
"identifier": "typeparam",
"docstring": "Type of the arguments that are sent along with the initial Connect call.",
"docstring_tokens": [
"Type",
"of",
"the",
"arguments",
"that",
"are",
"sent",
"along",
"with",
"the",
"initial",
"Connect",
"call",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Type of the response that is received after the initial Connect call.",
"docstring_tokens": [
"Type",
"of",
"the",
"response",
"that",
"is",
"received",
"after",
"the",
"initial",
"Connect",
"call",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Type of the requests sent from the Runtime to the Client.",
"docstring_tokens": [
"Type",
"of",
"the",
"requests",
"sent",
"from",
"the",
"Runtime",
"to",
"the",
"Client",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Type of the responses sent from the Client to the Runtime.",
"docstring_tokens": [
"Type",
"of",
"the",
"responses",
"sent",
"from",
"the",
"Client",
"to",
"the",
"Runtime",
"."
]
}
]
}
| false
| 15
| 888
| 202
|
c50cd37d6ea8540ab369c7cb1e71fbffbbfd4756
|
Erffun/dotnet-arangodb
|
Core.Arango/Relinq/Transformations/SubQueryFromClauseFlattener.cs
|
[
"Apache-2.0"
] |
C#
|
SubQueryFromClauseFlattener
|
/// <summary>
/// Takes a <see cref="QueryModel" /> and transforms it by replacing its <see cref="FromClauseBase" /> instances (
/// <see cref="MainFromClause" /> and
/// <see cref="AdditionalFromClause" />) that contain subqueries with equivalent flattened clauses. Subqueries that
/// contain a
/// <see cref="ResultOperatorBase" /> (such as <see cref="DistinctResultOperator" /> or
/// <see cref="TakeResultOperator" />) cannot be
/// flattened.
/// </summary>
/// <example>
/// As an example, take the following query:
/// <code>
/// from c in Customers
/// from o in (from oi in OrderInfos where oi.Customer == c orderby oi.OrderDate select oi.Order)
/// orderby o.Product.Name
/// select new { c, o }
/// </code>
/// This will be transformed into:
/// <code>
/// from c in Customers
/// from oi in OrderInfos
/// where oi.Customer == c
/// orderby oi.OrderDate
/// orderby oi.Order.Product.Name
/// select new { c, oi.Order }
/// </code>
/// As another example, take the following query:
/// <code>
/// from c in (from o in Orders select o.Customer)
/// where c.Name.StartsWith ("Miller")
/// select c
/// </code>
/// (This query is never produced by the <see cref="QueryParser" />, the only way to construct it is via manually
/// building a
/// <see cref="MainFromClause" />.)
/// This will be transforemd into:
/// <code>
/// from o in Orders
/// where o.Customer.Name.StartsWith ("Miller")
/// select o
/// </code>
/// </example>
|
Takes a and transforms it by replacing its instances (
and
) that contain subqueries with equivalent flattened clauses. Subqueries that
contain a
(such as or
) cannot be
flattened.
|
[
"Takes",
"a",
"and",
"transforms",
"it",
"by",
"replacing",
"its",
"instances",
"(",
"and",
")",
"that",
"contain",
"subqueries",
"with",
"equivalent",
"flattened",
"clauses",
".",
"Subqueries",
"that",
"contain",
"a",
"(",
"such",
"as",
"or",
")",
"cannot",
"be",
"flattened",
"."
] |
internal class SubQueryFromClauseFlattener : QueryModelVisitorBase
{
public override void VisitMainFromClause(MainFromClause fromClause, QueryModel queryModel)
{
ArgumentUtility.CheckNotNull("fromClause", fromClause);
ArgumentUtility.CheckNotNull("queryModel", queryModel);
var subQueryExpression = fromClause.FromExpression as SubQueryExpression;
if (subQueryExpression != null)
FlattenSubQuery(subQueryExpression, fromClause, queryModel, 0);
base.VisitMainFromClause(fromClause, queryModel);
}
public override void VisitAdditionalFromClause(AdditionalFromClause fromClause, QueryModel queryModel,
int index)
{
ArgumentUtility.CheckNotNull("fromClause", fromClause);
ArgumentUtility.CheckNotNull("queryModel", queryModel);
var subQueryExpression = fromClause.FromExpression as SubQueryExpression;
if (subQueryExpression != null)
FlattenSubQuery(subQueryExpression, fromClause, queryModel, index + 1);
base.VisitAdditionalFromClause(fromClause, queryModel, index);
}
protected virtual void FlattenSubQuery(SubQueryExpression subQueryExpression, IFromClause fromClause,
QueryModel queryModel, int destinationIndex)
{
ArgumentUtility.CheckNotNull("subQueryExpression", subQueryExpression);
ArgumentUtility.CheckNotNull("fromClause", fromClause);
ArgumentUtility.CheckNotNull("queryModel", queryModel);
CheckFlattenable(subQueryExpression.QueryModel);
var innerMainFromClause = subQueryExpression.QueryModel.MainFromClause;
fromClause.CopyFromSource(innerMainFromClause);
var innerSelectorMapping = new QuerySourceMapping();
innerSelectorMapping.AddMapping(fromClause, subQueryExpression.QueryModel.SelectClause.Selector);
queryModel.TransformExpressions(ex =>
ReferenceReplacingExpressionVisitor.ReplaceClauseReferences(ex, innerSelectorMapping, false));
InsertBodyClauses(subQueryExpression.QueryModel.BodyClauses, queryModel, destinationIndex);
var innerBodyClauseMapping = new QuerySourceMapping();
innerBodyClauseMapping.AddMapping(innerMainFromClause, new QuerySourceReferenceExpression(fromClause));
queryModel.TransformExpressions(ex =>
ReferenceReplacingExpressionVisitor.ReplaceClauseReferences(ex, innerBodyClauseMapping, false));
}
protected virtual void CheckFlattenable(QueryModel subQueryModel)
{
ArgumentUtility.CheckNotNull("subQueryModel", subQueryModel);
if (subQueryModel.ResultOperators.Count > 0)
{
var message = string.Format(
"The subquery '{0}' cannot be flattened and pulled out of the from clause because it contains result operators.",
subQueryModel);
throw new NotSupportedException(message);
}
if (subQueryModel.BodyClauses.Any(bc => bc is OrderByClause))
{
var message = string.Format(
"The subquery '{0}' cannot be flattened and pulled out of the from clause because it contains an OrderByClause.",
subQueryModel);
throw new NotSupportedException(message);
}
}
protected void InsertBodyClauses(ObservableCollection<IBodyClause> bodyClauses,
QueryModel destinationQueryModel, int destinationIndex)
{
ArgumentUtility.CheckNotNull("bodyClauses", bodyClauses);
ArgumentUtility.CheckNotNull("destinationQueryModel", destinationQueryModel);
foreach (var bodyClause in bodyClauses)
{
destinationQueryModel.BodyClauses.Insert(destinationIndex, bodyClause);
++destinationIndex;
}
}
}
|
[
"internal",
"class",
"SubQueryFromClauseFlattener",
":",
"QueryModelVisitorBase",
"{",
"public",
"override",
"void",
"VisitMainFromClause",
"(",
"MainFromClause",
"fromClause",
",",
"QueryModel",
"queryModel",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"fromClause",
"\"",
",",
"fromClause",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"queryModel",
"\"",
",",
"queryModel",
")",
";",
"var",
"subQueryExpression",
"=",
"fromClause",
".",
"FromExpression",
"as",
"SubQueryExpression",
";",
"if",
"(",
"subQueryExpression",
"!=",
"null",
")",
"FlattenSubQuery",
"(",
"subQueryExpression",
",",
"fromClause",
",",
"queryModel",
",",
"0",
")",
";",
"base",
".",
"VisitMainFromClause",
"(",
"fromClause",
",",
"queryModel",
")",
";",
"}",
"public",
"override",
"void",
"VisitAdditionalFromClause",
"(",
"AdditionalFromClause",
"fromClause",
",",
"QueryModel",
"queryModel",
",",
"int",
"index",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"fromClause",
"\"",
",",
"fromClause",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"queryModel",
"\"",
",",
"queryModel",
")",
";",
"var",
"subQueryExpression",
"=",
"fromClause",
".",
"FromExpression",
"as",
"SubQueryExpression",
";",
"if",
"(",
"subQueryExpression",
"!=",
"null",
")",
"FlattenSubQuery",
"(",
"subQueryExpression",
",",
"fromClause",
",",
"queryModel",
",",
"index",
"+",
"1",
")",
";",
"base",
".",
"VisitAdditionalFromClause",
"(",
"fromClause",
",",
"queryModel",
",",
"index",
")",
";",
"}",
"protected",
"virtual",
"void",
"FlattenSubQuery",
"(",
"SubQueryExpression",
"subQueryExpression",
",",
"IFromClause",
"fromClause",
",",
"QueryModel",
"queryModel",
",",
"int",
"destinationIndex",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"subQueryExpression",
"\"",
",",
"subQueryExpression",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"fromClause",
"\"",
",",
"fromClause",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"queryModel",
"\"",
",",
"queryModel",
")",
";",
"CheckFlattenable",
"(",
"subQueryExpression",
".",
"QueryModel",
")",
";",
"var",
"innerMainFromClause",
"=",
"subQueryExpression",
".",
"QueryModel",
".",
"MainFromClause",
";",
"fromClause",
".",
"CopyFromSource",
"(",
"innerMainFromClause",
")",
";",
"var",
"innerSelectorMapping",
"=",
"new",
"QuerySourceMapping",
"(",
")",
";",
"innerSelectorMapping",
".",
"AddMapping",
"(",
"fromClause",
",",
"subQueryExpression",
".",
"QueryModel",
".",
"SelectClause",
".",
"Selector",
")",
";",
"queryModel",
".",
"TransformExpressions",
"(",
"ex",
"=>",
"ReferenceReplacingExpressionVisitor",
".",
"ReplaceClauseReferences",
"(",
"ex",
",",
"innerSelectorMapping",
",",
"false",
")",
")",
";",
"InsertBodyClauses",
"(",
"subQueryExpression",
".",
"QueryModel",
".",
"BodyClauses",
",",
"queryModel",
",",
"destinationIndex",
")",
";",
"var",
"innerBodyClauseMapping",
"=",
"new",
"QuerySourceMapping",
"(",
")",
";",
"innerBodyClauseMapping",
".",
"AddMapping",
"(",
"innerMainFromClause",
",",
"new",
"QuerySourceReferenceExpression",
"(",
"fromClause",
")",
")",
";",
"queryModel",
".",
"TransformExpressions",
"(",
"ex",
"=>",
"ReferenceReplacingExpressionVisitor",
".",
"ReplaceClauseReferences",
"(",
"ex",
",",
"innerBodyClauseMapping",
",",
"false",
")",
")",
";",
"}",
"protected",
"virtual",
"void",
"CheckFlattenable",
"(",
"QueryModel",
"subQueryModel",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"subQueryModel",
"\"",
",",
"subQueryModel",
")",
";",
"if",
"(",
"subQueryModel",
".",
"ResultOperators",
".",
"Count",
">",
"0",
")",
"{",
"var",
"message",
"=",
"string",
".",
"Format",
"(",
"\"",
"The subquery '{0}' cannot be flattened and pulled out of the from clause because it contains result operators.",
"\"",
",",
"subQueryModel",
")",
";",
"throw",
"new",
"NotSupportedException",
"(",
"message",
")",
";",
"}",
"if",
"(",
"subQueryModel",
".",
"BodyClauses",
".",
"Any",
"(",
"bc",
"=>",
"bc",
"is",
"OrderByClause",
")",
")",
"{",
"var",
"message",
"=",
"string",
".",
"Format",
"(",
"\"",
"The subquery '{0}' cannot be flattened and pulled out of the from clause because it contains an OrderByClause.",
"\"",
",",
"subQueryModel",
")",
";",
"throw",
"new",
"NotSupportedException",
"(",
"message",
")",
";",
"}",
"}",
"protected",
"void",
"InsertBodyClauses",
"(",
"ObservableCollection",
"<",
"IBodyClause",
">",
"bodyClauses",
",",
"QueryModel",
"destinationQueryModel",
",",
"int",
"destinationIndex",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"bodyClauses",
"\"",
",",
"bodyClauses",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"destinationQueryModel",
"\"",
",",
"destinationQueryModel",
")",
";",
"foreach",
"(",
"var",
"bodyClause",
"in",
"bodyClauses",
")",
"{",
"destinationQueryModel",
".",
"BodyClauses",
".",
"Insert",
"(",
"destinationIndex",
",",
"bodyClause",
")",
";",
"++",
"destinationIndex",
";",
"}",
"}",
"}"
] |
Takes a and transforms it by replacing its instances (
and
) that contain subqueries with equivalent flattened clauses.
|
[
"Takes",
"a",
"and",
"transforms",
"it",
"by",
"replacing",
"its",
"instances",
"(",
"and",
")",
"that",
"contain",
"subqueries",
"with",
"equivalent",
"flattened",
"clauses",
"."
] |
[] |
[
{
"param": "QueryModelVisitorBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "QueryModelVisitorBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "As an example, take the following query.\n\nfrom c in Customers\nfrom o in (from oi in OrderInfos where oi.Customer == c orderby oi.OrderDate select oi.Order)\norderby o.Product.Name\nselect new { c, o }\n\nfrom c in Customers\nfrom oi in OrderInfos\nwhere oi.Customer == c\norderby oi.OrderDate\norderby oi.Order.Product.Name\nselect new { c, oi.Order }\n\nfrom c in (from o in Orders select o.Customer)\nwhere c.Name.StartsWith (\"Miller\")\nselect c\n, the only way to construct it is via manually\nbuilding a\n.)\nThis will be transforemd into.\n\nfrom o in Orders\nwhere o.Customer.Name.StartsWith (\"Miller\")\nselect o",
"docstring_tokens": [
"As",
"an",
"example",
"take",
"the",
"following",
"query",
".",
"from",
"c",
"in",
"Customers",
"from",
"o",
"in",
"(",
"from",
"oi",
"in",
"OrderInfos",
"where",
"oi",
".",
"Customer",
"==",
"c",
"orderby",
"oi",
".",
"OrderDate",
"select",
"oi",
".",
"Order",
")",
"orderby",
"o",
".",
"Product",
".",
"Name",
"select",
"new",
"{",
"c",
"o",
"}",
"from",
"c",
"in",
"Customers",
"from",
"oi",
"in",
"OrderInfos",
"where",
"oi",
".",
"Customer",
"==",
"c",
"orderby",
"oi",
".",
"OrderDate",
"orderby",
"oi",
".",
"Order",
".",
"Product",
".",
"Name",
"select",
"new",
"{",
"c",
"oi",
".",
"Order",
"}",
"from",
"c",
"in",
"(",
"from",
"o",
"in",
"Orders",
"select",
"o",
".",
"Customer",
")",
"where",
"c",
".",
"Name",
".",
"StartsWith",
"(",
"\"",
"Miller",
"\"",
")",
"select",
"c",
"the",
"only",
"way",
"to",
"construct",
"it",
"is",
"via",
"manually",
"building",
"a",
".",
")",
"This",
"will",
"be",
"transforemd",
"into",
".",
"from",
"o",
"in",
"Orders",
"where",
"o",
".",
"Customer",
".",
"Name",
".",
"StartsWith",
"(",
"\"",
"Miller",
"\"",
")",
"select",
"o"
]
}
]
}
| false
| 14
| 722
| 382
|
17c879f665ad765c3efd1aa284b884c28d9108ac
|
kll/nugetrepack
|
NugetRepack.UnitTests/FileSystemSocialTests.cs
|
[
"MIT"
] |
C#
|
FileSystemSocialTests
|
/// <summary>
/// Tests for FileSystem that interact with other classes.
/// </summary>
/// <remark>
/// I called these tests social because they interact with the real file
/// system and classes from Thinktecture.IO. No other classes from this
/// code base are used though so solitary could fit as well. It is a gray
/// area.
/// </remark>
|
Tests for FileSystem that interact with other classes.
|
[
"Tests",
"for",
"FileSystem",
"that",
"interact",
"with",
"other",
"classes",
"."
] |
public class FileSystemSocialTests
{
public FileSystemSocialTests()
{
this.Target = new FileSystem();
}
private FileSystem Target { get; }
[Fact]
public void CanDeleteDirectory()
{
Directory.CreateDirectory("temp");
this.Target.DeleteDirectory("temp");
Directory.Exists("temp").Should().BeFalse("because delete directory was called");
}
[Fact]
public void CanDeleteFile()
{
File.WriteAllText("temp.txt", "delete me if found");
this.Target.DeleteFile("temp.txt");
File.Exists("temp.txt").Should().BeFalse("because delete file was called");
}
[Fact]
public void CanGetDirectory()
{
var directory = this.Target.GetDirectory("temp");
directory.Should().NotBeNull();
}
[Fact]
public void CanGetFile()
{
var file = this.Target.GetFile("temp.txt");
file.Should().NotBeNull();
}
[Fact]
public async Task CanReadAllText()
{
File.WriteAllText("temp.txt", "delete me if found");
string result;
try
{
result = await this.Target.ReadAllText("temp.txt");
}
finally
{
File.Delete("temp.txt");
}
result.Should().Be("delete me if found", "because that is what was written to the file");
}
[Fact]
public void CanMoveFile()
{
File.WriteAllText("foo.txt", "delete this if found");
try
{
this.Target.MoveFile("foo.txt", "bar.txt");
File.Exists("bar.txt").Should().BeTrue("the file was renamed");
File.Exists("foo.txt").Should().BeFalse("the file was renamed");
}
finally
{
File.Delete("foo.txt");
File.Delete("bar.txt");
}
}
[Fact]
public async Task CanWriteAllText()
{
string result;
try
{
await this.Target.WriteAllText("temp.txt", "delete me if found");
result = File.ReadAllText("temp.txt");
}
finally
{
File.Delete("temp.txt");
}
result.Should().Be("delete me if found", "because that is what was written to the file");
}
}
|
[
"public",
"class",
"FileSystemSocialTests",
"{",
"public",
"FileSystemSocialTests",
"(",
")",
"{",
"this",
".",
"Target",
"=",
"new",
"FileSystem",
"(",
")",
";",
"}",
"private",
"FileSystem",
"Target",
"{",
"get",
";",
"}",
"[",
"Fact",
"]",
"public",
"void",
"CanDeleteDirectory",
"(",
")",
"{",
"Directory",
".",
"CreateDirectory",
"(",
"\"",
"temp",
"\"",
")",
";",
"this",
".",
"Target",
".",
"DeleteDirectory",
"(",
"\"",
"temp",
"\"",
")",
";",
"Directory",
".",
"Exists",
"(",
"\"",
"temp",
"\"",
")",
".",
"Should",
"(",
")",
".",
"BeFalse",
"(",
"\"",
"because delete directory was called",
"\"",
")",
";",
"}",
"[",
"Fact",
"]",
"public",
"void",
"CanDeleteFile",
"(",
")",
"{",
"File",
".",
"WriteAllText",
"(",
"\"",
"temp.txt",
"\"",
",",
"\"",
"delete me if found",
"\"",
")",
";",
"this",
".",
"Target",
".",
"DeleteFile",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"File",
".",
"Exists",
"(",
"\"",
"temp.txt",
"\"",
")",
".",
"Should",
"(",
")",
".",
"BeFalse",
"(",
"\"",
"because delete file was called",
"\"",
")",
";",
"}",
"[",
"Fact",
"]",
"public",
"void",
"CanGetDirectory",
"(",
")",
"{",
"var",
"directory",
"=",
"this",
".",
"Target",
".",
"GetDirectory",
"(",
"\"",
"temp",
"\"",
")",
";",
"directory",
".",
"Should",
"(",
")",
".",
"NotBeNull",
"(",
")",
";",
"}",
"[",
"Fact",
"]",
"public",
"void",
"CanGetFile",
"(",
")",
"{",
"var",
"file",
"=",
"this",
".",
"Target",
".",
"GetFile",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"file",
".",
"Should",
"(",
")",
".",
"NotBeNull",
"(",
")",
";",
"}",
"[",
"Fact",
"]",
"public",
"async",
"Task",
"CanReadAllText",
"(",
")",
"{",
"File",
".",
"WriteAllText",
"(",
"\"",
"temp.txt",
"\"",
",",
"\"",
"delete me if found",
"\"",
")",
";",
"string",
"result",
";",
"try",
"{",
"result",
"=",
"await",
"this",
".",
"Target",
".",
"ReadAllText",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"}",
"finally",
"{",
"File",
".",
"Delete",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"}",
"result",
".",
"Should",
"(",
")",
".",
"Be",
"(",
"\"",
"delete me if found",
"\"",
",",
"\"",
"because that is what was written to the file",
"\"",
")",
";",
"}",
"[",
"Fact",
"]",
"public",
"void",
"CanMoveFile",
"(",
")",
"{",
"File",
".",
"WriteAllText",
"(",
"\"",
"foo.txt",
"\"",
",",
"\"",
"delete this if found",
"\"",
")",
";",
"try",
"{",
"this",
".",
"Target",
".",
"MoveFile",
"(",
"\"",
"foo.txt",
"\"",
",",
"\"",
"bar.txt",
"\"",
")",
";",
"File",
".",
"Exists",
"(",
"\"",
"bar.txt",
"\"",
")",
".",
"Should",
"(",
")",
".",
"BeTrue",
"(",
"\"",
"the file was renamed",
"\"",
")",
";",
"File",
".",
"Exists",
"(",
"\"",
"foo.txt",
"\"",
")",
".",
"Should",
"(",
")",
".",
"BeFalse",
"(",
"\"",
"the file was renamed",
"\"",
")",
";",
"}",
"finally",
"{",
"File",
".",
"Delete",
"(",
"\"",
"foo.txt",
"\"",
")",
";",
"File",
".",
"Delete",
"(",
"\"",
"bar.txt",
"\"",
")",
";",
"}",
"}",
"[",
"Fact",
"]",
"public",
"async",
"Task",
"CanWriteAllText",
"(",
")",
"{",
"string",
"result",
";",
"try",
"{",
"await",
"this",
".",
"Target",
".",
"WriteAllText",
"(",
"\"",
"temp.txt",
"\"",
",",
"\"",
"delete me if found",
"\"",
")",
";",
"result",
"=",
"File",
".",
"ReadAllText",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"}",
"finally",
"{",
"File",
".",
"Delete",
"(",
"\"",
"temp.txt",
"\"",
")",
";",
"}",
"result",
".",
"Should",
"(",
")",
".",
"Be",
"(",
"\"",
"delete me if found",
"\"",
",",
"\"",
"because that is what was written to the file",
"\"",
")",
";",
"}",
"}"
] |
Tests for FileSystem that interact with other classes.
|
[
"Tests",
"for",
"FileSystem",
"that",
"interact",
"with",
"other",
"classes",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remark",
"docstring": "I called these tests social because they interact with the real file\nsystem and classes from Thinktecture.IO. No other classes from this\ncode base are used though so solitary could fit as well. It is a gray\narea.",
"docstring_tokens": [
"I",
"called",
"these",
"tests",
"social",
"because",
"they",
"interact",
"with",
"the",
"real",
"file",
"system",
"and",
"classes",
"from",
"Thinktecture",
".",
"IO",
".",
"No",
"other",
"classes",
"from",
"this",
"code",
"base",
"are",
"used",
"though",
"so",
"solitary",
"could",
"fit",
"as",
"well",
".",
"It",
"is",
"a",
"gray",
"area",
"."
]
}
]
}
| false
| 16
| 482
| 77
|
f24ed904c5251bb75c6ce9897a6691ca84f13842
|
re-motion/BuildTools
|
JiraReleaseNoteGenerator/JiraClient.cs
|
[
"Apache-2.0"
] |
C#
|
JiraClient
|
/// <summary> Default implementation of the <see cref="IJiraClient"/>.
/// </summary>
/// <example>
/// The issues returned from JIRA have the following structure:
/// <![CDATA[
/// <rss>
/// <channel>
/// <item>
/// <title>
/// <project>
/// ...
/// </item>
/// <item>
/// ...
/// </channel>
/// </rss>
/// ]]>
/// </example>
|
Default implementation of the .
|
[
"Default",
"implementation",
"of",
"the",
"."
] |
public class JiraClient : IJiraClient
{
private readonly IWebClient _webClient;
private readonly Func<IJiraRequestUrlBuilder> _builderFactory;
public JiraClient (IWebClient webClient, Func<IJiraRequestUrlBuilder> builderFactory)
{
ArgumentUtility.CheckNotNull ("webClient", webClient);
ArgumentUtility.CheckNotNull ("builderFactory", builderFactory);
_webClient = webClient;
_builderFactory = builderFactory;
}
public XDocument GetIssuesByCustomConstraints (CustomConstraints customConstraints)
{
ArgumentUtility.CheckNotNull ("customConstraints", customConstraints);
return GetIssues (customConstraints, null);
}
public XDocument GetIssuesByKeys (string[] keys)
{
ArgumentUtility.CheckNotNull ("keys", keys);
return GetIssues (null, keys);
}
private XDocument GetIssues (CustomConstraints customConstraints, string[] keys)
{
var builder = _builderFactory();
builder.FixVersion = customConstraints == null ? null : customConstraints.Version;
builder.Keys = keys;
builder.AdditionalConstraint = customConstraints == null ? null : customConstraints.AdditionalConstraint;
if (builder.IsValidQuery())
{
var url = builder.Build();
return GetIssuesFromUrl(url);
}
else
{
return CreateEmptyDocumentStructure();
}
}
private XDocument GetIssuesFromUrl (string url)
{
try
{
using (var data = _webClient.OpenRead (url))
{
using (var reader = new StreamReader (data))
{
var result = XDocument.Parse (reader.ReadToEnd());
if (IsValidXml (result))
return result;
else
return CreateEmptyDocumentStructure();
}
}
}
catch (WebException ex)
{
throw new WebException (ex.Message + "\nURL: " + url);
}
}
private XDocument CreateEmptyDocumentStructure ()
{
var result = new XDocument();
result.Add (new XElement ("rss", new XElement ("channel")));
return result;
}
private bool IsValidXml (XDocument result)
{
return result.Root != null
&& result.Element ("rss") != null
&& result.Element ("rss").Element("channel") != null;
}
}
|
[
"public",
"class",
"JiraClient",
":",
"IJiraClient",
"{",
"private",
"readonly",
"IWebClient",
"_webClient",
";",
"private",
"readonly",
"Func",
"<",
"IJiraRequestUrlBuilder",
">",
"_builderFactory",
";",
"public",
"JiraClient",
"(",
"IWebClient",
"webClient",
",",
"Func",
"<",
"IJiraRequestUrlBuilder",
">",
"builderFactory",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"webClient",
"\"",
",",
"webClient",
")",
";",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"builderFactory",
"\"",
",",
"builderFactory",
")",
";",
"_webClient",
"=",
"webClient",
";",
"_builderFactory",
"=",
"builderFactory",
";",
"}",
"public",
"XDocument",
"GetIssuesByCustomConstraints",
"(",
"CustomConstraints",
"customConstraints",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"customConstraints",
"\"",
",",
"customConstraints",
")",
";",
"return",
"GetIssues",
"(",
"customConstraints",
",",
"null",
")",
";",
"}",
"public",
"XDocument",
"GetIssuesByKeys",
"(",
"string",
"[",
"]",
"keys",
")",
"{",
"ArgumentUtility",
".",
"CheckNotNull",
"(",
"\"",
"keys",
"\"",
",",
"keys",
")",
";",
"return",
"GetIssues",
"(",
"null",
",",
"keys",
")",
";",
"}",
"private",
"XDocument",
"GetIssues",
"(",
"CustomConstraints",
"customConstraints",
",",
"string",
"[",
"]",
"keys",
")",
"{",
"var",
"builder",
"=",
"_builderFactory",
"(",
")",
";",
"builder",
".",
"FixVersion",
"=",
"customConstraints",
"==",
"null",
"?",
"null",
":",
"customConstraints",
".",
"Version",
";",
"builder",
".",
"Keys",
"=",
"keys",
";",
"builder",
".",
"AdditionalConstraint",
"=",
"customConstraints",
"==",
"null",
"?",
"null",
":",
"customConstraints",
".",
"AdditionalConstraint",
";",
"if",
"(",
"builder",
".",
"IsValidQuery",
"(",
")",
")",
"{",
"var",
"url",
"=",
"builder",
".",
"Build",
"(",
")",
";",
"return",
"GetIssuesFromUrl",
"(",
"url",
")",
";",
"}",
"else",
"{",
"return",
"CreateEmptyDocumentStructure",
"(",
")",
";",
"}",
"}",
"private",
"XDocument",
"GetIssuesFromUrl",
"(",
"string",
"url",
")",
"{",
"try",
"{",
"using",
"(",
"var",
"data",
"=",
"_webClient",
".",
"OpenRead",
"(",
"url",
")",
")",
"{",
"using",
"(",
"var",
"reader",
"=",
"new",
"StreamReader",
"(",
"data",
")",
")",
"{",
"var",
"result",
"=",
"XDocument",
".",
"Parse",
"(",
"reader",
".",
"ReadToEnd",
"(",
")",
")",
";",
"if",
"(",
"IsValidXml",
"(",
"result",
")",
")",
"return",
"result",
";",
"else",
"return",
"CreateEmptyDocumentStructure",
"(",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"WebException",
"ex",
")",
"{",
"throw",
"new",
"WebException",
"(",
"ex",
".",
"Message",
"+",
"\"",
"\\n",
"URL: ",
"\"",
"+",
"url",
")",
";",
"}",
"}",
"private",
"XDocument",
"CreateEmptyDocumentStructure",
"(",
")",
"{",
"var",
"result",
"=",
"new",
"XDocument",
"(",
")",
";",
"result",
".",
"Add",
"(",
"new",
"XElement",
"(",
"\"",
"rss",
"\"",
",",
"new",
"XElement",
"(",
"\"",
"channel",
"\"",
")",
")",
")",
";",
"return",
"result",
";",
"}",
"private",
"bool",
"IsValidXml",
"(",
"XDocument",
"result",
")",
"{",
"return",
"result",
".",
"Root",
"!=",
"null",
"&&",
"result",
".",
"Element",
"(",
"\"",
"rss",
"\"",
")",
"!=",
"null",
"&&",
"result",
".",
"Element",
"(",
"\"",
"rss",
"\"",
")",
".",
"Element",
"(",
"\"",
"channel",
"\"",
")",
"!=",
"null",
";",
"}",
"}"
] |
Default implementation of the .
|
[
"Default",
"implementation",
"of",
"the",
"."
] |
[] |
[
{
"param": "IJiraClient",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IJiraClient",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "The issues returned from JIRA have the following structure.\n\n",
"docstring_tokens": [
"The",
"issues",
"returned",
"from",
"JIRA",
"have",
"the",
"following",
"structure",
"."
]
}
]
}
| false
| 19
| 495
| 97
|
9ffda291545ed3ad9842a144e8ad1e4a8683de86
|
BenjaminBjoernRommel/SharpDX
|
Source/SharpDX.Direct3D12/Generated/DESKTOP_APP/Structures.cs
|
[
"MIT"
] |
C#
|
CommandSignatureDescription
|
/// <summary>
/// <p> Describes the arguments (parameters) of a command signature. </p>
/// </summary>
/// <remarks>
/// <p> Use this structure by <strong>CreateCommandSignature</strong>. </p>
/// </remarks>
/// <doc-id>dn986724</doc-id>
/// <unmanaged>D3D12_COMMAND_SIGNATURE_DESC</unmanaged>
/// <unmanaged-short>D3D12_COMMAND_SIGNATURE_DESC</unmanaged-short>
|
Describes the arguments (parameters) of a command signature.
|
[
"Describes",
"the",
"arguments",
"(",
"parameters",
")",
"of",
"a",
"command",
"signature",
"."
] |
public partial class CommandSignatureDescription
{
public System.Int32 ByteStride;
internal System.Int32 ArgumentDescCount;
internal System.IntPtr ArgumentDescsPointer;
public System.Int32 NodeMask;
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, Pack = 0, CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
internal partial struct __Native
{
public System.Int32 ByteStride;
public System.Int32 ArgumentDescCount;
public System.IntPtr ArgumentDescsPointer;
public System.Int32 NodeMask;
}
internal unsafe void __MarshalFree(ref __Native @ref)
{
}
internal unsafe void __MarshalFrom(ref __Native @ref)
{
ByteStride = @ref.ByteStride;
ArgumentDescCount = @ref.ArgumentDescCount;
ArgumentDescsPointer = @ref.ArgumentDescsPointer;
NodeMask = @ref.NodeMask;
}
internal unsafe void __MarshalTo(ref __Native @ref)
{
@ref.ByteStride = ByteStride;
@ref.ArgumentDescCount = ArgumentDescCount;
@ref.ArgumentDescsPointer = ArgumentDescsPointer;
@ref.NodeMask = NodeMask;
}
}
|
[
"public",
"partial",
"class",
"CommandSignatureDescription",
"{",
"public",
"System",
".",
"Int32",
"ByteStride",
";",
"internal",
"System",
".",
"Int32",
"ArgumentDescCount",
";",
"internal",
"System",
".",
"IntPtr",
"ArgumentDescsPointer",
";",
"public",
"System",
".",
"Int32",
"NodeMask",
";",
"[",
"System",
".",
"Runtime",
".",
"InteropServices",
".",
"StructLayoutAttribute",
"(",
"System",
".",
"Runtime",
".",
"InteropServices",
".",
"LayoutKind",
".",
"Sequential",
",",
"Pack",
"=",
"0",
",",
"CharSet",
"=",
"System",
".",
"Runtime",
".",
"InteropServices",
".",
"CharSet",
".",
"Unicode",
")",
"]",
"internal",
"partial",
"struct",
"__Native",
"{",
"public",
"System",
".",
"Int32",
"ByteStride",
";",
"public",
"System",
".",
"Int32",
"ArgumentDescCount",
";",
"public",
"System",
".",
"IntPtr",
"ArgumentDescsPointer",
";",
"public",
"System",
".",
"Int32",
"NodeMask",
";",
"}",
"internal",
"unsafe",
"void",
"__MarshalFree",
"(",
"ref",
"__Native",
"@ref",
")",
"{",
"}",
"internal",
"unsafe",
"void",
"__MarshalFrom",
"(",
"ref",
"__Native",
"@ref",
")",
"{",
"ByteStride",
"=",
"@ref",
".",
"ByteStride",
";",
"ArgumentDescCount",
"=",
"@ref",
".",
"ArgumentDescCount",
";",
"ArgumentDescsPointer",
"=",
"@ref",
".",
"ArgumentDescsPointer",
";",
"NodeMask",
"=",
"@ref",
".",
"NodeMask",
";",
"}",
"internal",
"unsafe",
"void",
"__MarshalTo",
"(",
"ref",
"__Native",
"@ref",
")",
"{",
"@ref",
".",
"ByteStride",
"=",
"ByteStride",
";",
"@ref",
".",
"ArgumentDescCount",
"=",
"ArgumentDescCount",
";",
"@ref",
".",
"ArgumentDescsPointer",
"=",
"ArgumentDescsPointer",
";",
"@ref",
".",
"NodeMask",
"=",
"NodeMask",
";",
"}",
"}"
] |
Describes the arguments (parameters) of a command signature.
|
[
"Describes",
"the",
"arguments",
"(",
"parameters",
")",
"of",
"a",
"command",
"signature",
"."
] |
[
"/// <summary>",
"/// <dd> <p> Specifies the size of each argument of a command signature, in bytes. </p> </dd>",
"/// </summary>",
"/// <doc-id>dn986724</doc-id>",
"/// <unmanaged>ByteStride</unmanaged>",
"/// <unmanaged-short>ByteStride</unmanaged-short>",
"/// <summary>",
"/// <dd> <p> Specifies the number of arguments in the command signature. </p> </dd>",
"/// </summary>",
"/// <doc-id>dn986724</doc-id>",
"/// <unmanaged>NumArgumentDescs</unmanaged>",
"/// <unmanaged-short>NumArgumentDescs</unmanaged-short>",
"/// <summary>",
"/// <dd> <p> An array of <strong><see cref = \"SharpDX.Direct3D12.IndirectArgumentDescription\"/></strong> structures, containing details of the arguments, including whether the argument is a vertex buffer, constant, constant buffer view, shader resource view, or unordered access view. </p> </dd>",
"/// </summary>",
"/// <doc-id>dn986724</doc-id>",
"/// <unmanaged>pArgumentDescs</unmanaged>",
"/// <unmanaged-short>pArgumentDescs</unmanaged-short>",
"/// <summary>",
"/// <dd> <p> For single GPU operation, set this to zero. If there are multiple GPU nodes, set bits to identify the nodes (the device's physical adapters) for which the command signature is to apply. Each bit in the mask corresponds to a single node. Refer to Multi-Adapter.</p> </dd>",
"/// </summary>",
"/// <doc-id>dn986724</doc-id>",
"/// <unmanaged>NodeMask</unmanaged>",
"/// <unmanaged-short>NodeMask</unmanaged-short>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Use this structure by CreateCommandSignature",
"docstring_tokens": [
"Use",
"this",
"structure",
"by",
"CreateCommandSignature"
]
},
{
"identifier": "doc-id",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "unmanaged",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "unmanaged-short",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 13
| 260
| 104
|
2847ca800421dcdeb9d2790f82f63078955125ce
|
ZiliasTheSaint/danfulea
|
src/danfulea/utils/SplashWindow.java
|
[
"BSD-3-Clause"
] |
Java
|
SplashWindow
|
/**
* Splash window that displays an image for a given time or until
* the user clicks on it with their mouse. Runs in a new thread therefore the calling application is initialized in parallel.
*
* @author Dan Fulea 27. JUN. 2011 based on code written by
* Tony Colston Nov 17, 2000 http://www.javaworld.com/article/2077467/core-java/java-tip-104--make-a-splash-with-swing.html,
*
*/
|
Splash window that displays an image for a given time or until
the user clicks on it with their mouse. Runs in a new thread therefore the calling application is initialized in parallel.
@author Dan Fulea 27. JUN.
|
[
"Splash",
"window",
"that",
"displays",
"an",
"image",
"for",
"a",
"given",
"time",
"or",
"until",
"the",
"user",
"clicks",
"on",
"it",
"with",
"their",
"mouse",
".",
"Runs",
"in",
"a",
"new",
"thread",
"therefore",
"the",
"calling",
"application",
"is",
"initialized",
"in",
"parallel",
".",
"@author",
"Dan",
"Fulea",
"27",
".",
"JUN",
"."
] |
@SuppressWarnings("serial")
public class SplashWindow extends JWindow {
/** Contains the splash image */
private JLabel splashLabel;
/**
* Creates a new Splash window and displays it for the specified period.
*
* @param splashImg
* The splash image
* @param iDisplayMs
* Time in milli-seconds to display splash window
*/
public SplashWindow(Image splashImg, int iDisplayMs) {
initComponents(splashImg, iDisplayMs);
}
/**
* Initializes the window's GUI components and display the splash window for
* the specified period of time.
*
* @param splashImg
* The splash image
* @param iDisplayMs
* Time in milli-seconds to display splash window
*/
private void initComponents(Image splashImg, int iDisplayMs) {
getContentPane().setLayout(new BorderLayout(0, 0));
splashLabel = new JLabel(new ImageIcon(splashImg));
getContentPane().add(splashLabel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
setVisible(false);
dispose();
}
});
final int iPauseMs = iDisplayMs;
final Runnable closerRunner = new Runnable() {
public void run() {
setVisible(false);
dispose();
}
};
Runnable waitRunner = new Runnable() {
public void run() {
try {
Thread.sleep(iPauseMs);
SwingUtilities.invokeAndWait(closerRunner);
} catch (InterruptedException e) { //
} catch (InvocationTargetException e) { //
}
}
};
setVisible(true);
toFront();//put this window on top
Thread splashThread = new Thread(waitRunner, "SplashThread");
splashThread.start();
}
}
|
[
"@",
"SuppressWarnings",
"(",
"\"",
"serial",
"\"",
")",
"public",
"class",
"SplashWindow",
"extends",
"JWindow",
"{",
"/** Contains the splash image */",
"private",
"JLabel",
"splashLabel",
";",
"/**\n\t * Creates a new Splash window and displays it for the specified period.\n\t * \n\t * @param splashImg\n\t * The splash image\n\t * @param iDisplayMs\n\t * Time in milli-seconds to display splash window\n\t */",
"public",
"SplashWindow",
"(",
"Image",
"splashImg",
",",
"int",
"iDisplayMs",
")",
"{",
"initComponents",
"(",
"splashImg",
",",
"iDisplayMs",
")",
";",
"}",
"/**\n\t * Initializes the window's GUI components and display the splash window for\n\t * the specified period of time.\n\t * \n\t * @param splashImg\n\t * The splash image\n\t * @param iDisplayMs\n\t * Time in milli-seconds to display splash window\n\t */",
"private",
"void",
"initComponents",
"(",
"Image",
"splashImg",
",",
"int",
"iDisplayMs",
")",
"{",
"getContentPane",
"(",
")",
".",
"setLayout",
"(",
"new",
"BorderLayout",
"(",
"0",
",",
"0",
")",
")",
";",
"splashLabel",
"=",
"new",
"JLabel",
"(",
"new",
"ImageIcon",
"(",
"splashImg",
")",
")",
";",
"getContentPane",
"(",
")",
".",
"add",
"(",
"splashLabel",
",",
"BorderLayout",
".",
"CENTER",
")",
";",
"pack",
"(",
")",
";",
"setLocationRelativeTo",
"(",
"null",
")",
";",
"addMouseListener",
"(",
"new",
"MouseAdapter",
"(",
")",
"{",
"public",
"void",
"mousePressed",
"(",
"MouseEvent",
"e",
")",
"{",
"setVisible",
"(",
"false",
")",
";",
"dispose",
"(",
")",
";",
"}",
"}",
")",
";",
"final",
"int",
"iPauseMs",
"=",
"iDisplayMs",
";",
"final",
"Runnable",
"closerRunner",
"=",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"setVisible",
"(",
"false",
")",
";",
"dispose",
"(",
")",
";",
"}",
"}",
";",
"Runnable",
"waitRunner",
"=",
"new",
"Runnable",
"(",
")",
"{",
"public",
"void",
"run",
"(",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"iPauseMs",
")",
";",
"SwingUtilities",
".",
"invokeAndWait",
"(",
"closerRunner",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"}",
"catch",
"(",
"InvocationTargetException",
"e",
")",
"{",
"}",
"}",
"}",
";",
"setVisible",
"(",
"true",
")",
";",
"toFront",
"(",
")",
";",
"Thread",
"splashThread",
"=",
"new",
"Thread",
"(",
"waitRunner",
",",
"\"",
"SplashThread",
"\"",
")",
";",
"splashThread",
".",
"start",
"(",
")",
";",
"}",
"}"
] |
Splash window that displays an image for a given time or until
the user clicks on it with their mouse.
|
[
"Splash",
"window",
"that",
"displays",
"an",
"image",
"for",
"a",
"given",
"time",
"or",
"until",
"the",
"user",
"clicks",
"on",
"it",
"with",
"their",
"mouse",
"."
] |
[
"//",
"//",
"//put this window on top"
] |
[
{
"param": "JWindow",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "JWindow",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 16
| 413
| 117
|
92eda02d19a21961625d95d5bbc0af1b0a7e8065
|
fireattack/instaloader
|
instaloader/structures.py
|
[
"MIT"
] |
Python
|
Story
|
Structure representing a user story with its associated items.
Provides methods for accessing story properties, as well as :meth:`Story.get_items` to request associated
:class:`StoryItem` nodes. Stories are returned by :meth:`Instaloader.get_stories`.
With a logged-in :class:`Instaloader` instance `L`, you may download all your visible user stories with::
for story in L.get_stories():
# story is a Story object
for item in story.get_items():
# item is a StoryItem object
L.download_storyitem(item, ':stories')
This class implements == and is hashable.
:param context: :class:`InstaloaderContext` instance used for additional queries if necessary.
:param node: Dictionary containing the available information of the story as returned by Instagram.
|
Structure representing a user story with its associated items.
Provides methods for accessing story properties, as well as :meth:`Story.get_items` to request associated
|
[
"Structure",
"representing",
"a",
"user",
"story",
"with",
"its",
"associated",
"items",
".",
"Provides",
"methods",
"for",
"accessing",
"story",
"properties",
"as",
"well",
"as",
":",
"meth",
":",
"`",
"Story",
".",
"get_items",
"`",
"to",
"request",
"associated"
] |
class Story:
"""
Structure representing a user story with its associated items.
Provides methods for accessing story properties, as well as :meth:`Story.get_items` to request associated
:class:`StoryItem` nodes. Stories are returned by :meth:`Instaloader.get_stories`.
With a logged-in :class:`Instaloader` instance `L`, you may download all your visible user stories with::
for story in L.get_stories():
# story is a Story object
for item in story.get_items():
# item is a StoryItem object
L.download_storyitem(item, ':stories')
This class implements == and is hashable.
:param context: :class:`InstaloaderContext` instance used for additional queries if necessary.
:param node: Dictionary containing the available information of the story as returned by Instagram.
"""
def __init__(self, context: InstaloaderContext, node: Dict[str, Any]):
self._context = context
self._node = node
self._unique_id = None # type: Optional[str]
self._owner_profile = None # type: Optional[Profile]
def __repr__(self):
return '<Story by {} changed {:%Y-%m-%d_%H-%M-%S_UTC}>'.format(self.owner_username, self.latest_media_utc)
def __eq__(self, o: object) -> bool:
if isinstance(o, Story):
return self.unique_id == o.unique_id
return NotImplemented
def __hash__(self) -> int:
return hash(self.unique_id)
@property
def unique_id(self) -> Union[str, int]:
"""
This ID only equals amongst :class:`Story` instances which have the same owner and the same set of
:class:`StoryItem`. For all other :class:`Story` instances this ID is different.
"""
if not self._unique_id:
id_list = [item.mediaid for item in self.get_items()]
id_list.sort()
self._unique_id = str().join([str(self.owner_id)] + list(map(str, id_list)))
return self._unique_id
@property
def last_seen_local(self) -> Optional[datetime]:
"""Timestamp of the most recent StoryItem that has been watched or None (local time zone)."""
if self._node['seen']:
return datetime.fromtimestamp(self._node['seen'])
return None
@property
def last_seen_utc(self) -> Optional[datetime]:
"""Timestamp of the most recent StoryItem that has been watched or None (UTC)."""
if self._node['seen']:
return datetime.utcfromtimestamp(self._node['seen'])
return None
@property
def latest_media_local(self) -> datetime:
"""Timestamp when the last item of the story was created (local time zone)."""
return datetime.fromtimestamp(self._node['latest_reel_media'])
@property
def latest_media_utc(self) -> datetime:
"""Timestamp when the last item of the story was created (UTC)."""
return datetime.utcfromtimestamp(self._node['latest_reel_media'])
@property
def itemcount(self) -> int:
"""Count of items associated with the :class:`Story` instance."""
return len(self._node['items'])
@property
def owner_profile(self) -> Profile:
""":class:`Profile` instance of the story owner."""
if not self._owner_profile:
self._owner_profile = Profile(self._context, self._node['user'])
return self._owner_profile
@property
def owner_username(self) -> str:
"""The story owner's lowercase username."""
return self.owner_profile.username
@property
def owner_id(self) -> int:
"""The story owner's ID."""
return self.owner_profile.userid
def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all items from a story."""
yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items']))
|
[
"class",
"Story",
":",
"def",
"__init__",
"(",
"self",
",",
"context",
":",
"InstaloaderContext",
",",
"node",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
":",
"self",
".",
"_context",
"=",
"context",
"self",
".",
"_node",
"=",
"node",
"self",
".",
"_unique_id",
"=",
"None",
"self",
".",
"_owner_profile",
"=",
"None",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"'<Story by {} changed {:%Y-%m-%d_%H-%M-%S_UTC}>'",
".",
"format",
"(",
"self",
".",
"owner_username",
",",
"self",
".",
"latest_media_utc",
")",
"def",
"__eq__",
"(",
"self",
",",
"o",
":",
"object",
")",
"->",
"bool",
":",
"if",
"isinstance",
"(",
"o",
",",
"Story",
")",
":",
"return",
"self",
".",
"unique_id",
"==",
"o",
".",
"unique_id",
"return",
"NotImplemented",
"def",
"__hash__",
"(",
"self",
")",
"->",
"int",
":",
"return",
"hash",
"(",
"self",
".",
"unique_id",
")",
"@",
"property",
"def",
"unique_id",
"(",
"self",
")",
"->",
"Union",
"[",
"str",
",",
"int",
"]",
":",
"\"\"\"\n This ID only equals amongst :class:`Story` instances which have the same owner and the same set of\n :class:`StoryItem`. For all other :class:`Story` instances this ID is different.\n \"\"\"",
"if",
"not",
"self",
".",
"_unique_id",
":",
"id_list",
"=",
"[",
"item",
".",
"mediaid",
"for",
"item",
"in",
"self",
".",
"get_items",
"(",
")",
"]",
"id_list",
".",
"sort",
"(",
")",
"self",
".",
"_unique_id",
"=",
"str",
"(",
")",
".",
"join",
"(",
"[",
"str",
"(",
"self",
".",
"owner_id",
")",
"]",
"+",
"list",
"(",
"map",
"(",
"str",
",",
"id_list",
")",
")",
")",
"return",
"self",
".",
"_unique_id",
"@",
"property",
"def",
"last_seen_local",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
"]",
":",
"\"\"\"Timestamp of the most recent StoryItem that has been watched or None (local time zone).\"\"\"",
"if",
"self",
".",
"_node",
"[",
"'seen'",
"]",
":",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"_node",
"[",
"'seen'",
"]",
")",
"return",
"None",
"@",
"property",
"def",
"last_seen_utc",
"(",
"self",
")",
"->",
"Optional",
"[",
"datetime",
"]",
":",
"\"\"\"Timestamp of the most recent StoryItem that has been watched or None (UTC).\"\"\"",
"if",
"self",
".",
"_node",
"[",
"'seen'",
"]",
":",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"_node",
"[",
"'seen'",
"]",
")",
"return",
"None",
"@",
"property",
"def",
"latest_media_local",
"(",
"self",
")",
"->",
"datetime",
":",
"\"\"\"Timestamp when the last item of the story was created (local time zone).\"\"\"",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"self",
".",
"_node",
"[",
"'latest_reel_media'",
"]",
")",
"@",
"property",
"def",
"latest_media_utc",
"(",
"self",
")",
"->",
"datetime",
":",
"\"\"\"Timestamp when the last item of the story was created (UTC).\"\"\"",
"return",
"datetime",
".",
"utcfromtimestamp",
"(",
"self",
".",
"_node",
"[",
"'latest_reel_media'",
"]",
")",
"@",
"property",
"def",
"itemcount",
"(",
"self",
")",
"->",
"int",
":",
"\"\"\"Count of items associated with the :class:`Story` instance.\"\"\"",
"return",
"len",
"(",
"self",
".",
"_node",
"[",
"'items'",
"]",
")",
"@",
"property",
"def",
"owner_profile",
"(",
"self",
")",
"->",
"Profile",
":",
"\"\"\":class:`Profile` instance of the story owner.\"\"\"",
"if",
"not",
"self",
".",
"_owner_profile",
":",
"self",
".",
"_owner_profile",
"=",
"Profile",
"(",
"self",
".",
"_context",
",",
"self",
".",
"_node",
"[",
"'user'",
"]",
")",
"return",
"self",
".",
"_owner_profile",
"@",
"property",
"def",
"owner_username",
"(",
"self",
")",
"->",
"str",
":",
"\"\"\"The story owner's lowercase username.\"\"\"",
"return",
"self",
".",
"owner_profile",
".",
"username",
"@",
"property",
"def",
"owner_id",
"(",
"self",
")",
"->",
"int",
":",
"\"\"\"The story owner's ID.\"\"\"",
"return",
"self",
".",
"owner_profile",
".",
"userid",
"def",
"get_items",
"(",
"self",
")",
"->",
"Iterator",
"[",
"StoryItem",
"]",
":",
"\"\"\"Retrieve all items from a story.\"\"\"",
"yield",
"from",
"(",
"StoryItem",
"(",
"self",
".",
"_context",
",",
"item",
",",
"self",
".",
"owner_profile",
")",
"for",
"item",
"in",
"reversed",
"(",
"self",
".",
"_node",
"[",
"'items'",
"]",
")",
")"
] |
Structure representing a user story with its associated items.
|
[
"Structure",
"representing",
"a",
"user",
"story",
"with",
"its",
"associated",
"items",
"."
] |
[
"\"\"\"\n Structure representing a user story with its associated items.\n\n Provides methods for accessing story properties, as well as :meth:`Story.get_items` to request associated\n :class:`StoryItem` nodes. Stories are returned by :meth:`Instaloader.get_stories`.\n\n With a logged-in :class:`Instaloader` instance `L`, you may download all your visible user stories with::\n\n for story in L.get_stories():\n # story is a Story object\n for item in story.get_items():\n # item is a StoryItem object\n L.download_storyitem(item, ':stories')\n\n This class implements == and is hashable.\n\n :param context: :class:`InstaloaderContext` instance used for additional queries if necessary.\n :param node: Dictionary containing the available information of the story as returned by Instagram.\n \"\"\"",
"# type: Optional[str]",
"# type: Optional[Profile]",
"\"\"\"\n This ID only equals amongst :class:`Story` instances which have the same owner and the same set of\n :class:`StoryItem`. For all other :class:`Story` instances this ID is different.\n \"\"\"",
"\"\"\"Timestamp of the most recent StoryItem that has been watched or None (local time zone).\"\"\"",
"\"\"\"Timestamp of the most recent StoryItem that has been watched or None (UTC).\"\"\"",
"\"\"\"Timestamp when the last item of the story was created (local time zone).\"\"\"",
"\"\"\"Timestamp when the last item of the story was created (UTC).\"\"\"",
"\"\"\"Count of items associated with the :class:`Story` instance.\"\"\"",
"\"\"\":class:`Profile` instance of the story owner.\"\"\"",
"\"\"\"The story owner's lowercase username.\"\"\"",
"\"\"\"The story owner's ID.\"\"\"",
"\"\"\"Retrieve all items from a story.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "context",
"type": null,
"docstring": ":class:`InstaloaderContext` instance used for additional queries if necessary.",
"docstring_tokens": [
":",
"class",
":",
"`",
"InstaloaderContext",
"`",
"instance",
"used",
"for",
"additional",
"queries",
"if",
"necessary",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "node",
"type": null,
"docstring": "Dictionary containing the available information of the story as returned by Instagram.",
"docstring_tokens": [
"Dictionary",
"containing",
"the",
"available",
"information",
"of",
"the",
"story",
"as",
"returned",
"by",
"Instagram",
"."
],
"default": null,
"is_optional": null
}
],
"others": [
{
"identifier": "class",
"docstring": "`StoryItem` nodes. Stories are returned by :meth:`Instaloader.get_stories`.\nWith a logged-in :class:`Instaloader` instance `L`, you may download all your visible user stories with:.\n\nfor story in L.get_stories():\nstory is a Story object\nfor item in story.get_items():\nitem is a StoryItem object\nL.download_storyitem(item, ':stories')\n\nThis class implements == and is hashable.",
"docstring_tokens": [
"`",
"StoryItem",
"`",
"nodes",
".",
"Stories",
"are",
"returned",
"by",
":",
"meth",
":",
"`",
"Instaloader",
".",
"get_stories",
"`",
".",
"With",
"a",
"logged",
"-",
"in",
":",
"class",
":",
"`",
"Instaloader",
"`",
"instance",
"`",
"L",
"`",
"you",
"may",
"download",
"all",
"your",
"visible",
"user",
"stories",
"with",
":",
".",
"for",
"story",
"in",
"L",
".",
"get_stories",
"()",
":",
"story",
"is",
"a",
"Story",
"object",
"for",
"item",
"in",
"story",
".",
"get_items",
"()",
":",
"item",
"is",
"a",
"StoryItem",
"object",
"L",
".",
"download_storyitem",
"(",
"item",
"'",
":",
"stories",
"'",
")",
"This",
"class",
"implements",
"==",
"and",
"is",
"hashable",
"."
]
}
]
}
| false
| 17
| 870
| 177
|
0e9e5242f2651ee0a2fd00a24ca125411b9d5ee1
|
johnknapprs/danger-sentiment
|
lib/sentiment/plugin.rb
|
[
"MIT"
] |
Ruby
|
DangerSentiment
|
# This is your plugin class. Any attributes or methods you expose here will
# be available from within your Dangerfile.
#
# To be published on the Danger plugins site, you will need to have
# the public interface documented. Danger uses [YARD](http://yardoc.org/)
# for generating documentation from your plugin source, and you can verify
# by running `danger plugins lint` or `bundle exec rake spec`.
#
# You should replace these comments with a public description of your library.
#
# @example Analyze all comments made on Pull Request
#
# sentiment.analyze
#
# @see johnknapprs/danger-sentiment
# @tags sentiment, tone, language
#
|
This is your plugin class. Any attributes or methods you expose here will
be available from within your Dangerfile.
To be published on the Danger plugins site, you will need to have
the public interface documented. Danger uses [YARD]
for generating documentation from your plugin source, and you can verify
by running `danger plugins lint` or `bundle exec rake spec`.
You should replace these comments with a public description of your library.
|
[
"This",
"is",
"your",
"plugin",
"class",
".",
"Any",
"attributes",
"or",
"methods",
"you",
"expose",
"here",
"will",
"be",
"available",
"from",
"within",
"your",
"Dangerfile",
".",
"To",
"be",
"published",
"on",
"the",
"Danger",
"plugins",
"site",
"you",
"will",
"need",
"to",
"have",
"the",
"public",
"interface",
"documented",
".",
"Danger",
"uses",
"[",
"YARD",
"]",
"for",
"generating",
"documentation",
"from",
"your",
"plugin",
"source",
"and",
"you",
"can",
"verify",
"by",
"running",
"`",
"danger",
"plugins",
"lint",
"`",
"or",
"`",
"bundle",
"exec",
"rake",
"spec",
"`",
".",
"You",
"should",
"replace",
"these",
"comments",
"with",
"a",
"public",
"description",
"of",
"your",
"library",
"."
] |
class DangerSentiment < Plugin
require 'rest-client'
# An attribute that you can read/write from your Dangerfile
#
# @return [String]
attr_accessor :api_token
# A method that you can call from your Dangerfile
# @return [String]
#
def initialize(msg = 'You must call sentiment.configure before sentiment.evaluate can be used')
super
@api_token = ENV['PARALLEL_DOTS_API_KEY']
end
# Analyze all PullRequest Comments and post results
# @return [String]
#
def post_analysis
issues.each do |i|
text_content = i[:comment_body]
response = RestClient.post(
'https://apis.paralleldots.com/v4/sentiment',
{
api_key: ENV['PARALLEL_DOTS_API_KEY'],
text: text_content
}
)
response = JSON.parse(response)
markdown("Username: #{i[:username]}\nMessage: #{text_content}\n\n#{format_response(response)}\n")
end
end
def formatted_analysis
result = []
issues.each do |i|
text_content = i[:comment_body]
response = RestClient.post(
'https://apis.paralleldots.com/v4/sentiment',
{
api_key: api_token,
text: text_content
}
)
response = JSON.parse(response)
result << "Username: #{i[:username]}\n\nMessage: #{text_content}\n#{format_response(response)}\n"
end
result.join("\n")
end
private
def format_response(data)
table = []
table << '| sentiment | score |'
table << '|---|---|'
table << data['sentiment'].map { |k, v| "| #{k} | #{v} |" }
table.join("\n")
end
# Array of hashes for posted Issues { username: , comment_id: comment_body: }
#
# @return [Array<Hash>]
def issues
@issues ||= github.api
.issue_comments(respository_name, github.pr_json.number)
.reject { |c| c.body.include?('<!--') }
.collect do |c|
{
username: c.user.login,
comment_id: c.id,
comment_body: c.body
}
end
end
def respository_name
github.pr_json.base.repo.full_name
end
end
|
[
"class",
"DangerSentiment",
"<",
"Plugin",
"require",
"'rest-client'",
"attr_accessor",
":api_token",
"def",
"initialize",
"(",
"msg",
"=",
"'You must call sentiment.configure before sentiment.evaluate can be used'",
")",
"super",
"@api_token",
"=",
"ENV",
"[",
"'PARALLEL_DOTS_API_KEY'",
"]",
"end",
"def",
"post_analysis",
"issues",
".",
"each",
"do",
"|",
"i",
"|",
"text_content",
"=",
"i",
"[",
":comment_body",
"]",
"response",
"=",
"RestClient",
".",
"post",
"(",
"'https://apis.paralleldots.com/v4/sentiment'",
",",
"{",
"api_key",
":",
"ENV",
"[",
"'PARALLEL_DOTS_API_KEY'",
"]",
",",
"text",
":",
"text_content",
"}",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
"markdown",
"(",
"\"Username: #{i[:username]}\\nMessage: #{text_content}\\n\\n#{format_response(response)}\\n\"",
")",
"end",
"end",
"def",
"formatted_analysis",
"result",
"=",
"[",
"]",
"issues",
".",
"each",
"do",
"|",
"i",
"|",
"text_content",
"=",
"i",
"[",
":comment_body",
"]",
"response",
"=",
"RestClient",
".",
"post",
"(",
"'https://apis.paralleldots.com/v4/sentiment'",
",",
"{",
"api_key",
":",
"api_token",
",",
"text",
":",
"text_content",
"}",
")",
"response",
"=",
"JSON",
".",
"parse",
"(",
"response",
")",
"result",
"<<",
"\"Username: #{i[:username]}\\n\\nMessage: #{text_content}\\n#{format_response(response)}\\n\"",
"end",
"result",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"private",
"def",
"format_response",
"(",
"data",
")",
"table",
"=",
"[",
"]",
"table",
"<<",
"'| sentiment | score |'",
"table",
"<<",
"'|---|---|'",
"table",
"<<",
"data",
"[",
"'sentiment'",
"]",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"| #{k} | #{v} |\"",
"}",
"table",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"def",
"issues",
"@issues",
"||=",
"github",
".",
"api",
".",
"issue_comments",
"(",
"respository_name",
",",
"github",
".",
"pr_json",
".",
"number",
")",
".",
"reject",
"{",
"|",
"c",
"|",
"c",
".",
"body",
".",
"include?",
"(",
"'<!--'",
")",
"}",
".",
"collect",
"do",
"|",
"c",
"|",
"{",
"username",
":",
"c",
".",
"user",
".",
"login",
",",
"comment_id",
":",
"c",
".",
"id",
",",
"comment_body",
":",
"c",
".",
"body",
"}",
"end",
"end",
"def",
"respository_name",
"github",
".",
"pr_json",
".",
"base",
".",
"repo",
".",
"full_name",
"end",
"end"
] |
This is your plugin class.
|
[
"This",
"is",
"your",
"plugin",
"class",
"."
] |
[
"# An attribute that you can read/write from your Dangerfile",
"#",
"# @return [String]",
"# A method that you can call from your Dangerfile",
"# @return [String]",
"#",
"# Analyze all PullRequest Comments and post results",
"# @return [String]",
"#",
"# Array of hashes for posted Issues { username: , comment_id: comment_body: }",
"#",
"# @return [Array<Hash>]"
] |
[
{
"param": "Plugin",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Plugin",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "example",
"docstring": "Analyze all comments made on Pull Request sentiment.analyze",
"docstring_tokens": [
"Analyze",
"all",
"comments",
"made",
"on",
"Pull",
"Request",
"sentiment",
".",
"analyze"
]
},
{
"identifier": "see",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "tags",
"docstring": "sentiment, tone, language",
"docstring_tokens": [
"sentiment",
"tone",
"language"
]
}
]
}
| false
| 15
| 543
| 149
|
65d0908fb8120901caf9199790eafb6eb0b4442e
|
msheehan17/CS113
|
HW 08 - HuffManTree/src/edu/miracosta/cs113/Main.java
|
[
"MIT"
] |
Java
|
Main
|
/**
* Main.java - The driver program for our HuffmanTree demonstration.
*
* 1. The program will prompt the user for the URL of a website of their choice. The program will then create a file
* that contains the characters of the website (Note: Only authorized characters are lowercase letters, uppercase
* letters, numbers 0-9, and ' ', ?, !, ., tabs, and newline characters).
*
* 2. The program will then generate a String representation of the file in it's entirety. This will be used to create
* our HuffmanTree object, and then be used to encode the file.
*
* 3. Once the file has been encoded, the program will then decode the file.
*
* 4. After creating the decoded file (at this point in the program there should be three files: original, encoded,
* decoded) the program will then display the number of bits within each file. For the original and decoded file,
* the number of bits will be the product of the number of characters within the file, and 16. Because the encoded file
* will be a series of '0's and '1's, the number of bits for the encoded file will be the number of '0's and '1's within
* the file.
*
* 5. After the number of bits within each file has been determined, the compression rate will be calculated and the
* result will be displayed to the console. This wil demonstrate the way in which the huffman tree works by reducing
* the number of bits required to generate a file.
*
* @author Matthew Sheehan
* @version 1.0
*
*/
|
Main.java - The driver program for our HuffmanTree demonstration.
1. The program will prompt the user for the URL of a website of their choice. The program will then create a file
that contains the characters of the website (Note: Only authorized characters are lowercase letters, uppercase
letters, numbers 0-9, and ' ', ?, !, ., tabs, and newline characters).
2. The program will then generate a String representation of the file in it's entirety. This will be used to create
our HuffmanTree object, and then be used to encode the file.
3. Once the file has been encoded, the program will then decode the file.
4. After creating the decoded file (at this point in the program there should be three files: original, encoded,
decoded) the program will then display the number of bits within each file. For the original and decoded file,
the number of bits will be the product of the number of characters within the file, and 16.
5. After the number of bits within each file has been determined, the compression rate will be calculated and the
result will be displayed to the console. This wil demonstrate the way in which the huffman tree works by reducing
the number of bits required to generate a file.
@author Matthew Sheehan
@version 1.0
|
[
"Main",
".",
"java",
"-",
"The",
"driver",
"program",
"for",
"our",
"HuffmanTree",
"demonstration",
".",
"1",
".",
"The",
"program",
"will",
"prompt",
"the",
"user",
"for",
"the",
"URL",
"of",
"a",
"website",
"of",
"their",
"choice",
".",
"The",
"program",
"will",
"then",
"create",
"a",
"file",
"that",
"contains",
"the",
"characters",
"of",
"the",
"website",
"(",
"Note",
":",
"Only",
"authorized",
"characters",
"are",
"lowercase",
"letters",
"uppercase",
"letters",
"numbers",
"0",
"-",
"9",
"and",
"'",
"'",
"?",
"!",
".",
"tabs",
"and",
"newline",
"characters",
")",
".",
"2",
".",
"The",
"program",
"will",
"then",
"generate",
"a",
"String",
"representation",
"of",
"the",
"file",
"in",
"it",
"'",
"s",
"entirety",
".",
"This",
"will",
"be",
"used",
"to",
"create",
"our",
"HuffmanTree",
"object",
"and",
"then",
"be",
"used",
"to",
"encode",
"the",
"file",
".",
"3",
".",
"Once",
"the",
"file",
"has",
"been",
"encoded",
"the",
"program",
"will",
"then",
"decode",
"the",
"file",
".",
"4",
".",
"After",
"creating",
"the",
"decoded",
"file",
"(",
"at",
"this",
"point",
"in",
"the",
"program",
"there",
"should",
"be",
"three",
"files",
":",
"original",
"encoded",
"decoded",
")",
"the",
"program",
"will",
"then",
"display",
"the",
"number",
"of",
"bits",
"within",
"each",
"file",
".",
"For",
"the",
"original",
"and",
"decoded",
"file",
"the",
"number",
"of",
"bits",
"will",
"be",
"the",
"product",
"of",
"the",
"number",
"of",
"characters",
"within",
"the",
"file",
"and",
"16",
".",
"5",
".",
"After",
"the",
"number",
"of",
"bits",
"within",
"each",
"file",
"has",
"been",
"determined",
"the",
"compression",
"rate",
"will",
"be",
"calculated",
"and",
"the",
"result",
"will",
"be",
"displayed",
"to",
"the",
"console",
".",
"This",
"wil",
"demonstrate",
"the",
"way",
"in",
"which",
"the",
"huffman",
"tree",
"works",
"by",
"reducing",
"the",
"number",
"of",
"bits",
"required",
"to",
"generate",
"a",
"file",
".",
"@author",
"Matthew",
"Sheehan",
"@version",
"1",
".",
"0"
] |
class Main {
private static final String ORIGINAL_FILE_NAME = "webFile.txt"; // The name of the original file generated.
private static final String ENCODED_FILE_NAME = "encode.txt"; // The name of the encoded file.
private static final String DECODED_FILE_NAME = "decode.txt"; // The name of the decoded file.
private static HuffmanTree huff = null; // The HuffmanTree object that will be used throughout the program.
public static void main ( String[ ] args ) {
runProgram ( );
}
/**
* Consolidates the methods within one method for use by main.
*/
private static void runProgram ( ) {
// Prompt the user for their web page.
buildHTMLFile ( );
// Build the HuffmanTree
huff = new HuffmanTree ( getFileAsString ( ORIGINAL_FILE_NAME ) );
// Encode the file to another file.
createEncodedFile ( );
// Decode the file to another file.
createDecodedFile ( );
// Display the number of bits for each file, and the final compression rate.
getOriginalFileBits ( );
getEncodedFileBits ( );
getDecodedFileBits ( );
determineCompressionRate ( );
}
/**
* Prompts the user for the URL of the website they would like to render a HTML version of.
*/
private static void buildHTMLFile ( ) {
Scanner sc = new Scanner ( System.in ); // Object for taking in user input.
String userGivenURL; // The URL specified by the user.
boolean validInput = false; // Controls the exception until the user can enter a valid URL.
while ( ! validInput ) {
try {
System.out.print ( "Please enter the URL of the website you would like to take the text from: " );
userGivenURL = sc.nextLine ( );
TextFileGenerator.makeCleanFile ( userGivenURL, ORIGINAL_FILE_NAME );
validInput = true;
}
catch ( IOException e ) {
System.out.println ( "File could not be created." );
sc.nextLine ( ); // clear buffer.
}
}
}
/**
* Returns a String representation of the file argument.
*
* @param fileName The name of the file we want a String representation of.
* @return The String representation of the file.
*/
private static String getFileAsString ( String fileName ) {
Scanner input = null;
StringBuilder sb = new StringBuilder ( );
try {
input = new Scanner ( new FileInputStream ( fileName ) );
}
catch ( FileNotFoundException e ) {
System.out.println ( fileName + " file not found." );
}
while ( input.hasNext ( ) )
sb.append ( input.nextLine () );
input.close ( );
return sb.toString ( );
}
/**
* Creates an encoded file from the original file.
*/
private static void createEncodedFile ( ) {
PrintWriter output = null;
try {
output = new PrintWriter ( new FileOutputStream ( ENCODED_FILE_NAME ) );
}
catch ( FileNotFoundException e ) {
System.out.println ( ENCODED_FILE_NAME + " file not found." );
}
output.println ( huff.encode ( getFileAsString ( ORIGINAL_FILE_NAME ) ) );
output.close ( );
}
/**
* Creates a decoded file from the encoded file.
*/
private static void createDecodedFile ( ) {
PrintWriter output = null;
try {
output = new PrintWriter ( new FileOutputStream ( DECODED_FILE_NAME ) );
}
catch ( FileNotFoundException e ) {
System.out.println ( DECODED_FILE_NAME + " file not found." );
}
output.println ( huff.decode ( getFileAsString ( ENCODED_FILE_NAME ) ) );
output.close ( );
}
/**
* Displays and returns the number of bits for the original file created from the URL.
*
* @return The number of bits for the original file.
*/
private static int getOriginalFileBits ( ) {
return ( ( getFileAsString ( ORIGINAL_FILE_NAME ).length ( ) ) * 16 );
}
/**
* Displays the number of bits for the decoded file (16 bits for each character).
*/
private static int getDecodedFileBits ( ) {
return ( ( getFileAsString ( DECODED_FILE_NAME ).length ( ) ) * 16 );
}
/**
* Displays and returns the number of bits for the encoded file (1 bit for each character).
*
* @return The number of bits for the encoded file.
*/
private static int getEncodedFileBits ( ) {
return ( getFileAsString ( ENCODED_FILE_NAME ).length ( ) );
}
/**
* Displays the rate at which the file was compressed when it became encoded.
*/
private static void determineCompressionRate () {
System.out.println ( "\nOriginal file bits: " + getOriginalFileBits ( ) );
System.out.println ( "Encoded file bits: " + getEncodedFileBits ( ) );
System.out.println ( "Decoded file bits: " + getDecodedFileBits ( ) );
double compressionRate = ( ( double ) ( getOriginalFileBits ( ) / getEncodedFileBits ( ) ) );
System.out.printf ( "Compression rate: %.1f%%%n", compressionRate );
}
}
|
[
"class",
"Main",
"{",
"private",
"static",
"final",
"String",
"ORIGINAL_FILE_NAME",
"=",
"\"",
"webFile.txt",
"\"",
";",
"private",
"static",
"final",
"String",
"ENCODED_FILE_NAME",
"=",
"\"",
"encode.txt",
"\"",
";",
"private",
"static",
"final",
"String",
"DECODED_FILE_NAME",
"=",
"\"",
"decode.txt",
"\"",
";",
"private",
"static",
"HuffmanTree",
"huff",
"=",
"null",
";",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"runProgram",
"(",
")",
";",
"}",
"/**\n * Consolidates the methods within one method for use by main.\n */",
"private",
"static",
"void",
"runProgram",
"(",
")",
"{",
"buildHTMLFile",
"(",
")",
";",
"huff",
"=",
"new",
"HuffmanTree",
"(",
"getFileAsString",
"(",
"ORIGINAL_FILE_NAME",
")",
")",
";",
"createEncodedFile",
"(",
")",
";",
"createDecodedFile",
"(",
")",
";",
"getOriginalFileBits",
"(",
")",
";",
"getEncodedFileBits",
"(",
")",
";",
"getDecodedFileBits",
"(",
")",
";",
"determineCompressionRate",
"(",
")",
";",
"}",
"/**\n * Prompts the user for the URL of the website they would like to render a HTML version of.\n */",
"private",
"static",
"void",
"buildHTMLFile",
"(",
")",
"{",
"Scanner",
"sc",
"=",
"new",
"Scanner",
"(",
"System",
".",
"in",
")",
";",
"String",
"userGivenURL",
";",
"boolean",
"validInput",
"=",
"false",
";",
"while",
"(",
"!",
"validInput",
")",
"{",
"try",
"{",
"System",
".",
"out",
".",
"print",
"(",
"\"",
"Please enter the URL of the website you would like to take the text from: ",
"\"",
")",
";",
"userGivenURL",
"=",
"sc",
".",
"nextLine",
"(",
")",
";",
"TextFileGenerator",
".",
"makeCleanFile",
"(",
"userGivenURL",
",",
"ORIGINAL_FILE_NAME",
")",
";",
"validInput",
"=",
"true",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"File could not be created.",
"\"",
")",
";",
"sc",
".",
"nextLine",
"(",
")",
";",
"}",
"}",
"}",
"/**\n * Returns a String representation of the file argument.\n *\n * @param fileName The name of the file we want a String representation of.\n * @return The String representation of the file.\n */",
"private",
"static",
"String",
"getFileAsString",
"(",
"String",
"fileName",
")",
"{",
"Scanner",
"input",
"=",
"null",
";",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"try",
"{",
"input",
"=",
"new",
"Scanner",
"(",
"new",
"FileInputStream",
"(",
"fileName",
")",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"fileName",
"+",
"\"",
" file not found.",
"\"",
")",
";",
"}",
"while",
"(",
"input",
".",
"hasNext",
"(",
")",
")",
"sb",
".",
"append",
"(",
"input",
".",
"nextLine",
"(",
")",
")",
";",
"input",
".",
"close",
"(",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"/**\n * Creates an encoded file from the original file.\n */",
"private",
"static",
"void",
"createEncodedFile",
"(",
")",
"{",
"PrintWriter",
"output",
"=",
"null",
";",
"try",
"{",
"output",
"=",
"new",
"PrintWriter",
"(",
"new",
"FileOutputStream",
"(",
"ENCODED_FILE_NAME",
")",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"ENCODED_FILE_NAME",
"+",
"\"",
" file not found.",
"\"",
")",
";",
"}",
"output",
".",
"println",
"(",
"huff",
".",
"encode",
"(",
"getFileAsString",
"(",
"ORIGINAL_FILE_NAME",
")",
")",
")",
";",
"output",
".",
"close",
"(",
")",
";",
"}",
"/**\n * Creates a decoded file from the encoded file.\n */",
"private",
"static",
"void",
"createDecodedFile",
"(",
")",
"{",
"PrintWriter",
"output",
"=",
"null",
";",
"try",
"{",
"output",
"=",
"new",
"PrintWriter",
"(",
"new",
"FileOutputStream",
"(",
"DECODED_FILE_NAME",
")",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"DECODED_FILE_NAME",
"+",
"\"",
" file not found.",
"\"",
")",
";",
"}",
"output",
".",
"println",
"(",
"huff",
".",
"decode",
"(",
"getFileAsString",
"(",
"ENCODED_FILE_NAME",
")",
")",
")",
";",
"output",
".",
"close",
"(",
")",
";",
"}",
"/**\n * Displays and returns the number of bits for the original file created from the URL.\n *\n * @return The number of bits for the original file.\n */",
"private",
"static",
"int",
"getOriginalFileBits",
"(",
")",
"{",
"return",
"(",
"(",
"getFileAsString",
"(",
"ORIGINAL_FILE_NAME",
")",
".",
"length",
"(",
")",
")",
"*",
"16",
")",
";",
"}",
"/**\n * Displays the number of bits for the decoded file (16 bits for each character).\n */",
"private",
"static",
"int",
"getDecodedFileBits",
"(",
")",
"{",
"return",
"(",
"(",
"getFileAsString",
"(",
"DECODED_FILE_NAME",
")",
".",
"length",
"(",
")",
")",
"*",
"16",
")",
";",
"}",
"/**\n * Displays and returns the number of bits for the encoded file (1 bit for each character).\n *\n * @return The number of bits for the encoded file.\n */",
"private",
"static",
"int",
"getEncodedFileBits",
"(",
")",
"{",
"return",
"(",
"getFileAsString",
"(",
"ENCODED_FILE_NAME",
")",
".",
"length",
"(",
")",
")",
";",
"}",
"/**\n * Displays the rate at which the file was compressed when it became encoded.\n */",
"private",
"static",
"void",
"determineCompressionRate",
"(",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"\\n",
"Original file bits: ",
"\"",
"+",
"getOriginalFileBits",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Encoded file bits: ",
"\"",
"+",
"getEncodedFileBits",
"(",
")",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Decoded file bits: ",
"\"",
"+",
"getDecodedFileBits",
"(",
")",
")",
";",
"double",
"compressionRate",
"=",
"(",
"(",
"double",
")",
"(",
"getOriginalFileBits",
"(",
")",
"/",
"getEncodedFileBits",
"(",
")",
")",
")",
";",
"System",
".",
"out",
".",
"printf",
"(",
"\"",
"Compression rate: %.1f%%%n",
"\"",
",",
"compressionRate",
")",
";",
"}",
"}"
] |
Main.java - The driver program for our HuffmanTree demonstration.
|
[
"Main",
".",
"java",
"-",
"The",
"driver",
"program",
"for",
"our",
"HuffmanTree",
"demonstration",
"."
] |
[
"// The name of the original file generated.",
"// The name of the encoded file.",
"// The name of the decoded file.",
"// The HuffmanTree object that will be used throughout the program.",
"// Prompt the user for their web page.",
"// Build the HuffmanTree",
"// Encode the file to another file.",
"// Decode the file to another file.",
"// Display the number of bits for each file, and the final compression rate.",
"// Object for taking in user input.",
"// The URL specified by the user.",
"// Controls the exception until the user can enter a valid URL.",
"// clear buffer."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,137
| 347
|
22a64c9cbee7d140f9c78984d93b0f866bd60b35
|
ozcandegirmenci/ProcessViewer
|
ProcessViewer/FormMain.cs
|
[
"MIT"
] |
C#
|
ListenerControl
|
/// <summary>
/// A control for listening messages from ProcessViewer.Hooks.dll (Our Hook dll)
/// </summary>
/// <remarks>
/// This class is really very important. Because it allows us to transport informations between
/// Hooked application and our application.
///
/// Whenever a message comes to our Hooked Window it redirects this message to this control
/// by using WM_COPYDATA message.
///
/// Also Hook dll sends messages to this control about Parameters changing and result of the message
/// </remarks>
|
A control for listening messages from ProcessViewer.Hooks.dll (Our Hook dll)
|
[
"A",
"control",
"for",
"listening",
"messages",
"from",
"ProcessViewer",
".",
"Hooks",
".",
"dll",
"(",
"Our",
"Hook",
"dll",
")"
] |
private class ListenerControl : Control
{
#region Members
private static int HM_MESSAGE_RESULT;
#endregion
#region Initialization
public ListenerControl()
{
HM_MESSAGE_RESULT = NativeMethods.RegisterWindowMessage("ProcessViewer_MessageResult");
Parent = Instance;
}
#endregion
#region Protected Methods
protected override void WndProc(ref Message m)
{
if (m.Msg == (int)NativeMethods.Msgs.WM_COPYDATA)
{
NativeMethods.COPYDATASTRUCT cdata =
(NativeMethods.COPYDATASTRUCT)m.GetLParam(typeof(NativeMethods.COPYDATASTRUCT));
NativeMethods.HOOK_MSG msg = (NativeMethods.HOOK_MSG)Marshal.PtrToStructure(cdata.lpData,
typeof(NativeMethods.HOOK_MSG));
m.Result = Instance._SubClass.ProcessMessage(m.WParam, ref msg);
Marshal.DestroyStructure(m.LParam, typeof(NativeMethods.COPYDATASTRUCT));
}
#region DELETED
#endregion
else if (m.Msg == HM_MESSAGE_RESULT
&& Properties.Settings.Default.HandleMessageResults)
{
Instance._SubClass.ProcessMessageResult(m.WParam.ToInt32(), m.LParam);
}
else
{
base.WndProc(ref m);
}
}
#endregion
}
|
[
"private",
"class",
"ListenerControl",
":",
"Control",
"{",
"region",
" Members",
"private",
"static",
"int",
"HM_MESSAGE_RESULT",
";",
"endregion",
"region",
" Initialization",
"public",
"ListenerControl",
"(",
")",
"{",
"HM_MESSAGE_RESULT",
"=",
"NativeMethods",
".",
"RegisterWindowMessage",
"(",
"\"",
"ProcessViewer_MessageResult",
"\"",
")",
";",
"Parent",
"=",
"Instance",
";",
"}",
"endregion",
"region",
" Protected Methods",
"protected",
"override",
"void",
"WndProc",
"(",
"ref",
"Message",
"m",
")",
"{",
"if",
"(",
"m",
".",
"Msg",
"==",
"(",
"int",
")",
"NativeMethods",
".",
"Msgs",
".",
"WM_COPYDATA",
")",
"{",
"NativeMethods",
".",
"COPYDATASTRUCT",
"cdata",
"=",
"(",
"NativeMethods",
".",
"COPYDATASTRUCT",
")",
"m",
".",
"GetLParam",
"(",
"typeof",
"(",
"NativeMethods",
".",
"COPYDATASTRUCT",
")",
")",
";",
"NativeMethods",
".",
"HOOK_MSG",
"msg",
"=",
"(",
"NativeMethods",
".",
"HOOK_MSG",
")",
"Marshal",
".",
"PtrToStructure",
"(",
"cdata",
".",
"lpData",
",",
"typeof",
"(",
"NativeMethods",
".",
"HOOK_MSG",
")",
")",
";",
"m",
".",
"Result",
"=",
"Instance",
".",
"_SubClass",
".",
"ProcessMessage",
"(",
"m",
".",
"WParam",
",",
"ref",
"msg",
")",
";",
"Marshal",
".",
"DestroyStructure",
"(",
"m",
".",
"LParam",
",",
"typeof",
"(",
"NativeMethods",
".",
"COPYDATASTRUCT",
")",
")",
";",
"}",
"region",
" DELETED",
"endregion",
"else",
"if",
"(",
"m",
".",
"Msg",
"==",
"HM_MESSAGE_RESULT",
"&&",
"Properties",
".",
"Settings",
".",
"Default",
".",
"HandleMessageResults",
")",
"{",
"Instance",
".",
"_SubClass",
".",
"ProcessMessageResult",
"(",
"m",
".",
"WParam",
".",
"ToInt32",
"(",
")",
",",
"m",
".",
"LParam",
")",
";",
"}",
"else",
"{",
"base",
".",
"WndProc",
"(",
"ref",
"m",
")",
";",
"}",
"}",
"endregion",
"}"
] |
A control for listening messages from ProcessViewer.Hooks.dll (Our Hook dll)
|
[
"A",
"control",
"for",
"listening",
"messages",
"from",
"ProcessViewer",
".",
"Hooks",
".",
"dll",
"(",
"Our",
"Hook",
"dll",
")"
] |
[
"//private static int HM_PARAMETERS_CHANGED;",
"/// <summary>",
"/// Initialize a new instance of this class",
"/// </summary>",
"//HM_PARAMETERS_CHANGED = NativeMethods.RegisterWindowMessage(\"ProcessViewer_ParametersChanged\");",
"// message was sended by ProcessViewer.Hooks.dll from the Hooked application when",
"// a new message comes to that window",
"// LPARAM of this message contains a COPYDATASTRUCT which has HOOK_MSG struct in it",
"// This is the information of the message which is sended to the hooked window",
"// process message and set its result (0 ignore, 1 do nothing, other values replace parameters)",
"//else if (m.Msg == HM_PARAMETERS_CHANGED)",
"//{",
"// // this message is also sended by hooked window",
"// // to inform us parameters are changed by us",
"// StringBuilder text = new StringBuilder();",
"// text.Append(Properties.Resources.Hook_Parameters_Changed);",
"// text.Append(\" wParam->\" + m.WParam.ToInt32());",
"// text.Append(\", lParam->\" + m.LParam.ToInt32());",
"// text.AppendLine();",
"// MainForm.txtMessages.AppendText(text.ToString());",
"//}",
"// this message sended by hooked window to give information about the result of a message"
] |
[
{
"param": "Control",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Control",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "This class is really very important. Because it allows us to transport informations between\nHooked application and our application.\n\nWhenever a message comes to our Hooked Window it redirects this message to this control\nby using WM_COPYDATA message.\n\nAlso Hook dll sends messages to this control about Parameters changing and result of the message",
"docstring_tokens": [
"This",
"class",
"is",
"really",
"very",
"important",
".",
"Because",
"it",
"allows",
"us",
"to",
"transport",
"informations",
"between",
"Hooked",
"application",
"and",
"our",
"application",
".",
"Whenever",
"a",
"message",
"comes",
"to",
"our",
"Hooked",
"Window",
"it",
"redirects",
"this",
"message",
"to",
"this",
"control",
"by",
"using",
"WM_COPYDATA",
"message",
".",
"Also",
"Hook",
"dll",
"sends",
"messages",
"to",
"this",
"control",
"about",
"Parameters",
"changing",
"and",
"result",
"of",
"the",
"message"
]
}
]
}
| false
| 16
| 280
| 106
|
3ede745f9158047c3a83e8c2d70b28b35689ade2
|
gabrielemilan/SimpleIdServer
|
src/Templates/templates/SimpleIdServer.OpenID.Full/Resources/OpenIdGlobal.Designer.cs
|
[
"Apache-2.0"
] |
C#
|
OpenIdGlobal
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class OpenIdGlobal {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal OpenIdGlobal() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SimpleIdServer.OpenID.Full.Resources.OpenIdGlobal", typeof(OpenIdGlobal).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
public static string active_sessions {
get {
return ResourceManager.GetString("active_sessions", resourceCulture);
}
}
public static string authenticate {
get {
return ResourceManager.GetString("authenticate", resourceCulture);
}
}
public static string authenticate_email {
get {
return ResourceManager.GetString("authenticate_email", resourceCulture);
}
}
public static string authenticate_pwd {
get {
return ResourceManager.GetString("authenticate_pwd", resourceCulture);
}
}
public static string authenticate_sms {
get {
return ResourceManager.GetString("authenticate_sms", resourceCulture);
}
}
public static string authentication_time {
get {
return ResourceManager.GetString("authentication_time", resourceCulture);
}
}
public static string choose_session {
get {
return ResourceManager.GetString("choose_session", resourceCulture);
}
}
public static string claims {
get {
return ResourceManager.GetString("claims", resourceCulture);
}
}
public static string code_validity {
get {
return ResourceManager.GetString("code_validity", resourceCulture);
}
}
public static string confirm {
get {
return ResourceManager.GetString("confirm", resourceCulture);
}
}
public static string confirmationcode {
get {
return ResourceManager.GetString("confirmationcode", resourceCulture);
}
}
public static string confirmationcode_sent {
get {
return ResourceManager.GetString("confirmationcode_sent", resourceCulture);
}
}
public static string consent_client_access {
get {
return ResourceManager.GetString("consent_client_access", resourceCulture);
}
}
public static string consents {
get {
return ResourceManager.GetString("consents", resourceCulture);
}
}
public static string disconnect {
get {
return ResourceManager.GetString("disconnect", resourceCulture);
}
}
public static string email {
get {
return ResourceManager.GetString("email", resourceCulture);
}
}
public static string expiration_time {
get {
return ResourceManager.GetString("expiration_time", resourceCulture);
}
}
public static string home {
get {
return ResourceManager.GetString("home", resourceCulture);
}
}
public static string invalid_confirmationcode {
get {
return ResourceManager.GetString("invalid_confirmationcode", resourceCulture);
}
}
public static string invalid_credentials {
get {
return ResourceManager.GetString("invalid_credentials", resourceCulture);
}
}
public static string invalid_phonenumber {
get {
return ResourceManager.GetString("invalid_phonenumber", resourceCulture);
}
}
public static string invalid_request {
get {
return ResourceManager.GetString("invalid_request", resourceCulture);
}
}
public static string login {
get {
return ResourceManager.GetString("login", resourceCulture);
}
}
public static string manage_consents {
get {
return ResourceManager.GetString("manage_consents", resourceCulture);
}
}
public static string missing_confirmationcode {
get {
return ResourceManager.GetString("missing_confirmationcode", resourceCulture);
}
}
public static string missing_login {
get {
return ResourceManager.GetString("missing_login", resourceCulture);
}
}
public static string missing_password {
get {
return ResourceManager.GetString("missing_password", resourceCulture);
}
}
public static string missing_phonenumber {
get {
return ResourceManager.GetString("missing_phonenumber", resourceCulture);
}
}
public static string missing_return_url {
get {
return ResourceManager.GetString("missing_return_url", resourceCulture);
}
}
public static string password {
get {
return ResourceManager.GetString("password", resourceCulture);
}
}
public static string phonenumber {
get {
return ResourceManager.GetString("phonenumber", resourceCulture);
}
}
public static string policy {
get {
return ResourceManager.GetString("policy", resourceCulture);
}
}
public static string reject {
get {
return ResourceManager.GetString("reject", resourceCulture);
}
}
public static string remember_login {
get {
return ResourceManager.GetString("remember_login", resourceCulture);
}
}
public static string revoke_session_title {
get {
return ResourceManager.GetString("revoke_session_title", resourceCulture);
}
}
public static string scope_address {
get {
return ResourceManager.GetString("scope_address", resourceCulture);
}
}
public static string scope_email {
get {
return ResourceManager.GetString("scope_email", resourceCulture);
}
}
public static string scope_offline_access {
get {
return ResourceManager.GetString("scope_offline_access", resourceCulture);
}
}
public static string scope_openid {
get {
return ResourceManager.GetString("scope_openid", resourceCulture);
}
}
public static string scope_phone {
get {
return ResourceManager.GetString("scope_phone", resourceCulture);
}
}
public static string scope_profile {
get {
return ResourceManager.GetString("scope_profile", resourceCulture);
}
}
public static string scopes {
get {
return ResourceManager.GetString("scopes", resourceCulture);
}
}
public static string select_session {
get {
return ResourceManager.GetString("select_session", resourceCulture);
}
}
public static string sendconfirmationcode {
get {
return ResourceManager.GetString("sendconfirmationcode", resourceCulture);
}
}
public static string submit {
get {
return ResourceManager.GetString("submit", resourceCulture);
}
}
public static string tos {
get {
return ResourceManager.GetString("tos", resourceCulture);
}
}
public static string unknown_email {
get {
return ResourceManager.GetString("unknown_email", resourceCulture);
}
}
public static string unknown_phonenumber {
get {
return ResourceManager.GetString("unknown_phonenumber", resourceCulture);
}
}
public static string unknown_user {
get {
return ResourceManager.GetString("unknown_user", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"16.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"public",
"class",
"OpenIdGlobal",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"OpenIdGlobal",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"SimpleIdServer.OpenID.Full.Resources.OpenIdGlobal",
"\"",
",",
"typeof",
"(",
"OpenIdGlobal",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"public",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"public",
"static",
"string",
"active_sessions",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"active_sessions",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"authenticate",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"authenticate",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"authenticate_email",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"authenticate_email",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"authenticate_pwd",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"authenticate_pwd",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"authenticate_sms",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"authenticate_sms",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"authentication_time",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"authentication_time",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"choose_session",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"choose_session",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"claims",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"claims",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"code_validity",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"code_validity",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"confirm",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"confirm",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"confirmationcode",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"confirmationcode",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"confirmationcode_sent",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"confirmationcode_sent",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"consent_client_access",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"consent_client_access",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"consents",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"consents",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"disconnect",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"disconnect",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"email",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"email",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"expiration_time",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"expiration_time",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"home",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"home",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"invalid_confirmationcode",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"invalid_confirmationcode",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"invalid_credentials",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"invalid_credentials",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"invalid_phonenumber",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"invalid_phonenumber",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"invalid_request",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"invalid_request",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"login",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"login",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"manage_consents",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"manage_consents",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"missing_confirmationcode",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"missing_confirmationcode",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"missing_login",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"missing_login",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"missing_password",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"missing_password",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"missing_phonenumber",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"missing_phonenumber",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"missing_return_url",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"missing_return_url",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"password",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"password",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"phonenumber",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"phonenumber",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"policy",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"policy",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"reject",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"reject",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"remember_login",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"remember_login",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"revoke_session_title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"revoke_session_title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_address",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_address",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_email",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_email",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_offline_access",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_offline_access",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_openid",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_openid",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_phone",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_phone",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scope_profile",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scope_profile",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"scopes",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"scopes",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"select_session",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"select_session",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"sendconfirmationcode",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"sendconfirmationcode",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"submit",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"submit",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"tos",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"tos",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"unknown_email",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"unknown_email",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"unknown_phonenumber",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"unknown_phonenumber",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"public",
"static",
"string",
"unknown_user",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"unknown_user",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Active sessions.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Authenticate.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Email authentication.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Login password authentication.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to SMS authentication.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Authentication time {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Choose session.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Claims.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Code has a validity of {0} seconds.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Confirm.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Confirmation code.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Confirmation code has been sent.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The client {0} would like to access to.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Consents.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Disconnect.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Email.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Expiration time {0}.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Home.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid confirmation code.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Bad credentials.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid phone number.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Invalid request.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Login.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Manage the consents.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Confirmation code is required.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Login is required.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Password is required.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Phone number is required.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Return url is required.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Password.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Phone number.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Policy.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Reject.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Remember my login.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Revoke session.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Access to the address.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Access to the email.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Offline access.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Access to user identifier.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Access to the phone.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Access to the profile.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Scopes.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Select active session.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Send confirmation code.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Submit.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Terms of service.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Email is unknown.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Unknown phone number.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to User is unknown.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,506
| 84
|
81c0c41fba5aa6a35c89a4bfc0ac913159825790
|
Syntea/xdef
|
xdef/src/main/java/org/xdef/XDFactory.java
|
[
"Apache-2.0"
] |
Java
|
XDFactory
|
/** Provides generation of {@link org.xdef.XDPool} from source
* X-definitions. You can modify properties of compilation by parameters from
* properties (see {@link org.xdef.XDConstants}). In most of cases you can
* get {@link org.xdef.XDPool} directly by using of static methods of
* {@link org.xdef.XDFactory} class. You can also create a XDBuilder when
* you have to compile XDPool from different sources of X-definitions.
* <p>The external methods must be static. The list of external classes with
* the external methods can be passed as a parameter containing array of
* classes. If relevant method is not found in the list of classes then the
* generator of XDPool is searching the the method in the system class path.
* <p>Typical use of XDFactory:
* <pre><code>
* // 1. Create XDPool from one source and no properties:
* File xdef = ...
* XDPool xd = XDFactory.compileXD(null, xdef);
* ...
* // 2. Create XDPool from more sources and with properties:
* File[] xdefs = ...
* Properties props = new Properties();
* props.setProperty(key, value); //see {@link org.xdef.XDConstants}
* XDPool xd = XDFactory.compileXD(props, xdefs);
* ...
* </code></pre>
* @author Vaclav Trojan
*/
|
Provides generation of org.xdef.XDPool from source
X-definitions. You can modify properties of compilation by parameters from
properties . In most of cases you can
get org.xdef.XDPool directly by using of static methods of
org.xdef.XDFactory class. You can also create a XDBuilder when
you have to compile XDPool from different sources of X-definitions.
The external methods must be static. The list of external classes with
the external methods can be passed as a parameter containing array of
classes. If relevant method is not found in the list of classes then the
generator of XDPool is searching the the method in the system class path.
Typical use of XDFactory:
1. Create XDPool from one source and no properties:
File xdef =
XDPool xd = XDFactory.compileXD(null, xdef);
2. Create XDPool from more sources and with properties:
File[] xdefs =
Properties props = new Properties();
props.setProperty(key, value); //see org.xdef.XDConstants
XDPool xd = XDFactory.compileXD(props, xdefs);
@author Vaclav Trojan
|
[
"Provides",
"generation",
"of",
"org",
".",
"xdef",
".",
"XDPool",
"from",
"source",
"X",
"-",
"definitions",
".",
"You",
"can",
"modify",
"properties",
"of",
"compilation",
"by",
"parameters",
"from",
"properties",
".",
"In",
"most",
"of",
"cases",
"you",
"can",
"get",
"org",
".",
"xdef",
".",
"XDPool",
"directly",
"by",
"using",
"of",
"static",
"methods",
"of",
"org",
".",
"xdef",
".",
"XDFactory",
"class",
".",
"You",
"can",
"also",
"create",
"a",
"XDBuilder",
"when",
"you",
"have",
"to",
"compile",
"XDPool",
"from",
"different",
"sources",
"of",
"X",
"-",
"definitions",
".",
"The",
"external",
"methods",
"must",
"be",
"static",
".",
"The",
"list",
"of",
"external",
"classes",
"with",
"the",
"external",
"methods",
"can",
"be",
"passed",
"as",
"a",
"parameter",
"containing",
"array",
"of",
"classes",
".",
"If",
"relevant",
"method",
"is",
"not",
"found",
"in",
"the",
"list",
"of",
"classes",
"then",
"the",
"generator",
"of",
"XDPool",
"is",
"searching",
"the",
"the",
"method",
"in",
"the",
"system",
"class",
"path",
".",
"Typical",
"use",
"of",
"XDFactory",
":",
"1",
".",
"Create",
"XDPool",
"from",
"one",
"source",
"and",
"no",
"properties",
":",
"File",
"xdef",
"=",
"XDPool",
"xd",
"=",
"XDFactory",
".",
"compileXD",
"(",
"null",
"xdef",
")",
";",
"2",
".",
"Create",
"XDPool",
"from",
"more",
"sources",
"and",
"with",
"properties",
":",
"File",
"[]",
"xdefs",
"=",
"Properties",
"props",
"=",
"new",
"Properties",
"()",
";",
"props",
".",
"setProperty",
"(",
"key",
"value",
")",
";",
"//",
"see",
"org",
".",
"xdef",
".",
"XDConstants",
"XDPool",
"xd",
"=",
"XDFactory",
".",
"compileXD",
"(",
"props",
"xdefs",
")",
";",
"@author",
"Vaclav",
"Trojan"
] |
public final class XDFactory extends XDTools {
/** Creates instance of XDBuilder with properties.
* @param props Properties or null - see {@link org.xdef.XDConstants}.
* @return created XDBuilder.
*/
public final static XDBuilder getXDBuilder(final Properties props) {
return getXDBuilder(null, props);
}
/** Creates instance of XDBuilder with properties.
* @param reporter the ReportWriter to be used for error reporting.
* @param props Properties or null - see {@link org.xdef.XDConstants}.
* @return created XDBuilder.
*/
public final static XDBuilder getXDBuilder(final ReportWriter reporter,
final Properties props) {
XDBuilder result = new org.xdef.impl.XBuilder(reporter, props);
return result;
}
@SuppressWarnings("deprecation")
/** Set object from parameter to be prepared for compiling.
* @param b Instance of XDBuilder.
* @param param Object to be analyzed for compiling.
*/
private static void setParam(final XDBuilder b, final Object param) {
if (param == null) {
return;
}
if (param instanceof Object[][]) {
Object[][] x = (Object[][]) param;
for (Object[] y : x) {
setParam(b, y);
}
return;
}
if (param instanceof Object[]) {
Object[] x = (Object[]) param;
if (x.length > 0 && x[0] instanceof Object[][]) {
setParam(b, (Object[][]) x[0]);
for (int i = 1; i < x.length; i++) {
setParam(b, x[i]);
}
return;
}
if (x.length == 2) {
if (x[0] instanceof InputStream && x[1] instanceof String) {
b.setSource((InputStream) x[0], (String) x[1]);
return;
}
if (x[0] instanceof Object[] && x[1] instanceof String[]) {
Object[] x1 = (Object[]) x[0];
String[] x2 = (String[]) x[1];
boolean ids = true;
for (int i = 0; i < x1.length; i++) {
Object y = x1[i];
if (y instanceof String) {
if (((String) y).charAt(0) != '<') {
ids = false;
break;
}
} else if (!(y instanceof InputStream)) {
ids = false;
break;
}
String s = x2[i];
if (s == null || s.charAt(0) == '<') {
ids = false;
break;
}
}
if (ids) {
// input data and source names
for (int i = 0; i < x1.length; i++) {
if (x1[i] instanceof String) {
b.setSource((String) x1[i], x2[i]);
} else {
b.setSource((InputStream) x1[i], x2[i]);
}
}
return;
}
}
}
for (Object o : x) {
setParam(b, o);
}
} else if (param instanceof Class) {
b.setExternals((Class) param);
} else if (param instanceof Class[]) {
Class[] x = (Class[]) param;
for (Class c : x) {
b.setExternals(c);
}
} else if (param instanceof String[]) {
String[] x = (String[]) param;
for (String s : x) {
b.setSource(s);
}
} else if (param instanceof String) {
b.setSource((String) param);
} else if (param instanceof File[]) {
File[] x = (File[]) param;
for (File f : x) {
b.setSource(f);
}
} else if (param instanceof File) {
b.setSource((File) param);
} else if (param instanceof URL[]) {
URL[] x = (URL[]) param;
for (URL u : x) {
b.setSource(u);
}
} else if (param instanceof URL) {
b.setSource((URL) param);
} else if ((param instanceof InputStream[])) {
InputStream[] x = (InputStream[]) param;
for (InputStream i : x) {
b.setSource(i, null);
}
} else if ((param instanceof InputStream)) {
b.setSource((InputStream) param, null);
} else if ((param instanceof Object[])) {
Object[] x = (Object[]) param;
if (x.length == 2 && (x[0] instanceof InputStream)
&& x[1] instanceof String) {
b.setSource((InputStream) x[0], (String) x[1]);
} else {
//Incorrect parameter of compiler of X-definitions&{0}{: }
throw new SRuntimeException(XDEF.XDEF904, param.getClass());
}
} else {
//Incorrect parameter of compiler of X-definitions&{0}{: }
throw new SRuntimeException(XDEF.XDEF904, param.getClass());
}
}
/** Compile XDPool from sources.
* @param props Properties or null.
* @param params list of strings with X-definition file names.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final String[] params) throws SRuntimeException {
XDBuilder builder = getXDBuilder(props);
setParam(builder, params);
return builder.compileXD();
}
/** Compile XDPool from URLs.
* @param props Properties or null.
* @param params list of URLs with X-definition sources.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final URL[] params) throws SRuntimeException {
XDBuilder builder = getXDBuilder(props);
setParam(builder, params);
return builder.compileXD();
}
/** Compile XDPool from files.
* @param props Properties or null.
* @param params list of files with X-definition sources.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final File[] params) throws SRuntimeException {
XDBuilder builder = getXDBuilder(props);
setParam(builder, params);
return builder.compileXD();
}
/** Compile XDPool from InputStreams.
* @param props Properties or null.
* @param params list of files with X-definition sources.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final InputStream[] params) throws SRuntimeException {
XDBuilder builder = getXDBuilder(props);
setParam(builder, params);
return builder.compileXD();
}
/** Compile XDPool from sources and assign the sourceId to each source.
* @param props Properties or null.
* @param sources array with source data with X-definitions source data.
* (The type of items can only be either the InputStreams or the String
* containing an XML document).
* @param sourceIds array with sourceIds (corresponding to the items
* in the argument sources).
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final Object[] sources,
final String[] sourceIds) throws SRuntimeException {
XDBuilder builder = XDFactory.getXDBuilder(props);
setParam(builder, new Object[] {sources, sourceIds});
return builder.compileXD();
}
/** Compile XDPool from source.
* @param props Properties or null.
* @param params list of sources, source pairs or external classes.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final Properties props,
final Object... params) throws SRuntimeException {
return compileXD((ReportWriter) null, props, params);
}
/** Compile XDPool from source.
* @param reporter the ReportWriter to be used for error reporting.
* @param props Properties or null.
* @param params list of sources, source pairs or external classes.
* @return generated XDPool.
* @throws SRuntimeException if an error occurs.
*/
public final static XDPool compileXD(final ReportWriter reporter,
final Properties props,
final Object... params) throws SRuntimeException {
if (params == null || params.length == 0) {
throw new SRuntimeException(XDEF.XDEF903);
}
XDBuilder builder = getXDBuilder(reporter, props);
setParam(builder, params);
return builder.compileXD();
}
/** Parse XML with X-definition declared in source input stream.
* @param source where to read XML.
* @param reporter used for error messages or null.
* @return created XDDocument object.
* @throws SRuntimeException if an error occurs.
*/
public final static XDDocument xparse(final InputStream source,
final ReportWriter reporter) throws SRuntimeException {
return XBuilder.xparse(source, reporter);
}
/** Parse XML with X-definition declared in source.
* @param source URL, pathname direct to XML or direct XML.
* @param reporter used for error messages or null.
* @return created XDDocument object.
* @throws SRuntimeException if an error occurs.
*/
public final static XDDocument xparse(final String source,
final ReportWriter reporter) throws SRuntimeException {
return XBuilder.xparse(source, reporter);
}
/** Write the XDPool to output stream.
* @param out output stream where to write XDPool.
* @param xp XDPool object.
* @throws IOException if an error occurs.
*/
public final static void writeXDPool(final OutputStream out,
final XDPool xp) throws IOException {
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(xp);
oout.close();
}
/** Write the XDPool to output stream.
* @param file file where to write XDPool.
* @param xp XDPool object.
* @throws IOException if an error occurs.
*/
public final static void writeXDPool(final File file, final XDPool xp)
throws IOException {
FileOutputStream fos = new FileOutputStream(file);
writeXDPool(fos, xp);
}
/** Write the XDPool to output stream.
* @param fname pathname where to write XDPool.
* @param xp XDPool object.
* @throws IOException if an error occurs.
*/
public final static void writeXDPool(final String fname, final XDPool xp)
throws IOException {
FileOutputStream fos = new FileOutputStream(fname);
writeXDPool(fos, xp);
}
/** Read the XDPool from the input stream.
* @param in input stream with X-definition.
* @return XDPool object.
* @throws IOException if an error occurs.
*/
public final static XDPool readXDPool(final InputStream in)
throws IOException {
try {
ObjectInputStream oin = new ObjectInputStream(in);
XDPool result = (XDPool) oin.readObject();
oin.close();
return result;
} catch (ClassNotFoundException ex) {
in.close();
throw new IOException(ex);
}
}
/** Read the XDPool from the input stream.
* @param file file with X-definition.
* @return XDPool object.
* @throws IOException if an error occurs.
*/
public final static XDPool readXDPool(final File file) throws IOException {
return readXDPool(new FileInputStream(file));
}
/** Read the XDPool from the input stream.
* @param fname pathname of file or string with URL with X-definition (it
* may be also "classpath://.....").
* @return XDPool object.
* @throws IOException if an error occurs.
*/
public final static XDPool readXDPool(final String fname)
throws IOException {
if (!new File(fname).exists() && fname.indexOf("://") > 0) {
return readXDPool(FUtils.getExtendedURL(fname).openStream());
} else {
return readXDPool(new FileInputStream(fname));
}
}
/** Read the XDPool from the input stream.
* @param url URL where is data with XDPool.
* @return XDPool object.
* @throws IOException if an error occurs.
*/
public final static XDPool readXDPool(final URL url) throws IOException {
return readXDPool(url.openStream());
}
}
|
[
"public",
"final",
"class",
"XDFactory",
"extends",
"XDTools",
"{",
"/** Creates instance of XDBuilder with properties.\n\t * @param props Properties or null - see {@link org.xdef.XDConstants}.\n\t * @return created XDBuilder.\n\t */",
"public",
"final",
"static",
"XDBuilder",
"getXDBuilder",
"(",
"final",
"Properties",
"props",
")",
"{",
"return",
"getXDBuilder",
"(",
"null",
",",
"props",
")",
";",
"}",
"/** Creates instance of XDBuilder with properties.\n\t * @param reporter the ReportWriter to be used for error reporting.\n\t * @param props Properties or null - see {@link org.xdef.XDConstants}.\n\t * @return created XDBuilder.\n\t */",
"public",
"final",
"static",
"XDBuilder",
"getXDBuilder",
"(",
"final",
"ReportWriter",
"reporter",
",",
"final",
"Properties",
"props",
")",
"{",
"XDBuilder",
"result",
"=",
"new",
"org",
".",
"xdef",
".",
"impl",
".",
"XBuilder",
"(",
"reporter",
",",
"props",
")",
";",
"return",
"result",
";",
"}",
"@",
"SuppressWarnings",
"(",
"\"",
"deprecation",
"\"",
")",
"/** Set object from parameter to be prepared for compiling.\n\t * @param b Instance of XDBuilder.\n\t * @param param Object to be analyzed for compiling.\n\t */",
"private",
"static",
"void",
"setParam",
"(",
"final",
"XDBuilder",
"b",
",",
"final",
"Object",
"param",
")",
"{",
"if",
"(",
"param",
"==",
"null",
")",
"{",
"return",
";",
"}",
"if",
"(",
"param",
"instanceof",
"Object",
"[",
"]",
"[",
"]",
")",
"{",
"Object",
"[",
"]",
"[",
"]",
"x",
"=",
"(",
"Object",
"[",
"]",
"[",
"]",
")",
"param",
";",
"for",
"(",
"Object",
"[",
"]",
"y",
":",
"x",
")",
"{",
"setParam",
"(",
"b",
",",
"y",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"param",
"instanceof",
"Object",
"[",
"]",
")",
"{",
"Object",
"[",
"]",
"x",
"=",
"(",
"Object",
"[",
"]",
")",
"param",
";",
"if",
"(",
"x",
".",
"length",
">",
"0",
"&&",
"x",
"[",
"0",
"]",
"instanceof",
"Object",
"[",
"]",
"[",
"]",
")",
"{",
"setParam",
"(",
"b",
",",
"(",
"Object",
"[",
"]",
"[",
"]",
")",
"x",
"[",
"0",
"]",
")",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"x",
".",
"length",
";",
"i",
"++",
")",
"{",
"setParam",
"(",
"b",
",",
"x",
"[",
"i",
"]",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"x",
".",
"length",
"==",
"2",
")",
"{",
"if",
"(",
"x",
"[",
"0",
"]",
"instanceof",
"InputStream",
"&&",
"x",
"[",
"1",
"]",
"instanceof",
"String",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"InputStream",
")",
"x",
"[",
"0",
"]",
",",
"(",
"String",
")",
"x",
"[",
"1",
"]",
")",
";",
"return",
";",
"}",
"if",
"(",
"x",
"[",
"0",
"]",
"instanceof",
"Object",
"[",
"]",
"&&",
"x",
"[",
"1",
"]",
"instanceof",
"String",
"[",
"]",
")",
"{",
"Object",
"[",
"]",
"x1",
"=",
"(",
"Object",
"[",
"]",
")",
"x",
"[",
"0",
"]",
";",
"String",
"[",
"]",
"x2",
"=",
"(",
"String",
"[",
"]",
")",
"x",
"[",
"1",
"]",
";",
"boolean",
"ids",
"=",
"true",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"x1",
".",
"length",
";",
"i",
"++",
")",
"{",
"Object",
"y",
"=",
"x1",
"[",
"i",
"]",
";",
"if",
"(",
"y",
"instanceof",
"String",
")",
"{",
"if",
"(",
"(",
"(",
"String",
")",
"y",
")",
".",
"charAt",
"(",
"0",
")",
"!=",
"'<'",
")",
"{",
"ids",
"=",
"false",
";",
"break",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"(",
"y",
"instanceof",
"InputStream",
")",
")",
"{",
"ids",
"=",
"false",
";",
"break",
";",
"}",
"String",
"s",
"=",
"x2",
"[",
"i",
"]",
";",
"if",
"(",
"s",
"==",
"null",
"||",
"s",
".",
"charAt",
"(",
"0",
")",
"==",
"'<'",
")",
"{",
"ids",
"=",
"false",
";",
"break",
";",
"}",
"}",
"if",
"(",
"ids",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"x1",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"x1",
"[",
"i",
"]",
"instanceof",
"String",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"String",
")",
"x1",
"[",
"i",
"]",
",",
"x2",
"[",
"i",
"]",
")",
";",
"}",
"else",
"{",
"b",
".",
"setSource",
"(",
"(",
"InputStream",
")",
"x1",
"[",
"i",
"]",
",",
"x2",
"[",
"i",
"]",
")",
";",
"}",
"}",
"return",
";",
"}",
"}",
"}",
"for",
"(",
"Object",
"o",
":",
"x",
")",
"{",
"setParam",
"(",
"b",
",",
"o",
")",
";",
"}",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"Class",
")",
"{",
"b",
".",
"setExternals",
"(",
"(",
"Class",
")",
"param",
")",
";",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"Class",
"[",
"]",
")",
"{",
"Class",
"[",
"]",
"x",
"=",
"(",
"Class",
"[",
"]",
")",
"param",
";",
"for",
"(",
"Class",
"c",
":",
"x",
")",
"{",
"b",
".",
"setExternals",
"(",
"c",
")",
";",
"}",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"String",
"[",
"]",
")",
"{",
"String",
"[",
"]",
"x",
"=",
"(",
"String",
"[",
"]",
")",
"param",
";",
"for",
"(",
"String",
"s",
":",
"x",
")",
"{",
"b",
".",
"setSource",
"(",
"s",
")",
";",
"}",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"String",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"String",
")",
"param",
")",
";",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"File",
"[",
"]",
")",
"{",
"File",
"[",
"]",
"x",
"=",
"(",
"File",
"[",
"]",
")",
"param",
";",
"for",
"(",
"File",
"f",
":",
"x",
")",
"{",
"b",
".",
"setSource",
"(",
"f",
")",
";",
"}",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"File",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"File",
")",
"param",
")",
";",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"URL",
"[",
"]",
")",
"{",
"URL",
"[",
"]",
"x",
"=",
"(",
"URL",
"[",
"]",
")",
"param",
";",
"for",
"(",
"URL",
"u",
":",
"x",
")",
"{",
"b",
".",
"setSource",
"(",
"u",
")",
";",
"}",
"}",
"else",
"if",
"(",
"param",
"instanceof",
"URL",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"URL",
")",
"param",
")",
";",
"}",
"else",
"if",
"(",
"(",
"param",
"instanceof",
"InputStream",
"[",
"]",
")",
")",
"{",
"InputStream",
"[",
"]",
"x",
"=",
"(",
"InputStream",
"[",
"]",
")",
"param",
";",
"for",
"(",
"InputStream",
"i",
":",
"x",
")",
"{",
"b",
".",
"setSource",
"(",
"i",
",",
"null",
")",
";",
"}",
"}",
"else",
"if",
"(",
"(",
"param",
"instanceof",
"InputStream",
")",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"InputStream",
")",
"param",
",",
"null",
")",
";",
"}",
"else",
"if",
"(",
"(",
"param",
"instanceof",
"Object",
"[",
"]",
")",
")",
"{",
"Object",
"[",
"]",
"x",
"=",
"(",
"Object",
"[",
"]",
")",
"param",
";",
"if",
"(",
"x",
".",
"length",
"==",
"2",
"&&",
"(",
"x",
"[",
"0",
"]",
"instanceof",
"InputStream",
")",
"&&",
"x",
"[",
"1",
"]",
"instanceof",
"String",
")",
"{",
"b",
".",
"setSource",
"(",
"(",
"InputStream",
")",
"x",
"[",
"0",
"]",
",",
"(",
"String",
")",
"x",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"SRuntimeException",
"(",
"XDEF",
".",
"XDEF904",
",",
"param",
".",
"getClass",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"throw",
"new",
"SRuntimeException",
"(",
"XDEF",
".",
"XDEF904",
",",
"param",
".",
"getClass",
"(",
")",
")",
";",
"}",
"}",
"/** Compile XDPool from sources.\n\t * @param props Properties or null.\n\t * @param params list of strings with X-definition file names.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"String",
"[",
"]",
"params",
")",
"throws",
"SRuntimeException",
"{",
"XDBuilder",
"builder",
"=",
"getXDBuilder",
"(",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"params",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Compile XDPool from URLs.\n\t * @param props Properties or null.\n\t * @param params list of URLs with X-definition sources.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"URL",
"[",
"]",
"params",
")",
"throws",
"SRuntimeException",
"{",
"XDBuilder",
"builder",
"=",
"getXDBuilder",
"(",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"params",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Compile XDPool from files.\n\t * @param props Properties or null.\n\t * @param params list of files with X-definition sources.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"File",
"[",
"]",
"params",
")",
"throws",
"SRuntimeException",
"{",
"XDBuilder",
"builder",
"=",
"getXDBuilder",
"(",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"params",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Compile XDPool from InputStreams.\n\t * @param props Properties or null.\n\t * @param params list of files with X-definition sources.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"InputStream",
"[",
"]",
"params",
")",
"throws",
"SRuntimeException",
"{",
"XDBuilder",
"builder",
"=",
"getXDBuilder",
"(",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"params",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Compile XDPool from sources and assign the sourceId to each source.\n\t * @param props Properties or null.\n\t * @param sources array with source data with X-definitions source data.\n\t * (The type of items can only be either the InputStreams or the String\n\t * containing an XML document).\n\t * @param sourceIds array with sourceIds (corresponding to the items\n\t * in the argument sources).\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"Object",
"[",
"]",
"sources",
",",
"final",
"String",
"[",
"]",
"sourceIds",
")",
"throws",
"SRuntimeException",
"{",
"XDBuilder",
"builder",
"=",
"XDFactory",
".",
"getXDBuilder",
"(",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"new",
"Object",
"[",
"]",
"{",
"sources",
",",
"sourceIds",
"}",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Compile XDPool from source.\n\t * @param props Properties or null.\n\t * @param params list of sources, source pairs or external classes.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"Properties",
"props",
",",
"final",
"Object",
"...",
"params",
")",
"throws",
"SRuntimeException",
"{",
"return",
"compileXD",
"(",
"(",
"ReportWriter",
")",
"null",
",",
"props",
",",
"params",
")",
";",
"}",
"/** Compile XDPool from source.\n\t * @param reporter the ReportWriter to be used for error reporting.\n\t * @param props Properties or null.\n\t * @param params list of sources, source pairs or external classes.\n\t * @return generated XDPool.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"compileXD",
"(",
"final",
"ReportWriter",
"reporter",
",",
"final",
"Properties",
"props",
",",
"final",
"Object",
"...",
"params",
")",
"throws",
"SRuntimeException",
"{",
"if",
"(",
"params",
"==",
"null",
"||",
"params",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"new",
"SRuntimeException",
"(",
"XDEF",
".",
"XDEF903",
")",
";",
"}",
"XDBuilder",
"builder",
"=",
"getXDBuilder",
"(",
"reporter",
",",
"props",
")",
";",
"setParam",
"(",
"builder",
",",
"params",
")",
";",
"return",
"builder",
".",
"compileXD",
"(",
")",
";",
"}",
"/** Parse XML with X-definition declared in source input stream.\n\t * @param source where to read XML.\n\t * @param reporter used for error messages or null.\n\t * @return created XDDocument object.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDDocument",
"xparse",
"(",
"final",
"InputStream",
"source",
",",
"final",
"ReportWriter",
"reporter",
")",
"throws",
"SRuntimeException",
"{",
"return",
"XBuilder",
".",
"xparse",
"(",
"source",
",",
"reporter",
")",
";",
"}",
"/** Parse XML with X-definition declared in source.\n\t * @param source URL, pathname direct to XML or direct XML.\n\t * @param reporter used for error messages or null.\n\t * @return created XDDocument object.\n\t * @throws SRuntimeException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDDocument",
"xparse",
"(",
"final",
"String",
"source",
",",
"final",
"ReportWriter",
"reporter",
")",
"throws",
"SRuntimeException",
"{",
"return",
"XBuilder",
".",
"xparse",
"(",
"source",
",",
"reporter",
")",
";",
"}",
"/** Write the XDPool to output stream.\n\t * @param out output stream where to write XDPool.\n\t * @param xp XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"void",
"writeXDPool",
"(",
"final",
"OutputStream",
"out",
",",
"final",
"XDPool",
"xp",
")",
"throws",
"IOException",
"{",
"ObjectOutputStream",
"oout",
"=",
"new",
"ObjectOutputStream",
"(",
"out",
")",
";",
"oout",
".",
"writeObject",
"(",
"xp",
")",
";",
"oout",
".",
"close",
"(",
")",
";",
"}",
"/** Write the XDPool to output stream.\n\t * @param file file where to write XDPool.\n\t * @param xp XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"void",
"writeXDPool",
"(",
"final",
"File",
"file",
",",
"final",
"XDPool",
"xp",
")",
"throws",
"IOException",
"{",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
";",
"writeXDPool",
"(",
"fos",
",",
"xp",
")",
";",
"}",
"/** Write the XDPool to output stream.\n\t * @param fname pathname where to write XDPool.\n\t * @param xp XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"void",
"writeXDPool",
"(",
"final",
"String",
"fname",
",",
"final",
"XDPool",
"xp",
")",
"throws",
"IOException",
"{",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"fname",
")",
";",
"writeXDPool",
"(",
"fos",
",",
"xp",
")",
";",
"}",
"/** Read the XDPool from the input stream.\n\t * @param in input stream with X-definition.\n\t * @return XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"readXDPool",
"(",
"final",
"InputStream",
"in",
")",
"throws",
"IOException",
"{",
"try",
"{",
"ObjectInputStream",
"oin",
"=",
"new",
"ObjectInputStream",
"(",
"in",
")",
";",
"XDPool",
"result",
"=",
"(",
"XDPool",
")",
"oin",
".",
"readObject",
"(",
")",
";",
"oin",
".",
"close",
"(",
")",
";",
"return",
"result",
";",
"}",
"catch",
"(",
"ClassNotFoundException",
"ex",
")",
"{",
"in",
".",
"close",
"(",
")",
";",
"throw",
"new",
"IOException",
"(",
"ex",
")",
";",
"}",
"}",
"/** Read the XDPool from the input stream.\n\t * @param file file with X-definition.\n\t * @return XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"readXDPool",
"(",
"final",
"File",
"file",
")",
"throws",
"IOException",
"{",
"return",
"readXDPool",
"(",
"new",
"FileInputStream",
"(",
"file",
")",
")",
";",
"}",
"/** Read the XDPool from the input stream.\n\t * @param fname pathname of file or string with URL with X-definition (it\n\t * may be also \"classpath://.....\").\n\t * @return XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"readXDPool",
"(",
"final",
"String",
"fname",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"new",
"File",
"(",
"fname",
")",
".",
"exists",
"(",
")",
"&&",
"fname",
".",
"indexOf",
"(",
"\"",
"://",
"\"",
")",
">",
"0",
")",
"{",
"return",
"readXDPool",
"(",
"FUtils",
".",
"getExtendedURL",
"(",
"fname",
")",
".",
"openStream",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"readXDPool",
"(",
"new",
"FileInputStream",
"(",
"fname",
")",
")",
";",
"}",
"}",
"/** Read the XDPool from the input stream.\n\t * @param url URL where is data with XDPool.\n\t * @return XDPool object.\n\t * @throws IOException if an error occurs.\n\t */",
"public",
"final",
"static",
"XDPool",
"readXDPool",
"(",
"final",
"URL",
"url",
")",
"throws",
"IOException",
"{",
"return",
"readXDPool",
"(",
"url",
".",
"openStream",
"(",
")",
")",
";",
"}",
"}"
] |
Provides generation of {@link org.xdef.XDPool} from source
X-definitions.
|
[
"Provides",
"generation",
"of",
"{",
"@link",
"org",
".",
"xdef",
".",
"XDPool",
"}",
"from",
"source",
"X",
"-",
"definitions",
"."
] |
[
"// input data and source names",
"//Incorrect parameter of compiler of X-definitions&{0}{: }",
"//Incorrect parameter of compiler of X-definitions&{0}{: }"
] |
[
{
"param": "XDTools",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "XDTools",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 25
| 2,869
| 309
|
a77a2ab0a571220eadfa52c1e30179009acf2148
|
KnowingNothing/akg-test
|
tests/prev_version_auto_tune/runner.py
|
[
"Apache-2.0"
] |
Python
|
KernelRunner
|
kernel runner
This runner will compile and execute configs of an operator, and return their running times.
Parameters
----------
op_type: str
The name of operator
op_desc: NamedTuple
The definition parameters of operator
timeout: int
Timeout for running one config
repeat_times:
Run one config repeat_times
|
kernel runner
This runner will compile and execute configs of an operator, and return their running times.
Parameters
str
The name of operator
op_desc: NamedTuple
The definition parameters of operator
timeout: int
Timeout for running one config
repeat_times:
Run one config repeat_times
|
[
"kernel",
"runner",
"This",
"runner",
"will",
"compile",
"and",
"execute",
"configs",
"of",
"an",
"operator",
"and",
"return",
"their",
"running",
"times",
".",
"Parameters",
"str",
"The",
"name",
"of",
"operator",
"op_desc",
":",
"NamedTuple",
"The",
"definition",
"parameters",
"of",
"operator",
"timeout",
":",
"int",
"Timeout",
"for",
"running",
"one",
"config",
"repeat_times",
":",
"Run",
"one",
"config",
"repeat_times"
] |
class KernelRunner:
"""kernel runner
This runner will compile and execute configs of an operator, and return their running times.
Parameters
----------
op_type: str
The name of operator
op_desc: NamedTuple
The definition parameters of operator
timeout: int
Timeout for running one config
repeat_times:
Run one config repeat_times
"""
def __init__(self, op_type: str, op_desc: NamedTuple, json_desc: str, index_table: list, timeout: int = 600,
repeat_times: int = 2, input_data=None, expect=None, mod_output_param=None):
self.op_type = op_type
self.op_desc = op_desc
self.json_desc = json_desc
self._index_table = index_table
self.run_kernel_time = 0.0
self.timeout = timeout
self.repeat_times = repeat_times
self.mod_output_param = mod_output_param
if input_data is None:
self.input, self.expect = gen_data(op_type, op_desc)
if isinstance(self.input, dict):
self.input, self.mod_output_param = self.input['args'], self.input['outputs']
else:
self.input, self.expect = input_data, expect
self.input_shape = [x.shape for x in self.input]
def info(self):
print('run kernel time:', self.run_kernel_time)
def run_one_kernel(self, run_times, idx, config, best_time=np.inf, is_auto=False):
"""Compile and execute a config of the operator on device"""
time_one_kernel_start = time.time()
logger.debug('compile %dth kernel', idx)
# get available device
if utils.get_available_devices_num() == 1:
device_id = utils.get_device_id()
else:
device_id = idx + utils.get_device_id()
os.environ['DEVICE_ID'] = str(device_id)
logger.debug('run %dth kernel', idx)
logger.debug('++++++++++++++++++++++=device_id')
logger.debug(device_id)
logger.debug('++++++++++++++++++++++=device_id')
try:
time_start_build = time.time()
logger.debug(config)
if self.op_type in ["json", "extra_tune"]:
if is_auto:
attrs = {}
attrs["kernel_name"] = "tuning_json_" + str(idx)
mod = composite.build(self.op_desc, attrs)
if self.op_type == "extra_tune":
del os.environ['MS_GRAPH_KERNEL_TILING']
else:
attrs = get_attr_from_config(config.input, self._index_table)
attrs["kernel_name"] = "tuning_json_" + str(idx)
if os.environ['RUNTIME_MODE'] == "gpu":
attrs['target'] = "cuda"
mod = composite.build(self.op_desc, attrs, use_repo=False)
elif self.op_type == "matmul_json":
attrs = get_matmul_cube_attrs(self.op_desc, config.input)
print(attrs)
mod = composite.build(self.json_desc, attrs, use_repo=False)
else:
mod = compile_kernel(self.op_type, self.op_desc, self.input_shape, self._index_table,
None if is_auto else config.input, idx)
time_end_build = time.time()
logger.debug("build module time: %f", time_end_build - time_start_build)
logger.debug('finished compile %dth kernel', idx)
except BaseException as e:
logger.warning("Compile Failed: [%s] : %s", "origin" if is_auto else str(config.input), str(e))
run_times[idx] = compile_fail_time
return
run_times[idx] = run_failed_time
try:
for _ in range(self.repeat_times):
stat_info = {}
try:
time_start_launch = time.time()
if self.mod_output_param is not None and len(self.mod_output_param) > 1:
output, stat_info = utils.mod_launch(mod, list(self.input), self.mod_output_param,
tuning=True, device_id=device_id)
if stat_info['run_time'] < best_time:
if not all(map(lambda x, y: np.allclose(x, y, rtol=5e-03, atol=5e-03, equal_nan=True),
output, self.expect)):
stat_info['run_time'] = precision_error_time
logger.warning("Precision Error: [%s]",
"origin" if config is None else str(config.input))
else:
if self.op_type in ["json", "extra_tune", "matmul_json"]:
output, stat_info = utils.mod_launch(mod, self.input, self.mod_output_param, tuning=True,
device_id=device_id)
else:
output, stat_info = utils.mod_launch(mod, self.input, tuning=True, device_id=device_id)
if stat_info['run_time'] < best_time:
if not np.allclose(output, self.expect, rtol=5e-03, atol=5e-03, equal_nan=True):
stat_info['run_time'] = precision_error_time
logger.warning("Precision Error: [%s]",
"origin" if config is None else str(config.input))
time_end_launch = time.time()
logger.debug("mod launch time: %f", time_end_launch - time_start_launch)
except BaseException as e:
logger.warning("Run Failed: [%s] : %s", str(config.input), str(e))
stat_info['run_time'] = run_failed_time
run_times[idx] = np.minimum(run_times[idx], stat_info['run_time'])
finally:
logger.debug('end of %dth kernel', idx)
time_one_kernel_end = time.time()
logger.debug('run one kernel time: %f', time_one_kernel_end - time_one_kernel_start)
return
def run(self, configs, best_time=np.inf, is_auto_set_dim=False, all_space=False):
"""Compile and execute a batch config of the operator on device"""
start = time.time()
logger.debug("gen cce kernels batch: %d kernels", len(configs))
subprocess.run("rm -rf ./jobs/JOB*", shell=True)
process_jobs = []
run_times = multiprocessing.Manager().list(np.full((len(configs),), compile_fail_time))
for idx, config in enumerate(configs):
p = multiprocessing.Process(target=self.run_one_kernel,
args=(run_times, idx, config, best_time, is_auto_set_dim))
process_jobs.append(p)
p.start()
timeout_error = False
for idx, p in enumerate(process_jobs):
if not timeout_error:
p.join(timeout=self.timeout)
if p.is_alive():
timeout_error = True
logger.debug("Timeout Error: [%s]", str(configs[idx].input))
run_times[idx] = timeout_time
p.terminate()
process_end = time.time()
logger.debug("process time: %f", process_end - start)
# clean the profiling directory
tune_device = int(os.environ['DEVICE_ID'])
tune_num = int(os.environ['DEVICE_TOTAL_NUM'])
if os.environ['RUNTIME_MODE'] == "gpu":
subprocess.run("rm -rf cuda_meta*", shell=True)
else:
profiling_dir = str(os.environ['PROFILING_DIR'])
if len(profiling_dir) == 0 or profiling_dir.isspace():
logger.error("The value about PROFILING_DIR shoud be setted correctly.")
subprocess.run("rm -rf %s/JOB*" % profiling_dir, shell=True)
end = time.time()
logger.debug("run kernels time: %f", end - start)
self.run_kernel_time += end - start
for idx, config in enumerate(configs):
if run_times[idx] not in error_time_list:
logger.debug("KernelRunTime : [%s] : %s", str(configs[idx].input), str(run_times[idx]))
else:
logger.debug("KernelRunTime : [%s] : %s",
str(configs[idx].input), str(error_time_string[run_times[idx]]))
return run_times
|
[
"class",
"KernelRunner",
":",
"def",
"__init__",
"(",
"self",
",",
"op_type",
":",
"str",
",",
"op_desc",
":",
"NamedTuple",
",",
"json_desc",
":",
"str",
",",
"index_table",
":",
"list",
",",
"timeout",
":",
"int",
"=",
"600",
",",
"repeat_times",
":",
"int",
"=",
"2",
",",
"input_data",
"=",
"None",
",",
"expect",
"=",
"None",
",",
"mod_output_param",
"=",
"None",
")",
":",
"self",
".",
"op_type",
"=",
"op_type",
"self",
".",
"op_desc",
"=",
"op_desc",
"self",
".",
"json_desc",
"=",
"json_desc",
"self",
".",
"_index_table",
"=",
"index_table",
"self",
".",
"run_kernel_time",
"=",
"0.0",
"self",
".",
"timeout",
"=",
"timeout",
"self",
".",
"repeat_times",
"=",
"repeat_times",
"self",
".",
"mod_output_param",
"=",
"mod_output_param",
"if",
"input_data",
"is",
"None",
":",
"self",
".",
"input",
",",
"self",
".",
"expect",
"=",
"gen_data",
"(",
"op_type",
",",
"op_desc",
")",
"if",
"isinstance",
"(",
"self",
".",
"input",
",",
"dict",
")",
":",
"self",
".",
"input",
",",
"self",
".",
"mod_output_param",
"=",
"self",
".",
"input",
"[",
"'args'",
"]",
",",
"self",
".",
"input",
"[",
"'outputs'",
"]",
"else",
":",
"self",
".",
"input",
",",
"self",
".",
"expect",
"=",
"input_data",
",",
"expect",
"self",
".",
"input_shape",
"=",
"[",
"x",
".",
"shape",
"for",
"x",
"in",
"self",
".",
"input",
"]",
"def",
"info",
"(",
"self",
")",
":",
"print",
"(",
"'run kernel time:'",
",",
"self",
".",
"run_kernel_time",
")",
"def",
"run_one_kernel",
"(",
"self",
",",
"run_times",
",",
"idx",
",",
"config",
",",
"best_time",
"=",
"np",
".",
"inf",
",",
"is_auto",
"=",
"False",
")",
":",
"\"\"\"Compile and execute a config of the operator on device\"\"\"",
"time_one_kernel_start",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"'compile %dth kernel'",
",",
"idx",
")",
"if",
"utils",
".",
"get_available_devices_num",
"(",
")",
"==",
"1",
":",
"device_id",
"=",
"utils",
".",
"get_device_id",
"(",
")",
"else",
":",
"device_id",
"=",
"idx",
"+",
"utils",
".",
"get_device_id",
"(",
")",
"os",
".",
"environ",
"[",
"'DEVICE_ID'",
"]",
"=",
"str",
"(",
"device_id",
")",
"logger",
".",
"debug",
"(",
"'run %dth kernel'",
",",
"idx",
")",
"logger",
".",
"debug",
"(",
"'++++++++++++++++++++++=device_id'",
")",
"logger",
".",
"debug",
"(",
"device_id",
")",
"logger",
".",
"debug",
"(",
"'++++++++++++++++++++++=device_id'",
")",
"try",
":",
"time_start_build",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"config",
")",
"if",
"self",
".",
"op_type",
"in",
"[",
"\"json\"",
",",
"\"extra_tune\"",
"]",
":",
"if",
"is_auto",
":",
"attrs",
"=",
"{",
"}",
"attrs",
"[",
"\"kernel_name\"",
"]",
"=",
"\"tuning_json_\"",
"+",
"str",
"(",
"idx",
")",
"mod",
"=",
"composite",
".",
"build",
"(",
"self",
".",
"op_desc",
",",
"attrs",
")",
"if",
"self",
".",
"op_type",
"==",
"\"extra_tune\"",
":",
"del",
"os",
".",
"environ",
"[",
"'MS_GRAPH_KERNEL_TILING'",
"]",
"else",
":",
"attrs",
"=",
"get_attr_from_config",
"(",
"config",
".",
"input",
",",
"self",
".",
"_index_table",
")",
"attrs",
"[",
"\"kernel_name\"",
"]",
"=",
"\"tuning_json_\"",
"+",
"str",
"(",
"idx",
")",
"if",
"os",
".",
"environ",
"[",
"'RUNTIME_MODE'",
"]",
"==",
"\"gpu\"",
":",
"attrs",
"[",
"'target'",
"]",
"=",
"\"cuda\"",
"mod",
"=",
"composite",
".",
"build",
"(",
"self",
".",
"op_desc",
",",
"attrs",
",",
"use_repo",
"=",
"False",
")",
"elif",
"self",
".",
"op_type",
"==",
"\"matmul_json\"",
":",
"attrs",
"=",
"get_matmul_cube_attrs",
"(",
"self",
".",
"op_desc",
",",
"config",
".",
"input",
")",
"print",
"(",
"attrs",
")",
"mod",
"=",
"composite",
".",
"build",
"(",
"self",
".",
"json_desc",
",",
"attrs",
",",
"use_repo",
"=",
"False",
")",
"else",
":",
"mod",
"=",
"compile_kernel",
"(",
"self",
".",
"op_type",
",",
"self",
".",
"op_desc",
",",
"self",
".",
"input_shape",
",",
"self",
".",
"_index_table",
",",
"None",
"if",
"is_auto",
"else",
"config",
".",
"input",
",",
"idx",
")",
"time_end_build",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"build module time: %f\"",
",",
"time_end_build",
"-",
"time_start_build",
")",
"logger",
".",
"debug",
"(",
"'finished compile %dth kernel'",
",",
"idx",
")",
"except",
"BaseException",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"Compile Failed: [%s] : %s\"",
",",
"\"origin\"",
"if",
"is_auto",
"else",
"str",
"(",
"config",
".",
"input",
")",
",",
"str",
"(",
"e",
")",
")",
"run_times",
"[",
"idx",
"]",
"=",
"compile_fail_time",
"return",
"run_times",
"[",
"idx",
"]",
"=",
"run_failed_time",
"try",
":",
"for",
"_",
"in",
"range",
"(",
"self",
".",
"repeat_times",
")",
":",
"stat_info",
"=",
"{",
"}",
"try",
":",
"time_start_launch",
"=",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"mod_output_param",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"mod_output_param",
")",
">",
"1",
":",
"output",
",",
"stat_info",
"=",
"utils",
".",
"mod_launch",
"(",
"mod",
",",
"list",
"(",
"self",
".",
"input",
")",
",",
"self",
".",
"mod_output_param",
",",
"tuning",
"=",
"True",
",",
"device_id",
"=",
"device_id",
")",
"if",
"stat_info",
"[",
"'run_time'",
"]",
"<",
"best_time",
":",
"if",
"not",
"all",
"(",
"map",
"(",
"lambda",
"x",
",",
"y",
":",
"np",
".",
"allclose",
"(",
"x",
",",
"y",
",",
"rtol",
"=",
"5e-03",
",",
"atol",
"=",
"5e-03",
",",
"equal_nan",
"=",
"True",
")",
",",
"output",
",",
"self",
".",
"expect",
")",
")",
":",
"stat_info",
"[",
"'run_time'",
"]",
"=",
"precision_error_time",
"logger",
".",
"warning",
"(",
"\"Precision Error: [%s]\"",
",",
"\"origin\"",
"if",
"config",
"is",
"None",
"else",
"str",
"(",
"config",
".",
"input",
")",
")",
"else",
":",
"if",
"self",
".",
"op_type",
"in",
"[",
"\"json\"",
",",
"\"extra_tune\"",
",",
"\"matmul_json\"",
"]",
":",
"output",
",",
"stat_info",
"=",
"utils",
".",
"mod_launch",
"(",
"mod",
",",
"self",
".",
"input",
",",
"self",
".",
"mod_output_param",
",",
"tuning",
"=",
"True",
",",
"device_id",
"=",
"device_id",
")",
"else",
":",
"output",
",",
"stat_info",
"=",
"utils",
".",
"mod_launch",
"(",
"mod",
",",
"self",
".",
"input",
",",
"tuning",
"=",
"True",
",",
"device_id",
"=",
"device_id",
")",
"if",
"stat_info",
"[",
"'run_time'",
"]",
"<",
"best_time",
":",
"if",
"not",
"np",
".",
"allclose",
"(",
"output",
",",
"self",
".",
"expect",
",",
"rtol",
"=",
"5e-03",
",",
"atol",
"=",
"5e-03",
",",
"equal_nan",
"=",
"True",
")",
":",
"stat_info",
"[",
"'run_time'",
"]",
"=",
"precision_error_time",
"logger",
".",
"warning",
"(",
"\"Precision Error: [%s]\"",
",",
"\"origin\"",
"if",
"config",
"is",
"None",
"else",
"str",
"(",
"config",
".",
"input",
")",
")",
"time_end_launch",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"mod launch time: %f\"",
",",
"time_end_launch",
"-",
"time_start_launch",
")",
"except",
"BaseException",
"as",
"e",
":",
"logger",
".",
"warning",
"(",
"\"Run Failed: [%s] : %s\"",
",",
"str",
"(",
"config",
".",
"input",
")",
",",
"str",
"(",
"e",
")",
")",
"stat_info",
"[",
"'run_time'",
"]",
"=",
"run_failed_time",
"run_times",
"[",
"idx",
"]",
"=",
"np",
".",
"minimum",
"(",
"run_times",
"[",
"idx",
"]",
",",
"stat_info",
"[",
"'run_time'",
"]",
")",
"finally",
":",
"logger",
".",
"debug",
"(",
"'end of %dth kernel'",
",",
"idx",
")",
"time_one_kernel_end",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"'run one kernel time: %f'",
",",
"time_one_kernel_end",
"-",
"time_one_kernel_start",
")",
"return",
"def",
"run",
"(",
"self",
",",
"configs",
",",
"best_time",
"=",
"np",
".",
"inf",
",",
"is_auto_set_dim",
"=",
"False",
",",
"all_space",
"=",
"False",
")",
":",
"\"\"\"Compile and execute a batch config of the operator on device\"\"\"",
"start",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"gen cce kernels batch: %d kernels\"",
",",
"len",
"(",
"configs",
")",
")",
"subprocess",
".",
"run",
"(",
"\"rm -rf ./jobs/JOB*\"",
",",
"shell",
"=",
"True",
")",
"process_jobs",
"=",
"[",
"]",
"run_times",
"=",
"multiprocessing",
".",
"Manager",
"(",
")",
".",
"list",
"(",
"np",
".",
"full",
"(",
"(",
"len",
"(",
"configs",
")",
",",
")",
",",
"compile_fail_time",
")",
")",
"for",
"idx",
",",
"config",
"in",
"enumerate",
"(",
"configs",
")",
":",
"p",
"=",
"multiprocessing",
".",
"Process",
"(",
"target",
"=",
"self",
".",
"run_one_kernel",
",",
"args",
"=",
"(",
"run_times",
",",
"idx",
",",
"config",
",",
"best_time",
",",
"is_auto_set_dim",
")",
")",
"process_jobs",
".",
"append",
"(",
"p",
")",
"p",
".",
"start",
"(",
")",
"timeout_error",
"=",
"False",
"for",
"idx",
",",
"p",
"in",
"enumerate",
"(",
"process_jobs",
")",
":",
"if",
"not",
"timeout_error",
":",
"p",
".",
"join",
"(",
"timeout",
"=",
"self",
".",
"timeout",
")",
"if",
"p",
".",
"is_alive",
"(",
")",
":",
"timeout_error",
"=",
"True",
"logger",
".",
"debug",
"(",
"\"Timeout Error: [%s]\"",
",",
"str",
"(",
"configs",
"[",
"idx",
"]",
".",
"input",
")",
")",
"run_times",
"[",
"idx",
"]",
"=",
"timeout_time",
"p",
".",
"terminate",
"(",
")",
"process_end",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"process time: %f\"",
",",
"process_end",
"-",
"start",
")",
"tune_device",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'DEVICE_ID'",
"]",
")",
"tune_num",
"=",
"int",
"(",
"os",
".",
"environ",
"[",
"'DEVICE_TOTAL_NUM'",
"]",
")",
"if",
"os",
".",
"environ",
"[",
"'RUNTIME_MODE'",
"]",
"==",
"\"gpu\"",
":",
"subprocess",
".",
"run",
"(",
"\"rm -rf cuda_meta*\"",
",",
"shell",
"=",
"True",
")",
"else",
":",
"profiling_dir",
"=",
"str",
"(",
"os",
".",
"environ",
"[",
"'PROFILING_DIR'",
"]",
")",
"if",
"len",
"(",
"profiling_dir",
")",
"==",
"0",
"or",
"profiling_dir",
".",
"isspace",
"(",
")",
":",
"logger",
".",
"error",
"(",
"\"The value about PROFILING_DIR shoud be setted correctly.\"",
")",
"subprocess",
".",
"run",
"(",
"\"rm -rf %s/JOB*\"",
"%",
"profiling_dir",
",",
"shell",
"=",
"True",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"logger",
".",
"debug",
"(",
"\"run kernels time: %f\"",
",",
"end",
"-",
"start",
")",
"self",
".",
"run_kernel_time",
"+=",
"end",
"-",
"start",
"for",
"idx",
",",
"config",
"in",
"enumerate",
"(",
"configs",
")",
":",
"if",
"run_times",
"[",
"idx",
"]",
"not",
"in",
"error_time_list",
":",
"logger",
".",
"debug",
"(",
"\"KernelRunTime : [%s] : %s\"",
",",
"str",
"(",
"configs",
"[",
"idx",
"]",
".",
"input",
")",
",",
"str",
"(",
"run_times",
"[",
"idx",
"]",
")",
")",
"else",
":",
"logger",
".",
"debug",
"(",
"\"KernelRunTime : [%s] : %s\"",
",",
"str",
"(",
"configs",
"[",
"idx",
"]",
".",
"input",
")",
",",
"str",
"(",
"error_time_string",
"[",
"run_times",
"[",
"idx",
"]",
"]",
")",
")",
"return",
"run_times"
] |
kernel runner
This runner will compile and execute configs of an operator, and return their running times.
|
[
"kernel",
"runner",
"This",
"runner",
"will",
"compile",
"and",
"execute",
"configs",
"of",
"an",
"operator",
"and",
"return",
"their",
"running",
"times",
"."
] |
[
"\"\"\"kernel runner\n This runner will compile and execute configs of an operator, and return their running times.\n\n Parameters\n ----------\n op_type: str\n The name of operator\n op_desc: NamedTuple\n The definition parameters of operator\n timeout: int\n Timeout for running one config\n repeat_times:\n Run one config repeat_times\n \"\"\"",
"\"\"\"Compile and execute a config of the operator on device\"\"\"",
"# get available device",
"\"\"\"Compile and execute a batch config of the operator on device\"\"\"",
"# clean the profiling directory"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 25
| 1,736
| 76
|
293ca689c6f4a1e735059569e5dccf927d173e7f
|
OpenKGC/hypergraphdb
|
apps/prolog/src/java/alice/tuprologx/ide/ThinletTheoryEditor.java
|
[
"Apache-2.0"
] |
Java
|
ThinletTheoryEditor
|
/**
* A set of commands and facilities for components implementing an edit area.
* Bundled with an appropriate edit area, it forms the tuProlog editor in the
* current <code>tuprologx.ide</code> package.
*
* @author <a href="mailto:[email protected]">Giulio Piancastelli</a>
* @version 1.0 - Friday 20th December, 2002
*/
|
A set of commands and facilities for components implementing an edit area.
Bundled with an appropriate edit area, it forms the tuProlog editor in the
current tuprologx.ide package.
@author Giulio Piancastelli
@version 1.0 - Friday 20th December, 2002
|
[
"A",
"set",
"of",
"commands",
"and",
"facilities",
"for",
"components",
"implementing",
"an",
"edit",
"area",
".",
"Bundled",
"with",
"an",
"appropriate",
"edit",
"area",
"it",
"forms",
"the",
"tuProlog",
"editor",
"in",
"the",
"current",
"tuprologx",
".",
"ide",
"package",
".",
"@author",
"Giulio",
"Piancastelli",
"@version",
"1",
".",
"0",
"-",
"Friday",
"20th",
"December",
"2002"
] |
public class ThinletTheoryEditor extends Thinlet implements PropertyChangeListener {
/** The Prolog engine referenced by the editor. */
private Prolog engine;
/** The edit area used by the editor. */
private TheoryEditArea editArea;
/** A message describing the status of the console. */
private String statusMessage;
/** Used for components interested in changes of console's properties. */
private PropertyChangeSupport propertyChangeSupport;
public ThinletTheoryEditor() {
try {
add(parse("xml/ThinletTheoryEditor.xml"));
} catch (Exception e) {
e.printStackTrace();
}
propertyChangeSupport = new PropertyChangeSupport(this);
}
/**
* Get the Prolog engine referenced by the editor.
*
* @return The Prolog engine referenced by the editor.
*/
public Prolog getEngine() {
return engine;
}
/**
* Set the Prolog engine referenced by the editor.
*
* @param engine an <code>alice.tuprolog.Prolog</code> engine.
*/
public void setEngine(Prolog engine) {
this.engine = engine;
}
/**
* Set the editor status.
*
* @param message The message describing the new status of the editor.
*/
public void setStatusMessage(String message) {
String oldStatusMessage = getStatusMessage();
statusMessage = message;
propertyChangeSupport.firePropertyChange("StatusMessage", oldStatusMessage, statusMessage);
}
/**
* Get the editor status as a <code>java.lang.String</code> message.
*
* @return the current status of the editor as a <code>java.lang.String</code>
* message.
*/
public String getStatusMessage() {
return statusMessage;
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
/**
* Set the edit area used by the editor to manipulate the text of
* Prolog theories.
*
* @param editArea The edit area we want the editor to use.
*/
public void setEditArea(TheoryEditArea editArea) {
this.editArea = editArea;
}
/**
* Set the theory of the tuProlog engine referenced by the editor to the
* theory currently contained in the edit area.
*/
public void setEngineTheory() {
// insert a check on feededTheory? -> if true does not feed anything.
String theory = editArea.getTheory();
try {
getEngine().setTheory(new Theory(theory));
editArea.setDirty(false);
setStatusMessage("New theory accepted.");
} catch (InvalidTheoryException ite) {
setStatusMessage("Error setting theory: Syntax Error at/before line " + ite.line);
}
}
/**
* Get the theory currently contained in the tuProlog engine referenced by
* the editor and display it in the edit area.
*/
public void getEngineTheory() {
String theory = getEngine().getTheory().toString();
editArea.setTheory(theory);
setStatusMessage("Engine theory displayed.");
}
/**
* Undo last action in the Edit Area.
*/
public void undo() {
editArea.undoAction();
}
/**
* Redo last action in the Edit Area.
*/
public void redo() {
editArea.redoAction();
}
public void propertyChange(PropertyChangeEvent event) {
String propertyName = event.getPropertyName();
if (propertyName.equals("caretLine"))
setCaretLine(event.getNewValue().toString());
}
/**
* Display the line number where the caret in the edit area is.
*
* @param caretLine The line number to be displayed.
*/
private void setCaretLine(String caretLine) {
Object lineField = find("lineField");
setString(lineField, "text", caretLine);
}
/**
* Enable or disable theory-related buttons.
*
* @param flag true if the buttons have to be enabled, false otherwise.
*/
protected void enableTheoryCommands(boolean flag) {
Object setTheoryButton = find("setTheoryButton");
setBoolean(setTheoryButton, "enabled", flag);
}
}
|
[
"public",
"class",
"ThinletTheoryEditor",
"extends",
"Thinlet",
"implements",
"PropertyChangeListener",
"{",
"/** The Prolog engine referenced by the editor. */",
"private",
"Prolog",
"engine",
";",
"/** The edit area used by the editor. */",
"private",
"TheoryEditArea",
"editArea",
";",
"/** A message describing the status of the console. */",
"private",
"String",
"statusMessage",
";",
"/** Used for components interested in changes of console's properties. */",
"private",
"PropertyChangeSupport",
"propertyChangeSupport",
";",
"public",
"ThinletTheoryEditor",
"(",
")",
"{",
"try",
"{",
"add",
"(",
"parse",
"(",
"\"",
"xml/ThinletTheoryEditor.xml",
"\"",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"propertyChangeSupport",
"=",
"new",
"PropertyChangeSupport",
"(",
"this",
")",
";",
"}",
"/**\r\n * Get the Prolog engine referenced by the editor.\r\n *\r\n * @return The Prolog engine referenced by the editor.\r\n */",
"public",
"Prolog",
"getEngine",
"(",
")",
"{",
"return",
"engine",
";",
"}",
"/**\r\n * Set the Prolog engine referenced by the editor.\r\n *\r\n * @param engine an <code>alice.tuprolog.Prolog</code> engine.\r\n */",
"public",
"void",
"setEngine",
"(",
"Prolog",
"engine",
")",
"{",
"this",
".",
"engine",
"=",
"engine",
";",
"}",
"/**\r\n * Set the editor status.\r\n *\r\n * @param message The message describing the new status of the editor.\r\n */",
"public",
"void",
"setStatusMessage",
"(",
"String",
"message",
")",
"{",
"String",
"oldStatusMessage",
"=",
"getStatusMessage",
"(",
")",
";",
"statusMessage",
"=",
"message",
";",
"propertyChangeSupport",
".",
"firePropertyChange",
"(",
"\"",
"StatusMessage",
"\"",
",",
"oldStatusMessage",
",",
"statusMessage",
")",
";",
"}",
"/**\r\n * Get the editor status as a <code>java.lang.String</code> message.\r\n *\r\n * @return the current status of the editor as a <code>java.lang.String</code>\r\n * message.\r\n */",
"public",
"String",
"getStatusMessage",
"(",
")",
"{",
"return",
"statusMessage",
";",
"}",
"public",
"void",
"addPropertyChangeListener",
"(",
"PropertyChangeListener",
"listener",
")",
"{",
"propertyChangeSupport",
".",
"addPropertyChangeListener",
"(",
"listener",
")",
";",
"}",
"public",
"void",
"removePropertyChangeListener",
"(",
"PropertyChangeListener",
"listener",
")",
"{",
"propertyChangeSupport",
".",
"removePropertyChangeListener",
"(",
"listener",
")",
";",
"}",
"/**\r\n * Set the edit area used by the editor to manipulate the text of\r\n * Prolog theories.\r\n *\r\n * @param editArea The edit area we want the editor to use.\r\n */",
"public",
"void",
"setEditArea",
"(",
"TheoryEditArea",
"editArea",
")",
"{",
"this",
".",
"editArea",
"=",
"editArea",
";",
"}",
"/**\r\n * Set the theory of the tuProlog engine referenced by the editor to the\r\n * theory currently contained in the edit area.\r\n */",
"public",
"void",
"setEngineTheory",
"(",
")",
"{",
"String",
"theory",
"=",
"editArea",
".",
"getTheory",
"(",
")",
";",
"try",
"{",
"getEngine",
"(",
")",
".",
"setTheory",
"(",
"new",
"Theory",
"(",
"theory",
")",
")",
";",
"editArea",
".",
"setDirty",
"(",
"false",
")",
";",
"setStatusMessage",
"(",
"\"",
"New theory accepted.",
"\"",
")",
";",
"}",
"catch",
"(",
"InvalidTheoryException",
"ite",
")",
"{",
"setStatusMessage",
"(",
"\"",
"Error setting theory: Syntax Error at/before line ",
"\"",
"+",
"ite",
".",
"line",
")",
";",
"}",
"}",
"/**\r\n\t * Get the theory currently contained in the tuProlog engine referenced by\r\n\t * the editor and display it in the edit area.\r\n\t */",
"public",
"void",
"getEngineTheory",
"(",
")",
"{",
"String",
"theory",
"=",
"getEngine",
"(",
")",
".",
"getTheory",
"(",
")",
".",
"toString",
"(",
")",
";",
"editArea",
".",
"setTheory",
"(",
"theory",
")",
";",
"setStatusMessage",
"(",
"\"",
"Engine theory displayed.",
"\"",
")",
";",
"}",
"/**\r\n * Undo last action in the Edit Area.\r\n */",
"public",
"void",
"undo",
"(",
")",
"{",
"editArea",
".",
"undoAction",
"(",
")",
";",
"}",
"/**\r\n * Redo last action in the Edit Area.\r\n */",
"public",
"void",
"redo",
"(",
")",
"{",
"editArea",
".",
"redoAction",
"(",
")",
";",
"}",
"public",
"void",
"propertyChange",
"(",
"PropertyChangeEvent",
"event",
")",
"{",
"String",
"propertyName",
"=",
"event",
".",
"getPropertyName",
"(",
")",
";",
"if",
"(",
"propertyName",
".",
"equals",
"(",
"\"",
"caretLine",
"\"",
")",
")",
"setCaretLine",
"(",
"event",
".",
"getNewValue",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"/**\r\n * Display the line number where the caret in the edit area is.\r\n *\r\n * @param caretLine The line number to be displayed.\r\n */",
"private",
"void",
"setCaretLine",
"(",
"String",
"caretLine",
")",
"{",
"Object",
"lineField",
"=",
"find",
"(",
"\"",
"lineField",
"\"",
")",
";",
"setString",
"(",
"lineField",
",",
"\"",
"text",
"\"",
",",
"caretLine",
")",
";",
"}",
"/**\r\n * Enable or disable theory-related buttons.\r\n *\r\n * @param flag true if the buttons have to be enabled, false otherwise.\r\n */",
"protected",
"void",
"enableTheoryCommands",
"(",
"boolean",
"flag",
")",
"{",
"Object",
"setTheoryButton",
"=",
"find",
"(",
"\"",
"setTheoryButton",
"\"",
")",
";",
"setBoolean",
"(",
"setTheoryButton",
",",
"\"",
"enabled",
"\"",
",",
"flag",
")",
";",
"}",
"}"
] |
A set of commands and facilities for components implementing an edit area.
|
[
"A",
"set",
"of",
"commands",
"and",
"facilities",
"for",
"components",
"implementing",
"an",
"edit",
"area",
"."
] |
[
"// insert a check on feededTheory? -> if true does not feed anything.\r"
] |
[
{
"param": "Thinlet",
"type": null
},
{
"param": "PropertyChangeListener",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Thinlet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "PropertyChangeListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 930
| 104
|
5e1e9739e9c00e1fd126afad0905cc1917c55a9f
|
WiseEagleOwl/LGoodDatePicker
|
Project/src/main/java/com/github/lgooddatepicker/zinternaltools/TimeSpinnerTimer.java
|
[
"MIT"
] |
Java
|
TimeSpinnerTimer
|
/**
* TimeSpinnerTimer, This class implements a timer which can fire an increment event at a rate that
* accelerates over a set period of time. This is used by the time picker component. The increment
* event is used to change the time and the time picker while the user is holding a spinner
* activation key. (The spinner functionality may be activated with the keyboard or the mouse.)
*/
|
TimeSpinnerTimer, This class implements a timer which can fire an increment event at a rate that
accelerates over a set period of time. This is used by the time picker component. The increment
event is used to change the time and the time picker while the user is holding a spinner
activation key. (The spinner functionality may be activated with the keyboard or the mouse.)
|
[
"TimeSpinnerTimer",
"This",
"class",
"implements",
"a",
"timer",
"which",
"can",
"fire",
"an",
"increment",
"event",
"at",
"a",
"rate",
"that",
"accelerates",
"over",
"a",
"set",
"period",
"of",
"time",
".",
"This",
"is",
"used",
"by",
"the",
"time",
"picker",
"component",
".",
"The",
"increment",
"event",
"is",
"used",
"to",
"change",
"the",
"time",
"and",
"the",
"time",
"picker",
"while",
"the",
"user",
"is",
"holding",
"a",
"spinner",
"activation",
"key",
".",
"(",
"The",
"spinner",
"functionality",
"may",
"be",
"activated",
"with",
"the",
"keyboard",
"or",
"the",
"mouse",
".",
")"
] |
public class TimeSpinnerTimer {
/** timePicker, This holds the time picker that is associated with this class. */
private final TimePicker timePicker;
/**
* timePicker, This holds the number of minutes that should be added or subtracted with each
* increment of the time picker value. This will typically be -1 or 1.
*/
private final int changeAmountMinutes;
/** timer, This holds the timer associated with this class. */
private final Timer timer;
/**
* startDelayMillis, This indicates how long the timer should wait before firing its first tick.
* This value is used to make sure that the user can easily increase or decrease the date picker
* value by only 1 minute.
*/
private final int startDelayMillis = 700;
/**
* timerRate, This indicates how often the timer should call the tick function, in milliseconds.
*/
private final int timerRate = 20;
/**
* millisForDivisorList, This indicates how long each value in the divisorList should be used,
* before moving onto the next value in the divisorList.
*/
private final int[] millisForDivisorList = new int[] {1800, 900, 400, 400, 400, 400, 400, 0};
/**
* divisorList, For as long as any particular index in this array remains in effect, the currently
* used number indicates how many tick calls should pass before the time picker value should be
* changed. For example, the number 3 indicates that the time picker value should be changed only
* once for every 3 calls to the tick function. Higher numbers make the spinner change slower,
* lower numbers make the spinner change faster.
*/
private final int[] divisorList = new int[] {12, 10, 8, 6, 4, 3, 2, 1};
/**
* startedIndexTimeStamp, This indicates the time that the currently used index in the divisorList
* started to be used.
*/
private long startedIndexTimeStamp = 0;
/**
* currentIndex, This indicates the index that is currently in effect for the divisorList and the
* millisForIndexList.
*/
private int currentIndex = 0;
/**
* ticksSinceIndexChange, This keeps track of the number of ticks that has passed since the last
* time that the current index was changed. This helps us calculate when we need to change the
* index to the next value.
*/
private int ticksSinceIndexChange;
/** Constructor. */
public TimeSpinnerTimer(TimePicker timePicker, int changeAmountMinutes) {
this.timePicker = timePicker;
this.changeAmountMinutes = changeAmountMinutes;
timer = new Timer(timerRate, event -> tick());
timer.setInitialDelay(startDelayMillis);
}
/**
* tick, This is called once each time that the timer fires. (Every 20 milliseconds).
*
* <p>However, the value in the time picker will only be changed once for every certain number of
* calls to the tick() function. The number of calls which is required is controlled by the
* "divisorList" array values.
*
* <p>The amount of time that is spent using each divisorList array value is controlled by the
* "millisForIndexList".
*/
private void tick() {
if (startedIndexTimeStamp == 0) {
startedIndexTimeStamp = System.currentTimeMillis();
}
long timeElapsedSinceIndexStartMilliseconds =
System.currentTimeMillis() - startedIndexTimeStamp;
int maximumIndex = divisorList.length - 1;
int currentDivisor = divisorList[currentIndex];
if (ticksSinceIndexChange % currentDivisor == 0) {
timePicker.zInternalTryChangeTimeByIncrement(changeAmountMinutes);
// System.out.println("\nMillis: " + System.currentTimeMillis());
// System.out.println("Divisor: " + divisor);
// System.out.println("Value: " + timePicker.getTime());
if ((currentIndex < maximumIndex)
&& (timeElapsedSinceIndexStartMilliseconds > millisForDivisorList[currentIndex])) {
ticksSinceIndexChange = 0;
++currentIndex;
startedIndexTimeStamp = System.currentTimeMillis();
}
}
++ticksSinceIndexChange;
}
/** stop, This is called to stop the timer. */
public void stop() {
timer.stop();
}
/** start, This is called to start the timer, and to initialize the needed variables. */
public void start() {
startedIndexTimeStamp = 0;
currentIndex = 0;
ticksSinceIndexChange = 0;
timer.start();
}
}
|
[
"public",
"class",
"TimeSpinnerTimer",
"{",
"/** timePicker, This holds the time picker that is associated with this class. */",
"private",
"final",
"TimePicker",
"timePicker",
";",
"/**\n * timePicker, This holds the number of minutes that should be added or subtracted with each\n * increment of the time picker value. This will typically be -1 or 1.\n */",
"private",
"final",
"int",
"changeAmountMinutes",
";",
"/** timer, This holds the timer associated with this class. */",
"private",
"final",
"Timer",
"timer",
";",
"/**\n * startDelayMillis, This indicates how long the timer should wait before firing its first tick.\n * This value is used to make sure that the user can easily increase or decrease the date picker\n * value by only 1 minute.\n */",
"private",
"final",
"int",
"startDelayMillis",
"=",
"700",
";",
"/**\n * timerRate, This indicates how often the timer should call the tick function, in milliseconds.\n */",
"private",
"final",
"int",
"timerRate",
"=",
"20",
";",
"/**\n * millisForDivisorList, This indicates how long each value in the divisorList should be used,\n * before moving onto the next value in the divisorList.\n */",
"private",
"final",
"int",
"[",
"]",
"millisForDivisorList",
"=",
"new",
"int",
"[",
"]",
"{",
"1800",
",",
"900",
",",
"400",
",",
"400",
",",
"400",
",",
"400",
",",
"400",
",",
"0",
"}",
";",
"/**\n * divisorList, For as long as any particular index in this array remains in effect, the currently\n * used number indicates how many tick calls should pass before the time picker value should be\n * changed. For example, the number 3 indicates that the time picker value should be changed only\n * once for every 3 calls to the tick function. Higher numbers make the spinner change slower,\n * lower numbers make the spinner change faster.\n */",
"private",
"final",
"int",
"[",
"]",
"divisorList",
"=",
"new",
"int",
"[",
"]",
"{",
"12",
",",
"10",
",",
"8",
",",
"6",
",",
"4",
",",
"3",
",",
"2",
",",
"1",
"}",
";",
"/**\n * startedIndexTimeStamp, This indicates the time that the currently used index in the divisorList\n * started to be used.\n */",
"private",
"long",
"startedIndexTimeStamp",
"=",
"0",
";",
"/**\n * currentIndex, This indicates the index that is currently in effect for the divisorList and the\n * millisForIndexList.\n */",
"private",
"int",
"currentIndex",
"=",
"0",
";",
"/**\n * ticksSinceIndexChange, This keeps track of the number of ticks that has passed since the last\n * time that the current index was changed. This helps us calculate when we need to change the\n * index to the next value.\n */",
"private",
"int",
"ticksSinceIndexChange",
";",
"/** Constructor. */",
"public",
"TimeSpinnerTimer",
"(",
"TimePicker",
"timePicker",
",",
"int",
"changeAmountMinutes",
")",
"{",
"this",
".",
"timePicker",
"=",
"timePicker",
";",
"this",
".",
"changeAmountMinutes",
"=",
"changeAmountMinutes",
";",
"timer",
"=",
"new",
"Timer",
"(",
"timerRate",
",",
"event",
"->",
"tick",
"(",
")",
")",
";",
"timer",
".",
"setInitialDelay",
"(",
"startDelayMillis",
")",
";",
"}",
"/**\n * tick, This is called once each time that the timer fires. (Every 20 milliseconds).\n *\n * <p>However, the value in the time picker will only be changed once for every certain number of\n * calls to the tick() function. The number of calls which is required is controlled by the\n * \"divisorList\" array values.\n *\n * <p>The amount of time that is spent using each divisorList array value is controlled by the\n * \"millisForIndexList\".\n */",
"private",
"void",
"tick",
"(",
")",
"{",
"if",
"(",
"startedIndexTimeStamp",
"==",
"0",
")",
"{",
"startedIndexTimeStamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"}",
"long",
"timeElapsedSinceIndexStartMilliseconds",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
"-",
"startedIndexTimeStamp",
";",
"int",
"maximumIndex",
"=",
"divisorList",
".",
"length",
"-",
"1",
";",
"int",
"currentDivisor",
"=",
"divisorList",
"[",
"currentIndex",
"]",
";",
"if",
"(",
"ticksSinceIndexChange",
"%",
"currentDivisor",
"==",
"0",
")",
"{",
"timePicker",
".",
"zInternalTryChangeTimeByIncrement",
"(",
"changeAmountMinutes",
")",
";",
"if",
"(",
"(",
"currentIndex",
"<",
"maximumIndex",
")",
"&&",
"(",
"timeElapsedSinceIndexStartMilliseconds",
">",
"millisForDivisorList",
"[",
"currentIndex",
"]",
")",
")",
"{",
"ticksSinceIndexChange",
"=",
"0",
";",
"++",
"currentIndex",
";",
"startedIndexTimeStamp",
"=",
"System",
".",
"currentTimeMillis",
"(",
")",
";",
"}",
"}",
"++",
"ticksSinceIndexChange",
";",
"}",
"/** stop, This is called to stop the timer. */",
"public",
"void",
"stop",
"(",
")",
"{",
"timer",
".",
"stop",
"(",
")",
";",
"}",
"/** start, This is called to start the timer, and to initialize the needed variables. */",
"public",
"void",
"start",
"(",
")",
"{",
"startedIndexTimeStamp",
"=",
"0",
";",
"currentIndex",
"=",
"0",
";",
"ticksSinceIndexChange",
"=",
"0",
";",
"timer",
".",
"start",
"(",
")",
";",
"}",
"}"
] |
TimeSpinnerTimer, This class implements a timer which can fire an increment event at a rate that
accelerates over a set period of time.
|
[
"TimeSpinnerTimer",
"This",
"class",
"implements",
"a",
"timer",
"which",
"can",
"fire",
"an",
"increment",
"event",
"at",
"a",
"rate",
"that",
"accelerates",
"over",
"a",
"set",
"period",
"of",
"time",
"."
] |
[
"// System.out.println(\"\\nMillis: \" + System.currentTimeMillis());",
"// System.out.println(\"Divisor: \" + divisor);",
"// System.out.println(\"Value: \" + timePicker.getTime());"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,035
| 83
|
5d9ab7bc8dc28a1ebbda6bc1c25f73c0137b6479
|
alinajabeen/MicroServicesRepo
|
src/Services/Ordering/Ordering.Application/Behaviours/ValidationBehaviour.cs
|
[
"MIT"
] |
C#
|
ValidationBehaviour
|
/// <summary>
/// This class runs all the validation classes if exist and collect the results, if there is any invalidate result then we are going to throw
/// custom validation exception. It is searching fluent validator object and abstract validator object and run all the validators before executing the request
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
|
This class runs all the validation classes if exist and collect the results, if there is any invalidate result then we are going to throw
custom validation exception. It is searching fluent validator object and abstract validator object and run all the validators before executing the request
|
[
"This",
"class",
"runs",
"all",
"the",
"validation",
"classes",
"if",
"exist",
"and",
"collect",
"the",
"results",
"if",
"there",
"is",
"any",
"invalidate",
"result",
"then",
"we",
"are",
"going",
"to",
"throw",
"custom",
"validation",
"exception",
".",
"It",
"is",
"searching",
"fluent",
"validator",
"object",
"and",
"abstract",
"validator",
"object",
"and",
"run",
"all",
"the",
"validators",
"before",
"executing",
"the",
"request"
] |
public class ValidationBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
{
private readonly IEnumerable<IValidator<IRequest>> _validators;
public ValidationBehaviour(IEnumerable<IValidator<IRequest>> validators)
{
_validators = validators ?? throw new ArgumentNullException(nameof(validators));
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
if (_validators.Any())
{
var context = new ValidationContext<TRequest>(request);
var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken)));
var failures = validationResults.SelectMany(r => r.Errors).Where(f => f != null).ToList();
if (failures.Count != 0)
throw new ValidationException(failures);
}
return await next();
}
}
|
[
"public",
"class",
"ValidationBehaviour",
"<",
"TRequest",
",",
"TResponse",
">",
":",
"IPipelineBehavior",
"<",
"TRequest",
",",
"TResponse",
">",
"{",
"private",
"readonly",
"IEnumerable",
"<",
"IValidator",
"<",
"IRequest",
">",
">",
"_validators",
";",
"public",
"ValidationBehaviour",
"(",
"IEnumerable",
"<",
"IValidator",
"<",
"IRequest",
">",
">",
"validators",
")",
"{",
"_validators",
"=",
"validators",
"??",
"throw",
"new",
"ArgumentNullException",
"(",
"nameof",
"(",
"validators",
")",
")",
";",
"}",
"public",
"async",
"Task",
"<",
"TResponse",
">",
"Handle",
"(",
"TRequest",
"request",
",",
"CancellationToken",
"cancellationToken",
",",
"RequestHandlerDelegate",
"<",
"TResponse",
">",
"next",
")",
"{",
"if",
"(",
"_validators",
".",
"Any",
"(",
")",
")",
"{",
"var",
"context",
"=",
"new",
"ValidationContext",
"<",
"TRequest",
">",
"(",
"request",
")",
";",
"var",
"validationResults",
"=",
"await",
"Task",
".",
"WhenAll",
"(",
"_validators",
".",
"Select",
"(",
"v",
"=>",
"v",
".",
"ValidateAsync",
"(",
"context",
",",
"cancellationToken",
")",
")",
")",
";",
"var",
"failures",
"=",
"validationResults",
".",
"SelectMany",
"(",
"r",
"=>",
"r",
".",
"Errors",
")",
".",
"Where",
"(",
"f",
"=>",
"f",
"!=",
"null",
")",
".",
"ToList",
"(",
")",
";",
"if",
"(",
"failures",
".",
"Count",
"!=",
"0",
")",
"throw",
"new",
"ValidationException",
"(",
"failures",
")",
";",
"}",
"return",
"await",
"next",
"(",
")",
";",
"}",
"}"
] |
This class runs all the validation classes if exist and collect the results, if there is any invalidate result then we are going to throw
custom validation exception.
|
[
"This",
"class",
"runs",
"all",
"the",
"validation",
"classes",
"if",
"exist",
"and",
"collect",
"the",
"results",
"if",
"there",
"is",
"any",
"invalidate",
"result",
"then",
"we",
"are",
"going",
"to",
"throw",
"custom",
"validation",
"exception",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "typeparam",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 21
| 181
| 81
|
6c473dd732fe7062bbbafaaf04ca536f61ecaffe
|
econmed/ImageServer20
|
ImageServer/Services/Dicom/StorageScp.cs
|
[
"Apache-2.0"
] |
C#
|
StorageScp
|
/// <summary>
/// Abstract class for handling Storage SCP connections.
/// </summary>
/// <remarks>
/// <para>This class is an abstract base class for ImageServer plugins that process DICOM C-STORE
/// request messages. The class implements a number of common methods needed for SCP handlers.
/// The class also implements the <see cref="IDicomScp{TContext}"/> interface.</para>
/// </remarks>
|
Abstract class for handling Storage SCP connections.
|
[
"Abstract",
"class",
"for",
"handling",
"Storage",
"SCP",
"connections",
"."
] |
public abstract class StorageScp : BaseScp
{
#region Abstract Properties
public abstract string StorageScpType { get; }
#endregion
#region Protected Members
protected static DicomFile ConvertToDicomFile(DicomMessage message, string filename, AssociationParameters assocParms)
{
DicomFile file = new DicomFile(message, filename);
file.SourceApplicationEntityTitle = assocParms.CallingAE;
if (message.TransferSyntax.Encapsulated)
file.TransferSyntax = message.TransferSyntax;
else
file.TransferSyntax = TransferSyntax.ExplicitVrLittleEndian;
return file;
}
protected static IList<PartitionTransferSyntax> LoadTransferSyntaxes(IReadContext read, ServerEntityKey partitionKey, bool encapsulated)
{
IList<PartitionTransferSyntax> list;
IQueryServerPartitionTransferSyntaxes broker = read.GetBroker<IQueryServerPartitionTransferSyntaxes>();
PartitionTransferSyntaxQueryParameters criteria = new PartitionTransferSyntaxQueryParameters();
criteria.ServerPartitionKey = partitionKey;
list = broker.Find(criteria);
List<PartitionTransferSyntax> returnList = new List<PartitionTransferSyntax>();
foreach (PartitionTransferSyntax syntax in list)
{
if (!syntax.Enabled) continue;
TransferSyntax dicomSyntax = TransferSyntax.GetTransferSyntax(syntax.Uid);
if (dicomSyntax.Encapsulated == encapsulated)
returnList.Add(syntax);
}
return returnList;
}
#endregion
#region Overridden BaseSCP methods
protected override DicomPresContextResult OnVerifyAssociation(AssociationParameters association, byte pcid)
{
if (Device == null)
return DicomPresContextResult.Accept;
if (!Device.AllowStorage)
{
return DicomPresContextResult.RejectUser;
}
if (Device.AcceptKOPR)
{
DicomPresContext context = association.GetPresentationContext(pcid);
if (context.AbstractSyntax.Equals(SopClass.KeyObjectSelectionDocumentStorage)
||context.AbstractSyntax.Equals(SopClass.GrayscaleSoftcopyPresentationStateStorageSopClass)
||context.AbstractSyntax.Equals(SopClass.BlendingSoftcopyPresentationStateStorageSopClass)
||context.AbstractSyntax.Equals(SopClass.ColorSoftcopyPresentationStateStorageSopClass)
||context.AbstractSyntax.Equals(SopClass.PseudoColorSoftcopyPresentationStateStorageSopClass))
return DicomPresContextResult.Accept;
return DicomPresContextResult.RejectUser;
}
return DicomPresContextResult.Accept;
}
#endregion Overridden BaseSCP methods
#region IDicomScp Members
public override bool OnReceiveRequest(DicomServer server, ServerAssociationParameters association, byte presentationID, DicomMessage message)
{
try
{
SopInstanceImporterContext context = new SopInstanceImporterContext(
String.Format("{0}_{1}", association.CallingAE, association.TimeStamp.ToString("yyyyMMddhhmmss")),
association.CallingAE, association.CalledAE);
SopInstanceImporter importer = new SopInstanceImporter(context);
DicomProcessingResult result = importer.Import(message);
if (result.Successful)
{
if (!String.IsNullOrEmpty(result.AccessionNumber))
Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
result.SopInstanceUid, association.CallingAE, association.CalledAE, result.AccessionNumber,
result.StudyInstanceUid);
else
Platform.Log(LogLevel.Info, "Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
result.SopInstanceUid, association.CallingAE, association.CalledAE,
result.StudyInstanceUid);
}
else
Platform.Log(LogLevel.Warn, "Failure importing sop: {0}", result.ErrorMessage);
server.SendCStoreResponse(presentationID, message.MessageId, message.AffectedSopInstanceUid, result.DicomStatus);
return true;
}
catch(DicomDataException ex)
{
Platform.Log(LogLevel.Error, ex);
return false;
}
catch(Exception ex)
{
Platform.Log(LogLevel.Error, ex);
return false;
}
}
#endregion
}
|
[
"public",
"abstract",
"class",
"StorageScp",
":",
"BaseScp",
"{",
"region",
" Abstract Properties",
"public",
"abstract",
"string",
"StorageScpType",
"{",
"get",
";",
"}",
"endregion",
"region",
" Protected Members",
"protected",
"static",
"DicomFile",
"ConvertToDicomFile",
"(",
"DicomMessage",
"message",
",",
"string",
"filename",
",",
"AssociationParameters",
"assocParms",
")",
"{",
"DicomFile",
"file",
"=",
"new",
"DicomFile",
"(",
"message",
",",
"filename",
")",
";",
"file",
".",
"SourceApplicationEntityTitle",
"=",
"assocParms",
".",
"CallingAE",
";",
"if",
"(",
"message",
".",
"TransferSyntax",
".",
"Encapsulated",
")",
"file",
".",
"TransferSyntax",
"=",
"message",
".",
"TransferSyntax",
";",
"else",
"file",
".",
"TransferSyntax",
"=",
"TransferSyntax",
".",
"ExplicitVrLittleEndian",
";",
"return",
"file",
";",
"}",
"protected",
"static",
"IList",
"<",
"PartitionTransferSyntax",
">",
"LoadTransferSyntaxes",
"(",
"IReadContext",
"read",
",",
"ServerEntityKey",
"partitionKey",
",",
"bool",
"encapsulated",
")",
"{",
"IList",
"<",
"PartitionTransferSyntax",
">",
"list",
";",
"IQueryServerPartitionTransferSyntaxes",
"broker",
"=",
"read",
".",
"GetBroker",
"<",
"IQueryServerPartitionTransferSyntaxes",
">",
"(",
")",
";",
"PartitionTransferSyntaxQueryParameters",
"criteria",
"=",
"new",
"PartitionTransferSyntaxQueryParameters",
"(",
")",
";",
"criteria",
".",
"ServerPartitionKey",
"=",
"partitionKey",
";",
"list",
"=",
"broker",
".",
"Find",
"(",
"criteria",
")",
";",
"List",
"<",
"PartitionTransferSyntax",
">",
"returnList",
"=",
"new",
"List",
"<",
"PartitionTransferSyntax",
">",
"(",
")",
";",
"foreach",
"(",
"PartitionTransferSyntax",
"syntax",
"in",
"list",
")",
"{",
"if",
"(",
"!",
"syntax",
".",
"Enabled",
")",
"continue",
";",
"TransferSyntax",
"dicomSyntax",
"=",
"TransferSyntax",
".",
"GetTransferSyntax",
"(",
"syntax",
".",
"Uid",
")",
";",
"if",
"(",
"dicomSyntax",
".",
"Encapsulated",
"==",
"encapsulated",
")",
"returnList",
".",
"Add",
"(",
"syntax",
")",
";",
"}",
"return",
"returnList",
";",
"}",
"endregion",
"region",
" Overridden BaseSCP methods",
"protected",
"override",
"DicomPresContextResult",
"OnVerifyAssociation",
"(",
"AssociationParameters",
"association",
",",
"byte",
"pcid",
")",
"{",
"if",
"(",
"Device",
"==",
"null",
")",
"return",
"DicomPresContextResult",
".",
"Accept",
";",
"if",
"(",
"!",
"Device",
".",
"AllowStorage",
")",
"{",
"return",
"DicomPresContextResult",
".",
"RejectUser",
";",
"}",
"if",
"(",
"Device",
".",
"AcceptKOPR",
")",
"{",
"DicomPresContext",
"context",
"=",
"association",
".",
"GetPresentationContext",
"(",
"pcid",
")",
";",
"if",
"(",
"context",
".",
"AbstractSyntax",
".",
"Equals",
"(",
"SopClass",
".",
"KeyObjectSelectionDocumentStorage",
")",
"||",
"context",
".",
"AbstractSyntax",
".",
"Equals",
"(",
"SopClass",
".",
"GrayscaleSoftcopyPresentationStateStorageSopClass",
")",
"||",
"context",
".",
"AbstractSyntax",
".",
"Equals",
"(",
"SopClass",
".",
"BlendingSoftcopyPresentationStateStorageSopClass",
")",
"||",
"context",
".",
"AbstractSyntax",
".",
"Equals",
"(",
"SopClass",
".",
"ColorSoftcopyPresentationStateStorageSopClass",
")",
"||",
"context",
".",
"AbstractSyntax",
".",
"Equals",
"(",
"SopClass",
".",
"PseudoColorSoftcopyPresentationStateStorageSopClass",
")",
")",
"return",
"DicomPresContextResult",
".",
"Accept",
";",
"return",
"DicomPresContextResult",
".",
"RejectUser",
";",
"}",
"return",
"DicomPresContextResult",
".",
"Accept",
";",
"}",
"endregion",
" Overridden BaseSCP methods",
"region",
" IDicomScp Members",
"public",
"override",
"bool",
"OnReceiveRequest",
"(",
"DicomServer",
"server",
",",
"ServerAssociationParameters",
"association",
",",
"byte",
"presentationID",
",",
"DicomMessage",
"message",
")",
"{",
"try",
"{",
"SopInstanceImporterContext",
"context",
"=",
"new",
"SopInstanceImporterContext",
"(",
"String",
".",
"Format",
"(",
"\"",
"{0}_{1}",
"\"",
",",
"association",
".",
"CallingAE",
",",
"association",
".",
"TimeStamp",
".",
"ToString",
"(",
"\"",
"yyyyMMddhhmmss",
"\"",
")",
")",
",",
"association",
".",
"CallingAE",
",",
"association",
".",
"CalledAE",
")",
";",
"SopInstanceImporter",
"importer",
"=",
"new",
"SopInstanceImporter",
"(",
"context",
")",
";",
"DicomProcessingResult",
"result",
"=",
"importer",
".",
"Import",
"(",
"message",
")",
";",
"if",
"(",
"result",
".",
"Successful",
")",
"{",
"if",
"(",
"!",
"String",
".",
"IsNullOrEmpty",
"(",
"result",
".",
"AccessionNumber",
")",
")",
"Platform",
".",
"Log",
"(",
"LogLevel",
".",
"Info",
",",
"\"",
"Received SOP Instance {0} from {1} to {2} (A#:{3} StudyUid:{4})",
"\"",
",",
"result",
".",
"SopInstanceUid",
",",
"association",
".",
"CallingAE",
",",
"association",
".",
"CalledAE",
",",
"result",
".",
"AccessionNumber",
",",
"result",
".",
"StudyInstanceUid",
")",
";",
"else",
"Platform",
".",
"Log",
"(",
"LogLevel",
".",
"Info",
",",
"\"",
"Received SOP Instance {0} from {1} to {2} (StudyUid:{3})",
"\"",
",",
"result",
".",
"SopInstanceUid",
",",
"association",
".",
"CallingAE",
",",
"association",
".",
"CalledAE",
",",
"result",
".",
"StudyInstanceUid",
")",
";",
"}",
"else",
"Platform",
".",
"Log",
"(",
"LogLevel",
".",
"Warn",
",",
"\"",
"Failure importing sop: {0}",
"\"",
",",
"result",
".",
"ErrorMessage",
")",
";",
"server",
".",
"SendCStoreResponse",
"(",
"presentationID",
",",
"message",
".",
"MessageId",
",",
"message",
".",
"AffectedSopInstanceUid",
",",
"result",
".",
"DicomStatus",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"DicomDataException",
"ex",
")",
"{",
"Platform",
".",
"Log",
"(",
"LogLevel",
".",
"Error",
",",
"ex",
")",
";",
"return",
"false",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"Platform",
".",
"Log",
"(",
"LogLevel",
".",
"Error",
",",
"ex",
")",
";",
"return",
"false",
";",
"}",
"}",
"endregion",
"}"
] |
Abstract class for handling Storage SCP connections.
|
[
"Abstract",
"class",
"for",
"handling",
"Storage",
"SCP",
"connections",
"."
] |
[
"/// <summary>",
"/// Converts a <see cref=\"DicomMessage\"/> instance into a <see cref=\"DicomFile\"/>.",
"/// </summary>",
"/// <remarks>This routine sets the Source AE title, </remarks>",
"/// <param name=\"message\"></param>",
"/// <param name=\"filename\"></param>",
"/// <param name=\"assocParms\"></param>",
"/// <returns></returns>",
"// This routine sets some of the group 0x0002 elements.",
"/// <summary>",
"/// Load from the database the configured transfer syntaxes",
"/// </summary>",
"/// <param name=\"read\">a Read context</param>",
"/// <param name=\"partitionKey\">The partition to retrieve the transfer syntaxes for</param>",
"/// <param name=\"encapsulated\">true if searching for encapsulated syntaxes only</param>",
"/// <returns>The list of syntaxes</returns>",
"// caller will abort the association",
"// caller will abort the association"
] |
[
{
"param": "BaseScp",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseScp",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "This class is an abstract base class for ImageServer plugins that process DICOM C-STORE\nrequest messages. The class implements a number of common methods needed for SCP handlers.\nThe class also implements the interface.",
"docstring_tokens": [
"This",
"class",
"is",
"an",
"abstract",
"base",
"class",
"for",
"ImageServer",
"plugins",
"that",
"process",
"DICOM",
"C",
"-",
"STORE",
"request",
"messages",
".",
"The",
"class",
"implements",
"a",
"number",
"of",
"common",
"methods",
"needed",
"for",
"SCP",
"handlers",
".",
"The",
"class",
"also",
"implements",
"the",
"interface",
"."
]
}
]
}
| false
| 20
| 920
| 87
|
e592a392a190b8632867315db8ef5bffe1272bbb
|
atranel/resqdb
|
Reports.py
|
[
"MIT"
] |
Python
|
GenerateGraphs
|
The class generating graphs into presentation and called inside the :class:`resqdb.Reports.GeneratePresentation`.
:param df: the dataframe with calculated statistics
:type df: pandas dataframe
:param presentation: the opened document (pptx)
:type presentation: Presentation object
:param title: the title of the slide
:type title: str
:param column_name: the name of column which should be used in the graph (for stacked graph represent the first column to get index where the data included in the graph starts)
:type column_name: str
:param country_name: the country name
:type coutnry_name: str
:param axis_name: the label of x-axis
:type axis_name: str
:param coloring: `True` if rows should be colored by number, else `False`
:type coloring: bool
:param region: `True` if region graphs should be generated (coloring issue)
:type region: bool
:param incorrect: `True` if graphs displaying the incorrect times are generated
:type incorrect: bool
:param maximum: maximum value of x-axis for some graph
:type maximum: int
:param content: the small guide text displayed on the slide next to graph, each paragraphs is new value in list
:type content: list
|
The class generating graphs into presentation and called inside the :class:`resqdb.Reports.GeneratePresentation`.
|
[
"The",
"class",
"generating",
"graphs",
"into",
"presentation",
"and",
"called",
"inside",
"the",
":",
"class",
":",
"`",
"resqdb",
".",
"Reports",
".",
"GeneratePresentation",
"`",
"."
] |
class GenerateGraphs:
""" The class generating graphs into presentation and called inside the :class:`resqdb.Reports.GeneratePresentation`.
:param df: the dataframe with calculated statistics
:type df: pandas dataframe
:param presentation: the opened document (pptx)
:type presentation: Presentation object
:param title: the title of the slide
:type title: str
:param column_name: the name of column which should be used in the graph (for stacked graph represent the first column to get index where the data included in the graph starts)
:type column_name: str
:param country_name: the country name
:type coutnry_name: str
:param axis_name: the label of x-axis
:type axis_name: str
:param coloring: `True` if rows should be colored by number, else `False`
:type coloring: bool
:param region: `True` if region graphs should be generated (coloring issue)
:type region: bool
:param incorrect: `True` if graphs displaying the incorrect times are generated
:type incorrect: bool
:param maximum: maximum value of x-axis for some graph
:type maximum: int
:param content: the small guide text displayed on the slide next to graph, each paragraphs is new value in list
:type content: list
"""
def __init__(self, df, presentation, title, column_name, country_name, axis_name=None, coloring=False, region=False, incorrect=False, maximum=0, content=None):
self.dataframe = df
self.presentation = presentation
self.title = title
self.column_name = column_name
self.font_name = 'Century Gothic'
self.categories_column = 'Site Name'
self.country_name = country_name
self.coloring = coloring
self.region = region
self.incorrect = incorrect
self.maximum = maximum
self.axis_name = axis_name
self.content = content
# Estimate font sizes based on number of sites included in the graph
if (len(self.dataframe) > 15):
self.category_font_size = Pt(10)
self.data_label_font_size = Pt(8)
else:
self.category_font_size = Pt(11)
self.data_label_font_size = Pt(11)
self._create_barplot()
def _set_transparency(self, transparency, elm):
""" The function set the transparency of the row.
:param transparency: the transparency in %
:type transparency: int
:param elm: the element which transparency should be changed
:type elm: format.line.color._xFill
"""
a = str(100 - transparency) + '196'
alpha = OxmlElement('a:alpha')
alpha.set('val', a)
elm.srgbClr.append(alpha)
def _create_barplot(self):
""" The function creating the new graph into the presentation based on the graph type. """
colors = {
'yellow': RGBColor(255, 192, 0),
'green': RGBColor(98, 153, 62),
'crimsom': RGBColor(220, 20, 60),
'blue': RGBColor(43, 88, 173),
'wine_red': RGBColor(134, 0, 0)
}
site_names = self.dataframe[self.categories_column].tolist()
values = self.dataframe[self.column_name].tolist()
# Add slide to presentation (layout 11 is our custom layout where only title 'Agency FB', color: RGBColor(43, 88, 173) and size:24 is set)
slide = self.presentation.slides.add_slide(self.presentation.slide_layouts[11])
# Get title object
title_placeholders = slide.shapes.title
# Set title
title_placeholders.text = self.title
# Add textbox explanation
if self.content is not None:
len_df = len(self.dataframe[self.dataframe[self.column_name] > 0])
if len_df < 12:
left = Cm(24.7)
top = Cm(12)
width = Cm(8)
height = Cm(5)
else:
left = Cm(24.7)
top = Cm(2)
width = Cm(8)
height = Cm(5)
# Add textbox with explanation
txBox = slide.shapes.add_textbox(left, top, width, height)
txBox.text_frame.clear()
txBox.text_frame.word_wrap = True
for i in range(0, len(self.content)):
if i == 0:
p = txBox.text_frame.paragraphs[0]
run = p.add_run()
run.text = self.content[i]
else:
p = txBox.text_frame.add_paragraph()
run = p.add_run()
run.text = self.content[i]
for paragraph in txBox.text_frame.paragraphs:
paragraph.line_spacing = Pt(18)
paragraph.alignment = PP_ALIGN.CENTER
for run in paragraph.runs:
run.font.size = Pt(10.5)
run.font.name = self.font_name
chart_data = ChartData()
chart_data.categories = self.dataframe[self.categories_column].tolist()
chart_data.add_series(self.column_name, self.dataframe[self.column_name].tolist())
# Add chart on slide
specs = {
'height': Cm(16.5),
'width': Cm(32),
'left': Cm(0.7),
'top': Cm(2)
}
chart = slide.shapes.add_chart(
XL_CHART_TYPE.BAR_CLUSTERED, specs['left'],specs['top'], specs['width'],specs['height'], chart_data).chart
# Get series of chart
series = chart.series[0]
if self.coloring:
# Coloring for median values - <= 20 green, > 20 and <= 30 yellow, else crimsom
for idx, point in enumerate(series.points):
fill = point.format.fill
fill.solid()
value = values[idx]
if (site_names[idx] == self.country_name):
fill.fore_color.rgb = colors['wine_red']
elif (value > 0 and value <= 20):
fill.fore_color.rgb = colors['green']
elif (value > 20 and value <= 30):
fill.fore_color.rgb = colors['yellow']
else:
fill.fore_color.rgb = colors['crimsom']
elif self.region:
# The lowest value colored red, the biggest value colored green
for idx, point in enumerate(series.points):
fill = point.format.fill
fill.solid()
if idx == values.count(0):
fill.fore_color.rgb = colors['crimsom']
elif (site_names[idx] == self.country_name):
fill.fore_color.rgb = colors['yellow']
elif idx == (len(values) - 1):
fill.fore_color.rgb = colors['green']
else:
fill.fore_color.rgb = colors['blue']
elif self.incorrect:
# Set red color for incorrect values
for idx, point in enumerate(series.points):
fill = point.format.fill
fill.solid()
if (site_names[idx] == self.country_name):
fill.fore_color.rgb = colors['wine_red']
else:
fill.fore_color.rgb = colors['crimsom']
else:
# Blue color for the remaining values
for idx, point in enumerate(series.points):
fill = point.format.fill
fill.solid()
if (site_names[idx] == self.country_name):
fill.fore_color.rgb = colors['wine_red']
else:
fill.fore_color.rgb = colors['blue']
# Get plot
plot = chart.plots[0]
# Set for each bar same color
plot.vary_by_categories = False
# Show data labels and set font
plot.has_data_labels = True
# Change gap width
plot.gap_width = 100
data_labels = plot.data_labels
data_labels.font.size = self.data_label_font_size
data_labels.font.bold = True
data_labels.font.name = self.font_name
# Value for x-axis (change font size, name, and other things)
value_axis = chart.value_axis
tick_labels = value_axis.tick_labels
tick_labels.font.size = self.category_font_size
tick_labels.font.name = self.font_name
# Don't show major gridlines
value_axis.major_tick_mark = XL_TICK_MARK.OUTSIDE
value_axis.has_major_gridlines = False
# Set range of axis
if self.maximum != 0:
value_axis.maximum_scale = self.maximum
value_axis.minimum_scale = 0
if self.axis_name is not None:
value_axis.has_title = True
value_axis.axis_title.text_frame.text = self.axis_name
for paragraph in value_axis.axis_title.text_frame.paragraphs:
paragraph.font.size = self.category_font_size
paragraph.font.name = self.font_name
# Value for y-axis (change font size, name, and other things)
category_axis = chart.category_axis
category_axis.format.line.color.rgb = RGBColor(0, 0, 0)
solidFill = category_axis.format.line.color._xFill
self._set_transparency(100, solidFill)
# Delete tick marks
category_axis.major_tick_mark = XL_TICK_MARK.NONE
category_axis.major_unit = 1
category_labels = category_axis.tick_labels
category_labels.font.size = self.category_font_size
category_labels.font.name = self.font_name
|
[
"class",
"GenerateGraphs",
":",
"def",
"__init__",
"(",
"self",
",",
"df",
",",
"presentation",
",",
"title",
",",
"column_name",
",",
"country_name",
",",
"axis_name",
"=",
"None",
",",
"coloring",
"=",
"False",
",",
"region",
"=",
"False",
",",
"incorrect",
"=",
"False",
",",
"maximum",
"=",
"0",
",",
"content",
"=",
"None",
")",
":",
"self",
".",
"dataframe",
"=",
"df",
"self",
".",
"presentation",
"=",
"presentation",
"self",
".",
"title",
"=",
"title",
"self",
".",
"column_name",
"=",
"column_name",
"self",
".",
"font_name",
"=",
"'Century Gothic'",
"self",
".",
"categories_column",
"=",
"'Site Name'",
"self",
".",
"country_name",
"=",
"country_name",
"self",
".",
"coloring",
"=",
"coloring",
"self",
".",
"region",
"=",
"region",
"self",
".",
"incorrect",
"=",
"incorrect",
"self",
".",
"maximum",
"=",
"maximum",
"self",
".",
"axis_name",
"=",
"axis_name",
"self",
".",
"content",
"=",
"content",
"if",
"(",
"len",
"(",
"self",
".",
"dataframe",
")",
">",
"15",
")",
":",
"self",
".",
"category_font_size",
"=",
"Pt",
"(",
"10",
")",
"self",
".",
"data_label_font_size",
"=",
"Pt",
"(",
"8",
")",
"else",
":",
"self",
".",
"category_font_size",
"=",
"Pt",
"(",
"11",
")",
"self",
".",
"data_label_font_size",
"=",
"Pt",
"(",
"11",
")",
"self",
".",
"_create_barplot",
"(",
")",
"def",
"_set_transparency",
"(",
"self",
",",
"transparency",
",",
"elm",
")",
":",
"\"\"\" The function set the transparency of the row. \n\n :param transparency: the transparency in %\n :type transparency: int\n :param elm: the element which transparency should be changed\n :type elm: format.line.color._xFill\n \"\"\"",
"a",
"=",
"str",
"(",
"100",
"-",
"transparency",
")",
"+",
"'196'",
"alpha",
"=",
"OxmlElement",
"(",
"'a:alpha'",
")",
"alpha",
".",
"set",
"(",
"'val'",
",",
"a",
")",
"elm",
".",
"srgbClr",
".",
"append",
"(",
"alpha",
")",
"def",
"_create_barplot",
"(",
"self",
")",
":",
"\"\"\" The function creating the new graph into the presentation based on the graph type. \"\"\"",
"colors",
"=",
"{",
"'yellow'",
":",
"RGBColor",
"(",
"255",
",",
"192",
",",
"0",
")",
",",
"'green'",
":",
"RGBColor",
"(",
"98",
",",
"153",
",",
"62",
")",
",",
"'crimsom'",
":",
"RGBColor",
"(",
"220",
",",
"20",
",",
"60",
")",
",",
"'blue'",
":",
"RGBColor",
"(",
"43",
",",
"88",
",",
"173",
")",
",",
"'wine_red'",
":",
"RGBColor",
"(",
"134",
",",
"0",
",",
"0",
")",
"}",
"site_names",
"=",
"self",
".",
"dataframe",
"[",
"self",
".",
"categories_column",
"]",
".",
"tolist",
"(",
")",
"values",
"=",
"self",
".",
"dataframe",
"[",
"self",
".",
"column_name",
"]",
".",
"tolist",
"(",
")",
"slide",
"=",
"self",
".",
"presentation",
".",
"slides",
".",
"add_slide",
"(",
"self",
".",
"presentation",
".",
"slide_layouts",
"[",
"11",
"]",
")",
"title_placeholders",
"=",
"slide",
".",
"shapes",
".",
"title",
"title_placeholders",
".",
"text",
"=",
"self",
".",
"title",
"if",
"self",
".",
"content",
"is",
"not",
"None",
":",
"len_df",
"=",
"len",
"(",
"self",
".",
"dataframe",
"[",
"self",
".",
"dataframe",
"[",
"self",
".",
"column_name",
"]",
">",
"0",
"]",
")",
"if",
"len_df",
"<",
"12",
":",
"left",
"=",
"Cm",
"(",
"24.7",
")",
"top",
"=",
"Cm",
"(",
"12",
")",
"width",
"=",
"Cm",
"(",
"8",
")",
"height",
"=",
"Cm",
"(",
"5",
")",
"else",
":",
"left",
"=",
"Cm",
"(",
"24.7",
")",
"top",
"=",
"Cm",
"(",
"2",
")",
"width",
"=",
"Cm",
"(",
"8",
")",
"height",
"=",
"Cm",
"(",
"5",
")",
"txBox",
"=",
"slide",
".",
"shapes",
".",
"add_textbox",
"(",
"left",
",",
"top",
",",
"width",
",",
"height",
")",
"txBox",
".",
"text_frame",
".",
"clear",
"(",
")",
"txBox",
".",
"text_frame",
".",
"word_wrap",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"self",
".",
"content",
")",
")",
":",
"if",
"i",
"==",
"0",
":",
"p",
"=",
"txBox",
".",
"text_frame",
".",
"paragraphs",
"[",
"0",
"]",
"run",
"=",
"p",
".",
"add_run",
"(",
")",
"run",
".",
"text",
"=",
"self",
".",
"content",
"[",
"i",
"]",
"else",
":",
"p",
"=",
"txBox",
".",
"text_frame",
".",
"add_paragraph",
"(",
")",
"run",
"=",
"p",
".",
"add_run",
"(",
")",
"run",
".",
"text",
"=",
"self",
".",
"content",
"[",
"i",
"]",
"for",
"paragraph",
"in",
"txBox",
".",
"text_frame",
".",
"paragraphs",
":",
"paragraph",
".",
"line_spacing",
"=",
"Pt",
"(",
"18",
")",
"paragraph",
".",
"alignment",
"=",
"PP_ALIGN",
".",
"CENTER",
"for",
"run",
"in",
"paragraph",
".",
"runs",
":",
"run",
".",
"font",
".",
"size",
"=",
"Pt",
"(",
"10.5",
")",
"run",
".",
"font",
".",
"name",
"=",
"self",
".",
"font_name",
"chart_data",
"=",
"ChartData",
"(",
")",
"chart_data",
".",
"categories",
"=",
"self",
".",
"dataframe",
"[",
"self",
".",
"categories_column",
"]",
".",
"tolist",
"(",
")",
"chart_data",
".",
"add_series",
"(",
"self",
".",
"column_name",
",",
"self",
".",
"dataframe",
"[",
"self",
".",
"column_name",
"]",
".",
"tolist",
"(",
")",
")",
"specs",
"=",
"{",
"'height'",
":",
"Cm",
"(",
"16.5",
")",
",",
"'width'",
":",
"Cm",
"(",
"32",
")",
",",
"'left'",
":",
"Cm",
"(",
"0.7",
")",
",",
"'top'",
":",
"Cm",
"(",
"2",
")",
"}",
"chart",
"=",
"slide",
".",
"shapes",
".",
"add_chart",
"(",
"XL_CHART_TYPE",
".",
"BAR_CLUSTERED",
",",
"specs",
"[",
"'left'",
"]",
",",
"specs",
"[",
"'top'",
"]",
",",
"specs",
"[",
"'width'",
"]",
",",
"specs",
"[",
"'height'",
"]",
",",
"chart_data",
")",
".",
"chart",
"series",
"=",
"chart",
".",
"series",
"[",
"0",
"]",
"if",
"self",
".",
"coloring",
":",
"for",
"idx",
",",
"point",
"in",
"enumerate",
"(",
"series",
".",
"points",
")",
":",
"fill",
"=",
"point",
".",
"format",
".",
"fill",
"fill",
".",
"solid",
"(",
")",
"value",
"=",
"values",
"[",
"idx",
"]",
"if",
"(",
"site_names",
"[",
"idx",
"]",
"==",
"self",
".",
"country_name",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'wine_red'",
"]",
"elif",
"(",
"value",
">",
"0",
"and",
"value",
"<=",
"20",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'green'",
"]",
"elif",
"(",
"value",
">",
"20",
"and",
"value",
"<=",
"30",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'yellow'",
"]",
"else",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'crimsom'",
"]",
"elif",
"self",
".",
"region",
":",
"for",
"idx",
",",
"point",
"in",
"enumerate",
"(",
"series",
".",
"points",
")",
":",
"fill",
"=",
"point",
".",
"format",
".",
"fill",
"fill",
".",
"solid",
"(",
")",
"if",
"idx",
"==",
"values",
".",
"count",
"(",
"0",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'crimsom'",
"]",
"elif",
"(",
"site_names",
"[",
"idx",
"]",
"==",
"self",
".",
"country_name",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'yellow'",
"]",
"elif",
"idx",
"==",
"(",
"len",
"(",
"values",
")",
"-",
"1",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'green'",
"]",
"else",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'blue'",
"]",
"elif",
"self",
".",
"incorrect",
":",
"for",
"idx",
",",
"point",
"in",
"enumerate",
"(",
"series",
".",
"points",
")",
":",
"fill",
"=",
"point",
".",
"format",
".",
"fill",
"fill",
".",
"solid",
"(",
")",
"if",
"(",
"site_names",
"[",
"idx",
"]",
"==",
"self",
".",
"country_name",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'wine_red'",
"]",
"else",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'crimsom'",
"]",
"else",
":",
"for",
"idx",
",",
"point",
"in",
"enumerate",
"(",
"series",
".",
"points",
")",
":",
"fill",
"=",
"point",
".",
"format",
".",
"fill",
"fill",
".",
"solid",
"(",
")",
"if",
"(",
"site_names",
"[",
"idx",
"]",
"==",
"self",
".",
"country_name",
")",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'wine_red'",
"]",
"else",
":",
"fill",
".",
"fore_color",
".",
"rgb",
"=",
"colors",
"[",
"'blue'",
"]",
"plot",
"=",
"chart",
".",
"plots",
"[",
"0",
"]",
"plot",
".",
"vary_by_categories",
"=",
"False",
"plot",
".",
"has_data_labels",
"=",
"True",
"plot",
".",
"gap_width",
"=",
"100",
"data_labels",
"=",
"plot",
".",
"data_labels",
"data_labels",
".",
"font",
".",
"size",
"=",
"self",
".",
"data_label_font_size",
"data_labels",
".",
"font",
".",
"bold",
"=",
"True",
"data_labels",
".",
"font",
".",
"name",
"=",
"self",
".",
"font_name",
"value_axis",
"=",
"chart",
".",
"value_axis",
"tick_labels",
"=",
"value_axis",
".",
"tick_labels",
"tick_labels",
".",
"font",
".",
"size",
"=",
"self",
".",
"category_font_size",
"tick_labels",
".",
"font",
".",
"name",
"=",
"self",
".",
"font_name",
"value_axis",
".",
"major_tick_mark",
"=",
"XL_TICK_MARK",
".",
"OUTSIDE",
"value_axis",
".",
"has_major_gridlines",
"=",
"False",
"if",
"self",
".",
"maximum",
"!=",
"0",
":",
"value_axis",
".",
"maximum_scale",
"=",
"self",
".",
"maximum",
"value_axis",
".",
"minimum_scale",
"=",
"0",
"if",
"self",
".",
"axis_name",
"is",
"not",
"None",
":",
"value_axis",
".",
"has_title",
"=",
"True",
"value_axis",
".",
"axis_title",
".",
"text_frame",
".",
"text",
"=",
"self",
".",
"axis_name",
"for",
"paragraph",
"in",
"value_axis",
".",
"axis_title",
".",
"text_frame",
".",
"paragraphs",
":",
"paragraph",
".",
"font",
".",
"size",
"=",
"self",
".",
"category_font_size",
"paragraph",
".",
"font",
".",
"name",
"=",
"self",
".",
"font_name",
"category_axis",
"=",
"chart",
".",
"category_axis",
"category_axis",
".",
"format",
".",
"line",
".",
"color",
".",
"rgb",
"=",
"RGBColor",
"(",
"0",
",",
"0",
",",
"0",
")",
"solidFill",
"=",
"category_axis",
".",
"format",
".",
"line",
".",
"color",
".",
"_xFill",
"self",
".",
"_set_transparency",
"(",
"100",
",",
"solidFill",
")",
"category_axis",
".",
"major_tick_mark",
"=",
"XL_TICK_MARK",
".",
"NONE",
"category_axis",
".",
"major_unit",
"=",
"1",
"category_labels",
"=",
"category_axis",
".",
"tick_labels",
"category_labels",
".",
"font",
".",
"size",
"=",
"self",
".",
"category_font_size",
"category_labels",
".",
"font",
".",
"name",
"=",
"self",
".",
"font_name"
] |
The class generating graphs into presentation and called inside the :class:`resqdb.Reports.GeneratePresentation`.
|
[
"The",
"class",
"generating",
"graphs",
"into",
"presentation",
"and",
"called",
"inside",
"the",
":",
"class",
":",
"`",
"resqdb",
".",
"Reports",
".",
"GeneratePresentation",
"`",
"."
] |
[
"\"\"\" The class generating graphs into presentation and called inside the :class:`resqdb.Reports.GeneratePresentation`. \n\n :param df: the dataframe with calculated statistics\n :type df: pandas dataframe\n :param presentation: the opened document (pptx)\n :type presentation: Presentation object\n :param title: the title of the slide\n :type title: str\n :param column_name: the name of column which should be used in the graph (for stacked graph represent the first column to get index where the data included in the graph starts)\n :type column_name: str\n :param country_name: the country name\n :type coutnry_name: str\n :param axis_name: the label of x-axis\n :type axis_name: str\n :param coloring: `True` if rows should be colored by number, else `False`\n :type coloring: bool\n :param region: `True` if region graphs should be generated (coloring issue)\n :type region: bool\n :param incorrect: `True` if graphs displaying the incorrect times are generated\n :type incorrect: bool\n :param maximum: maximum value of x-axis for some graph\n :type maximum: int\n :param content: the small guide text displayed on the slide next to graph, each paragraphs is new value in list\n :type content: list \n \"\"\"",
"# Estimate font sizes based on number of sites included in the graph",
"\"\"\" The function set the transparency of the row. \n\n :param transparency: the transparency in %\n :type transparency: int\n :param elm: the element which transparency should be changed\n :type elm: format.line.color._xFill\n \"\"\"",
"\"\"\" The function creating the new graph into the presentation based on the graph type. \"\"\"",
"# Add slide to presentation (layout 11 is our custom layout where only title 'Agency FB', color: RGBColor(43, 88, 173) and size:24 is set)",
"# Get title object",
"# Set title",
"# Add textbox explanation",
"# Add textbox with explanation",
"# Add chart on slide",
"# Get series of chart",
"# Coloring for median values - <= 20 green, > 20 and <= 30 yellow, else crimsom",
"# The lowest value colored red, the biggest value colored green",
"# Set red color for incorrect values",
"# Blue color for the remaining values ",
"# Get plot ",
"# Set for each bar same color",
"# Show data labels and set font",
"# Change gap width",
"# Value for x-axis (change font size, name, and other things)",
"# Don't show major gridlines",
"# Set range of axis",
"# Value for y-axis (change font size, name, and other things)",
"# Delete tick marks"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "df",
"type": null,
"docstring": "the dataframe with calculated statistics",
"docstring_tokens": [
"the",
"dataframe",
"with",
"calculated",
"statistics"
],
"default": null,
"is_optional": null
},
{
"identifier": "presentation",
"type": null,
"docstring": "the opened document (pptx)",
"docstring_tokens": [
"the",
"opened",
"document",
"(",
"pptx",
")"
],
"default": null,
"is_optional": null
},
{
"identifier": "title",
"type": null,
"docstring": "the title of the slide",
"docstring_tokens": [
"the",
"title",
"of",
"the",
"slide"
],
"default": null,
"is_optional": null
},
{
"identifier": "column_name",
"type": null,
"docstring": "the name of column which should be used in the graph (for stacked graph represent the first column to get index where the data included in the graph starts)",
"docstring_tokens": [
"the",
"name",
"of",
"column",
"which",
"should",
"be",
"used",
"in",
"the",
"graph",
"(",
"for",
"stacked",
"graph",
"represent",
"the",
"first",
"column",
"to",
"get",
"index",
"where",
"the",
"data",
"included",
"in",
"the",
"graph",
"starts",
")"
],
"default": null,
"is_optional": null
},
{
"identifier": "country_name",
"type": null,
"docstring": "the country name",
"docstring_tokens": [
"the",
"country",
"name"
],
"default": null,
"is_optional": null
},
{
"identifier": "axis_name",
"type": null,
"docstring": "the label of x-axis",
"docstring_tokens": [
"the",
"label",
"of",
"x",
"-",
"axis"
],
"default": null,
"is_optional": null
},
{
"identifier": "coloring",
"type": null,
"docstring": "`True` if rows should be colored by number, else `False`",
"docstring_tokens": [
"`",
"True",
"`",
"if",
"rows",
"should",
"be",
"colored",
"by",
"number",
"else",
"`",
"False",
"`"
],
"default": null,
"is_optional": null
},
{
"identifier": "region",
"type": null,
"docstring": "`True` if region graphs should be generated (coloring issue)",
"docstring_tokens": [
"`",
"True",
"`",
"if",
"region",
"graphs",
"should",
"be",
"generated",
"(",
"coloring",
"issue",
")"
],
"default": null,
"is_optional": null
},
{
"identifier": "incorrect",
"type": null,
"docstring": "`True` if graphs displaying the incorrect times are generated",
"docstring_tokens": [
"`",
"True",
"`",
"if",
"graphs",
"displaying",
"the",
"incorrect",
"times",
"are",
"generated"
],
"default": null,
"is_optional": null
},
{
"identifier": "maximum",
"type": null,
"docstring": "maximum value of x-axis for some graph",
"docstring_tokens": [
"maximum",
"value",
"of",
"x",
"-",
"axis",
"for",
"some",
"graph"
],
"default": null,
"is_optional": null
},
{
"identifier": "content",
"type": null,
"docstring": "the small guide text displayed on the slide next to graph, each paragraphs is new value in list",
"docstring_tokens": [
"the",
"small",
"guide",
"text",
"displayed",
"on",
"the",
"slide",
"next",
"to",
"graph",
"each",
"paragraphs",
"is",
"new",
"value",
"in",
"list"
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 17
| 2,155
| 295
|
aa6a981dd84ed81df2fa8da120e8325c15981626
|
xjc90s/native-samples
|
samples-dev/src/templates/release-plugin/src/main/java/org/gradle/samples/ReleasePlugin.java
|
[
"Apache-2.0"
] |
Java
|
ReleasePlugin
|
/**
* A sample plugin that produces releases of a Gradle project. Adds a 'release' task that generates the Swift Package
* Manager manifest for the project and then commits and tags the result. It uses the 'swiftpm-export' plugin to generate
* the Swift Package Manager manifest.
*
* The 'release' task also increments the version in the build.gradle, ready for the next release.
*
* Note: because this is just a sample, it only deals with single project builds.
*/
|
A sample plugin that produces releases of a Gradle project. Adds a 'release' task that generates the Swift Package
Manager manifest for the project and then commits and tags the result. It uses the 'swiftpm-export' plugin to generate
the Swift Package Manager manifest.
The 'release' task also increments the version in the build.gradle, ready for the next release.
because this is just a sample, it only deals with single project builds.
|
[
"A",
"sample",
"plugin",
"that",
"produces",
"releases",
"of",
"a",
"Gradle",
"project",
".",
"Adds",
"a",
"'",
"release",
"'",
"task",
"that",
"generates",
"the",
"Swift",
"Package",
"Manager",
"manifest",
"for",
"the",
"project",
"and",
"then",
"commits",
"and",
"tags",
"the",
"result",
".",
"It",
"uses",
"the",
"'",
"swiftpm",
"-",
"export",
"'",
"plugin",
"to",
"generate",
"the",
"Swift",
"Package",
"Manager",
"manifest",
".",
"The",
"'",
"release",
"'",
"task",
"also",
"increments",
"the",
"version",
"in",
"the",
"build",
".",
"gradle",
"ready",
"for",
"the",
"next",
"release",
".",
"because",
"this",
"is",
"just",
"a",
"sample",
"it",
"only",
"deals",
"with",
"single",
"project",
"builds",
"."
] |
public class ReleasePlugin implements Plugin<Project> {
public void apply(final Project project) {
project.getPluginManager().apply("swiftpm-export");
project.getTasks().register("release", task -> {
// Generate the Swift PM manifest prior to commit
task.dependsOn(project.getTasks().named("generateSwiftPmManifest"));
task.doLast(it -> {
// Commit and tag changes
project.exec(execSpec -> {
execSpec.commandLine("git", "add", "Package.swift");
});
project.exec(execSpec -> {
execSpec.commandLine("git", "commit", "-a", "-m", "version " + project.getVersion());
});
project.exec(execSpec -> {
execSpec.commandLine("git", "tag", project.getVersion());
});
// Increment the version in the build script, for next release
Pattern versionPattern = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d)");
Matcher matcher = versionPattern.matcher(project.getVersion().toString());
if (!matcher.matches()) {
throw new GradleException("Could not parse project version \'" + project.getVersion() + "\'");
}
String newVersion = matcher.group(1) + "." + ((StringGroovyMethods.asType(matcher.group(2), Integer.class)) + 1) + ".0";
String buildFileText = readFileAsString(project.getBuildFile());
String updatedText = buildFileText.replaceAll("version\\s*=\\s*\'" + String.valueOf(project.getVersion()) + "\'", "version = \'" + newVersion + "\'");
if (updatedText.equals(buildFileText)) {
throw new GradleException("Could not update version in " + project.getBuildFile().getName());
}
writeFile(project.getBuildFile(), updatedText);
});
});
}
private static String readFileAsString(File file) {
try (Scanner in = new Scanner(file).useDelimiter("\\Z")) {
return in.next();
} catch (FileNotFoundException e) {
throw new UncheckedIOException(e);
}
}
private static void writeFile(File file, String content) {
try (OutputStream out = new FileOutputStream(file)) {
out.write(content.getBytes());
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}
|
[
"public",
"class",
"ReleasePlugin",
"implements",
"Plugin",
"<",
"Project",
">",
"{",
"public",
"void",
"apply",
"(",
"final",
"Project",
"project",
")",
"{",
"project",
".",
"getPluginManager",
"(",
")",
".",
"apply",
"(",
"\"",
"swiftpm-export",
"\"",
")",
";",
"project",
".",
"getTasks",
"(",
")",
".",
"register",
"(",
"\"",
"release",
"\"",
",",
"task",
"->",
"{",
"task",
".",
"dependsOn",
"(",
"project",
".",
"getTasks",
"(",
")",
".",
"named",
"(",
"\"",
"generateSwiftPmManifest",
"\"",
")",
")",
";",
"task",
".",
"doLast",
"(",
"it",
"->",
"{",
"project",
".",
"exec",
"(",
"execSpec",
"->",
"{",
"execSpec",
".",
"commandLine",
"(",
"\"",
"git",
"\"",
",",
"\"",
"add",
"\"",
",",
"\"",
"Package.swift",
"\"",
")",
";",
"}",
")",
";",
"project",
".",
"exec",
"(",
"execSpec",
"->",
"{",
"execSpec",
".",
"commandLine",
"(",
"\"",
"git",
"\"",
",",
"\"",
"commit",
"\"",
",",
"\"",
"-a",
"\"",
",",
"\"",
"-m",
"\"",
",",
"\"",
"version ",
"\"",
"+",
"project",
".",
"getVersion",
"(",
")",
")",
";",
"}",
")",
";",
"project",
".",
"exec",
"(",
"execSpec",
"->",
"{",
"execSpec",
".",
"commandLine",
"(",
"\"",
"git",
"\"",
",",
"\"",
"tag",
"\"",
",",
"project",
".",
"getVersion",
"(",
")",
")",
";",
"}",
")",
";",
"Pattern",
"versionPattern",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"(",
"\\\\",
"d+)",
"\\\\",
".(",
"\\\\",
"d+)",
"\\\\",
".(",
"\\\\",
"d)",
"\"",
")",
";",
"Matcher",
"matcher",
"=",
"versionPattern",
".",
"matcher",
"(",
"project",
".",
"getVersion",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"if",
"(",
"!",
"matcher",
".",
"matches",
"(",
")",
")",
"{",
"throw",
"new",
"GradleException",
"(",
"\"",
"Could not parse project version ",
"\\'",
"\"",
"+",
"project",
".",
"getVersion",
"(",
")",
"+",
"\"",
"\\'",
"\"",
")",
";",
"}",
"String",
"newVersion",
"=",
"matcher",
".",
"group",
"(",
"1",
")",
"+",
"\"",
".",
"\"",
"+",
"(",
"(",
"StringGroovyMethods",
".",
"asType",
"(",
"matcher",
".",
"group",
"(",
"2",
")",
",",
"Integer",
".",
"class",
")",
")",
"+",
"1",
")",
"+",
"\"",
".0",
"\"",
";",
"String",
"buildFileText",
"=",
"readFileAsString",
"(",
"project",
".",
"getBuildFile",
"(",
")",
")",
";",
"String",
"updatedText",
"=",
"buildFileText",
".",
"replaceAll",
"(",
"\"",
"version",
"\\\\",
"s*=",
"\\\\",
"s*",
"\\'",
"\"",
"+",
"String",
".",
"valueOf",
"(",
"project",
".",
"getVersion",
"(",
")",
")",
"+",
"\"",
"\\'",
"\"",
",",
"\"",
"version = ",
"\\'",
"\"",
"+",
"newVersion",
"+",
"\"",
"\\'",
"\"",
")",
";",
"if",
"(",
"updatedText",
".",
"equals",
"(",
"buildFileText",
")",
")",
"{",
"throw",
"new",
"GradleException",
"(",
"\"",
"Could not update version in ",
"\"",
"+",
"project",
".",
"getBuildFile",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"writeFile",
"(",
"project",
".",
"getBuildFile",
"(",
")",
",",
"updatedText",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}",
"private",
"static",
"String",
"readFileAsString",
"(",
"File",
"file",
")",
"{",
"try",
"(",
"Scanner",
"in",
"=",
"new",
"Scanner",
"(",
"file",
")",
".",
"useDelimiter",
"(",
"\"",
"\\\\",
"Z",
"\"",
")",
")",
"{",
"return",
"in",
".",
"next",
"(",
")",
";",
"}",
"catch",
"(",
"FileNotFoundException",
"e",
")",
"{",
"throw",
"new",
"UncheckedIOException",
"(",
"e",
")",
";",
"}",
"}",
"private",
"static",
"void",
"writeFile",
"(",
"File",
"file",
",",
"String",
"content",
")",
"{",
"try",
"(",
"OutputStream",
"out",
"=",
"new",
"FileOutputStream",
"(",
"file",
")",
")",
"{",
"out",
".",
"write",
"(",
"content",
".",
"getBytes",
"(",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"UncheckedIOException",
"(",
"e",
")",
";",
"}",
"}",
"}"
] |
A sample plugin that produces releases of a Gradle project.
|
[
"A",
"sample",
"plugin",
"that",
"produces",
"releases",
"of",
"a",
"Gradle",
"project",
"."
] |
[
"// Generate the Swift PM manifest prior to commit",
"// Commit and tag changes",
"// Increment the version in the build script, for next release"
] |
[
{
"param": "Plugin<Project>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Plugin<Project>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 26
| 483
| 103
|
f3703d90304c3b03c6dc24989da87738252e0f41
|
brendan-rius/raytracer-epitech
|
raytracer/librt3/core/Renderer.cs
|
[
"MIT"
] |
C#
|
Renderer
|
/// <summary>
/// The renderer is the glue between the scene, the camera and the sampler.
/// It will generate samples using the sampler, make the camera generate rays
/// from those samples, intersect them with the object in the scene, and notify the
/// camera's film of the intersections.
/// <seealso cref="Scene" />
/// <seealso cref="Camera" />
/// <seealso cref="Sampler" />
/// <seealso cref="Sample" />
/// </summary>
|
The renderer is the glue between the scene, the camera and the sampler.
It will generate samples using the sampler, make the camera generate rays
from those samples, intersect them with the object in the scene, and notify the
camera's film of the intersections.
|
[
"The",
"renderer",
"is",
"the",
"glue",
"between",
"the",
"scene",
"the",
"camera",
"and",
"the",
"sampler",
".",
"It",
"will",
"generate",
"samples",
"using",
"the",
"sampler",
"make",
"the",
"camera",
"generate",
"rays",
"from",
"those",
"samples",
"intersect",
"them",
"with",
"the",
"object",
"in",
"the",
"scene",
"and",
"notify",
"the",
"camera",
"'",
"s",
"film",
"of",
"the",
"intersections",
"."
] |
public class Renderer
{
public Renderer(Scene scene, Sampler sampler, Camera camera, Film film, Integrator integrator)
{
Film = film;
Scene = scene;
Sampler = sampler;
Camera = camera;
Integrator = integrator;
}
public Integrator Integrator { get; set; }
public Film Film { get; set; }
public Camera Camera { get; set; }
public Sampler Sampler { get; set; }
public Scene Scene { get; set; }
public long Render()
{
var sw = new Stopwatch();
sw.Start();
var samples = Sampler.Samples();
Parallel.ForEach(samples, sample => Film.AddSample(sample, Li(sample)));
sw.Stop();
return sw.ElapsedMilliseconds;
}
public SampledSpectrum Li(Sample sample, Ray ray = null)
{
ray = ray ?? Camera.GenerateRay(sample);
var intersection = new Intersection();
var spectrum = SampledSpectrum.Black();
if (Scene.TryToIntersect(ray, ref intersection))
spectrum = Integrator.Li(Scene, ray, this, sample, ref intersection);
else
spectrum = Scene.Lights.Aggregate(spectrum, (current, light) => current + light.Le(ray));
return spectrum;
}
}
|
[
"public",
"class",
"Renderer",
"{",
"public",
"Renderer",
"(",
"Scene",
"scene",
",",
"Sampler",
"sampler",
",",
"Camera",
"camera",
",",
"Film",
"film",
",",
"Integrator",
"integrator",
")",
"{",
"Film",
"=",
"film",
";",
"Scene",
"=",
"scene",
";",
"Sampler",
"=",
"sampler",
";",
"Camera",
"=",
"camera",
";",
"Integrator",
"=",
"integrator",
";",
"}",
"public",
"Integrator",
"Integrator",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Film",
"Film",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Camera",
"Camera",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Sampler",
"Sampler",
"{",
"get",
";",
"set",
";",
"}",
"public",
"Scene",
"Scene",
"{",
"get",
";",
"set",
";",
"}",
"public",
"long",
"Render",
"(",
")",
"{",
"var",
"sw",
"=",
"new",
"Stopwatch",
"(",
")",
";",
"sw",
".",
"Start",
"(",
")",
";",
"var",
"samples",
"=",
"Sampler",
".",
"Samples",
"(",
")",
";",
"Parallel",
".",
"ForEach",
"(",
"samples",
",",
"sample",
"=>",
"Film",
".",
"AddSample",
"(",
"sample",
",",
"Li",
"(",
"sample",
")",
")",
")",
";",
"sw",
".",
"Stop",
"(",
")",
";",
"return",
"sw",
".",
"ElapsedMilliseconds",
";",
"}",
"public",
"SampledSpectrum",
"Li",
"(",
"Sample",
"sample",
",",
"Ray",
"ray",
"=",
"null",
")",
"{",
"ray",
"=",
"ray",
"??",
"Camera",
".",
"GenerateRay",
"(",
"sample",
")",
";",
"var",
"intersection",
"=",
"new",
"Intersection",
"(",
")",
";",
"var",
"spectrum",
"=",
"SampledSpectrum",
".",
"Black",
"(",
")",
";",
"if",
"(",
"Scene",
".",
"TryToIntersect",
"(",
"ray",
",",
"ref",
"intersection",
")",
")",
"spectrum",
"=",
"Integrator",
".",
"Li",
"(",
"Scene",
",",
"ray",
",",
"this",
",",
"sample",
",",
"ref",
"intersection",
")",
";",
"else",
"spectrum",
"=",
"Scene",
".",
"Lights",
".",
"Aggregate",
"(",
"spectrum",
",",
"(",
"current",
",",
"light",
")",
"=>",
"current",
"+",
"light",
".",
"Le",
"(",
"ray",
")",
")",
";",
"return",
"spectrum",
";",
"}",
"}"
] |
The renderer is the glue between the scene, the camera and the sampler.
|
[
"The",
"renderer",
"is",
"the",
"glue",
"between",
"the",
"scene",
"the",
"camera",
"and",
"the",
"sampler",
"."
] |
[
"/// <summary>",
"/// Create a new renderer",
"/// </summary>",
"/// <param name=\"scene\">the scene to render</param>",
"/// <param name=\"sampler\">the sampler</param>",
"/// <param name=\"camera\">the camera</param>",
"/// <param name=\"film\">the film to write to</param>",
"/// <param name=\"integrator\">the surface integrator</param>",
"/// <summary>",
"/// The integrator used",
"/// </summary>",
"/// <summary>",
"/// The film to which the scene will be rendered",
"/// </summary>",
"/// <summary>",
"/// The camera used to generate rays",
"/// </summary>",
"/// <summary>",
"/// THe sampler used to generate samles",
"/// </summary>",
"/// <summary>",
"/// The scene to render",
"/// </summary>",
"/// <summary>",
"/// Render the scene.",
"/// <returns>the duration of rendering (in milliseconds)</returns>",
"/// </summary>",
"/// <summary>",
"/// Compute radiance for a sample",
"/// </summary>",
"/// <param name=\"sample\"></param>",
"/// <param name=\"ray\"></param>",
"/// <returns></returns>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 272
| 105
|
f103467de80eb95a1060dec1e0ac0ebe711d79dc
|
danielribeiro/rubytricks
|
frombuilder.rb
|
[
"MIT"
] |
Ruby
|
Meuframe
|
# This class was automatically generated from XRC source. It is not
# recommended that this file is edited directly; instead, inherit from
# this class and extend its behaviour there.
#
# Source file: wxtest/dialog.xrc
# Generated at: Tue Dec 29 23:04:38 -0200 2009
|
This class was automatically generated from XRC source. It is not
recommended that this file is edited directly; instead, inherit from
this class and extend its behaviour there.
|
[
"This",
"class",
"was",
"automatically",
"generated",
"from",
"XRC",
"source",
".",
"It",
"is",
"not",
"recommended",
"that",
"this",
"file",
"is",
"edited",
"directly",
";",
"instead",
"inherit",
"from",
"this",
"class",
"and",
"extend",
"its",
"behaviour",
"there",
"."
] |
class Meuframe < Wx::Frame
def initialize(parent = nil)
super()
xml = Wx::XmlResource.get
xml.flags = 2 # Wx::XRC_NO_SUBCLASSING
xml.init_all_handlers
xml.load("wxtest/dialog.xrc")
xml.load_frame_subclass(self, parent, "ID_WXFRAME")
finder = lambda do | x |
int_id = Wx::xrcid(x)
begin
Wx::Window.find_window_by_id(int_id, self) || int_id
# Temporary hack to work around regression in 1.9.2; remove
# begin/rescue clause in later versions
rescue RuntimeError
int_id
end
end
if self.class.method_defined? "on_init"
self.on_init()
end
end
end
|
[
"class",
"Meuframe",
"<",
"Wx",
"::",
"Frame",
"def",
"initialize",
"(",
"parent",
"=",
"nil",
")",
"super",
"(",
")",
"xml",
"=",
"Wx",
"::",
"XmlResource",
".",
"get",
"xml",
".",
"flags",
"=",
"2",
"xml",
".",
"init_all_handlers",
"xml",
".",
"load",
"(",
"\"wxtest/dialog.xrc\"",
")",
"xml",
".",
"load_frame_subclass",
"(",
"self",
",",
"parent",
",",
"\"ID_WXFRAME\"",
")",
"finder",
"=",
"lambda",
"do",
"|",
"x",
"|",
"int_id",
"=",
"Wx",
"::",
"xrcid",
"(",
"x",
")",
"begin",
"Wx",
"::",
"Window",
".",
"find_window_by_id",
"(",
"int_id",
",",
"self",
")",
"||",
"int_id",
"rescue",
"RuntimeError",
"int_id",
"end",
"end",
"if",
"self",
".",
"class",
".",
"method_defined?",
"\"on_init\"",
"self",
".",
"on_init",
"(",
")",
"end",
"end",
"end"
] |
This class was automatically generated from XRC source.
|
[
"This",
"class",
"was",
"automatically",
"generated",
"from",
"XRC",
"source",
"."
] |
[
"# Wx::XRC_NO_SUBCLASSING",
"# Temporary hack to work around regression in 1.9.2; remove",
"# begin/rescue clause in later versions"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 188
| 78
|
6510486b457b45ab3429531f44b6f68da6cc2070
|
TeknologiPermainanYogyakarta/MultiplayerGame
|
Assets/Photon/PhotonUnityNetworking/Demos/DemoProcedural/Scripts/WorldGenerator.cs
|
[
"MIT"
] |
C#
|
WorldGenerator
|
/// <summary>
/// The World Generator creates a world based on four options the current MasterClient can set.
/// These options are available on the Ingame Control Panel. If those options are confirmed by the current MasterClient,
/// they will be stored in the Custom Room Properties to make them available on all clients.
/// These options are:
/// 1) a numerical Seed to make sure that each client generates the same world and to avoid Random functions and 'network-instantiate' everything
/// 2) the World Size to describe how large the generated world should be
/// 3) the Cluster Size to describe how many Blocks are inside each Cluster
/// 4) the World Type to make the generated world appear in different 'looks'.
/// </summary>
|
The World Generator creates a world based on four options the current MasterClient can set.
These options are available on the Ingame Control Panel. If those options are confirmed by the current MasterClient,
they will be stored in the Custom Room Properties to make them available on all clients.
These options are:
1) a numerical Seed to make sure that each client generates the same world and to avoid Random functions and 'network-instantiate' everything
2) the World Size to describe how large the generated world should be
3) the Cluster Size to describe how many Blocks are inside each Cluster
4) the World Type to make the generated world appear in different 'looks'.
|
[
"The",
"World",
"Generator",
"creates",
"a",
"world",
"based",
"on",
"four",
"options",
"the",
"current",
"MasterClient",
"can",
"set",
".",
"These",
"options",
"are",
"available",
"on",
"the",
"Ingame",
"Control",
"Panel",
".",
"If",
"those",
"options",
"are",
"confirmed",
"by",
"the",
"current",
"MasterClient",
"they",
"will",
"be",
"stored",
"in",
"the",
"Custom",
"Room",
"Properties",
"to",
"make",
"them",
"available",
"on",
"all",
"clients",
".",
"These",
"options",
"are",
":",
"1",
")",
"a",
"numerical",
"Seed",
"to",
"make",
"sure",
"that",
"each",
"client",
"generates",
"the",
"same",
"world",
"and",
"to",
"avoid",
"Random",
"functions",
"and",
"'",
"network",
"-",
"instantiate",
"'",
"everything",
"2",
")",
"the",
"World",
"Size",
"to",
"describe",
"how",
"large",
"the",
"generated",
"world",
"should",
"be",
"3",
")",
"the",
"Cluster",
"Size",
"to",
"describe",
"how",
"many",
"Blocks",
"are",
"inside",
"each",
"Cluster",
"4",
")",
"the",
"World",
"Type",
"to",
"make",
"the",
"generated",
"world",
"appear",
"in",
"different",
"'",
"looks",
"'",
"."
] |
public class WorldGenerator : MonoBehaviour
{
public readonly string SeedPropertiesKey = "Seed";
public readonly string WorldSizePropertiesKey = "WorldSize";
public readonly string ClusterSizePropertiesKey = "ClusterSize";
public readonly string WorldTypePropertiesKey = "WorldType";
private static WorldGenerator instance;
public static WorldGenerator Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<WorldGenerator>();
}
return instance;
}
}
public int Seed { get; set; }
public WorldSize WorldSize { get; set; }
public ClusterSize ClusterSize { get; set; }
public WorldType WorldType { get; set; }
private Dictionary<int, GameObject> clusterList;
public Material[] WorldMaterials;
#region UNITY
public void Awake()
{
clusterList = new Dictionary<int, GameObject>();
WorldSize = WorldSize.Tiny;
ClusterSize = ClusterSize.Small;
WorldType = WorldType.Standard;
}
#endregion
#region CLASS FUNCTIONS
public void CreateWorld()
{
StopAllCoroutines();
DestroyWorld();
StartCoroutine(GenerateWorld());
}
private void DestroyWorld()
{
foreach (GameObject cluster in clusterList.Values)
{
Cluster clusterComponent = cluster.GetComponent<Cluster>();
clusterComponent.DestroyCluster();
Destroy(cluster);
}
clusterList.Clear();
}
public void ConfirmAndUpdateProperties()
{
if (!PhotonNetwork.IsMasterClient)
{
return;
}
Hashtable properties = new Hashtable
{
{SeedPropertiesKey, Seed},
{WorldSizePropertiesKey, (int) WorldSize},
{ClusterSizePropertiesKey, (int) ClusterSize},
{WorldTypePropertiesKey, (int) WorldType}
};
PhotonNetwork.CurrentRoom.SetCustomProperties(properties);
}
public void DecreaseBlockHeight(int clusterId, int blockId)
{
Cluster c = clusterList[clusterId].GetComponent<Cluster>();
if (c != null)
{
c.DecreaseBlockHeight(blockId);
}
}
public void IncreaseBlockHeight(int clusterId, int blockId)
{
Cluster c = clusterList[clusterId].GetComponent<Cluster>();
if (c != null)
{
c.IncreaseBlockHeight(blockId);
}
}
#endregion
#region COROUTINES
private IEnumerator GenerateWorld()
{
Debug.Log(string.Format("<b>Procedural Demo</b>: Creating world using Seed: {0}, World Size: {1}, Cluster Size: {2} and World Type: {3}", Seed, WorldSize, ClusterSize, WorldType));
Simplex.Noise.Seed = Seed;
int clusterId = 0;
for (int x = 0; x < (int) WorldSize; x += (int) Mathf.Sqrt((int) ClusterSize))
{
for (int z = 0; z < (int) WorldSize; z += (int) Mathf.Sqrt((int) ClusterSize))
{
GameObject cluster = new GameObject();
cluster.name = "Cluster " + clusterId;
cluster.transform.SetParent(transform);
cluster.transform.position = new Vector3(x, 0.0f, z);
Cluster clusterComponent = cluster.AddComponent<Cluster>();
clusterComponent.ClusterId = clusterId;
clusterList.Add(clusterId++, cluster);
}
}
yield return new WaitForEndOfFrame();
foreach (GameObject cluster in clusterList.Values)
{
Vector3 clusterPosition = cluster.transform.position;
int blockId = 0;
for (int x = 0; x < (int) Mathf.Sqrt((int) ClusterSize); ++x)
{
for (int z = 0; z < (int) Mathf.Sqrt((int) ClusterSize); ++z)
{
float noiseValue = Simplex.Noise.CalcPixel2D((int) clusterPosition.x + x, (int) clusterPosition.z + z, 0.02f);
int height = (int) noiseValue / (int) (256.0f / (float) WorldType);
int materialIndex = (int) noiseValue / (int) (256.0f / WorldMaterials.Length);
GameObject block = GameObject.CreatePrimitive(PrimitiveType.Cube);
block.name = "Block " + blockId;
block.transform.SetParent(cluster.transform);
block.transform.localScale = new Vector3(1.0f, height, 1.0f);
block.transform.position = new Vector3(clusterPosition.x + x, height / 2.0f, clusterPosition.z + z);
block.GetComponent<MeshRenderer>().material = WorldMaterials[materialIndex];
Block blockComponent = block.AddComponent<Block>();
blockComponent.BlockId = blockId;
blockComponent.ClusterId = cluster.GetComponent<Cluster>().ClusterId;
cluster.GetComponent<Cluster>().AddBlock(blockId++, block);
}
}
yield return new WaitForEndOfFrame();
}
foreach (DictionaryEntry entry in PhotonNetwork.CurrentRoom.CustomProperties)
{
if (entry.Value == null)
{
continue;
}
string key = entry.Key.ToString();
if ((key == SeedPropertiesKey) || (key == WorldSizePropertiesKey) || (key == ClusterSizePropertiesKey) || (key == WorldTypePropertiesKey))
{
continue;
}
int indexOfBlank = key.IndexOf(' ');
key = key.Substring(indexOfBlank + 1, (key.Length - (indexOfBlank + 1)));
int.TryParse(key, out clusterId);
GameObject cluster;
if (clusterList.TryGetValue(clusterId, out cluster))
{
Cluster c = cluster.GetComponent<Cluster>();
if (c != null)
{
Dictionary<int, float> clusterModifications = (Dictionary<int, float>) entry.Value;
foreach (KeyValuePair<int, float> pair in clusterModifications)
{
c.SetBlockHeightRemote(pair.Key, pair.Value);
}
}
}
}
}
#endregion
}
|
[
"public",
"class",
"WorldGenerator",
":",
"MonoBehaviour",
"{",
"public",
"readonly",
"string",
"SeedPropertiesKey",
"=",
"\"",
"Seed",
"\"",
";",
"public",
"readonly",
"string",
"WorldSizePropertiesKey",
"=",
"\"",
"WorldSize",
"\"",
";",
"public",
"readonly",
"string",
"ClusterSizePropertiesKey",
"=",
"\"",
"ClusterSize",
"\"",
";",
"public",
"readonly",
"string",
"WorldTypePropertiesKey",
"=",
"\"",
"WorldType",
"\"",
";",
"private",
"static",
"WorldGenerator",
"instance",
";",
"public",
"static",
"WorldGenerator",
"Instance",
"{",
"get",
"{",
"if",
"(",
"instance",
"==",
"null",
")",
"{",
"instance",
"=",
"FindObjectOfType",
"<",
"WorldGenerator",
">",
"(",
")",
";",
"}",
"return",
"instance",
";",
"}",
"}",
"public",
"int",
"Seed",
"{",
"get",
";",
"set",
";",
"}",
"public",
"WorldSize",
"WorldSize",
"{",
"get",
";",
"set",
";",
"}",
"public",
"ClusterSize",
"ClusterSize",
"{",
"get",
";",
"set",
";",
"}",
"public",
"WorldType",
"WorldType",
"{",
"get",
";",
"set",
";",
"}",
"private",
"Dictionary",
"<",
"int",
",",
"GameObject",
">",
"clusterList",
";",
"public",
"Material",
"[",
"]",
"WorldMaterials",
";",
"region",
" UNITY",
"public",
"void",
"Awake",
"(",
")",
"{",
"clusterList",
"=",
"new",
"Dictionary",
"<",
"int",
",",
"GameObject",
">",
"(",
")",
";",
"WorldSize",
"=",
"WorldSize",
".",
"Tiny",
";",
"ClusterSize",
"=",
"ClusterSize",
".",
"Small",
";",
"WorldType",
"=",
"WorldType",
".",
"Standard",
";",
"}",
"endregion",
"region",
" CLASS FUNCTIONS",
"public",
"void",
"CreateWorld",
"(",
")",
"{",
"StopAllCoroutines",
"(",
")",
";",
"DestroyWorld",
"(",
")",
";",
"StartCoroutine",
"(",
"GenerateWorld",
"(",
")",
")",
";",
"}",
"private",
"void",
"DestroyWorld",
"(",
")",
"{",
"foreach",
"(",
"GameObject",
"cluster",
"in",
"clusterList",
".",
"Values",
")",
"{",
"Cluster",
"clusterComponent",
"=",
"cluster",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
";",
"clusterComponent",
".",
"DestroyCluster",
"(",
")",
";",
"Destroy",
"(",
"cluster",
")",
";",
"}",
"clusterList",
".",
"Clear",
"(",
")",
";",
"}",
"public",
"void",
"ConfirmAndUpdateProperties",
"(",
")",
"{",
"if",
"(",
"!",
"PhotonNetwork",
".",
"IsMasterClient",
")",
"{",
"return",
";",
"}",
"Hashtable",
"properties",
"=",
"new",
"Hashtable",
"{",
"{",
"SeedPropertiesKey",
",",
"Seed",
"}",
",",
"{",
"WorldSizePropertiesKey",
",",
"(",
"int",
")",
"WorldSize",
"}",
",",
"{",
"ClusterSizePropertiesKey",
",",
"(",
"int",
")",
"ClusterSize",
"}",
",",
"{",
"WorldTypePropertiesKey",
",",
"(",
"int",
")",
"WorldType",
"}",
"}",
";",
"PhotonNetwork",
".",
"CurrentRoom",
".",
"SetCustomProperties",
"(",
"properties",
")",
";",
"}",
"public",
"void",
"DecreaseBlockHeight",
"(",
"int",
"clusterId",
",",
"int",
"blockId",
")",
"{",
"Cluster",
"c",
"=",
"clusterList",
"[",
"clusterId",
"]",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"null",
")",
"{",
"c",
".",
"DecreaseBlockHeight",
"(",
"blockId",
")",
";",
"}",
"}",
"public",
"void",
"IncreaseBlockHeight",
"(",
"int",
"clusterId",
",",
"int",
"blockId",
")",
"{",
"Cluster",
"c",
"=",
"clusterList",
"[",
"clusterId",
"]",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"null",
")",
"{",
"c",
".",
"IncreaseBlockHeight",
"(",
"blockId",
")",
";",
"}",
"}",
"endregion",
"region",
" COROUTINES",
"private",
"IEnumerator",
"GenerateWorld",
"(",
")",
"{",
"Debug",
".",
"Log",
"(",
"string",
".",
"Format",
"(",
"\"",
"<b>Procedural Demo</b>: Creating world using Seed: {0}, World Size: {1}, Cluster Size: {2} and World Type: {3}",
"\"",
",",
"Seed",
",",
"WorldSize",
",",
"ClusterSize",
",",
"WorldType",
")",
")",
";",
"Simplex",
".",
"Noise",
".",
"Seed",
"=",
"Seed",
";",
"int",
"clusterId",
"=",
"0",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"(",
"int",
")",
"WorldSize",
";",
"x",
"+=",
"(",
"int",
")",
"Mathf",
".",
"Sqrt",
"(",
"(",
"int",
")",
"ClusterSize",
")",
")",
"{",
"for",
"(",
"int",
"z",
"=",
"0",
";",
"z",
"<",
"(",
"int",
")",
"WorldSize",
";",
"z",
"+=",
"(",
"int",
")",
"Mathf",
".",
"Sqrt",
"(",
"(",
"int",
")",
"ClusterSize",
")",
")",
"{",
"GameObject",
"cluster",
"=",
"new",
"GameObject",
"(",
")",
";",
"cluster",
".",
"name",
"=",
"\"",
"Cluster ",
"\"",
"+",
"clusterId",
";",
"cluster",
".",
"transform",
".",
"SetParent",
"(",
"transform",
")",
";",
"cluster",
".",
"transform",
".",
"position",
"=",
"new",
"Vector3",
"(",
"x",
",",
"0.0f",
",",
"z",
")",
";",
"Cluster",
"clusterComponent",
"=",
"cluster",
".",
"AddComponent",
"<",
"Cluster",
">",
"(",
")",
";",
"clusterComponent",
".",
"ClusterId",
"=",
"clusterId",
";",
"clusterList",
".",
"Add",
"(",
"clusterId",
"++",
",",
"cluster",
")",
";",
"}",
"}",
"yield",
"return",
"new",
"WaitForEndOfFrame",
"(",
")",
";",
"foreach",
"(",
"GameObject",
"cluster",
"in",
"clusterList",
".",
"Values",
")",
"{",
"Vector3",
"clusterPosition",
"=",
"cluster",
".",
"transform",
".",
"position",
";",
"int",
"blockId",
"=",
"0",
";",
"for",
"(",
"int",
"x",
"=",
"0",
";",
"x",
"<",
"(",
"int",
")",
"Mathf",
".",
"Sqrt",
"(",
"(",
"int",
")",
"ClusterSize",
")",
";",
"++",
"x",
")",
"{",
"for",
"(",
"int",
"z",
"=",
"0",
";",
"z",
"<",
"(",
"int",
")",
"Mathf",
".",
"Sqrt",
"(",
"(",
"int",
")",
"ClusterSize",
")",
";",
"++",
"z",
")",
"{",
"float",
"noiseValue",
"=",
"Simplex",
".",
"Noise",
".",
"CalcPixel2D",
"(",
"(",
"int",
")",
"clusterPosition",
".",
"x",
"+",
"x",
",",
"(",
"int",
")",
"clusterPosition",
".",
"z",
"+",
"z",
",",
"0.02f",
")",
";",
"int",
"height",
"=",
"(",
"int",
")",
"noiseValue",
"/",
"(",
"int",
")",
"(",
"256.0f",
"/",
"(",
"float",
")",
"WorldType",
")",
";",
"int",
"materialIndex",
"=",
"(",
"int",
")",
"noiseValue",
"/",
"(",
"int",
")",
"(",
"256.0f",
"/",
"WorldMaterials",
".",
"Length",
")",
";",
"GameObject",
"block",
"=",
"GameObject",
".",
"CreatePrimitive",
"(",
"PrimitiveType",
".",
"Cube",
")",
";",
"block",
".",
"name",
"=",
"\"",
"Block ",
"\"",
"+",
"blockId",
";",
"block",
".",
"transform",
".",
"SetParent",
"(",
"cluster",
".",
"transform",
")",
";",
"block",
".",
"transform",
".",
"localScale",
"=",
"new",
"Vector3",
"(",
"1.0f",
",",
"height",
",",
"1.0f",
")",
";",
"block",
".",
"transform",
".",
"position",
"=",
"new",
"Vector3",
"(",
"clusterPosition",
".",
"x",
"+",
"x",
",",
"height",
"/",
"2.0f",
",",
"clusterPosition",
".",
"z",
"+",
"z",
")",
";",
"block",
".",
"GetComponent",
"<",
"MeshRenderer",
">",
"(",
")",
".",
"material",
"=",
"WorldMaterials",
"[",
"materialIndex",
"]",
";",
"Block",
"blockComponent",
"=",
"block",
".",
"AddComponent",
"<",
"Block",
">",
"(",
")",
";",
"blockComponent",
".",
"BlockId",
"=",
"blockId",
";",
"blockComponent",
".",
"ClusterId",
"=",
"cluster",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
".",
"ClusterId",
";",
"cluster",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
".",
"AddBlock",
"(",
"blockId",
"++",
",",
"block",
")",
";",
"}",
"}",
"yield",
"return",
"new",
"WaitForEndOfFrame",
"(",
")",
";",
"}",
"foreach",
"(",
"DictionaryEntry",
"entry",
"in",
"PhotonNetwork",
".",
"CurrentRoom",
".",
"CustomProperties",
")",
"{",
"if",
"(",
"entry",
".",
"Value",
"==",
"null",
")",
"{",
"continue",
";",
"}",
"string",
"key",
"=",
"entry",
".",
"Key",
".",
"ToString",
"(",
")",
";",
"if",
"(",
"(",
"key",
"==",
"SeedPropertiesKey",
")",
"||",
"(",
"key",
"==",
"WorldSizePropertiesKey",
")",
"||",
"(",
"key",
"==",
"ClusterSizePropertiesKey",
")",
"||",
"(",
"key",
"==",
"WorldTypePropertiesKey",
")",
")",
"{",
"continue",
";",
"}",
"int",
"indexOfBlank",
"=",
"key",
".",
"IndexOf",
"(",
"'",
" ",
"'",
")",
";",
"key",
"=",
"key",
".",
"Substring",
"(",
"indexOfBlank",
"+",
"1",
",",
"(",
"key",
".",
"Length",
"-",
"(",
"indexOfBlank",
"+",
"1",
")",
")",
")",
";",
"int",
".",
"TryParse",
"(",
"key",
",",
"out",
"clusterId",
")",
";",
"GameObject",
"cluster",
";",
"if",
"(",
"clusterList",
".",
"TryGetValue",
"(",
"clusterId",
",",
"out",
"cluster",
")",
")",
"{",
"Cluster",
"c",
"=",
"cluster",
".",
"GetComponent",
"<",
"Cluster",
">",
"(",
")",
";",
"if",
"(",
"c",
"!=",
"null",
")",
"{",
"Dictionary",
"<",
"int",
",",
"float",
">",
"clusterModifications",
"=",
"(",
"Dictionary",
"<",
"int",
",",
"float",
">",
")",
"entry",
".",
"Value",
";",
"foreach",
"(",
"KeyValuePair",
"<",
"int",
",",
"float",
">",
"pair",
"in",
"clusterModifications",
")",
"{",
"c",
".",
"SetBlockHeightRemote",
"(",
"pair",
".",
"Key",
",",
"pair",
".",
"Value",
")",
";",
"}",
"}",
"}",
"}",
"}",
"endregion",
"}"
] |
The World Generator creates a world based on four options the current MasterClient can set.
|
[
"The",
"World",
"Generator",
"creates",
"a",
"world",
"based",
"on",
"four",
"options",
"the",
"current",
"MasterClient",
"can",
"set",
"."
] |
[
"/// <summary>",
"/// Called whenever a client receives a Custom Room Properties update containing all necessary information for creating a world.",
"/// If there is currently a world generation process running, it will be stopped automatically.",
"/// Also if there is a world already existing, it will be destroyed before the new one gets created.",
"/// </summary>",
"/// <summary>",
"/// Destroys each Block from each Cluster before actually destroying the Cluster itself.",
"/// </summary>",
"/// <summary>",
"/// Whenever the 'Confirm' button on the Control Panel is clicked by the MasterClient,",
"/// the Room Properties will be updated with the settings he defined.",
"/// </summary>",
"/// <summary>",
"/// Decreases the height of a certain Block from a certain Cluster.",
"/// </summary>",
"/// <summary>",
"/// Increases the height of a certain Block from a certain Cluster.",
"/// </summary>",
"/// <summary>",
"/// Generates a new world based on the settings made either by the MasterClient on the ",
"/// Ingame Control Panel or after receiving the new settings from the Custom Room Properties update.",
"/// </summary>",
"// Instantiating all necessary clusters at their target position",
"// Instantiating all necessary blocks as a child of a certain cluster",
"// Applying modifications made to the world when joining the room later or while it is created"
] |
[
{
"param": "MonoBehaviour",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "MonoBehaviour",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 20
| 1,295
| 154
|
0a5f89256cae39b6ceefcacb50a8b021c0f6356c
|
wso2/wso2-openjpa
|
openjpa-kernel/src/main/java/org/apache/openjpa/datacache/ConcurrentDataCache.java
|
[
"Apache-2.0"
] |
Java
|
ConcurrentDataCache
|
/**
* A {@link DataCache} implementation that is optimized for concurrent
* access. When the cache fills up, values to remove from cache are chosen
* randomly. Due to race conditions, it is possible that a get call might not
* return a cached instance if that instance is being transferred between
* internal datastructures.
*
* @since 0.4.0
*/
|
A DataCache implementation that is optimized for concurrent
access. When the cache fills up, values to remove from cache are chosen
randomly. Due to race conditions, it is possible that a get call might not
return a cached instance if that instance is being transferred between
internal datastructures.
|
[
"A",
"DataCache",
"implementation",
"that",
"is",
"optimized",
"for",
"concurrent",
"access",
".",
"When",
"the",
"cache",
"fills",
"up",
"values",
"to",
"remove",
"from",
"cache",
"are",
"chosen",
"randomly",
".",
"Due",
"to",
"race",
"conditions",
"it",
"is",
"possible",
"that",
"a",
"get",
"call",
"might",
"not",
"return",
"a",
"cached",
"instance",
"if",
"that",
"instance",
"is",
"being",
"transferred",
"between",
"internal",
"datastructures",
"."
] |
public class ConcurrentDataCache
extends AbstractDataCache
implements RemoteCommitListener {
private static final Localizer _loc = Localizer.forPackage
(ConcurrentDataCache.class);
private CacheMap _cache;
private int _cacheSize = Integer.MIN_VALUE;
private int _softRefs = Integer.MIN_VALUE;
protected boolean _lru = false;
/**
* Returns the underlying {@link CacheMap} that this cache is using.
* This is not an unmodifiable view on the map, so care should be taken
* with this reference. Implementations should probably not modify the
* contents of the cache, but should only use this reference to
* obtain cache metrics.
*/
public CacheMap getCacheMap() {
return _cache;
}
/**
* Sets the maximum number of unpinned objects to keep hard
* references to. If the map contains more unpinned objects than
* <code>size</code>, then this method will result in the cache
* flushing old values.
*/
public void setCacheSize(int size) {
_cacheSize = size;
}
/**
* Returns the maximum number of unpinned objects to keep hard
* references to.
*/
public int getCacheSize() {
return _cache.getCacheSize();
}
/**
* Sets the maximum number of unpinned objects to keep soft
* references to. If the map contains more soft references than
* <code>size</code>, then this method will result in the cache
* flushing values.
*/
public void setSoftReferenceSize(int size) {
_softRefs = size;
}
/**
* Returns the maximum number of unpinned objects to keep soft
* references to. Defaults to <code>-1</code>.
*/
public int getSoftReferenceSize() {
return _cache.getSoftReferenceSize();
}
public void initialize(DataCacheManager mgr) {
super.initialize(mgr);
conf.getRemoteCommitEventManager().addInternalListener(this);
// Wait to instantiate _cache so that we know the proper value of _cache
_cache = newCacheMap();
if (_cacheSize != Integer.MIN_VALUE) {
_cache.setCacheSize(_cacheSize);
}
if (_softRefs != Integer.MIN_VALUE) {
_cache.setSoftReferenceSize(_softRefs);
}
}
public void unpinAll(Class<?> cls, boolean subs) {
if (log.isWarnEnabled())
log.warn(_loc.get("cache-class-unpin-all", getName()));
unpinAll(_cache.getPinnedKeys());
}
public void writeLock() {
_cache.writeLock();
}
public void writeUnlock() {
_cache.writeUnlock();
}
/**
* Return the map to use as an internal cache; entry expirations must
* invoke {@link AbstractDataCache#keyRemoved}.
*/
protected CacheMap newCacheMap() {
CacheMap res = new CacheMap(_lru) {
protected void entryRemoved(Object key, Object value, boolean expired) {
keyRemoved(key, expired);
}
};
return res;
}
protected DataCachePCData getInternal(Object key) {
return (DataCachePCData) _cache.get(key);
}
protected DataCachePCData putInternal(Object key, DataCachePCData pc) {
return (DataCachePCData) _cache.put(key, pc);
}
protected DataCachePCData removeInternal(Object key) {
return (DataCachePCData) _cache.remove(key);
}
protected void removeAllInternal(Class<?> cls, boolean subs) {
// The performance in this area can be improved upon, however it seems
// unlikely that this method will be called in a performance intensive
// environment. In any event applications can revert to the old behavior
// by simply calling removeAll().
_cache.clear();
}
protected void clearInternal() {
_cache.clear();
}
protected boolean pinInternal(Object key) {
return _cache.pin(key);
}
protected boolean unpinInternal(Object key) {
return _cache.unpin (key);
}
protected boolean recacheUpdates() {
return true;
}
public void setLru(boolean l) {
_lru = l;
}
public boolean getLru() {
return _lru;
}
}
|
[
"public",
"class",
"ConcurrentDataCache",
"extends",
"AbstractDataCache",
"implements",
"RemoteCommitListener",
"{",
"private",
"static",
"final",
"Localizer",
"_loc",
"=",
"Localizer",
".",
"forPackage",
"(",
"ConcurrentDataCache",
".",
"class",
")",
";",
"private",
"CacheMap",
"_cache",
";",
"private",
"int",
"_cacheSize",
"=",
"Integer",
".",
"MIN_VALUE",
";",
"private",
"int",
"_softRefs",
"=",
"Integer",
".",
"MIN_VALUE",
";",
"protected",
"boolean",
"_lru",
"=",
"false",
";",
"/**\n * Returns the underlying {@link CacheMap} that this cache is using.\n * This is not an unmodifiable view on the map, so care should be taken\n * with this reference. Implementations should probably not modify the\n * contents of the cache, but should only use this reference to\n * obtain cache metrics.\n */",
"public",
"CacheMap",
"getCacheMap",
"(",
")",
"{",
"return",
"_cache",
";",
"}",
"/**\n * Sets the maximum number of unpinned objects to keep hard\n * references to. If the map contains more unpinned objects than\n * <code>size</code>, then this method will result in the cache\n * flushing old values.\n */",
"public",
"void",
"setCacheSize",
"(",
"int",
"size",
")",
"{",
"_cacheSize",
"=",
"size",
";",
"}",
"/**\n * Returns the maximum number of unpinned objects to keep hard\n * references to.\n */",
"public",
"int",
"getCacheSize",
"(",
")",
"{",
"return",
"_cache",
".",
"getCacheSize",
"(",
")",
";",
"}",
"/**\n * Sets the maximum number of unpinned objects to keep soft\n * references to. If the map contains more soft references than\n * <code>size</code>, then this method will result in the cache\n * flushing values.\n */",
"public",
"void",
"setSoftReferenceSize",
"(",
"int",
"size",
")",
"{",
"_softRefs",
"=",
"size",
";",
"}",
"/**\n * Returns the maximum number of unpinned objects to keep soft\n * references to. Defaults to <code>-1</code>.\n */",
"public",
"int",
"getSoftReferenceSize",
"(",
")",
"{",
"return",
"_cache",
".",
"getSoftReferenceSize",
"(",
")",
";",
"}",
"public",
"void",
"initialize",
"(",
"DataCacheManager",
"mgr",
")",
"{",
"super",
".",
"initialize",
"(",
"mgr",
")",
";",
"conf",
".",
"getRemoteCommitEventManager",
"(",
")",
".",
"addInternalListener",
"(",
"this",
")",
";",
"_cache",
"=",
"newCacheMap",
"(",
")",
";",
"if",
"(",
"_cacheSize",
"!=",
"Integer",
".",
"MIN_VALUE",
")",
"{",
"_cache",
".",
"setCacheSize",
"(",
"_cacheSize",
")",
";",
"}",
"if",
"(",
"_softRefs",
"!=",
"Integer",
".",
"MIN_VALUE",
")",
"{",
"_cache",
".",
"setSoftReferenceSize",
"(",
"_softRefs",
")",
";",
"}",
"}",
"public",
"void",
"unpinAll",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"boolean",
"subs",
")",
"{",
"if",
"(",
"log",
".",
"isWarnEnabled",
"(",
")",
")",
"log",
".",
"warn",
"(",
"_loc",
".",
"get",
"(",
"\"",
"cache-class-unpin-all",
"\"",
",",
"getName",
"(",
")",
")",
")",
";",
"unpinAll",
"(",
"_cache",
".",
"getPinnedKeys",
"(",
")",
")",
";",
"}",
"public",
"void",
"writeLock",
"(",
")",
"{",
"_cache",
".",
"writeLock",
"(",
")",
";",
"}",
"public",
"void",
"writeUnlock",
"(",
")",
"{",
"_cache",
".",
"writeUnlock",
"(",
")",
";",
"}",
"/**\n * Return the map to use as an internal cache; entry expirations must\n * invoke {@link AbstractDataCache#keyRemoved}.\n */",
"protected",
"CacheMap",
"newCacheMap",
"(",
")",
"{",
"CacheMap",
"res",
"=",
"new",
"CacheMap",
"(",
"_lru",
")",
"{",
"protected",
"void",
"entryRemoved",
"(",
"Object",
"key",
",",
"Object",
"value",
",",
"boolean",
"expired",
")",
"{",
"keyRemoved",
"(",
"key",
",",
"expired",
")",
";",
"}",
"}",
";",
"return",
"res",
";",
"}",
"protected",
"DataCachePCData",
"getInternal",
"(",
"Object",
"key",
")",
"{",
"return",
"(",
"DataCachePCData",
")",
"_cache",
".",
"get",
"(",
"key",
")",
";",
"}",
"protected",
"DataCachePCData",
"putInternal",
"(",
"Object",
"key",
",",
"DataCachePCData",
"pc",
")",
"{",
"return",
"(",
"DataCachePCData",
")",
"_cache",
".",
"put",
"(",
"key",
",",
"pc",
")",
";",
"}",
"protected",
"DataCachePCData",
"removeInternal",
"(",
"Object",
"key",
")",
"{",
"return",
"(",
"DataCachePCData",
")",
"_cache",
".",
"remove",
"(",
"key",
")",
";",
"}",
"protected",
"void",
"removeAllInternal",
"(",
"Class",
"<",
"?",
">",
"cls",
",",
"boolean",
"subs",
")",
"{",
"_cache",
".",
"clear",
"(",
")",
";",
"}",
"protected",
"void",
"clearInternal",
"(",
")",
"{",
"_cache",
".",
"clear",
"(",
")",
";",
"}",
"protected",
"boolean",
"pinInternal",
"(",
"Object",
"key",
")",
"{",
"return",
"_cache",
".",
"pin",
"(",
"key",
")",
";",
"}",
"protected",
"boolean",
"unpinInternal",
"(",
"Object",
"key",
")",
"{",
"return",
"_cache",
".",
"unpin",
"(",
"key",
")",
";",
"}",
"protected",
"boolean",
"recacheUpdates",
"(",
")",
"{",
"return",
"true",
";",
"}",
"public",
"void",
"setLru",
"(",
"boolean",
"l",
")",
"{",
"_lru",
"=",
"l",
";",
"}",
"public",
"boolean",
"getLru",
"(",
")",
"{",
"return",
"_lru",
";",
"}",
"}"
] |
A {@link DataCache} implementation that is optimized for concurrent
access.
|
[
"A",
"{",
"@link",
"DataCache",
"}",
"implementation",
"that",
"is",
"optimized",
"for",
"concurrent",
"access",
"."
] |
[
"// Wait to instantiate _cache so that we know the proper value of _cache",
"// The performance in this area can be improved upon, however it seems",
"// unlikely that this method will be called in a performance intensive",
"// environment. In any event applications can revert to the old behavior",
"// by simply calling removeAll()."
] |
[
{
"param": "AbstractDataCache",
"type": null
},
{
"param": "RemoteCommitListener",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AbstractDataCache",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "RemoteCommitListener",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 949
| 80
|
608d833cccd9b6cdf487f343a0f64babd79843d3
|
larryworm1127/autocomplete
|
autocomplete/engine.py
|
[
"MIT"
] |
Python
|
MelodyAutocompleteEngine
|
An autocomplete engine that suggests melodies based on a few intervals.
The values stored are Melody objects, and the corresponding
prefix sequence for a Melody is its interval sequence.
Because the prefix is based only on interval sequence and not the
starting pitch or duration of the notes, it is possible for different
melodies to have the same prefix.
=== Attributes ===
autocompleter: An Autocompleter used by this engine.
|
An autocomplete engine that suggests melodies based on a few intervals.
The values stored are Melody objects, and the corresponding
prefix sequence for a Melody is its interval sequence.
Because the prefix is based only on interval sequence and not the
starting pitch or duration of the notes, it is possible for different
melodies to have the same prefix.
Attributes
autocompleter: An Autocompleter used by this engine.
|
[
"An",
"autocomplete",
"engine",
"that",
"suggests",
"melodies",
"based",
"on",
"a",
"few",
"intervals",
".",
"The",
"values",
"stored",
"are",
"Melody",
"objects",
"and",
"the",
"corresponding",
"prefix",
"sequence",
"for",
"a",
"Melody",
"is",
"its",
"interval",
"sequence",
".",
"Because",
"the",
"prefix",
"is",
"based",
"only",
"on",
"interval",
"sequence",
"and",
"not",
"the",
"starting",
"pitch",
"or",
"duration",
"of",
"the",
"notes",
"it",
"is",
"possible",
"for",
"different",
"melodies",
"to",
"have",
"the",
"same",
"prefix",
".",
"Attributes",
"autocompleter",
":",
"An",
"Autocompleter",
"used",
"by",
"this",
"engine",
"."
] |
class MelodyAutocompleteEngine:
"""An autocomplete engine that suggests melodies based on a few intervals.
The values stored are Melody objects, and the corresponding
prefix sequence for a Melody is its interval sequence.
Because the prefix is based only on interval sequence and not the
starting pitch or duration of the notes, it is possible for different
melodies to have the same prefix.
=== Attributes ===
autocompleter: An Autocompleter used by this engine.
"""
autocompleter: Autocompleter
def __init__(self, config: Dict[str, Any]) -> None:
"""Initialize this engine with the given configuration.
<config> is a dictionary consisting of the following keys:
- 'file': the path to a CSV file
- 'autocompleter': either the string 'simple' or 'compressed',
specifying which subclass of Autocompleter to use.
- 'weight_type': either 'sum' or 'average', which specifies the
weight type for the prefix tree.
Precondition:
The given file is a *CSV file* where each line has the following format:
- The first entry is the name of a melody (a string).
- The remaining entries are grouped into pairs (as in Assignment 1)
where the first number in each pair is a note pitch,
and the second number is the corresponding duration.
Each melody is be inserted into the Autocompleter with a weight of 1.
"""
with open(config['file'], encoding='utf8') as csvfile:
if config['autocompleter'] == 'simple':
self.autocompleter = SimplePrefixTree(config['weight_type'])
else:
self.autocompleter = CompressedPrefixTree(config['weight_type'])
reader = csv.reader(csvfile)
for line in reader:
# separate name from notes
name = line[0]
notes = line[1:]
# process notes in form of (pitch, duration)
notes_lst = []
for index in range(0, len(notes), 2):
note = notes[index]
duration = notes[index + 1]
if not (note == '' or duration == ''):
notes_lst.append((int(note), int(duration)))
# insert value into auto completer
value = Melody(name, notes_lst)
prefix = [notes_lst[i + 1][0] - notes_lst[i][0]
for i in range(len(notes_lst) - 1)]
self.autocompleter.insert(value, 1.0, prefix)
def autocomplete(self, prefix: List[int],
limit: Optional[int] = None) -> List[Tuple[Melody, float]]:
"""Return up to <limit> matches for the given interval sequence.
The return value is a list of tuples (melody, weight), and must be
ordered in non-increasing weight. (You can decide how to break ties.)
If limit is None, return *every* match for the given interval sequence.
Precondition:
limit is None or limit > 0
"""
value = self.autocompleter.autocomplete(prefix, limit)
return [(melody, weight) for melody, weight in value]
def remove(self, prefix: List[int]) -> None:
"""Remove all melodies that match the given interval sequence.
"""
self.autocompleter.remove(prefix)
|
[
"class",
"MelodyAutocompleteEngine",
":",
"autocompleter",
":",
"Autocompleter",
"def",
"__init__",
"(",
"self",
",",
"config",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"None",
":",
"\"\"\"Initialize this engine with the given configuration.\n\n <config> is a dictionary consisting of the following keys:\n - 'file': the path to a CSV file\n - 'autocompleter': either the string 'simple' or 'compressed',\n specifying which subclass of Autocompleter to use.\n - 'weight_type': either 'sum' or 'average', which specifies the\n weight type for the prefix tree.\n\n Precondition:\n The given file is a *CSV file* where each line has the following format:\n - The first entry is the name of a melody (a string).\n - The remaining entries are grouped into pairs (as in Assignment 1)\n where the first number in each pair is a note pitch,\n and the second number is the corresponding duration.\n\n Each melody is be inserted into the Autocompleter with a weight of 1.\n \"\"\"",
"with",
"open",
"(",
"config",
"[",
"'file'",
"]",
",",
"encoding",
"=",
"'utf8'",
")",
"as",
"csvfile",
":",
"if",
"config",
"[",
"'autocompleter'",
"]",
"==",
"'simple'",
":",
"self",
".",
"autocompleter",
"=",
"SimplePrefixTree",
"(",
"config",
"[",
"'weight_type'",
"]",
")",
"else",
":",
"self",
".",
"autocompleter",
"=",
"CompressedPrefixTree",
"(",
"config",
"[",
"'weight_type'",
"]",
")",
"reader",
"=",
"csv",
".",
"reader",
"(",
"csvfile",
")",
"for",
"line",
"in",
"reader",
":",
"name",
"=",
"line",
"[",
"0",
"]",
"notes",
"=",
"line",
"[",
"1",
":",
"]",
"notes_lst",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"notes",
")",
",",
"2",
")",
":",
"note",
"=",
"notes",
"[",
"index",
"]",
"duration",
"=",
"notes",
"[",
"index",
"+",
"1",
"]",
"if",
"not",
"(",
"note",
"==",
"''",
"or",
"duration",
"==",
"''",
")",
":",
"notes_lst",
".",
"append",
"(",
"(",
"int",
"(",
"note",
")",
",",
"int",
"(",
"duration",
")",
")",
")",
"value",
"=",
"Melody",
"(",
"name",
",",
"notes_lst",
")",
"prefix",
"=",
"[",
"notes_lst",
"[",
"i",
"+",
"1",
"]",
"[",
"0",
"]",
"-",
"notes_lst",
"[",
"i",
"]",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"notes_lst",
")",
"-",
"1",
")",
"]",
"self",
".",
"autocompleter",
".",
"insert",
"(",
"value",
",",
"1.0",
",",
"prefix",
")",
"def",
"autocomplete",
"(",
"self",
",",
"prefix",
":",
"List",
"[",
"int",
"]",
",",
"limit",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"List",
"[",
"Tuple",
"[",
"Melody",
",",
"float",
"]",
"]",
":",
"\"\"\"Return up to <limit> matches for the given interval sequence.\n\n The return value is a list of tuples (melody, weight), and must be\n ordered in non-increasing weight. (You can decide how to break ties.)\n\n If limit is None, return *every* match for the given interval sequence.\n\n Precondition:\n limit is None or limit > 0\n \"\"\"",
"value",
"=",
"self",
".",
"autocompleter",
".",
"autocomplete",
"(",
"prefix",
",",
"limit",
")",
"return",
"[",
"(",
"melody",
",",
"weight",
")",
"for",
"melody",
",",
"weight",
"in",
"value",
"]",
"def",
"remove",
"(",
"self",
",",
"prefix",
":",
"List",
"[",
"int",
"]",
")",
"->",
"None",
":",
"\"\"\"Remove all melodies that match the given interval sequence.\n \"\"\"",
"self",
".",
"autocompleter",
".",
"remove",
"(",
"prefix",
")"
] |
An autocomplete engine that suggests melodies based on a few intervals.
|
[
"An",
"autocomplete",
"engine",
"that",
"suggests",
"melodies",
"based",
"on",
"a",
"few",
"intervals",
"."
] |
[
"\"\"\"An autocomplete engine that suggests melodies based on a few intervals.\n\n The values stored are Melody objects, and the corresponding\n prefix sequence for a Melody is its interval sequence.\n\n Because the prefix is based only on interval sequence and not the\n starting pitch or duration of the notes, it is possible for different\n melodies to have the same prefix.\n\n === Attributes ===\n autocompleter: An Autocompleter used by this engine.\n \"\"\"",
"\"\"\"Initialize this engine with the given configuration.\n\n <config> is a dictionary consisting of the following keys:\n - 'file': the path to a CSV file\n - 'autocompleter': either the string 'simple' or 'compressed',\n specifying which subclass of Autocompleter to use.\n - 'weight_type': either 'sum' or 'average', which specifies the\n weight type for the prefix tree.\n\n Precondition:\n The given file is a *CSV file* where each line has the following format:\n - The first entry is the name of a melody (a string).\n - The remaining entries are grouped into pairs (as in Assignment 1)\n where the first number in each pair is a note pitch,\n and the second number is the corresponding duration.\n\n Each melody is be inserted into the Autocompleter with a weight of 1.\n \"\"\"",
"# separate name from notes",
"# process notes in form of (pitch, duration)",
"# insert value into auto completer",
"\"\"\"Return up to <limit> matches for the given interval sequence.\n\n The return value is a list of tuples (melody, weight), and must be\n ordered in non-increasing weight. (You can decide how to break ties.)\n\n If limit is None, return *every* match for the given interval sequence.\n\n Precondition:\n limit is None or limit > 0\n \"\"\"",
"\"\"\"Remove all melodies that match the given interval sequence.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 736
| 96
|
dd82c22d16f95fe954929932e08d802625a08d1e
|
17666349388/google-api-dotnet-client
|
Src/Generated/Google.Apis.Workflows.v1beta/Google.Apis.Workflows.v1beta.cs
|
[
"Apache-2.0"
] |
C#
|
ListRequest
|
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't
/// support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to
/// override the binding to use different resource name schemes, such as `users/operations`. To override
/// the binding, API services can add a binding such as `"/v1/{name=users}/operations"` to their service
/// configuration. For backwards compatibility, the default name includes the operations collection id,
/// however overriding users must ensure the name binding is the parent resource, without the operations
/// collection id.</summary>
|
Lists operations that match the specified filter in the request. If the server doesn't
support this method, it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to
override the binding to use different resource name schemes, such as `users/operations`. To override
the binding, API services can add a binding such as `"/v1/{name=users}/operations"` to their service
configuration. For backwards compatibility, the default name includes the operations collection id,
however overriding users must ensure the name binding is the parent resource, without the operations
collection id.
|
[
"Lists",
"operations",
"that",
"match",
"the",
"specified",
"filter",
"in",
"the",
"request",
".",
"If",
"the",
"server",
"doesn",
"'",
"t",
"support",
"this",
"method",
"it",
"returns",
"`",
"UNIMPLEMENTED",
"`",
".",
"NOTE",
":",
"the",
"`",
"name",
"`",
"binding",
"allows",
"API",
"services",
"to",
"override",
"the",
"binding",
"to",
"use",
"different",
"resource",
"name",
"schemes",
"such",
"as",
"`",
"users",
"/",
"operations",
"`",
".",
"To",
"override",
"the",
"binding",
"API",
"services",
"can",
"add",
"a",
"binding",
"such",
"as",
"`",
"\"",
"/",
"v1",
"/",
"{",
"name",
"=",
"users",
"}",
"/",
"operations",
"\"",
"`",
"to",
"their",
"service",
"configuration",
".",
"For",
"backwards",
"compatibility",
"the",
"default",
"name",
"includes",
"the",
"operations",
"collection",
"id",
"however",
"overriding",
"users",
"must",
"ensure",
"the",
"name",
"binding",
"is",
"the",
"parent",
"resource",
"without",
"the",
"operations",
"collection",
"id",
"."
] |
public class ListRequest : WorkflowsBaseServiceRequest<Google.Apis.Workflows.v1beta.Data.ListOperationsResponse>
{
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
public override string MethodName => "list";
public override string HttpMethod => "GET";
public override string RestPath => "v1beta/{+name}/operations";
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
|
[
"public",
"class",
"ListRequest",
":",
"WorkflowsBaseServiceRequest",
"<",
"Google",
".",
"Apis",
".",
"Workflows",
".",
"v1beta",
".",
"Data",
".",
"ListOperationsResponse",
">",
"{",
"public",
"ListRequest",
"(",
"Google",
".",
"Apis",
".",
"Services",
".",
"IClientService",
"service",
",",
"string",
"name",
")",
":",
"base",
"(",
"service",
")",
"{",
"Name",
"=",
"name",
";",
"InitParameters",
"(",
")",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"name",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"Name",
"{",
"get",
";",
"private",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"filter",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"string",
"Filter",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"pageSize",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"System",
".",
"Nullable",
"<",
"int",
">",
"PageSize",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"pageToken",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"string",
"PageToken",
"{",
"get",
";",
"set",
";",
"}",
"public",
"override",
"string",
"MethodName",
"=>",
"\"",
"list",
"\"",
";",
"public",
"override",
"string",
"HttpMethod",
"=>",
"\"",
"GET",
"\"",
";",
"public",
"override",
"string",
"RestPath",
"=>",
"\"",
"v1beta/{+name}/operations",
"\"",
";",
"protected",
"override",
"void",
"InitParameters",
"(",
")",
"{",
"base",
".",
"InitParameters",
"(",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"name",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"name",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"@\"^projects/[^/]+/locations/[^/]+$\"",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"filter",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"filter",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"pageSize",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"pageSize",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"pageToken",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"pageToken",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"}",
"}"
] |
Lists operations that match the specified filter in the request.
|
[
"Lists",
"operations",
"that",
"match",
"the",
"specified",
"filter",
"in",
"the",
"request",
"."
] |
[
"/// <summary>Constructs a new List request.</summary>",
"/// <summary>The name of the operation's parent resource.</summary>",
"/// <summary>The standard list filter.</summary>",
"/// <summary>The standard list page size.</summary>",
"/// <summary>The standard list page token.</summary>",
"/// <summary>Gets the method name.</summary>",
"/// <summary>Gets the HTTP method.</summary>",
"/// <summary>Gets the REST path.</summary>",
"/// <summary>Initializes List parameter list.</summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 440
| 133
|
fa63f58eeb6470c5948af5a212022dcef364db7e
|
timcu/exanpe-t5-lib
|
src/main/java/fr/exanpe/t5/lib/components/Tooltip.java
|
[
"Apache-2.0"
] |
Java
|
Tooltip
|
/**
* A <code>Tooltip</code> component.<br />
* The Tooltip component use different parameters to determine the message displayed to the user.<br />
* First, we look at the "message" parameter; if message is bound, the content is displayed from
* properties file.
* Then, we look if "blockId" parameter is bound. If so, the content of the Tooltip is displayed
* from the block identified with "blockId".
* Finally, if neither the "message" parameter, nor "blockId" parameter is bound, by convention, we
* use the message key consolidated from the tooltip id and the suffix "-tooltip".
* JavaScript : This component is bound to a class Exanpe.Tooltip.<br/>
* CSS : This component is bound to a class exanpe-tooltip.<br/>
*
* @author lguerin
*/
|
A Tooltip component.
The Tooltip component use different parameters to determine the message displayed to the user.
First, we look at the "message" parameter; if message is bound, the content is displayed from
properties file.
Then, we look if "blockId" parameter is bound. If so, the content of the Tooltip is displayed
from the block identified with "blockId".
@author lguerin
|
[
"A",
"Tooltip",
"component",
".",
"The",
"Tooltip",
"component",
"use",
"different",
"parameters",
"to",
"determine",
"the",
"message",
"displayed",
"to",
"the",
"user",
".",
"First",
"we",
"look",
"at",
"the",
"\"",
"message",
"\"",
"parameter",
";",
"if",
"message",
"is",
"bound",
"the",
"content",
"is",
"displayed",
"from",
"properties",
"file",
".",
"Then",
"we",
"look",
"if",
"\"",
"blockId",
"\"",
"parameter",
"is",
"bound",
".",
"If",
"so",
"the",
"content",
"of",
"the",
"Tooltip",
"is",
"displayed",
"from",
"the",
"block",
"identified",
"with",
"\"",
"blockId",
"\"",
".",
"@author",
"lguerin"
] |
@Import(library =
{ "${exanpe.yui2-base}/yahoo-dom-event/yahoo-dom-event.js", "${exanpe.yui2-base}/animation/animation-min.js", "${exanpe.yui2-base}/container/container-min.js",
"js/exanpe-t5-lib.js" }, stylesheet =
{ "css/exanpe-t5-lib-core.css", "${exanpe.asset-base}/css/exanpe-t5-lib-skin.css" })
public class Tooltip
{
/**
* Message used for displaying Tooltip content
*/
@Property
@Parameter(defaultPrefix = BindingConstants.MESSAGE, allowNull = false)
private String message;
/**
* The id of the {@link Block} used for displaying Tooltip content
*/
@Property
@Parameter(defaultPrefix = BindingConstants.LITERAL, allowNull = false)
private String blockId;
@Property
private boolean isBuildFromBlock;
@Property
private String uniqueId;
@Property
@SuppressWarnings("unused")
private Block textBlock;
/**
* The default suffix used by convention to get content message of the tooltip from properties
*/
private static final String TOOLTIP_DEFAULT_SUFFIX = "-tooltip";
@Inject
private ComponentResources resources;
@Inject
private ExanpeComponentService exanpeService;
@Environmental
private JavaScriptSupport javascriptSupport;
@SetupRender
void begin()
{
uniqueId = javascriptSupport.allocateClientId(resources);
isBuildFromBlock = resources.isBound("blockId") ? true : false;
if (isBuildFromBlock)
{
textBlock = resources.getContainer().getComponentResources().getBlock(blockId);
}
}
@AfterRender
void end()
{
JSONObject data = buildJSONData();
javascriptSupport.addInitializerCall("tooltipBuilder", data);
}
private JSONObject buildJSONData()
{
JSONObject data = new JSONObject();
data.accumulate("id", getClientId());
data.accumulate("context", getClientId());
// Force tooltip text if message param is bound
if (resources.isBound("message"))
{
data.accumulate("text", message);
}
if (!resources.isBound("blockId") && !resources.isBound("message"))
{
data.accumulate("text", exanpeService.getEscaladeMessage(resources, getClientId() + TOOLTIP_DEFAULT_SUFFIX));
}
return data;
}
public String getClientId()
{
return uniqueId;
}
}
|
[
"@",
"Import",
"(",
"library",
"=",
"{",
"\"",
"${exanpe.yui2-base}/yahoo-dom-event/yahoo-dom-event.js",
"\"",
",",
"\"",
"${exanpe.yui2-base}/animation/animation-min.js",
"\"",
",",
"\"",
"${exanpe.yui2-base}/container/container-min.js",
"\"",
",",
"\"",
"js/exanpe-t5-lib.js",
"\"",
"}",
",",
"stylesheet",
"=",
"{",
"\"",
"css/exanpe-t5-lib-core.css",
"\"",
",",
"\"",
"${exanpe.asset-base}/css/exanpe-t5-lib-skin.css",
"\"",
"}",
")",
"public",
"class",
"Tooltip",
"{",
"/**\n * Message used for displaying Tooltip content\n */",
"@",
"Property",
"@",
"Parameter",
"(",
"defaultPrefix",
"=",
"BindingConstants",
".",
"MESSAGE",
",",
"allowNull",
"=",
"false",
")",
"private",
"String",
"message",
";",
"/**\n * The id of the {@link Block} used for displaying Tooltip content\n */",
"@",
"Property",
"@",
"Parameter",
"(",
"defaultPrefix",
"=",
"BindingConstants",
".",
"LITERAL",
",",
"allowNull",
"=",
"false",
")",
"private",
"String",
"blockId",
";",
"@",
"Property",
"private",
"boolean",
"isBuildFromBlock",
";",
"@",
"Property",
"private",
"String",
"uniqueId",
";",
"@",
"Property",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"private",
"Block",
"textBlock",
";",
"/**\n * The default suffix used by convention to get content message of the tooltip from properties\n */",
"private",
"static",
"final",
"String",
"TOOLTIP_DEFAULT_SUFFIX",
"=",
"\"",
"-tooltip",
"\"",
";",
"@",
"Inject",
"private",
"ComponentResources",
"resources",
";",
"@",
"Inject",
"private",
"ExanpeComponentService",
"exanpeService",
";",
"@",
"Environmental",
"private",
"JavaScriptSupport",
"javascriptSupport",
";",
"@",
"SetupRender",
"void",
"begin",
"(",
")",
"{",
"uniqueId",
"=",
"javascriptSupport",
".",
"allocateClientId",
"(",
"resources",
")",
";",
"isBuildFromBlock",
"=",
"resources",
".",
"isBound",
"(",
"\"",
"blockId",
"\"",
")",
"?",
"true",
":",
"false",
";",
"if",
"(",
"isBuildFromBlock",
")",
"{",
"textBlock",
"=",
"resources",
".",
"getContainer",
"(",
")",
".",
"getComponentResources",
"(",
")",
".",
"getBlock",
"(",
"blockId",
")",
";",
"}",
"}",
"@",
"AfterRender",
"void",
"end",
"(",
")",
"{",
"JSONObject",
"data",
"=",
"buildJSONData",
"(",
")",
";",
"javascriptSupport",
".",
"addInitializerCall",
"(",
"\"",
"tooltipBuilder",
"\"",
",",
"data",
")",
";",
"}",
"private",
"JSONObject",
"buildJSONData",
"(",
")",
"{",
"JSONObject",
"data",
"=",
"new",
"JSONObject",
"(",
")",
";",
"data",
".",
"accumulate",
"(",
"\"",
"id",
"\"",
",",
"getClientId",
"(",
")",
")",
";",
"data",
".",
"accumulate",
"(",
"\"",
"context",
"\"",
",",
"getClientId",
"(",
")",
")",
";",
"if",
"(",
"resources",
".",
"isBound",
"(",
"\"",
"message",
"\"",
")",
")",
"{",
"data",
".",
"accumulate",
"(",
"\"",
"text",
"\"",
",",
"message",
")",
";",
"}",
"if",
"(",
"!",
"resources",
".",
"isBound",
"(",
"\"",
"blockId",
"\"",
")",
"&&",
"!",
"resources",
".",
"isBound",
"(",
"\"",
"message",
"\"",
")",
")",
"{",
"data",
".",
"accumulate",
"(",
"\"",
"text",
"\"",
",",
"exanpeService",
".",
"getEscaladeMessage",
"(",
"resources",
",",
"getClientId",
"(",
")",
"+",
"TOOLTIP_DEFAULT_SUFFIX",
")",
")",
";",
"}",
"return",
"data",
";",
"}",
"public",
"String",
"getClientId",
"(",
")",
"{",
"return",
"uniqueId",
";",
"}",
"}"
] |
A <code>Tooltip</code> component.<br />
The Tooltip component use different parameters to determine the message displayed to the user.<br />
First, we look at the "message" parameter; if message is bound, the content is displayed from
properties file.
|
[
"A",
"<code",
">",
"Tooltip<",
"/",
"code",
">",
"component",
".",
"<br",
"/",
">",
"The",
"Tooltip",
"component",
"use",
"different",
"parameters",
"to",
"determine",
"the",
"message",
"displayed",
"to",
"the",
"user",
".",
"<br",
"/",
">",
"First",
"we",
"look",
"at",
"the",
"\"",
"message",
"\"",
"parameter",
";",
"if",
"message",
"is",
"bound",
"the",
"content",
"is",
"displayed",
"from",
"properties",
"file",
"."
] |
[
"// Force tooltip text if message param is bound"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 535
| 180
|
ef64d1e5126843baac930d445cd820bc36daf87c
|
abock/runtime
|
src/installer/managed/Microsoft.NET.HostModel/AppHost/RetryUtil.cs
|
[
"MIT"
] |
C#
|
RetryUtil
|
/// <summary>
/// HostModel library implements several services for updating the AppHost DLL.
/// These updates involve multiple file open/close operations.
/// An Antivirus scanner may intercept in-between and lock the file,
/// causing the operations to fail with IO-Error.
/// So, the operations are retried a few times on failures such as
/// - IOException
/// - Failure with Win32 errors indicating file-lock
/// </summary>
|
HostModel library implements several services for updating the AppHost DLL.
These updates involve multiple file open/close operations.
An Antivirus scanner may intercept in-between and lock the file,
causing the operations to fail with IO-Error.
So, the operations are retried a few times on failures such as
IOException
Failure with Win32 errors indicating file-lock
|
[
"HostModel",
"library",
"implements",
"several",
"services",
"for",
"updating",
"the",
"AppHost",
"DLL",
".",
"These",
"updates",
"involve",
"multiple",
"file",
"open",
"/",
"close",
"operations",
".",
"An",
"Antivirus",
"scanner",
"may",
"intercept",
"in",
"-",
"between",
"and",
"lock",
"the",
"file",
"causing",
"the",
"operations",
"to",
"fail",
"with",
"IO",
"-",
"Error",
".",
"So",
"the",
"operations",
"are",
"retried",
"a",
"few",
"times",
"on",
"failures",
"such",
"as",
"IOException",
"Failure",
"with",
"Win32",
"errors",
"indicating",
"file",
"-",
"lock"
] |
public static class RetryUtil
{
public const int NumberOfRetries = 500;
public const int NumMilliSecondsToWait = 100;
public static void RetryOnIOError(Action func)
{
for (int i = 1; i <= NumberOfRetries; i++)
{
try
{
func();
break;
}
catch (IOException) when (i < NumberOfRetries)
{
Thread.Sleep(NumMilliSecondsToWait);
}
}
}
public static void RetryOnWin32Error(Action func)
{
bool IsWin32FileLockError(int hresult)
{
const int ErrorLockViolation = 33;
const int ErrorDriveLocked = 108;
int errorCode = hresult & 0xffff;
return errorCode == ErrorLockViolation || errorCode == ErrorDriveLocked;
}
for (int i = 1; i <= NumberOfRetries; i++)
{
try
{
func();
break;
}
catch (HResultException hrex)
when (i < NumberOfRetries && IsWin32FileLockError(hrex.Win32HResult))
{
Thread.Sleep(NumMilliSecondsToWait);
}
}
}
}
|
[
"public",
"static",
"class",
"RetryUtil",
"{",
"public",
"const",
"int",
"NumberOfRetries",
"=",
"500",
";",
"public",
"const",
"int",
"NumMilliSecondsToWait",
"=",
"100",
";",
"public",
"static",
"void",
"RetryOnIOError",
"(",
"Action",
"func",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"NumberOfRetries",
";",
"i",
"++",
")",
"{",
"try",
"{",
"func",
"(",
")",
";",
"break",
";",
"}",
"catch",
"(",
"IOException",
")",
"when",
"(",
"i",
"<",
"NumberOfRetries",
")",
"{",
"Thread",
".",
"Sleep",
"(",
"NumMilliSecondsToWait",
")",
";",
"}",
"}",
"}",
"public",
"static",
"void",
"RetryOnWin32Error",
"(",
"Action",
"func",
")",
"{",
"bool",
"IsWin32FileLockError",
"(",
"int",
"hresult",
")",
"{",
"const",
"int",
"ErrorLockViolation",
"=",
"33",
";",
"const",
"int",
"ErrorDriveLocked",
"=",
"108",
";",
"int",
"errorCode",
"=",
"hresult",
"&",
"0xffff",
";",
"return",
"errorCode",
"==",
"ErrorLockViolation",
"||",
"errorCode",
"==",
"ErrorDriveLocked",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<=",
"NumberOfRetries",
";",
"i",
"++",
")",
"{",
"try",
"{",
"func",
"(",
")",
";",
"break",
";",
"}",
"catch",
"(",
"HResultException",
"hrex",
")",
"when",
"(",
"i",
"<",
"NumberOfRetries",
"&&",
"IsWin32FileLockError",
"(",
"hrex",
".",
"Win32HResult",
")",
")",
"{",
"Thread",
".",
"Sleep",
"(",
"NumMilliSecondsToWait",
")",
";",
"}",
"}",
"}",
"}"
] |
HostModel library implements several services for updating the AppHost DLL.
|
[
"HostModel",
"library",
"implements",
"several",
"services",
"for",
"updating",
"the",
"AppHost",
"DLL",
"."
] |
[
"// Error codes are defined in winerror.h",
"// The error code is stored in the lowest 16 bits of the HResult"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 280
| 90
|
14879b4f5564895ad8ca94dff9016b4efe828dc5
|
one3chens/storm
|
storm-core/src/jvm/org/apache/storm/blobstore/BlobStore.java
|
[
"Apache-2.0"
] |
Java
|
BlobStore
|
/**
* Provides a way to store blobs that can be downloaded.
* Blobs must be able to be uploaded and listed from Nimbus,
* and downloaded from the Supervisors. It is a key value based
* store. Key being a string and value being the blob data.
*
* ACL checking must take place against the provided subject.
* If the blob store does not support Security it must validate
* that all ACLs set are always WORLD, everything.
*
* The users can upload their blobs through the blob store command
* line. The command line also allows us to update and delete blobs.
*
* Modifying the replication factor only works for HdfsBlobStore
* as for the LocalFsBlobStore the replication is dependent on
* the number of Nimbodes available.
*/
|
Provides a way to store blobs that can be downloaded.
Blobs must be able to be uploaded and listed from Nimbus,
and downloaded from the Supervisors. It is a key value based
store. Key being a string and value being the blob data.
ACL checking must take place against the provided subject.
If the blob store does not support Security it must validate
that all ACLs set are always WORLD, everything.
The users can upload their blobs through the blob store command
line. The command line also allows us to update and delete blobs.
Modifying the replication factor only works for HdfsBlobStore
as for the LocalFsBlobStore the replication is dependent on
the number of Nimbodes available.
|
[
"Provides",
"a",
"way",
"to",
"store",
"blobs",
"that",
"can",
"be",
"downloaded",
".",
"Blobs",
"must",
"be",
"able",
"to",
"be",
"uploaded",
"and",
"listed",
"from",
"Nimbus",
"and",
"downloaded",
"from",
"the",
"Supervisors",
".",
"It",
"is",
"a",
"key",
"value",
"based",
"store",
".",
"Key",
"being",
"a",
"string",
"and",
"value",
"being",
"the",
"blob",
"data",
".",
"ACL",
"checking",
"must",
"take",
"place",
"against",
"the",
"provided",
"subject",
".",
"If",
"the",
"blob",
"store",
"does",
"not",
"support",
"Security",
"it",
"must",
"validate",
"that",
"all",
"ACLs",
"set",
"are",
"always",
"WORLD",
"everything",
".",
"The",
"users",
"can",
"upload",
"their",
"blobs",
"through",
"the",
"blob",
"store",
"command",
"line",
".",
"The",
"command",
"line",
"also",
"allows",
"us",
"to",
"update",
"and",
"delete",
"blobs",
".",
"Modifying",
"the",
"replication",
"factor",
"only",
"works",
"for",
"HdfsBlobStore",
"as",
"for",
"the",
"LocalFsBlobStore",
"the",
"replication",
"is",
"dependent",
"on",
"the",
"number",
"of",
"Nimbodes",
"available",
"."
] |
public abstract class BlobStore implements Shutdownable {
private static final Logger LOG = LoggerFactory.getLogger(BlobStore.class);
private static final Pattern KEY_PATTERN = Pattern.compile("^[\\w \\t\\.:_-]+$");
protected static final String BASE_BLOBS_DIR_NAME = "blobs";
/**
* Allows us to initialize the blob store
* @param conf The storm configuration
* @param baseDir The directory path to store the blobs
* @param nimbusInfo Contains the nimbus host, port and leadership information.
*/
public abstract void prepare(Map conf, String baseDir, NimbusInfo nimbusInfo);
/**
* Creates the blob.
* @param key Key for the blob.
* @param meta Metadata which contains the acls information
* @param who Is the subject creating the blob.
* @return AtomicOutputStream returns a stream into which the data
* can be written.
* @throws AuthorizationException
* @throws KeyAlreadyExistsException
*/
public abstract AtomicOutputStream createBlob(String key, SettableBlobMeta meta, Subject who) throws AuthorizationException, KeyAlreadyExistsException;
/**
* Updates the blob data.
* @param key Key for the blob.
* @param who Is the subject having the write privilege for the blob.
* @return AtomicOutputStream returns a stream into which the data
* can be written.
* @throws AuthorizationException
* @throws KeyNotFoundException
*/
public abstract AtomicOutputStream updateBlob(String key, Subject who) throws AuthorizationException, KeyNotFoundException;
/**
* Gets the current version of metadata for a blob
* to be viewed by the user or downloaded by the supervisor.
* @param key Key for the blob.
* @param who Is the subject having the read privilege for the blob.
* @return AtomicOutputStream returns a stream into which the data
* can be written.
* @throws AuthorizationException
* @throws KeyNotFoundException
*/
public abstract ReadableBlobMeta getBlobMeta(String key, Subject who) throws AuthorizationException, KeyNotFoundException;
/**
* Sets the metadata with renewed acls for the blob.
* @param key Key for the blob.
* @param meta Metadata which contains the updated
* acls information.
* @param who Is the subject having the write privilege for the blob.
* @throws AuthorizationException
* @throws KeyNotFoundException
*/
public abstract void setBlobMeta(String key, SettableBlobMeta meta, Subject who) throws AuthorizationException, KeyNotFoundException;
/**
* Deletes the blob data and metadata.
* @param key Key for the blob.
* @param who Is the subject having write privilege for the blob.
* @throws AuthorizationException
* @throws KeyNotFoundException
*/
public abstract void deleteBlob(String key, Subject who) throws AuthorizationException, KeyNotFoundException;
/**
* Gets the InputStream to read the blob details
* @param key Key for the blob.
* @param who Is the subject having the read privilege for the blob.
* @return InputStreamWithMeta has the additional
* file length and version information.
* @throws AuthorizationException
* @throws KeyNotFoundException
*/
public abstract InputStreamWithMeta getBlob(String key, Subject who) throws AuthorizationException, KeyNotFoundException;
/**
* Returns an iterator with all the list of
* keys currently available on the blob store.
* @return Iterator<String>
*/
public abstract Iterator<String> listKeys();
/**
* Gets the replication factor of the blob.
* @param key Key for the blob.
* @param who Is the subject having the read privilege for the blob.
* @return BlobReplication object containing the
* replication factor for the blob.
* @throws Exception
*/
public abstract int getBlobReplication(String key, Subject who) throws Exception;
/**
* Modifies the replication factor of the blob.
* @param key Key for the blob.
* @param replication The replication factor the
* blob has to be set.
* @param who Is the subject having the update privilege for the blob
* @return BlobReplication object containing the
* updated replication factor for the blob.
* @throws AuthorizationException
* @throws KeyNotFoundException
* @throws IOException
*/
public abstract int updateBlobReplication(String key, int replication, Subject who) throws AuthorizationException, KeyNotFoundException, IOException;
/**
* Filters keys based on the KeyFilter
* passed as the argument.
* @param filter KeyFilter
* @param <R> Type
* @return Set of filtered keys
*/
public <R> Set<R> filterAndListKeys(KeyFilter<R> filter) {
Set<R> ret = new HashSet<R>();
Iterator<String> keys = listKeys();
while (keys.hasNext()) {
String key = keys.next();
R filtered = filter.filter(key);
if (filtered != null) {
ret.add(filtered);
}
}
return ret;
}
/**
* Validates key checking for potentially harmful patterns
* @param key Key for the blob.
*/
public static final void validateKey(String key) throws AuthorizationException {
if (StringUtils.isEmpty(key) || "..".equals(key) || ".".equals(key) || !KEY_PATTERN.matcher(key).matches()) {
LOG.error("'{}' does not appear to be valid {}", key, KEY_PATTERN);
throw new AuthorizationException(key+" does not appear to be a valid blob key");
}
}
/**
* Wrapper called to create the blob which contains
* the byte data
* @param key Key for the blob.
* @param data Byte data that needs to be uploaded.
* @param meta Metadata which contains the acls information
* @param who Is the subject creating the blob.
* @throws AuthorizationException
* @throws KeyAlreadyExistsException
* @throws IOException
*/
public void createBlob(String key, byte [] data, SettableBlobMeta meta, Subject who) throws AuthorizationException, KeyAlreadyExistsException, IOException {
AtomicOutputStream out = null;
try {
out = createBlob(key, meta, who);
out.write(data);
out.close();
out = null;
} finally {
if (out != null) {
out.cancel();
}
}
}
/**
* Wrapper called to create the blob which contains
* the byte data
* @param key Key for the blob.
* @param in InputStream from which the data is read to be
* written as a part of the blob.
* @param meta Metadata which contains the acls information
* @param who Is the subject creating the blob.
* @throws AuthorizationException
* @throws KeyAlreadyExistsException
* @throws IOException
*/
public void createBlob(String key, InputStream in, SettableBlobMeta meta, Subject who) throws AuthorizationException, KeyAlreadyExistsException, IOException {
AtomicOutputStream out = null;
try {
out = createBlob(key, meta, who);
byte[] buffer = new byte[2048];
int len = 0;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.close();
} catch (AuthorizationException | IOException | RuntimeException e) {
if (out !=null) {
out.cancel();
}
} finally {
in.close();
}
}
/**
* Reads the blob from the blob store
* and writes it into the output stream.
* @param key Key for the blob.
* @param out Output stream
* @param who Is the subject having read
* privilege for the blob.
* @throws IOException
* @throws KeyNotFoundException
* @throws AuthorizationException
*/
public void readBlobTo(String key, OutputStream out, Subject who) throws IOException, KeyNotFoundException, AuthorizationException {
InputStreamWithMeta in = getBlob(key, who);
if (in == null) {
throw new IOException("Could not find " + key);
}
byte[] buffer = new byte[2048];
int len = 0;
try{
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
} finally {
in.close();
out.flush();
}
}
/**
* Wrapper around readBlobTo which
* returns a ByteArray output stream.
* @param key Key for the blob.
* @param who Is the subject having
* the read privilege for the blob.
* @return ByteArrayOutputStream
* @throws IOException
* @throws KeyNotFoundException
* @throws AuthorizationException
*/
public byte[] readBlob(String key, Subject who) throws IOException, KeyNotFoundException, AuthorizationException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
readBlobTo(key, out, who);
byte[] bytes = out.toByteArray();
out.close();
return bytes;
}
/**
* Output stream implementation used for reading the
* metadata and data information.
*/
protected class BlobStoreFileOutputStream extends AtomicOutputStream {
private BlobStoreFile part;
private OutputStream out;
public BlobStoreFileOutputStream(BlobStoreFile part) throws IOException {
this.part = part;
this.out = part.getOutputStream();
}
@Override
public void close() throws IOException {
try {
//close means commit
out.close();
part.commit();
} catch (IOException | RuntimeException e) {
cancel();
throw e;
}
}
@Override
public void cancel() throws IOException {
try {
out.close();
} finally {
part.cancel();
}
}
@Override
public void write(int b) throws IOException {
out.write(b);
}
@Override
public void write(byte []b) throws IOException {
out.write(b);
}
@Override
public void write(byte []b, int offset, int len) throws IOException {
out.write(b, offset, len);
}
}
/**
* Input stream implementation used for writing
* both the metadata containing the acl information
* and the blob data.
*/
protected class BlobStoreFileInputStream extends InputStreamWithMeta {
private BlobStoreFile part;
private InputStream in;
public BlobStoreFileInputStream(BlobStoreFile part) throws IOException {
this.part = part;
this.in = part.getInputStream();
}
@Override
public long getVersion() throws IOException {
return part.getModTime();
}
@Override
public int read() throws IOException {
return in.read();
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return in.read(b, off, len);
}
@Override
public int read(byte[] b) throws IOException {
return in.read(b);
}
@Override
public int available() throws IOException {
return in.available();
}
@Override
public long getFileLength() throws IOException {
return part.getFileLength();
}
@Override
public void close() throws IOException {
in.close();
}
}
/**
* Blob store implements its own version of iterator
* to list the blobs
*/
public static class KeyTranslationIterator implements Iterator<String> {
private Iterator<String> it = null;
private String next = null;
private String prefix = null;
public KeyTranslationIterator(Iterator<String> it, String prefix) throws IOException {
this.it = it;
this.prefix = prefix;
primeNext();
}
private void primeNext() {
next = null;
while (it.hasNext()) {
String tmp = it.next();
if (tmp.startsWith(prefix)) {
next = tmp.substring(prefix.length());
return;
}
}
}
@Override
public boolean hasNext() {
return next != null;
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
String current = next;
primeNext();
return current;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Delete Not Supported");
}
}
}
|
[
"public",
"abstract",
"class",
"BlobStore",
"implements",
"Shutdownable",
"{",
"private",
"static",
"final",
"Logger",
"LOG",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"BlobStore",
".",
"class",
")",
";",
"private",
"static",
"final",
"Pattern",
"KEY_PATTERN",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"^[",
"\\\\",
"w ",
"\\\\",
"t",
"\\\\",
".:_-]+$",
"\"",
")",
";",
"protected",
"static",
"final",
"String",
"BASE_BLOBS_DIR_NAME",
"=",
"\"",
"blobs",
"\"",
";",
"/**\n * Allows us to initialize the blob store\n * @param conf The storm configuration\n * @param baseDir The directory path to store the blobs\n * @param nimbusInfo Contains the nimbus host, port and leadership information.\n */",
"public",
"abstract",
"void",
"prepare",
"(",
"Map",
"conf",
",",
"String",
"baseDir",
",",
"NimbusInfo",
"nimbusInfo",
")",
";",
"/**\n * Creates the blob.\n * @param key Key for the blob.\n * @param meta Metadata which contains the acls information\n * @param who Is the subject creating the blob.\n * @return AtomicOutputStream returns a stream into which the data\n * can be written.\n * @throws AuthorizationException\n * @throws KeyAlreadyExistsException\n */",
"public",
"abstract",
"AtomicOutputStream",
"createBlob",
"(",
"String",
"key",
",",
"SettableBlobMeta",
"meta",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyAlreadyExistsException",
";",
"/**\n * Updates the blob data.\n * @param key Key for the blob.\n * @param who Is the subject having the write privilege for the blob.\n * @return AtomicOutputStream returns a stream into which the data\n * can be written.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n */",
"public",
"abstract",
"AtomicOutputStream",
"updateBlob",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
";",
"/**\n * Gets the current version of metadata for a blob\n * to be viewed by the user or downloaded by the supervisor.\n * @param key Key for the blob.\n * @param who Is the subject having the read privilege for the blob.\n * @return AtomicOutputStream returns a stream into which the data\n * can be written.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n */",
"public",
"abstract",
"ReadableBlobMeta",
"getBlobMeta",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
";",
"/**\n * Sets the metadata with renewed acls for the blob.\n * @param key Key for the blob.\n * @param meta Metadata which contains the updated\n * acls information.\n * @param who Is the subject having the write privilege for the blob.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n */",
"public",
"abstract",
"void",
"setBlobMeta",
"(",
"String",
"key",
",",
"SettableBlobMeta",
"meta",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
";",
"/**\n * Deletes the blob data and metadata.\n * @param key Key for the blob.\n * @param who Is the subject having write privilege for the blob.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n */",
"public",
"abstract",
"void",
"deleteBlob",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
";",
"/**\n * Gets the InputStream to read the blob details\n * @param key Key for the blob.\n * @param who Is the subject having the read privilege for the blob.\n * @return InputStreamWithMeta has the additional\n * file length and version information.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n */",
"public",
"abstract",
"InputStreamWithMeta",
"getBlob",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
";",
"/**\n * Returns an iterator with all the list of\n * keys currently available on the blob store.\n * @return Iterator<String>\n */",
"public",
"abstract",
"Iterator",
"<",
"String",
">",
"listKeys",
"(",
")",
";",
"/**\n * Gets the replication factor of the blob.\n * @param key Key for the blob.\n * @param who Is the subject having the read privilege for the blob.\n * @return BlobReplication object containing the\n * replication factor for the blob.\n * @throws Exception\n */",
"public",
"abstract",
"int",
"getBlobReplication",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"Exception",
";",
"/**\n * Modifies the replication factor of the blob.\n * @param key Key for the blob.\n * @param replication The replication factor the\n * blob has to be set.\n * @param who Is the subject having the update privilege for the blob\n * @return BlobReplication object containing the\n * updated replication factor for the blob.\n * @throws AuthorizationException\n * @throws KeyNotFoundException\n * @throws IOException\n */",
"public",
"abstract",
"int",
"updateBlobReplication",
"(",
"String",
"key",
",",
"int",
"replication",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyNotFoundException",
",",
"IOException",
";",
"/**\n * Filters keys based on the KeyFilter\n * passed as the argument.\n * @param filter KeyFilter\n * @param <R> Type\n * @return Set of filtered keys\n */",
"public",
"<",
"R",
">",
"Set",
"<",
"R",
">",
"filterAndListKeys",
"(",
"KeyFilter",
"<",
"R",
">",
"filter",
")",
"{",
"Set",
"<",
"R",
">",
"ret",
"=",
"new",
"HashSet",
"<",
"R",
">",
"(",
")",
";",
"Iterator",
"<",
"String",
">",
"keys",
"=",
"listKeys",
"(",
")",
";",
"while",
"(",
"keys",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"key",
"=",
"keys",
".",
"next",
"(",
")",
";",
"R",
"filtered",
"=",
"filter",
".",
"filter",
"(",
"key",
")",
";",
"if",
"(",
"filtered",
"!=",
"null",
")",
"{",
"ret",
".",
"add",
"(",
"filtered",
")",
";",
"}",
"}",
"return",
"ret",
";",
"}",
"/**\n * Validates key checking for potentially harmful patterns\n * @param key Key for the blob.\n */",
"public",
"static",
"final",
"void",
"validateKey",
"(",
"String",
"key",
")",
"throws",
"AuthorizationException",
"{",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"key",
")",
"||",
"\"",
"..",
"\"",
".",
"equals",
"(",
"key",
")",
"||",
"\"",
".",
"\"",
".",
"equals",
"(",
"key",
")",
"||",
"!",
"KEY_PATTERN",
".",
"matcher",
"(",
"key",
")",
".",
"matches",
"(",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"\"",
"'{}' does not appear to be valid {}",
"\"",
",",
"key",
",",
"KEY_PATTERN",
")",
";",
"throw",
"new",
"AuthorizationException",
"(",
"key",
"+",
"\"",
" does not appear to be a valid blob key",
"\"",
")",
";",
"}",
"}",
"/**\n * Wrapper called to create the blob which contains\n * the byte data\n * @param key Key for the blob.\n * @param data Byte data that needs to be uploaded.\n * @param meta Metadata which contains the acls information\n * @param who Is the subject creating the blob.\n * @throws AuthorizationException\n * @throws KeyAlreadyExistsException\n * @throws IOException\n */",
"public",
"void",
"createBlob",
"(",
"String",
"key",
",",
"byte",
"[",
"]",
"data",
",",
"SettableBlobMeta",
"meta",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyAlreadyExistsException",
",",
"IOException",
"{",
"AtomicOutputStream",
"out",
"=",
"null",
";",
"try",
"{",
"out",
"=",
"createBlob",
"(",
"key",
",",
"meta",
",",
"who",
")",
";",
"out",
".",
"write",
"(",
"data",
")",
";",
"out",
".",
"close",
"(",
")",
";",
"out",
"=",
"null",
";",
"}",
"finally",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"out",
".",
"cancel",
"(",
")",
";",
"}",
"}",
"}",
"/**\n * Wrapper called to create the blob which contains\n * the byte data\n * @param key Key for the blob.\n * @param in InputStream from which the data is read to be\n * written as a part of the blob.\n * @param meta Metadata which contains the acls information\n * @param who Is the subject creating the blob.\n * @throws AuthorizationException\n * @throws KeyAlreadyExistsException\n * @throws IOException\n */",
"public",
"void",
"createBlob",
"(",
"String",
"key",
",",
"InputStream",
"in",
",",
"SettableBlobMeta",
"meta",
",",
"Subject",
"who",
")",
"throws",
"AuthorizationException",
",",
"KeyAlreadyExistsException",
",",
"IOException",
"{",
"AtomicOutputStream",
"out",
"=",
"null",
";",
"try",
"{",
"out",
"=",
"createBlob",
"(",
"key",
",",
"meta",
",",
"who",
")",
";",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"2048",
"]",
";",
"int",
"len",
"=",
"0",
";",
"while",
"(",
"(",
"len",
"=",
"in",
".",
"read",
"(",
"buffer",
")",
")",
">",
"0",
")",
"{",
"out",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"len",
")",
";",
"}",
"out",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"AuthorizationException",
"|",
"IOException",
"|",
"RuntimeException",
"e",
")",
"{",
"if",
"(",
"out",
"!=",
"null",
")",
"{",
"out",
".",
"cancel",
"(",
")",
";",
"}",
"}",
"finally",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"}",
"/**\n * Reads the blob from the blob store\n * and writes it into the output stream.\n * @param key Key for the blob.\n * @param out Output stream\n * @param who Is the subject having read\n * privilege for the blob.\n * @throws IOException\n * @throws KeyNotFoundException\n * @throws AuthorizationException\n */",
"public",
"void",
"readBlobTo",
"(",
"String",
"key",
",",
"OutputStream",
"out",
",",
"Subject",
"who",
")",
"throws",
"IOException",
",",
"KeyNotFoundException",
",",
"AuthorizationException",
"{",
"InputStreamWithMeta",
"in",
"=",
"getBlob",
"(",
"key",
",",
"who",
")",
";",
"if",
"(",
"in",
"==",
"null",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"",
"Could not find ",
"\"",
"+",
"key",
")",
";",
"}",
"byte",
"[",
"]",
"buffer",
"=",
"new",
"byte",
"[",
"2048",
"]",
";",
"int",
"len",
"=",
"0",
";",
"try",
"{",
"while",
"(",
"(",
"len",
"=",
"in",
".",
"read",
"(",
"buffer",
")",
")",
">",
"0",
")",
"{",
"out",
".",
"write",
"(",
"buffer",
",",
"0",
",",
"len",
")",
";",
"}",
"}",
"finally",
"{",
"in",
".",
"close",
"(",
")",
";",
"out",
".",
"flush",
"(",
")",
";",
"}",
"}",
"/**\n * Wrapper around readBlobTo which\n * returns a ByteArray output stream.\n * @param key Key for the blob.\n * @param who Is the subject having\n * the read privilege for the blob.\n * @return ByteArrayOutputStream\n * @throws IOException\n * @throws KeyNotFoundException\n * @throws AuthorizationException\n */",
"public",
"byte",
"[",
"]",
"readBlob",
"(",
"String",
"key",
",",
"Subject",
"who",
")",
"throws",
"IOException",
",",
"KeyNotFoundException",
",",
"AuthorizationException",
"{",
"ByteArrayOutputStream",
"out",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"readBlobTo",
"(",
"key",
",",
"out",
",",
"who",
")",
";",
"byte",
"[",
"]",
"bytes",
"=",
"out",
".",
"toByteArray",
"(",
")",
";",
"out",
".",
"close",
"(",
")",
";",
"return",
"bytes",
";",
"}",
"/**\n * Output stream implementation used for reading the\n * metadata and data information.\n */",
"protected",
"class",
"BlobStoreFileOutputStream",
"extends",
"AtomicOutputStream",
"{",
"private",
"BlobStoreFile",
"part",
";",
"private",
"OutputStream",
"out",
";",
"public",
"BlobStoreFileOutputStream",
"(",
"BlobStoreFile",
"part",
")",
"throws",
"IOException",
"{",
"this",
".",
"part",
"=",
"part",
";",
"this",
".",
"out",
"=",
"part",
".",
"getOutputStream",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"out",
".",
"close",
"(",
")",
";",
"part",
".",
"commit",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"|",
"RuntimeException",
"e",
")",
"{",
"cancel",
"(",
")",
";",
"throw",
"e",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"cancel",
"(",
")",
"throws",
"IOException",
"{",
"try",
"{",
"out",
".",
"close",
"(",
")",
";",
"}",
"finally",
"{",
"part",
".",
"cancel",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"int",
"b",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"b",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"byte",
"[",
"]",
"b",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"b",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"offset",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"b",
",",
"offset",
",",
"len",
")",
";",
"}",
"}",
"/**\n * Input stream implementation used for writing\n * both the metadata containing the acl information\n * and the blob data.\n */",
"protected",
"class",
"BlobStoreFileInputStream",
"extends",
"InputStreamWithMeta",
"{",
"private",
"BlobStoreFile",
"part",
";",
"private",
"InputStream",
"in",
";",
"public",
"BlobStoreFileInputStream",
"(",
"BlobStoreFile",
"part",
")",
"throws",
"IOException",
"{",
"this",
".",
"part",
"=",
"part",
";",
"this",
".",
"in",
"=",
"part",
".",
"getInputStream",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"long",
"getVersion",
"(",
")",
"throws",
"IOException",
"{",
"return",
"part",
".",
"getModTime",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"read",
"(",
")",
"throws",
"IOException",
"{",
"return",
"in",
".",
"read",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"read",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"return",
"in",
".",
"read",
"(",
"b",
",",
"off",
",",
"len",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"read",
"(",
"byte",
"[",
"]",
"b",
")",
"throws",
"IOException",
"{",
"return",
"in",
".",
"read",
"(",
"b",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"available",
"(",
")",
"throws",
"IOException",
"{",
"return",
"in",
".",
"available",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"long",
"getFileLength",
"(",
")",
"throws",
"IOException",
"{",
"return",
"part",
".",
"getFileLength",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"throws",
"IOException",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"}",
"/**\n * Blob store implements its own version of iterator\n * to list the blobs\n */",
"public",
"static",
"class",
"KeyTranslationIterator",
"implements",
"Iterator",
"<",
"String",
">",
"{",
"private",
"Iterator",
"<",
"String",
">",
"it",
"=",
"null",
";",
"private",
"String",
"next",
"=",
"null",
";",
"private",
"String",
"prefix",
"=",
"null",
";",
"public",
"KeyTranslationIterator",
"(",
"Iterator",
"<",
"String",
">",
"it",
",",
"String",
"prefix",
")",
"throws",
"IOException",
"{",
"this",
".",
"it",
"=",
"it",
";",
"this",
".",
"prefix",
"=",
"prefix",
";",
"primeNext",
"(",
")",
";",
"}",
"private",
"void",
"primeNext",
"(",
")",
"{",
"next",
"=",
"null",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"String",
"tmp",
"=",
"it",
".",
"next",
"(",
")",
";",
"if",
"(",
"tmp",
".",
"startsWith",
"(",
"prefix",
")",
")",
"{",
"next",
"=",
"tmp",
".",
"substring",
"(",
"prefix",
".",
"length",
"(",
")",
")",
";",
"return",
";",
"}",
"}",
"}",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"next",
"!=",
"null",
";",
"}",
"@",
"Override",
"public",
"String",
"next",
"(",
")",
"{",
"if",
"(",
"!",
"hasNext",
"(",
")",
")",
"{",
"throw",
"new",
"NoSuchElementException",
"(",
")",
";",
"}",
"String",
"current",
"=",
"next",
";",
"primeNext",
"(",
")",
";",
"return",
"current",
";",
"}",
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
"\"",
"Delete Not Supported",
"\"",
")",
";",
"}",
"}",
"}"
] |
Provides a way to store blobs that can be downloaded.
|
[
"Provides",
"a",
"way",
"to",
"store",
"blobs",
"that",
"can",
"be",
"downloaded",
"."
] |
[
"//close means commit"
] |
[
{
"param": "Shutdownable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Shutdownable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,653
| 161
|
90678a74d8a61cb6a1161c8b105f725256adbd52
|
designer-framework/spring-boot-starter-batch-plus
|
src/main/java/org/springframework/batch/item/excel/AbstractExcelItemReader.java
|
[
"Apache-2.0"
] |
Java
|
AbstractExcelItemReader
|
/**
* {@link org.springframework.batch.item.ItemReader} implementation to read an Excel
* file. It will read the file sheet for sheet and row for row. It is loosy based on
* the {@link org.springframework.batch.item.file.FlatFileItemReader}
*
* @param <T> the type
* @author Marten Deinum
* @since 0.5.0
*/
|
org.springframework.batch.item.ItemReader implementation to read an Excel
file. It will read the file sheet for sheet and row for row. It is loosy based on
the org.springframework.batch.item.file.FlatFileItemReader
@param the type
@author Marten Deinum
@since 0.5.0
|
[
"org",
".",
"springframework",
".",
"batch",
".",
"item",
".",
"ItemReader",
"implementation",
"to",
"read",
"an",
"Excel",
"file",
".",
"It",
"will",
"read",
"the",
"file",
"sheet",
"for",
"sheet",
"and",
"row",
"for",
"row",
".",
"It",
"is",
"loosy",
"based",
"on",
"the",
"org",
".",
"springframework",
".",
"batch",
".",
"item",
".",
"file",
".",
"FlatFileItemReader",
"@param",
"the",
"type",
"@author",
"Marten",
"Deinum",
"@since",
"0",
".",
"5",
".",
"0"
] |
public abstract class AbstractExcelItemReader<T> extends AbstractItemCountingItemStreamItemReader<T> implements
ResourceAwareItemReaderItemStream<T>, InitializingBean {
protected final Log logger = LogFactory.getLog(getClass());
private Resource resource;
private int linesToSkip = 0;
private int currentSheet = 0;
private RowMapper<T> rowMapper;
private RowCallbackHandler skippedRowsCallback;
private boolean noInput = false;
private boolean strict = true;
private RowSetFactory rowSetFactory = new DefaultRowSetFactory();
private RowSet rs;
public AbstractExcelItemReader() {
super();
setName(ClassUtils.getShortName(getClass()));
}
/**
* @return string corresponding to logical record according to
* {@link #setRowMapper(RowMapper)} (might span multiple rows in file).
*/
@Override
protected T doRead() throws Exception {
if (noInput || rs == null) {
return null;
}
if (rs.next()) {
try {
return rowMapper.mapRow(rs);
} catch (final Exception e) {
throw new ExcelFileParseException("Exception parsing Excel file.", e, resource.getDescription(),
rs.getMetaData().getSheetName(), rs.getCurrentRowIndex(), rs.getCurrentRow());
}
} else {
currentSheet++;
if (currentSheet >= getNumberOfSheets()) {
if (logger.isDebugEnabled()) {
logger.debug("No more sheets in '" + resource.getDescription() + "'.");
}
return null;
} else {
openSheet();
return doRead();
}
}
}
@Override
protected void doOpen() throws Exception {
Assert.notNull(resource, "Input resource must be set");
noInput = true;
if (!resource.exists()) {
if (strict) {
throw new IllegalStateException("Input resource must exist (reader is in 'strict' mode): "
+ resource);
}
logger.warn("Input resource does not exist '" + resource.getDescription() + "'.");
return;
}
if (!resource.isReadable()) {
if (strict) {
throw new IllegalStateException("Input resource must be readable (reader is in 'strict' mode): "
+ resource);
}
logger.warn("Input resource is not readable '" + resource.getDescription() + "'.");
return;
}
openExcelFile(resource);
openSheet();
noInput = false;
if (logger.isDebugEnabled()) {
logger.debug("Opened workbook [" + resource.getFilename() + "] with " + getNumberOfSheets() + " sheets.");
}
}
private void openSheet() {
final Sheet sheet = getSheet(currentSheet);
rs = rowSetFactory.create(sheet);
if (logger.isDebugEnabled()) {
logger.debug("Opening sheet " + sheet.getName() + ".");
}
for (int i = 0; i < linesToSkip; i++) {
if (rs.next() && skippedRowsCallback != null) {
skippedRowsCallback.handleRow(rs);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Openend sheet " + sheet.getName() + ", with " + sheet.getNumberOfRows() + " rows.");
}
}
/**
* Public setter for the input resource.
*
* @param resource the {@code Resource} pointing to the Excelfile
*/
@Override
public void setResource(final Resource resource) {
this.resource = resource;
}
@Override
public void afterPropertiesSet() throws Exception {
Assert.notNull(rowMapper, "RowMapper must be set");
}
/**
* Set the number of lines to skip. This number is applied to all worksheet
* in the excel file! default to 0
*
* @param linesToSkip number of lines to skip
*/
public void setLinesToSkip(final int linesToSkip) {
this.linesToSkip = linesToSkip;
}
/**
* @param sheet the sheet index
* @return the sheet or <code>null</code> when no sheet available.
*/
protected abstract Sheet getSheet(int sheet);
/**
* The number of sheets in the underlying workbook.
*
* @return the number of sheets.
*/
protected abstract int getNumberOfSheets();
/**
* @param resource {@code Resource} pointing to the Excel file to read
* @throws Exception when the Excel sheet cannot be accessed
*/
protected abstract void openExcelFile(Resource resource) throws Exception;
/**
* In strict mode the reader will throw an exception on
* {@link #open(org.springframework.batch.item.ExecutionContext)} if the input resource does not exist.
*
* @param strict true by default
*/
public void setStrict(final boolean strict) {
this.strict = strict;
}
/**
* Public setter for the {@code rowMapper}. Used to map a row read from the underlying Excel workbook.
*
* @param rowMapper the {@code RowMapper} to use.
*/
public void setRowMapper(final RowMapper<T> rowMapper) {
this.rowMapper = rowMapper;
}
/**
* Public setter for the <code>rowSetFactory</code>. Used to create a {@code RowSet} implemenation. By default the
* {@code DefaultRowSetFactory} is used.
*
* @param rowSetFactory the {@code RowSetFactory} to use.
*/
public void setRowSetFactory(RowSetFactory rowSetFactory) {
this.rowSetFactory = rowSetFactory;
}
/**
* @param skippedRowsCallback will be called for each one of the initial skipped lines before any items are read.
*/
public void setSkippedRowsCallback(final RowCallbackHandler skippedRowsCallback) {
this.skippedRowsCallback = skippedRowsCallback;
}
}
|
[
"public",
"abstract",
"class",
"AbstractExcelItemReader",
"<",
"T",
">",
"extends",
"AbstractItemCountingItemStreamItemReader",
"<",
"T",
">",
"implements",
"ResourceAwareItemReaderItemStream",
"<",
"T",
">",
",",
"InitializingBean",
"{",
"protected",
"final",
"Log",
"logger",
"=",
"LogFactory",
".",
"getLog",
"(",
"getClass",
"(",
")",
")",
";",
"private",
"Resource",
"resource",
";",
"private",
"int",
"linesToSkip",
"=",
"0",
";",
"private",
"int",
"currentSheet",
"=",
"0",
";",
"private",
"RowMapper",
"<",
"T",
">",
"rowMapper",
";",
"private",
"RowCallbackHandler",
"skippedRowsCallback",
";",
"private",
"boolean",
"noInput",
"=",
"false",
";",
"private",
"boolean",
"strict",
"=",
"true",
";",
"private",
"RowSetFactory",
"rowSetFactory",
"=",
"new",
"DefaultRowSetFactory",
"(",
")",
";",
"private",
"RowSet",
"rs",
";",
"public",
"AbstractExcelItemReader",
"(",
")",
"{",
"super",
"(",
")",
";",
"setName",
"(",
"ClassUtils",
".",
"getShortName",
"(",
"getClass",
"(",
")",
")",
")",
";",
"}",
"/**\n * @return string corresponding to logical record according to\n * {@link #setRowMapper(RowMapper)} (might span multiple rows in file).\n */",
"@",
"Override",
"protected",
"T",
"doRead",
"(",
")",
"throws",
"Exception",
"{",
"if",
"(",
"noInput",
"||",
"rs",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"if",
"(",
"rs",
".",
"next",
"(",
")",
")",
"{",
"try",
"{",
"return",
"rowMapper",
".",
"mapRow",
"(",
"rs",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ExcelFileParseException",
"(",
"\"",
"Exception parsing Excel file.",
"\"",
",",
"e",
",",
"resource",
".",
"getDescription",
"(",
")",
",",
"rs",
".",
"getMetaData",
"(",
")",
".",
"getSheetName",
"(",
")",
",",
"rs",
".",
"getCurrentRowIndex",
"(",
")",
",",
"rs",
".",
"getCurrentRow",
"(",
")",
")",
";",
"}",
"}",
"else",
"{",
"currentSheet",
"++",
";",
"if",
"(",
"currentSheet",
">=",
"getNumberOfSheets",
"(",
")",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"No more sheets in '",
"\"",
"+",
"resource",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'.",
"\"",
")",
";",
"}",
"return",
"null",
";",
"}",
"else",
"{",
"openSheet",
"(",
")",
";",
"return",
"doRead",
"(",
")",
";",
"}",
"}",
"}",
"@",
"Override",
"protected",
"void",
"doOpen",
"(",
")",
"throws",
"Exception",
"{",
"Assert",
".",
"notNull",
"(",
"resource",
",",
"\"",
"Input resource must be set",
"\"",
")",
";",
"noInput",
"=",
"true",
";",
"if",
"(",
"!",
"resource",
".",
"exists",
"(",
")",
")",
"{",
"if",
"(",
"strict",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"Input resource must exist (reader is in 'strict' mode): ",
"\"",
"+",
"resource",
")",
";",
"}",
"logger",
".",
"warn",
"(",
"\"",
"Input resource does not exist '",
"\"",
"+",
"resource",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'.",
"\"",
")",
";",
"return",
";",
"}",
"if",
"(",
"!",
"resource",
".",
"isReadable",
"(",
")",
")",
"{",
"if",
"(",
"strict",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"Input resource must be readable (reader is in 'strict' mode): ",
"\"",
"+",
"resource",
")",
";",
"}",
"logger",
".",
"warn",
"(",
"\"",
"Input resource is not readable '",
"\"",
"+",
"resource",
".",
"getDescription",
"(",
")",
"+",
"\"",
"'.",
"\"",
")",
";",
"return",
";",
"}",
"openExcelFile",
"(",
"resource",
")",
";",
"openSheet",
"(",
")",
";",
"noInput",
"=",
"false",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Opened workbook [",
"\"",
"+",
"resource",
".",
"getFilename",
"(",
")",
"+",
"\"",
"] with ",
"\"",
"+",
"getNumberOfSheets",
"(",
")",
"+",
"\"",
" sheets.",
"\"",
")",
";",
"}",
"}",
"private",
"void",
"openSheet",
"(",
")",
"{",
"final",
"Sheet",
"sheet",
"=",
"getSheet",
"(",
"currentSheet",
")",
";",
"rs",
"=",
"rowSetFactory",
".",
"create",
"(",
"sheet",
")",
";",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Opening sheet ",
"\"",
"+",
"sheet",
".",
"getName",
"(",
")",
"+",
"\"",
".",
"\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"linesToSkip",
";",
"i",
"++",
")",
"{",
"if",
"(",
"rs",
".",
"next",
"(",
")",
"&&",
"skippedRowsCallback",
"!=",
"null",
")",
"{",
"skippedRowsCallback",
".",
"handleRow",
"(",
"rs",
")",
";",
"}",
"}",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Openend sheet ",
"\"",
"+",
"sheet",
".",
"getName",
"(",
")",
"+",
"\"",
", with ",
"\"",
"+",
"sheet",
".",
"getNumberOfRows",
"(",
")",
"+",
"\"",
" rows.",
"\"",
")",
";",
"}",
"}",
"/**\n * Public setter for the input resource.\n *\n * @param resource the {@code Resource} pointing to the Excelfile\n */",
"@",
"Override",
"public",
"void",
"setResource",
"(",
"final",
"Resource",
"resource",
")",
"{",
"this",
".",
"resource",
"=",
"resource",
";",
"}",
"@",
"Override",
"public",
"void",
"afterPropertiesSet",
"(",
")",
"throws",
"Exception",
"{",
"Assert",
".",
"notNull",
"(",
"rowMapper",
",",
"\"",
"RowMapper must be set",
"\"",
")",
";",
"}",
"/**\n * Set the number of lines to skip. This number is applied to all worksheet\n * in the excel file! default to 0\n *\n * @param linesToSkip number of lines to skip\n */",
"public",
"void",
"setLinesToSkip",
"(",
"final",
"int",
"linesToSkip",
")",
"{",
"this",
".",
"linesToSkip",
"=",
"linesToSkip",
";",
"}",
"/**\n * @param sheet the sheet index\n * @return the sheet or <code>null</code> when no sheet available.\n */",
"protected",
"abstract",
"Sheet",
"getSheet",
"(",
"int",
"sheet",
")",
";",
"/**\n * The number of sheets in the underlying workbook.\n *\n * @return the number of sheets.\n */",
"protected",
"abstract",
"int",
"getNumberOfSheets",
"(",
")",
";",
"/**\n * @param resource {@code Resource} pointing to the Excel file to read\n * @throws Exception when the Excel sheet cannot be accessed\n */",
"protected",
"abstract",
"void",
"openExcelFile",
"(",
"Resource",
"resource",
")",
"throws",
"Exception",
";",
"/**\n * In strict mode the reader will throw an exception on\n * {@link #open(org.springframework.batch.item.ExecutionContext)} if the input resource does not exist.\n *\n * @param strict true by default\n */",
"public",
"void",
"setStrict",
"(",
"final",
"boolean",
"strict",
")",
"{",
"this",
".",
"strict",
"=",
"strict",
";",
"}",
"/**\n * Public setter for the {@code rowMapper}. Used to map a row read from the underlying Excel workbook.\n *\n * @param rowMapper the {@code RowMapper} to use.\n */",
"public",
"void",
"setRowMapper",
"(",
"final",
"RowMapper",
"<",
"T",
">",
"rowMapper",
")",
"{",
"this",
".",
"rowMapper",
"=",
"rowMapper",
";",
"}",
"/**\n * Public setter for the <code>rowSetFactory</code>. Used to create a {@code RowSet} implemenation. By default the\n * {@code DefaultRowSetFactory} is used.\n *\n * @param rowSetFactory the {@code RowSetFactory} to use.\n */",
"public",
"void",
"setRowSetFactory",
"(",
"RowSetFactory",
"rowSetFactory",
")",
"{",
"this",
".",
"rowSetFactory",
"=",
"rowSetFactory",
";",
"}",
"/**\n * @param skippedRowsCallback will be called for each one of the initial skipped lines before any items are read.\n */",
"public",
"void",
"setSkippedRowsCallback",
"(",
"final",
"RowCallbackHandler",
"skippedRowsCallback",
")",
"{",
"this",
".",
"skippedRowsCallback",
"=",
"skippedRowsCallback",
";",
"}",
"}"
] |
{@link org.springframework.batch.item.ItemReader} implementation to read an Excel
file.
|
[
"{",
"@link",
"org",
".",
"springframework",
".",
"batch",
".",
"item",
".",
"ItemReader",
"}",
"implementation",
"to",
"read",
"an",
"Excel",
"file",
"."
] |
[] |
[
{
"param": "ResourceAwareItemReaderItemStream<T>, InitializingBean",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ResourceAwareItemReaderItemStream<T>, InitializingBean",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,247
| 84
|
48ecbccc32989ecd17905ceb896a9d371058d511
|
tdonca/AOG_AR
|
Assets/HoloToolkit/Input/Scripts/Interactions/TapToPlace.cs
|
[
"MIT"
] |
C#
|
TapToPlace
|
/// <summary>
/// The TapToPlace class is a basic way to enable users to move objects
/// and place them on real world surfaces.
/// Put this script on the object you want to be able to move.
/// Users will be able to tap objects, gaze elsewhere, and perform the tap gesture again to place.
/// This script is used in conjunction with GazeManager, WorldAnchorManager, and SpatialMappingManager.
/// </summary>
|
The TapToPlace class is a basic way to enable users to move objects
and place them on real world surfaces.
Put this script on the object you want to be able to move.
Users will be able to tap objects, gaze elsewhere, and perform the tap gesture again to place.
This script is used in conjunction with GazeManager, WorldAnchorManager, and SpatialMappingManager.
|
[
"The",
"TapToPlace",
"class",
"is",
"a",
"basic",
"way",
"to",
"enable",
"users",
"to",
"move",
"objects",
"and",
"place",
"them",
"on",
"real",
"world",
"surfaces",
".",
"Put",
"this",
"script",
"on",
"the",
"object",
"you",
"want",
"to",
"be",
"able",
"to",
"move",
".",
"Users",
"will",
"be",
"able",
"to",
"tap",
"objects",
"gaze",
"elsewhere",
"and",
"perform",
"the",
"tap",
"gesture",
"again",
"to",
"place",
".",
"This",
"script",
"is",
"used",
"in",
"conjunction",
"with",
"GazeManager",
"WorldAnchorManager",
"and",
"SpatialMappingManager",
"."
] |
[RequireComponent(typeof(Collider))]
[RequireComponent(typeof(Interpolator))]
public class TapToPlace : MonoBehaviour, IInputClickHandler
{
[Tooltip("Distance from camera to keep the object while placing it.")]
public float DefaultGazeDistance = 2.0f;
[Tooltip("Supply a friendly name for the anchor as the key name for the WorldAnchorStore.")]
public string SavedAnchorFriendlyName = "SavedAnchorFriendlyName";
[Tooltip("Place parent on tap instead of current game object.")]
public bool PlaceParentOnTap;
[Tooltip("Specify the parent game object to be moved on tap, if the immediate parent is not desired.")]
public GameObject ParentGameObjectToPlace;
[Tooltip("Setting this to true will enable the user to move and place the object in the scene without needing to tap on the object. Useful when you want to place an object immediately.")]
public bool IsBeingPlaced;
[Tooltip("Setting this to true will allow this behavior to control the DrawMesh property on the spatial mapping.")]
public bool AllowMeshVisualizationControl = true;
private const int IgnoreRaycastLayer = 2;
private Interpolator interpolator;
private static Dictionary<GameObject, int> defaultLayersCache = new Dictionary<GameObject, int>();
protected virtual void Start()
{
if (WorldAnchorManager.Instance == null)
{
Debug.LogError("This script expects that you have a WorldAnchorManager component in your scene.");
}
if (WorldAnchorManager.Instance != null)
{
if (!IsBeingPlaced)
{
WorldAnchorManager.Instance.AttachAnchor(gameObject, SavedAnchorFriendlyName);
}
}
DetermineParent();
interpolator = PlaceParentOnTap
? ParentGameObjectToPlace.EnsureComponent<Interpolator>()
: gameObject.EnsureComponent<Interpolator>();
if (IsBeingPlaced)
{
HandlePlacement();
}
}
protected virtual void Update()
{
if (!IsBeingPlaced) { return; }
Vector3 headPosition = Camera.main.transform.position;
Vector3 gazeDirection = Camera.main.transform.forward;
RaycastHit hitInfo;
Vector3 placementPosition = SpatialMappingManager.Instance != null &&
Physics.Raycast(headPosition, gazeDirection, out hitInfo, 30.0f, SpatialMappingManager.Instance.LayerMask)
? hitInfo.point
: (GazeManager.Instance.HitObject == null
? GazeManager.Instance.GazeOrigin + GazeManager.Instance.GazeNormal * DefaultGazeDistance
: GazeManager.Instance.HitPosition);
if (PlaceParentOnTap)
{
placementPosition = ParentGameObjectToPlace.transform.position + (placementPosition - gameObject.transform.position);
}
interpolator.SetTargetPosition(placementPosition);
interpolator.SetTargetRotation(Quaternion.Euler(0, Camera.main.transform.localEulerAngles.y, 0));
}
public virtual void OnInputClicked(InputClickedEventData eventData)
{
IsBeingPlaced = !IsBeingPlaced;
HandlePlacement();
}
private void HandlePlacement()
{
if (IsBeingPlaced)
{
SetLayerRecursively(transform, useDefaultLayer: false);
InputManager.Instance.AddGlobalListener(gameObject);
if (AllowMeshVisualizationControl)
{
SpatialMappingManager.Instance.DrawVisualMeshes = true;
}
#if UNITY_WSA && !UNITY_EDITOR
WorldAnchorManager.Instance.RemoveAnchor(gameObject);
#endif
}
else
{
SetLayerRecursively(transform, useDefaultLayer: true);
defaultLayersCache.Clear();
InputManager.Instance.RemoveGlobalListener(gameObject);
if (AllowMeshVisualizationControl)
{
SpatialMappingManager.Instance.DrawVisualMeshes = false;
}
#if UNITY_WSA && !UNITY_EDITOR
WorldAnchorManager.Instance.AttachAnchor(gameObject, SavedAnchorFriendlyName);
#endif
}
}
private void DetermineParent()
{
if (!PlaceParentOnTap) { return; }
if (ParentGameObjectToPlace == null)
{
if (gameObject.transform.parent == null)
{
Debug.LogWarning("The selected GameObject has no parent.");
PlaceParentOnTap = false;
}
else
{
Debug.LogWarning("No parent specified. Using immediate parent instead: " + gameObject.transform.parent.gameObject.name);
ParentGameObjectToPlace = gameObject.transform.parent.gameObject;
}
}
if (ParentGameObjectToPlace != null && !gameObject.transform.IsChildOf(ParentGameObjectToPlace.transform))
{
Debug.LogWarning("The specified parent object is not a parent of this object.");
}
}
private static void SetLayerRecursively(Transform objectToSet, bool useDefaultLayer)
{
if (useDefaultLayer)
{
int defaultLayerId;
if (defaultLayersCache.TryGetValue(objectToSet.gameObject, out defaultLayerId))
{
objectToSet.gameObject.layer = defaultLayerId;
defaultLayersCache.Remove(objectToSet.gameObject);
}
}
else
{
defaultLayersCache.Add(objectToSet.gameObject, objectToSet.gameObject.layer);
objectToSet.gameObject.layer = IgnoreRaycastLayer;
}
for (int i = 0; i < objectToSet.childCount; i++)
{
SetLayerRecursively(objectToSet.GetChild(i), useDefaultLayer);
}
}
}
|
[
"[",
"RequireComponent",
"(",
"typeof",
"(",
"Collider",
")",
")",
"]",
"[",
"RequireComponent",
"(",
"typeof",
"(",
"Interpolator",
")",
")",
"]",
"public",
"class",
"TapToPlace",
":",
"MonoBehaviour",
",",
"IInputClickHandler",
"{",
"[",
"Tooltip",
"(",
"\"",
"Distance from camera to keep the object while placing it.",
"\"",
")",
"]",
"public",
"float",
"DefaultGazeDistance",
"=",
"2.0f",
";",
"[",
"Tooltip",
"(",
"\"",
"Supply a friendly name for the anchor as the key name for the WorldAnchorStore.",
"\"",
")",
"]",
"public",
"string",
"SavedAnchorFriendlyName",
"=",
"\"",
"SavedAnchorFriendlyName",
"\"",
";",
"[",
"Tooltip",
"(",
"\"",
"Place parent on tap instead of current game object.",
"\"",
")",
"]",
"public",
"bool",
"PlaceParentOnTap",
";",
"[",
"Tooltip",
"(",
"\"",
"Specify the parent game object to be moved on tap, if the immediate parent is not desired.",
"\"",
")",
"]",
"public",
"GameObject",
"ParentGameObjectToPlace",
";",
"[",
"Tooltip",
"(",
"\"",
"Setting this to true will enable the user to move and place the object in the scene without needing to tap on the object. Useful when you want to place an object immediately.",
"\"",
")",
"]",
"public",
"bool",
"IsBeingPlaced",
";",
"[",
"Tooltip",
"(",
"\"",
"Setting this to true will allow this behavior to control the DrawMesh property on the spatial mapping.",
"\"",
")",
"]",
"public",
"bool",
"AllowMeshVisualizationControl",
"=",
"true",
";",
"private",
"const",
"int",
"IgnoreRaycastLayer",
"=",
"2",
";",
"private",
"Interpolator",
"interpolator",
";",
"private",
"static",
"Dictionary",
"<",
"GameObject",
",",
"int",
">",
"defaultLayersCache",
"=",
"new",
"Dictionary",
"<",
"GameObject",
",",
"int",
">",
"(",
")",
";",
"protected",
"virtual",
"void",
"Start",
"(",
")",
"{",
"if",
"(",
"WorldAnchorManager",
".",
"Instance",
"==",
"null",
")",
"{",
"Debug",
".",
"LogError",
"(",
"\"",
"This script expects that you have a WorldAnchorManager component in your scene.",
"\"",
")",
";",
"}",
"if",
"(",
"WorldAnchorManager",
".",
"Instance",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"IsBeingPlaced",
")",
"{",
"WorldAnchorManager",
".",
"Instance",
".",
"AttachAnchor",
"(",
"gameObject",
",",
"SavedAnchorFriendlyName",
")",
";",
"}",
"}",
"DetermineParent",
"(",
")",
";",
"interpolator",
"=",
"PlaceParentOnTap",
"?",
"ParentGameObjectToPlace",
".",
"EnsureComponent",
"<",
"Interpolator",
">",
"(",
")",
":",
"gameObject",
".",
"EnsureComponent",
"<",
"Interpolator",
">",
"(",
")",
";",
"if",
"(",
"IsBeingPlaced",
")",
"{",
"HandlePlacement",
"(",
")",
";",
"}",
"}",
"protected",
"virtual",
"void",
"Update",
"(",
")",
"{",
"if",
"(",
"!",
"IsBeingPlaced",
")",
"{",
"return",
";",
"}",
"Vector3",
"headPosition",
"=",
"Camera",
".",
"main",
".",
"transform",
".",
"position",
";",
"Vector3",
"gazeDirection",
"=",
"Camera",
".",
"main",
".",
"transform",
".",
"forward",
";",
"RaycastHit",
"hitInfo",
";",
"Vector3",
"placementPosition",
"=",
"SpatialMappingManager",
".",
"Instance",
"!=",
"null",
"&&",
"Physics",
".",
"Raycast",
"(",
"headPosition",
",",
"gazeDirection",
",",
"out",
"hitInfo",
",",
"30.0f",
",",
"SpatialMappingManager",
".",
"Instance",
".",
"LayerMask",
")",
"?",
"hitInfo",
".",
"point",
":",
"(",
"GazeManager",
".",
"Instance",
".",
"HitObject",
"==",
"null",
"?",
"GazeManager",
".",
"Instance",
".",
"GazeOrigin",
"+",
"GazeManager",
".",
"Instance",
".",
"GazeNormal",
"*",
"DefaultGazeDistance",
":",
"GazeManager",
".",
"Instance",
".",
"HitPosition",
")",
";",
"if",
"(",
"PlaceParentOnTap",
")",
"{",
"placementPosition",
"=",
"ParentGameObjectToPlace",
".",
"transform",
".",
"position",
"+",
"(",
"placementPosition",
"-",
"gameObject",
".",
"transform",
".",
"position",
")",
";",
"}",
"interpolator",
".",
"SetTargetPosition",
"(",
"placementPosition",
")",
";",
"interpolator",
".",
"SetTargetRotation",
"(",
"Quaternion",
".",
"Euler",
"(",
"0",
",",
"Camera",
".",
"main",
".",
"transform",
".",
"localEulerAngles",
".",
"y",
",",
"0",
")",
")",
";",
"}",
"public",
"virtual",
"void",
"OnInputClicked",
"(",
"InputClickedEventData",
"eventData",
")",
"{",
"IsBeingPlaced",
"=",
"!",
"IsBeingPlaced",
";",
"HandlePlacement",
"(",
")",
";",
"}",
"private",
"void",
"HandlePlacement",
"(",
")",
"{",
"if",
"(",
"IsBeingPlaced",
")",
"{",
"SetLayerRecursively",
"(",
"transform",
",",
"useDefaultLayer",
":",
"false",
")",
";",
"InputManager",
".",
"Instance",
".",
"AddGlobalListener",
"(",
"gameObject",
")",
";",
"if",
"(",
"AllowMeshVisualizationControl",
")",
"{",
"SpatialMappingManager",
".",
"Instance",
".",
"DrawVisualMeshes",
"=",
"true",
";",
"}",
"if",
"UNITY_WSA",
"&&",
"!",
"UNITY_EDITOR",
"WorldAnchorManager",
".",
"Instance",
".",
"RemoveAnchor",
"(",
"gameObject",
")",
";",
"endif",
"}",
"else",
"{",
"SetLayerRecursively",
"(",
"transform",
",",
"useDefaultLayer",
":",
"true",
")",
";",
"defaultLayersCache",
".",
"Clear",
"(",
")",
";",
"InputManager",
".",
"Instance",
".",
"RemoveGlobalListener",
"(",
"gameObject",
")",
";",
"if",
"(",
"AllowMeshVisualizationControl",
")",
"{",
"SpatialMappingManager",
".",
"Instance",
".",
"DrawVisualMeshes",
"=",
"false",
";",
"}",
"if",
"UNITY_WSA",
"&&",
"!",
"UNITY_EDITOR",
"WorldAnchorManager",
".",
"Instance",
".",
"AttachAnchor",
"(",
"gameObject",
",",
"SavedAnchorFriendlyName",
")",
";",
"endif",
"}",
"}",
"private",
"void",
"DetermineParent",
"(",
")",
"{",
"if",
"(",
"!",
"PlaceParentOnTap",
")",
"{",
"return",
";",
"}",
"if",
"(",
"ParentGameObjectToPlace",
"==",
"null",
")",
"{",
"if",
"(",
"gameObject",
".",
"transform",
".",
"parent",
"==",
"null",
")",
"{",
"Debug",
".",
"LogWarning",
"(",
"\"",
"The selected GameObject has no parent.",
"\"",
")",
";",
"PlaceParentOnTap",
"=",
"false",
";",
"}",
"else",
"{",
"Debug",
".",
"LogWarning",
"(",
"\"",
"No parent specified. Using immediate parent instead: ",
"\"",
"+",
"gameObject",
".",
"transform",
".",
"parent",
".",
"gameObject",
".",
"name",
")",
";",
"ParentGameObjectToPlace",
"=",
"gameObject",
".",
"transform",
".",
"parent",
".",
"gameObject",
";",
"}",
"}",
"if",
"(",
"ParentGameObjectToPlace",
"!=",
"null",
"&&",
"!",
"gameObject",
".",
"transform",
".",
"IsChildOf",
"(",
"ParentGameObjectToPlace",
".",
"transform",
")",
")",
"{",
"Debug",
".",
"LogWarning",
"(",
"\"",
"The specified parent object is not a parent of this object.",
"\"",
")",
";",
"}",
"}",
"private",
"static",
"void",
"SetLayerRecursively",
"(",
"Transform",
"objectToSet",
",",
"bool",
"useDefaultLayer",
")",
"{",
"if",
"(",
"useDefaultLayer",
")",
"{",
"int",
"defaultLayerId",
";",
"if",
"(",
"defaultLayersCache",
".",
"TryGetValue",
"(",
"objectToSet",
".",
"gameObject",
",",
"out",
"defaultLayerId",
")",
")",
"{",
"objectToSet",
".",
"gameObject",
".",
"layer",
"=",
"defaultLayerId",
";",
"defaultLayersCache",
".",
"Remove",
"(",
"objectToSet",
".",
"gameObject",
")",
";",
"}",
"}",
"else",
"{",
"defaultLayersCache",
".",
"Add",
"(",
"objectToSet",
".",
"gameObject",
",",
"objectToSet",
".",
"gameObject",
".",
"layer",
")",
";",
"objectToSet",
".",
"gameObject",
".",
"layer",
"=",
"IgnoreRaycastLayer",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"objectToSet",
".",
"childCount",
";",
"i",
"++",
")",
"{",
"SetLayerRecursively",
"(",
"objectToSet",
".",
"GetChild",
"(",
"i",
")",
",",
"useDefaultLayer",
")",
";",
"}",
"}",
"}"
] |
The TapToPlace class is a basic way to enable users to move objects
and place them on real world surfaces.
|
[
"The",
"TapToPlace",
"class",
"is",
"a",
"basic",
"way",
"to",
"enable",
"users",
"to",
"move",
"objects",
"and",
"place",
"them",
"on",
"real",
"world",
"surfaces",
"."
] |
[
"/// <summary>",
"/// Keeps track of if the user is moving the object or not.",
"/// Setting this to true will enable the user to move and place the object in the scene.",
"/// Useful when you want to place an object immediately.",
"/// </summary>",
"/// <summary>",
"/// The default ignore raycast layer built into unity.",
"/// </summary>",
"// Make sure we have all the components in the scene we need.",
"// If we are not starting out with actively placing the object, give it a World Anchor",
"// If we're using the spatial mapping, check to see if we got a hit, else use the gaze position.",
"// Here is where you might consider adding intelligence",
"// to how the object is placed. For example, consider",
"// placing based on the bottom of the object's",
"// collider so it sits properly on surfaces.",
"// update the placement to match the user's gaze.",
"// Rotate this object to face the user.",
"// On each tap gesture, toggle whether the user is in placing mode.",
"// If the user is in placing mode, display the spatial mapping mesh.",
"//Removes existing world anchor if any exist.",
"// Clear our cache in case we added or removed gameobjects between taps",
"// If the user is not in placing mode, hide the spatial mapping mesh.",
"// Add world anchor when object placement is done."
] |
[
{
"param": "MonoBehaviour",
"type": null
},
{
"param": "IInputClickHandler",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "MonoBehaviour",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "IInputClickHandler",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,110
| 92
|
5ff33b94bb33002cd2dd5b128671bff6ca3b5a41
|
loftwah/appscale
|
AppServer_Java/src/com/google/appengine/api/blobstore/BlobInfoFactory.java
|
[
"Apache-2.0"
] |
Java
|
BlobInfoFactory
|
/**
* {@code BlobInfoFactory} provides a trivial interface for retrieving
* {@link BlobInfo} metadata.
*
* <p>BlobInfo metadata is stored in read-only {@code __BlobInfo__}
* entities in the datastore. This class provides an easy way to
* access these entities. For more complex queries, you can use the
* datastore directly.
*
*/
|
BlobInfoFactory provides a trivial interface for retrieving
BlobInfo metadata.
BlobInfo metadata is stored in read-only __BlobInfo
entities in the datastore. This class provides an easy way to
access these entities. For more complex queries, you can use the
datastore directly.
|
[
"BlobInfoFactory",
"provides",
"a",
"trivial",
"interface",
"for",
"retrieving",
"BlobInfo",
"metadata",
".",
"BlobInfo",
"metadata",
"is",
"stored",
"in",
"read",
"-",
"only",
"__BlobInfo",
"entities",
"in",
"the",
"datastore",
".",
"This",
"class",
"provides",
"an",
"easy",
"way",
"to",
"access",
"these",
"entities",
".",
"For",
"more",
"complex",
"queries",
"you",
"can",
"use",
"the",
"datastore",
"directly",
"."
] |
public class BlobInfoFactory {
public static final String KIND = "__BlobInfo__";
public static final String CONTENT_TYPE = "content_type";
public static final String CREATION = "creation";
public static final String FILENAME = "filename";
public static final String SIZE = "size";
public static final String MD5_HASH = "md5_hash";
private final DatastoreService datastoreService;
/**
* Creates a {@code BlobInfoFactory} that uses the default
* implementation of {@link DatastoreService}.
*/
public BlobInfoFactory() {
this(DatastoreServiceFactory.getDatastoreService());
}
/**
* Creates a {@code BlobInfoFactory} with the specified
* implementation of {@link DatastoreService}.
*/
public BlobInfoFactory(DatastoreService datastoreService) {
this.datastoreService = datastoreService;
}
/**
* Loads the {@link BlobInfo} metadata for {@code blobKey}. Returns
* {@code null} if no matching blob is found.
*/
public BlobInfo loadBlobInfo(BlobKey blobKey) {
if (blobKey.getKeyString().contains(LocalBlobstoreService.GOOGLE_STORAGE_KEY_PREFIX))
return new BlobInfoStorage().loadGsFileInfo(blobKey);
try {
return createBlobInfo(datastoreService.get(getMetadataKeyForBlobKey(blobKey)));
} catch (EntityNotFoundException ex) {
return null;
}
}
/**
* Queries for {@link BlobInfo} instances, beginning with the {@link
* BlobKey} that appears first in lexicographic order.
*/
public Iterator<BlobInfo> queryBlobInfos() {
return queryBlobInfosAfter(null);
}
/**
* Queries for {@link BlobInfo} instances, beginning at the blob
* following {@code previousBlob} in lexicographic order. If {@code
* previousBlob} is null, the first blob will be returned.
*
* <p>This is useful for displaying discrete pages of blobs.
*/
public Iterator<BlobInfo> queryBlobInfosAfter(BlobKey previousBlob) {
String origNamespace = NamespaceManager.get();
Query query;
try {
NamespaceManager.set("");
query = new Query(KIND, null);
} finally {
NamespaceManager.set(origNamespace);
}
if (previousBlob != null) {
query.setFilter(new Query.FilterPredicate(
Entity.KEY_RESERVED_PROPERTY,
Query.FilterOperator.GREATER_THAN,
getMetadataKeyForBlobKey(previousBlob)));
}
final Iterator<Entity> parent = datastoreService.prepare(query).asIterator();
return new Iterator<BlobInfo>() {
@Override
public boolean hasNext() {
return parent.hasNext();
}
@Override
public BlobInfo next() {
return createBlobInfo(parent.next());
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Creates a {@link BlobInfo} by extracting content from the
* specified {@link Entity}.
*/
public BlobInfo createBlobInfo(Entity entity) {
if (entity.hasProperty(MD5_HASH)) {
return new BlobInfo(
new BlobKey(entity.getKey().getName()),
(String) entity.getProperty(CONTENT_TYPE),
(Date) entity.getProperty(CREATION),
(String) entity.getProperty(FILENAME),
(Long) entity.getProperty(SIZE),
(String) entity.getProperty(MD5_HASH));
} else {
return new BlobInfo(
new BlobKey(entity.getKey().getName()),
(String) entity.getProperty(CONTENT_TYPE),
(Date) entity.getProperty(CREATION),
(String) entity.getProperty(FILENAME),
(Long) entity.getProperty(SIZE));
}
}
private Key getMetadataKeyForBlobKey(BlobKey blobKey) {
String origNamespace = NamespaceManager.get();
try {
NamespaceManager.set("");
return KeyFactory.createKey(null, KIND, blobKey.getKeyString());
} finally {
NamespaceManager.set(origNamespace);
}
}
}
|
[
"public",
"class",
"BlobInfoFactory",
"{",
"public",
"static",
"final",
"String",
"KIND",
"=",
"\"",
"__BlobInfo__",
"\"",
";",
"public",
"static",
"final",
"String",
"CONTENT_TYPE",
"=",
"\"",
"content_type",
"\"",
";",
"public",
"static",
"final",
"String",
"CREATION",
"=",
"\"",
"creation",
"\"",
";",
"public",
"static",
"final",
"String",
"FILENAME",
"=",
"\"",
"filename",
"\"",
";",
"public",
"static",
"final",
"String",
"SIZE",
"=",
"\"",
"size",
"\"",
";",
"public",
"static",
"final",
"String",
"MD5_HASH",
"=",
"\"",
"md5_hash",
"\"",
";",
"private",
"final",
"DatastoreService",
"datastoreService",
";",
"/**\n * Creates a {@code BlobInfoFactory} that uses the default\n * implementation of {@link DatastoreService}.\n */",
"public",
"BlobInfoFactory",
"(",
")",
"{",
"this",
"(",
"DatastoreServiceFactory",
".",
"getDatastoreService",
"(",
")",
")",
";",
"}",
"/**\n * Creates a {@code BlobInfoFactory} with the specified\n * implementation of {@link DatastoreService}.\n */",
"public",
"BlobInfoFactory",
"(",
"DatastoreService",
"datastoreService",
")",
"{",
"this",
".",
"datastoreService",
"=",
"datastoreService",
";",
"}",
"/**\n * Loads the {@link BlobInfo} metadata for {@code blobKey}. Returns\n * {@code null} if no matching blob is found.\n */",
"public",
"BlobInfo",
"loadBlobInfo",
"(",
"BlobKey",
"blobKey",
")",
"{",
"if",
"(",
"blobKey",
".",
"getKeyString",
"(",
")",
".",
"contains",
"(",
"LocalBlobstoreService",
".",
"GOOGLE_STORAGE_KEY_PREFIX",
")",
")",
"return",
"new",
"BlobInfoStorage",
"(",
")",
".",
"loadGsFileInfo",
"(",
"blobKey",
")",
";",
"try",
"{",
"return",
"createBlobInfo",
"(",
"datastoreService",
".",
"get",
"(",
"getMetadataKeyForBlobKey",
"(",
"blobKey",
")",
")",
")",
";",
"}",
"catch",
"(",
"EntityNotFoundException",
"ex",
")",
"{",
"return",
"null",
";",
"}",
"}",
"/**\n * Queries for {@link BlobInfo} instances, beginning with the {@link\n * BlobKey} that appears first in lexicographic order.\n */",
"public",
"Iterator",
"<",
"BlobInfo",
">",
"queryBlobInfos",
"(",
")",
"{",
"return",
"queryBlobInfosAfter",
"(",
"null",
")",
";",
"}",
"/**\n * Queries for {@link BlobInfo} instances, beginning at the blob\n * following {@code previousBlob} in lexicographic order. If {@code\n * previousBlob} is null, the first blob will be returned.\n *\n * <p>This is useful for displaying discrete pages of blobs.\n */",
"public",
"Iterator",
"<",
"BlobInfo",
">",
"queryBlobInfosAfter",
"(",
"BlobKey",
"previousBlob",
")",
"{",
"String",
"origNamespace",
"=",
"NamespaceManager",
".",
"get",
"(",
")",
";",
"Query",
"query",
";",
"try",
"{",
"NamespaceManager",
".",
"set",
"(",
"\"",
"\"",
")",
";",
"query",
"=",
"new",
"Query",
"(",
"KIND",
",",
"null",
")",
";",
"}",
"finally",
"{",
"NamespaceManager",
".",
"set",
"(",
"origNamespace",
")",
";",
"}",
"if",
"(",
"previousBlob",
"!=",
"null",
")",
"{",
"query",
".",
"setFilter",
"(",
"new",
"Query",
".",
"FilterPredicate",
"(",
"Entity",
".",
"KEY_RESERVED_PROPERTY",
",",
"Query",
".",
"FilterOperator",
".",
"GREATER_THAN",
",",
"getMetadataKeyForBlobKey",
"(",
"previousBlob",
")",
")",
")",
";",
"}",
"final",
"Iterator",
"<",
"Entity",
">",
"parent",
"=",
"datastoreService",
".",
"prepare",
"(",
"query",
")",
".",
"asIterator",
"(",
")",
";",
"return",
"new",
"Iterator",
"<",
"BlobInfo",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"parent",
".",
"hasNext",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"BlobInfo",
"next",
"(",
")",
"{",
"return",
"createBlobInfo",
"(",
"parent",
".",
"next",
"(",
")",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"throw",
"new",
"UnsupportedOperationException",
"(",
")",
";",
"}",
"}",
";",
"}",
"/**\n * Creates a {@link BlobInfo} by extracting content from the\n * specified {@link Entity}.\n */",
"public",
"BlobInfo",
"createBlobInfo",
"(",
"Entity",
"entity",
")",
"{",
"if",
"(",
"entity",
".",
"hasProperty",
"(",
"MD5_HASH",
")",
")",
"{",
"return",
"new",
"BlobInfo",
"(",
"new",
"BlobKey",
"(",
"entity",
".",
"getKey",
"(",
")",
".",
"getName",
"(",
")",
")",
",",
"(",
"String",
")",
"entity",
".",
"getProperty",
"(",
"CONTENT_TYPE",
")",
",",
"(",
"Date",
")",
"entity",
".",
"getProperty",
"(",
"CREATION",
")",
",",
"(",
"String",
")",
"entity",
".",
"getProperty",
"(",
"FILENAME",
")",
",",
"(",
"Long",
")",
"entity",
".",
"getProperty",
"(",
"SIZE",
")",
",",
"(",
"String",
")",
"entity",
".",
"getProperty",
"(",
"MD5_HASH",
")",
")",
";",
"}",
"else",
"{",
"return",
"new",
"BlobInfo",
"(",
"new",
"BlobKey",
"(",
"entity",
".",
"getKey",
"(",
")",
".",
"getName",
"(",
")",
")",
",",
"(",
"String",
")",
"entity",
".",
"getProperty",
"(",
"CONTENT_TYPE",
")",
",",
"(",
"Date",
")",
"entity",
".",
"getProperty",
"(",
"CREATION",
")",
",",
"(",
"String",
")",
"entity",
".",
"getProperty",
"(",
"FILENAME",
")",
",",
"(",
"Long",
")",
"entity",
".",
"getProperty",
"(",
"SIZE",
")",
")",
";",
"}",
"}",
"private",
"Key",
"getMetadataKeyForBlobKey",
"(",
"BlobKey",
"blobKey",
")",
"{",
"String",
"origNamespace",
"=",
"NamespaceManager",
".",
"get",
"(",
")",
";",
"try",
"{",
"NamespaceManager",
".",
"set",
"(",
"\"",
"\"",
")",
";",
"return",
"KeyFactory",
".",
"createKey",
"(",
"null",
",",
"KIND",
",",
"blobKey",
".",
"getKeyString",
"(",
")",
")",
";",
"}",
"finally",
"{",
"NamespaceManager",
".",
"set",
"(",
"origNamespace",
")",
";",
"}",
"}",
"}"
] |
{@code BlobInfoFactory} provides a trivial interface for retrieving
{@link BlobInfo} metadata.
|
[
"{",
"@code",
"BlobInfoFactory",
"}",
"provides",
"a",
"trivial",
"interface",
"for",
"retrieving",
"{",
"@link",
"BlobInfo",
"}",
"metadata",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 859
| 80
|
fc70acb636c604c67502c5a77701f269bdc6cdcb
|
keNEticHEx/assemblyline-core
|
assemblyline_core/updater/run_updater.py
|
[
"MIT"
] |
Python
|
DockerUpdateInterface
|
Wrap docker interface for the commands used in the update process.
Volumes used for file updating on the docker interface are simply a host directory that gets
mounted at different depths and locations in each container.
FILE_UPDATE_VOLUME gives us the path of the directory on the host, so that we can mount
it properly on new containers we launch. FILE_UPDATE_DIRECTORY gives us the path
that it is mounted at in the update manager container.
|
Wrap docker interface for the commands used in the update process.
Volumes used for file updating on the docker interface are simply a host directory that gets
mounted at different depths and locations in each container.
FILE_UPDATE_VOLUME gives us the path of the directory on the host, so that we can mount
it properly on new containers we launch. FILE_UPDATE_DIRECTORY gives us the path
that it is mounted at in the update manager container.
|
[
"Wrap",
"docker",
"interface",
"for",
"the",
"commands",
"used",
"in",
"the",
"update",
"process",
".",
"Volumes",
"used",
"for",
"file",
"updating",
"on",
"the",
"docker",
"interface",
"are",
"simply",
"a",
"host",
"directory",
"that",
"gets",
"mounted",
"at",
"different",
"depths",
"and",
"locations",
"in",
"each",
"container",
".",
"FILE_UPDATE_VOLUME",
"gives",
"us",
"the",
"path",
"of",
"the",
"directory",
"on",
"the",
"host",
"so",
"that",
"we",
"can",
"mount",
"it",
"properly",
"on",
"new",
"containers",
"we",
"launch",
".",
"FILE_UPDATE_DIRECTORY",
"gives",
"us",
"the",
"path",
"that",
"it",
"is",
"mounted",
"at",
"in",
"the",
"update",
"manager",
"container",
"."
] |
class DockerUpdateInterface:
"""Wrap docker interface for the commands used in the update process.
Volumes used for file updating on the docker interface are simply a host directory that gets
mounted at different depths and locations in each container.
FILE_UPDATE_VOLUME gives us the path of the directory on the host, so that we can mount
it properly on new containers we launch. FILE_UPDATE_DIRECTORY gives us the path
that it is mounted at in the update manager container.
"""
def __init__(self, log_level="INFO"):
self.client = docker.from_env()
self._external_network = None
self.log_level = log_level
@property
def external_network(self):
"""Lazy load the external network information from docker.
In testing environments it may not exists, and we may not have docker socket anyway.
"""
if not self._external_network:
for network in self.client.networks.list(names=['external']):
self._external_network = network
break
else:
self._external_network = self.client.networks.create(name='external', internal=False)
return self._external_network
def launch(self, name, docker_config: DockerConfig, mounts, env, network, blocking: bool = True):
"""Run a container to completion."""
# Add the classification file if path is given
if CLASSIFICATION_HOST_PATH:
mounts.append({
'volume': CLASSIFICATION_HOST_PATH,
'source_path': '',
'dest_path': '/etc/assemblyline/classification.yml',
'mode': 'ro'
})
# Pull the image before we try to use it locally.
# This lets us override the auth_config on a per image basis.
# Split the image string into "[registry/]image_name" and "tag"
repository, _, tag = docker_config.image.rpartition(':')
if '/' in tag:
# if there is a '/' in the tag it is invalid. We have split ':' on a registry
# port not a tag, there can't be a tag in this image string. Put the registry
# string back together, and use a default tag
repository += ':' + tag
tag = 'latest'
# Add auth info if we have it
auth_config = None
if docker_config.registry_username or docker_config.registry_password:
auth_config = {
'username': docker_config.registry_username,
'password': docker_config.registry_password
}
self.client.images.pull(repository, tag, auth_config=auth_config)
# Launch container
container = self.client.containers.run(
image=docker_config.image,
name='update_' + name + '_' + uuid.uuid4().hex,
labels={'update_for': name, 'updater_launched': 'true'},
network=network,
restart_policy={'Name': 'no'},
command=docker_config.command,
volumes={os.path.join(row['volume'], row['source_path']): {'bind': row['dest_path'],
'mode': row.get('mode', 'rw')}
for row in mounts},
environment=[f'{_e.name}={_e.value}' for _e in docker_config.environment] +
[f'{k}={v}' for k, v in env.items()] +
[f'{name}={os.environ[name]}' for name in INHERITED_VARIABLES if name in os.environ] +
[f'LOG_LEVEL={self.log_level}'],
detach=True,
)
# Connect to extra networks
if docker_config.allow_internet_access:
self.external_network.connect(container)
# Wait for the container to terminate
if blocking:
container.wait()
def cleanup_stale(self):
# We want containers that are updater managed, already finished, and exited five minutes ago.
# The reason for the delay is in development systems people may want to check the output
# of failed update containers they are working on launching with the updater.
filters = {'label': 'updater_launched=true', 'status': 'exited'}
time_mark = isotime.now_as_iso(-60*5)
for container in self.client.containers.list(all=True, ignore_removed=True, filters=filters):
if container.attrs['State'].get('FinishedAt', '9999') < time_mark:
container.remove()
def restart(self, service_name):
for container in self.client.containers.list(filters={'label': f'component={service_name}'}):
container.kill()
|
[
"class",
"DockerUpdateInterface",
":",
"def",
"__init__",
"(",
"self",
",",
"log_level",
"=",
"\"INFO\"",
")",
":",
"self",
".",
"client",
"=",
"docker",
".",
"from_env",
"(",
")",
"self",
".",
"_external_network",
"=",
"None",
"self",
".",
"log_level",
"=",
"log_level",
"@",
"property",
"def",
"external_network",
"(",
"self",
")",
":",
"\"\"\"Lazy load the external network information from docker.\n\n In testing environments it may not exists, and we may not have docker socket anyway.\n \"\"\"",
"if",
"not",
"self",
".",
"_external_network",
":",
"for",
"network",
"in",
"self",
".",
"client",
".",
"networks",
".",
"list",
"(",
"names",
"=",
"[",
"'external'",
"]",
")",
":",
"self",
".",
"_external_network",
"=",
"network",
"break",
"else",
":",
"self",
".",
"_external_network",
"=",
"self",
".",
"client",
".",
"networks",
".",
"create",
"(",
"name",
"=",
"'external'",
",",
"internal",
"=",
"False",
")",
"return",
"self",
".",
"_external_network",
"def",
"launch",
"(",
"self",
",",
"name",
",",
"docker_config",
":",
"DockerConfig",
",",
"mounts",
",",
"env",
",",
"network",
",",
"blocking",
":",
"bool",
"=",
"True",
")",
":",
"\"\"\"Run a container to completion.\"\"\"",
"if",
"CLASSIFICATION_HOST_PATH",
":",
"mounts",
".",
"append",
"(",
"{",
"'volume'",
":",
"CLASSIFICATION_HOST_PATH",
",",
"'source_path'",
":",
"''",
",",
"'dest_path'",
":",
"'/etc/assemblyline/classification.yml'",
",",
"'mode'",
":",
"'ro'",
"}",
")",
"repository",
",",
"_",
",",
"tag",
"=",
"docker_config",
".",
"image",
".",
"rpartition",
"(",
"':'",
")",
"if",
"'/'",
"in",
"tag",
":",
"repository",
"+=",
"':'",
"+",
"tag",
"tag",
"=",
"'latest'",
"auth_config",
"=",
"None",
"if",
"docker_config",
".",
"registry_username",
"or",
"docker_config",
".",
"registry_password",
":",
"auth_config",
"=",
"{",
"'username'",
":",
"docker_config",
".",
"registry_username",
",",
"'password'",
":",
"docker_config",
".",
"registry_password",
"}",
"self",
".",
"client",
".",
"images",
".",
"pull",
"(",
"repository",
",",
"tag",
",",
"auth_config",
"=",
"auth_config",
")",
"container",
"=",
"self",
".",
"client",
".",
"containers",
".",
"run",
"(",
"image",
"=",
"docker_config",
".",
"image",
",",
"name",
"=",
"'update_'",
"+",
"name",
"+",
"'_'",
"+",
"uuid",
".",
"uuid4",
"(",
")",
".",
"hex",
",",
"labels",
"=",
"{",
"'update_for'",
":",
"name",
",",
"'updater_launched'",
":",
"'true'",
"}",
",",
"network",
"=",
"network",
",",
"restart_policy",
"=",
"{",
"'Name'",
":",
"'no'",
"}",
",",
"command",
"=",
"docker_config",
".",
"command",
",",
"volumes",
"=",
"{",
"os",
".",
"path",
".",
"join",
"(",
"row",
"[",
"'volume'",
"]",
",",
"row",
"[",
"'source_path'",
"]",
")",
":",
"{",
"'bind'",
":",
"row",
"[",
"'dest_path'",
"]",
",",
"'mode'",
":",
"row",
".",
"get",
"(",
"'mode'",
",",
"'rw'",
")",
"}",
"for",
"row",
"in",
"mounts",
"}",
",",
"environment",
"=",
"[",
"f'{_e.name}={_e.value}'",
"for",
"_e",
"in",
"docker_config",
".",
"environment",
"]",
"+",
"[",
"f'{k}={v}'",
"for",
"k",
",",
"v",
"in",
"env",
".",
"items",
"(",
")",
"]",
"+",
"[",
"f'{name}={os.environ[name]}'",
"for",
"name",
"in",
"INHERITED_VARIABLES",
"if",
"name",
"in",
"os",
".",
"environ",
"]",
"+",
"[",
"f'LOG_LEVEL={self.log_level}'",
"]",
",",
"detach",
"=",
"True",
",",
")",
"if",
"docker_config",
".",
"allow_internet_access",
":",
"self",
".",
"external_network",
".",
"connect",
"(",
"container",
")",
"if",
"blocking",
":",
"container",
".",
"wait",
"(",
")",
"def",
"cleanup_stale",
"(",
"self",
")",
":",
"filters",
"=",
"{",
"'label'",
":",
"'updater_launched=true'",
",",
"'status'",
":",
"'exited'",
"}",
"time_mark",
"=",
"isotime",
".",
"now_as_iso",
"(",
"-",
"60",
"*",
"5",
")",
"for",
"container",
"in",
"self",
".",
"client",
".",
"containers",
".",
"list",
"(",
"all",
"=",
"True",
",",
"ignore_removed",
"=",
"True",
",",
"filters",
"=",
"filters",
")",
":",
"if",
"container",
".",
"attrs",
"[",
"'State'",
"]",
".",
"get",
"(",
"'FinishedAt'",
",",
"'9999'",
")",
"<",
"time_mark",
":",
"container",
".",
"remove",
"(",
")",
"def",
"restart",
"(",
"self",
",",
"service_name",
")",
":",
"for",
"container",
"in",
"self",
".",
"client",
".",
"containers",
".",
"list",
"(",
"filters",
"=",
"{",
"'label'",
":",
"f'component={service_name}'",
"}",
")",
":",
"container",
".",
"kill",
"(",
")"
] |
Wrap docker interface for the commands used in the update process.
|
[
"Wrap",
"docker",
"interface",
"for",
"the",
"commands",
"used",
"in",
"the",
"update",
"process",
"."
] |
[
"\"\"\"Wrap docker interface for the commands used in the update process.\n\n Volumes used for file updating on the docker interface are simply a host directory that gets\n mounted at different depths and locations in each container.\n\n FILE_UPDATE_VOLUME gives us the path of the directory on the host, so that we can mount\n it properly on new containers we launch. FILE_UPDATE_DIRECTORY gives us the path\n that it is mounted at in the update manager container.\n \"\"\"",
"\"\"\"Lazy load the external network information from docker.\n\n In testing environments it may not exists, and we may not have docker socket anyway.\n \"\"\"",
"\"\"\"Run a container to completion.\"\"\"",
"# Add the classification file if path is given",
"# Pull the image before we try to use it locally.",
"# This lets us override the auth_config on a per image basis.",
"# Split the image string into \"[registry/]image_name\" and \"tag\"",
"# if there is a '/' in the tag it is invalid. We have split ':' on a registry",
"# port not a tag, there can't be a tag in this image string. Put the registry",
"# string back together, and use a default tag",
"# Add auth info if we have it",
"# Launch container",
"# Connect to extra networks",
"# Wait for the container to terminate",
"# We want containers that are updater managed, already finished, and exited five minutes ago.",
"# The reason for the delay is in development systems people may want to check the output",
"# of failed update containers they are working on launching with the updater."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 949
| 93
|
ad0cd617a405f34b0e68f3df609aa57dca7b82c3
|
danielogen/msc_research
|
selected projects/mobile/Signal-Android-4.60.5/app/src/main/java/org/thoughtcrime/securesms/util/views/AdaptiveActionsToolbar.java
|
[
"MIT"
] |
Java
|
AdaptiveActionsToolbar
|
/**
* AdaptiveActionsToolbar behaves like a normal {@link Toolbar} except in that it ignores the
* showAsAlways attributes of menu items added via menu inflation, opting for an adaptive algorithm
* instead. This algorithm will display as many icons as it can up to a specific percentage of the
* screen.
*
* Each ActionView icon is expected to occupy 48dp of space, including padding. Items are stacked one
* after the next with no margins.
*
* This view can be customized via attributes:
*
* aat_max_shown -- controls the max number of items to display.
* aat_percent_for_actions -- controls the max percent of screen width the buttons can occupy.
*/
|
AdaptiveActionsToolbar behaves like a normal Toolbar except in that it ignores the
showAsAlways attributes of menu items added via menu inflation, opting for an adaptive algorithm
instead. This algorithm will display as many icons as it can up to a specific percentage of the
screen.
Each ActionView icon is expected to occupy 48dp of space, including padding. Items are stacked one
after the next with no margins.
This view can be customized via attributes.
aat_max_shown -- controls the max number of items to display.
aat_percent_for_actions -- controls the max percent of screen width the buttons can occupy.
|
[
"AdaptiveActionsToolbar",
"behaves",
"like",
"a",
"normal",
"Toolbar",
"except",
"in",
"that",
"it",
"ignores",
"the",
"showAsAlways",
"attributes",
"of",
"menu",
"items",
"added",
"via",
"menu",
"inflation",
"opting",
"for",
"an",
"adaptive",
"algorithm",
"instead",
".",
"This",
"algorithm",
"will",
"display",
"as",
"many",
"icons",
"as",
"it",
"can",
"up",
"to",
"a",
"specific",
"percentage",
"of",
"the",
"screen",
".",
"Each",
"ActionView",
"icon",
"is",
"expected",
"to",
"occupy",
"48dp",
"of",
"space",
"including",
"padding",
".",
"Items",
"are",
"stacked",
"one",
"after",
"the",
"next",
"with",
"no",
"margins",
".",
"This",
"view",
"can",
"be",
"customized",
"via",
"attributes",
".",
"aat_max_shown",
"--",
"controls",
"the",
"max",
"number",
"of",
"items",
"to",
"display",
".",
"aat_percent_for_actions",
"--",
"controls",
"the",
"max",
"percent",
"of",
"screen",
"width",
"the",
"buttons",
"can",
"occupy",
"."
] |
public class AdaptiveActionsToolbar extends Toolbar {
private static final int NAVIGATION_DP = 56;
private static final int ACTION_VIEW_WIDTH_DP = 48;
private static final int OVERFLOW_VIEW_WIDTH_DP = 36;
private int maxShown;
public AdaptiveActionsToolbar(@NonNull Context context) {
this(context, null);
}
public AdaptiveActionsToolbar(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.toolbarStyle);
}
public AdaptiveActionsToolbar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.AdaptiveActionsToolbar);
maxShown = array.getInteger(R.styleable.AdaptiveActionsToolbar_aat_max_shown, 100);
array.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
adjustMenuActions(getMenu(), maxShown, getMeasuredWidth());
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public static void adjustMenuActions(@NonNull Menu menu, int maxToShow, int toolbarWidthPx) {
int menuSize = 0;
for (int i = 0; i < menu.size(); i++) {
if (menu.getItem(i).isVisible()) {
menuSize++;
}
}
int widthAllowed = toolbarWidthPx - ViewUtil.dpToPx(NAVIGATION_DP);
int nItemsToShow = Math.min(maxToShow, widthAllowed / ViewUtil.dpToPx(ACTION_VIEW_WIDTH_DP));
if (nItemsToShow < menuSize) {
widthAllowed -= ViewUtil.dpToPx(OVERFLOW_VIEW_WIDTH_DP);
}
nItemsToShow = Math.min(maxToShow, widthAllowed / ViewUtil.dpToPx(ACTION_VIEW_WIDTH_DP));
for (int i = 0; i < menu.size(); i++) {
MenuItem item = menu.getItem(i);
if (item.isVisible() && nItemsToShow > 0) {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
nItemsToShow--;
} else {
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
}
}
}
}
|
[
"public",
"class",
"AdaptiveActionsToolbar",
"extends",
"Toolbar",
"{",
"private",
"static",
"final",
"int",
"NAVIGATION_DP",
"=",
"56",
";",
"private",
"static",
"final",
"int",
"ACTION_VIEW_WIDTH_DP",
"=",
"48",
";",
"private",
"static",
"final",
"int",
"OVERFLOW_VIEW_WIDTH_DP",
"=",
"36",
";",
"private",
"int",
"maxShown",
";",
"public",
"AdaptiveActionsToolbar",
"(",
"@",
"NonNull",
"Context",
"context",
")",
"{",
"this",
"(",
"context",
",",
"null",
")",
";",
"}",
"public",
"AdaptiveActionsToolbar",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"@",
"Nullable",
"AttributeSet",
"attrs",
")",
"{",
"this",
"(",
"context",
",",
"attrs",
",",
"R",
".",
"attr",
".",
"toolbarStyle",
")",
";",
"}",
"public",
"AdaptiveActionsToolbar",
"(",
"@",
"NonNull",
"Context",
"context",
",",
"@",
"Nullable",
"AttributeSet",
"attrs",
",",
"int",
"defStyleAttr",
")",
"{",
"super",
"(",
"context",
",",
"attrs",
",",
"defStyleAttr",
")",
";",
"TypedArray",
"array",
"=",
"context",
".",
"obtainStyledAttributes",
"(",
"attrs",
",",
"R",
".",
"styleable",
".",
"AdaptiveActionsToolbar",
")",
";",
"maxShown",
"=",
"array",
".",
"getInteger",
"(",
"R",
".",
"styleable",
".",
"AdaptiveActionsToolbar_aat_max_shown",
",",
"100",
")",
";",
"array",
".",
"recycle",
"(",
")",
";",
"}",
"@",
"Override",
"protected",
"void",
"onMeasure",
"(",
"int",
"widthMeasureSpec",
",",
"int",
"heightMeasureSpec",
")",
"{",
"super",
".",
"onMeasure",
"(",
"widthMeasureSpec",
",",
"heightMeasureSpec",
")",
";",
"adjustMenuActions",
"(",
"getMenu",
"(",
")",
",",
"maxShown",
",",
"getMeasuredWidth",
"(",
")",
")",
";",
"super",
".",
"onMeasure",
"(",
"widthMeasureSpec",
",",
"heightMeasureSpec",
")",
";",
"}",
"public",
"static",
"void",
"adjustMenuActions",
"(",
"@",
"NonNull",
"Menu",
"menu",
",",
"int",
"maxToShow",
",",
"int",
"toolbarWidthPx",
")",
"{",
"int",
"menuSize",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"menu",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"menu",
".",
"getItem",
"(",
"i",
")",
".",
"isVisible",
"(",
")",
")",
"{",
"menuSize",
"++",
";",
"}",
"}",
"int",
"widthAllowed",
"=",
"toolbarWidthPx",
"-",
"ViewUtil",
".",
"dpToPx",
"(",
"NAVIGATION_DP",
")",
";",
"int",
"nItemsToShow",
"=",
"Math",
".",
"min",
"(",
"maxToShow",
",",
"widthAllowed",
"/",
"ViewUtil",
".",
"dpToPx",
"(",
"ACTION_VIEW_WIDTH_DP",
")",
")",
";",
"if",
"(",
"nItemsToShow",
"<",
"menuSize",
")",
"{",
"widthAllowed",
"-=",
"ViewUtil",
".",
"dpToPx",
"(",
"OVERFLOW_VIEW_WIDTH_DP",
")",
";",
"}",
"nItemsToShow",
"=",
"Math",
".",
"min",
"(",
"maxToShow",
",",
"widthAllowed",
"/",
"ViewUtil",
".",
"dpToPx",
"(",
"ACTION_VIEW_WIDTH_DP",
")",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"menu",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"MenuItem",
"item",
"=",
"menu",
".",
"getItem",
"(",
"i",
")",
";",
"if",
"(",
"item",
".",
"isVisible",
"(",
")",
"&&",
"nItemsToShow",
">",
"0",
")",
"{",
"item",
".",
"setShowAsAction",
"(",
"MenuItem",
".",
"SHOW_AS_ACTION_ALWAYS",
")",
";",
"nItemsToShow",
"--",
";",
"}",
"else",
"{",
"item",
".",
"setShowAsAction",
"(",
"MenuItem",
".",
"SHOW_AS_ACTION_NEVER",
")",
";",
"}",
"}",
"}",
"}"
] |
AdaptiveActionsToolbar behaves like a normal {@link Toolbar} except in that it ignores the
showAsAlways attributes of menu items added via menu inflation, opting for an adaptive algorithm
instead.
|
[
"AdaptiveActionsToolbar",
"behaves",
"like",
"a",
"normal",
"{",
"@link",
"Toolbar",
"}",
"except",
"in",
"that",
"it",
"ignores",
"the",
"showAsAlways",
"attributes",
"of",
"menu",
"items",
"added",
"via",
"menu",
"inflation",
"opting",
"for",
"an",
"adaptive",
"algorithm",
"instead",
"."
] |
[] |
[
{
"param": "Toolbar",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Toolbar",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 483
| 144
|
d46476e017834fc4d9103bfc53bafca07b742b1d
|
jgorgolewski/cookbook-cq
|
libraries/resource_cq_user.rb
|
[
"Apache-2.0"
] |
Ruby
|
Chef
|
#
# Cookbook:: cq
# Resource:: user
#
# Copyright:: (C) 2018 Jakub Wadolowski
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
|
: cq
Resource:: user
: (C) 2018 Jakub Wadolowski
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
":",
"cq",
"Resource",
"::",
"user",
":",
"(",
"C",
")",
"2018",
"Jakub",
"Wadolowski",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
".",
"You",
"may",
"obtain",
"a",
"copy",
"of",
"the",
"License",
"at",
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
class Chef
class Resource
class CqUser < Chef::Resource
provides :cq_user
attr_accessor :query_result
attr_accessor :exist
attr_accessor :path
attr_accessor :info
attr_accessor :profile
attr_accessor :admin_password
attr_accessor :my_password
def initialize(name, run_context = nil)
super
@resource_name = :cq_user
@allowed_actions = [:nothing, :modify]
@action = :nothing
@id = name
@username = nil
@password = nil
@instance = nil
@email = nil
@first_name = nil
@last_name = nil
@phone_number = nil
@job_title = nil
@street = nil
@mobile = nil
@city = nil
@postal_code = nil
@country = nil
@state = nil
@gender = nil
@about = nil
@user_password = nil
@enabled = true
@old_password = nil
end
def id(arg = nil)
set_or_return(:id, arg, kind_of: String)
end
def username(arg = nil)
set_or_return(:username, arg, kind_of: String)
end
def password(arg = nil)
set_or_return(:password, arg, kind_of: String)
end
def instance(arg = nil)
set_or_return(:instance, arg, kind_of: String)
end
def email(arg = nil)
set_or_return(:email, arg, kind_of: String)
end
def first_name(arg = nil)
set_or_return(:first_name, arg, kind_of: String)
end
def last_name(arg = nil)
set_or_return(:last_name, arg, kind_of: String)
end
def phone_number(arg = nil)
set_or_return(:phone_number, arg, kind_of: String)
end
def job_title(arg = nil)
set_or_return(:job_title, arg, kind_of: String)
end
def street(arg = nil)
set_or_return(:street, arg, kind_of: String)
end
def mobile(arg = nil)
set_or_return(:mobile, arg, kind_of: String)
end
def city(arg = nil)
set_or_return(:city, arg, kind_of: String)
end
def postal_code(arg = nil)
set_or_return(:postal_code, arg, kind_of: String)
end
def country(arg = nil)
set_or_return(:country, arg, kind_of: String)
end
def state(arg = nil)
set_or_return(:state, arg, kind_of: String)
end
def gender(arg = nil)
set_or_return(:gender, arg, kind_of: String)
end
def about(arg = nil)
set_or_return(:about, arg, kind_of: String)
end
def user_password(arg = nil)
set_or_return(:user_password, arg, kind_of: String)
end
def enabled(arg = nil)
set_or_return(:enabled, arg, kind_of: [TrueClass, FalseClass])
end
def old_password(arg = nil)
set_or_return(:old_password, arg, kind_of: String)
end
end
end
end
|
[
"class",
"Chef",
"class",
"Resource",
"class",
"CqUser",
"<",
"Chef",
"::",
"Resource",
"provides",
":cq_user",
"attr_accessor",
":query_result",
"attr_accessor",
":exist",
"attr_accessor",
":path",
"attr_accessor",
":info",
"attr_accessor",
":profile",
"attr_accessor",
":admin_password",
"attr_accessor",
":my_password",
"def",
"initialize",
"(",
"name",
",",
"run_context",
"=",
"nil",
")",
"super",
"@resource_name",
"=",
":cq_user",
"@allowed_actions",
"=",
"[",
":nothing",
",",
":modify",
"]",
"@action",
"=",
":nothing",
"@id",
"=",
"name",
"@username",
"=",
"nil",
"@password",
"=",
"nil",
"@instance",
"=",
"nil",
"@email",
"=",
"nil",
"@first_name",
"=",
"nil",
"@last_name",
"=",
"nil",
"@phone_number",
"=",
"nil",
"@job_title",
"=",
"nil",
"@street",
"=",
"nil",
"@mobile",
"=",
"nil",
"@city",
"=",
"nil",
"@postal_code",
"=",
"nil",
"@country",
"=",
"nil",
"@state",
"=",
"nil",
"@gender",
"=",
"nil",
"@about",
"=",
"nil",
"@user_password",
"=",
"nil",
"@enabled",
"=",
"true",
"@old_password",
"=",
"nil",
"end",
"def",
"id",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":id",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"username",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":username",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"password",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":password",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"instance",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":instance",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"email",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":email",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"first_name",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":first_name",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"last_name",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":last_name",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"phone_number",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":phone_number",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"job_title",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":job_title",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"street",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":street",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"mobile",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":mobile",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"city",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":city",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"postal_code",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":postal_code",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"country",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":country",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"state",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":state",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"gender",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":gender",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"about",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":about",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"user_password",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":user_password",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"def",
"enabled",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":enabled",
",",
"arg",
",",
"kind_of",
":",
"[",
"TrueClass",
",",
"FalseClass",
"]",
")",
"end",
"def",
"old_password",
"(",
"arg",
"=",
"nil",
")",
"set_or_return",
"(",
":old_password",
",",
"arg",
",",
"kind_of",
":",
"String",
")",
"end",
"end",
"end",
"end"
] |
Cookbook:: cq
Resource:: user
|
[
"Cookbook",
"::",
"cq",
"Resource",
"::",
"user"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 744
| 150
|
4f373ca402724ff4c91804c832032bc735fbda66
|
1690296356/jdk
|
test/hotspot/jtreg/testlibrary_tests/ir_framework/tests/TestCompLevels.java
|
[
"Apache-2.0"
] |
Java
|
TestCompLevels
|
/*
* @test
* @requires vm.flagless
* @summary Test if compilation levels are used correctly in the framework.
* This test partly runs directly the test VM which normally does and should not happen in user tests.
* @library /test/lib /
* @build sun.hotspot.WhiteBox
* @run driver jdk.test.lib.helpers.ClassFileInstaller sun.hotspot.WhiteBox
* @run main/othervm -Xbootclasspath/a:. -DSkipWhiteBoxInstall=true -XX:+IgnoreUnrecognizedVMOptions -XX:+UnlockDiagnosticVMOptions
* -Xbatch -XX:+WhiteBoxAPI ir_framework.tests.TestCompLevels
*/
|
@test
@requires vm.flagless
@summary Test if compilation levels are used correctly in the framework.
This test partly runs directly the test VM which normally does and should not happen in user tests.
|
[
"@test",
"@requires",
"vm",
".",
"flagless",
"@summary",
"Test",
"if",
"compilation",
"levels",
"are",
"used",
"correctly",
"in",
"the",
"framework",
".",
"This",
"test",
"partly",
"runs",
"directly",
"the",
"test",
"VM",
"which",
"normally",
"does",
"and",
"should",
"not",
"happen",
"in",
"user",
"tests",
"."
] |
public class TestCompLevels {
static int[] testExecuted = new int[5];
public static void main(String[] args) throws Exception {
Method runTestsOnSameVM = TestVM.class.getDeclaredMethod("runTestsOnSameVM", Class.class);
runTestsOnSameVM.setAccessible(true);
runTestsOnSameVM.invoke(null, new Object[]{null});
for (int i = 0; i < testExecuted.length; i++) {
int value = testExecuted[i];
if (value != TestVM.WARMUP_ITERATIONS + 1) {
// Warmups + 1 compiled invocation
throw new RuntimeException("Test " + i + " was executed " + value + " times stead of "
+ TestVM.WARMUP_ITERATIONS + 1 + " times." );
}
}
TestFramework framework = new TestFramework(TestNoTiered.class);
framework.setDefaultWarmup(10).addFlags("-XX:-TieredCompilation").start();
framework = new TestFramework(TestNoTiered.class);
framework.setDefaultWarmup(10).addScenarios(new Scenario(0, "-XX:-TieredCompilation")).start();
framework = new TestFramework(TestStopAtLevel1.class);
framework.setDefaultWarmup(10).addFlags("-XX:TieredStopAtLevel=1").start();
framework = new TestFramework(TestStopAtLevel1.class);
framework.setDefaultWarmup(10).addScenarios(new Scenario(0, "-XX:TieredStopAtLevel=1")).start();
}
@Test(compLevel = CompLevel.C1_SIMPLE)
public void testC1() {
testExecuted[0]++;
}
@Check(test = "testC1", when = CheckAt.COMPILED)
public void checkTestC1(TestInfo info) {
TestFramework.assertCompiledAtLevel(info.getTest(), CompLevel.C1_SIMPLE);
}
@Test(compLevel = CompLevel.C1_LIMITED_PROFILE)
public void testC1Limited() {
testExecuted[1]++;
}
@Check(test = "testC1Limited", when = CheckAt.COMPILED)
public void checkTestLimited(TestInfo info) {
TestFramework.assertCompiledAtLevel(info.getTest(), CompLevel.C1_LIMITED_PROFILE);
}
@Test(compLevel = CompLevel.C1_FULL_PROFILE)
public void testC1Full() {
testExecuted[2]++;
}
@Check(test = "testC1Full", when = CheckAt.COMPILED)
public void checkTestC1Full(TestInfo info) {
TestFramework.assertCompiledAtLevel(info.getTest(), CompLevel.C1_FULL_PROFILE);
}
@Test(compLevel = CompLevel.C2)
public void testC2() {
testExecuted[3]++;
}
@Check(test = "testC2", when = CheckAt.COMPILED)
public void checkTestC2(TestInfo info) {
TestFramework.assertCompiledAtLevel(info.getTest(), CompLevel.C2);
}
@Test(compLevel = CompLevel.SKIP)
public void testSkip() {
testExecuted[4]++; // Executed by eventually not compiled by framework
}
}
|
[
"public",
"class",
"TestCompLevels",
"{",
"static",
"int",
"[",
"]",
"testExecuted",
"=",
"new",
"int",
"[",
"5",
"]",
";",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"Exception",
"{",
"Method",
"runTestsOnSameVM",
"=",
"TestVM",
".",
"class",
".",
"getDeclaredMethod",
"(",
"\"",
"runTestsOnSameVM",
"\"",
",",
"Class",
".",
"class",
")",
";",
"runTestsOnSameVM",
".",
"setAccessible",
"(",
"true",
")",
";",
"runTestsOnSameVM",
".",
"invoke",
"(",
"null",
",",
"new",
"Object",
"[",
"]",
"{",
"null",
"}",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"testExecuted",
".",
"length",
";",
"i",
"++",
")",
"{",
"int",
"value",
"=",
"testExecuted",
"[",
"i",
"]",
";",
"if",
"(",
"value",
"!=",
"TestVM",
".",
"WARMUP_ITERATIONS",
"+",
"1",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Test ",
"\"",
"+",
"i",
"+",
"\"",
" was executed ",
"\"",
"+",
"value",
"+",
"\"",
" times stead of ",
"\"",
"+",
"TestVM",
".",
"WARMUP_ITERATIONS",
"+",
"1",
"+",
"\"",
" times.",
"\"",
")",
";",
"}",
"}",
"TestFramework",
"framework",
"=",
"new",
"TestFramework",
"(",
"TestNoTiered",
".",
"class",
")",
";",
"framework",
".",
"setDefaultWarmup",
"(",
"10",
")",
".",
"addFlags",
"(",
"\"",
"-XX:-TieredCompilation",
"\"",
")",
".",
"start",
"(",
")",
";",
"framework",
"=",
"new",
"TestFramework",
"(",
"TestNoTiered",
".",
"class",
")",
";",
"framework",
".",
"setDefaultWarmup",
"(",
"10",
")",
".",
"addScenarios",
"(",
"new",
"Scenario",
"(",
"0",
",",
"\"",
"-XX:-TieredCompilation",
"\"",
")",
")",
".",
"start",
"(",
")",
";",
"framework",
"=",
"new",
"TestFramework",
"(",
"TestStopAtLevel1",
".",
"class",
")",
";",
"framework",
".",
"setDefaultWarmup",
"(",
"10",
")",
".",
"addFlags",
"(",
"\"",
"-XX:TieredStopAtLevel=1",
"\"",
")",
".",
"start",
"(",
")",
";",
"framework",
"=",
"new",
"TestFramework",
"(",
"TestStopAtLevel1",
".",
"class",
")",
";",
"framework",
".",
"setDefaultWarmup",
"(",
"10",
")",
".",
"addScenarios",
"(",
"new",
"Scenario",
"(",
"0",
",",
"\"",
"-XX:TieredStopAtLevel=1",
"\"",
")",
")",
".",
"start",
"(",
")",
";",
"}",
"@",
"Test",
"(",
"compLevel",
"=",
"CompLevel",
".",
"C1_SIMPLE",
")",
"public",
"void",
"testC1",
"(",
")",
"{",
"testExecuted",
"[",
"0",
"]",
"++",
";",
"}",
"@",
"Check",
"(",
"test",
"=",
"\"",
"testC1",
"\"",
",",
"when",
"=",
"CheckAt",
".",
"COMPILED",
")",
"public",
"void",
"checkTestC1",
"(",
"TestInfo",
"info",
")",
"{",
"TestFramework",
".",
"assertCompiledAtLevel",
"(",
"info",
".",
"getTest",
"(",
")",
",",
"CompLevel",
".",
"C1_SIMPLE",
")",
";",
"}",
"@",
"Test",
"(",
"compLevel",
"=",
"CompLevel",
".",
"C1_LIMITED_PROFILE",
")",
"public",
"void",
"testC1Limited",
"(",
")",
"{",
"testExecuted",
"[",
"1",
"]",
"++",
";",
"}",
"@",
"Check",
"(",
"test",
"=",
"\"",
"testC1Limited",
"\"",
",",
"when",
"=",
"CheckAt",
".",
"COMPILED",
")",
"public",
"void",
"checkTestLimited",
"(",
"TestInfo",
"info",
")",
"{",
"TestFramework",
".",
"assertCompiledAtLevel",
"(",
"info",
".",
"getTest",
"(",
")",
",",
"CompLevel",
".",
"C1_LIMITED_PROFILE",
")",
";",
"}",
"@",
"Test",
"(",
"compLevel",
"=",
"CompLevel",
".",
"C1_FULL_PROFILE",
")",
"public",
"void",
"testC1Full",
"(",
")",
"{",
"testExecuted",
"[",
"2",
"]",
"++",
";",
"}",
"@",
"Check",
"(",
"test",
"=",
"\"",
"testC1Full",
"\"",
",",
"when",
"=",
"CheckAt",
".",
"COMPILED",
")",
"public",
"void",
"checkTestC1Full",
"(",
"TestInfo",
"info",
")",
"{",
"TestFramework",
".",
"assertCompiledAtLevel",
"(",
"info",
".",
"getTest",
"(",
")",
",",
"CompLevel",
".",
"C1_FULL_PROFILE",
")",
";",
"}",
"@",
"Test",
"(",
"compLevel",
"=",
"CompLevel",
".",
"C2",
")",
"public",
"void",
"testC2",
"(",
")",
"{",
"testExecuted",
"[",
"3",
"]",
"++",
";",
"}",
"@",
"Check",
"(",
"test",
"=",
"\"",
"testC2",
"\"",
",",
"when",
"=",
"CheckAt",
".",
"COMPILED",
")",
"public",
"void",
"checkTestC2",
"(",
"TestInfo",
"info",
")",
"{",
"TestFramework",
".",
"assertCompiledAtLevel",
"(",
"info",
".",
"getTest",
"(",
")",
",",
"CompLevel",
".",
"C2",
")",
";",
"}",
"@",
"Test",
"(",
"compLevel",
"=",
"CompLevel",
".",
"SKIP",
")",
"public",
"void",
"testSkip",
"(",
")",
"{",
"testExecuted",
"[",
"4",
"]",
"++",
";",
"}",
"}"
] |
@test
@requires vm.flagless
@summary Test if compilation levels are used correctly in the framework.
|
[
"@test",
"@requires",
"vm",
".",
"flagless",
"@summary",
"Test",
"if",
"compilation",
"levels",
"are",
"used",
"correctly",
"in",
"the",
"framework",
"."
] |
[
"// Warmups + 1 compiled invocation",
"// Executed by eventually not compiled by framework"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 690
| 137
|
7a3fa8acaf83acfc9bda86a7bf37191b65cc9546
|
martin-g/velocity-tools
|
velocity-tools-generic/src/main/java/org/apache/velocity/tools/config/XmlFactoryConfiguration.java
|
[
"Apache-2.0"
] |
Java
|
XmlFactoryConfiguration
|
/**
* <p>This reads in configuration info formatted as an XML file
* using Commons-{@link Digester}. This uses
* {@link XmlFactoryConfigurationRuleSet} as the default set of rules
* for processing the XML. However, you may always change this by
* passing a new {@link RuleSet} to the {@link #setRuleSet} method.
* See the configuration documentation on the main web site for
* instructions on the XML format supported by the default rules.</p>
* <p>Example usage:</p>
* <pre>
* FactoryConfiguration cfg = new XmlFactoryConfiguration("Dev Tools");
* cfg.read("devtools.xml");
* ToolboxFactory factory = cfg.createFactory();
* </pre>
*
* @author Nathan Bubna
* @version $Id: XmlFactoryConfiguration.java 511959 2007-02-26 19:24:39Z nbubna $
*/
|
This reads in configuration info formatted as an XML file
using Commons- Digester. This uses
XmlFactoryConfigurationRuleSet as the default set of rules
for processing the XML. However, you may always change this by
passing a new RuleSet to the #setRuleSet method.
See the configuration documentation on the main web site for
instructions on the XML format supported by the default rules.
Example usage:
FactoryConfiguration cfg = new XmlFactoryConfiguration("Dev Tools");
cfg.read("devtools.xml");
ToolboxFactory factory = cfg.createFactory();
@author Nathan Bubna
@version $Id: XmlFactoryConfiguration.java 511959 2007-02-26 19:24:39Z nbubna $
|
[
"This",
"reads",
"in",
"configuration",
"info",
"formatted",
"as",
"an",
"XML",
"file",
"using",
"Commons",
"-",
"Digester",
".",
"This",
"uses",
"XmlFactoryConfigurationRuleSet",
"as",
"the",
"default",
"set",
"of",
"rules",
"for",
"processing",
"the",
"XML",
".",
"However",
"you",
"may",
"always",
"change",
"this",
"by",
"passing",
"a",
"new",
"RuleSet",
"to",
"the",
"#setRuleSet",
"method",
".",
"See",
"the",
"configuration",
"documentation",
"on",
"the",
"main",
"web",
"site",
"for",
"instructions",
"on",
"the",
"XML",
"format",
"supported",
"by",
"the",
"default",
"rules",
".",
"Example",
"usage",
":",
"FactoryConfiguration",
"cfg",
"=",
"new",
"XmlFactoryConfiguration",
"(",
"\"",
"Dev",
"Tools",
"\"",
")",
";",
"cfg",
".",
"read",
"(",
"\"",
"devtools",
".",
"xml",
"\"",
")",
";",
"ToolboxFactory",
"factory",
"=",
"cfg",
".",
"createFactory",
"()",
";",
"@author",
"Nathan",
"Bubna",
"@version",
"$Id",
":",
"XmlFactoryConfiguration",
".",
"java",
"511959",
"2007",
"-",
"02",
"-",
"26",
"19",
":",
"24",
":",
"39Z",
"nbubna",
"$"
] |
public class XmlFactoryConfiguration extends FileFactoryConfiguration
{
private RuleSet ruleSet;
/**
* Creates an instance
*
* @see FactoryConfiguration#setSource(String)
*/
public XmlFactoryConfiguration()
{
this("");
}
/**
* Creates an instance using the specified string
* as an identifier to distinguish this instance when debugging
*
* @param id the name of the "source" of this instance
* @see FactoryConfiguration#setSource(String)
*/
public XmlFactoryConfiguration(String id)
{
super(XmlFactoryConfiguration.class, id);
setRuleSet(new XmlFactoryConfigurationRuleSet());
}
/**
* Sets the {@link RuleSet} this loader will use to
* digest the xml toolbox.
* @param rules rules set
*/
public void setRuleSet(RuleSet rules)
{
this.ruleSet = rules;
}
/**
* <p>Retrieves the rule set Digester should use to parse and load
* the toolbox for this manager.</p>
* @return rules set
*/
public RuleSet getRuleSet()
{
return ruleSet;
}
/**
* <p>Reads an XML document from an {@link URL}
* and uses it to configure this {@link FactoryConfiguration}.</p>
*
* @param url the URL to read from
*/
protected void readImpl(URL url) throws IOException
{
// since beanutils 1.9.4, we need to relax access to the 'class' method
BeanUtilsBean.getInstance().getPropertyUtils().removeBeanIntrospector(SuppressPropertiesBeanIntrospector.SUPPRESS_CLASS);
Digester digester = new Digester();
digester.setNamespaceAware(true);
digester.setXIncludeAware(true);
digester.setValidating(false);
digester.setUseContextClassLoader(true);
digester.push(this);
digester.addRuleSet(getRuleSet());
try
{
digester.parse(url);
}
catch (SAXException saxe)
{
throw new RuntimeException("There was an error while parsing the InputStream", saxe);
}
finally
{
BeanUtilsBean.getInstance().getPropertyUtils().resetBeanIntrospectors();
}
}
}
|
[
"public",
"class",
"XmlFactoryConfiguration",
"extends",
"FileFactoryConfiguration",
"{",
"private",
"RuleSet",
"ruleSet",
";",
"/**\n * Creates an instance\n *\n * @see FactoryConfiguration#setSource(String)\n */",
"public",
"XmlFactoryConfiguration",
"(",
")",
"{",
"this",
"(",
"\"",
"\"",
")",
";",
"}",
"/**\n * Creates an instance using the specified string\n * as an identifier to distinguish this instance when debugging\n *\n * @param id the name of the \"source\" of this instance\n * @see FactoryConfiguration#setSource(String)\n */",
"public",
"XmlFactoryConfiguration",
"(",
"String",
"id",
")",
"{",
"super",
"(",
"XmlFactoryConfiguration",
".",
"class",
",",
"id",
")",
";",
"setRuleSet",
"(",
"new",
"XmlFactoryConfigurationRuleSet",
"(",
")",
")",
";",
"}",
"/**\n * Sets the {@link RuleSet} this loader will use to\n * digest the xml toolbox.\n * @param rules rules set\n */",
"public",
"void",
"setRuleSet",
"(",
"RuleSet",
"rules",
")",
"{",
"this",
".",
"ruleSet",
"=",
"rules",
";",
"}",
"/**\n * <p>Retrieves the rule set Digester should use to parse and load\n * the toolbox for this manager.</p>\n * @return rules set\n */",
"public",
"RuleSet",
"getRuleSet",
"(",
")",
"{",
"return",
"ruleSet",
";",
"}",
"/**\n * <p>Reads an XML document from an {@link URL}\n * and uses it to configure this {@link FactoryConfiguration}.</p>\n * \n * @param url the URL to read from\n */",
"protected",
"void",
"readImpl",
"(",
"URL",
"url",
")",
"throws",
"IOException",
"{",
"BeanUtilsBean",
".",
"getInstance",
"(",
")",
".",
"getPropertyUtils",
"(",
")",
".",
"removeBeanIntrospector",
"(",
"SuppressPropertiesBeanIntrospector",
".",
"SUPPRESS_CLASS",
")",
";",
"Digester",
"digester",
"=",
"new",
"Digester",
"(",
")",
";",
"digester",
".",
"setNamespaceAware",
"(",
"true",
")",
";",
"digester",
".",
"setXIncludeAware",
"(",
"true",
")",
";",
"digester",
".",
"setValidating",
"(",
"false",
")",
";",
"digester",
".",
"setUseContextClassLoader",
"(",
"true",
")",
";",
"digester",
".",
"push",
"(",
"this",
")",
";",
"digester",
".",
"addRuleSet",
"(",
"getRuleSet",
"(",
")",
")",
";",
"try",
"{",
"digester",
".",
"parse",
"(",
"url",
")",
";",
"}",
"catch",
"(",
"SAXException",
"saxe",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"There was an error while parsing the InputStream",
"\"",
",",
"saxe",
")",
";",
"}",
"finally",
"{",
"BeanUtilsBean",
".",
"getInstance",
"(",
")",
".",
"getPropertyUtils",
"(",
")",
".",
"resetBeanIntrospectors",
"(",
")",
";",
"}",
"}",
"}"
] |
<p>This reads in configuration info formatted as an XML file
using Commons-{@link Digester}.
|
[
"<p",
">",
"This",
"reads",
"in",
"configuration",
"info",
"formatted",
"as",
"an",
"XML",
"file",
"using",
"Commons",
"-",
"{",
"@link",
"Digester",
"}",
"."
] |
[
"// since beanutils 1.9.4, we need to relax access to the 'class' method"
] |
[
{
"param": "FileFactoryConfiguration",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "FileFactoryConfiguration",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 497
| 205
|
436ac7a3d3abc78a199e7cb90c1b447dad10436d
|
faceless2/jai-imageio-jpeg2000
|
src/main/java/com/github/jpeg2000/ImageHeaderBox.java
|
[
"BSD-3-Clause-No-Nuclear-Warranty"
] |
Java
|
ImageHeaderBox
|
/**
* This represents the "ihdr" Box
*
* The content of an image header box contains the width/height, number of
* image components, the bit depth (coded with sign/unsign information),
* the compression type (7 for JP2 file), the flag to indicate the color
* space is known or not, and a flag to indicate whether the intellectual
* property information included in this file.
*
* @author http://bfo.com
*/
|
This represents the "ihdr" Box
The content of an image header box contains the width/height, number of
image components, the bit depth (coded with sign/unsign information),
the compression type (7 for JP2 file), the flag to indicate the color
space is known or not, and a flag to indicate whether the intellectual
property information included in this file.
|
[
"This",
"represents",
"the",
"\"",
"ihdr",
"\"",
"Box",
"The",
"content",
"of",
"an",
"image",
"header",
"box",
"contains",
"the",
"width",
"/",
"height",
"number",
"of",
"image",
"components",
"the",
"bit",
"depth",
"(",
"coded",
"with",
"sign",
"/",
"unsign",
"information",
")",
"the",
"compression",
"type",
"(",
"7",
"for",
"JP2",
"file",
")",
"the",
"flag",
"to",
"indicate",
"the",
"color",
"space",
"is",
"known",
"or",
"not",
"and",
"a",
"flag",
"to",
"indicate",
"whether",
"the",
"intellectual",
"property",
"information",
"included",
"in",
"this",
"file",
"."
] |
public class ImageHeaderBox extends Box {
private int width;
private int height;
private short numComp;
private byte bitDepth;
private byte compressionType;
private byte unknownColor;
private byte intelProp;
public ImageHeaderBox() {
super(fromString("ihdr"));
}
/** Create an Image Header Box from the element values. */
public ImageHeaderBox(int width, int height, int numComp, int bitDepth, boolean unknownColor, boolean intelProp) {
this();
this.height = height;
this.width = width;
this.numComp = (short)numComp;
this.bitDepth = (byte)bitDepth;
this.compressionType = (byte)7;
this.unknownColor = (byte)(unknownColor ? 1 : 0);
this.intelProp = (byte)(intelProp ? 1 : 0);
}
@Override public int getLength() {
return 14;
}
@Override public void read(RandomAccessIO in) throws IOException {
height = in.readInt();
width = in.readInt();
numComp = in.readShort();
bitDepth = in.readByte();
compressionType = in.readByte();
unknownColor = in.readByte();
intelProp = in.readByte();
}
@Override public void write(DataOutputStream out) throws IOException {
out.writeInt(height);
out.writeInt(width);
out.writeShort(numComp);
out.write(bitDepth);
out.write(compressionType);
out.write(unknownColor);
out.write(intelProp);
}
/** Returns the height of the image. */
public int getHeight() {
return height;
}
/** Returns the width of the image. */
public int getWidth() {
return width;
}
/** Returns the number of image components. */
public short getNumComponents() {
return numComp;
}
/** Returns the compression type. */
public byte getCompressionType() {
return compressionType;
}
/** Returns the bit depth for all the image components. */
public byte getBitDepth() {
return bitDepth;
}
/** Returns the <code>UnknowColorspace</code> flag. */
public byte getUnknownColorspace() {
return unknownColor;
}
/** Returns the <code>IntellectualProperty</code> flag. */
public byte getIntellectualProperty() {
return intelProp;
}
@Override public void write(XMLStreamWriter out) throws XMLStreamException {
out.writeEmptyElement(toString(getType()).trim());
out.writeAttribute("length", Integer.toString(getLength()));
out.writeAttribute("width", Integer.toString(getWidth()));
out.writeAttribute("height", Integer.toString(getHeight()));
out.writeAttribute("numc", Integer.toString(getNumComponents()));
if (getBitDepth() != 255) {
out.writeAttribute("depth", Integer.toString(getBitDepth()));
}
if (getCompressionType() != 7) {
out.writeAttribute("compression", Integer.toString(getCompressionType()));
}
out.writeAttribute("unknownColorSpace", Integer.toString(getUnknownColorspace()));
out.writeAttribute("ip", Integer.toString(getIntellectualProperty()));
}
public String toString() {
StringBuilder sb = new StringBuilder(super.toString());
sb.deleteCharAt(sb.length() - 1);
sb.append(",\"width\":\"");
sb.append(getWidth());
sb.append(",\"height\":\"");
sb.append(getHeight());
sb.append(",\"numc\":\"");
sb.append(getNumComponents());
if (getBitDepth() != 255) {
sb.append(",\"depth\":\"");
sb.append(getBitDepth());
}
if (getCompressionType() != 7) {
sb.append(",\"compression\":\"");
sb.append(getCompressionType());
}
sb.append("\",\"unknownColorSpace\":");
sb.append(getUnknownColorspace());
sb.append("\",\"ip\":");
sb.append(getIntellectualProperty());
sb.append("}");
return sb.toString();
}
}
|
[
"public",
"class",
"ImageHeaderBox",
"extends",
"Box",
"{",
"private",
"int",
"width",
";",
"private",
"int",
"height",
";",
"private",
"short",
"numComp",
";",
"private",
"byte",
"bitDepth",
";",
"private",
"byte",
"compressionType",
";",
"private",
"byte",
"unknownColor",
";",
"private",
"byte",
"intelProp",
";",
"public",
"ImageHeaderBox",
"(",
")",
"{",
"super",
"(",
"fromString",
"(",
"\"",
"ihdr",
"\"",
")",
")",
";",
"}",
"/** Create an Image Header Box from the element values. */",
"public",
"ImageHeaderBox",
"(",
"int",
"width",
",",
"int",
"height",
",",
"int",
"numComp",
",",
"int",
"bitDepth",
",",
"boolean",
"unknownColor",
",",
"boolean",
"intelProp",
")",
"{",
"this",
"(",
")",
";",
"this",
".",
"height",
"=",
"height",
";",
"this",
".",
"width",
"=",
"width",
";",
"this",
".",
"numComp",
"=",
"(",
"short",
")",
"numComp",
";",
"this",
".",
"bitDepth",
"=",
"(",
"byte",
")",
"bitDepth",
";",
"this",
".",
"compressionType",
"=",
"(",
"byte",
")",
"7",
";",
"this",
".",
"unknownColor",
"=",
"(",
"byte",
")",
"(",
"unknownColor",
"?",
"1",
":",
"0",
")",
";",
"this",
".",
"intelProp",
"=",
"(",
"byte",
")",
"(",
"intelProp",
"?",
"1",
":",
"0",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getLength",
"(",
")",
"{",
"return",
"14",
";",
"}",
"@",
"Override",
"public",
"void",
"read",
"(",
"RandomAccessIO",
"in",
")",
"throws",
"IOException",
"{",
"height",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"width",
"=",
"in",
".",
"readInt",
"(",
")",
";",
"numComp",
"=",
"in",
".",
"readShort",
"(",
")",
";",
"bitDepth",
"=",
"in",
".",
"readByte",
"(",
")",
";",
"compressionType",
"=",
"in",
".",
"readByte",
"(",
")",
";",
"unknownColor",
"=",
"in",
".",
"readByte",
"(",
")",
";",
"intelProp",
"=",
"in",
".",
"readByte",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"DataOutputStream",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"writeInt",
"(",
"height",
")",
";",
"out",
".",
"writeInt",
"(",
"width",
")",
";",
"out",
".",
"writeShort",
"(",
"numComp",
")",
";",
"out",
".",
"write",
"(",
"bitDepth",
")",
";",
"out",
".",
"write",
"(",
"compressionType",
")",
";",
"out",
".",
"write",
"(",
"unknownColor",
")",
";",
"out",
".",
"write",
"(",
"intelProp",
")",
";",
"}",
"/** Returns the height of the image. */",
"public",
"int",
"getHeight",
"(",
")",
"{",
"return",
"height",
";",
"}",
"/** Returns the width of the image. */",
"public",
"int",
"getWidth",
"(",
")",
"{",
"return",
"width",
";",
"}",
"/** Returns the number of image components. */",
"public",
"short",
"getNumComponents",
"(",
")",
"{",
"return",
"numComp",
";",
"}",
"/** Returns the compression type. */",
"public",
"byte",
"getCompressionType",
"(",
")",
"{",
"return",
"compressionType",
";",
"}",
"/** Returns the bit depth for all the image components. */",
"public",
"byte",
"getBitDepth",
"(",
")",
"{",
"return",
"bitDepth",
";",
"}",
"/** Returns the <code>UnknowColorspace</code> flag. */",
"public",
"byte",
"getUnknownColorspace",
"(",
")",
"{",
"return",
"unknownColor",
";",
"}",
"/** Returns the <code>IntellectualProperty</code> flag. */",
"public",
"byte",
"getIntellectualProperty",
"(",
")",
"{",
"return",
"intelProp",
";",
"}",
"@",
"Override",
"public",
"void",
"write",
"(",
"XMLStreamWriter",
"out",
")",
"throws",
"XMLStreamException",
"{",
"out",
".",
"writeEmptyElement",
"(",
"toString",
"(",
"getType",
"(",
")",
")",
".",
"trim",
"(",
")",
")",
";",
"out",
".",
"writeAttribute",
"(",
"\"",
"length",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getLength",
"(",
")",
")",
")",
";",
"out",
".",
"writeAttribute",
"(",
"\"",
"width",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getWidth",
"(",
")",
")",
")",
";",
"out",
".",
"writeAttribute",
"(",
"\"",
"height",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getHeight",
"(",
")",
")",
")",
";",
"out",
".",
"writeAttribute",
"(",
"\"",
"numc",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getNumComponents",
"(",
")",
")",
")",
";",
"if",
"(",
"getBitDepth",
"(",
")",
"!=",
"255",
")",
"{",
"out",
".",
"writeAttribute",
"(",
"\"",
"depth",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getBitDepth",
"(",
")",
")",
")",
";",
"}",
"if",
"(",
"getCompressionType",
"(",
")",
"!=",
"7",
")",
"{",
"out",
".",
"writeAttribute",
"(",
"\"",
"compression",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getCompressionType",
"(",
")",
")",
")",
";",
"}",
"out",
".",
"writeAttribute",
"(",
"\"",
"unknownColorSpace",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getUnknownColorspace",
"(",
")",
")",
")",
";",
"out",
".",
"writeAttribute",
"(",
"\"",
"ip",
"\"",
",",
"Integer",
".",
"toString",
"(",
"getIntellectualProperty",
"(",
")",
")",
")",
";",
"}",
"public",
"String",
"toString",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"super",
".",
"toString",
"(",
")",
")",
";",
"sb",
".",
"deleteCharAt",
"(",
"sb",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"sb",
".",
"append",
"(",
"\"",
",",
"\\\"",
"width",
"\\\"",
":",
"\\\"",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getWidth",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
",",
"\\\"",
"height",
"\\\"",
":",
"\\\"",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getHeight",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
",",
"\\\"",
"numc",
"\\\"",
":",
"\\\"",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getNumComponents",
"(",
")",
")",
";",
"if",
"(",
"getBitDepth",
"(",
")",
"!=",
"255",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
",",
"\\\"",
"depth",
"\\\"",
":",
"\\\"",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getBitDepth",
"(",
")",
")",
";",
"}",
"if",
"(",
"getCompressionType",
"(",
")",
"!=",
"7",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
",",
"\\\"",
"compression",
"\\\"",
":",
"\\\"",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getCompressionType",
"(",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\"",
"\\\"",
",",
"\\\"",
"unknownColorSpace",
"\\\"",
":",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getUnknownColorspace",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
"\\\"",
",",
"\\\"",
"ip",
"\\\"",
":",
"\"",
")",
";",
"sb",
".",
"append",
"(",
"getIntellectualProperty",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"",
"}",
"\"",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}",
"}"
] |
This represents the "ihdr" Box
The content of an image header box contains the width/height, number of
image components, the bit depth (coded with sign/unsign information),
the compression type (7 for JP2 file), the flag to indicate the color
space is known or not, and a flag to indicate whether the intellectual
property information included in this file.
|
[
"This",
"represents",
"the",
"\"",
"ihdr",
"\"",
"Box",
"The",
"content",
"of",
"an",
"image",
"header",
"box",
"contains",
"the",
"width",
"/",
"height",
"number",
"of",
"image",
"components",
"the",
"bit",
"depth",
"(",
"coded",
"with",
"sign",
"/",
"unsign",
"information",
")",
"the",
"compression",
"type",
"(",
"7",
"for",
"JP2",
"file",
")",
"the",
"flag",
"to",
"indicate",
"the",
"color",
"space",
"is",
"known",
"or",
"not",
"and",
"a",
"flag",
"to",
"indicate",
"whether",
"the",
"intellectual",
"property",
"information",
"included",
"in",
"this",
"file",
"."
] |
[] |
[
{
"param": "Box",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Box",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 865
| 97
|
31fd9400d7cceca96a8dbd197e79eb76e67d5ab3
|
kinshuk4/leetcode-solutions
|
java/leetcode/src/main/java/com/vaani/leetcode/tree/FlipEquivalentBinaryTrees.java
|
[
"MIT"
] |
Java
|
FlipEquivalentBinaryTrees
|
/**
* 06/08/2019 For a binary tree T, we can define a flip operation
* as follows: choose any node, and swap the left and right child subtrees.
*
* <p>A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y
* after some number of flip operations.
*
* <p>Write a function that determines whether two binary trees are flip equivalent. The trees are
* given by root nodes root1 and root2.
*
* <p>Example 1:
*
* <p>Input: root1 = [1,2,3,4,5,6,null,null,null,7,8], root2 =
* [1,3,2,null,6,4,5,null,null,null,null,8,7] Output: true Explanation: We flipped at nodes with
* values 1, 3, and 5. Flipped Trees Diagram
*
* <p>Note:
*
* <p>Each tree will have at most 100 nodes. Each value in each tree will be a unique integer in the
* range [0, 99]. Solution O(N ^ 2) Since the node values are unique general idea is to find the
* node on right tree for every node on the left tree and check if the values need to be swapped, if
* yes then swap the node's left and right child in the left tree. After this operation is complete
* check if both the trees are equal
*/
|
06/08/2019 For a binary tree T, we can define a flip operation
as follows: choose any node, and swap the left and right child subtrees.
A binary tree X is flip equivalent to a binary tree Y if and only if we can make X equal to Y
after some number of flip operations.
Write a function that determines whether two binary trees are flip equivalent. The trees are
given by root nodes root1 and root2.
Example 1.
Note.
Each tree will have at most 100 nodes. Each value in each tree will be a unique integer in the
range [0, 99]. Solution O(N ^ 2) Since the node values are unique general idea is to find the
node on right tree for every node on the left tree and check if the values need to be swapped, if
yes then swap the node's left and right child in the left tree. After this operation is complete
check if both the trees are equal
|
[
"06",
"/",
"08",
"/",
"2019",
"For",
"a",
"binary",
"tree",
"T",
"we",
"can",
"define",
"a",
"flip",
"operation",
"as",
"follows",
":",
"choose",
"any",
"node",
"and",
"swap",
"the",
"left",
"and",
"right",
"child",
"subtrees",
".",
"A",
"binary",
"tree",
"X",
"is",
"flip",
"equivalent",
"to",
"a",
"binary",
"tree",
"Y",
"if",
"and",
"only",
"if",
"we",
"can",
"make",
"X",
"equal",
"to",
"Y",
"after",
"some",
"number",
"of",
"flip",
"operations",
".",
"Write",
"a",
"function",
"that",
"determines",
"whether",
"two",
"binary",
"trees",
"are",
"flip",
"equivalent",
".",
"The",
"trees",
"are",
"given",
"by",
"root",
"nodes",
"root1",
"and",
"root2",
".",
"Example",
"1",
".",
"Note",
".",
"Each",
"tree",
"will",
"have",
"at",
"most",
"100",
"nodes",
".",
"Each",
"value",
"in",
"each",
"tree",
"will",
"be",
"a",
"unique",
"integer",
"in",
"the",
"range",
"[",
"0",
"99",
"]",
".",
"Solution",
"O",
"(",
"N",
"^",
"2",
")",
"Since",
"the",
"node",
"values",
"are",
"unique",
"general",
"idea",
"is",
"to",
"find",
"the",
"node",
"on",
"right",
"tree",
"for",
"every",
"node",
"on",
"the",
"left",
"tree",
"and",
"check",
"if",
"the",
"values",
"need",
"to",
"be",
"swapped",
"if",
"yes",
"then",
"swap",
"the",
"node",
"'",
"s",
"left",
"and",
"right",
"child",
"in",
"the",
"left",
"tree",
".",
"After",
"this",
"operation",
"is",
"complete",
"check",
"if",
"both",
"the",
"trees",
"are",
"equal"
] |
public class FlipEquivalentBinaryTrees {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public static void main(String[] args) {
TreeNode node = new TreeNode(1);
node.left = new TreeNode(2);
node.left.left = new TreeNode(4);
node.left.right = new TreeNode(5);
node.left.right.left = new TreeNode(7);
node.left.right.right = new TreeNode(8);
node.right = new TreeNode(3);
node.right.left = new TreeNode(6);
TreeNode node1 = new TreeNode(1);
node1.left = new TreeNode(3);
node1.left.right = new TreeNode(6);
node1.right = new TreeNode(2);
node1.right.left = new TreeNode(4);
node1.right.right = new TreeNode(5);
node1.right.right.left = new TreeNode(8);
node1.right.right.right = new TreeNode(7);
System.out.println(new FlipEquivalentBinaryTrees().flipEquiv(node, node1));
}
public boolean flipEquiv(TreeNode root1, TreeNode root2) {
flip(root1, root2);
return checkIfBothAreSame(root1, root2);
}
private boolean checkIfBothAreSame(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
else if (root1 == null) return false;
else if (root2 == null) return false;
else {
if (root1.val != root2.val) return false;
if (!checkIfBothAreSame(root1.left, root2.left)) return false;
return checkIfBothAreSame(root1.right, root2.right);
}
}
private void flip(TreeNode root1, TreeNode root2) {
if (root1 != null) {
TreeNode result = find(root2, root1.val);
boolean valid = true;
if (result != null) {
if (root1.left == null) {
if (result.right != null) {
valid = false;
}
}
if (root1.right == null) {
if (result.left != null) {
valid = false;
}
}
if (root1.left != null) {
if (result.right == null) {
valid = false;
} else {
if (root1.left.val != result.right.val) {
valid = false;
}
}
}
if (root1.right != null) {
if (result.left == null) {
valid = false;
} else {
if (root1.right.val != result.left.val) {
valid = false;
}
}
}
if (valid) {
TreeNode temp = result.left;
result.left = result.right;
result.right = temp;
}
}
flip(root1.left, root2);
flip(root1.right, root2);
}
}
private TreeNode find(TreeNode node, int value) {
if (node != null) {
if (node.val == value) return node;
TreeNode left = find(node.left, value);
if (left != null) return left;
TreeNode right = find(node.right, value);
if (right != null) return right;
}
return null;
}
}
|
[
"public",
"class",
"FlipEquivalentBinaryTrees",
"{",
"public",
"static",
"class",
"TreeNode",
"{",
"int",
"val",
";",
"TreeNode",
"left",
";",
"TreeNode",
"right",
";",
"TreeNode",
"(",
"int",
"x",
")",
"{",
"val",
"=",
"x",
";",
"}",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"TreeNode",
"node",
"=",
"new",
"TreeNode",
"(",
"1",
")",
";",
"node",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"2",
")",
";",
"node",
".",
"left",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"4",
")",
";",
"node",
".",
"left",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"5",
")",
";",
"node",
".",
"left",
".",
"right",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"7",
")",
";",
"node",
".",
"left",
".",
"right",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"8",
")",
";",
"node",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"3",
")",
";",
"node",
".",
"right",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"6",
")",
";",
"TreeNode",
"node1",
"=",
"new",
"TreeNode",
"(",
"1",
")",
";",
"node1",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"3",
")",
";",
"node1",
".",
"left",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"6",
")",
";",
"node1",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"2",
")",
";",
"node1",
".",
"right",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"4",
")",
";",
"node1",
".",
"right",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"5",
")",
";",
"node1",
".",
"right",
".",
"right",
".",
"left",
"=",
"new",
"TreeNode",
"(",
"8",
")",
";",
"node1",
".",
"right",
".",
"right",
".",
"right",
"=",
"new",
"TreeNode",
"(",
"7",
")",
";",
"System",
".",
"out",
".",
"println",
"(",
"new",
"FlipEquivalentBinaryTrees",
"(",
")",
".",
"flipEquiv",
"(",
"node",
",",
"node1",
")",
")",
";",
"}",
"public",
"boolean",
"flipEquiv",
"(",
"TreeNode",
"root1",
",",
"TreeNode",
"root2",
")",
"{",
"flip",
"(",
"root1",
",",
"root2",
")",
";",
"return",
"checkIfBothAreSame",
"(",
"root1",
",",
"root2",
")",
";",
"}",
"private",
"boolean",
"checkIfBothAreSame",
"(",
"TreeNode",
"root1",
",",
"TreeNode",
"root2",
")",
"{",
"if",
"(",
"root1",
"==",
"null",
"&&",
"root2",
"==",
"null",
")",
"return",
"true",
";",
"else",
"if",
"(",
"root1",
"==",
"null",
")",
"return",
"false",
";",
"else",
"if",
"(",
"root2",
"==",
"null",
")",
"return",
"false",
";",
"else",
"{",
"if",
"(",
"root1",
".",
"val",
"!=",
"root2",
".",
"val",
")",
"return",
"false",
";",
"if",
"(",
"!",
"checkIfBothAreSame",
"(",
"root1",
".",
"left",
",",
"root2",
".",
"left",
")",
")",
"return",
"false",
";",
"return",
"checkIfBothAreSame",
"(",
"root1",
".",
"right",
",",
"root2",
".",
"right",
")",
";",
"}",
"}",
"private",
"void",
"flip",
"(",
"TreeNode",
"root1",
",",
"TreeNode",
"root2",
")",
"{",
"if",
"(",
"root1",
"!=",
"null",
")",
"{",
"TreeNode",
"result",
"=",
"find",
"(",
"root2",
",",
"root1",
".",
"val",
")",
";",
"boolean",
"valid",
"=",
"true",
";",
"if",
"(",
"result",
"!=",
"null",
")",
"{",
"if",
"(",
"root1",
".",
"left",
"==",
"null",
")",
"{",
"if",
"(",
"result",
".",
"right",
"!=",
"null",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"root1",
".",
"right",
"==",
"null",
")",
"{",
"if",
"(",
"result",
".",
"left",
"!=",
"null",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"}",
"if",
"(",
"root1",
".",
"left",
"!=",
"null",
")",
"{",
"if",
"(",
"result",
".",
"right",
"==",
"null",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"root1",
".",
"left",
".",
"val",
"!=",
"result",
".",
"right",
".",
"val",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"}",
"}",
"if",
"(",
"root1",
".",
"right",
"!=",
"null",
")",
"{",
"if",
"(",
"result",
".",
"left",
"==",
"null",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"else",
"{",
"if",
"(",
"root1",
".",
"right",
".",
"val",
"!=",
"result",
".",
"left",
".",
"val",
")",
"{",
"valid",
"=",
"false",
";",
"}",
"}",
"}",
"if",
"(",
"valid",
")",
"{",
"TreeNode",
"temp",
"=",
"result",
".",
"left",
";",
"result",
".",
"left",
"=",
"result",
".",
"right",
";",
"result",
".",
"right",
"=",
"temp",
";",
"}",
"}",
"flip",
"(",
"root1",
".",
"left",
",",
"root2",
")",
";",
"flip",
"(",
"root1",
".",
"right",
",",
"root2",
")",
";",
"}",
"}",
"private",
"TreeNode",
"find",
"(",
"TreeNode",
"node",
",",
"int",
"value",
")",
"{",
"if",
"(",
"node",
"!=",
"null",
")",
"{",
"if",
"(",
"node",
".",
"val",
"==",
"value",
")",
"return",
"node",
";",
"TreeNode",
"left",
"=",
"find",
"(",
"node",
".",
"left",
",",
"value",
")",
";",
"if",
"(",
"left",
"!=",
"null",
")",
"return",
"left",
";",
"TreeNode",
"right",
"=",
"find",
"(",
"node",
".",
"right",
",",
"value",
")",
";",
"if",
"(",
"right",
"!=",
"null",
")",
"return",
"right",
";",
"}",
"return",
"null",
";",
"}",
"}"
] |
06/08/2019 For a binary tree T, we can define a flip operation
as follows: choose any node, and swap the left and right child subtrees.
|
[
"06",
"/",
"08",
"/",
"2019",
"For",
"a",
"binary",
"tree",
"T",
"we",
"can",
"define",
"a",
"flip",
"operation",
"as",
"follows",
":",
"choose",
"any",
"node",
"and",
"swap",
"the",
"left",
"and",
"right",
"child",
"subtrees",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 725
| 327
|
ea0c9c114a5adf94769dc0f345f44c9ac50c0a6c
|
jlivingstonsg/Cellbots-2019
|
android/java/cellbots/src/com/cellbots/httpserver/HttpCommandServer.java
|
[
"Apache-2.0"
] |
Java
|
HttpCommandServer
|
/**
* This is the HTTP server that runs locally and listens on the specified port.
* The server is designed slightly differently than a standard HTTP server -- it
* is designed as a command server where each GET/PUT/POST request is a command
* sent to the Android app using this server.
* All PUT requests are forwarded to the listener via HttpCommandServerListener
* if one is set through the constructor of this class.
* HTTP clients can request resources from this server. The server serves out
* named resources that exist in the memory. If none exists, then it looks for
* files by that name in the specified root directory.
* For example: An HTTP PUT request to the URL http://<ip>:<port>/mycommand
* will result in a callback made to HttpCommandServerListener.onRequest() with
* |req| = "mycommand" and with the URL parameters and request entity passed
* appropriately.
* When an HTTP GET request to the URL http://<ip>:<port>/myres is made, the
* server first looks for the resource by name "myres" in the memory, ad returns
* its value in the response with the appropriate content type. If the named
* resource is not found in the memory, it searched for a file by name "myres"
* in the default root directory, and returns the contents of the file in the
* HTTP response.
*
* @author [email protected] (Chaitanya Gharpure)
*
*/
|
This is the HTTP server that runs locally and listens on the specified port.
The server is designed slightly differently than a standard HTTP server -- it
is designed as a command server where each GET/PUT/POST request is a command
sent to the Android app using this server.
All PUT requests are forwarded to the listener via HttpCommandServerListener
if one is set through the constructor of this class.
HTTP clients can request resources from this server. The server serves out
named resources that exist in the memory. If none exists, then it looks for
files by that name in the specified root directory.
|
[
"This",
"is",
"the",
"HTTP",
"server",
"that",
"runs",
"locally",
"and",
"listens",
"on",
"the",
"specified",
"port",
".",
"The",
"server",
"is",
"designed",
"slightly",
"differently",
"than",
"a",
"standard",
"HTTP",
"server",
"--",
"it",
"is",
"designed",
"as",
"a",
"command",
"server",
"where",
"each",
"GET",
"/",
"PUT",
"/",
"POST",
"request",
"is",
"a",
"command",
"sent",
"to",
"the",
"Android",
"app",
"using",
"this",
"server",
".",
"All",
"PUT",
"requests",
"are",
"forwarded",
"to",
"the",
"listener",
"via",
"HttpCommandServerListener",
"if",
"one",
"is",
"set",
"through",
"the",
"constructor",
"of",
"this",
"class",
".",
"HTTP",
"clients",
"can",
"request",
"resources",
"from",
"this",
"server",
".",
"The",
"server",
"serves",
"out",
"named",
"resources",
"that",
"exist",
"in",
"the",
"memory",
".",
"If",
"none",
"exists",
"then",
"it",
"looks",
"for",
"files",
"by",
"that",
"name",
"in",
"the",
"specified",
"root",
"directory",
"."
] |
public class HttpCommandServer {
private class ResponseResource<T> {
public T resource;
public String contentType;
public ResponseResource(T res, String ct) {
resource = res;
contentType = ct;
}
}
private class UrlParams {
public String[] keys;
public String[] values;
public UrlParams(String url) {
int index = url.indexOf('?');
if (index >= 0) {
String paramStr = url.substring(url.indexOf('?') + 1);
String[] toks = paramStr.split("&");
keys = new String[toks.length];
values = new String[toks.length];
int i = 0;
for (String tok : toks) {
String[] tmp = tok.split("=");
if (tmp.length > 0) {
keys[i] = tmp[0];
if (tmp.length > 1)
values[i] = tmp[1];
} else {
keys[i] = tok;
}
i++;
}
}
}
}
private static final String TAG = "HttpCommandServer";
private static final String EXTERNAL_STORAGE_PATH =
Environment.getExternalStorageDirectory() + "/";
private int mPort = 8080;
private String rootDir;
private RequestListenerThread listenerThread;
private boolean running = true;
HashMap<String, ResponseResource<byte[]>> dataMap =
new HashMap<String, ResponseResource<byte[]>>();
HashMap<String, ResponseResource<String>> resourceMap =
new HashMap<String, ResponseResource<String>>();
private HttpCommandServerListener serverListener;
public HttpCommandServer(String root, int port, HttpCommandServerListener listener) {
serverListener = listener;
mPort = port;
setRoot(root);
try {
listenerThread = new RequestListenerThread(port);
listenerThread.setDaemon(false);
listenerThread.start();
} catch (IOException e) {
Log.e(TAG, "Error starting HTTP server: " + e.getMessage());
}
Log.d(TAG, "*** IP address: " + getLocalIpAddress());
}
public void setRoot(String root) {
rootDir = EXTERNAL_STORAGE_PATH + root;
File dir = new File(EXTERNAL_STORAGE_PATH + root);
if (!dir.exists()) {
dir.mkdirs();
}
}
public void addResponseByName(String name, byte[] data, String contentType) {
if (name == null || data == null) return;
dataMap.put(name, new ResponseResource<byte[]>(data, contentType));
}
public void addResponseByName(String name, String path, String contentType) {
if (name == null || path == null) return;
resourceMap.put(name, new ResponseResource<String>(path, contentType));
}
public byte[] getResponseByName(String name) {
return dataMap.containsKey(name) ? dataMap.get(name).resource : null;
}
public void stopServer() {
running = false;
if (listenerThread == null) return;
listenerThread.stopServer();
try {
listenerThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getResourceNameFromTarget(String target) {
int lastPos = target.indexOf('?');
return target.substring(1, lastPos >= 0 ? lastPos : target.length());
}
private ArrayList<String> getDirListing(File file) {
if (file == null || !file.isDirectory()) return null;
File[] files = file.listFiles();
ArrayList<File> fileArrayList = new ArrayList<File>();
for (File f : files) {
fileArrayList.add(f);
}
Collections.sort(fileArrayList);
ArrayList<String> fileList = new ArrayList<String>();
for (File f : fileArrayList) {
fileList.add(f.getAbsolutePath().substring(rootDir.length() + 1));
}
return fileList;
}
private String getDirListingHTML(File file) {
ArrayList<String> fileList = getDirListing(file);
String html = "<html><body>";
for (String fileName : fileList) {
html += "<a href='http://" + getLocalIpAddress() + ":" + mPort + "/" + fileName +
"'>" + fileName + "</a><br>";
}
html += "</body></html>";
return html;
}
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("", ex.toString());
}
return null;
}
public void handle(final HttpServerConnection conn, final HttpContext context)
throws HttpException, IOException {
HttpRequest request = conn.receiveRequestHeader();
HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
HttpStatus.SC_OK, "OK");
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") &&
!method.equals("HEAD") &&
!method.equals("POST") &&
!method.equals("PUT")) {
throw new MethodNotSupportedException(method + " method not supported");
}
// Get the requested target. This is the string after the domain name in
// the URL. If the full URL was http://mydomain.com/test.html, target
// will be /test.html.
String target = request.getRequestLine().getUri();
//Log.w(TAG, "*** Request target: " + target);
// Gets the requested resource name. For example, if the full URL was
// http://mydomain.com/test.html?x=1&y=2, resource name will be
// test.html
final String resName = getResourceNameFromTarget(target);
UrlParams params = new UrlParams(target);
//Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString());
//Log.w(TAG, "*** Request resource: " + resName);
if (method.equals("POST") || method.equals("PUT")) {
byte[] entityContent = null;
// Gets the content if the request has an entity.
if (request instanceof HttpEntityEnclosingRequest) {
conn.receiveRequestEntity((HttpEntityEnclosingRequest) request);
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
entityContent = EntityUtils.toByteArray(entity);
}
}
response.setStatusCode(HttpStatus.SC_OK);
if (serverListener != null) {
serverListener.onRequest(resName, params.keys, params.values, entityContent);
}
} else if (dataMap.containsKey(resName)) { // The requested resource is
// a byte array
response.setStatusCode(HttpStatus.SC_OK);
response.setHeader("Content-Type", dataMap.get(resName).contentType);
response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource));
} else { // Resource is a file recognized by the app
String fileName = resourceMap.containsKey(resName) ?
resourceMap.get(resName).resource : resName;
String contentType = resourceMap.containsKey(resName) ?
resourceMap.get(resName).contentType : "text/html";
Log.d(TAG, "*** mapped resource: " + fileName);
Log.d(TAG, "*** checking for file: " + rootDir +
(rootDir.endsWith("/") ? "" : "/") + fileName);
response.setStatusCode(HttpStatus.SC_OK);
final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName);
if (file.exists() && !file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file,
URLConnection.guessContentTypeFromName(fileName));
response.setHeader("Content-Type",
URLConnection.guessContentTypeFromName(fileName));
response.setEntity(body);
} else if (file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_OK);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
ArrayList<String> fileList = getDirListing(file);
String resp = "{ \"list\": [";
for (String fl : fileList) {
resp += "\"" + fl + "\",";
}
resp = resp.substring(0, resp.length() - 1);
resp += "]}";
writer.write(resp);
writer.flush();
}
});
body.setContentType(contentType);
response.setEntity(body);
} else if (resourceMap.containsKey(resName)) {
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write(resourceMap.get(resName).resource);
writer.flush();
}
});
body.setContentType(contentType);
response.setEntity(body);
} else {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
response.setEntity(new StringEntity("Not Found"));
}
}
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
conn.flush();
conn.shutdown();
}
/**
* This thread listens to HTTP requests and delegates it to worker threads.
*/
class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
public RequestListenerThread(int port) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new BasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up the HTTP service
new HttpService(httpproc, new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory());
}
public void stopServer() {
try {
this.serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
Log.d(TAG, "*** Listening on port " + this.serversocket.getLocalPort());
while (running) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
Log.e(TAG, "I/O error initialising connection thread: " + e.getMessage());
break;
}
}
try {
this.serversocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* This thread handles the HTTP requests.
*/
class WorkerThread extends Thread {
private final HttpServerConnection conn;
public WorkerThread(final HttpServerConnection conn) {
super();
this.conn = conn;
}
@Override
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
HttpCommandServer.this.handle(conn, context);
}
} catch (ConnectionClosedException ex) {
Log.e(TAG, "Client closed connection");
} catch (IOException ex) {
ex.printStackTrace();
Log.e(TAG, "I/O error: " + ex.getMessage());
} catch (HttpException ex) {
Log.e(TAG, "Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
/**
* Implement this interface to receive callback when an HTTP PUT/POST
* request is received.
*/
public interface HttpCommandServerListener {
public void onRequest(String req, String[] keys, String[] values, byte[] data);
}
}
|
[
"public",
"class",
"HttpCommandServer",
"{",
"private",
"class",
"ResponseResource",
"<",
"T",
">",
"{",
"public",
"T",
"resource",
";",
"public",
"String",
"contentType",
";",
"public",
"ResponseResource",
"(",
"T",
"res",
",",
"String",
"ct",
")",
"{",
"resource",
"=",
"res",
";",
"contentType",
"=",
"ct",
";",
"}",
"}",
"private",
"class",
"UrlParams",
"{",
"public",
"String",
"[",
"]",
"keys",
";",
"public",
"String",
"[",
"]",
"values",
";",
"public",
"UrlParams",
"(",
"String",
"url",
")",
"{",
"int",
"index",
"=",
"url",
".",
"indexOf",
"(",
"'?'",
")",
";",
"if",
"(",
"index",
">=",
"0",
")",
"{",
"String",
"paramStr",
"=",
"url",
".",
"substring",
"(",
"url",
".",
"indexOf",
"(",
"'?'",
")",
"+",
"1",
")",
";",
"String",
"[",
"]",
"toks",
"=",
"paramStr",
".",
"split",
"(",
"\"",
"&",
"\"",
")",
";",
"keys",
"=",
"new",
"String",
"[",
"toks",
".",
"length",
"]",
";",
"values",
"=",
"new",
"String",
"[",
"toks",
".",
"length",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"String",
"tok",
":",
"toks",
")",
"{",
"String",
"[",
"]",
"tmp",
"=",
"tok",
".",
"split",
"(",
"\"",
"=",
"\"",
")",
";",
"if",
"(",
"tmp",
".",
"length",
">",
"0",
")",
"{",
"keys",
"[",
"i",
"]",
"=",
"tmp",
"[",
"0",
"]",
";",
"if",
"(",
"tmp",
".",
"length",
">",
"1",
")",
"values",
"[",
"i",
"]",
"=",
"tmp",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"keys",
"[",
"i",
"]",
"=",
"tok",
";",
"}",
"i",
"++",
";",
"}",
"}",
"}",
"}",
"private",
"static",
"final",
"String",
"TAG",
"=",
"\"",
"HttpCommandServer",
"\"",
";",
"private",
"static",
"final",
"String",
"EXTERNAL_STORAGE_PATH",
"=",
"Environment",
".",
"getExternalStorageDirectory",
"(",
")",
"+",
"\"",
"/",
"\"",
";",
"private",
"int",
"mPort",
"=",
"8080",
";",
"private",
"String",
"rootDir",
";",
"private",
"RequestListenerThread",
"listenerThread",
";",
"private",
"boolean",
"running",
"=",
"true",
";",
"HashMap",
"<",
"String",
",",
"ResponseResource",
"<",
"byte",
"[",
"]",
">",
">",
"dataMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"ResponseResource",
"<",
"byte",
"[",
"]",
">",
">",
"(",
")",
";",
"HashMap",
"<",
"String",
",",
"ResponseResource",
"<",
"String",
">",
">",
"resourceMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"ResponseResource",
"<",
"String",
">",
">",
"(",
")",
";",
"private",
"HttpCommandServerListener",
"serverListener",
";",
"public",
"HttpCommandServer",
"(",
"String",
"root",
",",
"int",
"port",
",",
"HttpCommandServerListener",
"listener",
")",
"{",
"serverListener",
"=",
"listener",
";",
"mPort",
"=",
"port",
";",
"setRoot",
"(",
"root",
")",
";",
"try",
"{",
"listenerThread",
"=",
"new",
"RequestListenerThread",
"(",
"port",
")",
";",
"listenerThread",
".",
"setDaemon",
"(",
"false",
")",
";",
"listenerThread",
".",
"start",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Error starting HTTP server: ",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"",
"*** IP address: ",
"\"",
"+",
"getLocalIpAddress",
"(",
")",
")",
";",
"}",
"public",
"void",
"setRoot",
"(",
"String",
"root",
")",
"{",
"rootDir",
"=",
"EXTERNAL_STORAGE_PATH",
"+",
"root",
";",
"File",
"dir",
"=",
"new",
"File",
"(",
"EXTERNAL_STORAGE_PATH",
"+",
"root",
")",
";",
"if",
"(",
"!",
"dir",
".",
"exists",
"(",
")",
")",
"{",
"dir",
".",
"mkdirs",
"(",
")",
";",
"}",
"}",
"public",
"void",
"addResponseByName",
"(",
"String",
"name",
",",
"byte",
"[",
"]",
"data",
",",
"String",
"contentType",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"data",
"==",
"null",
")",
"return",
";",
"dataMap",
".",
"put",
"(",
"name",
",",
"new",
"ResponseResource",
"<",
"byte",
"[",
"]",
">",
"(",
"data",
",",
"contentType",
")",
")",
";",
"}",
"public",
"void",
"addResponseByName",
"(",
"String",
"name",
",",
"String",
"path",
",",
"String",
"contentType",
")",
"{",
"if",
"(",
"name",
"==",
"null",
"||",
"path",
"==",
"null",
")",
"return",
";",
"resourceMap",
".",
"put",
"(",
"name",
",",
"new",
"ResponseResource",
"<",
"String",
">",
"(",
"path",
",",
"contentType",
")",
")",
";",
"}",
"public",
"byte",
"[",
"]",
"getResponseByName",
"(",
"String",
"name",
")",
"{",
"return",
"dataMap",
".",
"containsKey",
"(",
"name",
")",
"?",
"dataMap",
".",
"get",
"(",
"name",
")",
".",
"resource",
":",
"null",
";",
"}",
"public",
"void",
"stopServer",
"(",
")",
"{",
"running",
"=",
"false",
";",
"if",
"(",
"listenerThread",
"==",
"null",
")",
"return",
";",
"listenerThread",
".",
"stopServer",
"(",
")",
";",
"try",
"{",
"listenerThread",
".",
"join",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"private",
"String",
"getResourceNameFromTarget",
"(",
"String",
"target",
")",
"{",
"int",
"lastPos",
"=",
"target",
".",
"indexOf",
"(",
"'?'",
")",
";",
"return",
"target",
".",
"substring",
"(",
"1",
",",
"lastPos",
">=",
"0",
"?",
"lastPos",
":",
"target",
".",
"length",
"(",
")",
")",
";",
"}",
"private",
"ArrayList",
"<",
"String",
">",
"getDirListing",
"(",
"File",
"file",
")",
"{",
"if",
"(",
"file",
"==",
"null",
"||",
"!",
"file",
".",
"isDirectory",
"(",
")",
")",
"return",
"null",
";",
"File",
"[",
"]",
"files",
"=",
"file",
".",
"listFiles",
"(",
")",
";",
"ArrayList",
"<",
"File",
">",
"fileArrayList",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
")",
";",
"for",
"(",
"File",
"f",
":",
"files",
")",
"{",
"fileArrayList",
".",
"add",
"(",
"f",
")",
";",
"}",
"Collections",
".",
"sort",
"(",
"fileArrayList",
")",
";",
"ArrayList",
"<",
"String",
">",
"fileList",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"for",
"(",
"File",
"f",
":",
"fileArrayList",
")",
"{",
"fileList",
".",
"add",
"(",
"f",
".",
"getAbsolutePath",
"(",
")",
".",
"substring",
"(",
"rootDir",
".",
"length",
"(",
")",
"+",
"1",
")",
")",
";",
"}",
"return",
"fileList",
";",
"}",
"private",
"String",
"getDirListingHTML",
"(",
"File",
"file",
")",
"{",
"ArrayList",
"<",
"String",
">",
"fileList",
"=",
"getDirListing",
"(",
"file",
")",
";",
"String",
"html",
"=",
"\"",
"<html><body>",
"\"",
";",
"for",
"(",
"String",
"fileName",
":",
"fileList",
")",
"{",
"html",
"+=",
"\"",
"<a href='http://",
"\"",
"+",
"getLocalIpAddress",
"(",
")",
"+",
"\"",
":",
"\"",
"+",
"mPort",
"+",
"\"",
"/",
"\"",
"+",
"fileName",
"+",
"\"",
"'>",
"\"",
"+",
"fileName",
"+",
"\"",
"</a><br>",
"\"",
";",
"}",
"html",
"+=",
"\"",
"</body></html>",
"\"",
";",
"return",
"html",
";",
"}",
"public",
"String",
"getLocalIpAddress",
"(",
")",
"{",
"try",
"{",
"for",
"(",
"Enumeration",
"<",
"NetworkInterface",
">",
"en",
"=",
"NetworkInterface",
".",
"getNetworkInterfaces",
"(",
")",
";",
"en",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"NetworkInterface",
"intf",
"=",
"en",
".",
"nextElement",
"(",
")",
";",
"for",
"(",
"Enumeration",
"<",
"InetAddress",
">",
"enumIpAddr",
"=",
"intf",
".",
"getInetAddresses",
"(",
")",
";",
"enumIpAddr",
".",
"hasMoreElements",
"(",
")",
";",
")",
"{",
"InetAddress",
"inetAddress",
"=",
"enumIpAddr",
".",
"nextElement",
"(",
")",
";",
"if",
"(",
"!",
"inetAddress",
".",
"isLoopbackAddress",
"(",
")",
")",
"{",
"return",
"inetAddress",
".",
"getHostAddress",
"(",
")",
".",
"toString",
"(",
")",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"SocketException",
"ex",
")",
"{",
"Log",
".",
"e",
"(",
"\"",
"\"",
",",
"ex",
".",
"toString",
"(",
")",
")",
";",
"}",
"return",
"null",
";",
"}",
"public",
"void",
"handle",
"(",
"final",
"HttpServerConnection",
"conn",
",",
"final",
"HttpContext",
"context",
")",
"throws",
"HttpException",
",",
"IOException",
"{",
"HttpRequest",
"request",
"=",
"conn",
".",
"receiveRequestHeader",
"(",
")",
";",
"HttpResponse",
"response",
"=",
"new",
"BasicHttpResponse",
"(",
"new",
"ProtocolVersion",
"(",
"\"",
"HTTP",
"\"",
",",
"1",
",",
"1",
")",
",",
"HttpStatus",
".",
"SC_OK",
",",
"\"",
"OK",
"\"",
")",
";",
"String",
"method",
"=",
"request",
".",
"getRequestLine",
"(",
")",
".",
"getMethod",
"(",
")",
".",
"toUpperCase",
"(",
"Locale",
".",
"ENGLISH",
")",
";",
"if",
"(",
"!",
"method",
".",
"equals",
"(",
"\"",
"GET",
"\"",
")",
"&&",
"!",
"method",
".",
"equals",
"(",
"\"",
"HEAD",
"\"",
")",
"&&",
"!",
"method",
".",
"equals",
"(",
"\"",
"POST",
"\"",
")",
"&&",
"!",
"method",
".",
"equals",
"(",
"\"",
"PUT",
"\"",
")",
")",
"{",
"throw",
"new",
"MethodNotSupportedException",
"(",
"method",
"+",
"\"",
" method not supported",
"\"",
")",
";",
"}",
"String",
"target",
"=",
"request",
".",
"getRequestLine",
"(",
")",
".",
"getUri",
"(",
")",
";",
"final",
"String",
"resName",
"=",
"getResourceNameFromTarget",
"(",
"target",
")",
";",
"UrlParams",
"params",
"=",
"new",
"UrlParams",
"(",
"target",
")",
";",
"if",
"(",
"method",
".",
"equals",
"(",
"\"",
"POST",
"\"",
")",
"||",
"method",
".",
"equals",
"(",
"\"",
"PUT",
"\"",
")",
")",
"{",
"byte",
"[",
"]",
"entityContent",
"=",
"null",
";",
"if",
"(",
"request",
"instanceof",
"HttpEntityEnclosingRequest",
")",
"{",
"conn",
".",
"receiveRequestEntity",
"(",
"(",
"HttpEntityEnclosingRequest",
")",
"request",
")",
";",
"HttpEntity",
"entity",
"=",
"(",
"(",
"HttpEntityEnclosingRequest",
")",
"request",
")",
".",
"getEntity",
"(",
")",
";",
"if",
"(",
"entity",
"!=",
"null",
")",
"{",
"entityContent",
"=",
"EntityUtils",
".",
"toByteArray",
"(",
"entity",
")",
";",
"}",
"}",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_OK",
")",
";",
"if",
"(",
"serverListener",
"!=",
"null",
")",
"{",
"serverListener",
".",
"onRequest",
"(",
"resName",
",",
"params",
".",
"keys",
",",
"params",
".",
"values",
",",
"entityContent",
")",
";",
"}",
"}",
"else",
"if",
"(",
"dataMap",
".",
"containsKey",
"(",
"resName",
")",
")",
"{",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_OK",
")",
";",
"response",
".",
"setHeader",
"(",
"\"",
"Content-Type",
"\"",
",",
"dataMap",
".",
"get",
"(",
"resName",
")",
".",
"contentType",
")",
";",
"response",
".",
"setEntity",
"(",
"new",
"ByteArrayEntity",
"(",
"dataMap",
".",
"get",
"(",
"resName",
")",
".",
"resource",
")",
")",
";",
"}",
"else",
"{",
"String",
"fileName",
"=",
"resourceMap",
".",
"containsKey",
"(",
"resName",
")",
"?",
"resourceMap",
".",
"get",
"(",
"resName",
")",
".",
"resource",
":",
"resName",
";",
"String",
"contentType",
"=",
"resourceMap",
".",
"containsKey",
"(",
"resName",
")",
"?",
"resourceMap",
".",
"get",
"(",
"resName",
")",
".",
"contentType",
":",
"\"",
"text/html",
"\"",
";",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"",
"*** mapped resource: ",
"\"",
"+",
"fileName",
")",
";",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"",
"*** checking for file: ",
"\"",
"+",
"rootDir",
"+",
"(",
"rootDir",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
"?",
"\"",
"\"",
":",
"\"",
"/",
"\"",
")",
"+",
"fileName",
")",
";",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_OK",
")",
";",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"rootDir",
"+",
"(",
"rootDir",
".",
"endsWith",
"(",
"\"",
"/",
"\"",
")",
"?",
"\"",
"\"",
":",
"\"",
"/",
"\"",
")",
"+",
"fileName",
")",
";",
"if",
"(",
"file",
".",
"exists",
"(",
")",
"&&",
"!",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_OK",
")",
";",
"FileEntity",
"body",
"=",
"new",
"FileEntity",
"(",
"file",
",",
"URLConnection",
".",
"guessContentTypeFromName",
"(",
"fileName",
")",
")",
";",
"response",
".",
"setHeader",
"(",
"\"",
"Content-Type",
"\"",
",",
"URLConnection",
".",
"guessContentTypeFromName",
"(",
"fileName",
")",
")",
";",
"response",
".",
"setEntity",
"(",
"body",
")",
";",
"}",
"else",
"if",
"(",
"file",
".",
"isDirectory",
"(",
")",
")",
"{",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_OK",
")",
";",
"EntityTemplate",
"body",
"=",
"new",
"EntityTemplate",
"(",
"new",
"ContentProducer",
"(",
")",
"{",
"public",
"void",
"writeTo",
"(",
"final",
"OutputStream",
"outstream",
")",
"throws",
"IOException",
"{",
"OutputStreamWriter",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"outstream",
",",
"\"",
"UTF-8",
"\"",
")",
";",
"ArrayList",
"<",
"String",
">",
"fileList",
"=",
"getDirListing",
"(",
"file",
")",
";",
"String",
"resp",
"=",
"\"",
"{ ",
"\\\"",
"list",
"\\\"",
": [",
"\"",
";",
"for",
"(",
"String",
"fl",
":",
"fileList",
")",
"{",
"resp",
"+=",
"\"",
"\\\"",
"\"",
"+",
"fl",
"+",
"\"",
"\\\"",
",",
"\"",
";",
"}",
"resp",
"=",
"resp",
".",
"substring",
"(",
"0",
",",
"resp",
".",
"length",
"(",
")",
"-",
"1",
")",
";",
"resp",
"+=",
"\"",
"]}",
"\"",
";",
"writer",
".",
"write",
"(",
"resp",
")",
";",
"writer",
".",
"flush",
"(",
")",
";",
"}",
"}",
")",
";",
"body",
".",
"setContentType",
"(",
"contentType",
")",
";",
"response",
".",
"setEntity",
"(",
"body",
")",
";",
"}",
"else",
"if",
"(",
"resourceMap",
".",
"containsKey",
"(",
"resName",
")",
")",
"{",
"EntityTemplate",
"body",
"=",
"new",
"EntityTemplate",
"(",
"new",
"ContentProducer",
"(",
")",
"{",
"public",
"void",
"writeTo",
"(",
"final",
"OutputStream",
"outstream",
")",
"throws",
"IOException",
"{",
"OutputStreamWriter",
"writer",
"=",
"new",
"OutputStreamWriter",
"(",
"outstream",
",",
"\"",
"UTF-8",
"\"",
")",
";",
"writer",
".",
"write",
"(",
"resourceMap",
".",
"get",
"(",
"resName",
")",
".",
"resource",
")",
";",
"writer",
".",
"flush",
"(",
")",
";",
"}",
"}",
")",
";",
"body",
".",
"setContentType",
"(",
"contentType",
")",
";",
"response",
".",
"setEntity",
"(",
"body",
")",
";",
"}",
"else",
"{",
"response",
".",
"setStatusCode",
"(",
"HttpStatus",
".",
"SC_NOT_FOUND",
")",
";",
"response",
".",
"setEntity",
"(",
"new",
"StringEntity",
"(",
"\"",
"Not Found",
"\"",
")",
")",
";",
"}",
"}",
"conn",
".",
"sendResponseHeader",
"(",
"response",
")",
";",
"conn",
".",
"sendResponseEntity",
"(",
"response",
")",
";",
"conn",
".",
"flush",
"(",
")",
";",
"conn",
".",
"shutdown",
"(",
")",
";",
"}",
"/**\n * This thread listens to HTTP requests and delegates it to worker threads.\n */",
"class",
"RequestListenerThread",
"extends",
"Thread",
"{",
"private",
"final",
"ServerSocket",
"serversocket",
";",
"private",
"final",
"HttpParams",
"params",
";",
"public",
"RequestListenerThread",
"(",
"int",
"port",
")",
"throws",
"IOException",
"{",
"this",
".",
"serversocket",
"=",
"new",
"ServerSocket",
"(",
"port",
")",
";",
"this",
".",
"params",
"=",
"new",
"BasicHttpParams",
"(",
")",
";",
"this",
".",
"params",
".",
"setIntParameter",
"(",
"CoreConnectionPNames",
".",
"SO_TIMEOUT",
",",
"5000",
")",
".",
"setIntParameter",
"(",
"CoreConnectionPNames",
".",
"SOCKET_BUFFER_SIZE",
",",
"8",
"*",
"1024",
")",
".",
"setBooleanParameter",
"(",
"CoreConnectionPNames",
".",
"STALE_CONNECTION_CHECK",
",",
"false",
")",
".",
"setBooleanParameter",
"(",
"CoreConnectionPNames",
".",
"TCP_NODELAY",
",",
"true",
")",
".",
"setParameter",
"(",
"CoreProtocolPNames",
".",
"ORIGIN_SERVER",
",",
"\"",
"HttpComponents/1.1",
"\"",
")",
";",
"BasicHttpProcessor",
"httpproc",
"=",
"new",
"BasicHttpProcessor",
"(",
")",
";",
"httpproc",
".",
"addInterceptor",
"(",
"new",
"ResponseDate",
"(",
")",
")",
";",
"httpproc",
".",
"addInterceptor",
"(",
"new",
"ResponseServer",
"(",
")",
")",
";",
"httpproc",
".",
"addInterceptor",
"(",
"new",
"ResponseContent",
"(",
")",
")",
";",
"httpproc",
".",
"addInterceptor",
"(",
"new",
"ResponseConnControl",
"(",
")",
")",
";",
"new",
"HttpService",
"(",
"httpproc",
",",
"new",
"DefaultConnectionReuseStrategy",
"(",
")",
",",
"new",
"DefaultHttpResponseFactory",
"(",
")",
")",
";",
"}",
"public",
"void",
"stopServer",
"(",
")",
"{",
"try",
"{",
"this",
".",
"serversocket",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"",
"*** Listening on port ",
"\"",
"+",
"this",
".",
"serversocket",
".",
"getLocalPort",
"(",
")",
")",
";",
"while",
"(",
"running",
")",
"{",
"try",
"{",
"Socket",
"socket",
"=",
"this",
".",
"serversocket",
".",
"accept",
"(",
")",
";",
"DefaultHttpServerConnection",
"conn",
"=",
"new",
"DefaultHttpServerConnection",
"(",
")",
";",
"conn",
".",
"bind",
"(",
"socket",
",",
"this",
".",
"params",
")",
";",
"Thread",
"t",
"=",
"new",
"WorkerThread",
"(",
"conn",
")",
";",
"t",
".",
"setDaemon",
"(",
"true",
")",
";",
"t",
".",
"start",
"(",
")",
";",
"}",
"catch",
"(",
"InterruptedIOException",
"ex",
")",
"{",
"break",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"I/O error initialising connection thread: ",
"\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"try",
"{",
"this",
".",
"serversocket",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"e",
".",
"printStackTrace",
"(",
")",
";",
"}",
"}",
"}",
"/**\n * This thread handles the HTTP requests.\n */",
"class",
"WorkerThread",
"extends",
"Thread",
"{",
"private",
"final",
"HttpServerConnection",
"conn",
";",
"public",
"WorkerThread",
"(",
"final",
"HttpServerConnection",
"conn",
")",
"{",
"super",
"(",
")",
";",
"this",
".",
"conn",
"=",
"conn",
";",
"}",
"@",
"Override",
"public",
"void",
"run",
"(",
")",
"{",
"HttpContext",
"context",
"=",
"new",
"BasicHttpContext",
"(",
"null",
")",
";",
"try",
"{",
"while",
"(",
"!",
"Thread",
".",
"interrupted",
"(",
")",
"&&",
"this",
".",
"conn",
".",
"isOpen",
"(",
")",
")",
"{",
"HttpCommandServer",
".",
"this",
".",
"handle",
"(",
"conn",
",",
"context",
")",
";",
"}",
"}",
"catch",
"(",
"ConnectionClosedException",
"ex",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Client closed connection",
"\"",
")",
";",
"}",
"catch",
"(",
"IOException",
"ex",
")",
"{",
"ex",
".",
"printStackTrace",
"(",
")",
";",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"I/O error: ",
"\"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"HttpException",
"ex",
")",
"{",
"Log",
".",
"e",
"(",
"TAG",
",",
"\"",
"Unrecoverable HTTP protocol violation: ",
"\"",
"+",
"ex",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"finally",
"{",
"try",
"{",
"this",
".",
"conn",
".",
"shutdown",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"ignore",
")",
"{",
"}",
"}",
"}",
"}",
"/**\n * Implement this interface to receive callback when an HTTP PUT/POST\n * request is received.\n */",
"public",
"interface",
"HttpCommandServerListener",
"{",
"public",
"void",
"onRequest",
"(",
"String",
"req",
",",
"String",
"[",
"]",
"keys",
",",
"String",
"[",
"]",
"values",
",",
"byte",
"[",
"]",
"data",
")",
";",
"}",
"}"
] |
This is the HTTP server that runs locally and listens on the specified port.
|
[
"This",
"is",
"the",
"HTTP",
"server",
"that",
"runs",
"locally",
"and",
"listens",
"on",
"the",
"specified",
"port",
"."
] |
[
"// TODO Auto-generated catch block",
"// Get the requested target. This is the string after the domain name in",
"// the URL. If the full URL was http://mydomain.com/test.html, target",
"// will be /test.html.",
"//Log.w(TAG, \"*** Request target: \" + target);",
"// Gets the requested resource name. For example, if the full URL was",
"// http://mydomain.com/test.html?x=1&y=2, resource name will be",
"// test.html",
"//Log.w(TAG, \"*** Request LINE: \" + request.getRequestLine().toString());",
"//Log.w(TAG, \"*** Request resource: \" + resName);",
"// Gets the content if the request has an entity.",
"// The requested resource is",
"// a byte array",
"// Resource is a file recognized by the app",
"// Set up the HTTP protocol processor",
"// Set up the HTTP service",
"// Set up HTTP connection",
"// Start worker thread"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 26
| 2,755
| 316
|
8b1b69bb14a3815da604b6257d4742c5c6af214f
|
Dot42Xna/master
|
Generated/v2.3.3/Org.Apache.Http.Impl.Io.cs
|
[
"Apache-2.0"
] |
C#
|
ChunkedInputStream
|
/// <summary>
/// <para>Implements chunked transfer coding. See , . It transparently coalesces chunks of a HTTP stream that uses chunked transfer coding. After the stream is read to the end, it provides access to the trailers, if any. </para><para>Note that this class NEVER closes the underlying stream, even when close gets called. Instead, it will read until the "end" of its chunking on close, which allows for the seamless execution of subsequent HTTP 1.1 requests, while not requiring the client to remember to read the entire contents of the response. </para><para><para>Ortwin Glueck </para><simplesectsep></simplesectsep><para>Sean C. Sullivan </para><simplesectsep></simplesectsep><para>Martin Elwin </para><simplesectsep></simplesectsep><para>Eric Johnson </para><simplesectsep></simplesectsep><para> </para><simplesectsep></simplesectsep><para>Michael Becke </para><simplesectsep></simplesectsep><para></para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/impl/io/ChunkedInputStream
/// </java-name>
|
Implements chunked transfer coding. See , . It transparently coalesces chunks of a HTTP stream that uses chunked transfer coding. After the stream is read to the end, it provides access to the trailers, if any. Note that this class NEVER closes the underlying stream, even when close gets called. Instead, it will read until the "end" of its chunking on close, which allows for the seamless execution of subsequent HTTP 1.1 requests, while not requiring the client to remember to read the entire contents of the response.
Ortwin Glueck Sean C. Sullivan Martin Elwin Eric Johnson Michael Becke 4.0
|
[
"Implements",
"chunked",
"transfer",
"coding",
".",
"See",
".",
"It",
"transparently",
"coalesces",
"chunks",
"of",
"a",
"HTTP",
"stream",
"that",
"uses",
"chunked",
"transfer",
"coding",
".",
"After",
"the",
"stream",
"is",
"read",
"to",
"the",
"end",
"it",
"provides",
"access",
"to",
"the",
"trailers",
"if",
"any",
".",
"Note",
"that",
"this",
"class",
"NEVER",
"closes",
"the",
"underlying",
"stream",
"even",
"when",
"close",
"gets",
"called",
".",
"Instead",
"it",
"will",
"read",
"until",
"the",
"\"",
"end",
"\"",
"of",
"its",
"chunking",
"on",
"close",
"which",
"allows",
"for",
"the",
"seamless",
"execution",
"of",
"subsequent",
"HTTP",
"1",
".",
"1",
"requests",
"while",
"not",
"requiring",
"the",
"client",
"to",
"remember",
"to",
"read",
"the",
"entire",
"contents",
"of",
"the",
"response",
".",
"Ortwin",
"Glueck",
"Sean",
"C",
".",
"Sullivan",
"Martin",
"Elwin",
"Eric",
"Johnson",
"Michael",
"Becke",
"4",
".",
"0"
] |
[Dot42.DexImport("org/apache/http/impl/io/ChunkedInputStream", AccessFlags = 33)]
public partial class ChunkedInputStream : global::Java.Io.InputStream
{
[Dot42.DexImport("<init>", "(Lorg/apache/http/io/SessionInputBuffer;)V", AccessFlags = 1)]
public ChunkedInputStream(global::Org.Apache.Http.Io.ISessionInputBuffer @in)
{
}
[Dot42.DexImport("read", "()I", AccessFlags = 1)]
public override int Read()
{
return default(int);
}
[Dot42.DexImport("read", "([BII)I", AccessFlags = 1)]
public override int Read(sbyte[] b, int off, int len)
{
return default(int);
}
[Dot42.DexImport("read", "([BII)I", AccessFlags = 1, IgnoreFromJava = true)]
public override int Read(byte[] b, int off, int len)
{
return default(int);
}
[Dot42.DexImport("read", "([B)I", AccessFlags = 1)]
public override int Read(sbyte[] b)
{
return default(int);
}
[Dot42.DexImport("read", "([B)I", AccessFlags = 1, IgnoreFromJava = true)]
public override int Read(byte[] b)
{
return default(int);
}
[Dot42.DexImport("close", "()V", AccessFlags = 1)]
public override void Close()
{
}
[Dot42.DexImport("getFooters", "()[Lorg/apache/http/Header;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IHeader[] GetFooters()
{
return default(global::Org.Apache.Http.IHeader[]);
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
internal ChunkedInputStream()
{
}
public global::Org.Apache.Http.IHeader[] Footers
{
[Dot42.DexImport("getFooters", "()[Lorg/apache/http/Header;", AccessFlags = 1)]
get{ return GetFooters(); }
}
}
|
[
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"org/apache/http/impl/io/ChunkedInputStream",
"\"",
",",
"AccessFlags",
"=",
"33",
")",
"]",
"public",
"partial",
"class",
"ChunkedInputStream",
":",
"global",
"::",
"Java",
".",
"Io",
".",
"InputStream",
"{",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"<init>",
"\"",
",",
"\"",
"(Lorg/apache/http/io/SessionInputBuffer;)V",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"ChunkedInputStream",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"Io",
".",
"ISessionInputBuffer",
"@in",
")",
"{",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"read",
"\"",
",",
"\"",
"()I",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"int",
"Read",
"(",
")",
"{",
"return",
"default",
"(",
"int",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"read",
"\"",
",",
"\"",
"([BII)I",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"int",
"Read",
"(",
"sbyte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"return",
"default",
"(",
"int",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"read",
"\"",
",",
"\"",
"([BII)I",
"\"",
",",
"AccessFlags",
"=",
"1",
",",
"IgnoreFromJava",
"=",
"true",
")",
"]",
"public",
"override",
"int",
"Read",
"(",
"byte",
"[",
"]",
"b",
",",
"int",
"off",
",",
"int",
"len",
")",
"{",
"return",
"default",
"(",
"int",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"read",
"\"",
",",
"\"",
"([B)I",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"int",
"Read",
"(",
"sbyte",
"[",
"]",
"b",
")",
"{",
"return",
"default",
"(",
"int",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"read",
"\"",
",",
"\"",
"([B)I",
"\"",
",",
"AccessFlags",
"=",
"1",
",",
"IgnoreFromJava",
"=",
"true",
")",
"]",
"public",
"override",
"int",
"Read",
"(",
"byte",
"[",
"]",
"b",
")",
"{",
"return",
"default",
"(",
"int",
")",
";",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"close",
"\"",
",",
"\"",
"()V",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"override",
"void",
"Close",
"(",
")",
"{",
"}",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"getFooters",
"\"",
",",
"\"",
"()[Lorg/apache/http/Header;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"public",
"virtual",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"IHeader",
"[",
"]",
"GetFooters",
"(",
")",
"{",
"return",
"default",
"(",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"IHeader",
"[",
"]",
")",
";",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsable",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Never",
")",
"]",
"internal",
"ChunkedInputStream",
"(",
")",
"{",
"}",
"public",
"global",
"::",
"Org",
".",
"Apache",
".",
"Http",
".",
"IHeader",
"[",
"]",
"Footers",
"{",
"[",
"Dot42",
".",
"DexImport",
"(",
"\"",
"getFooters",
"\"",
",",
"\"",
"()[Lorg/apache/http/Header;",
"\"",
",",
"AccessFlags",
"=",
"1",
")",
"]",
"get",
"{",
"return",
"GetFooters",
"(",
")",
";",
"}",
"}",
"}"
] |
Implements chunked transfer coding.
|
[
"Implements",
"chunked",
"transfer",
"coding",
"."
] |
[
"/* scope: __dot42__ */",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Returns all the data in a chunked stream in coalesced form. A chunk is followed by a CRLF. The method returns -1 as soon as a chunksize of 0 is detected.</para><para>Trailer headers are read automcatically at the end of the stream and can be obtained with the getResponseFooters() method.</para><para></para> ",
"/// </summary>",
"/// <returns>",
"/// <para>-1 of the end of the stream has been reached or the next data byte </para>",
"/// </returns>",
"/// <java-name>",
"/// read",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Read some bytes from the stream. <para>java.io.InputStream::read(byte[], int, int) </para></para> ",
"/// </summary>",
"/// <returns>",
"/// <para>The number of bytes returned or -1 if the end of stream has been reached. </para>",
"/// </returns>",
"/// <java-name>",
"/// read",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Read some bytes from the stream. <para>java.io.InputStream::read(byte[], int, int) </para></para> ",
"/// </summary>",
"/// <returns>",
"/// <para>The number of bytes returned or -1 if the end of stream has been reached. </para>",
"/// </returns>",
"/// <java-name>",
"/// read",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Read some bytes from the stream. <para>java.io.InputStream::read(byte[]) </para></para> ",
"/// </summary>",
"/// <returns>",
"/// <para>The number of bytes returned or -1 if the end of stream has been reached. </para>",
"/// </returns>",
"/// <java-name>",
"/// read",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Read some bytes from the stream. <para>java.io.InputStream::read(byte[]) </para></para> ",
"/// </summary>",
"/// <returns>",
"/// <para>The number of bytes returned or -1 if the end of stream has been reached. </para>",
"/// </returns>",
"/// <java-name>",
"/// read",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <summary>",
"/// <para>Upon close, this reads the remainder of the chunked message, leaving the underlying socket at a position to start reading the next response without scanning. </para> ",
"/// </summary>",
"/// <java-name>",
"/// close",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/// <java-name>",
"/// getFooters",
"/// </java-name>",
"/* MethodBuilder.Create */",
"/* TypeBuilder.AddDefaultConstructor */",
"/// <java-name>",
"/// getFooters",
"/// </java-name>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "java-name",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 13
| 537
| 265
|
a9c227e90d2956ee063aaa5f2625b0964ec380b6
|
taldcroft/deproject
|
src/deproject/fieldstore.py
|
[
"BSD-2-Clause"
] |
Python
|
FieldStore
|
Run and convert an object with keys to a set of values.
Parameters
----------
runfunc : function
The function to call, which takes as argument the dataset ids.
getfunc : function
The function to call to return the structure. It takes no
arguments.
fields : sequence of str
The field names to report, and the order to use. These fields
must exist in the object returned by the getfunc.
|
Run and convert an object with keys to a set of values.
Parameters
runfunc : function
The function to call, which takes as argument the dataset ids.
getfunc : function
The function to call to return the structure. It takes no
arguments.
fields : sequence of str
The field names to report, and the order to use. These fields
must exist in the object returned by the getfunc.
|
[
"Run",
"and",
"convert",
"an",
"object",
"with",
"keys",
"to",
"a",
"set",
"of",
"values",
".",
"Parameters",
"runfunc",
":",
"function",
"The",
"function",
"to",
"call",
"which",
"takes",
"as",
"argument",
"the",
"dataset",
"ids",
".",
"getfunc",
":",
"function",
"The",
"function",
"to",
"call",
"to",
"return",
"the",
"structure",
".",
"It",
"takes",
"no",
"arguments",
".",
"fields",
":",
"sequence",
"of",
"str",
"The",
"field",
"names",
"to",
"report",
"and",
"the",
"order",
"to",
"use",
".",
"These",
"fields",
"must",
"exist",
"in",
"the",
"object",
"returned",
"by",
"the",
"getfunc",
"."
] |
class FieldStore:
"""Run and convert an object with keys to a set of values.
Parameters
----------
runfunc : function
The function to call, which takes as argument the dataset ids.
getfunc : function
The function to call to return the structure. It takes no
arguments.
fields : sequence of str
The field names to report, and the order to use. These fields
must exist in the object returned by the getfunc.
"""
def __init__(self, runfunc, getfunc, fields):
if not callable(runfunc):
raise ValueError("runfunc must be callable")
if not callable(getfunc):
raise ValueError("getfunc must be callable")
self._run = runfunc
self._get = getfunc
# Copy the fields and ensure it is a list; I'm not sure why I
# want a list, but a list we get.
#
self._fields = [f for f in fields]
def run(self, annuli, components, *ids):
"""Run the function and return the values.
Parameters
----------
annuli : dict
The key is the dataset identifier and the value the annulus
number.
components : dict
The keys are the annulus number and the values are a list of
tuples of (model components, parent model name).
*ids : dataset identifiers
The dataset identifiers to use. They must all exist as keys
in the `annuli` map.
Returns
-------
data : dict of OrderedDict values
The keys are the annulus value, and the values are the
shell results. The order of the keys in the results dict is
defined by the fields list given to the object constructor.
Notes
-----
There is only support for simple parameter links, where one parameter
is set equal to another, and both model components are associated
with the given set of dataset identifiers.
"""
anns = sorted(list(set([annuli[i] for i in ids])))
datamap = defaultdict(list)
for i, ann in annuli.items():
if ann not in anns:
continue
datamap[ann].append(i)
self._run(*ids)
indata = self._get()
# Group the data by annulus. The assumption here is that each
# dataset in the same annulus has the same set of model components.
#
# All the fields are copied over to each annulus except for
# datasets
# parameter values
# which are restricted to the given annulus.
#
anndata = {}
for ann in anns:
dids = datamap[ann]
# Sanity check
for did in dids:
if did not in indata.datasets:
raise RuntimeError("Dataset {} not found in the ouput!".format(did))
# Create the non-parameter columns
#
store = OrderedDict()
store['datasets'] = dids
for field in self._fields:
if field == 'datasets':
continue
store[field] = getattr(indata, field)
for mcpt, pname in components[ann]:
for par in mcpt.pars:
# It would be nice to report these values too,
# for completeness, but leave for now.
#
# Note: linked parameters appear to be marked as
# frozen...
#
# I think a better check may be needed (or send in
# the actual pars to report).
#
if par.frozen and par.link is None:
continue
# It is important to use the "base" name for the
# parameter - e.g 'xsapec.kT' - rather than the
# name for this shell (e.g. 'xsapec_0.kT').
#
name = "{}.{}".format(pname, par.name)
self._extract(indata, par, name, store)
anndata[ann] = store
return anndata
def _extract(self, datavals, par, field, store):
"""Extract the parameter value from the results structure.
Parameters
----------
datavals
The results structure (FitResults, ErrorEstResults).
par : sherpa.models.parameter.Parameter instance
The model parameter of interest. It must be related to the
datasets in datavals.
field : str
The name of the item of interest.
store : dict
The results are added to this structure, using the field key
(multiple values can be added, in which case the field is
expected to be a suffix).
"""
name = par.fullname
# Just want the value. Could just take the value from the
# parameter input, but use the value in datavals.
#
if self._store(datavals, name, field, store):
return
# Parameter not found, which should mean it is a link
#
if par.link is None:
raise ValueError("Parameter {} not found in the fit results".format(name))
# For now only support simple links - equality and not a more-complex
# functional relationship. Assume that checking whether modelname
# is not empty is a sufficient check
#
if par.link.modelname == '':
raise ValueError("Unable to handle complex parameter links: {}".format(name))
if self._store(datavals, par.link.fullname, field, store):
return
raise ValueError("Unable to find linked value for {}".format(name))
def _store(self, datavals, name, field, store):
"""Add the values to the output structure.
This functionality is provided by the sub-classes.
Parameters
----------
datavals
The results structure (FitResults, ErrorEstResults).
name : str
The parameter name.
field : str
The name of the item of interest.
store : dict
The results are added to this structure, using the field key
(multiple values can be added, in which case the field is
expected to be a suffix).
Returns
-------
flag : bool
True if the parameter was found and added to store, False
otherwise.
"""
raise NotImplementedError()
|
[
"class",
"FieldStore",
":",
"def",
"__init__",
"(",
"self",
",",
"runfunc",
",",
"getfunc",
",",
"fields",
")",
":",
"if",
"not",
"callable",
"(",
"runfunc",
")",
":",
"raise",
"ValueError",
"(",
"\"runfunc must be callable\"",
")",
"if",
"not",
"callable",
"(",
"getfunc",
")",
":",
"raise",
"ValueError",
"(",
"\"getfunc must be callable\"",
")",
"self",
".",
"_run",
"=",
"runfunc",
"self",
".",
"_get",
"=",
"getfunc",
"self",
".",
"_fields",
"=",
"[",
"f",
"for",
"f",
"in",
"fields",
"]",
"def",
"run",
"(",
"self",
",",
"annuli",
",",
"components",
",",
"*",
"ids",
")",
":",
"\"\"\"Run the function and return the values.\n\n Parameters\n ----------\n annuli : dict\n The key is the dataset identifier and the value the annulus\n number.\n components : dict\n The keys are the annulus number and the values are a list of\n tuples of (model components, parent model name).\n *ids : dataset identifiers\n The dataset identifiers to use. They must all exist as keys\n in the `annuli` map.\n\n Returns\n -------\n data : dict of OrderedDict values\n The keys are the annulus value, and the values are the\n shell results. The order of the keys in the results dict is\n defined by the fields list given to the object constructor.\n\n Notes\n -----\n There is only support for simple parameter links, where one parameter\n is set equal to another, and both model components are associated\n with the given set of dataset identifiers.\n\n \"\"\"",
"anns",
"=",
"sorted",
"(",
"list",
"(",
"set",
"(",
"[",
"annuli",
"[",
"i",
"]",
"for",
"i",
"in",
"ids",
"]",
")",
")",
")",
"datamap",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"i",
",",
"ann",
"in",
"annuli",
".",
"items",
"(",
")",
":",
"if",
"ann",
"not",
"in",
"anns",
":",
"continue",
"datamap",
"[",
"ann",
"]",
".",
"append",
"(",
"i",
")",
"self",
".",
"_run",
"(",
"*",
"ids",
")",
"indata",
"=",
"self",
".",
"_get",
"(",
")",
"anndata",
"=",
"{",
"}",
"for",
"ann",
"in",
"anns",
":",
"dids",
"=",
"datamap",
"[",
"ann",
"]",
"for",
"did",
"in",
"dids",
":",
"if",
"did",
"not",
"in",
"indata",
".",
"datasets",
":",
"raise",
"RuntimeError",
"(",
"\"Dataset {} not found in the ouput!\"",
".",
"format",
"(",
"did",
")",
")",
"store",
"=",
"OrderedDict",
"(",
")",
"store",
"[",
"'datasets'",
"]",
"=",
"dids",
"for",
"field",
"in",
"self",
".",
"_fields",
":",
"if",
"field",
"==",
"'datasets'",
":",
"continue",
"store",
"[",
"field",
"]",
"=",
"getattr",
"(",
"indata",
",",
"field",
")",
"for",
"mcpt",
",",
"pname",
"in",
"components",
"[",
"ann",
"]",
":",
"for",
"par",
"in",
"mcpt",
".",
"pars",
":",
"if",
"par",
".",
"frozen",
"and",
"par",
".",
"link",
"is",
"None",
":",
"continue",
"name",
"=",
"\"{}.{}\"",
".",
"format",
"(",
"pname",
",",
"par",
".",
"name",
")",
"self",
".",
"_extract",
"(",
"indata",
",",
"par",
",",
"name",
",",
"store",
")",
"anndata",
"[",
"ann",
"]",
"=",
"store",
"return",
"anndata",
"def",
"_extract",
"(",
"self",
",",
"datavals",
",",
"par",
",",
"field",
",",
"store",
")",
":",
"\"\"\"Extract the parameter value from the results structure.\n\n Parameters\n ----------\n datavals\n The results structure (FitResults, ErrorEstResults).\n par : sherpa.models.parameter.Parameter instance\n The model parameter of interest. It must be related to the\n datasets in datavals.\n field : str\n The name of the item of interest.\n store : dict\n The results are added to this structure, using the field key\n (multiple values can be added, in which case the field is\n expected to be a suffix).\n\n \"\"\"",
"name",
"=",
"par",
".",
"fullname",
"if",
"self",
".",
"_store",
"(",
"datavals",
",",
"name",
",",
"field",
",",
"store",
")",
":",
"return",
"if",
"par",
".",
"link",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Parameter {} not found in the fit results\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"par",
".",
"link",
".",
"modelname",
"==",
"''",
":",
"raise",
"ValueError",
"(",
"\"Unable to handle complex parameter links: {}\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"self",
".",
"_store",
"(",
"datavals",
",",
"par",
".",
"link",
".",
"fullname",
",",
"field",
",",
"store",
")",
":",
"return",
"raise",
"ValueError",
"(",
"\"Unable to find linked value for {}\"",
".",
"format",
"(",
"name",
")",
")",
"def",
"_store",
"(",
"self",
",",
"datavals",
",",
"name",
",",
"field",
",",
"store",
")",
":",
"\"\"\"Add the values to the output structure.\n\n This functionality is provided by the sub-classes.\n\n Parameters\n ----------\n datavals\n The results structure (FitResults, ErrorEstResults).\n name : str\n The parameter name.\n field : str\n The name of the item of interest.\n store : dict\n The results are added to this structure, using the field key\n (multiple values can be added, in which case the field is\n expected to be a suffix).\n\n Returns\n -------\n flag : bool\n True if the parameter was found and added to store, False\n otherwise.\n\n \"\"\"",
"raise",
"NotImplementedError",
"(",
")"
] |
Run and convert an object with keys to a set of values.
|
[
"Run",
"and",
"convert",
"an",
"object",
"with",
"keys",
"to",
"a",
"set",
"of",
"values",
"."
] |
[
"\"\"\"Run and convert an object with keys to a set of values.\n\n Parameters\n ----------\n runfunc : function\n The function to call, which takes as argument the dataset ids.\n getfunc : function\n The function to call to return the structure. It takes no\n arguments.\n fields : sequence of str\n The field names to report, and the order to use. These fields\n must exist in the object returned by the getfunc.\n \"\"\"",
"# Copy the fields and ensure it is a list; I'm not sure why I",
"# want a list, but a list we get.",
"#",
"\"\"\"Run the function and return the values.\n\n Parameters\n ----------\n annuli : dict\n The key is the dataset identifier and the value the annulus\n number.\n components : dict\n The keys are the annulus number and the values are a list of\n tuples of (model components, parent model name).\n *ids : dataset identifiers\n The dataset identifiers to use. They must all exist as keys\n in the `annuli` map.\n\n Returns\n -------\n data : dict of OrderedDict values\n The keys are the annulus value, and the values are the\n shell results. The order of the keys in the results dict is\n defined by the fields list given to the object constructor.\n\n Notes\n -----\n There is only support for simple parameter links, where one parameter\n is set equal to another, and both model components are associated\n with the given set of dataset identifiers.\n\n \"\"\"",
"# Group the data by annulus. The assumption here is that each",
"# dataset in the same annulus has the same set of model components.",
"#",
"# All the fields are copied over to each annulus except for",
"# datasets",
"# parameter values",
"# which are restricted to the given annulus.",
"#",
"# Sanity check",
"# Create the non-parameter columns",
"#",
"# It would be nice to report these values too,",
"# for completeness, but leave for now.",
"#",
"# Note: linked parameters appear to be marked as",
"# frozen...",
"#",
"# I think a better check may be needed (or send in",
"# the actual pars to report).",
"#",
"# It is important to use the \"base\" name for the",
"# parameter - e.g 'xsapec.kT' - rather than the",
"# name for this shell (e.g. 'xsapec_0.kT').",
"#",
"\"\"\"Extract the parameter value from the results structure.\n\n Parameters\n ----------\n datavals\n The results structure (FitResults, ErrorEstResults).\n par : sherpa.models.parameter.Parameter instance\n The model parameter of interest. It must be related to the\n datasets in datavals.\n field : str\n The name of the item of interest.\n store : dict\n The results are added to this structure, using the field key\n (multiple values can be added, in which case the field is\n expected to be a suffix).\n\n \"\"\"",
"# Just want the value. Could just take the value from the",
"# parameter input, but use the value in datavals.",
"#",
"# Parameter not found, which should mean it is a link",
"#",
"# For now only support simple links - equality and not a more-complex",
"# functional relationship. Assume that checking whether modelname",
"# is not empty is a sufficient check",
"#",
"\"\"\"Add the values to the output structure.\n\n This functionality is provided by the sub-classes.\n\n Parameters\n ----------\n datavals\n The results structure (FitResults, ErrorEstResults).\n name : str\n The parameter name.\n field : str\n The name of the item of interest.\n store : dict\n The results are added to this structure, using the field key\n (multiple values can be added, in which case the field is\n expected to be a suffix).\n\n Returns\n -------\n flag : bool\n True if the parameter was found and added to store, False\n otherwise.\n\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,368
| 97
|
fe027bae619203e7cb82ed34c6ba311ce679eeb5
|
arianpasquali/tilse
|
tilse/models/models.py
|
[
"MIT"
] |
Python
|
Model
|
Manages a machine learning model for timeline summarization.
In particular, provides functionality for model-specific preprocessing, training and
prediction. This class is abstract, actual models should should inherit from this class and
implement the preprocessing, training and prediction methods.
Attributes:
summary_length_assesor (function(Groundtruth, int)): A function to assess length of
daily summaries given a reference groundtruth.
sentence_representation_computer (tilse.representations.sentence_representations.SentenceRepresentation): A model for computing sentence
representations.
rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.
|
Manages a machine learning model for timeline summarization.
In particular, provides functionality for model-specific preprocessing, training and
prediction. This class is abstract, actual models should should inherit from this class and
implement the preprocessing, training and prediction methods.
|
[
"Manages",
"a",
"machine",
"learning",
"model",
"for",
"timeline",
"summarization",
".",
"In",
"particular",
"provides",
"functionality",
"for",
"model",
"-",
"specific",
"preprocessing",
"training",
"and",
"prediction",
".",
"This",
"class",
"is",
"abstract",
"actual",
"models",
"should",
"should",
"inherit",
"from",
"this",
"class",
"and",
"implement",
"the",
"preprocessing",
"training",
"and",
"prediction",
"methods",
"."
] |
class Model:
"""
Manages a machine learning model for timeline summarization.
In particular, provides functionality for model-specific preprocessing, training and
prediction. This class is abstract, actual models should should inherit from this class and
implement the preprocessing, training and prediction methods.
Attributes:
summary_length_assesor (function(Groundtruth, int)): A function to assess length of
daily summaries given a reference groundtruth.
sentence_representation_computer (tilse.representations.sentence_representations.SentenceRepresentation): A model for computing sentence
representations.
rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.
"""
def __init__(self, config, rouge):
"""
Initializes a machine learning model for timeline summarization.
Params:
config (dict): A configuration dict. needs to have at least entries for `"assess_length"`
(should be a function from `tilse.models.assess_length` and for `"sentence_representations"`
(should be a class from `tilse.representations.sentence_representations`).
rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.
Returns:
A model for timeline summarization intialized with the above parameters.
"""
self.summary_length_assessor = import_helper("tilse.models.assess_length", config["assess_length"])
self.sentence_representation_computer = import_helper("tilse.representations.sentence_representations",
config["sentence_representation"])
self.rouge = rouge
random.seed(23)
def run(self, corpora, reference_timelines):
"""
Runs the model on a set of corpora and evaluates w.r.t reference timelines.
Trains and evaluates model using topic-based cross-validation.
Params:
corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.
reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names
to corresponding reference timelines.
Returns:
A tuple consisting of predicted timelines (dict(str, tilse.data.timelines.Timeline), naming in the
dict by topic name and integer identifiers), and of corresponding evaluation
results (of type tilse.evaluation.scores.Scores).
"""
topics = sorted(list(corpora.keys()))
print("all topics", topics)
results_rouge = {}
results_date = {}
returned_timelines = {}
# preprocess
topic_to_preprocessed = {}
for t in topics:
print("preprocessing topic", t)
topic_to_preprocessed[t] = self.preprocess(t, corpora[t])
for t in topics:
print("predict timeline for topic", t)
new_results_rouge, new_results_date, new_returned_timelines = self._run_for_one(t, corpora,
topic_to_preprocessed,
reference_timelines)
results_rouge.update(new_results_rouge)
results_date.update(new_results_date)
returned_timelines.update(new_returned_timelines)
return returned_timelines, scores.Scores(results_rouge, results_date, beta=self.rouge.beta)
def _run_for_one(self, t, corpora, topic_to_preprocessed, reference_timelines):
logging.info(t)
corpus = corpora[t]
# train
params = self.train(corpora, topic_to_preprocessed, reference_timelines, t)
results_rouge = {}
results_date_selection = {}
returned_timelines = {}
# predict
for i, timeline in enumerate(reference_timelines[t].timelines):
timeline_properties = self.get_timeline_properties(timeline)
groundtruth = timelines.GroundTruth([timeline])
pred = self.predict(corpus, topic_to_preprocessed[t], timeline_properties, params)
# evaluate
print("topic_to_preprocessed", topic_to_preprocessed)
print("timeline_properties", timeline_properties)
print("groundtruth", groundtruth)
print("pred", pred)
results_rouge[t + "_" + str(i)] = self.rouge.evaluate_all(pred, groundtruth)
results_date_selection[t + "_" + str(i)] = dates.evaluate_dates(pred, groundtruth)
returned_timelines[t + "_" + str(i)] = pred
return results_rouge, results_date_selection, returned_timelines
def get_timeline_properties(self, timeline):
"""
Computes timeline properties for a given timeline.
Params:
timeline (tilse.data.timelines.Timeline): A timeline.
Returns:
A tilse.models.timeline_properties.TimelineProperties object,
with:
* `daily_summary_length` set to the output of `self.asses_length`,
* `num_dates` set to the length of the input timeline in days,
* `num_sentences` set to the length of the input timeline in sentences,
* `start` and `end` set to the first and last days in the input timeline.
"""
groundtruth = timelines.GroundTruth([timeline])
groundtruth_dates = sorted(list(timeline.get_dates()))
desired_timeline_length = len(groundtruth_dates)
summary_length = self.summary_length_assessor(groundtruth)
timeline_properties = TimelineProperties(
summary_length,
desired_timeline_length,
timeline.get_number_of_sentences(),
groundtruth_dates[0],
groundtruth_dates[-1]
)
return timeline_properties
def train(self, corpora, preprocessed_information, reference_timelines, topic_to_evaluate):
"""
Trains the model. Needs to be implemented by subclasses.
Params:
corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.
preprocessed_information (object): Arbitrary information obtained from preprocessing.
reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names
to corresponding reference timelines.
topic_to_evaluate (str): The topic to evaluate (must be a key in `corpora`. The given topic will not
be used during training (such that it can serve as evaluation data later).
Returns:
Arbitrary information specifying results of training.
"""
raise NotImplementedError("Needs to be implemented by subclass.")
def predict(self, corpus, preprocessed_information, timeline_properties, params):
"""
Predicts a timeline. Needs to be implemented by subclasses.
Params:
corpus (tilse.data.corpora.Corpus): A corpus.
preprocessed_information (object): Arbitrary information obtained from preprocessing.
timeline_properties (tilse.models.timeline_properties.TimelineProperties): Properties of the timeline to
predict.
params (object): Arbitrary information obtained from training.
Returns:
A timeline (tilse.data.timelines.Timeline).
"""
raise NotImplementedError("Needs to be implemented by subclass.")
def preprocess(self, topic_name, corpus):
"""
Preprocesses a corpus. Needs to be implemented by subclasses.
Params:
topic_name (str): name of the topic to which the corpus belongs.
corpus (tilse.data.corpora.Corpus): A corpus.
Returns:
Arbitrary preprocessed information.
"""
raise NotImplementedError("Needs to be implemented by subclass.")
|
[
"class",
"Model",
":",
"def",
"__init__",
"(",
"self",
",",
"config",
",",
"rouge",
")",
":",
"\"\"\"\n Initializes a machine learning model for timeline summarization.\n \n Params:\n config (dict): A configuration dict. needs to have at least entries for `\"assess_length\"` \n (should be a function from `tilse.models.assess_length` and for `\"sentence_representations\"`\n (should be a class from `tilse.representations.sentence_representations`).\n rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.\n \n Returns:\n A model for timeline summarization intialized with the above parameters.\n \"\"\"",
"self",
".",
"summary_length_assessor",
"=",
"import_helper",
"(",
"\"tilse.models.assess_length\"",
",",
"config",
"[",
"\"assess_length\"",
"]",
")",
"self",
".",
"sentence_representation_computer",
"=",
"import_helper",
"(",
"\"tilse.representations.sentence_representations\"",
",",
"config",
"[",
"\"sentence_representation\"",
"]",
")",
"self",
".",
"rouge",
"=",
"rouge",
"random",
".",
"seed",
"(",
"23",
")",
"def",
"run",
"(",
"self",
",",
"corpora",
",",
"reference_timelines",
")",
":",
"\"\"\"\n Runs the model on a set of corpora and evaluates w.r.t reference timelines.\n \n Trains and evaluates model using topic-based cross-validation.\n \n Params:\n corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.\n reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names\n to corresponding reference timelines.\n \n Returns:\n A tuple consisting of predicted timelines (dict(str, tilse.data.timelines.Timeline), naming in the \n dict by topic name and integer identifiers), and of corresponding evaluation\n results (of type tilse.evaluation.scores.Scores).\n \"\"\"",
"topics",
"=",
"sorted",
"(",
"list",
"(",
"corpora",
".",
"keys",
"(",
")",
")",
")",
"print",
"(",
"\"all topics\"",
",",
"topics",
")",
"results_rouge",
"=",
"{",
"}",
"results_date",
"=",
"{",
"}",
"returned_timelines",
"=",
"{",
"}",
"topic_to_preprocessed",
"=",
"{",
"}",
"for",
"t",
"in",
"topics",
":",
"print",
"(",
"\"preprocessing topic\"",
",",
"t",
")",
"topic_to_preprocessed",
"[",
"t",
"]",
"=",
"self",
".",
"preprocess",
"(",
"t",
",",
"corpora",
"[",
"t",
"]",
")",
"for",
"t",
"in",
"topics",
":",
"print",
"(",
"\"predict timeline for topic\"",
",",
"t",
")",
"new_results_rouge",
",",
"new_results_date",
",",
"new_returned_timelines",
"=",
"self",
".",
"_run_for_one",
"(",
"t",
",",
"corpora",
",",
"topic_to_preprocessed",
",",
"reference_timelines",
")",
"results_rouge",
".",
"update",
"(",
"new_results_rouge",
")",
"results_date",
".",
"update",
"(",
"new_results_date",
")",
"returned_timelines",
".",
"update",
"(",
"new_returned_timelines",
")",
"return",
"returned_timelines",
",",
"scores",
".",
"Scores",
"(",
"results_rouge",
",",
"results_date",
",",
"beta",
"=",
"self",
".",
"rouge",
".",
"beta",
")",
"def",
"_run_for_one",
"(",
"self",
",",
"t",
",",
"corpora",
",",
"topic_to_preprocessed",
",",
"reference_timelines",
")",
":",
"logging",
".",
"info",
"(",
"t",
")",
"corpus",
"=",
"corpora",
"[",
"t",
"]",
"params",
"=",
"self",
".",
"train",
"(",
"corpora",
",",
"topic_to_preprocessed",
",",
"reference_timelines",
",",
"t",
")",
"results_rouge",
"=",
"{",
"}",
"results_date_selection",
"=",
"{",
"}",
"returned_timelines",
"=",
"{",
"}",
"for",
"i",
",",
"timeline",
"in",
"enumerate",
"(",
"reference_timelines",
"[",
"t",
"]",
".",
"timelines",
")",
":",
"timeline_properties",
"=",
"self",
".",
"get_timeline_properties",
"(",
"timeline",
")",
"groundtruth",
"=",
"timelines",
".",
"GroundTruth",
"(",
"[",
"timeline",
"]",
")",
"pred",
"=",
"self",
".",
"predict",
"(",
"corpus",
",",
"topic_to_preprocessed",
"[",
"t",
"]",
",",
"timeline_properties",
",",
"params",
")",
"print",
"(",
"\"topic_to_preprocessed\"",
",",
"topic_to_preprocessed",
")",
"print",
"(",
"\"timeline_properties\"",
",",
"timeline_properties",
")",
"print",
"(",
"\"groundtruth\"",
",",
"groundtruth",
")",
"print",
"(",
"\"pred\"",
",",
"pred",
")",
"results_rouge",
"[",
"t",
"+",
"\"_\"",
"+",
"str",
"(",
"i",
")",
"]",
"=",
"self",
".",
"rouge",
".",
"evaluate_all",
"(",
"pred",
",",
"groundtruth",
")",
"results_date_selection",
"[",
"t",
"+",
"\"_\"",
"+",
"str",
"(",
"i",
")",
"]",
"=",
"dates",
".",
"evaluate_dates",
"(",
"pred",
",",
"groundtruth",
")",
"returned_timelines",
"[",
"t",
"+",
"\"_\"",
"+",
"str",
"(",
"i",
")",
"]",
"=",
"pred",
"return",
"results_rouge",
",",
"results_date_selection",
",",
"returned_timelines",
"def",
"get_timeline_properties",
"(",
"self",
",",
"timeline",
")",
":",
"\"\"\"\n Computes timeline properties for a given timeline.\n \n Params:\n timeline (tilse.data.timelines.Timeline): A timeline.\n \n Returns:\n A tilse.models.timeline_properties.TimelineProperties object,\n with:\n * `daily_summary_length` set to the output of `self.asses_length`,\n * `num_dates` set to the length of the input timeline in days,\n * `num_sentences` set to the length of the input timeline in sentences,\n * `start` and `end` set to the first and last days in the input timeline.\n \"\"\"",
"groundtruth",
"=",
"timelines",
".",
"GroundTruth",
"(",
"[",
"timeline",
"]",
")",
"groundtruth_dates",
"=",
"sorted",
"(",
"list",
"(",
"timeline",
".",
"get_dates",
"(",
")",
")",
")",
"desired_timeline_length",
"=",
"len",
"(",
"groundtruth_dates",
")",
"summary_length",
"=",
"self",
".",
"summary_length_assessor",
"(",
"groundtruth",
")",
"timeline_properties",
"=",
"TimelineProperties",
"(",
"summary_length",
",",
"desired_timeline_length",
",",
"timeline",
".",
"get_number_of_sentences",
"(",
")",
",",
"groundtruth_dates",
"[",
"0",
"]",
",",
"groundtruth_dates",
"[",
"-",
"1",
"]",
")",
"return",
"timeline_properties",
"def",
"train",
"(",
"self",
",",
"corpora",
",",
"preprocessed_information",
",",
"reference_timelines",
",",
"topic_to_evaluate",
")",
":",
"\"\"\"\n Trains the model. Needs to be implemented by subclasses.\n \n Params:\n corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.\n preprocessed_information (object): Arbitrary information obtained from preprocessing.\n reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names\n to corresponding reference timelines.\n topic_to_evaluate (str): The topic to evaluate (must be a key in `corpora`. The given topic will not\n be used during training (such that it can serve as evaluation data later).\n \n Returns:\n Arbitrary information specifying results of training.\n \"\"\"",
"raise",
"NotImplementedError",
"(",
"\"Needs to be implemented by subclass.\"",
")",
"def",
"predict",
"(",
"self",
",",
"corpus",
",",
"preprocessed_information",
",",
"timeline_properties",
",",
"params",
")",
":",
"\"\"\"\n Predicts a timeline. Needs to be implemented by subclasses.\n \n Params:\n corpus (tilse.data.corpora.Corpus): A corpus.\n preprocessed_information (object): Arbitrary information obtained from preprocessing.\n timeline_properties (tilse.models.timeline_properties.TimelineProperties): Properties of the timeline to\n predict.\n params (object): Arbitrary information obtained from training.\n \n Returns:\n A timeline (tilse.data.timelines.Timeline).\n \"\"\"",
"raise",
"NotImplementedError",
"(",
"\"Needs to be implemented by subclass.\"",
")",
"def",
"preprocess",
"(",
"self",
",",
"topic_name",
",",
"corpus",
")",
":",
"\"\"\"\n Preprocesses a corpus. Needs to be implemented by subclasses.\n \n Params:\n topic_name (str): name of the topic to which the corpus belongs.\n corpus (tilse.data.corpora.Corpus): A corpus.\n \n Returns:\n Arbitrary preprocessed information.\n \"\"\"",
"raise",
"NotImplementedError",
"(",
"\"Needs to be implemented by subclass.\"",
")"
] |
Manages a machine learning model for timeline summarization.
|
[
"Manages",
"a",
"machine",
"learning",
"model",
"for",
"timeline",
"summarization",
"."
] |
[
"\"\"\"\n Manages a machine learning model for timeline summarization.\n \n In particular, provides functionality for model-specific preprocessing, training and\n prediction. This class is abstract, actual models should should inherit from this class and \n implement the preprocessing, training and prediction methods.\n \n Attributes:\n summary_length_assesor (function(Groundtruth, int)): A function to assess length of\n daily summaries given a reference groundtruth.\n sentence_representation_computer (tilse.representations.sentence_representations.SentenceRepresentation): A model for computing sentence\n representations.\n rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.\n \"\"\"",
"\"\"\"\n Initializes a machine learning model for timeline summarization.\n \n Params:\n config (dict): A configuration dict. needs to have at least entries for `\"assess_length\"` \n (should be a function from `tilse.models.assess_length` and for `\"sentence_representations\"`\n (should be a class from `tilse.representations.sentence_representations`).\n rouge (pyrouge.Rouge155 or tilse.evaluation.rouge.RougeReimplementation): An object for computing ROUGE scores.\n \n Returns:\n A model for timeline summarization intialized with the above parameters.\n \"\"\"",
"\"\"\"\n Runs the model on a set of corpora and evaluates w.r.t reference timelines.\n \n Trains and evaluates model using topic-based cross-validation.\n \n Params:\n corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.\n reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names\n to corresponding reference timelines.\n \n Returns:\n A tuple consisting of predicted timelines (dict(str, tilse.data.timelines.Timeline), naming in the \n dict by topic name and integer identifiers), and of corresponding evaluation\n results (of type tilse.evaluation.scores.Scores).\n \"\"\"",
"# preprocess",
"# train",
"# predict",
"# evaluate",
"\"\"\"\n Computes timeline properties for a given timeline.\n \n Params:\n timeline (tilse.data.timelines.Timeline): A timeline.\n \n Returns:\n A tilse.models.timeline_properties.TimelineProperties object,\n with:\n * `daily_summary_length` set to the output of `self.asses_length`,\n * `num_dates` set to the length of the input timeline in days,\n * `num_sentences` set to the length of the input timeline in sentences,\n * `start` and `end` set to the first and last days in the input timeline.\n \"\"\"",
"\"\"\"\n Trains the model. Needs to be implemented by subclasses.\n \n Params:\n corpora (dict(str, tilse.data.corpora.Corpus)): A mapping of topic names to corresponding corpora.\n preprocessed_information (object): Arbitrary information obtained from preprocessing.\n reference_timelines (dict(str, tilse.data.timelines.Groundtruth)): A mapping of topic names\n to corresponding reference timelines.\n topic_to_evaluate (str): The topic to evaluate (must be a key in `corpora`. The given topic will not\n be used during training (such that it can serve as evaluation data later).\n \n Returns:\n Arbitrary information specifying results of training.\n \"\"\"",
"\"\"\"\n Predicts a timeline. Needs to be implemented by subclasses.\n \n Params:\n corpus (tilse.data.corpora.Corpus): A corpus.\n preprocessed_information (object): Arbitrary information obtained from preprocessing.\n timeline_properties (tilse.models.timeline_properties.TimelineProperties): Properties of the timeline to\n predict.\n params (object): Arbitrary information obtained from training.\n \n Returns:\n A timeline (tilse.data.timelines.Timeline).\n \"\"\"",
"\"\"\"\n Preprocesses a corpus. Needs to be implemented by subclasses.\n \n Params:\n topic_name (str): name of the topic to which the corpus belongs.\n corpus (tilse.data.corpora.Corpus): A corpus.\n \n Returns:\n Arbitrary preprocessed information.\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "summary_length_assesor",
"type": null,
"docstring": "A function to assess length of\ndaily summaries given a reference groundtruth.",
"docstring_tokens": [
"A",
"function",
"to",
"assess",
"length",
"of",
"daily",
"summaries",
"given",
"a",
"reference",
"groundtruth",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "sentence_representation_computer",
"type": null,
"docstring": "A model for computing sentence\nrepresentations.",
"docstring_tokens": [
"A",
"model",
"for",
"computing",
"sentence",
"representations",
"."
],
"default": null,
"is_optional": false
},
{
"identifier": "rouge",
"type": null,
"docstring": "An object for computing ROUGE scores.",
"docstring_tokens": [
"An",
"object",
"for",
"computing",
"ROUGE",
"scores",
"."
],
"default": null,
"is_optional": false
}
],
"others": []
}
| false
| 13
| 1,585
| 153
|
54a1f41492ce6dbc777096e0dddeaf4604a451f1
|
thevuuranusls/hapax2
|
src/hapax/Iterator.java
|
[
"MIT"
] |
Java
|
Iterator
|
/**
* Section and include iterations (one or many) are evaluated with
* special sections shown and hidden during their interpretation, as
* defined here.
*
* <dl>
*
* <dt> <i>name</i><code>_it_First</code> </dt> <dd> A section only
* visible in the first iteration. </dd>
*
* <dt> <i>name</i><code>_it_NotFirst</code> </dt> <dd> A section only
* visible after the first iteration. </dd>
*
* <dt> <i>name</i><code>_it_Last</code> </dt> <dd> A section only
* visible in the last iteration. </dd>
*
* <dt> <i>name</i><code>_it_NotLast</code> </dt> <dd> A section only
* visible before the first iteration. </dd>
*
* <dt> <i>name</i><code>_it_Exclusive</code> </dt> <dd> A section only
* visible after the first iteration and before the last
* iteration. </dd>
*
* </dl>
*
*
* @author jdp
*/
|
Section and include iterations (one or many) are evaluated with
special sections shown and hidden during their interpretation, as
defined here.
name_it_First A section only
visible in the first iteration.
name_it_NotFirst A section only
visible after the first iteration.
name_it_Last A section only
visible in the last iteration.
name_it_NotLast A section only
visible before the first iteration.
name_it_Exclusive A section only
visible after the first iteration and before the last
iteration.
@author jdp
|
[
"Section",
"and",
"include",
"iterations",
"(",
"one",
"or",
"many",
")",
"are",
"evaluated",
"with",
"special",
"sections",
"shown",
"and",
"hidden",
"during",
"their",
"interpretation",
"as",
"defined",
"here",
".",
"name_it_First",
"A",
"section",
"only",
"visible",
"in",
"the",
"first",
"iteration",
".",
"name_it_NotFirst",
"A",
"section",
"only",
"visible",
"after",
"the",
"first",
"iteration",
".",
"name_it_Last",
"A",
"section",
"only",
"visible",
"in",
"the",
"last",
"iteration",
".",
"name_it_NotLast",
"A",
"section",
"only",
"visible",
"before",
"the",
"first",
"iteration",
".",
"name_it_Exclusive",
"A",
"section",
"only",
"visible",
"after",
"the",
"first",
"iteration",
"and",
"before",
"the",
"last",
"iteration",
".",
"@author",
"jdp"
] |
public class Iterator
extends Object
{
public final static class Suffix {
public final static String First = "_it_First";
public final static String NotFirst = "_it_NotFirst";
public final static String Last = "_it_Last";
public final static String NotLast = "_it_NotLast";
public final static String Exclusive = "_it_Exclusive";
}
public final static void Define(TemplateDataDictionary dict, String sectionName, int cc, int count){
if (0 == cc){
dict.showSection(sectionName+Suffix.First);
if (1 == count)
dict.showSection(sectionName+Suffix.Last);
else
dict.showSection(sectionName+Suffix.NotLast);
}
else if (cc == (count-1)){
dict.showSection(sectionName+Suffix.NotFirst);
dict.showSection(sectionName+Suffix.Last);
}
else {
dict.showSection(sectionName+Suffix.NotFirst);
dict.showSection(sectionName+Suffix.NotLast);
dict.showSection(sectionName+Suffix.Exclusive);
}
}
}
|
[
"public",
"class",
"Iterator",
"extends",
"Object",
"{",
"public",
"final",
"static",
"class",
"Suffix",
"{",
"public",
"final",
"static",
"String",
"First",
"=",
"\"",
"_it_First",
"\"",
";",
"public",
"final",
"static",
"String",
"NotFirst",
"=",
"\"",
"_it_NotFirst",
"\"",
";",
"public",
"final",
"static",
"String",
"Last",
"=",
"\"",
"_it_Last",
"\"",
";",
"public",
"final",
"static",
"String",
"NotLast",
"=",
"\"",
"_it_NotLast",
"\"",
";",
"public",
"final",
"static",
"String",
"Exclusive",
"=",
"\"",
"_it_Exclusive",
"\"",
";",
"}",
"public",
"final",
"static",
"void",
"Define",
"(",
"TemplateDataDictionary",
"dict",
",",
"String",
"sectionName",
",",
"int",
"cc",
",",
"int",
"count",
")",
"{",
"if",
"(",
"0",
"==",
"cc",
")",
"{",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"First",
")",
";",
"if",
"(",
"1",
"==",
"count",
")",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"Last",
")",
";",
"else",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"NotLast",
")",
";",
"}",
"else",
"if",
"(",
"cc",
"==",
"(",
"count",
"-",
"1",
")",
")",
"{",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"NotFirst",
")",
";",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"Last",
")",
";",
"}",
"else",
"{",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"NotFirst",
")",
";",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"NotLast",
")",
";",
"dict",
".",
"showSection",
"(",
"sectionName",
"+",
"Suffix",
".",
"Exclusive",
")",
";",
"}",
"}",
"}"
] |
Section and include iterations (one or many) are evaluated with
special sections shown and hidden during their interpretation, as
defined here.
|
[
"Section",
"and",
"include",
"iterations",
"(",
"one",
"or",
"many",
")",
"are",
"evaluated",
"with",
"special",
"sections",
"shown",
"and",
"hidden",
"during",
"their",
"interpretation",
"as",
"defined",
"here",
"."
] |
[] |
[
{
"param": "Object",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Object",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 230
| 264
|
ea926b4af9065b3d9e5e898057620dfb1e5ce8e0
|
letmaik/leaflet-coverage
|
src/layers/palettes.js
|
[
"BSD-3-Clause"
] |
JavaScript
|
PaletteManager
|
/**
* Manages palettes under common names.
*
* @example
* var palettes = new C.PaletteManager({defaultSteps: 10})
* palettes.addLinear('grayscale', ['#FFFFFF', '#000000']) // 10 steps
* palettes.addLinear('grayscalehd', ['#FFFFFF', '#000000'], {steps: 200}) // high-resolution palette
* palettes.add('breweroranges3', ['#fee6ce', '#fdae6b', '#e6550d']) // palette of those 3 colors
* palettes.add('mycustom', {red: [0,255], green: [0,0], blue: [10,20]}) // different syntax
*/
|
Manages palettes under common names.
|
[
"Manages",
"palettes",
"under",
"common",
"names",
"."
] |
class PaletteManager {
/**
* @param {Integer} defaultSteps The default number of steps when adding palettes with addLinear().
*/
constructor({defaultSteps=256} = {}) {
this._defaultSteps = defaultSteps
this._palettes = new Map()
}
/**
* Store a supplied generic palette under the given name.
*
* @example
* var palettes = new C.PaletteManager()
* palettes.add('breweroranges3', ['#fee6ce', '#fdae6b', '#e6550d']) // palette of those 3 colors
* palettes.add('mycustom', {red: [0,255], green: [0,0], blue: [10,20]}) // different syntax
*
* @param {string} name The unique name of the palette.
* @param {Palette|Array<string>} palette A palette object or an array of CSS colors.
*/
add (name, palette) {
if (Array.isArray(palette)) {
palette = directPalette(palette)
}
if (![palette.red, palette.green, palette.blue].every(arr => arr.length === palette.red.length)) {
throw new Error('The red, green, blue arrays of the palette must be of equal lengths')
}
if (!(palette.red instanceof Uint8Array)) {
palette.red = _asUint8Array(palette.red)
palette.green = _asUint8Array(palette.green)
palette.blue = _asUint8Array(palette.blue)
}
palette.steps = palette.red.length // for convenience in clients
this._palettes.set(name, palette)
}
/**
* Store a linear palette under the given name created with the given CSS color specifications.
*
* @example
* var palettes = new C.PaletteManager()
* palettes.addLinear('grayscale', ['#FFFFFF', '#000000']) // 10 steps
* palettes.addLinear('grayscalehd', ['#FFFFFF', '#000000'], {steps: 200})
*
* @param {String} name The unique name of the palette
* @param {Array<string>} colors An array of CSS color specifications
* @param {number} steps Use a different number of steps than the default of this manager.
*/
addLinear (name, colors, {steps} = {}) {
this.add(name, linearPalette(colors, steps ? steps : this._defaultSteps))
}
/**
* Return the palette stored under the given name, or throw an error if not found.
* The palette is an object with properties steps, red, green, and blue.
* Each of the color arrays is an Uint8Array of length steps.
*
* @param {string} name The unique name of the palette
* @returns {Palette}
*/
get (name) {
var palette = this._palettes.get(name)
if (palette === undefined) {
throw new Error('Palette "' + name + '" not found')
}
return palette
}
get [Symbol.iterator] () {
return this._palettes[Symbol.iterator]
}
}
|
[
"class",
"PaletteManager",
"{",
"constructor",
"(",
"{",
"defaultSteps",
"=",
"256",
"}",
"=",
"{",
"}",
")",
"{",
"this",
".",
"_defaultSteps",
"=",
"defaultSteps",
"this",
".",
"_palettes",
"=",
"new",
"Map",
"(",
")",
"}",
"add",
"(",
"name",
",",
"palette",
")",
"{",
"if",
"(",
"Array",
".",
"isArray",
"(",
"palette",
")",
")",
"{",
"palette",
"=",
"directPalette",
"(",
"palette",
")",
"}",
"if",
"(",
"!",
"[",
"palette",
".",
"red",
",",
"palette",
".",
"green",
",",
"palette",
".",
"blue",
"]",
".",
"every",
"(",
"arr",
"=>",
"arr",
".",
"length",
"===",
"palette",
".",
"red",
".",
"length",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'The red, green, blue arrays of the palette must be of equal lengths'",
")",
"}",
"if",
"(",
"!",
"(",
"palette",
".",
"red",
"instanceof",
"Uint8Array",
")",
")",
"{",
"palette",
".",
"red",
"=",
"_asUint8Array",
"(",
"palette",
".",
"red",
")",
"palette",
".",
"green",
"=",
"_asUint8Array",
"(",
"palette",
".",
"green",
")",
"palette",
".",
"blue",
"=",
"_asUint8Array",
"(",
"palette",
".",
"blue",
")",
"}",
"palette",
".",
"steps",
"=",
"palette",
".",
"red",
".",
"length",
"this",
".",
"_palettes",
".",
"set",
"(",
"name",
",",
"palette",
")",
"}",
"addLinear",
"(",
"name",
",",
"colors",
",",
"{",
"steps",
"}",
"=",
"{",
"}",
")",
"{",
"this",
".",
"add",
"(",
"name",
",",
"linearPalette",
"(",
"colors",
",",
"steps",
"?",
"steps",
":",
"this",
".",
"_defaultSteps",
")",
")",
"}",
"get",
"(",
"name",
")",
"{",
"var",
"palette",
"=",
"this",
".",
"_palettes",
".",
"get",
"(",
"name",
")",
"if",
"(",
"palette",
"===",
"undefined",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Palette \"'",
"+",
"name",
"+",
"'\" not found'",
")",
"}",
"return",
"palette",
"}",
"get",
"[",
"Symbol",
".",
"iterator",
"]",
"(",
")",
"{",
"return",
"this",
".",
"_palettes",
"[",
"Symbol",
".",
"iterator",
"]",
"}",
"}"
] |
Manages palettes under common names.
|
[
"Manages",
"palettes",
"under",
"common",
"names",
"."
] |
[
"/**\n * @param {Integer} defaultSteps The default number of steps when adding palettes with addLinear().\n */",
"/**\n * Store a supplied generic palette under the given name.\n * \n * @example\n * var palettes = new C.PaletteManager()\n * palettes.add('breweroranges3', ['#fee6ce', '#fdae6b', '#e6550d']) // palette of those 3 colors\n * palettes.add('mycustom', {red: [0,255], green: [0,0], blue: [10,20]}) // different syntax\n * \n * @param {string} name The unique name of the palette.\n * @param {Palette|Array<string>} palette A palette object or an array of CSS colors.\n */",
"// for convenience in clients",
"/**\n * Store a linear palette under the given name created with the given CSS color specifications.\n * \n * @example\n * var palettes = new C.PaletteManager()\n * palettes.addLinear('grayscale', ['#FFFFFF', '#000000']) // 10 steps\n * palettes.addLinear('grayscalehd', ['#FFFFFF', '#000000'], {steps: 200})\n * \n * @param {String} name The unique name of the palette\n * @param {Array<string>} colors An array of CSS color specifications\n * @param {number} steps Use a different number of steps than the default of this manager.\n */",
"/**\n * Return the palette stored under the given name, or throw an error if not found.\n * The palette is an object with properties steps, red, green, and blue.\n * Each of the color arrays is an Uint8Array of length steps.\n * \n * @param {string} name The unique name of the palette\n * @returns {Palette}\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 711
| 172
|
698d2a18604f7bf21ed8d2ffdcefb428adbbd858
|
Ash222/DSA
|
src/problems/Arrays/Leetcode209/Solution.java
|
[
"MIT"
] |
Java
|
Solution
|
/*
Given an array of positive integers nums and a positive integer target, return the
minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which
the sum is greater than or equal to target. If there is no such subarray, return 0
instead.
Input: target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Input: target = 4, nums = [1,4,4]
Output: 1
Input: target = 11, nums = [1,1,1,1,1,1,1,1]
Output: 0
Follow up: If you have figured out the O(n) solution, try coding another solution of
which the time complexity is O(n log(n)).
*/
|
Given an array of positive integers nums and a positive integer target, return the
minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which
the sum is greater than or equal to target. If there is no such subarray, return 0
instead.
target = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
Follow up: If you have figured out the O(n) solution, try coding another solution of
which the time complexity is O(n log(n)).
|
[
"Given",
"an",
"array",
"of",
"positive",
"integers",
"nums",
"and",
"a",
"positive",
"integer",
"target",
"return",
"the",
"minimal",
"length",
"of",
"a",
"contiguous",
"subarray",
"[",
"numsl",
"numsl",
"+",
"1",
"...",
"numsr",
"-",
"1",
"numsr",
"]",
"of",
"which",
"the",
"sum",
"is",
"greater",
"than",
"or",
"equal",
"to",
"target",
".",
"If",
"there",
"is",
"no",
"such",
"subarray",
"return",
"0",
"instead",
".",
"target",
"=",
"7",
"nums",
"=",
"[",
"2",
"3",
"1",
"2",
"4",
"3",
"]",
"Output",
":",
"2",
"Explanation",
":",
"The",
"subarray",
"[",
"4",
"3",
"]",
"has",
"the",
"minimal",
"length",
"under",
"the",
"problem",
"constraint",
".",
"Follow",
"up",
":",
"If",
"you",
"have",
"figured",
"out",
"the",
"O",
"(",
"n",
")",
"solution",
"try",
"coding",
"another",
"solution",
"of",
"which",
"the",
"time",
"complexity",
"is",
"O",
"(",
"n",
"log",
"(",
"n",
"))",
"."
] |
public class Solution {
private static int minSubArrayLen( int target , int[] nums ) {
int minLength = nSolution( target , nums );
return minLength;
}
private static int nSolution( int target , int[] nums ) {
int result = Integer.MAX_VALUE;
int left = 0;
int sum = 0;
for ( int i = 0 ; i < nums.length ; i++ ) {
sum += nums[i];
while ( sum >= target ) {
result = Math.min( result , i + 1 - left );
sum -= nums[left];
left++;
}
}
return result == Integer.MAX_VALUE ? 0 : result;
}
@Deprecated
// this is n^2 solution. Ok so this solution is flawed.
private static int n2Solution( int target , int[] nums ) {
int minCount = Integer.MAX_VALUE;
for ( int i = 0 ; i < nums.length - 1 ; i++ ) {
int count = 1;
int sum = nums[i];
if( sum == target ) return count;
for ( int j = i + 1 ; j < nums.length ; j++ ) {
sum += nums[j];
count++;
if( sum > target ) {
break;
}
if( sum == target ) {
minCount = Math.min( minCount , count );
}
}
}
return minCount == Integer.MAX_VALUE ? 0 : minCount;
}
public static void main( String[] args ) {
int arr[] = { 1 , 2 , 3 , 4 , 5 };
int target = 11;
System.out.println( "Minimum length = " + minSubArrayLen( target , arr ) );
}
}
|
[
"public",
"class",
"Solution",
"{",
"private",
"static",
"int",
"minSubArrayLen",
"(",
"int",
"target",
",",
"int",
"[",
"]",
"nums",
")",
"{",
"int",
"minLength",
"=",
"nSolution",
"(",
"target",
",",
"nums",
")",
";",
"return",
"minLength",
";",
"}",
"private",
"static",
"int",
"nSolution",
"(",
"int",
"target",
",",
"int",
"[",
"]",
"nums",
")",
"{",
"int",
"result",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"int",
"left",
"=",
"0",
";",
"int",
"sum",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nums",
".",
"length",
";",
"i",
"++",
")",
"{",
"sum",
"+=",
"nums",
"[",
"i",
"]",
";",
"while",
"(",
"sum",
">=",
"target",
")",
"{",
"result",
"=",
"Math",
".",
"min",
"(",
"result",
",",
"i",
"+",
"1",
"-",
"left",
")",
";",
"sum",
"-=",
"nums",
"[",
"left",
"]",
";",
"left",
"++",
";",
"}",
"}",
"return",
"result",
"==",
"Integer",
".",
"MAX_VALUE",
"?",
"0",
":",
"result",
";",
"}",
"@",
"Deprecated",
"private",
"static",
"int",
"n2Solution",
"(",
"int",
"target",
",",
"int",
"[",
"]",
"nums",
")",
"{",
"int",
"minCount",
"=",
"Integer",
".",
"MAX_VALUE",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"nums",
".",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"int",
"count",
"=",
"1",
";",
"int",
"sum",
"=",
"nums",
"[",
"i",
"]",
";",
"if",
"(",
"sum",
"==",
"target",
")",
"return",
"count",
";",
"for",
"(",
"int",
"j",
"=",
"i",
"+",
"1",
";",
"j",
"<",
"nums",
".",
"length",
";",
"j",
"++",
")",
"{",
"sum",
"+=",
"nums",
"[",
"j",
"]",
";",
"count",
"++",
";",
"if",
"(",
"sum",
">",
"target",
")",
"{",
"break",
";",
"}",
"if",
"(",
"sum",
"==",
"target",
")",
"{",
"minCount",
"=",
"Math",
".",
"min",
"(",
"minCount",
",",
"count",
")",
";",
"}",
"}",
"}",
"return",
"minCount",
"==",
"Integer",
".",
"MAX_VALUE",
"?",
"0",
":",
"minCount",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"int",
"arr",
"[",
"]",
"=",
"{",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
"}",
";",
"int",
"target",
"=",
"11",
";",
"System",
".",
"out",
".",
"println",
"(",
"\"",
"Minimum length = ",
"\"",
"+",
"minSubArrayLen",
"(",
"target",
",",
"arr",
")",
")",
";",
"}",
"}"
] |
Given an array of positive integers nums and a positive integer target, return the
minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which
the sum is greater than or equal to target.
|
[
"Given",
"an",
"array",
"of",
"positive",
"integers",
"nums",
"and",
"a",
"positive",
"integer",
"target",
"return",
"the",
"minimal",
"length",
"of",
"a",
"contiguous",
"subarray",
"[",
"numsl",
"numsl",
"+",
"1",
"...",
"numsr",
"-",
"1",
"numsr",
"]",
"of",
"which",
"the",
"sum",
"is",
"greater",
"than",
"or",
"equal",
"to",
"target",
"."
] |
[
"// this is n^2 solution. Ok so this solution is flawed."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 406
| 200
|
93e8e7a23d56fb0ba741786ef788242520b3ca60
|
eldarbogdanov/clubsandwich
|
clubsandwich/datastore.py
|
[
"MIT"
] |
Python
|
CSVReader
|
Returns the lines from a single CSV file. If your first line is just column
labels, you can skip it (this is the default behavior).
.. py:attribute:: path
Path to the file
.. py:attribute:: identifier
See :py:attr:`Reader.identifier`
.. py:attribute:: skip_first_line
If ``True`` (default), always skip the first line of the file.
|
Returns the lines from a single CSV file. If your first line is just column
labels, you can skip it (this is the default behavior).
: path
Path to the file
: identifier
If ``True`` (default), always skip the first line of the file.
|
[
"Returns",
"the",
"lines",
"from",
"a",
"single",
"CSV",
"file",
".",
"If",
"your",
"first",
"line",
"is",
"just",
"column",
"labels",
"you",
"can",
"skip",
"it",
"(",
"this",
"is",
"the",
"default",
"behavior",
")",
".",
":",
"path",
"Path",
"to",
"the",
"file",
":",
"identifier",
"If",
"`",
"`",
"True",
"`",
"`",
"(",
"default",
")",
"always",
"skip",
"the",
"first",
"line",
"of",
"the",
"file",
"."
] |
class CSVReader:
"""
Returns the lines from a single CSV file. If your first line is just column
labels, you can skip it (this is the default behavior).
.. py:attribute:: path
Path to the file
.. py:attribute:: identifier
See :py:attr:`Reader.identifier`
.. py:attribute:: skip_first_line
If ``True`` (default), always skip the first line of the file.
"""
def __init__(self, path, skip_first_line=True):
"""
"""
self.path = path
self.skip_first_line = skip_first_line
self.identifier = path
def read(self):
"""Iterator of CSV values. Values are lists."""
with open(self.path) as f:
reader = csv.reader(f)
skip_next_line = self.skip_first_line
for line in reader:
if skip_next_line:
skip_next_line = False
continue
yield line
|
[
"class",
"CSVReader",
":",
"def",
"__init__",
"(",
"self",
",",
"path",
",",
"skip_first_line",
"=",
"True",
")",
":",
"\"\"\"\n \"\"\"",
"self",
".",
"path",
"=",
"path",
"self",
".",
"skip_first_line",
"=",
"skip_first_line",
"self",
".",
"identifier",
"=",
"path",
"def",
"read",
"(",
"self",
")",
":",
"\"\"\"Iterator of CSV values. Values are lists.\"\"\"",
"with",
"open",
"(",
"self",
".",
"path",
")",
"as",
"f",
":",
"reader",
"=",
"csv",
".",
"reader",
"(",
"f",
")",
"skip_next_line",
"=",
"self",
".",
"skip_first_line",
"for",
"line",
"in",
"reader",
":",
"if",
"skip_next_line",
":",
"skip_next_line",
"=",
"False",
"continue",
"yield",
"line"
] |
Returns the lines from a single CSV file.
|
[
"Returns",
"the",
"lines",
"from",
"a",
"single",
"CSV",
"file",
"."
] |
[
"\"\"\"\n Returns the lines from a single CSV file. If your first line is just column\n labels, you can skip it (this is the default behavior).\n\n .. py:attribute:: path\n\n Path to the file\n\n .. py:attribute:: identifier\n\n See :py:attr:`Reader.identifier`\n\n .. py:attribute:: skip_first_line\n\n If ``True`` (default), always skip the first line of the file.\n \"\"\"",
"\"\"\"\n \"\"\"",
"\"\"\"Iterator of CSV values. Values are lists.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 206
| 93
|
10271fb822012239f2d6438137d74c0f7ff19afd
|
Mugen87/yuka
|
build/yuka.module.js
|
[
"MIT"
] |
JavaScript
|
Graph
|
/**
* Class representing a sparse graph implementation based on adjacency lists.
* A sparse graph can be used to model many different types of graphs like navigation
* graphs (pathfinding), dependency graphs (e.g. technology trees) or state graphs
* (a representation of every possible state in a game).
*
* @author {@link https://github.com/Mugen87|Mugen87}
*/
|
Class representing a sparse graph implementation based on adjacency lists.
A sparse graph can be used to model many different types of graphs like navigation
graphs (pathfinding), dependency graphs or state graphs
(a representation of every possible state in a game).
|
[
"Class",
"representing",
"a",
"sparse",
"graph",
"implementation",
"based",
"on",
"adjacency",
"lists",
".",
"A",
"sparse",
"graph",
"can",
"be",
"used",
"to",
"model",
"many",
"different",
"types",
"of",
"graphs",
"like",
"navigation",
"graphs",
"(",
"pathfinding",
")",
"dependency",
"graphs",
"or",
"state",
"graphs",
"(",
"a",
"representation",
"of",
"every",
"possible",
"state",
"in",
"a",
"game",
")",
"."
] |
class Graph {
/**
* Constructs a new graph.
*/
constructor() {
/**
* Whether this graph is directed or not.
* @type {Boolean}
* @default false
*/
this.digraph = false;
this._nodes = new Map(); // contains all nodes in a map: (nodeIndex => node)
this._edges = new Map(); // adjacency list for each node: (nodeIndex => edges)
}
/**
* Adds a node to the graph.
*
* @param {Node} node - The node to add.
* @return {Graph} A reference to this graph.
*/
addNode( node ) {
const index = node.index;
this._nodes.set( index, node );
this._edges.set( index, new Array() );
return this;
}
/**
* Adds an edge to the graph. If the graph is undirected, the method
* automatically creates the opponent edge.
*
* @param {Edge} edge - The edge to add.
* @return {Graph} A reference to this graph.
*/
addEdge( edge ) {
let edges;
edges = this._edges.get( edge.from );
edges.push( edge );
if ( this.digraph === false ) {
const oppositeEdge = edge.clone();
oppositeEdge.from = edge.to;
oppositeEdge.to = edge.from;
edges = this._edges.get( edge.to );
edges.push( oppositeEdge );
}
return this;
}
/**
* Returns a node for the given node index. If no node is found,
* *null* is returned.
*
* @param {Number} index - The index of the node.
* @return {Node} The requested node.
*/
getNode( index ) {
return this._nodes.get( index ) || null;
}
/**
* Returns an edge for the given *from* and *to* node indices.
* If no node is found, *null* is returned.
*
* @param {Number} from - The index of the from node.
* @param {Number} to - The index of the to node.
* @return {Edge} The requested edge.
*/
getEdge( from, to ) {
if ( this.hasNode( from ) && this.hasNode( to ) ) {
const edges = this._edges.get( from );
for ( let i = 0, l = edges.length; i < l; i ++ ) {
const edge = edges[ i ];
if ( edge.to === to ) {
return edge;
}
}
}
return null;
}
/**
* Gathers all nodes of the graph and stores them into the given array.
*
* @param {Array<Node>} result - The result array.
* @return {Array<Node>} The result array.
*/
getNodes( result ) {
result.length = 0;
result.push( ...this._nodes.values() );
return result;
}
/**
* Gathers all edges leading from the given node index and stores them
* into the given array.
*
* @param {Number} index - The node index.
* @param {Array<Edge>} result - The result array.
* @return {Array<Edge>} The result array.
*/
getEdgesOfNode( index, result ) {
const edges = this._edges.get( index );
if ( edges !== undefined ) {
result.length = 0;
result.push( ...edges );
}
return result;
}
/**
* Returns the node count of the graph.
*
* @return {number} The amount of nodes.
*/
getNodeCount() {
return this._nodes.size;
}
/**
* Returns the edge count of the graph.
*
* @return {number} The amount of edges.
*/
getEdgeCount() {
let count = 0;
for ( const edges of this._edges.values() ) {
count += edges.length;
}
return count;
}
/**
* Removes the given node from the graph and all edges which are connected
* with this node.
*
* @param {Node} node - The node to remove.
* @return {Graph} A reference to this graph.
*/
removeNode( node ) {
this._nodes.delete( node.index );
if ( this.digraph === false ) {
// if the graph is not directed, remove all edges leading to this node
const edges = this._edges.get( node.index );
for ( const edge of edges ) {
const edgesOfNeighbor = this._edges.get( edge.to );
for ( let i = ( edgesOfNeighbor.length - 1 ); i >= 0; i -- ) {
const edgeNeighbor = edgesOfNeighbor[ i ];
if ( edgeNeighbor.to === node.index ) {
const index = edgesOfNeighbor.indexOf( edgeNeighbor );
edgesOfNeighbor.splice( index, 1 );
break;
}
}
}
} else {
// if the graph is directed, remove the edges the slow way
for ( const edges of this._edges.values() ) {
for ( let i = ( edges.length - 1 ); i >= 0; i -- ) {
const edge = edges[ i ];
if ( ! this.hasNode( edge.to ) || ! this.hasNode( edge.from ) ) {
const index = edges.indexOf( edge );
edges.splice( index, 1 );
}
}
}
}
// delete edge list of node (edges leading from this node)
this._edges.delete( node.index );
return this;
}
/**
* Removes the given edge from the graph. If the graph is undirected, the
* method also removes the opponent edge.
*
* @param {Edge} edge - The edge to remove.
* @return {Graph} A reference to this graph.
*/
removeEdge( edge ) {
// delete the edge from the node's edge list
const edges = this._edges.get( edge.from );
if ( edges !== undefined ) {
const index = edges.indexOf( edge );
edges.splice( index, 1 );
// if the graph is not directed, delete the edge connecting the node in the opposite direction
if ( this.digraph === false ) {
const edges = this._edges.get( edge.to );
for ( let i = 0, l = edges.length; i < l; i ++ ) {
const e = edges[ i ];
if ( e.to === edge.from ) {
const index = edges.indexOf( e );
edges.splice( index, 1 );
break;
}
}
}
}
return this;
}
/**
* Return true if the graph has the given node index.
*
* @param {Number} index - The node index to test.
* @return {Boolean} Whether this graph has the node or not.
*/
hasNode( index ) {
return this._nodes.has( index );
}
/**
* Return true if the graph has an edge connecting the given
* *from* and *to* node indices.
*
* @param {Number} from - The index of the from node.
* @param {Number} to - The index of the to node.
* @return {Boolean} Whether this graph has the edge or not.
*/
hasEdge( from, to ) {
if ( this.hasNode( from ) && this.hasNode( to ) ) {
const edges = this._edges.get( from );
for ( let i = 0, l = edges.length; i < l; i ++ ) {
const edge = edges[ i ];
if ( edge.to === to ) {
return true;
}
}
return false;
} else {
return false;
}
}
/**
* Removes all nodes and edges from this graph.
*
* @return {Graph} A reference to this graph.
*/
clear() {
this._nodes.clear();
this._edges.clear();
return this;
}
/**
* Transforms this instance into a JSON object.
*
* @return {Object} The JSON object.
*/
toJSON() {
const json = {
type: this.constructor.name,
digraph: this.digraph
};
const edges = new Array();
const nodes = new Array();
for ( let [ key, value ] of this._nodes.entries() ) {
const adjacencyList = new Array();
this.getEdgesOfNode( key, adjacencyList );
for ( let i = 0, l = adjacencyList.length; i < l; i ++ ) {
edges.push( adjacencyList[ i ].toJSON() );
}
nodes.push( value.toJSON() );
}
json._edges = edges;
json._nodes = nodes;
return json;
}
/**
* Restores this instance from the given JSON object.
*
* @param {Object} json - The JSON object.
* @return {Graph} A reference to this graph.
*/
fromJSON( json ) {
this.digraph = json.digraph;
for ( let i = 0, l = json._nodes.length; i < l; i ++ ) {
this.addNode( new Node().fromJSON( json._nodes[ i ] ) );
}
for ( let i = 0, l = json._edges.length; i < l; i ++ ) {
this.addEdge( new Edge().fromJSON( json._edges[ i ] ) );
}
return this;
}
}
|
[
"class",
"Graph",
"{",
"constructor",
"(",
")",
"{",
"this",
".",
"digraph",
"=",
"false",
";",
"this",
".",
"_nodes",
"=",
"new",
"Map",
"(",
")",
";",
"this",
".",
"_edges",
"=",
"new",
"Map",
"(",
")",
";",
"}",
"addNode",
"(",
"node",
")",
"{",
"const",
"index",
"=",
"node",
".",
"index",
";",
"this",
".",
"_nodes",
".",
"set",
"(",
"index",
",",
"node",
")",
";",
"this",
".",
"_edges",
".",
"set",
"(",
"index",
",",
"new",
"Array",
"(",
")",
")",
";",
"return",
"this",
";",
"}",
"addEdge",
"(",
"edge",
")",
"{",
"let",
"edges",
";",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"edge",
".",
"from",
")",
";",
"edges",
".",
"push",
"(",
"edge",
")",
";",
"if",
"(",
"this",
".",
"digraph",
"===",
"false",
")",
"{",
"const",
"oppositeEdge",
"=",
"edge",
".",
"clone",
"(",
")",
";",
"oppositeEdge",
".",
"from",
"=",
"edge",
".",
"to",
";",
"oppositeEdge",
".",
"to",
"=",
"edge",
".",
"from",
";",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"edge",
".",
"to",
")",
";",
"edges",
".",
"push",
"(",
"oppositeEdge",
")",
";",
"}",
"return",
"this",
";",
"}",
"getNode",
"(",
"index",
")",
"{",
"return",
"this",
".",
"_nodes",
".",
"get",
"(",
"index",
")",
"||",
"null",
";",
"}",
"getEdge",
"(",
"from",
",",
"to",
")",
"{",
"if",
"(",
"this",
".",
"hasNode",
"(",
"from",
")",
"&&",
"this",
".",
"hasNode",
"(",
"to",
")",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"from",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"const",
"edge",
"=",
"edges",
"[",
"i",
"]",
";",
"if",
"(",
"edge",
".",
"to",
"===",
"to",
")",
"{",
"return",
"edge",
";",
"}",
"}",
"}",
"return",
"null",
";",
"}",
"getNodes",
"(",
"result",
")",
"{",
"result",
".",
"length",
"=",
"0",
";",
"result",
".",
"push",
"(",
"...",
"this",
".",
"_nodes",
".",
"values",
"(",
")",
")",
";",
"return",
"result",
";",
"}",
"getEdgesOfNode",
"(",
"index",
",",
"result",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"index",
")",
";",
"if",
"(",
"edges",
"!==",
"undefined",
")",
"{",
"result",
".",
"length",
"=",
"0",
";",
"result",
".",
"push",
"(",
"...",
"edges",
")",
";",
"}",
"return",
"result",
";",
"}",
"getNodeCount",
"(",
")",
"{",
"return",
"this",
".",
"_nodes",
".",
"size",
";",
"}",
"getEdgeCount",
"(",
")",
"{",
"let",
"count",
"=",
"0",
";",
"for",
"(",
"const",
"edges",
"of",
"this",
".",
"_edges",
".",
"values",
"(",
")",
")",
"{",
"count",
"+=",
"edges",
".",
"length",
";",
"}",
"return",
"count",
";",
"}",
"removeNode",
"(",
"node",
")",
"{",
"this",
".",
"_nodes",
".",
"delete",
"(",
"node",
".",
"index",
")",
";",
"if",
"(",
"this",
".",
"digraph",
"===",
"false",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"node",
".",
"index",
")",
";",
"for",
"(",
"const",
"edge",
"of",
"edges",
")",
"{",
"const",
"edgesOfNeighbor",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"edge",
".",
"to",
")",
";",
"for",
"(",
"let",
"i",
"=",
"(",
"edgesOfNeighbor",
".",
"length",
"-",
"1",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"edgeNeighbor",
"=",
"edgesOfNeighbor",
"[",
"i",
"]",
";",
"if",
"(",
"edgeNeighbor",
".",
"to",
"===",
"node",
".",
"index",
")",
"{",
"const",
"index",
"=",
"edgesOfNeighbor",
".",
"indexOf",
"(",
"edgeNeighbor",
")",
";",
"edgesOfNeighbor",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"else",
"{",
"for",
"(",
"const",
"edges",
"of",
"this",
".",
"_edges",
".",
"values",
"(",
")",
")",
"{",
"for",
"(",
"let",
"i",
"=",
"(",
"edges",
".",
"length",
"-",
"1",
")",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"const",
"edge",
"=",
"edges",
"[",
"i",
"]",
";",
"if",
"(",
"!",
"this",
".",
"hasNode",
"(",
"edge",
".",
"to",
")",
"||",
"!",
"this",
".",
"hasNode",
"(",
"edge",
".",
"from",
")",
")",
"{",
"const",
"index",
"=",
"edges",
".",
"indexOf",
"(",
"edge",
")",
";",
"edges",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"}",
"}",
"}",
"}",
"this",
".",
"_edges",
".",
"delete",
"(",
"node",
".",
"index",
")",
";",
"return",
"this",
";",
"}",
"removeEdge",
"(",
"edge",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"edge",
".",
"from",
")",
";",
"if",
"(",
"edges",
"!==",
"undefined",
")",
"{",
"const",
"index",
"=",
"edges",
".",
"indexOf",
"(",
"edge",
")",
";",
"edges",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"if",
"(",
"this",
".",
"digraph",
"===",
"false",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"edge",
".",
"to",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"const",
"e",
"=",
"edges",
"[",
"i",
"]",
";",
"if",
"(",
"e",
".",
"to",
"===",
"edge",
".",
"from",
")",
"{",
"const",
"index",
"=",
"edges",
".",
"indexOf",
"(",
"e",
")",
";",
"edges",
".",
"splice",
"(",
"index",
",",
"1",
")",
";",
"break",
";",
"}",
"}",
"}",
"}",
"return",
"this",
";",
"}",
"hasNode",
"(",
"index",
")",
"{",
"return",
"this",
".",
"_nodes",
".",
"has",
"(",
"index",
")",
";",
"}",
"hasEdge",
"(",
"from",
",",
"to",
")",
"{",
"if",
"(",
"this",
".",
"hasNode",
"(",
"from",
")",
"&&",
"this",
".",
"hasNode",
"(",
"to",
")",
")",
"{",
"const",
"edges",
"=",
"this",
".",
"_edges",
".",
"get",
"(",
"from",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"const",
"edge",
"=",
"edges",
"[",
"i",
"]",
";",
"if",
"(",
"edge",
".",
"to",
"===",
"to",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"else",
"{",
"return",
"false",
";",
"}",
"}",
"clear",
"(",
")",
"{",
"this",
".",
"_nodes",
".",
"clear",
"(",
")",
";",
"this",
".",
"_edges",
".",
"clear",
"(",
")",
";",
"return",
"this",
";",
"}",
"toJSON",
"(",
")",
"{",
"const",
"json",
"=",
"{",
"type",
":",
"this",
".",
"constructor",
".",
"name",
",",
"digraph",
":",
"this",
".",
"digraph",
"}",
";",
"const",
"edges",
"=",
"new",
"Array",
"(",
")",
";",
"const",
"nodes",
"=",
"new",
"Array",
"(",
")",
";",
"for",
"(",
"let",
"[",
"key",
",",
"value",
"]",
"of",
"this",
".",
"_nodes",
".",
"entries",
"(",
")",
")",
"{",
"const",
"adjacencyList",
"=",
"new",
"Array",
"(",
")",
";",
"this",
".",
"getEdgesOfNode",
"(",
"key",
",",
"adjacencyList",
")",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"adjacencyList",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"edges",
".",
"push",
"(",
"adjacencyList",
"[",
"i",
"]",
".",
"toJSON",
"(",
")",
")",
";",
"}",
"nodes",
".",
"push",
"(",
"value",
".",
"toJSON",
"(",
")",
")",
";",
"}",
"json",
".",
"_edges",
"=",
"edges",
";",
"json",
".",
"_nodes",
"=",
"nodes",
";",
"return",
"json",
";",
"}",
"fromJSON",
"(",
"json",
")",
"{",
"this",
".",
"digraph",
"=",
"json",
".",
"digraph",
";",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"json",
".",
"_nodes",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"this",
".",
"addNode",
"(",
"new",
"Node",
"(",
")",
".",
"fromJSON",
"(",
"json",
".",
"_nodes",
"[",
"i",
"]",
")",
")",
";",
"}",
"for",
"(",
"let",
"i",
"=",
"0",
",",
"l",
"=",
"json",
".",
"_edges",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"this",
".",
"addEdge",
"(",
"new",
"Edge",
"(",
")",
".",
"fromJSON",
"(",
"json",
".",
"_edges",
"[",
"i",
"]",
")",
")",
";",
"}",
"return",
"this",
";",
"}",
"}"
] |
Class representing a sparse graph implementation based on adjacency lists.
|
[
"Class",
"representing",
"a",
"sparse",
"graph",
"implementation",
"based",
"on",
"adjacency",
"lists",
"."
] |
[
"/**\n\t* Constructs a new graph.\n\t*/",
"/**\n\t\t* Whether this graph is directed or not.\n\t\t* @type {Boolean}\n\t\t* @default false\n\t\t*/",
"// contains all nodes in a map: (nodeIndex => node)",
"// adjacency list for each node: (nodeIndex => edges)",
"/**\n\t* Adds a node to the graph.\n\t*\n\t* @param {Node} node - The node to add.\n\t* @return {Graph} A reference to this graph.\n\t*/",
"/**\n\t* Adds an edge to the graph. If the graph is undirected, the method\n\t* automatically creates the opponent edge.\n\t*\n\t* @param {Edge} edge - The edge to add.\n\t* @return {Graph} A reference to this graph.\n\t*/",
"/**\n\t* Returns a node for the given node index. If no node is found,\n\t* *null* is returned.\n\t*\n\t* @param {Number} index - The index of the node.\n\t* @return {Node} The requested node.\n\t*/",
"/**\n\t* Returns an edge for the given *from* and *to* node indices.\n\t* If no node is found, *null* is returned.\n\t*\n\t* @param {Number} from - The index of the from node.\n\t* @param {Number} to - The index of the to node.\n\t* @return {Edge} The requested edge.\n\t*/",
"/**\n\t* Gathers all nodes of the graph and stores them into the given array.\n\t*\n\t* @param {Array<Node>} result - The result array.\n\t* @return {Array<Node>} The result array.\n\t*/",
"/**\n\t* Gathers all edges leading from the given node index and stores them\n\t* into the given array.\n\t*\n\t* @param {Number} index - The node index.\n\t* @param {Array<Edge>} result - The result array.\n\t* @return {Array<Edge>} The result array.\n\t*/",
"/**\n\t* Returns the node count of the graph.\n\t*\n\t* @return {number} The amount of nodes.\n\t*/",
"/**\n\t* Returns the edge count of the graph.\n\t*\n\t* @return {number} The amount of edges.\n\t*/",
"/**\n\t* Removes the given node from the graph and all edges which are connected\n\t* with this node.\n\t*\n\t* @param {Node} node - The node to remove.\n\t* @return {Graph} A reference to this graph.\n\t*/",
"// if the graph is not directed, remove all edges leading to this node",
"// if the graph is directed, remove the edges the slow way",
"// delete edge list of node (edges leading from this node)",
"/**\n\t* Removes the given edge from the graph. If the graph is undirected, the\n\t* method also removes the opponent edge.\n\t*\n\t* @param {Edge} edge - The edge to remove.\n\t* @return {Graph} A reference to this graph.\n\t*/",
"// delete the edge from the node's edge list",
"// if the graph is not directed, delete the edge connecting the node in the opposite direction",
"/**\n\t* Return true if the graph has the given node index.\n\t*\n\t* @param {Number} index - The node index to test.\n\t* @return {Boolean} Whether this graph has the node or not.\n\t*/",
"/**\n\t* Return true if the graph has an edge connecting the given\n\t* *from* and *to* node indices.\n\t*\n\t* @param {Number} from - The index of the from node.\n\t* @param {Number} to - The index of the to node.\n\t* @return {Boolean} Whether this graph has the edge or not.\n\t*/",
"/**\n\t* Removes all nodes and edges from this graph.\n\t*\n\t* @return {Graph} A reference to this graph.\n\t*/",
"/**\n\t* Transforms this instance into a JSON object.\n\t*\n\t* @return {Object} The JSON object.\n\t*/",
"/**\n\t* Restores this instance from the given JSON object.\n\t*\n\t* @param {Object} json - The JSON object.\n\t* @return {Graph} A reference to this graph.\n\t*/"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "author",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 19
| 2,139
| 81
|
ab4dfbcd7bdbc544a243d74e87e90efaa4fa9bfa
|
skremp/pictura-io
|
servlet/src/main/java/io/pictura/servlet/RequestProcessor.java
|
[
"Apache-2.0"
] |
Java
|
IpAddressMatcher
|
/**
* Matches a request based on IP Address or subnet mask matching against the
* remote address.
* <p>
* Both IPv6 and IPv4 addresses are supported, but a matcher which is
* configured with an IPv4 address will never match a request which returns
* an IPv6 address, and vice-versa.
* <p>
* <i>
* Derived from org.springframework.security/spring-security-web/
* 3.1.2.RELEASE/org/springframework/security/web/util/IpAddressMatcher.java.
* The origin source is licensed under the Apache License, Version 2.0
*/
|
Matches a request based on IP Address or subnet mask matching against the
remote address.
Both IPv6 and IPv4 addresses are supported, but a matcher which is
configured with an IPv4 address will never match a request which returns
an IPv6 address, and vice-versa.
|
[
"Matches",
"a",
"request",
"based",
"on",
"IP",
"Address",
"or",
"subnet",
"mask",
"matching",
"against",
"the",
"remote",
"address",
".",
"Both",
"IPv6",
"and",
"IPv4",
"addresses",
"are",
"supported",
"but",
"a",
"matcher",
"which",
"is",
"configured",
"with",
"an",
"IPv4",
"address",
"will",
"never",
"match",
"a",
"request",
"which",
"returns",
"an",
"IPv6",
"address",
"and",
"vice",
"-",
"versa",
"."
] |
private static final class IpAddressMatcher {
private final int nMaskBits;
private final InetAddress requiredAddress;
/**
* Takes a specific IP address or a range specified using the IP/Netmask
* (e.g. 192.168.1.0/24 or 202.24.0.0/14).
*
* @param ipAddress the address or range of addresses from which the
* request must come.
*/
IpAddressMatcher(String ipAddress) {
if (ipAddress.indexOf('/') > 0) {
String[] addressAndMask = ipAddress.split("/");
ipAddress = addressAndMask[0];
nMaskBits = Integer.parseInt(addressAndMask[1]);
} else {
nMaskBits = -1;
}
requiredAddress = parseAddress(ipAddress);
}
boolean matches(String address) {
InetAddress remoteAddress = parseAddress(address);
if (!requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (nMaskBits < 0) {
return remoteAddress.equals(requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = requiredAddress.getAddress();
int oddBits = nMaskBits % 8;
int nMaskBytes = nMaskBits / 8 + (oddBits == 0 ? 0 : 1);
byte[] mask = new byte[nMaskBytes];
Arrays.fill(mask, 0, oddBits == 0 ? mask.length : mask.length - 1, (byte) 0xFF);
if (oddBits != 0) {
int finalByte = (1 << oddBits) - 1;
finalByte <<= 8 - oddBits;
mask[mask.length - 1] = (byte) finalByte;
}
for (int i = 0; i < mask.length; i++) {
if ((remAddr[i] & mask[i]) != (reqAddr[i] & mask[i])) {
return false;
}
}
return true;
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
} catch (UnknownHostException e) {
throw new IllegalArgumentException("Failed to parse address" + address, e);
}
}
}
|
[
"private",
"static",
"final",
"class",
"IpAddressMatcher",
"{",
"private",
"final",
"int",
"nMaskBits",
";",
"private",
"final",
"InetAddress",
"requiredAddress",
";",
"/**\n\t * Takes a specific IP address or a range specified using the IP/Netmask\n\t * (e.g. 192.168.1.0/24 or 202.24.0.0/14).\n\t *\n\t * @param ipAddress the address or range of addresses from which the\n\t * request must come.\n\t */",
"IpAddressMatcher",
"(",
"String",
"ipAddress",
")",
"{",
"if",
"(",
"ipAddress",
".",
"indexOf",
"(",
"'/'",
")",
">",
"0",
")",
"{",
"String",
"[",
"]",
"addressAndMask",
"=",
"ipAddress",
".",
"split",
"(",
"\"",
"/",
"\"",
")",
";",
"ipAddress",
"=",
"addressAndMask",
"[",
"0",
"]",
";",
"nMaskBits",
"=",
"Integer",
".",
"parseInt",
"(",
"addressAndMask",
"[",
"1",
"]",
")",
";",
"}",
"else",
"{",
"nMaskBits",
"=",
"-",
"1",
";",
"}",
"requiredAddress",
"=",
"parseAddress",
"(",
"ipAddress",
")",
";",
"}",
"boolean",
"matches",
"(",
"String",
"address",
")",
"{",
"InetAddress",
"remoteAddress",
"=",
"parseAddress",
"(",
"address",
")",
";",
"if",
"(",
"!",
"requiredAddress",
".",
"getClass",
"(",
")",
".",
"equals",
"(",
"remoteAddress",
".",
"getClass",
"(",
")",
")",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"nMaskBits",
"<",
"0",
")",
"{",
"return",
"remoteAddress",
".",
"equals",
"(",
"requiredAddress",
")",
";",
"}",
"byte",
"[",
"]",
"remAddr",
"=",
"remoteAddress",
".",
"getAddress",
"(",
")",
";",
"byte",
"[",
"]",
"reqAddr",
"=",
"requiredAddress",
".",
"getAddress",
"(",
")",
";",
"int",
"oddBits",
"=",
"nMaskBits",
"%",
"8",
";",
"int",
"nMaskBytes",
"=",
"nMaskBits",
"/",
"8",
"+",
"(",
"oddBits",
"==",
"0",
"?",
"0",
":",
"1",
")",
";",
"byte",
"[",
"]",
"mask",
"=",
"new",
"byte",
"[",
"nMaskBytes",
"]",
";",
"Arrays",
".",
"fill",
"(",
"mask",
",",
"0",
",",
"oddBits",
"==",
"0",
"?",
"mask",
".",
"length",
":",
"mask",
".",
"length",
"-",
"1",
",",
"(",
"byte",
")",
"0xFF",
")",
";",
"if",
"(",
"oddBits",
"!=",
"0",
")",
"{",
"int",
"finalByte",
"=",
"(",
"1",
"<<",
"oddBits",
")",
"-",
"1",
";",
"finalByte",
"<<=",
"8",
"-",
"oddBits",
";",
"mask",
"[",
"mask",
".",
"length",
"-",
"1",
"]",
"=",
"(",
"byte",
")",
"finalByte",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"mask",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"(",
"remAddr",
"[",
"i",
"]",
"&",
"mask",
"[",
"i",
"]",
")",
"!=",
"(",
"reqAddr",
"[",
"i",
"]",
"&",
"mask",
"[",
"i",
"]",
")",
")",
"{",
"return",
"false",
";",
"}",
"}",
"return",
"true",
";",
"}",
"private",
"InetAddress",
"parseAddress",
"(",
"String",
"address",
")",
"{",
"try",
"{",
"return",
"InetAddress",
".",
"getByName",
"(",
"address",
")",
";",
"}",
"catch",
"(",
"UnknownHostException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Failed to parse address",
"\"",
"+",
"address",
",",
"e",
")",
";",
"}",
"}",
"}"
] |
Matches a request based on IP Address or subnet mask matching against the
remote address.
|
[
"Matches",
"a",
"request",
"based",
"on",
"IP",
"Address",
"or",
"subnet",
"mask",
"matching",
"against",
"the",
"remote",
"address",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 488
| 137
|
90d217a75fb8b84342a1b1d26115846b32b60a03
|
MartinSpiessl/java-common-lib
|
src/org/sosy_lab/common/ProcessExecutor.java
|
[
"ECL-2.0",
"Apache-2.0"
] |
Java
|
ProcessExecutor
|
/**
* This class can be used to execute a separate process and read its output in a convenient way. It
* is only useful for processes which handle only one task and exit afterwards.
*
* <p>This class is not thread-safe, it assumes that never two of its methods are executed
* simultaneously.
*
* <p>When an instance of this class is created, the corresponding process is started immediately.
* Then some text may be written to stdin of the process with the {@link #println(String)} method.
* Afterwards {@link #join()} has to be called, which reads the output from the process and calls
* the handle* methods. This method blocks, i.e. when it returns the process has terminated. Now the
* get* methods may be used to get the output of the process.
*
* @param <E> The type of the exceptions the handle* methods may throw.
*/
|
This class can be used to execute a separate process and read its output in a convenient way. It
is only useful for processes which handle only one task and exit afterwards.
This class is not thread-safe, it assumes that never two of its methods are executed
simultaneously.
When an instance of this class is created, the corresponding process is started immediately.
Then some text may be written to stdin of the process with the #println(String) method.
Afterwards #join() has to be called, which reads the output from the process and calls
the handle* methods.
@param The type of the exceptions the handle* methods may throw.
|
[
"This",
"class",
"can",
"be",
"used",
"to",
"execute",
"a",
"separate",
"process",
"and",
"read",
"its",
"output",
"in",
"a",
"convenient",
"way",
".",
"It",
"is",
"only",
"useful",
"for",
"processes",
"which",
"handle",
"only",
"one",
"task",
"and",
"exit",
"afterwards",
".",
"This",
"class",
"is",
"not",
"thread",
"-",
"safe",
"it",
"assumes",
"that",
"never",
"two",
"of",
"its",
"methods",
"are",
"executed",
"simultaneously",
".",
"When",
"an",
"instance",
"of",
"this",
"class",
"is",
"created",
"the",
"corresponding",
"process",
"is",
"started",
"immediately",
".",
"Then",
"some",
"text",
"may",
"be",
"written",
"to",
"stdin",
"of",
"the",
"process",
"with",
"the",
"#println",
"(",
"String",
")",
"method",
".",
"Afterwards",
"#join",
"()",
"has",
"to",
"be",
"called",
"which",
"reads",
"the",
"output",
"from",
"the",
"process",
"and",
"calls",
"the",
"handle",
"*",
"methods",
".",
"@param",
"The",
"type",
"of",
"the",
"exceptions",
"the",
"handle",
"*",
"methods",
"may",
"throw",
"."
] |
public class ProcessExecutor<E extends Exception> {
private final String name;
private final Class<E> exceptionClass;
private final Writer in;
private final ListeningExecutorService executor =
MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
private final ListenableFuture<?> outFuture;
private final ListenableFuture<?> errFuture;
private final ListenableFuture<Integer> processFuture;
private final List<String> output = new ArrayList<>();
private final List<String> errorOutput = new ArrayList<>();
private boolean finished = false;
protected final LogManager logger;
/** @see #ProcessExecutor(LogManager, Class, String...) */
public ProcessExecutor(LogManager logger, Class<E> exceptionClass, String... cmd)
throws IOException {
this(logger, exceptionClass, ImmutableMap.<String, String>of(), cmd);
}
/**
* Create an instance and immediately execute the supplied command with the supplied environment
* variables.
*
* <p>The map with the environment parameters will override the values from the default
* environment. Values in the map may be null, which means that this variable is removed from the
* environment. Null is not allowed as a key in the map.
*
* <p>Whenever a line is read on stdout or stderr of the process, the {@link
* #handleOutput(String)} or the {@link #handleErrorOutput(String)} are called respectively.
*
* <p>It is strongly advised to call {@link #join()} sometimes, as otherwise there may be
* resources not being cleaned up properly. Also exceptions thrown by the handling methods would
* get swallowed.
*
* @see Runtime#exec(String[])
* @param logger A LogManager for debug output.
* @param exceptionClass The type of exception that the handler methods may throw.
* @param environmentOverride Map with environment variables to set.
* @param cmd The command with arguments to execute.
* @throws IOException If the process cannot be executed.
*/
@SuppressWarnings("ConstructorInvokesOverridable")
public ProcessExecutor(
LogManager logger,
Class<E> exceptionClass,
Map<String, String> environmentOverride,
String... cmd)
throws IOException {
checkNotNull(cmd);
checkArgument(cmd.length > 0);
this.logger = checkNotNull(logger);
this.exceptionClass = checkNotNull(exceptionClass);
this.name = cmd[0];
logger.log(Level.FINEST, "Executing", name);
logger.log(Level.ALL, (Object[]) cmd);
ProcessBuilder proc = new ProcessBuilder(cmd);
Map<String, String> environment = proc.environment();
for (Map.Entry<String, String> entry : environmentOverride.entrySet()) {
if (entry.getValue() == null) {
environment.remove(entry.getKey());
} else {
environment.put(entry.getKey(), entry.getValue());
}
}
Process process = proc.start();
processFuture =
executor.submit(
() -> {
// this callable guarantees that when it finishes,
// the external process also has finished and it has been wait()ed for
// (which is important for ulimit timing measurements on Linux)
logger.log(Level.FINEST, "Waiting for", name);
try {
int exitCode1 = process.waitFor();
logger.log(Level.FINEST, name, "has terminated normally");
handleExitCode(exitCode1);
return exitCode1;
} catch (InterruptedException e) {
process.destroy();
while (true) {
try {
int exitCode2 = process.waitFor();
logger.log(Level.FINEST, name, "has terminated after it was cancelled");
// no call to handleExitCode() here, we do this only with normal termination
// reset interrupted status
Thread.currentThread().interrupt();
return exitCode2;
} catch (InterruptedException ignored) {
// ignore, we will call interrupt()
}
}
}
});
// platform charset is what processes usually use for communication
in = new OutputStreamWriter(process.getOutputStream(), Charset.defaultCharset());
// wrap both output handling callables in CancellingCallables so that
// exceptions thrown by the handling methods terminate the process immediately
outFuture =
executor.submit(
() -> {
try (BufferedReader reader =
new BufferedReader(
// platform charset is what processes usually use for communication
new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
@Var String line;
while ((line = reader.readLine()) != null) {
handleOutput(line);
}
} catch (IOException e) {
if (processFuture.isCancelled()) {
// IOExceptions after a killed process are no suprise
// Log and ignore so they don't mask the real cause
// why we killed the process.
logger.logDebugException(e, "IOException after process was killed");
} else {
throw e;
}
}
return null;
});
errFuture =
executor.submit(
() -> {
try (BufferedReader reader =
new BufferedReader(
// platform charset is what processes usually use for communication
new InputStreamReader(process.getErrorStream(), Charset.defaultCharset()))) {
@Var String line;
while ((line = reader.readLine()) != null) {
handleErrorOutput(line);
}
} catch (IOException e) {
if (processFuture.isCancelled()) {
// IOExceptions after a killed process are no suprise
// Log and ignore so they don't mask the real cause
// why we killed the process.
logger.logDebugException(e, "IOException after process was killed");
} else {
throw e;
}
}
return null;
});
FutureCallback<Object> cancelProcessOnFailure =
new FutureCallback<Object>() {
@Override
public void onFailure(Throwable e) {
if (!processFuture.isCancelled()) {
logger.logUserException(
Level.FINEST, e, "Killing " + name + " due to error in output handling");
processFuture.cancel(true);
} else {
logger.logDebugException(
e, "Error in output handling after " + name + " was already killed");
}
}
@Override
public void onSuccess(Object pArg0) {}
};
Futures.addCallback(outFuture, cancelProcessOnFailure, directExecutor());
Futures.addCallback(errFuture, cancelProcessOnFailure, directExecutor());
executor.shutdown(); // don't accept further tasks
}
/**
* Write a String to the process. May only be called before {@link #join()} was called, as
* afterwards the process is not running anymore.
*/
public void println(String s) throws IOException {
checkNotNull(s);
print(s + "\n");
}
/**
* Write a String to the process. May only be called before {@link #join()} was called, as
* afterwards the process is not running anymore.
*/
public void print(String s) throws IOException {
checkNotNull(s);
checkState(!finished, "Cannot write to process that has already terminated.");
in.write(s);
in.flush();
}
/** Sends the EOF (end of file) signal to stdin of the process. */
public void sendEOF() throws IOException {
checkState(!finished, "Cannot write to process that has already terminated.");
in.close();
}
/**
* Wait for the process to terminate.
*
* @param timelimit Maximum time to wait for process (in milliseconds)
* @return The exit code of the process.
* @throws IOException passed from the handle* methods.
* @throws E passed from the handle* methods.
* @throws TimeoutException If timeout is hit.
* @throws InterruptedException If the current thread is interrupted.
*/
public int join(long timelimit) throws IOException, E, TimeoutException, InterruptedException {
try {
@Var Integer exitCode = null;
try {
if (timelimit > 0) {
exitCode = processFuture.get(timelimit, TimeUnit.MILLISECONDS);
} else {
exitCode = processFuture.get();
}
} catch (CancellationException e) {
// the processFuture has been cancelled, probably because the outFuture or
// the errFuture threw an exception
// ignore exception here and call get() on the other futures to get their
// exceptions
}
// wait for reading tasks to finish and to get exceptions
outFuture.get();
errFuture.get();
if (exitCode == null) {
// the processFuture threw a CancellationException,
// but the reading futures threw no exception
// Shouldn't happen, this probably means that our processFuture
// was interrupted from some outsider.
// Assume this as an interrupt.
throw new InterruptedException();
}
return exitCode;
} catch (TimeoutException e) {
logger.log(Level.WARNING, "Killing", name, "due to timeout");
processFuture.cancel(true);
throw e;
} catch (InterruptedException e) {
logger.log(Level.WARNING, "Killing", name, "due to user interrupt");
processFuture.cancel(true);
throw e;
} catch (ExecutionException e) {
Throwable t = e.getCause();
Throwables.propagateIfPossible(t, IOException.class, exceptionClass);
throw new UnexpectedCheckedException("output handling of external process " + name, t);
} finally {
// cleanup
assert processFuture.isDone();
Concurrency.waitForTermination(executor); // needed for memory visibility of the Callables
try {
in.close();
} catch (IOException e) {
// Not expected to happen because process is already dead anyway.
// Don't hide any real exception by throwing this one.
}
finished = true;
}
}
/**
* Wait for the process to terminate and read all of it's output. Whenever a line is read on
* stdout or stderr of the process, the {@link #handleOutput(String)} or the {@link
* #handleErrorOutput(String)} are called respectively.
*
* @return The exit code of the process.
* @throws IOException passed from the handle* methods.
* @throws E passed from the handle* methods.
* @throws InterruptedException If the current thread is interrupted.
*/
public int join() throws IOException, E, InterruptedException {
try {
return join(0);
} catch (TimeoutException e) {
// cannot occur with timeout==0
throw new AssertionError(e);
}
}
/**
* Handle one line of output from the process. This method may be overwritten by clients. The
* default implementation logs the line on level ALL and adds it to a list which may later be
* retrieved with {@link #getOutput()}. It never throws an exception (but client implementations
* may do so).
*
* <p>This method will be called in a new thread.
*
* @throws E Overwriting methods may throw this exception which will be propagated.
*/
protected void handleOutput(String line) throws E {
checkNotNull(line);
logger.log(Level.ALL, name, "output:", line);
output.add(line);
}
/**
* Handle one line of stderr output from the process. This method may be overwritten by clients.
* The default implementation logs the line on level WARNING and adds it to a list which may later
* be retrieved with {@link #getErrorOutput()}. It never throws an exception (but client
* implementations may do so).
*
* <p>This method will be called in a new thread.
*
* @throws E Overwriting methods may throw this exception which will be propagated.
*/
protected void handleErrorOutput(String line) throws E {
checkNotNull(line);
logger.log(Level.WARNING, name, "error output:", line);
errorOutput.add(line);
}
/**
* Handle the exit code of the process. This method may be overwritten by clients. The default
* implementation logs the code on level WARNING, if it is non-zero.
*
* <p>This method will be called in a new thread.
*
* @throws E Overwriting methods may throw this exception which will be propagated.
*/
protected void handleExitCode(int code) throws E {
if (code != 0) {
logger.log(Level.WARNING, "Exit code from", name, "was", code);
}
}
/**
* Checks whether the process has finished already. This is true exactly if {@link #join()} has
* been called.
*/
public boolean isFinished() {
return finished;
}
/**
* Returns the complete output of the process. May only be called after {@link #join()} has been
* called.
*/
public List<String> getOutput() {
checkState(finished, "Cannot get output while process is not yet finished");
return output;
}
/**
* Returns the complete output to stderr of the process. May only be called after {@link #join()}
* has been called.
*/
public List<String> getErrorOutput() {
checkState(finished, "Cannot get error output while process is not yet finished");
return errorOutput;
}
}
|
[
"public",
"class",
"ProcessExecutor",
"<",
"E",
"extends",
"Exception",
">",
"{",
"private",
"final",
"String",
"name",
";",
"private",
"final",
"Class",
"<",
"E",
">",
"exceptionClass",
";",
"private",
"final",
"Writer",
"in",
";",
"private",
"final",
"ListeningExecutorService",
"executor",
"=",
"MoreExecutors",
".",
"listeningDecorator",
"(",
"Executors",
".",
"newFixedThreadPool",
"(",
"3",
")",
")",
";",
"private",
"final",
"ListenableFuture",
"<",
"?",
">",
"outFuture",
";",
"private",
"final",
"ListenableFuture",
"<",
"?",
">",
"errFuture",
";",
"private",
"final",
"ListenableFuture",
"<",
"Integer",
">",
"processFuture",
";",
"private",
"final",
"List",
"<",
"String",
">",
"output",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"private",
"final",
"List",
"<",
"String",
">",
"errorOutput",
"=",
"new",
"ArrayList",
"<",
">",
"(",
")",
";",
"private",
"boolean",
"finished",
"=",
"false",
";",
"protected",
"final",
"LogManager",
"logger",
";",
"/** @see #ProcessExecutor(LogManager, Class, String...) */",
"public",
"ProcessExecutor",
"(",
"LogManager",
"logger",
",",
"Class",
"<",
"E",
">",
"exceptionClass",
",",
"String",
"...",
"cmd",
")",
"throws",
"IOException",
"{",
"this",
"(",
"logger",
",",
"exceptionClass",
",",
"ImmutableMap",
".",
"<",
"String",
",",
"String",
">",
"of",
"(",
")",
",",
"cmd",
")",
";",
"}",
"/**\n * Create an instance and immediately execute the supplied command with the supplied environment\n * variables.\n *\n * <p>The map with the environment parameters will override the values from the default\n * environment. Values in the map may be null, which means that this variable is removed from the\n * environment. Null is not allowed as a key in the map.\n *\n * <p>Whenever a line is read on stdout or stderr of the process, the {@link\n * #handleOutput(String)} or the {@link #handleErrorOutput(String)} are called respectively.\n *\n * <p>It is strongly advised to call {@link #join()} sometimes, as otherwise there may be\n * resources not being cleaned up properly. Also exceptions thrown by the handling methods would\n * get swallowed.\n *\n * @see Runtime#exec(String[])\n * @param logger A LogManager for debug output.\n * @param exceptionClass The type of exception that the handler methods may throw.\n * @param environmentOverride Map with environment variables to set.\n * @param cmd The command with arguments to execute.\n * @throws IOException If the process cannot be executed.\n */",
"@",
"SuppressWarnings",
"(",
"\"",
"ConstructorInvokesOverridable",
"\"",
")",
"public",
"ProcessExecutor",
"(",
"LogManager",
"logger",
",",
"Class",
"<",
"E",
">",
"exceptionClass",
",",
"Map",
"<",
"String",
",",
"String",
">",
"environmentOverride",
",",
"String",
"...",
"cmd",
")",
"throws",
"IOException",
"{",
"checkNotNull",
"(",
"cmd",
")",
";",
"checkArgument",
"(",
"cmd",
".",
"length",
">",
"0",
")",
";",
"this",
".",
"logger",
"=",
"checkNotNull",
"(",
"logger",
")",
";",
"this",
".",
"exceptionClass",
"=",
"checkNotNull",
"(",
"exceptionClass",
")",
";",
"this",
".",
"name",
"=",
"cmd",
"[",
"0",
"]",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"\"",
"Executing",
"\"",
",",
"name",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"ALL",
",",
"(",
"Object",
"[",
"]",
")",
"cmd",
")",
";",
"ProcessBuilder",
"proc",
"=",
"new",
"ProcessBuilder",
"(",
"cmd",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"environment",
"=",
"proc",
".",
"environment",
"(",
")",
";",
"for",
"(",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
"entry",
":",
"environmentOverride",
".",
"entrySet",
"(",
")",
")",
"{",
"if",
"(",
"entry",
".",
"getValue",
"(",
")",
"==",
"null",
")",
"{",
"environment",
".",
"remove",
"(",
"entry",
".",
"getKey",
"(",
")",
")",
";",
"}",
"else",
"{",
"environment",
".",
"put",
"(",
"entry",
".",
"getKey",
"(",
")",
",",
"entry",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"Process",
"process",
"=",
"proc",
".",
"start",
"(",
")",
";",
"processFuture",
"=",
"executor",
".",
"submit",
"(",
"(",
")",
"->",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"\"",
"Waiting for",
"\"",
",",
"name",
")",
";",
"try",
"{",
"int",
"exitCode1",
"=",
"process",
".",
"waitFor",
"(",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"name",
",",
"\"",
"has terminated normally",
"\"",
")",
";",
"handleExitCode",
"(",
"exitCode1",
")",
";",
"return",
"exitCode1",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"process",
".",
"destroy",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"try",
"{",
"int",
"exitCode2",
"=",
"process",
".",
"waitFor",
"(",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"FINEST",
",",
"name",
",",
"\"",
"has terminated after it was cancelled",
"\"",
")",
";",
"Thread",
".",
"currentThread",
"(",
")",
".",
"interrupt",
"(",
")",
";",
"return",
"exitCode2",
";",
"}",
"catch",
"(",
"InterruptedException",
"ignored",
")",
"{",
"}",
"}",
"}",
"}",
")",
";",
"in",
"=",
"new",
"OutputStreamWriter",
"(",
"process",
".",
"getOutputStream",
"(",
")",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
";",
"outFuture",
"=",
"executor",
".",
"submit",
"(",
"(",
")",
"->",
"{",
"try",
"(",
"BufferedReader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"process",
".",
"getInputStream",
"(",
")",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
")",
")",
"{",
"@",
"Var",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"handleOutput",
"(",
"line",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"processFuture",
".",
"isCancelled",
"(",
")",
")",
"{",
"logger",
".",
"logDebugException",
"(",
"e",
",",
"\"",
"IOException after process was killed",
"\"",
")",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"return",
"null",
";",
"}",
")",
";",
"errFuture",
"=",
"executor",
".",
"submit",
"(",
"(",
")",
"->",
"{",
"try",
"(",
"BufferedReader",
"reader",
"=",
"new",
"BufferedReader",
"(",
"new",
"InputStreamReader",
"(",
"process",
".",
"getErrorStream",
"(",
")",
",",
"Charset",
".",
"defaultCharset",
"(",
")",
")",
")",
")",
"{",
"@",
"Var",
"String",
"line",
";",
"while",
"(",
"(",
"line",
"=",
"reader",
".",
"readLine",
"(",
")",
")",
"!=",
"null",
")",
"{",
"handleErrorOutput",
"(",
"line",
")",
";",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"processFuture",
".",
"isCancelled",
"(",
")",
")",
"{",
"logger",
".",
"logDebugException",
"(",
"e",
",",
"\"",
"IOException after process was killed",
"\"",
")",
";",
"}",
"else",
"{",
"throw",
"e",
";",
"}",
"}",
"return",
"null",
";",
"}",
")",
";",
"FutureCallback",
"<",
"Object",
">",
"cancelProcessOnFailure",
"=",
"new",
"FutureCallback",
"<",
"Object",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onFailure",
"(",
"Throwable",
"e",
")",
"{",
"if",
"(",
"!",
"processFuture",
".",
"isCancelled",
"(",
")",
")",
"{",
"logger",
".",
"logUserException",
"(",
"Level",
".",
"FINEST",
",",
"e",
",",
"\"",
"Killing ",
"\"",
"+",
"name",
"+",
"\"",
" due to error in output handling",
"\"",
")",
";",
"processFuture",
".",
"cancel",
"(",
"true",
")",
";",
"}",
"else",
"{",
"logger",
".",
"logDebugException",
"(",
"e",
",",
"\"",
"Error in output handling after ",
"\"",
"+",
"name",
"+",
"\"",
" was already killed",
"\"",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onSuccess",
"(",
"Object",
"pArg0",
")",
"{",
"}",
"}",
";",
"Futures",
".",
"addCallback",
"(",
"outFuture",
",",
"cancelProcessOnFailure",
",",
"directExecutor",
"(",
")",
")",
";",
"Futures",
".",
"addCallback",
"(",
"errFuture",
",",
"cancelProcessOnFailure",
",",
"directExecutor",
"(",
")",
")",
";",
"executor",
".",
"shutdown",
"(",
")",
";",
"}",
"/**\n * Write a String to the process. May only be called before {@link #join()} was called, as\n * afterwards the process is not running anymore.\n */",
"public",
"void",
"println",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"checkNotNull",
"(",
"s",
")",
";",
"print",
"(",
"s",
"+",
"\"",
"\\n",
"\"",
")",
";",
"}",
"/**\n * Write a String to the process. May only be called before {@link #join()} was called, as\n * afterwards the process is not running anymore.\n */",
"public",
"void",
"print",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"checkNotNull",
"(",
"s",
")",
";",
"checkState",
"(",
"!",
"finished",
",",
"\"",
"Cannot write to process that has already terminated.",
"\"",
")",
";",
"in",
".",
"write",
"(",
"s",
")",
";",
"in",
".",
"flush",
"(",
")",
";",
"}",
"/** Sends the EOF (end of file) signal to stdin of the process. */",
"public",
"void",
"sendEOF",
"(",
")",
"throws",
"IOException",
"{",
"checkState",
"(",
"!",
"finished",
",",
"\"",
"Cannot write to process that has already terminated.",
"\"",
")",
";",
"in",
".",
"close",
"(",
")",
";",
"}",
"/**\n * Wait for the process to terminate.\n *\n * @param timelimit Maximum time to wait for process (in milliseconds)\n * @return The exit code of the process.\n * @throws IOException passed from the handle* methods.\n * @throws E passed from the handle* methods.\n * @throws TimeoutException If timeout is hit.\n * @throws InterruptedException If the current thread is interrupted.\n */",
"public",
"int",
"join",
"(",
"long",
"timelimit",
")",
"throws",
"IOException",
",",
"E",
",",
"TimeoutException",
",",
"InterruptedException",
"{",
"try",
"{",
"@",
"Var",
"Integer",
"exitCode",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"timelimit",
">",
"0",
")",
"{",
"exitCode",
"=",
"processFuture",
".",
"get",
"(",
"timelimit",
",",
"TimeUnit",
".",
"MILLISECONDS",
")",
";",
"}",
"else",
"{",
"exitCode",
"=",
"processFuture",
".",
"get",
"(",
")",
";",
"}",
"}",
"catch",
"(",
"CancellationException",
"e",
")",
"{",
"}",
"outFuture",
".",
"get",
"(",
")",
";",
"errFuture",
".",
"get",
"(",
")",
";",
"if",
"(",
"exitCode",
"==",
"null",
")",
"{",
"throw",
"new",
"InterruptedException",
"(",
")",
";",
"}",
"return",
"exitCode",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Killing",
"\"",
",",
"name",
",",
"\"",
"due to timeout",
"\"",
")",
";",
"processFuture",
".",
"cancel",
"(",
"true",
")",
";",
"throw",
"e",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Killing",
"\"",
",",
"name",
",",
"\"",
"due to user interrupt",
"\"",
")",
";",
"processFuture",
".",
"cancel",
"(",
"true",
")",
";",
"throw",
"e",
";",
"}",
"catch",
"(",
"ExecutionException",
"e",
")",
"{",
"Throwable",
"t",
"=",
"e",
".",
"getCause",
"(",
")",
";",
"Throwables",
".",
"propagateIfPossible",
"(",
"t",
",",
"IOException",
".",
"class",
",",
"exceptionClass",
")",
";",
"throw",
"new",
"UnexpectedCheckedException",
"(",
"\"",
"output handling of external process ",
"\"",
"+",
"name",
",",
"t",
")",
";",
"}",
"finally",
"{",
"assert",
"processFuture",
".",
"isDone",
"(",
")",
";",
"Concurrency",
".",
"waitForTermination",
"(",
"executor",
")",
";",
"try",
"{",
"in",
".",
"close",
"(",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"}",
"finished",
"=",
"true",
";",
"}",
"}",
"/**\n * Wait for the process to terminate and read all of it's output. Whenever a line is read on\n * stdout or stderr of the process, the {@link #handleOutput(String)} or the {@link\n * #handleErrorOutput(String)} are called respectively.\n *\n * @return The exit code of the process.\n * @throws IOException passed from the handle* methods.\n * @throws E passed from the handle* methods.\n * @throws InterruptedException If the current thread is interrupted.\n */",
"public",
"int",
"join",
"(",
")",
"throws",
"IOException",
",",
"E",
",",
"InterruptedException",
"{",
"try",
"{",
"return",
"join",
"(",
"0",
")",
";",
"}",
"catch",
"(",
"TimeoutException",
"e",
")",
"{",
"throw",
"new",
"AssertionError",
"(",
"e",
")",
";",
"}",
"}",
"/**\n * Handle one line of output from the process. This method may be overwritten by clients. The\n * default implementation logs the line on level ALL and adds it to a list which may later be\n * retrieved with {@link #getOutput()}. It never throws an exception (but client implementations\n * may do so).\n *\n * <p>This method will be called in a new thread.\n *\n * @throws E Overwriting methods may throw this exception which will be propagated.\n */",
"protected",
"void",
"handleOutput",
"(",
"String",
"line",
")",
"throws",
"E",
"{",
"checkNotNull",
"(",
"line",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"ALL",
",",
"name",
",",
"\"",
"output:",
"\"",
",",
"line",
")",
";",
"output",
".",
"add",
"(",
"line",
")",
";",
"}",
"/**\n * Handle one line of stderr output from the process. This method may be overwritten by clients.\n * The default implementation logs the line on level WARNING and adds it to a list which may later\n * be retrieved with {@link #getErrorOutput()}. It never throws an exception (but client\n * implementations may do so).\n *\n * <p>This method will be called in a new thread.\n *\n * @throws E Overwriting methods may throw this exception which will be propagated.\n */",
"protected",
"void",
"handleErrorOutput",
"(",
"String",
"line",
")",
"throws",
"E",
"{",
"checkNotNull",
"(",
"line",
")",
";",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"name",
",",
"\"",
"error output:",
"\"",
",",
"line",
")",
";",
"errorOutput",
".",
"add",
"(",
"line",
")",
";",
"}",
"/**\n * Handle the exit code of the process. This method may be overwritten by clients. The default\n * implementation logs the code on level WARNING, if it is non-zero.\n *\n * <p>This method will be called in a new thread.\n *\n * @throws E Overwriting methods may throw this exception which will be propagated.\n */",
"protected",
"void",
"handleExitCode",
"(",
"int",
"code",
")",
"throws",
"E",
"{",
"if",
"(",
"code",
"!=",
"0",
")",
"{",
"logger",
".",
"log",
"(",
"Level",
".",
"WARNING",
",",
"\"",
"Exit code from",
"\"",
",",
"name",
",",
"\"",
"was",
"\"",
",",
"code",
")",
";",
"}",
"}",
"/**\n * Checks whether the process has finished already. This is true exactly if {@link #join()} has\n * been called.\n */",
"public",
"boolean",
"isFinished",
"(",
")",
"{",
"return",
"finished",
";",
"}",
"/**\n * Returns the complete output of the process. May only be called after {@link #join()} has been\n * called.\n */",
"public",
"List",
"<",
"String",
">",
"getOutput",
"(",
")",
"{",
"checkState",
"(",
"finished",
",",
"\"",
"Cannot get output while process is not yet finished",
"\"",
")",
";",
"return",
"output",
";",
"}",
"/**\n * Returns the complete output to stderr of the process. May only be called after {@link #join()}\n * has been called.\n */",
"public",
"List",
"<",
"String",
">",
"getErrorOutput",
"(",
")",
"{",
"checkState",
"(",
"finished",
",",
"\"",
"Cannot get error output while process is not yet finished",
"\"",
")",
";",
"return",
"errorOutput",
";",
"}",
"}"
] |
This class can be used to execute a separate process and read its output in a convenient way.
|
[
"This",
"class",
"can",
"be",
"used",
"to",
"execute",
"a",
"separate",
"process",
"and",
"read",
"its",
"output",
"in",
"a",
"convenient",
"way",
"."
] |
[
"// this callable guarantees that when it finishes,",
"// the external process also has finished and it has been wait()ed for",
"// (which is important for ulimit timing measurements on Linux)",
"// no call to handleExitCode() here, we do this only with normal termination",
"// reset interrupted status",
"// ignore, we will call interrupt()",
"// platform charset is what processes usually use for communication",
"// wrap both output handling callables in CancellingCallables so that",
"// exceptions thrown by the handling methods terminate the process immediately",
"// platform charset is what processes usually use for communication",
"// IOExceptions after a killed process are no suprise",
"// Log and ignore so they don't mask the real cause",
"// why we killed the process.",
"// platform charset is what processes usually use for communication",
"// IOExceptions after a killed process are no suprise",
"// Log and ignore so they don't mask the real cause",
"// why we killed the process.",
"// don't accept further tasks",
"// the processFuture has been cancelled, probably because the outFuture or",
"// the errFuture threw an exception",
"// ignore exception here and call get() on the other futures to get their",
"// exceptions",
"// wait for reading tasks to finish and to get exceptions",
"// the processFuture threw a CancellationException,",
"// but the reading futures threw no exception",
"// Shouldn't happen, this probably means that our processFuture",
"// was interrupted from some outsider.",
"// Assume this as an interrupt.",
"// cleanup",
"// needed for memory visibility of the Callables",
"// Not expected to happen because process is already dead anyway.",
"// Don't hide any real exception by throwing this one.",
"// cannot occur with timeout==0"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 22
| 2,821
| 187
|
9b57fe4c154080103d967eb10e0a6e854d000c69
|
wjiec/leetcode-solution
|
leetcode-java/src/daily/d220102p390eliminationgame/Solution.java
|
[
"MIT"
] |
Java
|
Solution
|
/**
* 390. Elimination Game
*
* https://leetcode-cn.com/problems/elimination-game/
*
* You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order.
*
* Apply the following algorithm on arr:
*
* Starting from left to right, remove the first number and every other number
* afterward until you reach the end of the list.
*
* Repeat the previous step again, but this time from right to left,
* remove the rightmost number and every other number from the remaining numbers.
*
* Keep repeating the steps again, alternating left to right and right to left, until a single number remains.
*
* Given the integer n, return the last number that remains in arr.
*/
|
390.
You have a list arr of all integers in the range [1, n] sorted in a strictly increasing order.
Apply the following algorithm on arr.
Starting from left to right, remove the first number and every other number
afterward until you reach the end of the list.
Repeat the previous step again, but this time from right to left,
remove the rightmost number and every other number from the remaining numbers.
Keep repeating the steps again, alternating left to right and right to left, until a single number remains.
Given the integer n, return the last number that remains in arr.
|
[
"390",
".",
"You",
"have",
"a",
"list",
"arr",
"of",
"all",
"integers",
"in",
"the",
"range",
"[",
"1",
"n",
"]",
"sorted",
"in",
"a",
"strictly",
"increasing",
"order",
".",
"Apply",
"the",
"following",
"algorithm",
"on",
"arr",
".",
"Starting",
"from",
"left",
"to",
"right",
"remove",
"the",
"first",
"number",
"and",
"every",
"other",
"number",
"afterward",
"until",
"you",
"reach",
"the",
"end",
"of",
"the",
"list",
".",
"Repeat",
"the",
"previous",
"step",
"again",
"but",
"this",
"time",
"from",
"right",
"to",
"left",
"remove",
"the",
"rightmost",
"number",
"and",
"every",
"other",
"number",
"from",
"the",
"remaining",
"numbers",
".",
"Keep",
"repeating",
"the",
"steps",
"again",
"alternating",
"left",
"to",
"right",
"and",
"right",
"to",
"left",
"until",
"a",
"single",
"number",
"remains",
".",
"Given",
"the",
"integer",
"n",
"return",
"the",
"last",
"number",
"that",
"remains",
"in",
"arr",
"."
] |
public class Solution {
public int lastRemaining(int n) {
int a1 = 1, k = 0, step = 1;
while (n > 1) {
if (k % 2 == 0) {
a1 = a1 + step;
} else {
a1 = (n % 2 == 0) ? a1 : a1 + step;
}
k++;
n >>= 1;
step <<= 1;
}
return a1;
}
public static void main(String[] args) {
assert new Solution().lastRemaining(9) == 6;
assert new Solution().lastRemaining(1) == 1;
}
}
|
[
"public",
"class",
"Solution",
"{",
"public",
"int",
"lastRemaining",
"(",
"int",
"n",
")",
"{",
"int",
"a1",
"=",
"1",
",",
"k",
"=",
"0",
",",
"step",
"=",
"1",
";",
"while",
"(",
"n",
">",
"1",
")",
"{",
"if",
"(",
"k",
"%",
"2",
"==",
"0",
")",
"{",
"a1",
"=",
"a1",
"+",
"step",
";",
"}",
"else",
"{",
"a1",
"=",
"(",
"n",
"%",
"2",
"==",
"0",
")",
"?",
"a1",
":",
"a1",
"+",
"step",
";",
"}",
"k",
"++",
";",
"n",
">>=",
"1",
";",
"step",
"<<=",
"1",
";",
"}",
"return",
"a1",
";",
"}",
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"{",
"assert",
"new",
"Solution",
"(",
")",
".",
"lastRemaining",
"(",
"9",
")",
"==",
"6",
";",
"assert",
"new",
"Solution",
"(",
")",
".",
"lastRemaining",
"(",
"1",
")",
"==",
"1",
";",
"}",
"}"
] |
390.
|
[
"390",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 154
| 157
|
7ec011823839c8d64e51a76fb01d6bbbd9e034f9
|
sravyasri/dislib
|
dislib/decomposition/pca/base.py
|
[
"Apache-2.0"
] |
Python
|
PCA
|
Principal component analysis (PCA) using the covariance method.
Performs a full eigendecomposition of the covariance matrix.
Parameters
----------
n_components : int or None, optional (default=None)
Number of components to keep. If None, all components are kept.
arity : int, optional (default=50)
Arity of the reductions.
Attributes
----------
components_ : array, shape (n_components, n_features)
Principal axes in feature space, representing the directions of maximum
variance in the data. The components are sorted by explained_variance_.
Equal to the n_components eigenvectors of the covariance matrix with
greater eigenvalues.
explained_variance_ : array, shape (n_components,)
The amount of variance explained by each of the selected components.
Equal to the first n_components largest eigenvalues of the covariance
matrix.
mean_ : array, shape (n_features,)
Per-feature empirical mean, estimated from the training set.
Examples
--------
>>> from dislib.decomposition import PCA
>>> import numpy as np
>>> import dislib as ds
>>> x = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
>>> bn, bm = 2, 2
>>> data = ds.array(x=x, block_size=(bn, bm))
>>> pca = PCA()
>>> transformed_data = pca.fit_transform(data)
>>> print(transformed_data)
>>> print(pca.components_)
>>> print(pca.explained_variance_)
|
Principal component analysis (PCA) using the covariance method.
Performs a full eigendecomposition of the covariance matrix.
Parameters
n_components : int or None, optional (default=None)
Number of components to keep. If None, all components are kept.
arity : int, optional (default=50)
Arity of the reductions.
Attributes
components_ : array, shape (n_components, n_features)
Principal axes in feature space, representing the directions of maximum
variance in the data. The components are sorted by explained_variance_.
Equal to the n_components eigenvectors of the covariance matrix with
greater eigenvalues.
explained_variance_ : array, shape (n_components,)
The amount of variance explained by each of the selected components.
Equal to the first n_components largest eigenvalues of the covariance
matrix.
mean_ : array, shape (n_features,)
Per-feature empirical mean, estimated from the training set.
Examples
|
[
"Principal",
"component",
"analysis",
"(",
"PCA",
")",
"using",
"the",
"covariance",
"method",
".",
"Performs",
"a",
"full",
"eigendecomposition",
"of",
"the",
"covariance",
"matrix",
".",
"Parameters",
"n_components",
":",
"int",
"or",
"None",
"optional",
"(",
"default",
"=",
"None",
")",
"Number",
"of",
"components",
"to",
"keep",
".",
"If",
"None",
"all",
"components",
"are",
"kept",
".",
"arity",
":",
"int",
"optional",
"(",
"default",
"=",
"50",
")",
"Arity",
"of",
"the",
"reductions",
".",
"Attributes",
"components_",
":",
"array",
"shape",
"(",
"n_components",
"n_features",
")",
"Principal",
"axes",
"in",
"feature",
"space",
"representing",
"the",
"directions",
"of",
"maximum",
"variance",
"in",
"the",
"data",
".",
"The",
"components",
"are",
"sorted",
"by",
"explained_variance_",
".",
"Equal",
"to",
"the",
"n_components",
"eigenvectors",
"of",
"the",
"covariance",
"matrix",
"with",
"greater",
"eigenvalues",
".",
"explained_variance_",
":",
"array",
"shape",
"(",
"n_components",
")",
"The",
"amount",
"of",
"variance",
"explained",
"by",
"each",
"of",
"the",
"selected",
"components",
".",
"Equal",
"to",
"the",
"first",
"n_components",
"largest",
"eigenvalues",
"of",
"the",
"covariance",
"matrix",
".",
"mean_",
":",
"array",
"shape",
"(",
"n_features",
")",
"Per",
"-",
"feature",
"empirical",
"mean",
"estimated",
"from",
"the",
"training",
"set",
".",
"Examples"
] |
class PCA:
""" Principal component analysis (PCA) using the covariance method.
Performs a full eigendecomposition of the covariance matrix.
Parameters
----------
n_components : int or None, optional (default=None)
Number of components to keep. If None, all components are kept.
arity : int, optional (default=50)
Arity of the reductions.
Attributes
----------
components_ : array, shape (n_components, n_features)
Principal axes in feature space, representing the directions of maximum
variance in the data. The components are sorted by explained_variance_.
Equal to the n_components eigenvectors of the covariance matrix with
greater eigenvalues.
explained_variance_ : array, shape (n_components,)
The amount of variance explained by each of the selected components.
Equal to the first n_components largest eigenvalues of the covariance
matrix.
mean_ : array, shape (n_features,)
Per-feature empirical mean, estimated from the training set.
Examples
--------
>>> from dislib.decomposition import PCA
>>> import numpy as np
>>> import dislib as ds
>>> x = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])
>>> bn, bm = 2, 2
>>> data = ds.array(x=x, block_size=(bn, bm))
>>> pca = PCA()
>>> transformed_data = pca.fit_transform(data)
>>> print(transformed_data)
>>> print(pca.components_)
>>> print(pca.explained_variance_)
"""
def __init__(self, n_components=None, arity=50):
self.n_components = n_components
self.arity = arity
self._components = None
self._variance = None
@property
def components_(self):
self._components = compss_wait_on(self._components)
return self._components
@property
def explained_variance_(self):
self._variance = compss_wait_on(self._variance)
return self._variance
def fit(self, x):
""" Fit the model with the dataset.
Parameters
----------
x : ds-array, shape (n_samples, n_features)
Training data.
Returns
-------
self : PCA
"""
n_samples = x.shape[0]
self.mean_ = _features_mean(x, self.arity, n_samples)
norm_blocks = []
for rows in x._iterator('rows'):
aux_rows = [object() for _ in range(x._n_blocks[1])]
_normalize(rows._blocks, aux_rows, self.mean_)
norm_blocks.append(aux_rows)
# we shallow copy the original to create a normalized darray
norm_x = copy(x)
# shallow copy is enough to avoid modifying original darray x when
# changing the blocks
norm_x._blocks = norm_blocks
scatter_matrix = _scatter_matrix(norm_x, self.arity)
covariance_matrix = _estimate_covariance(scatter_matrix, n_samples)
eig_val, eig_vec = _decompose(covariance_matrix, self.n_components)
self._components = eig_vec
self._variance = eig_val
return self
def fit_transform(self, x):
""" Fit the model with the dataset and apply the dimensionality
reduction to it.
Parameters
----------
x : ds-array, shape (n_samples, n_features)
Training data.
Returns
-------
transformed_darray : ds-array, shape (n_samples, n_components)
"""
return self.fit(x).transform(x)
def transform(self, x):
"""
Apply dimensionality reduction to ds-array.
The given dataset is projected on the first principal components
previously extracted from a training ds-array.
Parameters
----------
x : ds-array, shape (n_samples, n_features)
New ds-array, with the same n_features as the training dataset.
Returns
-------
transformed_darray : ds-array, shape (n_samples, n_components)
"""
return _transform(x, self.mean_, self.components_)
|
[
"class",
"PCA",
":",
"def",
"__init__",
"(",
"self",
",",
"n_components",
"=",
"None",
",",
"arity",
"=",
"50",
")",
":",
"self",
".",
"n_components",
"=",
"n_components",
"self",
".",
"arity",
"=",
"arity",
"self",
".",
"_components",
"=",
"None",
"self",
".",
"_variance",
"=",
"None",
"@",
"property",
"def",
"components_",
"(",
"self",
")",
":",
"self",
".",
"_components",
"=",
"compss_wait_on",
"(",
"self",
".",
"_components",
")",
"return",
"self",
".",
"_components",
"@",
"property",
"def",
"explained_variance_",
"(",
"self",
")",
":",
"self",
".",
"_variance",
"=",
"compss_wait_on",
"(",
"self",
".",
"_variance",
")",
"return",
"self",
".",
"_variance",
"def",
"fit",
"(",
"self",
",",
"x",
")",
":",
"\"\"\" Fit the model with the dataset.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n Training data.\n\n Returns\n -------\n self : PCA\n \"\"\"",
"n_samples",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"mean_",
"=",
"_features_mean",
"(",
"x",
",",
"self",
".",
"arity",
",",
"n_samples",
")",
"norm_blocks",
"=",
"[",
"]",
"for",
"rows",
"in",
"x",
".",
"_iterator",
"(",
"'rows'",
")",
":",
"aux_rows",
"=",
"[",
"object",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"x",
".",
"_n_blocks",
"[",
"1",
"]",
")",
"]",
"_normalize",
"(",
"rows",
".",
"_blocks",
",",
"aux_rows",
",",
"self",
".",
"mean_",
")",
"norm_blocks",
".",
"append",
"(",
"aux_rows",
")",
"norm_x",
"=",
"copy",
"(",
"x",
")",
"norm_x",
".",
"_blocks",
"=",
"norm_blocks",
"scatter_matrix",
"=",
"_scatter_matrix",
"(",
"norm_x",
",",
"self",
".",
"arity",
")",
"covariance_matrix",
"=",
"_estimate_covariance",
"(",
"scatter_matrix",
",",
"n_samples",
")",
"eig_val",
",",
"eig_vec",
"=",
"_decompose",
"(",
"covariance_matrix",
",",
"self",
".",
"n_components",
")",
"self",
".",
"_components",
"=",
"eig_vec",
"self",
".",
"_variance",
"=",
"eig_val",
"return",
"self",
"def",
"fit_transform",
"(",
"self",
",",
"x",
")",
":",
"\"\"\" Fit the model with the dataset and apply the dimensionality\n reduction to it.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n Training data.\n\n Returns\n -------\n transformed_darray : ds-array, shape (n_samples, n_components)\n \"\"\"",
"return",
"self",
".",
"fit",
"(",
"x",
")",
".",
"transform",
"(",
"x",
")",
"def",
"transform",
"(",
"self",
",",
"x",
")",
":",
"\"\"\"\n Apply dimensionality reduction to ds-array.\n\n The given dataset is projected on the first principal components\n previously extracted from a training ds-array.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n New ds-array, with the same n_features as the training dataset.\n\n Returns\n -------\n transformed_darray : ds-array, shape (n_samples, n_components)\n \"\"\"",
"return",
"_transform",
"(",
"x",
",",
"self",
".",
"mean_",
",",
"self",
".",
"components_",
")"
] |
Principal component analysis (PCA) using the covariance method.
|
[
"Principal",
"component",
"analysis",
"(",
"PCA",
")",
"using",
"the",
"covariance",
"method",
"."
] |
[
"\"\"\" Principal component analysis (PCA) using the covariance method.\n\n Performs a full eigendecomposition of the covariance matrix.\n\n Parameters\n ----------\n n_components : int or None, optional (default=None)\n Number of components to keep. If None, all components are kept.\n arity : int, optional (default=50)\n Arity of the reductions.\n\n Attributes\n ----------\n components_ : array, shape (n_components, n_features)\n Principal axes in feature space, representing the directions of maximum\n variance in the data. The components are sorted by explained_variance_.\n\n Equal to the n_components eigenvectors of the covariance matrix with\n greater eigenvalues.\n explained_variance_ : array, shape (n_components,)\n The amount of variance explained by each of the selected components.\n\n Equal to the first n_components largest eigenvalues of the covariance\n matrix.\n mean_ : array, shape (n_features,)\n Per-feature empirical mean, estimated from the training set.\n\n Examples\n --------\n >>> from dislib.decomposition import PCA\n >>> import numpy as np\n >>> import dislib as ds\n >>> x = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])\n >>> bn, bm = 2, 2\n >>> data = ds.array(x=x, block_size=(bn, bm))\n >>> pca = PCA()\n >>> transformed_data = pca.fit_transform(data)\n >>> print(transformed_data)\n >>> print(pca.components_)\n >>> print(pca.explained_variance_)\n \"\"\"",
"\"\"\" Fit the model with the dataset.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n Training data.\n\n Returns\n -------\n self : PCA\n \"\"\"",
"# we shallow copy the original to create a normalized darray",
"# shallow copy is enough to avoid modifying original darray x when",
"# changing the blocks",
"\"\"\" Fit the model with the dataset and apply the dimensionality\n reduction to it.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n Training data.\n\n Returns\n -------\n transformed_darray : ds-array, shape (n_samples, n_components)\n \"\"\"",
"\"\"\"\n Apply dimensionality reduction to ds-array.\n\n The given dataset is projected on the first principal components\n previously extracted from a training ds-array.\n\n Parameters\n ----------\n x : ds-array, shape (n_samples, n_features)\n New ds-array, with the same n_features as the training dataset.\n\n Returns\n -------\n transformed_darray : ds-array, shape (n_samples, n_components)\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 903
| 349
|
df162f74d3e18746771a7259a37bb1a5bc10c7c5
|
DarwinSPL/DarwinSPL
|
plugins/eu.hyvar.context.contextValidity.resource.hyvalidityformula/src-gen/eu/hyvar/context/contextValidity/resource/hyvalidityformula/util/HyvalidityformulaTextResourceUtil.java
|
[
"Apache-2.0"
] |
Java
|
HyvalidityformulaTextResourceUtil
|
/**
* Class HyvalidityformulaTextResourceUtil can be used to perform common tasks on
* text resources, such as loading and saving resources, as well as, checking them
* for errors. This class is deprecated and has been replaced by
* eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
* laResourceUtil.
*/
|
Class HyvalidityformulaTextResourceUtil can be used to perform common tasks on
text resources, such as loading and saving resources, as well as, checking them
for errors. This class is deprecated and has been replaced by
eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
laResourceUtil.
|
[
"Class",
"HyvalidityformulaTextResourceUtil",
"can",
"be",
"used",
"to",
"perform",
"common",
"tasks",
"on",
"text",
"resources",
"such",
"as",
"loading",
"and",
"saving",
"resources",
"as",
"well",
"as",
"checking",
"them",
"for",
"errors",
".",
"This",
"class",
"is",
"deprecated",
"and",
"has",
"been",
"replaced",
"by",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"util",
".",
"Hyvalidityformu",
"laResourceUtil",
"."
] |
public class HyvalidityformulaTextResourceUtil {
/**
* Use
* eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
* laResourceUtil.getResource() instead.
*/
@Deprecated
public static eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource getResource(IFile file) {
return new eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.HyvalidityformulaEclipseProxy().getResource(file);
}
/**
* Use
* eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
* laResourceUtil.getResource() instead.
*/
@Deprecated
public static eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource getResource(File file, Map<?,?> options) {
return eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.HyvalidityformulaResourceUtil.getResource(file, options);
}
/**
* Use
* eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
* laResourceUtil.getResource() instead.
*/
@Deprecated
public static eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource getResource(URI uri) {
return eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.HyvalidityformulaResourceUtil.getResource(uri);
}
/**
* Use
* eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu
* laResourceUtil.getResource() instead.
*/
@Deprecated
public static eu.hyvar.context.contextValidity.resource.hyvalidityformula.mopp.HyvalidityformulaResource getResource(URI uri, Map<?,?> options) {
return eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.HyvalidityformulaResourceUtil.getResource(uri, options);
}
}
|
[
"public",
"class",
"HyvalidityformulaTextResourceUtil",
"{",
"/**\n\t * Use\n\t * eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu\n\t * laResourceUtil.getResource() instead.\n\t */",
"@",
"Deprecated",
"public",
"static",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"mopp",
".",
"HyvalidityformulaResource",
"getResource",
"(",
"IFile",
"file",
")",
"{",
"return",
"new",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"util",
".",
"HyvalidityformulaEclipseProxy",
"(",
")",
".",
"getResource",
"(",
"file",
")",
";",
"}",
"/**\n\t * Use\n\t * eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu\n\t * laResourceUtil.getResource() instead.\n\t */",
"@",
"Deprecated",
"public",
"static",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"mopp",
".",
"HyvalidityformulaResource",
"getResource",
"(",
"File",
"file",
",",
"Map",
"<",
"?",
",",
"?",
">",
"options",
")",
"{",
"return",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"util",
".",
"HyvalidityformulaResourceUtil",
".",
"getResource",
"(",
"file",
",",
"options",
")",
";",
"}",
"/**\n\t * Use\n\t * eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu\n\t * laResourceUtil.getResource() instead.\n\t */",
"@",
"Deprecated",
"public",
"static",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"mopp",
".",
"HyvalidityformulaResource",
"getResource",
"(",
"URI",
"uri",
")",
"{",
"return",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"util",
".",
"HyvalidityformulaResourceUtil",
".",
"getResource",
"(",
"uri",
")",
";",
"}",
"/**\n\t * Use\n\t * eu.hyvar.context.contextValidity.resource.hyvalidityformula.util.Hyvalidityformu\n\t * laResourceUtil.getResource() instead.\n\t */",
"@",
"Deprecated",
"public",
"static",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"mopp",
".",
"HyvalidityformulaResource",
"getResource",
"(",
"URI",
"uri",
",",
"Map",
"<",
"?",
",",
"?",
">",
"options",
")",
"{",
"return",
"eu",
".",
"hyvar",
".",
"context",
".",
"contextValidity",
".",
"resource",
".",
"hyvalidityformula",
".",
"util",
".",
"HyvalidityformulaResourceUtil",
".",
"getResource",
"(",
"uri",
",",
"options",
")",
";",
"}",
"}"
] |
Class HyvalidityformulaTextResourceUtil can be used to perform common tasks on
text resources, such as loading and saving resources, as well as, checking them
for errors.
|
[
"Class",
"HyvalidityformulaTextResourceUtil",
"can",
"be",
"used",
"to",
"perform",
"common",
"tasks",
"on",
"text",
"resources",
"such",
"as",
"loading",
"and",
"saving",
"resources",
"as",
"well",
"as",
"checking",
"them",
"for",
"errors",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 412
| 77
|
0a7e9c553d8b2822012071a186b9246ad35531f0
|
bmenees/Analyzers
|
src/Menees.Analyzers/Resources.Designer.cs
|
[
"MIT"
] |
C#
|
Resources
|
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
|
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Menees.Analyzers.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string Men001Description {
get {
return ResourceManager.GetString("Men001Description", resourceCulture);
}
}
internal static string Men001MessageFormat {
get {
return ResourceManager.GetString("Men001MessageFormat", resourceCulture);
}
}
internal static string Men001Title {
get {
return ResourceManager.GetString("Men001Title", resourceCulture);
}
}
internal static string Men002Description {
get {
return ResourceManager.GetString("Men002Description", resourceCulture);
}
}
internal static string Men002MessageFormat {
get {
return ResourceManager.GetString("Men002MessageFormat", resourceCulture);
}
}
internal static string Men002MessageFormatNotify {
get {
return ResourceManager.GetString("Men002MessageFormatNotify", resourceCulture);
}
}
internal static string Men002Title {
get {
return ResourceManager.GetString("Men002Title", resourceCulture);
}
}
internal static string Men002TitleNotify {
get {
return ResourceManager.GetString("Men002TitleNotify", resourceCulture);
}
}
internal static string Men003Description {
get {
return ResourceManager.GetString("Men003Description", resourceCulture);
}
}
internal static string Men003MessageFormat {
get {
return ResourceManager.GetString("Men003MessageFormat", resourceCulture);
}
}
internal static string Men003Title {
get {
return ResourceManager.GetString("Men003Title", resourceCulture);
}
}
internal static string Men004Description {
get {
return ResourceManager.GetString("Men004Description", resourceCulture);
}
}
internal static string Men004MessageFormat {
get {
return ResourceManager.GetString("Men004MessageFormat", resourceCulture);
}
}
internal static string Men004Title {
get {
return ResourceManager.GetString("Men004Title", resourceCulture);
}
}
internal static string Men005Description {
get {
return ResourceManager.GetString("Men005Description", resourceCulture);
}
}
internal static string Men005MessageFormat {
get {
return ResourceManager.GetString("Men005MessageFormat", resourceCulture);
}
}
internal static string Men005Title {
get {
return ResourceManager.GetString("Men005Title", resourceCulture);
}
}
internal static string Men006Description {
get {
return ResourceManager.GetString("Men006Description", resourceCulture);
}
}
internal static string Men006MessageFormat {
get {
return ResourceManager.GetString("Men006MessageFormat", resourceCulture);
}
}
internal static string Men006Title {
get {
return ResourceManager.GetString("Men006Title", resourceCulture);
}
}
internal static string Men007Description {
get {
return ResourceManager.GetString("Men007Description", resourceCulture);
}
}
internal static string Men007MessageFormat {
get {
return ResourceManager.GetString("Men007MessageFormat", resourceCulture);
}
}
internal static string Men007MessageFormatVoid {
get {
return ResourceManager.GetString("Men007MessageFormatVoid", resourceCulture);
}
}
internal static string Men007Title {
get {
return ResourceManager.GetString("Men007Title", resourceCulture);
}
}
internal static string Men008Description {
get {
return ResourceManager.GetString("Men008Description", resourceCulture);
}
}
internal static string Men008MessageFormat {
get {
return ResourceManager.GetString("Men008MessageFormat", resourceCulture);
}
}
internal static string Men008Title {
get {
return ResourceManager.GetString("Men008Title", resourceCulture);
}
}
internal static string Men009Description {
get {
return ResourceManager.GetString("Men009Description", resourceCulture);
}
}
internal static string Men009MessageFormat {
get {
return ResourceManager.GetString("Men009MessageFormat", resourceCulture);
}
}
internal static string Men009Title {
get {
return ResourceManager.GetString("Men009Title", resourceCulture);
}
}
internal static string Men010Description {
get {
return ResourceManager.GetString("Men010Description", resourceCulture);
}
}
internal static string Men010MessageFormat {
get {
return ResourceManager.GetString("Men010MessageFormat", resourceCulture);
}
}
internal static string Men010Title {
get {
return ResourceManager.GetString("Men010Title", resourceCulture);
}
}
internal static string Men011Description {
get {
return ResourceManager.GetString("Men011Description", resourceCulture);
}
}
internal static string Men011MessageFormat {
get {
return ResourceManager.GetString("Men011MessageFormat", resourceCulture);
}
}
internal static string Men011Title {
get {
return ResourceManager.GetString("Men011Title", resourceCulture);
}
}
internal static string Men012Description {
get {
return ResourceManager.GetString("Men012Description", resourceCulture);
}
}
internal static string Men012MessageFormat {
get {
return ResourceManager.GetString("Men012MessageFormat", resourceCulture);
}
}
internal static string Men012MessageFormatNoValue {
get {
return ResourceManager.GetString("Men012MessageFormatNoValue", resourceCulture);
}
}
internal static string Men012Title {
get {
return ResourceManager.GetString("Men012Title", resourceCulture);
}
}
internal static string Men013Description {
get {
return ResourceManager.GetString("Men013Description", resourceCulture);
}
}
internal static string Men013MessageFormat {
get {
return ResourceManager.GetString("Men013MessageFormat", resourceCulture);
}
}
internal static string Men013Title {
get {
return ResourceManager.GetString("Men013Title", resourceCulture);
}
}
internal static string Men014Description {
get {
return ResourceManager.GetString("Men014Description", resourceCulture);
}
}
internal static string Men014MessageFormat {
get {
return ResourceManager.GetString("Men014MessageFormat", resourceCulture);
}
}
internal static string Men014Title {
get {
return ResourceManager.GetString("Men014Title", resourceCulture);
}
}
internal static string Men015Description {
get {
return ResourceManager.GetString("Men015Description", resourceCulture);
}
}
internal static string Men015MessageFormat {
get {
return ResourceManager.GetString("Men015MessageFormat", resourceCulture);
}
}
internal static string Men015Title {
get {
return ResourceManager.GetString("Men015Title", resourceCulture);
}
}
}
|
[
"[",
"global",
"::",
"System",
".",
"CodeDom",
".",
"Compiler",
".",
"GeneratedCodeAttribute",
"(",
"\"",
"System.Resources.Tools.StronglyTypedResourceBuilder",
"\"",
",",
"\"",
"17.0.0.0",
"\"",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"DebuggerNonUserCodeAttribute",
"(",
")",
"]",
"[",
"global",
"::",
"System",
".",
"Runtime",
".",
"CompilerServices",
".",
"CompilerGeneratedAttribute",
"(",
")",
"]",
"internal",
"class",
"Resources",
"{",
"private",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"resourceMan",
";",
"private",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"resourceCulture",
";",
"[",
"global",
"::",
"System",
".",
"Diagnostics",
".",
"CodeAnalysis",
".",
"SuppressMessageAttribute",
"(",
"\"",
"Microsoft.Performance",
"\"",
",",
"\"",
"CA1811:AvoidUncalledPrivateCode",
"\"",
")",
"]",
"internal",
"Resources",
"(",
")",
"{",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"ResourceManager",
"{",
"get",
"{",
"if",
"(",
"object",
".",
"ReferenceEquals",
"(",
"resourceMan",
",",
"null",
")",
")",
"{",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"temp",
"=",
"new",
"global",
"::",
"System",
".",
"Resources",
".",
"ResourceManager",
"(",
"\"",
"Menees.Analyzers.Resources",
"\"",
",",
"typeof",
"(",
"Resources",
")",
".",
"Assembly",
")",
";",
"resourceMan",
"=",
"temp",
";",
"}",
"return",
"resourceMan",
";",
"}",
"}",
"[",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableAttribute",
"(",
"global",
"::",
"System",
".",
"ComponentModel",
".",
"EditorBrowsableState",
".",
"Advanced",
")",
"]",
"internal",
"static",
"global",
"::",
"System",
".",
"Globalization",
".",
"CultureInfo",
"Culture",
"{",
"get",
"{",
"return",
"resourceCulture",
";",
"}",
"set",
"{",
"resourceCulture",
"=",
"value",
";",
"}",
"}",
"internal",
"static",
"string",
"Men001Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men001Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men001MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men001MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men001Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men001Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men002Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men002Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men002MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men002MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men002MessageFormatNotify",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men002MessageFormatNotify",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men002Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men002Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men002TitleNotify",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men002TitleNotify",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men003Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men003Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men003MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men003MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men003Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men003Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men004Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men004Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men004MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men004MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men004Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men004Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men005Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men005Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men005MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men005MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men005Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men005Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men006Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men006Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men006MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men006MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men006Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men006Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men007Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men007Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men007MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men007MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men007MessageFormatVoid",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men007MessageFormatVoid",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men007Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men007Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men008Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men008Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men008MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men008MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men008Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men008Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men009Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men009Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men009MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men009MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men009Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men009Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men010Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men010Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men010MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men010MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men010Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men010Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men011Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men011Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men011MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men011MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men011Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men011Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men012Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men012Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men012MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men012MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men012MessageFormatNoValue",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men012MessageFormatNoValue",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men012Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men012Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men013Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men013Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men013MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men013MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men013Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men013Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men014Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men014Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men014MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men014MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men014Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men014Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men015Description",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men015Description",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men015MessageFormat",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men015MessageFormat",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"internal",
"static",
"string",
"Men015Title",
"{",
"get",
"{",
"return",
"ResourceManager",
".",
"GetString",
"(",
"\"",
"Men015Title",
"\"",
",",
"resourceCulture",
")",
";",
"}",
"}",
"}"
] |
A strongly-typed resource class, for looking up localized strings, etc.
|
[
"A",
"strongly",
"-",
"typed",
"resource",
"class",
"for",
"looking",
"up",
"localized",
"strings",
"etc",
"."
] |
[
"/// <summary>",
"/// Returns the cached ResourceManager instance used by this class.",
"/// </summary>",
"/// <summary>",
"/// Overrides the current thread's CurrentUICulture property for all",
"/// resource lookups using this strongly typed resource class.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The code contains space characters used for indentation..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Tabs should be used for indentation..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Tabs should be used for indentation.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Lines should be a readable, maintainable length..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Line must be no longer than {0} characters (now {1})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Line is over {0} characters (now {1})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Line is too long.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Line is long.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Methods should be a readable, maintainable length..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to {0} must be no longer than {1} lines (now {2})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Method is too long.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Property accessors should be a readable, maintainable length..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to {0} must be no longer than {1} lines (now {2})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Property accessor is too long.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Files should be a readable, maintainable length..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to File {0} must be no longer than {1} lines (now {2})..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to File is too long.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to #regions should be used to group related items in large code files..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to #regions should be used{0}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to #regions should be used.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Using a single return keeps control flow simple and makes refactoring easier..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Multiple return statements ({0}) are used in {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to A return statement is used in {0}, which returns void..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use a single return.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to A file's name should match or include the name of the main type it contains..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to File name {0} {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to File name should match type.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Using preferred exception types makes calling code more consistent and maintainable..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use {0} instead of {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use the preferred exception type.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Using named constants instead of numeric literals in expressions improves readability and maintainability..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The numeric literal {0} should be replaced with a named constant..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Avoid magic numbers.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Using directives should be indented consistently based on their nesting level inside a namespace..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to The using directive should be indented consistent with its nesting level..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Align using directives.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Flags enum members should be powers of two or bitwise-or combinations of named members..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Flags enum member {0}.{1} has value {2}, which is not a {3}power of two..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Flags enum member {0}.{1} should explicitly assign its value to zero or a power of two..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Flags should be powers of two.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to UTC times are safer because they're unambiguous and always increasing..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use {0} instead of {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use UTC time.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to TryGetValue does a single key lookup, which is more efficient than doing a ContainsKey lookup and a this[key] lookup..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use {0} instead of {1} and {2}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Prefer TryGetValue.",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Preferred terms and casing should be used in identifiers..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use {0} instead of {1}..",
"/// </summary>",
"/// <summary>",
"/// Looks up a localized string similar to Use preferred terms.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,829
| 84
|
8a7303ef3df76cb39a3e975cd376813f24475d5d
|
project-tetsuo/project-tetstuo
|
p2p/node_modules/libp2p/src/transport-manager.js
|
[
"MIT"
] |
JavaScript
|
TransportManager
|
/**
* @typedef {import('multiaddr').Multiaddr} Multiaddr
* @typedef {import('libp2p-interfaces/src/connection').Connection} Connection
* @typedef {import('libp2p-interfaces/src/transport/types').TransportFactory<any, any>} TransportFactory
* @typedef {import('libp2p-interfaces/src/transport/types').Transport<any, any>} Transport
*
* @typedef {Object} TransportManagerProperties
* @property {import('./')} libp2p
* @property {import('./upgrader')} upgrader
*
* @typedef {Object} TransportManagerOptions
* @property {number} [faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance.
*/
|
@typedef {Object} TransportManagerProperties
@property {import('./')} libp2p
@property {import('./upgrader')} upgrader
@typedef {Object} TransportManagerOptions
@property {number} [faultTolerance = FAULT_TOLERANCE.FATAL_ALL] - Address listen error tolerance.
|
[
"@typedef",
"{",
"Object",
"}",
"TransportManagerProperties",
"@property",
"{",
"import",
"(",
"'",
".",
"/",
"'",
")",
"}",
"libp2p",
"@property",
"{",
"import",
"(",
"'",
".",
"/",
"upgrader",
"'",
")",
"}",
"upgrader",
"@typedef",
"{",
"Object",
"}",
"TransportManagerOptions",
"@property",
"{",
"number",
"}",
"[",
"faultTolerance",
"=",
"FAULT_TOLERANCE",
".",
"FATAL_ALL",
"]",
"-",
"Address",
"listen",
"error",
"tolerance",
"."
] |
class TransportManager {
/**
* @class
* @param {TransportManagerProperties & TransportManagerOptions} options
*/
constructor ({ libp2p, upgrader, faultTolerance = FAULT_TOLERANCE.FATAL_ALL }) {
this.libp2p = libp2p
this.upgrader = upgrader
/** @type {Map<string, Transport>} */
this._transports = new Map()
this._listeners = new Map()
this._listenerOptions = new Map()
this.faultTolerance = faultTolerance
}
/**
* Adds a `Transport` to the manager
*
* @param {string} key
* @param {TransportFactory} Transport
* @param {*} transportOptions - Additional options to pass to the transport
* @returns {void}
*/
add (key, Transport, transportOptions = {}) {
log('adding %s', key)
if (!key) {
throw errCode(new Error(`Transport must have a valid key, was given '${key}'`), codes.ERR_INVALID_KEY)
}
if (this._transports.has(key)) {
throw errCode(new Error('There is already a transport with this key'), codes.ERR_DUPLICATE_TRANSPORT)
}
const transport = new Transport({
...transportOptions,
libp2p: this.libp2p,
upgrader: this.upgrader
})
this._transports.set(key, transport)
this._listenerOptions.set(key, transportOptions.listenerOptions || {})
if (!this._listeners.has(key)) {
this._listeners.set(key, [])
}
}
/**
* Stops all listeners
*
* @async
*/
async close () {
const tasks = []
for (const [key, listeners] of this._listeners) {
log('closing listeners for %s', key)
while (listeners.length) {
const listener = listeners.pop()
listener.removeAllListeners('listening')
listener.removeAllListeners('close')
tasks.push(listener.close())
}
}
await Promise.all(tasks)
log('all listeners closed')
for (const key of this._listeners.keys()) {
this._listeners.set(key, [])
}
}
/**
* Dials the given Multiaddr over it's supported transport
*
* @param {Multiaddr} ma
* @param {*} options
* @returns {Promise<Connection>}
*/
async dial (ma, options) {
const transport = this.transportForMultiaddr(ma)
if (!transport) {
throw errCode(new Error(`No transport available for address ${String(ma)}`), codes.ERR_TRANSPORT_UNAVAILABLE)
}
try {
return await transport.dial(ma, options)
} catch (/** @type {any} */ err) {
if (!err.code) err.code = codes.ERR_TRANSPORT_DIAL_FAILED
throw err
}
}
/**
* Returns all Multiaddr's the listeners are using
*
* @returns {Multiaddr[]}
*/
getAddrs () {
/** @type {Multiaddr[]} */
let addrs = []
for (const listeners of this._listeners.values()) {
for (const listener of listeners) {
addrs = [...addrs, ...listener.getAddrs()]
}
}
return addrs
}
/**
* Returns all the transports instances.
*
* @returns {IterableIterator<Transport>}
*/
getTransports () {
return this._transports.values()
}
/**
* Finds a transport that matches the given Multiaddr
*
* @param {Multiaddr} ma
* @returns {Transport|null}
*/
transportForMultiaddr (ma) {
for (const transport of this._transports.values()) {
const addrs = transport.filter([ma])
if (addrs.length) return transport
}
return null
}
/**
* Starts listeners for each listen Multiaddr.
*
* @async
* @param {Multiaddr[]} addrs - addresses to attempt to listen on
*/
async listen (addrs) {
if (!addrs || addrs.length === 0) {
log('no addresses were provided for listening, this node is dial only')
return
}
const couldNotListen = []
for (const [key, transport] of this._transports.entries()) {
const supportedAddrs = transport.filter(addrs)
const tasks = []
// For each supported multiaddr, create a listener
for (const addr of supportedAddrs) {
log('creating listener for %s on %s', key, addr)
const listener = transport.createListener(this._listenerOptions.get(key))
this._listeners.get(key).push(listener)
// Track listen/close events
listener.on('listening', () => updateSelfPeerRecord(this.libp2p))
listener.on('close', () => updateSelfPeerRecord(this.libp2p))
// We need to attempt to listen on everything
tasks.push(listener.listen(addr))
}
// Keep track of transports we had no addresses for
if (tasks.length === 0) {
couldNotListen.push(key)
continue
}
const results = await pSettle(tasks)
// If we are listening on at least 1 address, succeed.
// TODO: we should look at adding a retry (`p-retry`) here to better support
// listening on remote addresses as they may be offline. We could then potentially
// just wait for any (`p-any`) listener to succeed on each transport before returning
const isListening = results.find(r => r.isFulfilled === true)
if (!isListening && this.faultTolerance !== FAULT_TOLERANCE.NO_FATAL) {
throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES)
}
}
// If no transports were able to listen, throw an error. This likely
// means we were given addresses we do not have transports for
if (couldNotListen.length === this._transports.size) {
const message = `no valid addresses were provided for transports [${couldNotListen}]`
if (this.faultTolerance === FAULT_TOLERANCE.FATAL_ALL) {
throw errCode(new Error(message), codes.ERR_NO_VALID_ADDRESSES)
}
log(`libp2p in dial mode only: ${message}`)
}
}
/**
* Removes the given transport from the manager.
* If a transport has any running listeners, they will be closed.
*
* @async
* @param {string} key
*/
async remove (key) {
log('removing %s', key)
if (this._listeners.has(key)) {
// Close any running listeners
for (const listener of this._listeners.get(key)) {
listener.removeAllListeners('listening')
listener.removeAllListeners('close')
await listener.close()
}
}
this._transports.delete(key)
this._listeners.delete(key)
}
/**
* Removes all transports from the manager.
* If any listeners are running, they will be closed.
*
* @async
*/
async removeAll () {
const tasks = []
for (const key of this._transports.keys()) {
tasks.push(this.remove(key))
}
await Promise.all(tasks)
}
}
|
[
"class",
"TransportManager",
"{",
"constructor",
"(",
"{",
"libp2p",
",",
"upgrader",
",",
"faultTolerance",
"=",
"FAULT_TOLERANCE",
".",
"FATAL_ALL",
"}",
")",
"{",
"this",
".",
"libp2p",
"=",
"libp2p",
"this",
".",
"upgrader",
"=",
"upgrader",
"this",
".",
"_transports",
"=",
"new",
"Map",
"(",
")",
"this",
".",
"_listeners",
"=",
"new",
"Map",
"(",
")",
"this",
".",
"_listenerOptions",
"=",
"new",
"Map",
"(",
")",
"this",
".",
"faultTolerance",
"=",
"faultTolerance",
"}",
"add",
"(",
"key",
",",
"Transport",
",",
"transportOptions",
"=",
"{",
"}",
")",
"{",
"log",
"(",
"'adding %s'",
",",
"key",
")",
"if",
"(",
"!",
"key",
")",
"{",
"throw",
"errCode",
"(",
"new",
"Error",
"(",
"`",
"${",
"key",
"}",
"`",
")",
",",
"codes",
".",
"ERR_INVALID_KEY",
")",
"}",
"if",
"(",
"this",
".",
"_transports",
".",
"has",
"(",
"key",
")",
")",
"{",
"throw",
"errCode",
"(",
"new",
"Error",
"(",
"'There is already a transport with this key'",
")",
",",
"codes",
".",
"ERR_DUPLICATE_TRANSPORT",
")",
"}",
"const",
"transport",
"=",
"new",
"Transport",
"(",
"{",
"...",
"transportOptions",
",",
"libp2p",
":",
"this",
".",
"libp2p",
",",
"upgrader",
":",
"this",
".",
"upgrader",
"}",
")",
"this",
".",
"_transports",
".",
"set",
"(",
"key",
",",
"transport",
")",
"this",
".",
"_listenerOptions",
".",
"set",
"(",
"key",
",",
"transportOptions",
".",
"listenerOptions",
"||",
"{",
"}",
")",
"if",
"(",
"!",
"this",
".",
"_listeners",
".",
"has",
"(",
"key",
")",
")",
"{",
"this",
".",
"_listeners",
".",
"set",
"(",
"key",
",",
"[",
"]",
")",
"}",
"}",
"async",
"close",
"(",
")",
"{",
"const",
"tasks",
"=",
"[",
"]",
"for",
"(",
"const",
"[",
"key",
",",
"listeners",
"]",
"of",
"this",
".",
"_listeners",
")",
"{",
"log",
"(",
"'closing listeners for %s'",
",",
"key",
")",
"while",
"(",
"listeners",
".",
"length",
")",
"{",
"const",
"listener",
"=",
"listeners",
".",
"pop",
"(",
")",
"listener",
".",
"removeAllListeners",
"(",
"'listening'",
")",
"listener",
".",
"removeAllListeners",
"(",
"'close'",
")",
"tasks",
".",
"push",
"(",
"listener",
".",
"close",
"(",
")",
")",
"}",
"}",
"await",
"Promise",
".",
"all",
"(",
"tasks",
")",
"log",
"(",
"'all listeners closed'",
")",
"for",
"(",
"const",
"key",
"of",
"this",
".",
"_listeners",
".",
"keys",
"(",
")",
")",
"{",
"this",
".",
"_listeners",
".",
"set",
"(",
"key",
",",
"[",
"]",
")",
"}",
"}",
"async",
"dial",
"(",
"ma",
",",
"options",
")",
"{",
"const",
"transport",
"=",
"this",
".",
"transportForMultiaddr",
"(",
"ma",
")",
"if",
"(",
"!",
"transport",
")",
"{",
"throw",
"errCode",
"(",
"new",
"Error",
"(",
"`",
"${",
"String",
"(",
"ma",
")",
"}",
"`",
")",
",",
"codes",
".",
"ERR_TRANSPORT_UNAVAILABLE",
")",
"}",
"try",
"{",
"return",
"await",
"transport",
".",
"dial",
"(",
"ma",
",",
"options",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"!",
"err",
".",
"code",
")",
"err",
".",
"code",
"=",
"codes",
".",
"ERR_TRANSPORT_DIAL_FAILED",
"throw",
"err",
"}",
"}",
"getAddrs",
"(",
")",
"{",
"let",
"addrs",
"=",
"[",
"]",
"for",
"(",
"const",
"listeners",
"of",
"this",
".",
"_listeners",
".",
"values",
"(",
")",
")",
"{",
"for",
"(",
"const",
"listener",
"of",
"listeners",
")",
"{",
"addrs",
"=",
"[",
"...",
"addrs",
",",
"...",
"listener",
".",
"getAddrs",
"(",
")",
"]",
"}",
"}",
"return",
"addrs",
"}",
"getTransports",
"(",
")",
"{",
"return",
"this",
".",
"_transports",
".",
"values",
"(",
")",
"}",
"transportForMultiaddr",
"(",
"ma",
")",
"{",
"for",
"(",
"const",
"transport",
"of",
"this",
".",
"_transports",
".",
"values",
"(",
")",
")",
"{",
"const",
"addrs",
"=",
"transport",
".",
"filter",
"(",
"[",
"ma",
"]",
")",
"if",
"(",
"addrs",
".",
"length",
")",
"return",
"transport",
"}",
"return",
"null",
"}",
"async",
"listen",
"(",
"addrs",
")",
"{",
"if",
"(",
"!",
"addrs",
"||",
"addrs",
".",
"length",
"===",
"0",
")",
"{",
"log",
"(",
"'no addresses were provided for listening, this node is dial only'",
")",
"return",
"}",
"const",
"couldNotListen",
"=",
"[",
"]",
"for",
"(",
"const",
"[",
"key",
",",
"transport",
"]",
"of",
"this",
".",
"_transports",
".",
"entries",
"(",
")",
")",
"{",
"const",
"supportedAddrs",
"=",
"transport",
".",
"filter",
"(",
"addrs",
")",
"const",
"tasks",
"=",
"[",
"]",
"for",
"(",
"const",
"addr",
"of",
"supportedAddrs",
")",
"{",
"log",
"(",
"'creating listener for %s on %s'",
",",
"key",
",",
"addr",
")",
"const",
"listener",
"=",
"transport",
".",
"createListener",
"(",
"this",
".",
"_listenerOptions",
".",
"get",
"(",
"key",
")",
")",
"this",
".",
"_listeners",
".",
"get",
"(",
"key",
")",
".",
"push",
"(",
"listener",
")",
"listener",
".",
"on",
"(",
"'listening'",
",",
"(",
")",
"=>",
"updateSelfPeerRecord",
"(",
"this",
".",
"libp2p",
")",
")",
"listener",
".",
"on",
"(",
"'close'",
",",
"(",
")",
"=>",
"updateSelfPeerRecord",
"(",
"this",
".",
"libp2p",
")",
")",
"tasks",
".",
"push",
"(",
"listener",
".",
"listen",
"(",
"addr",
")",
")",
"}",
"if",
"(",
"tasks",
".",
"length",
"===",
"0",
")",
"{",
"couldNotListen",
".",
"push",
"(",
"key",
")",
"continue",
"}",
"const",
"results",
"=",
"await",
"pSettle",
"(",
"tasks",
")",
"const",
"isListening",
"=",
"results",
".",
"find",
"(",
"r",
"=>",
"r",
".",
"isFulfilled",
"===",
"true",
")",
"if",
"(",
"!",
"isListening",
"&&",
"this",
".",
"faultTolerance",
"!==",
"FAULT_TOLERANCE",
".",
"NO_FATAL",
")",
"{",
"throw",
"errCode",
"(",
"new",
"Error",
"(",
"`",
"${",
"key",
"}",
"`",
")",
",",
"codes",
".",
"ERR_NO_VALID_ADDRESSES",
")",
"}",
"}",
"if",
"(",
"couldNotListen",
".",
"length",
"===",
"this",
".",
"_transports",
".",
"size",
")",
"{",
"const",
"message",
"=",
"`",
"${",
"couldNotListen",
"}",
"`",
"if",
"(",
"this",
".",
"faultTolerance",
"===",
"FAULT_TOLERANCE",
".",
"FATAL_ALL",
")",
"{",
"throw",
"errCode",
"(",
"new",
"Error",
"(",
"message",
")",
",",
"codes",
".",
"ERR_NO_VALID_ADDRESSES",
")",
"}",
"log",
"(",
"`",
"${",
"message",
"}",
"`",
")",
"}",
"}",
"async",
"remove",
"(",
"key",
")",
"{",
"log",
"(",
"'removing %s'",
",",
"key",
")",
"if",
"(",
"this",
".",
"_listeners",
".",
"has",
"(",
"key",
")",
")",
"{",
"for",
"(",
"const",
"listener",
"of",
"this",
".",
"_listeners",
".",
"get",
"(",
"key",
")",
")",
"{",
"listener",
".",
"removeAllListeners",
"(",
"'listening'",
")",
"listener",
".",
"removeAllListeners",
"(",
"'close'",
")",
"await",
"listener",
".",
"close",
"(",
")",
"}",
"}",
"this",
".",
"_transports",
".",
"delete",
"(",
"key",
")",
"this",
".",
"_listeners",
".",
"delete",
"(",
"key",
")",
"}",
"async",
"removeAll",
"(",
")",
"{",
"const",
"tasks",
"=",
"[",
"]",
"for",
"(",
"const",
"key",
"of",
"this",
".",
"_transports",
".",
"keys",
"(",
")",
")",
"{",
"tasks",
".",
"push",
"(",
"this",
".",
"remove",
"(",
"key",
")",
")",
"}",
"await",
"Promise",
".",
"all",
"(",
"tasks",
")",
"}",
"}"
] |
@typedef {import('multiaddr').Multiaddr} Multiaddr
@typedef {import('libp2p-interfaces/src/connection').Connection} Connection
@typedef {import('libp2p-interfaces/src/transport/types').TransportFactory<any, any>} TransportFactory
@typedef {import('libp2p-interfaces/src/transport/types').Transport<any, any>} Transport
|
[
"@typedef",
"{",
"import",
"(",
"'",
"multiaddr",
"'",
")",
".",
"Multiaddr",
"}",
"Multiaddr",
"@typedef",
"{",
"import",
"(",
"'",
"libp2p",
"-",
"interfaces",
"/",
"src",
"/",
"connection",
"'",
")",
".",
"Connection",
"}",
"Connection",
"@typedef",
"{",
"import",
"(",
"'",
"libp2p",
"-",
"interfaces",
"/",
"src",
"/",
"transport",
"/",
"types",
"'",
")",
".",
"TransportFactory<any",
"any",
">",
"}",
"TransportFactory",
"@typedef",
"{",
"import",
"(",
"'",
"libp2p",
"-",
"interfaces",
"/",
"src",
"/",
"transport",
"/",
"types",
"'",
")",
".",
"Transport<any",
"any",
">",
"}",
"Transport"
] |
[
"/**\n * @class\n * @param {TransportManagerProperties & TransportManagerOptions} options\n */",
"/** @type {Map<string, Transport>} */",
"/**\n * Adds a `Transport` to the manager\n *\n * @param {string} key\n * @param {TransportFactory} Transport\n * @param {*} transportOptions - Additional options to pass to the transport\n * @returns {void}\n */",
"/**\n * Stops all listeners\n *\n * @async\n */",
"/**\n * Dials the given Multiaddr over it's supported transport\n *\n * @param {Multiaddr} ma\n * @param {*} options\n * @returns {Promise<Connection>}\n */",
"/** @type {any} */",
"/**\n * Returns all Multiaddr's the listeners are using\n *\n * @returns {Multiaddr[]}\n */",
"/** @type {Multiaddr[]} */",
"/**\n * Returns all the transports instances.\n *\n * @returns {IterableIterator<Transport>}\n */",
"/**\n * Finds a transport that matches the given Multiaddr\n *\n * @param {Multiaddr} ma\n * @returns {Transport|null}\n */",
"/**\n * Starts listeners for each listen Multiaddr.\n *\n * @async\n * @param {Multiaddr[]} addrs - addresses to attempt to listen on\n */",
"// For each supported multiaddr, create a listener",
"// Track listen/close events",
"// We need to attempt to listen on everything",
"// Keep track of transports we had no addresses for",
"// If we are listening on at least 1 address, succeed.",
"// TODO: we should look at adding a retry (`p-retry`) here to better support",
"// listening on remote addresses as they may be offline. We could then potentially",
"// just wait for any (`p-any`) listener to succeed on each transport before returning",
"// If no transports were able to listen, throw an error. This likely",
"// means we were given addresses we do not have transports for",
"/**\n * Removes the given transport from the manager.\n * If a transport has any running listeners, they will be closed.\n *\n * @async\n * @param {string} key\n */",
"// Close any running listeners",
"/**\n * Removes all transports from the manager.\n * If any listeners are running, they will be closed.\n *\n * @async\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,620
| 160
|
aaf59af8cadd873c149b3b903015b57ccff52e31
|
06000208/handler
|
src/node/ListenerBlock.js
|
[
"Unlicense"
] |
JavaScript
|
ListenerBlock
|
/**
* A block based on a listener callback for an event emitter. Specifically,
* node.js's [EventEmitter](https://nodejs.org/docs/latest-v17.x/api/events.html#class-eventemitter)
* class. This should also be compatible with re-implementations and shims,
* so it's still exported by the browser compatible version of Handler.
*
* By default, this uses handler's generateIdentifier function for it's ids. If
* this is undesirable, extend the class and replace Block#_getIdentifier by
* adding a static function of the same name.
*/
|
A block based on a listener callback for an event emitter.
By default, this uses handler's generateIdentifier function for it's ids. If
this is undesirable, extend the class and replace Block#_getIdentifier by
adding a static function of the same name.
|
[
"A",
"block",
"based",
"on",
"a",
"listener",
"callback",
"for",
"an",
"event",
"emitter",
".",
"By",
"default",
"this",
"uses",
"handler",
"'",
"s",
"generateIdentifier",
"function",
"for",
"it",
"'",
"s",
"ids",
".",
"If",
"this",
"is",
"undesirable",
"extend",
"the",
"class",
"and",
"replace",
"Block#_getIdentifier",
"by",
"adding",
"a",
"static",
"function",
"of",
"the",
"same",
"name",
"."
] |
class ListenerBlock extends BlockModule {
/**
* @param {ListenerData|string} input Either a ListenerData object, or
* the name of the event. If using the latter, you must provide the listener
* function as the second parameter.
* @param {?listener} [listener] One way of providing the listener function.
* If omitted, you must provide the listener using the ListenerData object.
* This parameter is ignored when the listener is provided using the
* ListenerData object.
*/
constructor(input, listener) {
super();
if (!input) throw new TypeError("first parameter cannot be falsy, must be an object or string");
let data;
if (typeof input == "string") {
data = { "event": input, "listener": listener };
} else {
data = { ...input };
if (!data.event || typeof data.event != "string") throw new TypeError("event must be a string");
if (!data.listener) data.listener = listener;
}
if (!data.listener || typeof data.listener != "function") throw new TypeError("a listener function must be supplied");
/**
* The name of the event the listener is for
* @type {string}
*/
this.event = data.event;
/**
* Whether the listener should only run once (whether EventEmitter#on()
* or EventEmitter#once() is used). If null, construct behavior will be
* left unchanged.
* @type {boolean|null}
*/
this.once = data.once == null ? null : Boolean(data.once);
/**
* Whether the EventEmitterConstruct should bind the emitter as the
* first parameter of the function. If null, construct behavior will be
* left unchanged.
* @type {boolean|null}
*/
this.bindEmitterParameter = data.bindEmitterParameter == null ? null : Boolean(data.bindEmitterParameter);
/**
* The event emitter which will emit the event, so you can access it
* using `this.emitter` inside your listener functions.
*
* This property is only set on load, and will be null after
* instantiation.
* @type {EventEmitter|null}
*/
this.emitter = null;
/**
* The construct which manages this block, so you can access it using
* `this.construct` inside your listener functions.
*
* This property is only set on load, and will be null after
* instantiation.
* @type {EventEmitterConstruct|null}
*/
this.construct = null;
/**
* Callback function called when the event named by the
* ListenerBlock.event property is emitted, referred to as the listener
* function.
*
* Note that if you use an arrow function, you won't be able to use the
* `this` keyword to access ListenerBlock#emitter,
* ListenerBlock#construct, etc.
*
* The emitter can be bound as the first parameter by
* EventEmitterConstruct on load depending on it's
* `bindEmitterParameter` property, or ListenerBlock's override of the
* same name.
* @type {listener}
* @abstract
*/
this.listener = data.listener;
}
}
|
[
"class",
"ListenerBlock",
"extends",
"BlockModule",
"{",
"constructor",
"(",
"input",
",",
"listener",
")",
"{",
"super",
"(",
")",
";",
"if",
"(",
"!",
"input",
")",
"throw",
"new",
"TypeError",
"(",
"\"first parameter cannot be falsy, must be an object or string\"",
")",
";",
"let",
"data",
";",
"if",
"(",
"typeof",
"input",
"==",
"\"string\"",
")",
"{",
"data",
"=",
"{",
"\"event\"",
":",
"input",
",",
"\"listener\"",
":",
"listener",
"}",
";",
"}",
"else",
"{",
"data",
"=",
"{",
"...",
"input",
"}",
";",
"if",
"(",
"!",
"data",
".",
"event",
"||",
"typeof",
"data",
".",
"event",
"!=",
"\"string\"",
")",
"throw",
"new",
"TypeError",
"(",
"\"event must be a string\"",
")",
";",
"if",
"(",
"!",
"data",
".",
"listener",
")",
"data",
".",
"listener",
"=",
"listener",
";",
"}",
"if",
"(",
"!",
"data",
".",
"listener",
"||",
"typeof",
"data",
".",
"listener",
"!=",
"\"function\"",
")",
"throw",
"new",
"TypeError",
"(",
"\"a listener function must be supplied\"",
")",
";",
"this",
".",
"event",
"=",
"data",
".",
"event",
";",
"this",
".",
"once",
"=",
"data",
".",
"once",
"==",
"null",
"?",
"null",
":",
"Boolean",
"(",
"data",
".",
"once",
")",
";",
"this",
".",
"bindEmitterParameter",
"=",
"data",
".",
"bindEmitterParameter",
"==",
"null",
"?",
"null",
":",
"Boolean",
"(",
"data",
".",
"bindEmitterParameter",
")",
";",
"this",
".",
"emitter",
"=",
"null",
";",
"this",
".",
"construct",
"=",
"null",
";",
"this",
".",
"listener",
"=",
"data",
".",
"listener",
";",
"}",
"}"
] |
A block based on a listener callback for an event emitter.
|
[
"A",
"block",
"based",
"on",
"a",
"listener",
"callback",
"for",
"an",
"event",
"emitter",
"."
] |
[
"/**\n * @param {ListenerData|string} input Either a ListenerData object, or\n * the name of the event. If using the latter, you must provide the listener\n * function as the second parameter.\n * @param {?listener} [listener] One way of providing the listener function.\n * If omitted, you must provide the listener using the ListenerData object.\n * This parameter is ignored when the listener is provided using the\n * ListenerData object.\n */",
"/**\n * The name of the event the listener is for\n * @type {string}\n */",
"/**\n * Whether the listener should only run once (whether EventEmitter#on()\n * or EventEmitter#once() is used). If null, construct behavior will be\n * left unchanged.\n * @type {boolean|null}\n */",
"/**\n * Whether the EventEmitterConstruct should bind the emitter as the\n * first parameter of the function. If null, construct behavior will be\n * left unchanged.\n * @type {boolean|null}\n */",
"/**\n * The event emitter which will emit the event, so you can access it\n * using `this.emitter` inside your listener functions.\n *\n * This property is only set on load, and will be null after\n * instantiation.\n * @type {EventEmitter|null}\n */",
"/**\n * The construct which manages this block, so you can access it using\n * `this.construct` inside your listener functions.\n *\n * This property is only set on load, and will be null after\n * instantiation.\n * @type {EventEmitterConstruct|null}\n */",
"/**\n * Callback function called when the event named by the\n * ListenerBlock.event property is emitted, referred to as the listener\n * function.\n *\n * Note that if you use an arrow function, you won't be able to use the\n * `this` keyword to access ListenerBlock#emitter,\n * ListenerBlock#construct, etc.\n *\n * The emitter can be bound as the first parameter by\n * EventEmitterConstruct on load depending on it's\n * `bindEmitterParameter` property, or ListenerBlock's override of the\n * same name.\n * @type {listener}\n * @abstract\n */"
] |
[
{
"param": "BlockModule",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BlockModule",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 14
| 695
| 122
|
48df650bf6f39a31d1728695f06b38c228887952
|
pushinginertia/pushinginertia-commons
|
pushinginertia-commons-core/src/main/java/com/pushinginertia/commons/core/math/KCombinations.java
|
[
"Apache-2.0"
] |
Java
|
KCombinations
|
/**
* Computes a list of N rows where each row represents the combinations for N choose K for K in 1..N. Each
* combination in each row also contains a payload. This is applied by taking two previous combinations from rows 1
* and K-1 and calling {@link Combination.Payload#add(Object)} to produce a new payload. This works fine for N
* up to about 16. After that, it becomes inefficient and optimizations would need to be made.
*/
|
Computes a list of N rows where each row represents the combinations for N choose K for K in 1..N. Each
combination in each row also contains a payload. This is applied by taking two previous combinations from rows 1
and K-1 and calling Combination.Payload#add(Object) to produce a new payload. This works fine for N
up to about 16. After that, it becomes inefficient and optimizations would need to be made.
|
[
"Computes",
"a",
"list",
"of",
"N",
"rows",
"where",
"each",
"row",
"represents",
"the",
"combinations",
"for",
"N",
"choose",
"K",
"for",
"K",
"in",
"1",
"..",
"N",
".",
"Each",
"combination",
"in",
"each",
"row",
"also",
"contains",
"a",
"payload",
".",
"This",
"is",
"applied",
"by",
"taking",
"two",
"previous",
"combinations",
"from",
"rows",
"1",
"and",
"K",
"-",
"1",
"and",
"calling",
"Combination",
".",
"Payload#add",
"(",
"Object",
")",
"to",
"produce",
"a",
"new",
"payload",
".",
"This",
"works",
"fine",
"for",
"N",
"up",
"to",
"about",
"16",
".",
"After",
"that",
"it",
"becomes",
"inefficient",
"and",
"optimizations",
"would",
"need",
"to",
"be",
"made",
"."
] |
public class KCombinations<P extends Combination.Payload<P>> {
private final List<Map<Combination.Key, Combination<P>>> rows;
private int size;
/**
* Computes a list of N rows where each row represents the combinations for N choose K for K in 1..N. Each
* combination in each row also contains a payload. This is applied by taking two previous combinations from rows 1
* and K-1 and calling {@link Combination.Payload#add(Object)} to produce a new payload. This works fine for N
* up to about 16. After that, it becomes inefficient and optimizations would need to be made.
*
* @param initialPayloads List of initial payloads for N choose 1. The size of this list defines N and all N choose
* K combinations for K > 1 are calculated from this initial list.
*/
public KCombinations(final List<P> initialPayloads) {
final int n = initialPayloads.size();
if (n > 16) {
throw new IllegalArgumentException("n is too high for this algorithm.");
}
this.rows = new ArrayList<Map<Combination.Key, Combination<P>>>(n);
for (int i = 0; i < n; i++) {
rows.add(new HashMap<Combination.Key, Combination<P>>());
}
this.size = 0;
for (int i = 0; i < n; i++) {
add(new Combination<P>(i, initialPayloads.get(i)));
}
for (int k = 1; k < n; k++) {
computeK(k);
}
}
/**
* The number of combinations identified for N choose K for K in 1..N.
* @return Combination count.
*/
public int size() {
return size;
}
/**
* Merges all of the payloads into a single payload.
* @param payload Empty payload to merge everything into.
* @return Merged payload.
*/
public P merge(final P payload) {
for (final Map<Combination.Key, Combination<P>> row: rows) {
for (final Combination<P> combination: row.values()) {
payload.merge(combination.getPayload());
}
}
return payload;
}
int rowCount() {
return rows.size();
}
int rowSize(final int k) {
if (k >= rows.size()) {
throw new IllegalArgumentException("k must be < n");
}
return rows.get(k).size();
}
private void add(final Combination<P> combination) {
final Combination.Key key = combination.getKey();
final int k = key.size();
if (k > rows.size()) {
throw new IllegalArgumentException("k (" + k + ") must be < n (" + rows.size() + ")");
}
final Map<Combination.Key, Combination<P>> row = rows.get(k - 1);
if (row.containsKey(key)) {
throw new IllegalArgumentException("Combination already exists: " + combination);
}
row.put(key, combination);
size++;
}
private void computeK(final int k) {
if (k < 1) {
throw new IllegalArgumentException("k must be >= 2");
}
final Map<Combination.Key, Combination<P>> row0 = rows.get(0);
final Map<Combination.Key, Combination<P>> rowPrevious = rows.get(k - 1);
for (final Combination<P> combinationPrevious: rowPrevious.values()) {
final int r = combinationPrevious.getKey().getRightIndex();
for (final Combination<P> combinationFirst: row0.values()) {
final int i = combinationFirst.getKey().getOnlyIndex();
if (r < i) {
add(new Combination<P>(combinationPrevious, combinationFirst));
}
}
}
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for (final Map<Combination.Key, Combination<P>> row: rows) {
if (sb.length() > 0) {
sb.append(", ");
}
sb.append('[');
final StringBuilder sbRow = new StringBuilder();
for (final Combination<P> combination : row.values()) {
if (sbRow.length() > 0) {
sbRow.append(',');
}
sbRow.append(combination);
}
sb.append(sbRow);
sb.append(']');
}
return "R{" + sb.toString() + '}';
}
}
|
[
"public",
"class",
"KCombinations",
"<",
"P",
"extends",
"Combination",
".",
"Payload",
"<",
"P",
">",
">",
"{",
"private",
"final",
"List",
"<",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
">",
"rows",
";",
"private",
"int",
"size",
";",
"/**\n\t * Computes a list of N rows where each row represents the combinations for N choose K for K in 1..N. Each\n\t * combination in each row also contains a payload. This is applied by taking two previous combinations from rows 1\n\t * and K-1 and calling {@link Combination.Payload#add(Object)} to produce a new payload. This works fine for N\n\t * up to about 16. After that, it becomes inefficient and optimizations would need to be made.\n\t *\n\t * @param initialPayloads List of initial payloads for N choose 1. The size of this list defines N and all N choose\n\t * K combinations for K > 1 are calculated from this initial list.\n\t */",
"public",
"KCombinations",
"(",
"final",
"List",
"<",
"P",
">",
"initialPayloads",
")",
"{",
"final",
"int",
"n",
"=",
"initialPayloads",
".",
"size",
"(",
")",
";",
"if",
"(",
"n",
">",
"16",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"n is too high for this algorithm.",
"\"",
")",
";",
"}",
"this",
".",
"rows",
"=",
"new",
"ArrayList",
"<",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
">",
"(",
"n",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"rows",
".",
"add",
"(",
"new",
"HashMap",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"(",
")",
")",
";",
"}",
"this",
".",
"size",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"n",
";",
"i",
"++",
")",
"{",
"add",
"(",
"new",
"Combination",
"<",
"P",
">",
"(",
"i",
",",
"initialPayloads",
".",
"get",
"(",
"i",
")",
")",
")",
";",
"}",
"for",
"(",
"int",
"k",
"=",
"1",
";",
"k",
"<",
"n",
";",
"k",
"++",
")",
"{",
"computeK",
"(",
"k",
")",
";",
"}",
"}",
"/**\n\t * The number of combinations identified for N choose K for K in 1..N.\n\t * @return Combination count.\n\t */",
"public",
"int",
"size",
"(",
")",
"{",
"return",
"size",
";",
"}",
"/**\n\t * Merges all of the payloads into a single payload.\n\t * @param payload Empty payload to merge everything into.\n\t * @return Merged payload.\n\t */",
"public",
"P",
"merge",
"(",
"final",
"P",
"payload",
")",
"{",
"for",
"(",
"final",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"row",
":",
"rows",
")",
"{",
"for",
"(",
"final",
"Combination",
"<",
"P",
">",
"combination",
":",
"row",
".",
"values",
"(",
")",
")",
"{",
"payload",
".",
"merge",
"(",
"combination",
".",
"getPayload",
"(",
")",
")",
";",
"}",
"}",
"return",
"payload",
";",
"}",
"int",
"rowCount",
"(",
")",
"{",
"return",
"rows",
".",
"size",
"(",
")",
";",
"}",
"int",
"rowSize",
"(",
"final",
"int",
"k",
")",
"{",
"if",
"(",
"k",
">=",
"rows",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"k must be < n",
"\"",
")",
";",
"}",
"return",
"rows",
".",
"get",
"(",
"k",
")",
".",
"size",
"(",
")",
";",
"}",
"private",
"void",
"add",
"(",
"final",
"Combination",
"<",
"P",
">",
"combination",
")",
"{",
"final",
"Combination",
".",
"Key",
"key",
"=",
"combination",
".",
"getKey",
"(",
")",
";",
"final",
"int",
"k",
"=",
"key",
".",
"size",
"(",
")",
";",
"if",
"(",
"k",
">",
"rows",
".",
"size",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"k (",
"\"",
"+",
"k",
"+",
"\"",
") must be < n (",
"\"",
"+",
"rows",
".",
"size",
"(",
")",
"+",
"\"",
")",
"\"",
")",
";",
"}",
"final",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"row",
"=",
"rows",
".",
"get",
"(",
"k",
"-",
"1",
")",
";",
"if",
"(",
"row",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Combination already exists: ",
"\"",
"+",
"combination",
")",
";",
"}",
"row",
".",
"put",
"(",
"key",
",",
"combination",
")",
";",
"size",
"++",
";",
"}",
"private",
"void",
"computeK",
"(",
"final",
"int",
"k",
")",
"{",
"if",
"(",
"k",
"<",
"1",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"k must be >= 2",
"\"",
")",
";",
"}",
"final",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"row0",
"=",
"rows",
".",
"get",
"(",
"0",
")",
";",
"final",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"rowPrevious",
"=",
"rows",
".",
"get",
"(",
"k",
"-",
"1",
")",
";",
"for",
"(",
"final",
"Combination",
"<",
"P",
">",
"combinationPrevious",
":",
"rowPrevious",
".",
"values",
"(",
")",
")",
"{",
"final",
"int",
"r",
"=",
"combinationPrevious",
".",
"getKey",
"(",
")",
".",
"getRightIndex",
"(",
")",
";",
"for",
"(",
"final",
"Combination",
"<",
"P",
">",
"combinationFirst",
":",
"row0",
".",
"values",
"(",
")",
")",
"{",
"final",
"int",
"i",
"=",
"combinationFirst",
".",
"getKey",
"(",
")",
".",
"getOnlyIndex",
"(",
")",
";",
"if",
"(",
"r",
"<",
"i",
")",
"{",
"add",
"(",
"new",
"Combination",
"<",
"P",
">",
"(",
"combinationPrevious",
",",
"combinationFirst",
")",
")",
";",
"}",
"}",
"}",
"}",
"@",
"Override",
"public",
"String",
"toString",
"(",
")",
"{",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"final",
"Map",
"<",
"Combination",
".",
"Key",
",",
"Combination",
"<",
"P",
">",
">",
"row",
":",
"rows",
")",
"{",
"if",
"(",
"sb",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\"",
", ",
"\"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"'['",
")",
";",
"final",
"StringBuilder",
"sbRow",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"final",
"Combination",
"<",
"P",
">",
"combination",
":",
"row",
".",
"values",
"(",
")",
")",
"{",
"if",
"(",
"sbRow",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sbRow",
".",
"append",
"(",
"','",
")",
";",
"}",
"sbRow",
".",
"append",
"(",
"combination",
")",
";",
"}",
"sb",
".",
"append",
"(",
"sbRow",
")",
";",
"sb",
".",
"append",
"(",
"']'",
")",
";",
"}",
"return",
"\"",
"R{",
"\"",
"+",
"sb",
".",
"toString",
"(",
")",
"+",
"'}'",
";",
"}",
"}"
] |
Computes a list of N rows where each row represents the combinations for N choose K for K in 1..N. Each
combination in each row also contains a payload.
|
[
"Computes",
"a",
"list",
"of",
"N",
"rows",
"where",
"each",
"row",
"represents",
"the",
"combinations",
"for",
"N",
"choose",
"K",
"for",
"K",
"in",
"1",
"..",
"N",
".",
"Each",
"combination",
"in",
"each",
"row",
"also",
"contains",
"a",
"payload",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 959
| 101
|
7d48647658408c86a41d5985a0429c78cee28d97
|
aTiKhan/SharpVectors
|
Source/SharpVectorModel/Fills/SvgRadialGradientElement.cs
|
[
"MIT",
"BSD-3-Clause"
] |
C#
|
SvgRadialGradientElement
|
/// <summary>
/// The implementation of the <c>radialGradient</c> element or the <see cref="ISvgRadialGradientElement"/> interface.
/// </summary>
/// <remarks>
/// Radial Gradient fx/fy values should only be inherited from a referenced element if that element is explicitly
/// defining them, otherwise they should follow the cy special case behavior. Additionally, because xlink references
/// can inherit to an arbitrary level, we should walk up the tree looking for explicitly defined fx/fy values to
/// inherit before falling back to the cx/cy definitions.
/// </remarks>
|
The implementation of the radialGradient interface.
|
[
"The",
"implementation",
"of",
"the",
"radialGradient",
"interface",
"."
] |
public sealed class SvgRadialGradientElement : SvgGradientElement, ISvgRadialGradientElement
{
#region Private Fields
private ISvgAnimatedLength _cx;
private ISvgAnimatedLength _cy;
private ISvgAnimatedLength _r;
private ISvgAnimatedLength _fx;
private ISvgAnimatedLength _fy;
#endregion
#region Constructors and Destructor
public SvgRadialGradientElement(string prefix, string localname, string ns, SvgDocument doc)
: base(prefix, localname, ns, doc)
{
}
#endregion
#region ISvgRadialGradientElement Members
public override bool IsRenderable
{
get {
return false;
}
}
public ISvgAnimatedLength Cx
{
get {
var refElem = this.ReferencedElement;
if (!HasAttribute("cx") && refElem != null)
{
return refElem.Cx;
}
if (_cx == null)
{
_cx = new SvgAnimatedLength(this, "cx", SvgLengthDirection.Horizontal, "50%");
}
return _cx;
}
}
public ISvgAnimatedLength Cy
{
get {
var refElem = this.ReferencedElement;
if (!HasAttribute("cy") && refElem != null)
{
return refElem.Cy;
}
if (_cy == null)
{
_cy = new SvgAnimatedLength(this, "cy", SvgLengthDirection.Vertical, "50%");
}
return _cy;
}
}
public ISvgAnimatedLength R
{
get {
var refElem = this.ReferencedElement;
if (!HasAttribute("r") && refElem != null)
{
return refElem.R;
}
if (_r == null)
{
_r = new SvgAnimatedLength(this, "r", SvgLengthDirection.Viewport, "50%");
}
return _r;
}
}
public ISvgAnimatedLength Fx
{
get {
var refElem = this.ReferencedElement;
if (!HasAttribute("fx") && refElem != null)
{
if (!refElem.HasAttribute("fx"))
{
var nextRef = refElem.ReferencedElement;
while (nextRef != null)
{
if (nextRef.HasAttribute("fx"))
{
return nextRef.Fx;
}
nextRef = nextRef.ReferencedElement;
}
if (HasAttribute("cx"))
{
return Cx;
}
}
return refElem.Fx;
}
if (!HasAttribute("fx") && HasAttribute("cx"))
{
return Cx;
}
if (!HasAttribute("fx") && HasAttribute("fy"))
{
return Fy;
}
if (_fx == null)
{
_fx = new SvgAnimatedLength(this, "fx", SvgLengthDirection.Horizontal, "50%");
}
return _fx;
}
}
public ISvgAnimatedLength Fy
{
get {
var refElem = this.ReferencedElement;
if (!HasAttribute("fy") && refElem != null)
{
if (!refElem.HasAttribute("fy"))
{
var nextRef = refElem.ReferencedElement;
while (nextRef != null)
{
if (nextRef.HasAttribute("fy"))
{
return nextRef.Fy;
}
nextRef = nextRef.ReferencedElement;
}
if (HasAttribute("cy"))
{
return Cy;
}
}
return refElem.Fy;
}
if (!HasAttribute("fy") && HasAttribute("cy"))
{
return Cy;
}
if (!HasAttribute("fy") && HasAttribute("fx"))
{
return Fx;
}
if (_fy == null)
{
_fy = new SvgAnimatedLength(this, "fy", SvgLengthDirection.Vertical, "50%");
}
return _fy;
}
}
#endregion
#region ISvgURIReference Members
public new SvgRadialGradientElement ReferencedElement
{
get {
return base.ReferencedElement as SvgRadialGradientElement;
}
}
#endregion
#region Update handling
#endregion
}
|
[
"public",
"sealed",
"class",
"SvgRadialGradientElement",
":",
"SvgGradientElement",
",",
"ISvgRadialGradientElement",
"{",
"region",
" Private Fields",
"private",
"ISvgAnimatedLength",
"_cx",
";",
"private",
"ISvgAnimatedLength",
"_cy",
";",
"private",
"ISvgAnimatedLength",
"_r",
";",
"private",
"ISvgAnimatedLength",
"_fx",
";",
"private",
"ISvgAnimatedLength",
"_fy",
";",
"endregion",
"region",
" Constructors and Destructor",
"public",
"SvgRadialGradientElement",
"(",
"string",
"prefix",
",",
"string",
"localname",
",",
"string",
"ns",
",",
"SvgDocument",
"doc",
")",
":",
"base",
"(",
"prefix",
",",
"localname",
",",
"ns",
",",
"doc",
")",
"{",
"}",
"endregion",
"region",
" ISvgRadialGradientElement Members",
"public",
"override",
"bool",
"IsRenderable",
"{",
"get",
"{",
"return",
"false",
";",
"}",
"}",
"public",
"ISvgAnimatedLength",
"Cx",
"{",
"get",
"{",
"var",
"refElem",
"=",
"this",
".",
"ReferencedElement",
";",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"cx",
"\"",
")",
"&&",
"refElem",
"!=",
"null",
")",
"{",
"return",
"refElem",
".",
"Cx",
";",
"}",
"if",
"(",
"_cx",
"==",
"null",
")",
"{",
"_cx",
"=",
"new",
"SvgAnimatedLength",
"(",
"this",
",",
"\"",
"cx",
"\"",
",",
"SvgLengthDirection",
".",
"Horizontal",
",",
"\"",
"50%",
"\"",
")",
";",
"}",
"return",
"_cx",
";",
"}",
"}",
"public",
"ISvgAnimatedLength",
"Cy",
"{",
"get",
"{",
"var",
"refElem",
"=",
"this",
".",
"ReferencedElement",
";",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"cy",
"\"",
")",
"&&",
"refElem",
"!=",
"null",
")",
"{",
"return",
"refElem",
".",
"Cy",
";",
"}",
"if",
"(",
"_cy",
"==",
"null",
")",
"{",
"_cy",
"=",
"new",
"SvgAnimatedLength",
"(",
"this",
",",
"\"",
"cy",
"\"",
",",
"SvgLengthDirection",
".",
"Vertical",
",",
"\"",
"50%",
"\"",
")",
";",
"}",
"return",
"_cy",
";",
"}",
"}",
"public",
"ISvgAnimatedLength",
"R",
"{",
"get",
"{",
"var",
"refElem",
"=",
"this",
".",
"ReferencedElement",
";",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"r",
"\"",
")",
"&&",
"refElem",
"!=",
"null",
")",
"{",
"return",
"refElem",
".",
"R",
";",
"}",
"if",
"(",
"_r",
"==",
"null",
")",
"{",
"_r",
"=",
"new",
"SvgAnimatedLength",
"(",
"this",
",",
"\"",
"r",
"\"",
",",
"SvgLengthDirection",
".",
"Viewport",
",",
"\"",
"50%",
"\"",
")",
";",
"}",
"return",
"_r",
";",
"}",
"}",
"public",
"ISvgAnimatedLength",
"Fx",
"{",
"get",
"{",
"var",
"refElem",
"=",
"this",
".",
"ReferencedElement",
";",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
"&&",
"refElem",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"refElem",
".",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
")",
"{",
"var",
"nextRef",
"=",
"refElem",
".",
"ReferencedElement",
";",
"while",
"(",
"nextRef",
"!=",
"null",
")",
"{",
"if",
"(",
"nextRef",
".",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
")",
"{",
"return",
"nextRef",
".",
"Fx",
";",
"}",
"nextRef",
"=",
"nextRef",
".",
"ReferencedElement",
";",
"}",
"if",
"(",
"HasAttribute",
"(",
"\"",
"cx",
"\"",
")",
")",
"{",
"return",
"Cx",
";",
"}",
"}",
"return",
"refElem",
".",
"Fx",
";",
"}",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
"&&",
"HasAttribute",
"(",
"\"",
"cx",
"\"",
")",
")",
"{",
"return",
"Cx",
";",
"}",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
"&&",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
")",
"{",
"return",
"Fy",
";",
"}",
"if",
"(",
"_fx",
"==",
"null",
")",
"{",
"_fx",
"=",
"new",
"SvgAnimatedLength",
"(",
"this",
",",
"\"",
"fx",
"\"",
",",
"SvgLengthDirection",
".",
"Horizontal",
",",
"\"",
"50%",
"\"",
")",
";",
"}",
"return",
"_fx",
";",
"}",
"}",
"public",
"ISvgAnimatedLength",
"Fy",
"{",
"get",
"{",
"var",
"refElem",
"=",
"this",
".",
"ReferencedElement",
";",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
"&&",
"refElem",
"!=",
"null",
")",
"{",
"if",
"(",
"!",
"refElem",
".",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
")",
"{",
"var",
"nextRef",
"=",
"refElem",
".",
"ReferencedElement",
";",
"while",
"(",
"nextRef",
"!=",
"null",
")",
"{",
"if",
"(",
"nextRef",
".",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
")",
"{",
"return",
"nextRef",
".",
"Fy",
";",
"}",
"nextRef",
"=",
"nextRef",
".",
"ReferencedElement",
";",
"}",
"if",
"(",
"HasAttribute",
"(",
"\"",
"cy",
"\"",
")",
")",
"{",
"return",
"Cy",
";",
"}",
"}",
"return",
"refElem",
".",
"Fy",
";",
"}",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
"&&",
"HasAttribute",
"(",
"\"",
"cy",
"\"",
")",
")",
"{",
"return",
"Cy",
";",
"}",
"if",
"(",
"!",
"HasAttribute",
"(",
"\"",
"fy",
"\"",
")",
"&&",
"HasAttribute",
"(",
"\"",
"fx",
"\"",
")",
")",
"{",
"return",
"Fx",
";",
"}",
"if",
"(",
"_fy",
"==",
"null",
")",
"{",
"_fy",
"=",
"new",
"SvgAnimatedLength",
"(",
"this",
",",
"\"",
"fy",
"\"",
",",
"SvgLengthDirection",
".",
"Vertical",
",",
"\"",
"50%",
"\"",
")",
";",
"}",
"return",
"_fy",
";",
"}",
"}",
"endregion",
"region",
" ISvgURIReference Members",
"public",
"new",
"SvgRadialGradientElement",
"ReferencedElement",
"{",
"get",
"{",
"return",
"base",
".",
"ReferencedElement",
"as",
"SvgRadialGradientElement",
";",
"}",
"}",
"endregion",
"region",
" Update handling",
"endregion",
"}"
] |
The implementation of the radialGradient interface.
|
[
"The",
"implementation",
"of",
"the",
"radialGradient",
"interface",
"."
] |
[
"/// <summary>",
"/// Gets a value indicating whether this SVG element is renderable.",
"/// </summary>",
"/// <value>",
"/// This is <see langword=\"'true\"/> if the element is renderable; otherwise,",
"/// it is <see langword=\"false\"/>.",
"/// </value>",
"/*public override void OnAttributeChange(XmlNodeChangedAction action, XmlAttribute attribute)\r\n\t\t{\r\n\t\t\tbase.OnAttributeChange(action, attribute);\r\n\r\n\t\t\tif(attribute.NamespaceURI.Length == 0)\r\n\t\t\t{\r\n\t\t\t\tswitch(attribute.LocalName)\r\n\t\t\t\t{\r\n\t\t\t\t\tcase \"cx\":\r\n\t\t\t\t\t\tcx = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"cy\":\r\n\t\t\t\t\t\tcy = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"r\":\r\n\t\t\t\t\t\tr = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"fx\":\r\n\t\t\t\t\t\tfx = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase \"fy\":\r\n\t\t\t\t\t\tfy = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}*/"
] |
[
{
"param": "SvgGradientElement",
"type": null
},
{
"param": "ISvgRadialGradientElement",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SvgGradientElement",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "ISvgRadialGradientElement",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "Radial Gradient fx/fy values should only be inherited from a referenced element if that element is explicitly\ndefining them, otherwise they should follow the cy special case behavior. Additionally, because xlink references\ncan inherit to an arbitrary level, we should walk up the tree looking for explicitly defined fx/fy values to\ninherit before falling back to the cx/cy definitions.",
"docstring_tokens": [
"Radial",
"Gradient",
"fx",
"/",
"fy",
"values",
"should",
"only",
"be",
"inherited",
"from",
"a",
"referenced",
"element",
"if",
"that",
"element",
"is",
"explicitly",
"defining",
"them",
"otherwise",
"they",
"should",
"follow",
"the",
"cy",
"special",
"case",
"behavior",
".",
"Additionally",
"because",
"xlink",
"references",
"can",
"inherit",
"to",
"an",
"arbitrary",
"level",
"we",
"should",
"walk",
"up",
"the",
"tree",
"looking",
"for",
"explicitly",
"defined",
"fx",
"/",
"fy",
"values",
"to",
"inherit",
"before",
"falling",
"back",
"to",
"the",
"cx",
"/",
"cy",
"definitions",
"."
]
}
]
}
| false
| 18
| 943
| 124
|
1d99080561b26fa622c445ca3aa7252fd9625f1e
|
mattcolefla/SwarmOps
|
RandomOps/RandomOps/RandomOps/IndexDistribution.cs
|
[
"0BSD"
] |
C#
|
IndexDistribution
|
/// <summary>
/// A set of integers enumerated from zero and upwards that
/// can be drawn at random according to the given probability
/// distribution. Probabilities are assumed to sum to one.
/// Various functions for drawing numbers are supplied with
/// different time-complexity advantages. Thread-safe if
/// supplied RNG's Uniform() is thread-safe.
/// </summary>
|
A set of integers enumerated from zero and upwards that
can be drawn at random according to the given probability
distribution. Probabilities are assumed to sum to one.
Various functions for drawing numbers are supplied with
different time-complexity advantages. Thread-safe if
supplied RNG's Uniform() is thread-safe.
|
[
"A",
"set",
"of",
"integers",
"enumerated",
"from",
"zero",
"and",
"upwards",
"that",
"can",
"be",
"drawn",
"at",
"random",
"according",
"to",
"the",
"given",
"probability",
"distribution",
".",
"Probabilities",
"are",
"assumed",
"to",
"sum",
"to",
"one",
".",
"Various",
"functions",
"for",
"drawing",
"numbers",
"are",
"supplied",
"with",
"different",
"time",
"-",
"complexity",
"advantages",
".",
"Thread",
"-",
"safe",
"if",
"supplied",
"RNG",
"'",
"s",
"Uniform",
"()",
"is",
"thread",
"-",
"safe",
"."
] |
public class IndexDistribution
{
#region Constructors.
public IndexDistribution(Random rand, double[] probabilities)
{
Rand = rand;
ProbabilitySum = new double[probabilities.Length + 1];
ProbabilitySum[0] = 0;
double sum = 0;
for (int i = 0; i < probabilities.Length; i++)
{
sum += probabilities[i];
ProbabilitySum[i + 1] = sum;
}
}
#endregion
#region Public methods.
public int DrawLinearSearch()
{
double r = Rand.Uniform();
int i;
for (i = 0; ProbabilitySum[i] < r && i < ProbabilitySum.Length-1; i++)
{
}
return i - 1;
}
public int DrawBinarySearch()
{
double r = Rand.Uniform();
int minIdx=0;
int maxIdx = ProbabilitySum.Length - 1;
while (minIdx < maxIdx - 1)
{
int middle = (maxIdx - minIdx) / 2 + minIdx;
if (r < ProbabilitySum[middle])
{
maxIdx = middle;
}
else
{
minIdx = middle;
}
}
return minIdx;
}
#endregion
#region Public properties.
public Random Rand
{
get;
set;
}
#endregion
#region Internal variables.
private double[] ProbabilitySum;
#endregion
}
|
[
"public",
"class",
"IndexDistribution",
"{",
"region",
" Constructors.",
"public",
"IndexDistribution",
"(",
"Random",
"rand",
",",
"double",
"[",
"]",
"probabilities",
")",
"{",
"Rand",
"=",
"rand",
";",
"ProbabilitySum",
"=",
"new",
"double",
"[",
"probabilities",
".",
"Length",
"+",
"1",
"]",
";",
"ProbabilitySum",
"[",
"0",
"]",
"=",
"0",
";",
"double",
"sum",
"=",
"0",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"probabilities",
".",
"Length",
";",
"i",
"++",
")",
"{",
"sum",
"+=",
"probabilities",
"[",
"i",
"]",
";",
"ProbabilitySum",
"[",
"i",
"+",
"1",
"]",
"=",
"sum",
";",
"}",
"}",
"endregion",
"region",
" Public methods.",
"public",
"int",
"DrawLinearSearch",
"(",
")",
"{",
"double",
"r",
"=",
"Rand",
".",
"Uniform",
"(",
")",
";",
"int",
"i",
";",
"for",
"(",
"i",
"=",
"0",
";",
"ProbabilitySum",
"[",
"i",
"]",
"<",
"r",
"&&",
"i",
"<",
"ProbabilitySum",
".",
"Length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"}",
"return",
"i",
"-",
"1",
";",
"}",
"public",
"int",
"DrawBinarySearch",
"(",
")",
"{",
"double",
"r",
"=",
"Rand",
".",
"Uniform",
"(",
")",
";",
"int",
"minIdx",
"=",
"0",
";",
"int",
"maxIdx",
"=",
"ProbabilitySum",
".",
"Length",
"-",
"1",
";",
"while",
"(",
"minIdx",
"<",
"maxIdx",
"-",
"1",
")",
"{",
"int",
"middle",
"=",
"(",
"maxIdx",
"-",
"minIdx",
")",
"/",
"2",
"+",
"minIdx",
";",
"if",
"(",
"r",
"<",
"ProbabilitySum",
"[",
"middle",
"]",
")",
"{",
"maxIdx",
"=",
"middle",
";",
"}",
"else",
"{",
"minIdx",
"=",
"middle",
";",
"}",
"}",
"return",
"minIdx",
";",
"}",
"endregion",
"region",
" Public properties.",
"public",
"Random",
"Rand",
"{",
"get",
";",
"set",
";",
"}",
"endregion",
"region",
" Internal variables.",
"private",
"double",
"[",
"]",
"ProbabilitySum",
";",
"endregion",
"}"
] |
A set of integers enumerated from zero and upwards that
can be drawn at random according to the given probability
distribution.
|
[
"A",
"set",
"of",
"integers",
"enumerated",
"from",
"zero",
"and",
"upwards",
"that",
"can",
"be",
"drawn",
"at",
"random",
"according",
"to",
"the",
"given",
"probability",
"distribution",
"."
] |
[
"/// <summary>",
"/// Create the object. Time-complexity for doing this is O(n),",
"/// where n is the length of the probabilities-array. ",
"/// </summary>",
"/// <param name=\"rand\">RNG object to use.</param>",
"/// <param name=\"probabilities\">Probability distribution.</param>",
"/// <summary>",
"/// Draw a random integer from {0, .., n-1} according to previously",
"/// supplied probability distribution. Time-complexity is O(n),",
"/// where n is the length of the probabilities-array supplied to",
"/// CreateIndexDistribution().",
"/// Use this function if you make repeated draws from the same",
"/// set and the set-size is small.",
"/// </summary>",
"/// <returns></returns>",
"/// <summary>",
"/// Draw a random integer from {0, .., n-1} according to previously",
"/// supplied probability distribution. Time-complexity is O(log(n)),",
"/// where n is the length of the probabilities-array supplied to",
"/// CreateIndexDistribution().",
"/// Use this function if you make repeated draws from the same",
"/// set and the set-size is large.",
"/// </summary>",
"/// <summary>",
"/// RNG object being used.",
"/// </summary>",
"/// <summary>",
"/// Intermediate summation of the probability-distribution.",
"/// </summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 327
| 76
|
5b6277ec381565e83c8af07b05e9947f4a1445a6
|
talon2king/BotBuilder-Samples
|
samples/csharp_dotnetcore/12.nlp-with-luis/LuisBot.cs
|
[
"MIT"
] |
C#
|
LuisBot
|
/// <summary>
/// For each interaction from the user, an instance of this class is created and
/// the OnTurnAsync method is called.
/// This is a transient lifetime service. Transient lifetime services are created
/// each time they're requested. For each <see cref="Activity"/> received, a new instance of this
/// class is created. Objects that are expensive to construct, or have a lifetime
/// beyond the single turn, should be carefully managed.
/// </summary>
/// <seealso cref="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1"/>
/// <seealso cref="https://docs.microsoft.com/en-us/dotnet/api/microsoft.bot.ibot?view=botbuilder-dotnet-preview"/>
|
For each interaction from the user, an instance of this class is created and
the OnTurnAsync method is called.
This is a transient lifetime service. Transient lifetime services are created
each time they're requested. For each received, a new instance of this
class is created. Objects that are expensive to construct, or have a lifetime
beyond the single turn, should be carefully managed.
|
[
"For",
"each",
"interaction",
"from",
"the",
"user",
"an",
"instance",
"of",
"this",
"class",
"is",
"created",
"and",
"the",
"OnTurnAsync",
"method",
"is",
"called",
".",
"This",
"is",
"a",
"transient",
"lifetime",
"service",
".",
"Transient",
"lifetime",
"services",
"are",
"created",
"each",
"time",
"they",
"'",
"re",
"requested",
".",
"For",
"each",
"received",
"a",
"new",
"instance",
"of",
"this",
"class",
"is",
"created",
".",
"Objects",
"that",
"are",
"expensive",
"to",
"construct",
"or",
"have",
"a",
"lifetime",
"beyond",
"the",
"single",
"turn",
"should",
"be",
"carefully",
"managed",
"."
] |
public class LuisBot : IBot
{
private const string WelcomeText = "This bot will introduce you to natural language processing with LUIS. Type an utterance to get started";
public static readonly string LuisKey = "LuisBot";
private readonly BotServices _services;
public LuisBot(BotServices services)
{
_services = services ?? throw new System.ArgumentNullException(nameof(services));
if (!_services.LuisServices.ContainsKey(LuisKey))
{
throw new System.ArgumentException($"Invalid configuration. Please check your '.bot' file for a LUIS service named '{LuisKey}'.");
}
}
public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken = default(CancellationToken))
{
if (turnContext.Activity.Type == ActivityTypes.Message)
{
var recognizerResult = await _services.LuisServices[LuisKey].RecognizeAsync(turnContext, cancellationToken);
var topIntent = recognizerResult?.GetTopScoringIntent();
if (topIntent != null && topIntent.HasValue && topIntent.Value.intent != "None")
{
await turnContext.SendActivityAsync($"==>LUIS Top Scoring Intent: {topIntent.Value.intent}, Score: {topIntent.Value.score}\n");
}
else
{
var msg = @"No LUIS intents were found.
This sample is about identifying two user intents:
'Calendar.Add'
'Calendar.Find'
Try typing 'Add Event' or 'Show me tomorrow'.";
await turnContext.SendActivityAsync(msg);
}
}
else if (turnContext.Activity.Type == ActivityTypes.ConversationUpdate)
{
await SendWelcomeMessageAsync(turnContext, cancellationToken);
}
else
{
await turnContext.SendActivityAsync($"{turnContext.Activity.Type} event detected", cancellationToken: cancellationToken);
}
}
private static async Task SendWelcomeMessageAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
foreach (var member in turnContext.Activity.MembersAdded)
{
if (member.Id != turnContext.Activity.Recipient.Id)
{
await turnContext.SendActivityAsync(
$"Welcome to LuisBot {member.Name}. {WelcomeText}",
cancellationToken: cancellationToken);
}
}
}
}
|
[
"public",
"class",
"LuisBot",
":",
"IBot",
"{",
"private",
"const",
"string",
"WelcomeText",
"=",
"\"",
"This bot will introduce you to natural language processing with LUIS. Type an utterance to get started",
"\"",
";",
"public",
"static",
"readonly",
"string",
"LuisKey",
"=",
"\"",
"LuisBot",
"\"",
";",
"private",
"readonly",
"BotServices",
"_services",
";",
"public",
"LuisBot",
"(",
"BotServices",
"services",
")",
"{",
"_services",
"=",
"services",
"??",
"throw",
"new",
"System",
".",
"ArgumentNullException",
"(",
"nameof",
"(",
"services",
")",
")",
";",
"if",
"(",
"!",
"_services",
".",
"LuisServices",
".",
"ContainsKey",
"(",
"LuisKey",
")",
")",
"{",
"throw",
"new",
"System",
".",
"ArgumentException",
"(",
"$\"",
"Invalid configuration. Please check your '.bot' file for a LUIS service named '",
"{",
"LuisKey",
"}",
"'.",
"\"",
")",
";",
"}",
"}",
"public",
"async",
"Task",
"OnTurnAsync",
"(",
"ITurnContext",
"turnContext",
",",
"CancellationToken",
"cancellationToken",
"=",
"default",
"(",
"CancellationToken",
")",
")",
"{",
"if",
"(",
"turnContext",
".",
"Activity",
".",
"Type",
"==",
"ActivityTypes",
".",
"Message",
")",
"{",
"var",
"recognizerResult",
"=",
"await",
"_services",
".",
"LuisServices",
"[",
"LuisKey",
"]",
".",
"RecognizeAsync",
"(",
"turnContext",
",",
"cancellationToken",
")",
";",
"var",
"topIntent",
"=",
"recognizerResult",
"?",
".",
"GetTopScoringIntent",
"(",
")",
";",
"if",
"(",
"topIntent",
"!=",
"null",
"&&",
"topIntent",
".",
"HasValue",
"&&",
"topIntent",
".",
"Value",
".",
"intent",
"!=",
"\"",
"None",
"\"",
")",
"{",
"await",
"turnContext",
".",
"SendActivityAsync",
"(",
"$\"",
"==>LUIS Top Scoring Intent: ",
"{",
"topIntent",
".",
"Value",
".",
"intent",
"}",
", Score: ",
"{",
"topIntent",
".",
"Value",
".",
"score",
"}",
"\\n",
"\"",
")",
";",
"}",
"else",
"{",
"var",
"msg",
"=",
"@\"No LUIS intents were found.\n This sample is about identifying two user intents:\n 'Calendar.Add'\n 'Calendar.Find'\n Try typing 'Add Event' or 'Show me tomorrow'.\"",
";",
"await",
"turnContext",
".",
"SendActivityAsync",
"(",
"msg",
")",
";",
"}",
"}",
"else",
"if",
"(",
"turnContext",
".",
"Activity",
".",
"Type",
"==",
"ActivityTypes",
".",
"ConversationUpdate",
")",
"{",
"await",
"SendWelcomeMessageAsync",
"(",
"turnContext",
",",
"cancellationToken",
")",
";",
"}",
"else",
"{",
"await",
"turnContext",
".",
"SendActivityAsync",
"(",
"$\"",
"{",
"turnContext",
".",
"Activity",
".",
"Type",
"}",
" event detected",
"\"",
",",
"cancellationToken",
":",
"cancellationToken",
")",
";",
"}",
"}",
"private",
"static",
"async",
"Task",
"SendWelcomeMessageAsync",
"(",
"ITurnContext",
"turnContext",
",",
"CancellationToken",
"cancellationToken",
")",
"{",
"foreach",
"(",
"var",
"member",
"in",
"turnContext",
".",
"Activity",
".",
"MembersAdded",
")",
"{",
"if",
"(",
"member",
".",
"Id",
"!=",
"turnContext",
".",
"Activity",
".",
"Recipient",
".",
"Id",
")",
"{",
"await",
"turnContext",
".",
"SendActivityAsync",
"(",
"$\"",
"Welcome to LuisBot ",
"{",
"member",
".",
"Name",
"}",
". ",
"{",
"WelcomeText",
"}",
"\"",
",",
"cancellationToken",
":",
"cancellationToken",
")",
";",
"}",
"}",
"}",
"}"
] |
For each interaction from the user, an instance of this class is created and
the OnTurnAsync method is called.
|
[
"For",
"each",
"interaction",
"from",
"the",
"user",
"an",
"instance",
"of",
"this",
"class",
"is",
"created",
"and",
"the",
"OnTurnAsync",
"method",
"is",
"called",
"."
] |
[
"/// <summary>",
"/// Key in the bot config (.bot file) for the LUIS instance.",
"/// In the .bot file, multiple instances of LUIS can be configured.",
"/// </summary>",
"/// <summary>",
"/// Services configured from the \".bot\" file.",
"/// </summary>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"LuisBot\"/> class.",
"/// </summary>",
"/// <param name=\"services\">Services configured from the \".bot\" file.</param>",
"/// <summary>",
"/// Every conversation turn for our LUIS Bot will call this method.",
"/// There are no dialogs used, the sample only uses \"single turn\" processing,",
"/// meaning a single request and response, with no stateful conversation.",
"/// </summary>",
"/// <param name=\"turnContext\">A <see cref=\"ITurnContext\"/> containing all the data needed",
"/// for processing this conversation turn. </param>",
"/// <param name=\"cancellationToken\">(Optional) A <see cref=\"CancellationToken\"/> that can be used by other objects",
"/// or threads to receive notice of cancellation.</param>",
"/// <returns>A <see cref=\"Task\"/> that represents the work queued to execute.</returns>",
"// Check LUIS model",
"// Send a welcome message to the user and tell them what actions they may perform to use this bot",
"/// <summary>",
"/// On a conversation update activity sent to the bot, the bot will",
"/// send a message to the any new user(s) that were added.",
"/// </summary>",
"/// <param name=\"turnContext\">Provides the <see cref=\"ITurnContext\"/> for the turn of the bot.</param>",
"/// <param name=\"cancellationToken\" >(Optional) A <see cref=\"CancellationToken\"/> that can be used by other objects",
"/// or threads to receive notice of cancellation.</param>",
"/// <returns>>A <see cref=\"Task\"/> representing the operation result of the Turn operation.</returns>"
] |
[
{
"param": "IBot",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IBot",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 18
| 469
| 165
|
2cf87a218c26039a37ffed026d87e08afce02509
|
DallanQ/WeRelateData
|
src/main/java/org/folg/werelatedata/editor/PageEditor.java
|
[
"Apache-2.0"
] |
Java
|
PageEditor
|
/*
* Copyright 2010 Foundation for On-Line Genealogy Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
public class PageEditor {
public static final Pattern EDITTIME_PATTERN = Pattern.compile(
"<input type='hidden' value=\"([^>]*?)\" name=\"wpEdittime\" />");
public static final Pattern STARTTIME_PATTERN = Pattern.compile(
"<input type='hidden' value=\"([^>]*?)\" name=\"wpStarttime\" />");
public static final Pattern EDIT_TOKEN_PATTERN1 = Pattern.compile(
"<input type='hidden' value=['\"]([^>]*?)['\"] name=['\"]wpEditToken['\"] />");
public static final Pattern EDIT_TOKEN_PATTERN2 = Pattern.compile(
"<input type='hidden' name=['\"]wpEditToken['\"] value=['\"]([^>]*?)['\"] />");
public static final Pattern TEXTBOX1_PATTERN = Pattern.compile(
"<textarea[^>]*?name=\"wpTextbox1\"[^>]*>(.*?)</textarea>", Pattern.DOTALL);
private static final String NOT_LOGGED_IN = "sign in</a> to edit pages.";
private static final String STILL_EDITING = "<h1 class=\"firstHeading\">Editing";
private static int MAX_RETRIES = 15;
private static int RETRY_WAIT_MILLIS = 20000;
private static int TIMEOUT_MILLIS = 60000;
private static Logger logger = Logger.getLogger("org.folg.werelatedata.editor");
private static final int BUF_SIZE = 32 * 1024;
private static final int MAX_BUF_SIZE = 64 * 1024 * 1024;
private String baseUrl;
private String agentUsername;
private String agentPassword;
private String mockContents;
private String title;
private String contents;
boolean loggedIn;
protected Map<String, String> variables;
private HttpClient client;
/**
* A PageEditor is used to fetch and update wiki pages
* @param host
* @param agentUsername
* @param agentPassword
*/
public PageEditor(String host, String agentUsername, String agentPassword) {
this.baseUrl = "http://" + host;
this.agentUsername = agentUsername;
this.agentPassword = agentPassword;
this.mockContents = null;
this.title = null;
this.contents = null;
this.loggedIn = false;
this.variables = new HashMap<String, String>();
resetHttpClient();
}
public void resetHttpClient() {
this.client = new HttpClient();
this.client.getParams().setParameter("http.protocol.content-charset", "UTF-8");
this.client.getParams().setParameter("http.socket.timeout", TIMEOUT_MILLIS);
this.client.getParams().setParameter("http.connection.timeout", TIMEOUT_MILLIS);
}
public String getMockContents()
{
return mockContents;
}
/**
* Set mock page contents for testing variable patterns
* @param mockContents
*/
public void setMockContents(String mockContents)
{
this.mockContents = mockContents;
}
/**
* Return full page contents
* @return
*/
public String getContents() {
return this.contents;
}
/**
* Return the page contents matching the specified pattern
* @param p
* @param isRequired if true, throws an exception if variable not found
* @return
*/
public String readVariable(Pattern p, boolean isRequired) {
Matcher m = p.matcher(contents);
if (m.find()) {
return Util.unencodeXML(m.group(1)); // we need to unencode just HTML entities, but this works fine
}
if (isRequired) {
throw new RuntimeException("Pattern not found: " + p + " on page: "+title);
}
return null;
}
public String readVariable(Pattern p) {
return readVariable(p, true);
}
public String readSelectVariable(Pattern p, boolean isRequired) {
Matcher m = p.matcher(contents);
if (m.find()) {
if (m.group(0).contains("</select>")) {
return ""; // no option selected
}
else {
return Util.unencodeXML(m.group(1));
}
}
if (isRequired) {
throw new RuntimeException("Pattern not found: " + p + " on page: "+title);
}
return null;
}
public String readSelectVariable(Pattern p) {
return readSelectVariable(p,true);
}
/**
* Set a variable for posting
* wpStarttime, wpEdittime, wpEditToken, and wpSave are set automatically
* @param var
* @param value
*/
public void setPostVariable(String var, String value) {
variables.put(var, value);
}
private String constructUrl(String title, String action, String extraParams)
{
StringBuilder url = new StringBuilder();
url.append(baseUrl);
url.append("/w/index.php?title=");
try {
url.append(URLEncoder.encode(title, "UTF-8"));
}
catch (UnsupportedEncodingException e) {
// this will never happen
logger.severe("Unsupported encoding exception for UTF-8!?");
}
if (!Util.isEmpty(action)) {
url.append("&action=");
url.append(action);
}
if (!Util.isEmpty(extraParams)) {
url.append("&");
url.append(extraParams);
}
return url.toString();
}
private String getResponse(HttpMethodBase m) throws IOException
{
InputStream s = m.getResponseBodyAsStream();
int bytesRead = -1;
int totalBytes = 0;
int bytesToRead = BUF_SIZE;
byte[] buf = new byte[BUF_SIZE];
while (true) {
bytesRead = s.read(buf, totalBytes, bytesToRead);
if (bytesRead < 0) {
break;
}
totalBytes += bytesRead;
bytesToRead -= bytesRead;
if (bytesToRead == 0) { // buffer full, so allocate more
if (buf.length * 2 > MAX_BUF_SIZE) {
throw new IOException("Response too long: "+m.getURI().toString());
}
byte[] temp = buf;
buf = new byte[temp.length * 2];
System.arraycopy(temp, 0, buf, 0, temp.length);
bytesToRead = temp.length;
}
}
if (totalBytes > 0) {
return EncodingUtil.getString(buf, 0, totalBytes, m.getResponseCharSet());
} else {
return null;
}
}
/**
* Fetch the page
* @param title
* @param edit
*/
public void doGet(String title, boolean edit) {
doGet(title, edit, null);
}
public void doGet(String title, boolean edit, String extraParams) {
this.title = title;
String url = constructUrl(title, edit ? "edit" : null, extraParams);
for (int i = 0; i < MAX_RETRIES; i++) {
if (doGetHttp(url, edit)) {
return;
}
Util.sleep(RETRY_WAIT_MILLIS);
resetHttpClient();
}
throw new RuntimeException("Get failed: " + title);
}
private boolean doGetHttp(String url, boolean edit) {
contents = null;
variables.clear();
if (!loggedIn) {
loggedIn = login();
}
if (!loggedIn) {
logger.severe("Not logged in after login attempt");
return false; // error
}
if (!Util.isEmpty(getMockContents())) {
contents = getMockContents();
}
else {
GetMethod m = new GetMethod(url);
try {
client.executeMethod(m);
if (m.getStatusCode() != 200) {
logger.severe("Unexpected status code on get: " + m.getStatusCode());
return false;
}
else {
contents = getResponse(m);
if(contents.contains(NOT_LOGGED_IN))
{
loggedIn = false;
logger.warning("Not logged in");
return false;
}
}
}
catch (IOException e)
{
logger.warning("IOException on "+ url + " -> " + e);
return false;
}
finally {
m.releaseConnection();
}
}
// set 3 variables
String var = readVariable(EDIT_TOKEN_PATTERN1, false);
if (var == null) var = readVariable(EDIT_TOKEN_PATTERN2, false);
if (var != null) variables.put("wpEditToken", var);
if (edit) {
variables.put("wpEdittime", readVariable(EDITTIME_PATTERN));
variables.put("wpStarttime", readVariable(STARTTIME_PATTERN));
variables.put("wpSave", "Save page");
}
return true;
}
public void doPost() {
doPost("submit", null);
}
public void doPost(String action, String extraParams) {
if (variables.size() > 0) {
String url = constructUrl(title, action, extraParams);
for (int i = 0; i < MAX_RETRIES; i++) {
if (doPostHttp(url)) {
return;
}
Util.sleep(RETRY_WAIT_MILLIS);
resetHttpClient();
}
}
throw new RuntimeException("Post failed: " + title);
}
private boolean doPostHttp(String url) {
if (!loggedIn) {
loggedIn = login();
}
if (!loggedIn) {
logger.severe("Not logged in after login attempt");
return false;
}
PostMethod m = new PostMethod(url);
NameValuePair[] nvps = new NameValuePair[variables.size()];
int i = 0;
for (String name : variables.keySet()) {
String value = variables.get(name);
nvps[i] = new NameValuePair(name, value);
i++;
}
m.setRequestBody(nvps);
try {
client.executeMethod(m);
if (m.getStatusCode() == 302) {
url = m.getResponseHeader("Location").getValue();
m.releaseConnection();
m = new PostMethod(url);
m.setRequestBody(nvps);
client.executeMethod(m);
}
if (m.getStatusCode() != 200) {
logger.severe("Unexpected status code on post: " + m.getStatusCode());
return false;
}
else {
contents = getResponse(m);
if(contents.contains(NOT_LOGGED_IN))
{
loggedIn = false;
logger.warning("Not logged in");
return false;
}
else if (contents.contains(STILL_EDITING)) {
logger.warning("Still editing");
return false;
}
}
}
catch (IOException e)
{
logger.warning("IOException on "+ url + " -> " + e);
return false;
}
finally {
m.releaseConnection();
}
return true;
}
private boolean login() {
String url = constructUrl("Special:Userlogin", "submitlogin", "type=login");
logger.info("Logging in: " + url);
PostMethod m = new PostMethod(url);
NameValuePair [] nvp = {
new NameValuePair("wpName", agentUsername),
new NameValuePair("wpPassword", agentPassword),
new NameValuePair("wpLoginattempt", "Log in")
};
m.setRequestBody(nvp);
try {
client.executeMethod(m);
if (m.getStatusCode() == 302) {
url = m.getResponseHeader("Location").getValue();
m.releaseConnection();
m = new PostMethod(url);
m.setRequestBody(nvp);
client.executeMethod(m);
}
if (m.getStatusCode() != 200) {
logger.severe("Unexpected status code logging in: " + m.getStatusCode());
return false;
}
else {
String returnText = getResponse(m);
if (returnText.indexOf("Login successful") == -1) {
logger.severe("There was a problem logging in. Here is the text:\n\n" + returnText);
return false;
}
}
} catch (IOException e) {
logger.severe("There was an IOException when executing this url: " + url + " -> " + e);
return false;
} finally {
m.releaseConnection();
}
return true;
}
}
|
[
"public",
"class",
"PageEditor",
"{",
"public",
"static",
"final",
"Pattern",
"EDITTIME_PATTERN",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"<input type='hidden' value=",
"\\\"",
"([^>]*?)",
"\\\"",
" name=",
"\\\"",
"wpEdittime",
"\\\"",
" />",
"\"",
")",
";",
"public",
"static",
"final",
"Pattern",
"STARTTIME_PATTERN",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"<input type='hidden' value=",
"\\\"",
"([^>]*?)",
"\\\"",
" name=",
"\\\"",
"wpStarttime",
"\\\"",
" />",
"\"",
")",
";",
"public",
"static",
"final",
"Pattern",
"EDIT_TOKEN_PATTERN1",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"<input type='hidden' value=['",
"\\\"",
"]([^>]*?)['",
"\\\"",
"] name=['",
"\\\"",
"]wpEditToken['",
"\\\"",
"] />",
"\"",
")",
";",
"public",
"static",
"final",
"Pattern",
"EDIT_TOKEN_PATTERN2",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"<input type='hidden' name=['",
"\\\"",
"]wpEditToken['",
"\\\"",
"] value=['",
"\\\"",
"]([^>]*?)['",
"\\\"",
"] />",
"\"",
")",
";",
"public",
"static",
"final",
"Pattern",
"TEXTBOX1_PATTERN",
"=",
"Pattern",
".",
"compile",
"(",
"\"",
"<textarea[^>]*?name=",
"\\\"",
"wpTextbox1",
"\\\"",
"[^>]*>(.*?)</textarea>",
"\"",
",",
"Pattern",
".",
"DOTALL",
")",
";",
"private",
"static",
"final",
"String",
"NOT_LOGGED_IN",
"=",
"\"",
"sign in</a> to edit pages.",
"\"",
";",
"private",
"static",
"final",
"String",
"STILL_EDITING",
"=",
"\"",
"<h1 class=",
"\\\"",
"firstHeading",
"\\\"",
">Editing",
"\"",
";",
"private",
"static",
"int",
"MAX_RETRIES",
"=",
"15",
";",
"private",
"static",
"int",
"RETRY_WAIT_MILLIS",
"=",
"20000",
";",
"private",
"static",
"int",
"TIMEOUT_MILLIS",
"=",
"60000",
";",
"private",
"static",
"Logger",
"logger",
"=",
"Logger",
".",
"getLogger",
"(",
"\"",
"org.folg.werelatedata.editor",
"\"",
")",
";",
"private",
"static",
"final",
"int",
"BUF_SIZE",
"=",
"32",
"*",
"1024",
";",
"private",
"static",
"final",
"int",
"MAX_BUF_SIZE",
"=",
"64",
"*",
"1024",
"*",
"1024",
";",
"private",
"String",
"baseUrl",
";",
"private",
"String",
"agentUsername",
";",
"private",
"String",
"agentPassword",
";",
"private",
"String",
"mockContents",
";",
"private",
"String",
"title",
";",
"private",
"String",
"contents",
";",
"boolean",
"loggedIn",
";",
"protected",
"Map",
"<",
"String",
",",
"String",
">",
"variables",
";",
"private",
"HttpClient",
"client",
";",
"/**\n * A PageEditor is used to fetch and update wiki pages\n * @param host\n * @param agentUsername\n * @param agentPassword\n */",
"public",
"PageEditor",
"(",
"String",
"host",
",",
"String",
"agentUsername",
",",
"String",
"agentPassword",
")",
"{",
"this",
".",
"baseUrl",
"=",
"\"",
"http://",
"\"",
"+",
"host",
";",
"this",
".",
"agentUsername",
"=",
"agentUsername",
";",
"this",
".",
"agentPassword",
"=",
"agentPassword",
";",
"this",
".",
"mockContents",
"=",
"null",
";",
"this",
".",
"title",
"=",
"null",
";",
"this",
".",
"contents",
"=",
"null",
";",
"this",
".",
"loggedIn",
"=",
"false",
";",
"this",
".",
"variables",
"=",
"new",
"HashMap",
"<",
"String",
",",
"String",
">",
"(",
")",
";",
"resetHttpClient",
"(",
")",
";",
"}",
"public",
"void",
"resetHttpClient",
"(",
")",
"{",
"this",
".",
"client",
"=",
"new",
"HttpClient",
"(",
")",
";",
"this",
".",
"client",
".",
"getParams",
"(",
")",
".",
"setParameter",
"(",
"\"",
"http.protocol.content-charset",
"\"",
",",
"\"",
"UTF-8",
"\"",
")",
";",
"this",
".",
"client",
".",
"getParams",
"(",
")",
".",
"setParameter",
"(",
"\"",
"http.socket.timeout",
"\"",
",",
"TIMEOUT_MILLIS",
")",
";",
"this",
".",
"client",
".",
"getParams",
"(",
")",
".",
"setParameter",
"(",
"\"",
"http.connection.timeout",
"\"",
",",
"TIMEOUT_MILLIS",
")",
";",
"}",
"public",
"String",
"getMockContents",
"(",
")",
"{",
"return",
"mockContents",
";",
"}",
"/**\n * Set mock page contents for testing variable patterns\n * @param mockContents\n */",
"public",
"void",
"setMockContents",
"(",
"String",
"mockContents",
")",
"{",
"this",
".",
"mockContents",
"=",
"mockContents",
";",
"}",
"/**\n * Return full page contents\n * @return\n */",
"public",
"String",
"getContents",
"(",
")",
"{",
"return",
"this",
".",
"contents",
";",
"}",
"/**\n * Return the page contents matching the specified pattern\n * @param p\n * @param isRequired if true, throws an exception if variable not found\n * @return\n */",
"public",
"String",
"readVariable",
"(",
"Pattern",
"p",
",",
"boolean",
"isRequired",
")",
"{",
"Matcher",
"m",
"=",
"p",
".",
"matcher",
"(",
"contents",
")",
";",
"if",
"(",
"m",
".",
"find",
"(",
")",
")",
"{",
"return",
"Util",
".",
"unencodeXML",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
";",
"}",
"if",
"(",
"isRequired",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Pattern not found: ",
"\"",
"+",
"p",
"+",
"\"",
" on page: ",
"\"",
"+",
"title",
")",
";",
"}",
"return",
"null",
";",
"}",
"public",
"String",
"readVariable",
"(",
"Pattern",
"p",
")",
"{",
"return",
"readVariable",
"(",
"p",
",",
"true",
")",
";",
"}",
"public",
"String",
"readSelectVariable",
"(",
"Pattern",
"p",
",",
"boolean",
"isRequired",
")",
"{",
"Matcher",
"m",
"=",
"p",
".",
"matcher",
"(",
"contents",
")",
";",
"if",
"(",
"m",
".",
"find",
"(",
")",
")",
"{",
"if",
"(",
"m",
".",
"group",
"(",
"0",
")",
".",
"contains",
"(",
"\"",
"</select>",
"\"",
")",
")",
"{",
"return",
"\"",
"\"",
";",
"}",
"else",
"{",
"return",
"Util",
".",
"unencodeXML",
"(",
"m",
".",
"group",
"(",
"1",
")",
")",
";",
"}",
"}",
"if",
"(",
"isRequired",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Pattern not found: ",
"\"",
"+",
"p",
"+",
"\"",
" on page: ",
"\"",
"+",
"title",
")",
";",
"}",
"return",
"null",
";",
"}",
"public",
"String",
"readSelectVariable",
"(",
"Pattern",
"p",
")",
"{",
"return",
"readSelectVariable",
"(",
"p",
",",
"true",
")",
";",
"}",
"/**\n * Set a variable for posting\n * wpStarttime, wpEdittime, wpEditToken, and wpSave are set automatically\n * @param var\n * @param value\n */",
"public",
"void",
"setPostVariable",
"(",
"String",
"var",
",",
"String",
"value",
")",
"{",
"variables",
".",
"put",
"(",
"var",
",",
"value",
")",
";",
"}",
"private",
"String",
"constructUrl",
"(",
"String",
"title",
",",
"String",
"action",
",",
"String",
"extraParams",
")",
"{",
"StringBuilder",
"url",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"url",
".",
"append",
"(",
"baseUrl",
")",
";",
"url",
".",
"append",
"(",
"\"",
"/w/index.php?title=",
"\"",
")",
";",
"try",
"{",
"url",
".",
"append",
"(",
"URLEncoder",
".",
"encode",
"(",
"title",
",",
"\"",
"UTF-8",
"\"",
")",
")",
";",
"}",
"catch",
"(",
"UnsupportedEncodingException",
"e",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Unsupported encoding exception for UTF-8!?",
"\"",
")",
";",
"}",
"if",
"(",
"!",
"Util",
".",
"isEmpty",
"(",
"action",
")",
")",
"{",
"url",
".",
"append",
"(",
"\"",
"&action=",
"\"",
")",
";",
"url",
".",
"append",
"(",
"action",
")",
";",
"}",
"if",
"(",
"!",
"Util",
".",
"isEmpty",
"(",
"extraParams",
")",
")",
"{",
"url",
".",
"append",
"(",
"\"",
"&",
"\"",
")",
";",
"url",
".",
"append",
"(",
"extraParams",
")",
";",
"}",
"return",
"url",
".",
"toString",
"(",
")",
";",
"}",
"private",
"String",
"getResponse",
"(",
"HttpMethodBase",
"m",
")",
"throws",
"IOException",
"{",
"InputStream",
"s",
"=",
"m",
".",
"getResponseBodyAsStream",
"(",
")",
";",
"int",
"bytesRead",
"=",
"-",
"1",
";",
"int",
"totalBytes",
"=",
"0",
";",
"int",
"bytesToRead",
"=",
"BUF_SIZE",
";",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"BUF_SIZE",
"]",
";",
"while",
"(",
"true",
")",
"{",
"bytesRead",
"=",
"s",
".",
"read",
"(",
"buf",
",",
"totalBytes",
",",
"bytesToRead",
")",
";",
"if",
"(",
"bytesRead",
"<",
"0",
")",
"{",
"break",
";",
"}",
"totalBytes",
"+=",
"bytesRead",
";",
"bytesToRead",
"-=",
"bytesRead",
";",
"if",
"(",
"bytesToRead",
"==",
"0",
")",
"{",
"if",
"(",
"buf",
".",
"length",
"*",
"2",
">",
"MAX_BUF_SIZE",
")",
"{",
"throw",
"new",
"IOException",
"(",
"\"",
"Response too long: ",
"\"",
"+",
"m",
".",
"getURI",
"(",
")",
".",
"toString",
"(",
")",
")",
";",
"}",
"byte",
"[",
"]",
"temp",
"=",
"buf",
";",
"buf",
"=",
"new",
"byte",
"[",
"temp",
".",
"length",
"*",
"2",
"]",
";",
"System",
".",
"arraycopy",
"(",
"temp",
",",
"0",
",",
"buf",
",",
"0",
",",
"temp",
".",
"length",
")",
";",
"bytesToRead",
"=",
"temp",
".",
"length",
";",
"}",
"}",
"if",
"(",
"totalBytes",
">",
"0",
")",
"{",
"return",
"EncodingUtil",
".",
"getString",
"(",
"buf",
",",
"0",
",",
"totalBytes",
",",
"m",
".",
"getResponseCharSet",
"(",
")",
")",
";",
"}",
"else",
"{",
"return",
"null",
";",
"}",
"}",
"/**\n * Fetch the page\n * @param title\n * @param edit\n */",
"public",
"void",
"doGet",
"(",
"String",
"title",
",",
"boolean",
"edit",
")",
"{",
"doGet",
"(",
"title",
",",
"edit",
",",
"null",
")",
";",
"}",
"public",
"void",
"doGet",
"(",
"String",
"title",
",",
"boolean",
"edit",
",",
"String",
"extraParams",
")",
"{",
"this",
".",
"title",
"=",
"title",
";",
"String",
"url",
"=",
"constructUrl",
"(",
"title",
",",
"edit",
"?",
"\"",
"edit",
"\"",
":",
"null",
",",
"extraParams",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"MAX_RETRIES",
";",
"i",
"++",
")",
"{",
"if",
"(",
"doGetHttp",
"(",
"url",
",",
"edit",
")",
")",
"{",
"return",
";",
"}",
"Util",
".",
"sleep",
"(",
"RETRY_WAIT_MILLIS",
")",
";",
"resetHttpClient",
"(",
")",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Get failed: ",
"\"",
"+",
"title",
")",
";",
"}",
"private",
"boolean",
"doGetHttp",
"(",
"String",
"url",
",",
"boolean",
"edit",
")",
"{",
"contents",
"=",
"null",
";",
"variables",
".",
"clear",
"(",
")",
";",
"if",
"(",
"!",
"loggedIn",
")",
"{",
"loggedIn",
"=",
"login",
"(",
")",
";",
"}",
"if",
"(",
"!",
"loggedIn",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Not logged in after login attempt",
"\"",
")",
";",
"return",
"false",
";",
"}",
"if",
"(",
"!",
"Util",
".",
"isEmpty",
"(",
"getMockContents",
"(",
")",
")",
")",
"{",
"contents",
"=",
"getMockContents",
"(",
")",
";",
"}",
"else",
"{",
"GetMethod",
"m",
"=",
"new",
"GetMethod",
"(",
"url",
")",
";",
"try",
"{",
"client",
".",
"executeMethod",
"(",
"m",
")",
";",
"if",
"(",
"m",
".",
"getStatusCode",
"(",
")",
"!=",
"200",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Unexpected status code on get: ",
"\"",
"+",
"m",
".",
"getStatusCode",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"contents",
"=",
"getResponse",
"(",
"m",
")",
";",
"if",
"(",
"contents",
".",
"contains",
"(",
"NOT_LOGGED_IN",
")",
")",
"{",
"loggedIn",
"=",
"false",
";",
"logger",
".",
"warning",
"(",
"\"",
"Not logged in",
"\"",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"warning",
"(",
"\"",
"IOException on ",
"\"",
"+",
"url",
"+",
"\"",
" -> ",
"\"",
"+",
"e",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"m",
".",
"releaseConnection",
"(",
")",
";",
"}",
"}",
"String",
"var",
"=",
"readVariable",
"(",
"EDIT_TOKEN_PATTERN1",
",",
"false",
")",
";",
"if",
"(",
"var",
"==",
"null",
")",
"var",
"=",
"readVariable",
"(",
"EDIT_TOKEN_PATTERN2",
",",
"false",
")",
";",
"if",
"(",
"var",
"!=",
"null",
")",
"variables",
".",
"put",
"(",
"\"",
"wpEditToken",
"\"",
",",
"var",
")",
";",
"if",
"(",
"edit",
")",
"{",
"variables",
".",
"put",
"(",
"\"",
"wpEdittime",
"\"",
",",
"readVariable",
"(",
"EDITTIME_PATTERN",
")",
")",
";",
"variables",
".",
"put",
"(",
"\"",
"wpStarttime",
"\"",
",",
"readVariable",
"(",
"STARTTIME_PATTERN",
")",
")",
";",
"variables",
".",
"put",
"(",
"\"",
"wpSave",
"\"",
",",
"\"",
"Save page",
"\"",
")",
";",
"}",
"return",
"true",
";",
"}",
"public",
"void",
"doPost",
"(",
")",
"{",
"doPost",
"(",
"\"",
"submit",
"\"",
",",
"null",
")",
";",
"}",
"public",
"void",
"doPost",
"(",
"String",
"action",
",",
"String",
"extraParams",
")",
"{",
"if",
"(",
"variables",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"String",
"url",
"=",
"constructUrl",
"(",
"title",
",",
"action",
",",
"extraParams",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"MAX_RETRIES",
";",
"i",
"++",
")",
"{",
"if",
"(",
"doPostHttp",
"(",
"url",
")",
")",
"{",
"return",
";",
"}",
"Util",
".",
"sleep",
"(",
"RETRY_WAIT_MILLIS",
")",
";",
"resetHttpClient",
"(",
")",
";",
"}",
"}",
"throw",
"new",
"RuntimeException",
"(",
"\"",
"Post failed: ",
"\"",
"+",
"title",
")",
";",
"}",
"private",
"boolean",
"doPostHttp",
"(",
"String",
"url",
")",
"{",
"if",
"(",
"!",
"loggedIn",
")",
"{",
"loggedIn",
"=",
"login",
"(",
")",
";",
"}",
"if",
"(",
"!",
"loggedIn",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Not logged in after login attempt",
"\"",
")",
";",
"return",
"false",
";",
"}",
"PostMethod",
"m",
"=",
"new",
"PostMethod",
"(",
"url",
")",
";",
"NameValuePair",
"[",
"]",
"nvps",
"=",
"new",
"NameValuePair",
"[",
"variables",
".",
"size",
"(",
")",
"]",
";",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"String",
"name",
":",
"variables",
".",
"keySet",
"(",
")",
")",
"{",
"String",
"value",
"=",
"variables",
".",
"get",
"(",
"name",
")",
";",
"nvps",
"[",
"i",
"]",
"=",
"new",
"NameValuePair",
"(",
"name",
",",
"value",
")",
";",
"i",
"++",
";",
"}",
"m",
".",
"setRequestBody",
"(",
"nvps",
")",
";",
"try",
"{",
"client",
".",
"executeMethod",
"(",
"m",
")",
";",
"if",
"(",
"m",
".",
"getStatusCode",
"(",
")",
"==",
"302",
")",
"{",
"url",
"=",
"m",
".",
"getResponseHeader",
"(",
"\"",
"Location",
"\"",
")",
".",
"getValue",
"(",
")",
";",
"m",
".",
"releaseConnection",
"(",
")",
";",
"m",
"=",
"new",
"PostMethod",
"(",
"url",
")",
";",
"m",
".",
"setRequestBody",
"(",
"nvps",
")",
";",
"client",
".",
"executeMethod",
"(",
"m",
")",
";",
"}",
"if",
"(",
"m",
".",
"getStatusCode",
"(",
")",
"!=",
"200",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Unexpected status code on post: ",
"\"",
"+",
"m",
".",
"getStatusCode",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"contents",
"=",
"getResponse",
"(",
"m",
")",
";",
"if",
"(",
"contents",
".",
"contains",
"(",
"NOT_LOGGED_IN",
")",
")",
"{",
"loggedIn",
"=",
"false",
";",
"logger",
".",
"warning",
"(",
"\"",
"Not logged in",
"\"",
")",
";",
"return",
"false",
";",
"}",
"else",
"if",
"(",
"contents",
".",
"contains",
"(",
"STILL_EDITING",
")",
")",
"{",
"logger",
".",
"warning",
"(",
"\"",
"Still editing",
"\"",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"warning",
"(",
"\"",
"IOException on ",
"\"",
"+",
"url",
"+",
"\"",
" -> ",
"\"",
"+",
"e",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"m",
".",
"releaseConnection",
"(",
")",
";",
"}",
"return",
"true",
";",
"}",
"private",
"boolean",
"login",
"(",
")",
"{",
"String",
"url",
"=",
"constructUrl",
"(",
"\"",
"Special:Userlogin",
"\"",
",",
"\"",
"submitlogin",
"\"",
",",
"\"",
"type=login",
"\"",
")",
";",
"logger",
".",
"info",
"(",
"\"",
"Logging in: ",
"\"",
"+",
"url",
")",
";",
"PostMethod",
"m",
"=",
"new",
"PostMethod",
"(",
"url",
")",
";",
"NameValuePair",
"[",
"]",
"nvp",
"=",
"{",
"new",
"NameValuePair",
"(",
"\"",
"wpName",
"\"",
",",
"agentUsername",
")",
",",
"new",
"NameValuePair",
"(",
"\"",
"wpPassword",
"\"",
",",
"agentPassword",
")",
",",
"new",
"NameValuePair",
"(",
"\"",
"wpLoginattempt",
"\"",
",",
"\"",
"Log in",
"\"",
")",
"}",
";",
"m",
".",
"setRequestBody",
"(",
"nvp",
")",
";",
"try",
"{",
"client",
".",
"executeMethod",
"(",
"m",
")",
";",
"if",
"(",
"m",
".",
"getStatusCode",
"(",
")",
"==",
"302",
")",
"{",
"url",
"=",
"m",
".",
"getResponseHeader",
"(",
"\"",
"Location",
"\"",
")",
".",
"getValue",
"(",
")",
";",
"m",
".",
"releaseConnection",
"(",
")",
";",
"m",
"=",
"new",
"PostMethod",
"(",
"url",
")",
";",
"m",
".",
"setRequestBody",
"(",
"nvp",
")",
";",
"client",
".",
"executeMethod",
"(",
"m",
")",
";",
"}",
"if",
"(",
"m",
".",
"getStatusCode",
"(",
")",
"!=",
"200",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"Unexpected status code logging in: ",
"\"",
"+",
"m",
".",
"getStatusCode",
"(",
")",
")",
";",
"return",
"false",
";",
"}",
"else",
"{",
"String",
"returnText",
"=",
"getResponse",
"(",
"m",
")",
";",
"if",
"(",
"returnText",
".",
"indexOf",
"(",
"\"",
"Login successful",
"\"",
")",
"==",
"-",
"1",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"There was a problem logging in. Here is the text:",
"\\n",
"\\n",
"\"",
"+",
"returnText",
")",
";",
"return",
"false",
";",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"logger",
".",
"severe",
"(",
"\"",
"There was an IOException when executing this url: ",
"\"",
"+",
"url",
"+",
"\"",
" -> ",
"\"",
"+",
"e",
")",
";",
"return",
"false",
";",
"}",
"finally",
"{",
"m",
".",
"releaseConnection",
"(",
")",
";",
"}",
"return",
"true",
";",
"}",
"}"
] |
Copyright 2010 Foundation for On-Line Genealogy Inc.
|
[
"Copyright",
"2010",
"Foundation",
"for",
"On",
"-",
"Line",
"Genealogy",
"Inc",
"."
] |
[
"// we need to unencode just HTML entities, but this works fine",
"// no option selected",
"// this will never happen",
"// buffer full, so allocate more",
"// error",
"// set 3 variables"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 2,640
| 140
|
47c9afafb30d1e50b8edc02920286a2d5425572b
|
odellus/proteus
|
proteus/WaveTools.py
|
[
"NASA-1.3"
] |
Python
|
directionalWaves
|
Generate approximate directiona random wave solutions
:param Tp: peak period [T]
:param Hs: significant wave height [L]
:param d: depth [L]
:param fp: frequency [1/T]
:param bandFactor: width factor for band around fp [-]
:param N: number of frequency bins [-]
:param mwl: mean water level [L]
|
Generate approximate directiona random wave solutions
|
[
"Generate",
"approximate",
"directiona",
"random",
"wave",
"solutions"
] |
class directionalWaves:
"""Generate approximate directiona random wave solutions
:param Tp: peak period [T]
:param Hs: significant wave height [L]
:param d: depth [L]
:param fp: frequency [1/T]
:param bandFactor: width factor for band around fp [-]
:param N: number of frequency bins [-]
:param mwl: mean water level [L]"""
def __init__(self,
Tp , #s peak period
Hs , #m significant wave height
d , #m depth
fp , #peak frequency
bandFactor, #controls width of band around fp
N , #number of frequency bins
M , #half number of directional bins
mwl, #mean water level
waveDir, #main wave direction
normalWaveDir,# Normal to wave direction, on propagation plane
g, #accelerationof gravity
spec_fun , # spectral function
thetamax = pi, #max directional band, measured from lead wave direction, defaults to pi
s =5 , # dir function coefficient
dir_fun = cos2s # directional function
): #wave spectrum
self.waveDir = waveDir/sqrt(sum(waveDir * waveDir))
self.normalWaveDir = normalWaveDir/sqrt(sum(normalWaveDir * normalWaveDir))
self.g = g
self.gAbs = sqrt(sum(g * g))
self.Tp = Tp
self.Hs = Hs
self.d = d
self.fp = fp
self.bandFactor = bandFactor
self.N = N
self.mwl = mwl
self.fmax = self.bandFactor*self.fp
self.fmin = self.fp/self.bandFactor
self.df = (self.fmax-self.fmin)/float(self.N-1)
self.fi=np.zeros(self.N,'d')
for i in range(self.N):
self.fi[i] = self.fmin+self.df*i
self.ki = dispersion(2.0*pi*self.fi,self.d,g=self.gAbs)
self.wi = 2.*math.pi/self.ki
#ai = np.sqrt((Si_J[1:]+Si_J[:-1])*(fi[1:]-fi[:-1]))
fim_tmp = (0.5*(self.fi[1:]+self.fi[:-1])).tolist()
self.fim = np.array([fim_tmp[0]-0.5*self.df]+fim_tmp+[fim_tmp[-1]+0.5*self.df])
self.Si_Jm = spec_fun(self.fim,f0=self.fp,Hs=self.Hs,g=self.g,gamma=3.3)
self.ai = np.sqrt((self.Si_Jm[1:]+self.Si_Jm[:-1])*(self.fim[1:]-self.fim[:-1]))
self.waves = MonochromaticWaves
self.M = M
self.thetas = np.linspace(0,thetamax,self.M+1)
self.dth = thetas[1]-thetas[0]
self.spread = dir_fun(thetas,s)
self.dirs = zeros((2*self.M + 1,3),'d')
self.ai_d = zeros((self.N,2*M+1),'d')
self.phi = zeros((self.N,2*M+1),'d')
self.G_Int = normInt(self.dth,self.dir_fun,s,self.M+1)
for ii in range(1,self.M+1):
self.dirs[self.M+ii,:]= cos(self.thetas[ii])*waveDir + sin(self.thetas[ii])*normalWaveDir
self.dirs[self.M-ii,:] = cos(self.thetas[ii])*waveDir - sin(self.thetas[ii])*normalWaveDir
self.ai_d[self.M+ii,:] = self.ai*self.G_Int*spread[ii]
self.ai_d[self.M-ii,:] = self.ai*self.G_Int*spread[ii]
self.phi[self.M+ii,:] = 2.0*pi*np.random.random(self.fi.shape[0])
self.phi[self.M-ii,:] = 2.0*pi*np.random.random(self.fi.shape[0])
self.dirs[self.M,:] = self.waveDir
self.phi[self.M,:] = 2.0*pi*np.random.random(self.fi.shape[0])
self.ai_d[self.M,:] = self.ai*self.G_Int*spread[0]
def eta(self,x,y,z,t):
"""Free surface displacement
:param x: floating point x coordinate
:param t: time"""
Eta=0.
for jj in range(2*self.M + 1):
for ii in range(self.N):
Eta+=waves(period = 1./self.fi[ii], waveHeight = 2.*self.ai[ii,jj],mwl = self.mwl, depth = self.d,g = self.g,waveDir = self.dirs[ii,jj],wavelength=wi[ii], phi0 = self.phi[ii,jj]).eta(x,y,z,t)
return Eta
# return (self.ai*np.cos(2.0*pi*self.fi*t - self.ki*x + self.phi)).sum()
def u(self,x,z,t):
"""x-component of velocity
:param x: floating point x coordinate
:param z: floating point z coordinate (height above bottom)
:param t: time
"""
U=0.
for jj in range(2*self.M + 1):
for ii in range(self.N):
U+=waves(period = 1./self.fi[ii], waveHeight = 2.*self.ai[ii,jj],mwl = self.mwl, depth = self.d,g = self.g,waveDir = self.dirs[ii,jj],wavelength=wi[ii], phi0 = self.phi[ii,jj]).u(x,y,z,t)
return U
def v(self,x,z,t):
"""x-component of velocity
:param x: floating point x coordinate
:param z: floating point z coordinate (height above bottom)
:param t: time
"""
V=0.
for jj in range(2*self.M + 1):
for ii in range(self.N):
V+=waves(period = 1./self.fi[ii], waveHeight = 2.*self.ai[ii,jj],mwl = self.mwl, depth = self.d,g = self.g,waveDir = self.dirs[ii,jj],wavelength=wi[ii], phi0 = self.phi[ii,jj]).v(x,y,z,t)
return V
def w(self,x,z,t):
"""x-component of velocity
:param x: floating point x coordinate
:param z: floating point z coordinate (height above bottom)
:param t: time
"""
W=0.
for jj in range(2*self.M + 1):
for ii in range(self.N):
W+=waves(period = 1./self.fi[ii], waveHeight = 2.*self.ai[ii,jj],mwl = self.mwl, depth = self.d,g = self.g,waveDir = self.dirs[ii,jj],wavelength=wi[ii], phi0 = self.phi[ii,jj]).w(x,y,z,t)
return W
|
[
"class",
"directionalWaves",
":",
"def",
"__init__",
"(",
"self",
",",
"Tp",
",",
"Hs",
",",
"d",
",",
"fp",
",",
"bandFactor",
",",
"N",
",",
"M",
",",
"mwl",
",",
"waveDir",
",",
"normalWaveDir",
",",
"g",
",",
"spec_fun",
",",
"thetamax",
"=",
"pi",
",",
"s",
"=",
"5",
",",
"dir_fun",
"=",
"cos2s",
")",
":",
"self",
".",
"waveDir",
"=",
"waveDir",
"/",
"sqrt",
"(",
"sum",
"(",
"waveDir",
"*",
"waveDir",
")",
")",
"self",
".",
"normalWaveDir",
"=",
"normalWaveDir",
"/",
"sqrt",
"(",
"sum",
"(",
"normalWaveDir",
"*",
"normalWaveDir",
")",
")",
"self",
".",
"g",
"=",
"g",
"self",
".",
"gAbs",
"=",
"sqrt",
"(",
"sum",
"(",
"g",
"*",
"g",
")",
")",
"self",
".",
"Tp",
"=",
"Tp",
"self",
".",
"Hs",
"=",
"Hs",
"self",
".",
"d",
"=",
"d",
"self",
".",
"fp",
"=",
"fp",
"self",
".",
"bandFactor",
"=",
"bandFactor",
"self",
".",
"N",
"=",
"N",
"self",
".",
"mwl",
"=",
"mwl",
"self",
".",
"fmax",
"=",
"self",
".",
"bandFactor",
"*",
"self",
".",
"fp",
"self",
".",
"fmin",
"=",
"self",
".",
"fp",
"/",
"self",
".",
"bandFactor",
"self",
".",
"df",
"=",
"(",
"self",
".",
"fmax",
"-",
"self",
".",
"fmin",
")",
"/",
"float",
"(",
"self",
".",
"N",
"-",
"1",
")",
"self",
".",
"fi",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"N",
",",
"'d'",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"self",
".",
"fi",
"[",
"i",
"]",
"=",
"self",
".",
"fmin",
"+",
"self",
".",
"df",
"*",
"i",
"self",
".",
"ki",
"=",
"dispersion",
"(",
"2.0",
"*",
"pi",
"*",
"self",
".",
"fi",
",",
"self",
".",
"d",
",",
"g",
"=",
"self",
".",
"gAbs",
")",
"self",
".",
"wi",
"=",
"2.",
"*",
"math",
".",
"pi",
"/",
"self",
".",
"ki",
"fim_tmp",
"=",
"(",
"0.5",
"*",
"(",
"self",
".",
"fi",
"[",
"1",
":",
"]",
"+",
"self",
".",
"fi",
"[",
":",
"-",
"1",
"]",
")",
")",
".",
"tolist",
"(",
")",
"self",
".",
"fim",
"=",
"np",
".",
"array",
"(",
"[",
"fim_tmp",
"[",
"0",
"]",
"-",
"0.5",
"*",
"self",
".",
"df",
"]",
"+",
"fim_tmp",
"+",
"[",
"fim_tmp",
"[",
"-",
"1",
"]",
"+",
"0.5",
"*",
"self",
".",
"df",
"]",
")",
"self",
".",
"Si_Jm",
"=",
"spec_fun",
"(",
"self",
".",
"fim",
",",
"f0",
"=",
"self",
".",
"fp",
",",
"Hs",
"=",
"self",
".",
"Hs",
",",
"g",
"=",
"self",
".",
"g",
",",
"gamma",
"=",
"3.3",
")",
"self",
".",
"ai",
"=",
"np",
".",
"sqrt",
"(",
"(",
"self",
".",
"Si_Jm",
"[",
"1",
":",
"]",
"+",
"self",
".",
"Si_Jm",
"[",
":",
"-",
"1",
"]",
")",
"*",
"(",
"self",
".",
"fim",
"[",
"1",
":",
"]",
"-",
"self",
".",
"fim",
"[",
":",
"-",
"1",
"]",
")",
")",
"self",
".",
"waves",
"=",
"MonochromaticWaves",
"self",
".",
"M",
"=",
"M",
"self",
".",
"thetas",
"=",
"np",
".",
"linspace",
"(",
"0",
",",
"thetamax",
",",
"self",
".",
"M",
"+",
"1",
")",
"self",
".",
"dth",
"=",
"thetas",
"[",
"1",
"]",
"-",
"thetas",
"[",
"0",
"]",
"self",
".",
"spread",
"=",
"dir_fun",
"(",
"thetas",
",",
"s",
")",
"self",
".",
"dirs",
"=",
"zeros",
"(",
"(",
"2",
"*",
"self",
".",
"M",
"+",
"1",
",",
"3",
")",
",",
"'d'",
")",
"self",
".",
"ai_d",
"=",
"zeros",
"(",
"(",
"self",
".",
"N",
",",
"2",
"*",
"M",
"+",
"1",
")",
",",
"'d'",
")",
"self",
".",
"phi",
"=",
"zeros",
"(",
"(",
"self",
".",
"N",
",",
"2",
"*",
"M",
"+",
"1",
")",
",",
"'d'",
")",
"self",
".",
"G_Int",
"=",
"normInt",
"(",
"self",
".",
"dth",
",",
"self",
".",
"dir_fun",
",",
"s",
",",
"self",
".",
"M",
"+",
"1",
")",
"for",
"ii",
"in",
"range",
"(",
"1",
",",
"self",
".",
"M",
"+",
"1",
")",
":",
"self",
".",
"dirs",
"[",
"self",
".",
"M",
"+",
"ii",
",",
":",
"]",
"=",
"cos",
"(",
"self",
".",
"thetas",
"[",
"ii",
"]",
")",
"*",
"waveDir",
"+",
"sin",
"(",
"self",
".",
"thetas",
"[",
"ii",
"]",
")",
"*",
"normalWaveDir",
"self",
".",
"dirs",
"[",
"self",
".",
"M",
"-",
"ii",
",",
":",
"]",
"=",
"cos",
"(",
"self",
".",
"thetas",
"[",
"ii",
"]",
")",
"*",
"waveDir",
"-",
"sin",
"(",
"self",
".",
"thetas",
"[",
"ii",
"]",
")",
"*",
"normalWaveDir",
"self",
".",
"ai_d",
"[",
"self",
".",
"M",
"+",
"ii",
",",
":",
"]",
"=",
"self",
".",
"ai",
"*",
"self",
".",
"G_Int",
"*",
"spread",
"[",
"ii",
"]",
"self",
".",
"ai_d",
"[",
"self",
".",
"M",
"-",
"ii",
",",
":",
"]",
"=",
"self",
".",
"ai",
"*",
"self",
".",
"G_Int",
"*",
"spread",
"[",
"ii",
"]",
"self",
".",
"phi",
"[",
"self",
".",
"M",
"+",
"ii",
",",
":",
"]",
"=",
"2.0",
"*",
"pi",
"*",
"np",
".",
"random",
".",
"random",
"(",
"self",
".",
"fi",
".",
"shape",
"[",
"0",
"]",
")",
"self",
".",
"phi",
"[",
"self",
".",
"M",
"-",
"ii",
",",
":",
"]",
"=",
"2.0",
"*",
"pi",
"*",
"np",
".",
"random",
".",
"random",
"(",
"self",
".",
"fi",
".",
"shape",
"[",
"0",
"]",
")",
"self",
".",
"dirs",
"[",
"self",
".",
"M",
",",
":",
"]",
"=",
"self",
".",
"waveDir",
"self",
".",
"phi",
"[",
"self",
".",
"M",
",",
":",
"]",
"=",
"2.0",
"*",
"pi",
"*",
"np",
".",
"random",
".",
"random",
"(",
"self",
".",
"fi",
".",
"shape",
"[",
"0",
"]",
")",
"self",
".",
"ai_d",
"[",
"self",
".",
"M",
",",
":",
"]",
"=",
"self",
".",
"ai",
"*",
"self",
".",
"G_Int",
"*",
"spread",
"[",
"0",
"]",
"def",
"eta",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"t",
")",
":",
"\"\"\"Free surface displacement\n \n :param x: floating point x coordinate\n :param t: time\"\"\"",
"Eta",
"=",
"0.",
"for",
"jj",
"in",
"range",
"(",
"2",
"*",
"self",
".",
"M",
"+",
"1",
")",
":",
"for",
"ii",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"Eta",
"+=",
"waves",
"(",
"period",
"=",
"1.",
"/",
"self",
".",
"fi",
"[",
"ii",
"]",
",",
"waveHeight",
"=",
"2.",
"*",
"self",
".",
"ai",
"[",
"ii",
",",
"jj",
"]",
",",
"mwl",
"=",
"self",
".",
"mwl",
",",
"depth",
"=",
"self",
".",
"d",
",",
"g",
"=",
"self",
".",
"g",
",",
"waveDir",
"=",
"self",
".",
"dirs",
"[",
"ii",
",",
"jj",
"]",
",",
"wavelength",
"=",
"wi",
"[",
"ii",
"]",
",",
"phi0",
"=",
"self",
".",
"phi",
"[",
"ii",
",",
"jj",
"]",
")",
".",
"eta",
"(",
"x",
",",
"y",
",",
"z",
",",
"t",
")",
"return",
"Eta",
"def",
"u",
"(",
"self",
",",
"x",
",",
"z",
",",
"t",
")",
":",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\"",
"U",
"=",
"0.",
"for",
"jj",
"in",
"range",
"(",
"2",
"*",
"self",
".",
"M",
"+",
"1",
")",
":",
"for",
"ii",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"U",
"+=",
"waves",
"(",
"period",
"=",
"1.",
"/",
"self",
".",
"fi",
"[",
"ii",
"]",
",",
"waveHeight",
"=",
"2.",
"*",
"self",
".",
"ai",
"[",
"ii",
",",
"jj",
"]",
",",
"mwl",
"=",
"self",
".",
"mwl",
",",
"depth",
"=",
"self",
".",
"d",
",",
"g",
"=",
"self",
".",
"g",
",",
"waveDir",
"=",
"self",
".",
"dirs",
"[",
"ii",
",",
"jj",
"]",
",",
"wavelength",
"=",
"wi",
"[",
"ii",
"]",
",",
"phi0",
"=",
"self",
".",
"phi",
"[",
"ii",
",",
"jj",
"]",
")",
".",
"u",
"(",
"x",
",",
"y",
",",
"z",
",",
"t",
")",
"return",
"U",
"def",
"v",
"(",
"self",
",",
"x",
",",
"z",
",",
"t",
")",
":",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\"",
"V",
"=",
"0.",
"for",
"jj",
"in",
"range",
"(",
"2",
"*",
"self",
".",
"M",
"+",
"1",
")",
":",
"for",
"ii",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"V",
"+=",
"waves",
"(",
"period",
"=",
"1.",
"/",
"self",
".",
"fi",
"[",
"ii",
"]",
",",
"waveHeight",
"=",
"2.",
"*",
"self",
".",
"ai",
"[",
"ii",
",",
"jj",
"]",
",",
"mwl",
"=",
"self",
".",
"mwl",
",",
"depth",
"=",
"self",
".",
"d",
",",
"g",
"=",
"self",
".",
"g",
",",
"waveDir",
"=",
"self",
".",
"dirs",
"[",
"ii",
",",
"jj",
"]",
",",
"wavelength",
"=",
"wi",
"[",
"ii",
"]",
",",
"phi0",
"=",
"self",
".",
"phi",
"[",
"ii",
",",
"jj",
"]",
")",
".",
"v",
"(",
"x",
",",
"y",
",",
"z",
",",
"t",
")",
"return",
"V",
"def",
"w",
"(",
"self",
",",
"x",
",",
"z",
",",
"t",
")",
":",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\"",
"W",
"=",
"0.",
"for",
"jj",
"in",
"range",
"(",
"2",
"*",
"self",
".",
"M",
"+",
"1",
")",
":",
"for",
"ii",
"in",
"range",
"(",
"self",
".",
"N",
")",
":",
"W",
"+=",
"waves",
"(",
"period",
"=",
"1.",
"/",
"self",
".",
"fi",
"[",
"ii",
"]",
",",
"waveHeight",
"=",
"2.",
"*",
"self",
".",
"ai",
"[",
"ii",
",",
"jj",
"]",
",",
"mwl",
"=",
"self",
".",
"mwl",
",",
"depth",
"=",
"self",
".",
"d",
",",
"g",
"=",
"self",
".",
"g",
",",
"waveDir",
"=",
"self",
".",
"dirs",
"[",
"ii",
",",
"jj",
"]",
",",
"wavelength",
"=",
"wi",
"[",
"ii",
"]",
",",
"phi0",
"=",
"self",
".",
"phi",
"[",
"ii",
",",
"jj",
"]",
")",
".",
"w",
"(",
"x",
",",
"y",
",",
"z",
",",
"t",
")",
"return",
"W"
] |
Generate approximate directiona random wave solutions
|
[
"Generate",
"approximate",
"directiona",
"random",
"wave",
"solutions"
] |
[
"\"\"\"Generate approximate directiona random wave solutions\n\n :param Tp: peak period [T]\n :param Hs: significant wave height [L]\n :param d: depth [L]\n :param fp: frequency [1/T]\n :param bandFactor: width factor for band around fp [-]\n :param N: number of frequency bins [-]\n :param mwl: mean water level [L]\"\"\"",
"#s peak period",
"#m significant wave height",
"#m depth",
"#peak frequency",
"#controls width of band around fp",
"#number of frequency bins",
"#half number of directional bins",
"#mean water level",
"#main wave direction",
"# Normal to wave direction, on propagation plane",
"#accelerationof gravity",
"# spectral function",
"#max directional band, measured from lead wave direction, defaults to pi",
"# dir function coefficient",
"# directional function",
"#wave spectrum",
"#ai = np.sqrt((Si_J[1:]+Si_J[:-1])*(fi[1:]-fi[:-1]))",
"\"\"\"Free surface displacement\n \n :param x: floating point x coordinate\n :param t: time\"\"\"",
"# return (self.ai*np.cos(2.0*pi*self.fi*t - self.ki*x + self.phi)).sum()",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\"",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\"",
"\"\"\"x-component of velocity\n\n :param x: floating point x coordinate\n :param z: floating point z coordinate (height above bottom)\n :param t: time\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [
{
"identifier": "Tp",
"type": null,
"docstring": "peak period [T]",
"docstring_tokens": [
"peak",
"period",
"[",
"T",
"]"
],
"default": null,
"is_optional": null
},
{
"identifier": "Hs",
"type": null,
"docstring": "significant wave height [L]",
"docstring_tokens": [
"significant",
"wave",
"height",
"[",
"L",
"]"
],
"default": null,
"is_optional": null
},
{
"identifier": "d",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
},
{
"identifier": "fp",
"type": null,
"docstring": null,
"docstring_tokens": [
"None"
],
"default": null,
"is_optional": null
},
{
"identifier": "bandFactor",
"type": null,
"docstring": "width factor for band around fp [-]",
"docstring_tokens": [
"width",
"factor",
"for",
"band",
"around",
"fp",
"[",
"-",
"]"
],
"default": null,
"is_optional": null
},
{
"identifier": "N",
"type": null,
"docstring": "number of frequency bins [-]",
"docstring_tokens": [
"number",
"of",
"frequency",
"bins",
"[",
"-",
"]"
],
"default": null,
"is_optional": null
},
{
"identifier": "mwl",
"type": null,
"docstring": "mean water level [L]",
"docstring_tokens": [
"mean",
"water",
"level",
"[",
"L",
"]"
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 19
| 1,604
| 89
|
737997e2779dc3787aeb58b96e9869d6e905ff62
|
daxnet/guluwin
|
SunnyChen.Gulu.Gulus/BasicFileOperations/PermanentDelete/Gulu.cs
|
[
"MIT"
] |
C#
|
Gulu
|
/// <summary>
/// The permanent delete gulu is used for deleting files permanently.
/// Before the action is going to be taken, a dialog box will appear
/// to let user input "OK" so that the deleting operation is absolutely
/// confirmed. This is because that the operation doesn't require the
/// backup of the original files and this operation cannot be rollback.
/// </summary>
|
The permanent delete gulu is used for deleting files permanently.
Before the action is going to be taken, a dialog box will appear
to let user input "OK" so that the deleting operation is absolutely
confirmed. This is because that the operation doesn't require the
backup of the original files and this operation cannot be rollback.
|
[
"The",
"permanent",
"delete",
"gulu",
"is",
"used",
"for",
"deleting",
"files",
"permanently",
".",
"Before",
"the",
"action",
"is",
"going",
"to",
"be",
"taken",
"a",
"dialog",
"box",
"will",
"appear",
"to",
"let",
"user",
"input",
"\"",
"OK",
"\"",
"so",
"that",
"the",
"deleting",
"operation",
"is",
"absolutely",
"confirmed",
".",
"This",
"is",
"because",
"that",
"the",
"operation",
"doesn",
"'",
"t",
"require",
"the",
"backup",
"of",
"the",
"original",
"files",
"and",
"this",
"operation",
"cannot",
"be",
"rollback",
"."
] |
[Gulu]
public sealed class Gulu : GuluBase
{
#region Private Fields
private const int BlockSize = 102400;
private char[] block__ = new char[BlockSize];
private long numOfBlocks__;
private long remaining__;
#endregion
#region Constructors
public Gulu()
{
Resources.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
Array.Clear(block__, 0, BlockSize);
}
#endregion
#region Public Properties
public override string Name
{
get { return Resources.PDG_NAME; }
}
public override string Category
{
get { return Resources.PDG_CATEGORY; }
}
public override string Description
{
get { return Resources.PDG_DESCRIPTION; }
}
public override DateTime CreatedDate
{
get
{
DateTime date = DateTime.Now;
DateTime.TryParse("5/27/2008", out date);
return date;
}
}
public override string Author
{
get { return Resources.AUTHOR_NAME; }
}
public override string Version
{
get { return "1.0"; }
}
public override string Company
{
get { return Resources.COMPANY_NAME; }
}
public override string Copyright
{
get { return Resources.COPYRIGHT; }
}
public override string Documentation
{
get
{
return Resources.PDG_DOCUMENT;
}
}
public override Bitmap Image
{
get { return Resources.BMP_DELETE; }
}
public override bool BackupRequired
{
get { return false; }
}
#endregion
#region Public Overrided Methods
public override bool Init()
{
string ok = StringInputBox.GetInputString(
Resources.TEXT_INPUT_OK_TEXT,
Resources.TEXT_INPUT_OK_TITLE,
CharacterCasing.Upper);
if (ok.Trim().ToUpper().Equals("OK"))
return true;
return false;
}
public override bool Execute(string _param)
{
try
{
Output.Add(string.Format(Resources.TEXT_PROCESSING, _param));
FileStream fileStream = File.OpenWrite(_param);
StreamWriter writer = new StreamWriter(fileStream);
numOfBlocks__ = fileStream.Length / BlockSize;
remaining__ = fileStream.Length % BlockSize;
for (long i = 0; i < numOfBlocks__; i++)
{
writer.Write(block__);
}
if (remaining__ > 0)
{
char[] remainingBlock = new char[remaining__];
Array.Clear(remainingBlock, 0, (int)remaining__);
writer.Write(remainingBlock);
}
writer.Flush();
writer.Close();
fileStream.Close();
File.Delete(_param);
return true;
}
catch (Exception ex)
{
Output.Add(ex.Message);
return false;
}
}
public override bool Done()
{
return true;
}
#endregion
}
|
[
"[",
"Gulu",
"]",
"public",
"sealed",
"class",
"Gulu",
":",
"GuluBase",
"{",
"region",
" Private Fields",
"private",
"const",
"int",
"BlockSize",
"=",
"102400",
";",
"private",
"char",
"[",
"]",
"block__",
"=",
"new",
"char",
"[",
"BlockSize",
"]",
";",
"private",
"long",
"numOfBlocks__",
";",
"private",
"long",
"remaining__",
";",
"endregion",
"region",
" Constructors",
"public",
"Gulu",
"(",
")",
"{",
"Resources",
".",
"Culture",
"=",
"System",
".",
"Threading",
".",
"Thread",
".",
"CurrentThread",
".",
"CurrentCulture",
";",
"Array",
".",
"Clear",
"(",
"block__",
",",
"0",
",",
"BlockSize",
")",
";",
"}",
"endregion",
"region",
" Public Properties",
"public",
"override",
"string",
"Name",
"{",
"get",
"{",
"return",
"Resources",
".",
"PDG_NAME",
";",
"}",
"}",
"public",
"override",
"string",
"Category",
"{",
"get",
"{",
"return",
"Resources",
".",
"PDG_CATEGORY",
";",
"}",
"}",
"public",
"override",
"string",
"Description",
"{",
"get",
"{",
"return",
"Resources",
".",
"PDG_DESCRIPTION",
";",
"}",
"}",
"public",
"override",
"DateTime",
"CreatedDate",
"{",
"get",
"{",
"DateTime",
"date",
"=",
"DateTime",
".",
"Now",
";",
"DateTime",
".",
"TryParse",
"(",
"\"",
"5/27/2008",
"\"",
",",
"out",
"date",
")",
";",
"return",
"date",
";",
"}",
"}",
"public",
"override",
"string",
"Author",
"{",
"get",
"{",
"return",
"Resources",
".",
"AUTHOR_NAME",
";",
"}",
"}",
"public",
"override",
"string",
"Version",
"{",
"get",
"{",
"return",
"\"",
"1.0",
"\"",
";",
"}",
"}",
"public",
"override",
"string",
"Company",
"{",
"get",
"{",
"return",
"Resources",
".",
"COMPANY_NAME",
";",
"}",
"}",
"public",
"override",
"string",
"Copyright",
"{",
"get",
"{",
"return",
"Resources",
".",
"COPYRIGHT",
";",
"}",
"}",
"public",
"override",
"string",
"Documentation",
"{",
"get",
"{",
"return",
"Resources",
".",
"PDG_DOCUMENT",
";",
"}",
"}",
"public",
"override",
"Bitmap",
"Image",
"{",
"get",
"{",
"return",
"Resources",
".",
"BMP_DELETE",
";",
"}",
"}",
"public",
"override",
"bool",
"BackupRequired",
"{",
"get",
"{",
"return",
"false",
";",
"}",
"}",
"endregion",
"region",
" Public Overrided Methods",
"public",
"override",
"bool",
"Init",
"(",
")",
"{",
"string",
"ok",
"=",
"StringInputBox",
".",
"GetInputString",
"(",
"Resources",
".",
"TEXT_INPUT_OK_TEXT",
",",
"Resources",
".",
"TEXT_INPUT_OK_TITLE",
",",
"CharacterCasing",
".",
"Upper",
")",
";",
"if",
"(",
"ok",
".",
"Trim",
"(",
")",
".",
"ToUpper",
"(",
")",
".",
"Equals",
"(",
"\"",
"OK",
"\"",
")",
")",
"return",
"true",
";",
"return",
"false",
";",
"}",
"public",
"override",
"bool",
"Execute",
"(",
"string",
"_param",
")",
"{",
"try",
"{",
"Output",
".",
"Add",
"(",
"string",
".",
"Format",
"(",
"Resources",
".",
"TEXT_PROCESSING",
",",
"_param",
")",
")",
";",
"FileStream",
"fileStream",
"=",
"File",
".",
"OpenWrite",
"(",
"_param",
")",
";",
"StreamWriter",
"writer",
"=",
"new",
"StreamWriter",
"(",
"fileStream",
")",
";",
"numOfBlocks__",
"=",
"fileStream",
".",
"Length",
"/",
"BlockSize",
";",
"remaining__",
"=",
"fileStream",
".",
"Length",
"%",
"BlockSize",
";",
"for",
"(",
"long",
"i",
"=",
"0",
";",
"i",
"<",
"numOfBlocks__",
";",
"i",
"++",
")",
"{",
"writer",
".",
"Write",
"(",
"block__",
")",
";",
"}",
"if",
"(",
"remaining__",
">",
"0",
")",
"{",
"char",
"[",
"]",
"remainingBlock",
"=",
"new",
"char",
"[",
"remaining__",
"]",
";",
"Array",
".",
"Clear",
"(",
"remainingBlock",
",",
"0",
",",
"(",
"int",
")",
"remaining__",
")",
";",
"writer",
".",
"Write",
"(",
"remainingBlock",
")",
";",
"}",
"writer",
".",
"Flush",
"(",
")",
";",
"writer",
".",
"Close",
"(",
")",
";",
"fileStream",
".",
"Close",
"(",
")",
";",
"File",
".",
"Delete",
"(",
"_param",
")",
";",
"return",
"true",
";",
"}",
"catch",
"(",
"Exception",
"ex",
")",
"{",
"Output",
".",
"Add",
"(",
"ex",
".",
"Message",
")",
";",
"return",
"false",
";",
"}",
"}",
"public",
"override",
"bool",
"Done",
"(",
")",
"{",
"return",
"true",
";",
"}",
"endregion",
"}"
] |
The permanent delete gulu is used for deleting files permanently.
|
[
"The",
"permanent",
"delete",
"gulu",
"is",
"used",
"for",
"deleting",
"files",
"permanently",
"."
] |
[
"/// <summary>",
"/// Size of the filling block, here we use 100KB for standard.",
"/// </summary>",
"/// <summary>",
"/// A block of zero bytes, with the fixed length specified by",
"/// BlockSize.",
"/// </summary>",
"/// <summary>",
"/// Number of blocks that we should fill into the file, it depends",
"/// on the length of the file.",
"/// </summary>",
"/// <summary>",
"/// Remaining bytes that should be filled into the file.",
"/// </summary>",
"/// <summary>",
"/// Default constructor. Initializes the zero-value block.",
"/// </summary>",
"/// <summary>",
"/// Gets the name of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the category of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the description of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the day on which the Gulu was created.",
"/// </summary>",
"/// <summary>",
"/// Gets the author of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the version of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the company of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the copyright information of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets the documentation of the Gulu, which will be used in",
"/// Dynamic Help.",
"/// </summary>",
"/// <summary>",
"/// Gets the image of the Gulu.",
"/// </summary>",
"/// <summary>",
"/// Gets a value that indicates if the files should have a backup",
"/// before any action has been taken.",
"/// </summary>",
"/// <summary>",
"/// Initializes the Gulu.",
"/// </summary>",
"/// <returns>True if succeed. False if it failed, in this case the",
"/// operation will be canceled.</returns>",
"/// <summary>",
"/// Running logic of the Gulu.",
"/// </summary>",
"/// <param name=\"_param\">The filename that is going to be processed.</param>",
"/// <returns>True if succeed. False if it failed.</returns>",
"/// <summary>",
"/// Finializes the Gulu.",
"/// </summary>",
"/// <returns>True if succeed. False if it failed.</returns>"
] |
[
{
"param": "GuluBase",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "GuluBase",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 647
| 80
|
148b2c563f3ddb428a60c35e4c230c530e26d5ed
|
mnagaku/ParaMol
|
ParaMol/QM_engines/dftb_wrapper.py
|
[
"MIT"
] |
Python
|
DFTBWrapper
|
ParaMol implementation of a DFTB+ wrapper.
Parameters
----------
system_name : str
Name of the system to which this wrapper is associated.
interface : :obj:`ParaMol.Utils.interface.ParaMolInterface`
ParaMol interface object instance.
n_atoms : int
number of atoms
atom_list : list of str
List with the atom symbols
n_calculations : int
Number of parallel calculations.
slater_koster_files_prefix : str
Path to the Slater-Koster files.
work_dir : str, default="DFTBWorkDir"
Path to the working directory.
calc_file : str, default="dftb_in.hsd"
Name given to the DFTB+ calculation file.
calc_file : str, default="dftb_output.out"
Name given to the DFTB+ stdout file.
detailed_file_output : str, default="detailed.out"
Name of the detailed output file written by DFTB+.
By default DFTB+ writes this to 'detailed.out'. Don't change this unless you know what you're doing.
geometry_file : str, default="geometry.gen"
Name given to the DFTB+ .gen geometry file.
calc_dir_prefix : str, default="dftb\_"
Prefix given to the directories where the calculations will be performed.
max_ang_mom : dict, default={"H": "s", "C": "p", "N": "p", "O": "p", "F": "p", "S": "p"}
Dictionary that defines the maximum angular momentum for each chemical element.
|
ParaMol implementation of a DFTB+ wrapper.
Parameters
system_name : str
Name of the system to which this wrapper is associated.
|
[
"ParaMol",
"implementation",
"of",
"a",
"DFTB",
"+",
"wrapper",
".",
"Parameters",
"system_name",
":",
"str",
"Name",
"of",
"the",
"system",
"to",
"which",
"this",
"wrapper",
"is",
"associated",
"."
] |
class DFTBWrapper:
"""
ParaMol implementation of a DFTB+ wrapper.
Parameters
----------
system_name : str
Name of the system to which this wrapper is associated.
interface : :obj:`ParaMol.Utils.interface.ParaMolInterface`
ParaMol interface object instance.
n_atoms : int
number of atoms
atom_list : list of str
List with the atom symbols
n_calculations : int
Number of parallel calculations.
slater_koster_files_prefix : str
Path to the Slater-Koster files.
work_dir : str, default="DFTBWorkDir"
Path to the working directory.
calc_file : str, default="dftb_in.hsd"
Name given to the DFTB+ calculation file.
calc_file : str, default="dftb_output.out"
Name given to the DFTB+ stdout file.
detailed_file_output : str, default="detailed.out"
Name of the detailed output file written by DFTB+.
By default DFTB+ writes this to 'detailed.out'. Don't change this unless you know what you're doing.
geometry_file : str, default="geometry.gen"
Name given to the DFTB+ .gen geometry file.
calc_dir_prefix : str, default="dftb\_"
Prefix given to the directories where the calculations will be performed.
max_ang_mom : dict, default={"H": "s", "C": "p", "N": "p", "O": "p", "F": "p", "S": "p"}
Dictionary that defines the maximum angular momentum for each chemical element.
"""
def __init__(self, system_name, interface, n_atoms, atom_list, n_calculations,
slater_koster_files_prefix, work_dir_prefix="DFTBWorkDir_", calc_file="dftb_in.hsd", geometry_file="geometry.gen",
calc_dir_prefix="dftb_", detailed_file_output="detailed.out", calc_file_output="dftb_output.out",
max_ang_mom={"H": "s", "C": "p", "N": "p", "O": "p", "F": "p", "S": "p"}):
# Name of the system to which this wrapper is associated to
self._system_name = system_name
# Natoms, atom list, n calculations
self._n_atoms = n_atoms
self._atom_list = atom_list
self._n_calculations = n_calculations
# Get unique atomic element and atomic indexes list
self._unique_elements = list(set(self._atom_list))
self._atom_list_idx = [(self._unique_elements.index(element) + 1) for element in self._atom_list]
# ParaMol interface
self._interface = interface
self._calculation_dirs = []
# Constants
self._slater_koster_files_prefix = slater_koster_files_prefix
self._work_dir = "{}{}".format(work_dir_prefix, self._system_name)
self._calc_file = calc_file
self._calc_file_output = calc_file_output
self._geometry_file = geometry_file
self._calc_dir_prefix = calc_dir_prefix
self._detailed_file_output = detailed_file_output
# Maximum angular momentum dictionary
self._max_ang_mom = max_ang_mom
# Prepare working directory
self._prepare_work_dir()
# ------------------------------------------------------------ #
# #
# PUBLIC METHODS #
# #
# ------------------------------------------------------------ #
def run_calculation(self, coords, label):
"""
Method that perform a single-point calculation with forces.
Parameters
----------
coords : np.ndarray, shape=(n_atoms, 3), dtype=float
Coordinates array.
label : str
Seed for the calculation.
Returns
-------
energy : float
Energy in kJ/mol.
forces: np.ndarray, shape=np.array(n_atoms,3)
Forces in kJ/mol/nm
"""
# Run calculation and extract potential energy
# Change to calculation directory
self._interface.chdir(self._calculation_dirs[label], absolute=True)
# Write geometry in GEN format
self._write_geometry_gen_format(coords)
# Run DFTB+
self._interface.run_subprocess("dftb+", self._calc_file, output_file=self._calc_file_output)
# Extract Potential Energy
energy = float(self._interface.run_subprocess("grep 'Total energy' {}".format(self._detailed_file_output),
"awk {'print $3'}", pipe=True))
# Extract forces
forces = (self._interface.run_subprocess("grep -A{} 'Total Forces' {}".format(self._n_atoms, self._detailed_file_output),
"awk {'print $2 \" \" $3 \" \" $4'}",
"tail -n +2",
pipe=True))
forces = np.asarray(forces.split(), dtype=np.float64).reshape(self._n_atoms, 3)
self._interface.chdir_base()
# Do the necessary conversions
energy = energy * 2625.5002 # Hartree -> kJ/mol
forces = forces * 2625.5002 / 0.529177 * 10 # Hartree/a.u. -> kJ/mol/nm
return energy, forces
# ------------------------------------------------------------ #
# #
# PRIVATE METHODS #
# #
# ------------------------------------------------------------ #
def _prepare_work_dir(self):
"""
Method that prepares the working directory.
Returns
-------
None
"""
# Go to base directory
self._interface.chdir_base()
# Create working directory
self._interface.create_dir(self._work_dir)
# Change to working directory
self._interface.chdir(self._work_dir, relative_to_base=True)
for i in range(self._n_calculations):
self._interface.create_dir(self._calc_dir_prefix+"{}".format(i))
self._interface.chdir(self._calc_dir_prefix+"{}".format(i))
self._write_input_file()
self._calculation_dirs.append(os.getcwd())
self._interface.chdir_previous()
self._interface.chdir_base()
return 1
def _write_input_file(self, dispersion_correction=False):
"""
Method that writes the input file necessary to run single-point with forces calculation.
Notes
-----
It only needs to be run upon creation of the QM wrapper.
Parameters
----------
dispersion_correction : bool
Whether or not to include D3 dispersion correction section.
Returns
-------
`True` if file was closed successfully. `False` otherwise.
"""
input_file = open(self._calc_file, 'w')
input_file.write("Geometry = GenFormat { \n")
input_file.write("<<< '{}' \n".format(self._geometry_file))
input_file.write("} \n \n")
input_file.write("Driver = {} \n \n")
input_file.write("Hamiltonian = DFTB { \n")
input_file.write("Scc = yes \n")
input_file.write(" SlaterKosterFiles = Type2FileNames {\n")
input_file.write("Prefix = '{}' \n".format(self._slater_koster_files_prefix))
input_file.write("Separator = '-' \n")
input_file.write("Suffix = '.skf' \n")
input_file.write("}\n")
input_file.write(" MaxAngularMomentum {\n")
for element in self._unique_elements:
input_file.write("{} = '{}' \n".format(element, self._max_ang_mom[element]))
input_file.write("}\n")
if dispersion_correction:
# Write dispersion correction part
input_file.write("Dispersion = DftD3 { Damping = BeckeJohnson { \n")
input_file.write("a1 = 0.5719 \n")
input_file.write("a2 = 3.6017 } \n")
input_file.write("s6 = 1.0 \n")
input_file.write("s8 = 0.5883 }\n")
# End of Hamiltonian
input_file.write("}\n \n")
input_file.write("Options { \n")
input_file.write(" WriteDetailedOut = Yes \n")
input_file.write("} \n")
input_file.write("Analysis { \n ")
input_file.write(" CalculateForces = Yes \n")
input_file.write("} \n")
input_file.write("ParserOptions { \n")
input_file.write(" ParserVersion = 7 \n")
input_file.write("} \n")
return input_file.close()
def _write_geometry_gen_format(self, coords):
"""
Method that writes the geometry in gen format.
Parameters
----------
coords: list or np.array
(n_atoms,3) coordinates array
Returns
-------
`True` if file was closed successfully. `False` otherwise.
"""
gen_file = open(self._geometry_file, "w")
gen_file.write("{} C \n".format(self._n_atoms))
# Write unique elements
for unique_element in self._unique_elements:
gen_file.write("{} ".format(unique_element))
gen_file.write("\n")
# Write coordinates
for i in range(self._n_atoms):
gen_file.write("{} {} {} {} {} \n".format(i+1, self._atom_list_idx[i], *coords[i]))
return gen_file.close()
|
[
"class",
"DFTBWrapper",
":",
"def",
"__init__",
"(",
"self",
",",
"system_name",
",",
"interface",
",",
"n_atoms",
",",
"atom_list",
",",
"n_calculations",
",",
"slater_koster_files_prefix",
",",
"work_dir_prefix",
"=",
"\"DFTBWorkDir_\"",
",",
"calc_file",
"=",
"\"dftb_in.hsd\"",
",",
"geometry_file",
"=",
"\"geometry.gen\"",
",",
"calc_dir_prefix",
"=",
"\"dftb_\"",
",",
"detailed_file_output",
"=",
"\"detailed.out\"",
",",
"calc_file_output",
"=",
"\"dftb_output.out\"",
",",
"max_ang_mom",
"=",
"{",
"\"H\"",
":",
"\"s\"",
",",
"\"C\"",
":",
"\"p\"",
",",
"\"N\"",
":",
"\"p\"",
",",
"\"O\"",
":",
"\"p\"",
",",
"\"F\"",
":",
"\"p\"",
",",
"\"S\"",
":",
"\"p\"",
"}",
")",
":",
"self",
".",
"_system_name",
"=",
"system_name",
"self",
".",
"_n_atoms",
"=",
"n_atoms",
"self",
".",
"_atom_list",
"=",
"atom_list",
"self",
".",
"_n_calculations",
"=",
"n_calculations",
"self",
".",
"_unique_elements",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"_atom_list",
")",
")",
"self",
".",
"_atom_list_idx",
"=",
"[",
"(",
"self",
".",
"_unique_elements",
".",
"index",
"(",
"element",
")",
"+",
"1",
")",
"for",
"element",
"in",
"self",
".",
"_atom_list",
"]",
"self",
".",
"_interface",
"=",
"interface",
"self",
".",
"_calculation_dirs",
"=",
"[",
"]",
"self",
".",
"_slater_koster_files_prefix",
"=",
"slater_koster_files_prefix",
"self",
".",
"_work_dir",
"=",
"\"{}{}\"",
".",
"format",
"(",
"work_dir_prefix",
",",
"self",
".",
"_system_name",
")",
"self",
".",
"_calc_file",
"=",
"calc_file",
"self",
".",
"_calc_file_output",
"=",
"calc_file_output",
"self",
".",
"_geometry_file",
"=",
"geometry_file",
"self",
".",
"_calc_dir_prefix",
"=",
"calc_dir_prefix",
"self",
".",
"_detailed_file_output",
"=",
"detailed_file_output",
"self",
".",
"_max_ang_mom",
"=",
"max_ang_mom",
"self",
".",
"_prepare_work_dir",
"(",
")",
"def",
"run_calculation",
"(",
"self",
",",
"coords",
",",
"label",
")",
":",
"\"\"\"\n Method that perform a single-point calculation with forces.\n\n Parameters\n ----------\n coords : np.ndarray, shape=(n_atoms, 3), dtype=float\n Coordinates array.\n label : str\n Seed for the calculation.\n\n Returns\n -------\n energy : float\n Energy in kJ/mol.\n forces: np.ndarray, shape=np.array(n_atoms,3)\n Forces in kJ/mol/nm\n \"\"\"",
"self",
".",
"_interface",
".",
"chdir",
"(",
"self",
".",
"_calculation_dirs",
"[",
"label",
"]",
",",
"absolute",
"=",
"True",
")",
"self",
".",
"_write_geometry_gen_format",
"(",
"coords",
")",
"self",
".",
"_interface",
".",
"run_subprocess",
"(",
"\"dftb+\"",
",",
"self",
".",
"_calc_file",
",",
"output_file",
"=",
"self",
".",
"_calc_file_output",
")",
"energy",
"=",
"float",
"(",
"self",
".",
"_interface",
".",
"run_subprocess",
"(",
"\"grep 'Total energy' {}\"",
".",
"format",
"(",
"self",
".",
"_detailed_file_output",
")",
",",
"\"awk {'print $3'}\"",
",",
"pipe",
"=",
"True",
")",
")",
"forces",
"=",
"(",
"self",
".",
"_interface",
".",
"run_subprocess",
"(",
"\"grep -A{} 'Total Forces' {}\"",
".",
"format",
"(",
"self",
".",
"_n_atoms",
",",
"self",
".",
"_detailed_file_output",
")",
",",
"\"awk {'print $2 \\\" \\\" $3 \\\" \\\" $4'}\"",
",",
"\"tail -n +2\"",
",",
"pipe",
"=",
"True",
")",
")",
"forces",
"=",
"np",
".",
"asarray",
"(",
"forces",
".",
"split",
"(",
")",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
".",
"reshape",
"(",
"self",
".",
"_n_atoms",
",",
"3",
")",
"self",
".",
"_interface",
".",
"chdir_base",
"(",
")",
"energy",
"=",
"energy",
"*",
"2625.5002",
"forces",
"=",
"forces",
"*",
"2625.5002",
"/",
"0.529177",
"*",
"10",
"return",
"energy",
",",
"forces",
"def",
"_prepare_work_dir",
"(",
"self",
")",
":",
"\"\"\"\n Method that prepares the working directory.\n\n Returns\n -------\n None\n \"\"\"",
"self",
".",
"_interface",
".",
"chdir_base",
"(",
")",
"self",
".",
"_interface",
".",
"create_dir",
"(",
"self",
".",
"_work_dir",
")",
"self",
".",
"_interface",
".",
"chdir",
"(",
"self",
".",
"_work_dir",
",",
"relative_to_base",
"=",
"True",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_n_calculations",
")",
":",
"self",
".",
"_interface",
".",
"create_dir",
"(",
"self",
".",
"_calc_dir_prefix",
"+",
"\"{}\"",
".",
"format",
"(",
"i",
")",
")",
"self",
".",
"_interface",
".",
"chdir",
"(",
"self",
".",
"_calc_dir_prefix",
"+",
"\"{}\"",
".",
"format",
"(",
"i",
")",
")",
"self",
".",
"_write_input_file",
"(",
")",
"self",
".",
"_calculation_dirs",
".",
"append",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"self",
".",
"_interface",
".",
"chdir_previous",
"(",
")",
"self",
".",
"_interface",
".",
"chdir_base",
"(",
")",
"return",
"1",
"def",
"_write_input_file",
"(",
"self",
",",
"dispersion_correction",
"=",
"False",
")",
":",
"\"\"\"\n Method that writes the input file necessary to run single-point with forces calculation.\n\n Notes\n -----\n It only needs to be run upon creation of the QM wrapper.\n\n Parameters\n ----------\n dispersion_correction : bool\n Whether or not to include D3 dispersion correction section.\n\n Returns\n -------\n `True` if file was closed successfully. `False` otherwise.\n \"\"\"",
"input_file",
"=",
"open",
"(",
"self",
".",
"_calc_file",
",",
"'w'",
")",
"input_file",
".",
"write",
"(",
"\"Geometry = GenFormat { \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"<<< '{}' \\n\"",
".",
"format",
"(",
"self",
".",
"_geometry_file",
")",
")",
"input_file",
".",
"write",
"(",
"\"} \\n \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Driver = {} \\n \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Hamiltonian = DFTB { \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Scc = yes \\n\"",
")",
"input_file",
".",
"write",
"(",
"\" SlaterKosterFiles = Type2FileNames {\\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Prefix = '{}' \\n\"",
".",
"format",
"(",
"self",
".",
"_slater_koster_files_prefix",
")",
")",
"input_file",
".",
"write",
"(",
"\"Separator = '-' \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Suffix = '.skf' \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"}\\n\"",
")",
"input_file",
".",
"write",
"(",
"\" MaxAngularMomentum {\\n\"",
")",
"for",
"element",
"in",
"self",
".",
"_unique_elements",
":",
"input_file",
".",
"write",
"(",
"\"{} = '{}' \\n\"",
".",
"format",
"(",
"element",
",",
"self",
".",
"_max_ang_mom",
"[",
"element",
"]",
")",
")",
"input_file",
".",
"write",
"(",
"\"}\\n\"",
")",
"if",
"dispersion_correction",
":",
"input_file",
".",
"write",
"(",
"\"Dispersion = DftD3 { Damping = BeckeJohnson { \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"a1 = 0.5719 \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"a2 = 3.6017 } \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"s6 = 1.0 \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"s8 = 0.5883 }\\n\"",
")",
"input_file",
".",
"write",
"(",
"\"}\\n \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Options { \\n\"",
")",
"input_file",
".",
"write",
"(",
"\" WriteDetailedOut = Yes \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"} \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"Analysis { \\n \"",
")",
"input_file",
".",
"write",
"(",
"\" CalculateForces = Yes \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"} \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"ParserOptions { \\n\"",
")",
"input_file",
".",
"write",
"(",
"\" ParserVersion = 7 \\n\"",
")",
"input_file",
".",
"write",
"(",
"\"} \\n\"",
")",
"return",
"input_file",
".",
"close",
"(",
")",
"def",
"_write_geometry_gen_format",
"(",
"self",
",",
"coords",
")",
":",
"\"\"\"\n Method that writes the geometry in gen format.\n\n Parameters\n ----------\n coords: list or np.array\n (n_atoms,3) coordinates array\n\n Returns\n -------\n `True` if file was closed successfully. `False` otherwise.\n \"\"\"",
"gen_file",
"=",
"open",
"(",
"self",
".",
"_geometry_file",
",",
"\"w\"",
")",
"gen_file",
".",
"write",
"(",
"\"{} C \\n\"",
".",
"format",
"(",
"self",
".",
"_n_atoms",
")",
")",
"for",
"unique_element",
"in",
"self",
".",
"_unique_elements",
":",
"gen_file",
".",
"write",
"(",
"\"{} \"",
".",
"format",
"(",
"unique_element",
")",
")",
"gen_file",
".",
"write",
"(",
"\"\\n\"",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"_n_atoms",
")",
":",
"gen_file",
".",
"write",
"(",
"\"{} {} {} {} {} \\n\"",
".",
"format",
"(",
"i",
"+",
"1",
",",
"self",
".",
"_atom_list_idx",
"[",
"i",
"]",
",",
"*",
"coords",
"[",
"i",
"]",
")",
")",
"return",
"gen_file",
".",
"close",
"(",
")"
] |
ParaMol implementation of a DFTB+ wrapper.
|
[
"ParaMol",
"implementation",
"of",
"a",
"DFTB",
"+",
"wrapper",
"."
] |
[
"\"\"\"\n ParaMol implementation of a DFTB+ wrapper.\n\n Parameters\n ----------\n system_name : str\n Name of the system to which this wrapper is associated.\n interface : :obj:`ParaMol.Utils.interface.ParaMolInterface`\n ParaMol interface object instance.\n n_atoms : int\n number of atoms\n atom_list : list of str\n List with the atom symbols\n n_calculations : int\n Number of parallel calculations.\n slater_koster_files_prefix : str\n Path to the Slater-Koster files.\n work_dir : str, default=\"DFTBWorkDir\"\n Path to the working directory.\n calc_file : str, default=\"dftb_in.hsd\"\n Name given to the DFTB+ calculation file.\n calc_file : str, default=\"dftb_output.out\"\n Name given to the DFTB+ stdout file.\n detailed_file_output : str, default=\"detailed.out\"\n Name of the detailed output file written by DFTB+.\n By default DFTB+ writes this to 'detailed.out'. Don't change this unless you know what you're doing.\n geometry_file : str, default=\"geometry.gen\"\n Name given to the DFTB+ .gen geometry file.\n calc_dir_prefix : str, default=\"dftb\\_\"\n Prefix given to the directories where the calculations will be performed.\n max_ang_mom : dict, default={\"H\": \"s\", \"C\": \"p\", \"N\": \"p\", \"O\": \"p\", \"F\": \"p\", \"S\": \"p\"}\n Dictionary that defines the maximum angular momentum for each chemical element.\n \"\"\"",
"# Name of the system to which this wrapper is associated to",
"# Natoms, atom list, n calculations",
"# Get unique atomic element and atomic indexes list",
"# ParaMol interface",
"# Constants",
"# Maximum angular momentum dictionary",
"# Prepare working directory",
"# ------------------------------------------------------------ #",
"# #",
"# PUBLIC METHODS #",
"# #",
"# ------------------------------------------------------------ #",
"\"\"\"\n Method that perform a single-point calculation with forces.\n\n Parameters\n ----------\n coords : np.ndarray, shape=(n_atoms, 3), dtype=float\n Coordinates array.\n label : str\n Seed for the calculation.\n\n Returns\n -------\n energy : float\n Energy in kJ/mol.\n forces: np.ndarray, shape=np.array(n_atoms,3)\n Forces in kJ/mol/nm\n \"\"\"",
"# Run calculation and extract potential energy",
"# Change to calculation directory",
"# Write geometry in GEN format",
"# Run DFTB+",
"# Extract Potential Energy",
"# Extract forces",
"# Do the necessary conversions",
"# Hartree -> kJ/mol",
"# Hartree/a.u. -> kJ/mol/nm",
"# ------------------------------------------------------------ #",
"# #",
"# PRIVATE METHODS #",
"# #",
"# ------------------------------------------------------------ #",
"\"\"\"\n Method that prepares the working directory.\n\n Returns\n -------\n None\n \"\"\"",
"# Go to base directory",
"# Create working directory",
"# Change to working directory",
"\"\"\"\n Method that writes the input file necessary to run single-point with forces calculation.\n\n Notes\n -----\n It only needs to be run upon creation of the QM wrapper.\n\n Parameters\n ----------\n dispersion_correction : bool\n Whether or not to include D3 dispersion correction section.\n\n Returns\n -------\n `True` if file was closed successfully. `False` otherwise.\n \"\"\"",
"# Write dispersion correction part",
"# End of Hamiltonian",
"\"\"\"\n Method that writes the geometry in gen format.\n\n Parameters\n ----------\n coords: list or np.array\n (n_atoms,3) coordinates array\n\n Returns\n -------\n `True` if file was closed successfully. `False` otherwise.\n \"\"\"",
"# Write unique elements",
"# Write coordinates"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 2,083
| 360
|
41196a28a099ecb2b68d8afaac92f4820402fac1
|
francislavoie/spring-boot
|
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/sql/init/dependency/DatabaseInitializationDependencyConfigurer.java
|
[
"Apache-2.0"
] |
Java
|
DatabaseInitializationDependencyConfigurer
|
/**
* Configures beans that depend upon SQL database initialization with
* {@link BeanDefinition#getDependsOn() dependencies} upon beans that perform database
* initialization. Intended for {@link Import import} in configuration classes that define
* database initialization beans or that define beans that require database initialization
* to have completed before they are initialized.
* <p>
* Beans that initialize a database are identified by {@link DatabaseInitializerDetector
* DatabaseInitializerDetectors}. Beans that depend upon database initialization are
* identified by {@link DependsOnDatabaseInitializationDetector
* DependsOnDatabaseInitializationDetectors}.
*
* @author Andy Wilkinson
* @since 2.5.0
* @see DatabaseInitializerDetector
* @see DependsOnDatabaseInitializationDetector
* @see DependsOnDatabaseInitialization
*/
|
Configures beans that depend upon SQL database initialization with
BeanDefinition#getDependsOn() dependencies upon beans that perform database
initialization. Intended for Import import in configuration classes that define
database initialization beans or that define beans that require database initialization
to have completed before they are initialized.
Beans that initialize a database are identified by {@link DatabaseInitializerDetector
DatabaseInitializerDetectors}. Beans that depend upon database initialization are
identified by {@link DependsOnDatabaseInitializationDetector
DependsOnDatabaseInitializationDetectors}.
|
[
"Configures",
"beans",
"that",
"depend",
"upon",
"SQL",
"database",
"initialization",
"with",
"BeanDefinition#getDependsOn",
"()",
"dependencies",
"upon",
"beans",
"that",
"perform",
"database",
"initialization",
".",
"Intended",
"for",
"Import",
"import",
"in",
"configuration",
"classes",
"that",
"define",
"database",
"initialization",
"beans",
"or",
"that",
"define",
"beans",
"that",
"require",
"database",
"initialization",
"to",
"have",
"completed",
"before",
"they",
"are",
"initialized",
".",
"Beans",
"that",
"initialize",
"a",
"database",
"are",
"identified",
"by",
"{",
"@link",
"DatabaseInitializerDetector",
"DatabaseInitializerDetectors",
"}",
".",
"Beans",
"that",
"depend",
"upon",
"database",
"initialization",
"are",
"identified",
"by",
"{",
"@link",
"DependsOnDatabaseInitializationDetector",
"DependsOnDatabaseInitializationDetectors",
"}",
"."
] |
public class DatabaseInitializationDependencyConfigurer implements ImportBeanDefinitionRegistrar {
private final Environment environment;
DatabaseInitializationDependencyConfigurer(Environment environment) {
this.environment = environment;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
String name = DependsOnDatabaseInitializationPostProcessor.class.getName();
if (!registry.containsBeanDefinition(name)) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(
DependsOnDatabaseInitializationPostProcessor.class,
this::createDependsOnDatabaseInitializationPostProcessor);
registry.registerBeanDefinition(name, builder.getBeanDefinition());
}
}
private DependsOnDatabaseInitializationPostProcessor createDependsOnDatabaseInitializationPostProcessor() {
return new DependsOnDatabaseInitializationPostProcessor(this.environment);
}
/**
* {@link BeanFactoryPostProcessor} used to configure database initialization
* dependency relationships.
*/
static class DependsOnDatabaseInitializationPostProcessor implements BeanFactoryPostProcessor {
private final Environment environment;
DependsOnDatabaseInitializationPostProcessor(Environment environment) {
this.environment = environment;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
Set<String> initializerBeanNames = detectInitializerBeanNames(beanFactory);
if (initializerBeanNames.isEmpty()) {
return;
}
for (String dependsOnInitializationBeanNames : detectDependsOnInitializationBeanNames(beanFactory)) {
BeanDefinition definition = getBeanDefinition(dependsOnInitializationBeanNames, beanFactory);
definition.setDependsOn(merge(definition.getDependsOn(), initializerBeanNames));
}
}
private String[] merge(String[] source, Set<String> additional) {
Set<String> result = new LinkedHashSet<>((source != null) ? Arrays.asList(source) : Collections.emptySet());
result.addAll(additional);
return StringUtils.toStringArray(result);
}
private Set<String> detectInitializerBeanNames(ConfigurableListableBeanFactory beanFactory) {
List<DatabaseInitializerDetector> detectors = getDetectors(beanFactory, DatabaseInitializerDetector.class);
Set<String> beanNames = new HashSet<>();
for (DatabaseInitializerDetector detector : detectors) {
for (String beanName : detector.detect(beanFactory)) {
BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);
beanDefinition.setAttribute(DatabaseInitializerDetector.class.getName(),
detector.getClass().getName());
beanNames.add(beanName);
}
}
beanNames = Collections.unmodifiableSet(beanNames);
for (DatabaseInitializerDetector detector : detectors) {
detector.detectionComplete(beanFactory, beanNames);
}
return beanNames;
}
private Collection<String> detectDependsOnInitializationBeanNames(ConfigurableListableBeanFactory beanFactory) {
List<DependsOnDatabaseInitializationDetector> detectors = getDetectors(beanFactory,
DependsOnDatabaseInitializationDetector.class);
Set<String> beanNames = new HashSet<>();
for (DependsOnDatabaseInitializationDetector detector : detectors) {
beanNames.addAll(detector.detect(beanFactory));
}
return beanNames;
}
private <T> List<T> getDetectors(ConfigurableListableBeanFactory beanFactory, Class<T> type) {
List<String> names = SpringFactoriesLoader.loadFactoryNames(type, beanFactory.getBeanClassLoader());
Instantiator<T> instantiator = new Instantiator<>(type,
(availableParameters) -> availableParameters.add(Environment.class, this.environment));
return instantiator.instantiate(names);
}
private static BeanDefinition getBeanDefinition(String beanName, ConfigurableListableBeanFactory beanFactory) {
try {
return beanFactory.getBeanDefinition(beanName);
}
catch (NoSuchBeanDefinitionException ex) {
BeanFactory parentBeanFactory = beanFactory.getParentBeanFactory();
if (parentBeanFactory instanceof ConfigurableListableBeanFactory) {
return getBeanDefinition(beanName, (ConfigurableListableBeanFactory) parentBeanFactory);
}
throw ex;
}
}
}
}
|
[
"public",
"class",
"DatabaseInitializationDependencyConfigurer",
"implements",
"ImportBeanDefinitionRegistrar",
"{",
"private",
"final",
"Environment",
"environment",
";",
"DatabaseInitializationDependencyConfigurer",
"(",
"Environment",
"environment",
")",
"{",
"this",
".",
"environment",
"=",
"environment",
";",
"}",
"@",
"Override",
"public",
"void",
"registerBeanDefinitions",
"(",
"AnnotationMetadata",
"importingClassMetadata",
",",
"BeanDefinitionRegistry",
"registry",
")",
"{",
"String",
"name",
"=",
"DependsOnDatabaseInitializationPostProcessor",
".",
"class",
".",
"getName",
"(",
")",
";",
"if",
"(",
"!",
"registry",
".",
"containsBeanDefinition",
"(",
"name",
")",
")",
"{",
"BeanDefinitionBuilder",
"builder",
"=",
"BeanDefinitionBuilder",
".",
"genericBeanDefinition",
"(",
"DependsOnDatabaseInitializationPostProcessor",
".",
"class",
",",
"this",
"::",
"createDependsOnDatabaseInitializationPostProcessor",
")",
";",
"registry",
".",
"registerBeanDefinition",
"(",
"name",
",",
"builder",
".",
"getBeanDefinition",
"(",
")",
")",
";",
"}",
"}",
"private",
"DependsOnDatabaseInitializationPostProcessor",
"createDependsOnDatabaseInitializationPostProcessor",
"(",
")",
"{",
"return",
"new",
"DependsOnDatabaseInitializationPostProcessor",
"(",
"this",
".",
"environment",
")",
";",
"}",
"/**\n\t * {@link BeanFactoryPostProcessor} used to configure database initialization\n\t * dependency relationships.\n\t */",
"static",
"class",
"DependsOnDatabaseInitializationPostProcessor",
"implements",
"BeanFactoryPostProcessor",
"{",
"private",
"final",
"Environment",
"environment",
";",
"DependsOnDatabaseInitializationPostProcessor",
"(",
"Environment",
"environment",
")",
"{",
"this",
".",
"environment",
"=",
"environment",
";",
"}",
"@",
"Override",
"public",
"void",
"postProcessBeanFactory",
"(",
"ConfigurableListableBeanFactory",
"beanFactory",
")",
"{",
"Set",
"<",
"String",
">",
"initializerBeanNames",
"=",
"detectInitializerBeanNames",
"(",
"beanFactory",
")",
";",
"if",
"(",
"initializerBeanNames",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
";",
"}",
"for",
"(",
"String",
"dependsOnInitializationBeanNames",
":",
"detectDependsOnInitializationBeanNames",
"(",
"beanFactory",
")",
")",
"{",
"BeanDefinition",
"definition",
"=",
"getBeanDefinition",
"(",
"dependsOnInitializationBeanNames",
",",
"beanFactory",
")",
";",
"definition",
".",
"setDependsOn",
"(",
"merge",
"(",
"definition",
".",
"getDependsOn",
"(",
")",
",",
"initializerBeanNames",
")",
")",
";",
"}",
"}",
"private",
"String",
"[",
"]",
"merge",
"(",
"String",
"[",
"]",
"source",
",",
"Set",
"<",
"String",
">",
"additional",
")",
"{",
"Set",
"<",
"String",
">",
"result",
"=",
"new",
"LinkedHashSet",
"<",
">",
"(",
"(",
"source",
"!=",
"null",
")",
"?",
"Arrays",
".",
"asList",
"(",
"source",
")",
":",
"Collections",
".",
"emptySet",
"(",
")",
")",
";",
"result",
".",
"addAll",
"(",
"additional",
")",
";",
"return",
"StringUtils",
".",
"toStringArray",
"(",
"result",
")",
";",
"}",
"private",
"Set",
"<",
"String",
">",
"detectInitializerBeanNames",
"(",
"ConfigurableListableBeanFactory",
"beanFactory",
")",
"{",
"List",
"<",
"DatabaseInitializerDetector",
">",
"detectors",
"=",
"getDetectors",
"(",
"beanFactory",
",",
"DatabaseInitializerDetector",
".",
"class",
")",
";",
"Set",
"<",
"String",
">",
"beanNames",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"for",
"(",
"DatabaseInitializerDetector",
"detector",
":",
"detectors",
")",
"{",
"for",
"(",
"String",
"beanName",
":",
"detector",
".",
"detect",
"(",
"beanFactory",
")",
")",
"{",
"BeanDefinition",
"beanDefinition",
"=",
"beanFactory",
".",
"getBeanDefinition",
"(",
"beanName",
")",
";",
"beanDefinition",
".",
"setAttribute",
"(",
"DatabaseInitializerDetector",
".",
"class",
".",
"getName",
"(",
")",
",",
"detector",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
")",
";",
"beanNames",
".",
"add",
"(",
"beanName",
")",
";",
"}",
"}",
"beanNames",
"=",
"Collections",
".",
"unmodifiableSet",
"(",
"beanNames",
")",
";",
"for",
"(",
"DatabaseInitializerDetector",
"detector",
":",
"detectors",
")",
"{",
"detector",
".",
"detectionComplete",
"(",
"beanFactory",
",",
"beanNames",
")",
";",
"}",
"return",
"beanNames",
";",
"}",
"private",
"Collection",
"<",
"String",
">",
"detectDependsOnInitializationBeanNames",
"(",
"ConfigurableListableBeanFactory",
"beanFactory",
")",
"{",
"List",
"<",
"DependsOnDatabaseInitializationDetector",
">",
"detectors",
"=",
"getDetectors",
"(",
"beanFactory",
",",
"DependsOnDatabaseInitializationDetector",
".",
"class",
")",
";",
"Set",
"<",
"String",
">",
"beanNames",
"=",
"new",
"HashSet",
"<",
">",
"(",
")",
";",
"for",
"(",
"DependsOnDatabaseInitializationDetector",
"detector",
":",
"detectors",
")",
"{",
"beanNames",
".",
"addAll",
"(",
"detector",
".",
"detect",
"(",
"beanFactory",
")",
")",
";",
"}",
"return",
"beanNames",
";",
"}",
"private",
"<",
"T",
">",
"List",
"<",
"T",
">",
"getDetectors",
"(",
"ConfigurableListableBeanFactory",
"beanFactory",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"List",
"<",
"String",
">",
"names",
"=",
"SpringFactoriesLoader",
".",
"loadFactoryNames",
"(",
"type",
",",
"beanFactory",
".",
"getBeanClassLoader",
"(",
")",
")",
";",
"Instantiator",
"<",
"T",
">",
"instantiator",
"=",
"new",
"Instantiator",
"<",
">",
"(",
"type",
",",
"(",
"availableParameters",
")",
"->",
"availableParameters",
".",
"add",
"(",
"Environment",
".",
"class",
",",
"this",
".",
"environment",
")",
")",
";",
"return",
"instantiator",
".",
"instantiate",
"(",
"names",
")",
";",
"}",
"private",
"static",
"BeanDefinition",
"getBeanDefinition",
"(",
"String",
"beanName",
",",
"ConfigurableListableBeanFactory",
"beanFactory",
")",
"{",
"try",
"{",
"return",
"beanFactory",
".",
"getBeanDefinition",
"(",
"beanName",
")",
";",
"}",
"catch",
"(",
"NoSuchBeanDefinitionException",
"ex",
")",
"{",
"BeanFactory",
"parentBeanFactory",
"=",
"beanFactory",
".",
"getParentBeanFactory",
"(",
")",
";",
"if",
"(",
"parentBeanFactory",
"instanceof",
"ConfigurableListableBeanFactory",
")",
"{",
"return",
"getBeanDefinition",
"(",
"beanName",
",",
"(",
"ConfigurableListableBeanFactory",
")",
"parentBeanFactory",
")",
";",
"}",
"throw",
"ex",
";",
"}",
"}",
"}",
"}"
] |
Configures beans that depend upon SQL database initialization with
{@link BeanDefinition#getDependsOn() dependencies} upon beans that perform database
initialization.
|
[
"Configures",
"beans",
"that",
"depend",
"upon",
"SQL",
"database",
"initialization",
"with",
"{",
"@link",
"BeanDefinition#getDependsOn",
"()",
"dependencies",
"}",
"upon",
"beans",
"that",
"perform",
"database",
"initialization",
"."
] |
[] |
[
{
"param": "ImportBeanDefinitionRegistrar",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ImportBeanDefinitionRegistrar",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 17
| 865
| 164
|
485c75232154e89a9c1898080bf271d576ad15cf
|
rauhs/lucenenet
|
src/Lucene.Net.Spatial/Serialized/SerializedDVStrategy.cs
|
[
"ICU",
"Apache-2.0"
] |
C#
|
SerializedDVStrategy
|
/// <summary>
/// A <see cref="SpatialStrategy"/> based on serializing a Shape stored into BinaryDocValues.
/// This is not at all fast; it's designed to be used in conjuction with another index based
/// SpatialStrategy that is approximated(like <see cref="Prefix.RecursivePrefixTreeStrategy"/>)
/// to add precision or eventually make more specific / advanced calculations on the per-document
/// geometry.
/// The serialization uses Spatial4j's <see cref="BinaryCodec"/>.
///
/// @lucene.experimental
/// </summary>
|
A based on serializing a Shape stored into BinaryDocValues.
This is not at all fast; it's designed to be used in conjuction with another index based
SpatialStrategy that is approximated(like )
to add precision or eventually make more specific / advanced calculations on the per-document
geometry.
The serialization uses Spatial4j's .
|
[
"A",
"based",
"on",
"serializing",
"a",
"Shape",
"stored",
"into",
"BinaryDocValues",
".",
"This",
"is",
"not",
"at",
"all",
"fast",
";",
"it",
"'",
"s",
"designed",
"to",
"be",
"used",
"in",
"conjuction",
"with",
"another",
"index",
"based",
"SpatialStrategy",
"that",
"is",
"approximated",
"(",
"like",
")",
"to",
"add",
"precision",
"or",
"eventually",
"make",
"more",
"specific",
"/",
"advanced",
"calculations",
"on",
"the",
"per",
"-",
"document",
"geometry",
".",
"The",
"serialization",
"uses",
"Spatial4j",
"'",
"s",
"."
] |
public class SerializedDVStrategy : SpatialStrategy
{
private volatile int indexLastBufSize = 8 * 1024;
public SerializedDVStrategy(SpatialContext ctx, string fieldName)
: base(ctx, fieldName)
{
}
public override Field[] CreateIndexableFields(IShape shape)
{
int bufSize = Math.Max(128, (int)(this.indexLastBufSize * 1.5));
MemoryStream byteStream = new MemoryStream(bufSize);
BytesRef bytesRef = new BytesRef();
try
{
m_ctx.BinaryCodec.WriteShape(new BinaryWriter(byteStream), shape);
byteStream.WriteTo(new OutputStreamAnonymousClass(bytesRef));
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
this.indexLastBufSize = bytesRef.Length;
return new Field[] { new BinaryDocValuesField(FieldName, bytesRef) };
}
private class OutputStreamAnonymousClass : MemoryStream
{
private readonly BytesRef bytesRef;
public OutputStreamAnonymousClass(BytesRef bytesRef)
{
this.bytesRef = bytesRef;
}
public override void Write(byte[] buffer, int index, int count)
{
bytesRef.Bytes = buffer;
bytesRef.Offset = index;
bytesRef.Length = count;
}
}
public override ValueSource MakeDistanceValueSource(IPoint queryPoint, double multiplier)
{
return new DistanceToShapeValueSource(MakeShapeValueSource(), queryPoint, multiplier, m_ctx);
}
public override ConstantScoreQuery MakeQuery(SpatialArgs args)
{
throw new NotSupportedException("This strategy can't return a query that operates" +
" efficiently. Instead try a Filter or ValueSource.");
}
public override Filter MakeFilter(SpatialArgs args)
{
ValueSource shapeValueSource = MakeShapeValueSource();
ShapePredicateValueSource predicateValueSource = new ShapePredicateValueSource(
shapeValueSource, args.Operation, args.Shape);
return new PredicateValueSourceFilter(predicateValueSource);
}
public virtual ValueSource MakeShapeValueSource()
{
return new ShapeDocValueSource(FieldName, m_ctx.BinaryCodec);
}
internal class PredicateValueSourceFilter : Filter
{
private readonly ValueSource predicateValueSource;
public PredicateValueSourceFilter(ValueSource predicateValueSource)
{
this.predicateValueSource = predicateValueSource;
}
public override DocIdSet GetDocIdSet(AtomicReaderContext context, IBits acceptDocs)
{
return new DocIdSetAnonymousClass(this, context, acceptDocs);
}
private class DocIdSetAnonymousClass : DocIdSet
{
private readonly PredicateValueSourceFilter outerInstance;
private readonly AtomicReaderContext context;
private readonly IBits acceptDocs;
public DocIdSetAnonymousClass(PredicateValueSourceFilter outerInstance, AtomicReaderContext context, IBits acceptDocs)
{
this.outerInstance = outerInstance;
this.context = context;
this.acceptDocs = acceptDocs;
}
public override DocIdSetIterator GetIterator()
{
throw new NotSupportedException(
"Iteration is too slow; instead try FilteredQuery.QUERY_FIRST_FILTER_STRATEGY");
}
public override IBits Bits
{
get
{
FunctionValues predFuncValues = outerInstance.predicateValueSource.GetValues(null, context);
return new BitsAnonymousClass(predFuncValues, context, acceptDocs);
}
}
private class BitsAnonymousClass : IBits
{
private readonly FunctionValues predFuncValues;
private readonly AtomicReaderContext context;
private readonly IBits acceptDocs;
public BitsAnonymousClass(FunctionValues predFuncValues, AtomicReaderContext context, IBits acceptDocs)
{
this.predFuncValues = predFuncValues;
this.context = context;
this.acceptDocs = acceptDocs;
}
public virtual bool Get(int index)
{
if (acceptDocs != null && !acceptDocs.Get(index))
return false;
return predFuncValues.BoolVal(index);
}
public virtual int Length => context.Reader.MaxDoc;
}
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
PredicateValueSourceFilter that = (PredicateValueSourceFilter)o;
if (!predicateValueSource.Equals(that.predicateValueSource)) return false;
return true;
}
public override int GetHashCode()
{
return predicateValueSource.GetHashCode();
}
}
internal class ShapeDocValueSource : ValueSource
{
private readonly string fieldName;
private readonly BinaryCodec binaryCodec;
internal ShapeDocValueSource(string fieldName, BinaryCodec binaryCodec)
{
this.fieldName = fieldName;
this.binaryCodec = binaryCodec;
}
public override FunctionValues GetValues(IDictionary context, AtomicReaderContext readerContext)
{
BinaryDocValues docValues = readerContext.AtomicReader.GetBinaryDocValues(fieldName);
return new FuctionValuesAnonymousClass(this, docValues);
}
private class FuctionValuesAnonymousClass : FunctionValues
{
private readonly ShapeDocValueSource outerInstance;
private readonly BinaryDocValues docValues;
public FuctionValuesAnonymousClass(ShapeDocValueSource outerInstance, BinaryDocValues docValues)
{
this.outerInstance = outerInstance;
this.docValues = docValues;
}
private int bytesRefDoc = -1;
private readonly BytesRef bytesRef = new BytesRef();
internal bool FillBytes(int doc)
{
if (bytesRefDoc != doc)
{
docValues.Get(doc, bytesRef);
bytesRefDoc = doc;
}
return bytesRef.Length != 0;
}
public override bool Exists(int doc)
{
return FillBytes(doc);
}
public override bool BytesVal(int doc, BytesRef target)
{
if (FillBytes(doc))
{
target.Bytes = bytesRef.Bytes;
target.Offset = bytesRef.Offset;
target.Length = bytesRef.Length;
return true;
}
else
{
target.Length = 0;
return false;
}
}
public override object ObjectVal(int docId)
{
if (!FillBytes(docId))
return null;
BinaryReader dataInput = new BinaryReader(
new MemoryStream(bytesRef.Bytes, bytesRef.Offset, bytesRef.Length));
try
{
return outerInstance.binaryCodec.ReadShape(dataInput);
}
catch (IOException e)
{
throw new Exception(e.ToString(), e);
}
}
public override Explanation Explain(int doc)
{
return new Explanation(float.NaN, ToString(doc));
}
public override string ToString(int doc)
{
return outerInstance.GetDescription() + "=" + ObjectVal(doc);
}
}
public override bool Equals(object o)
{
if (this == o) return true;
if (o == null || GetType() != o.GetType()) return false;
ShapeDocValueSource that = (ShapeDocValueSource)o;
if (!fieldName.Equals(that.fieldName, StringComparison.Ordinal)) return false;
return true;
}
public override int GetHashCode()
{
int result = fieldName.GetHashCode();
return result;
}
public override string GetDescription()
{
return "shapeDocVal(" + fieldName + ")";
}
}
}
|
[
"public",
"class",
"SerializedDVStrategy",
":",
"SpatialStrategy",
"{",
"private",
"volatile",
"int",
"indexLastBufSize",
"=",
"8",
"*",
"1024",
";",
"public",
"SerializedDVStrategy",
"(",
"SpatialContext",
"ctx",
",",
"string",
"fieldName",
")",
":",
"base",
"(",
"ctx",
",",
"fieldName",
")",
"{",
"}",
"public",
"override",
"Field",
"[",
"]",
"CreateIndexableFields",
"(",
"IShape",
"shape",
")",
"{",
"int",
"bufSize",
"=",
"Math",
".",
"Max",
"(",
"128",
",",
"(",
"int",
")",
"(",
"this",
".",
"indexLastBufSize",
"*",
"1.5",
")",
")",
";",
"MemoryStream",
"byteStream",
"=",
"new",
"MemoryStream",
"(",
"bufSize",
")",
";",
"BytesRef",
"bytesRef",
"=",
"new",
"BytesRef",
"(",
")",
";",
"try",
"{",
"m_ctx",
".",
"BinaryCodec",
".",
"WriteShape",
"(",
"new",
"BinaryWriter",
"(",
"byteStream",
")",
",",
"shape",
")",
";",
"byteStream",
".",
"WriteTo",
"(",
"new",
"OutputStreamAnonymousClass",
"(",
"bytesRef",
")",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"Exception",
"(",
"e",
".",
"ToString",
"(",
")",
",",
"e",
")",
";",
"}",
"this",
".",
"indexLastBufSize",
"=",
"bytesRef",
".",
"Length",
";",
"return",
"new",
"Field",
"[",
"]",
"{",
"new",
"BinaryDocValuesField",
"(",
"FieldName",
",",
"bytesRef",
")",
"}",
";",
"}",
"private",
"class",
"OutputStreamAnonymousClass",
":",
"MemoryStream",
"{",
"private",
"readonly",
"BytesRef",
"bytesRef",
";",
"public",
"OutputStreamAnonymousClass",
"(",
"BytesRef",
"bytesRef",
")",
"{",
"this",
".",
"bytesRef",
"=",
"bytesRef",
";",
"}",
"public",
"override",
"void",
"Write",
"(",
"byte",
"[",
"]",
"buffer",
",",
"int",
"index",
",",
"int",
"count",
")",
"{",
"bytesRef",
".",
"Bytes",
"=",
"buffer",
";",
"bytesRef",
".",
"Offset",
"=",
"index",
";",
"bytesRef",
".",
"Length",
"=",
"count",
";",
"}",
"}",
"public",
"override",
"ValueSource",
"MakeDistanceValueSource",
"(",
"IPoint",
"queryPoint",
",",
"double",
"multiplier",
")",
"{",
"return",
"new",
"DistanceToShapeValueSource",
"(",
"MakeShapeValueSource",
"(",
")",
",",
"queryPoint",
",",
"multiplier",
",",
"m_ctx",
")",
";",
"}",
"public",
"override",
"ConstantScoreQuery",
"MakeQuery",
"(",
"SpatialArgs",
"args",
")",
"{",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"This strategy can't return a query that operates",
"\"",
"+",
"\"",
" efficiently. Instead try a Filter or ValueSource.",
"\"",
")",
";",
"}",
"public",
"override",
"Filter",
"MakeFilter",
"(",
"SpatialArgs",
"args",
")",
"{",
"ValueSource",
"shapeValueSource",
"=",
"MakeShapeValueSource",
"(",
")",
";",
"ShapePredicateValueSource",
"predicateValueSource",
"=",
"new",
"ShapePredicateValueSource",
"(",
"shapeValueSource",
",",
"args",
".",
"Operation",
",",
"args",
".",
"Shape",
")",
";",
"return",
"new",
"PredicateValueSourceFilter",
"(",
"predicateValueSource",
")",
";",
"}",
"public",
"virtual",
"ValueSource",
"MakeShapeValueSource",
"(",
")",
"{",
"return",
"new",
"ShapeDocValueSource",
"(",
"FieldName",
",",
"m_ctx",
".",
"BinaryCodec",
")",
";",
"}",
"internal",
"class",
"PredicateValueSourceFilter",
":",
"Filter",
"{",
"private",
"readonly",
"ValueSource",
"predicateValueSource",
";",
"public",
"PredicateValueSourceFilter",
"(",
"ValueSource",
"predicateValueSource",
")",
"{",
"this",
".",
"predicateValueSource",
"=",
"predicateValueSource",
";",
"}",
"public",
"override",
"DocIdSet",
"GetDocIdSet",
"(",
"AtomicReaderContext",
"context",
",",
"IBits",
"acceptDocs",
")",
"{",
"return",
"new",
"DocIdSetAnonymousClass",
"(",
"this",
",",
"context",
",",
"acceptDocs",
")",
";",
"}",
"private",
"class",
"DocIdSetAnonymousClass",
":",
"DocIdSet",
"{",
"private",
"readonly",
"PredicateValueSourceFilter",
"outerInstance",
";",
"private",
"readonly",
"AtomicReaderContext",
"context",
";",
"private",
"readonly",
"IBits",
"acceptDocs",
";",
"public",
"DocIdSetAnonymousClass",
"(",
"PredicateValueSourceFilter",
"outerInstance",
",",
"AtomicReaderContext",
"context",
",",
"IBits",
"acceptDocs",
")",
"{",
"this",
".",
"outerInstance",
"=",
"outerInstance",
";",
"this",
".",
"context",
"=",
"context",
";",
"this",
".",
"acceptDocs",
"=",
"acceptDocs",
";",
"}",
"public",
"override",
"DocIdSetIterator",
"GetIterator",
"(",
")",
"{",
"throw",
"new",
"NotSupportedException",
"(",
"\"",
"Iteration is too slow; instead try FilteredQuery.QUERY_FIRST_FILTER_STRATEGY",
"\"",
")",
";",
"}",
"public",
"override",
"IBits",
"Bits",
"{",
"get",
"{",
"FunctionValues",
"predFuncValues",
"=",
"outerInstance",
".",
"predicateValueSource",
".",
"GetValues",
"(",
"null",
",",
"context",
")",
";",
"return",
"new",
"BitsAnonymousClass",
"(",
"predFuncValues",
",",
"context",
",",
"acceptDocs",
")",
";",
"}",
"}",
"private",
"class",
"BitsAnonymousClass",
":",
"IBits",
"{",
"private",
"readonly",
"FunctionValues",
"predFuncValues",
";",
"private",
"readonly",
"AtomicReaderContext",
"context",
";",
"private",
"readonly",
"IBits",
"acceptDocs",
";",
"public",
"BitsAnonymousClass",
"(",
"FunctionValues",
"predFuncValues",
",",
"AtomicReaderContext",
"context",
",",
"IBits",
"acceptDocs",
")",
"{",
"this",
".",
"predFuncValues",
"=",
"predFuncValues",
";",
"this",
".",
"context",
"=",
"context",
";",
"this",
".",
"acceptDocs",
"=",
"acceptDocs",
";",
"}",
"public",
"virtual",
"bool",
"Get",
"(",
"int",
"index",
")",
"{",
"if",
"(",
"acceptDocs",
"!=",
"null",
"&&",
"!",
"acceptDocs",
".",
"Get",
"(",
"index",
")",
")",
"return",
"false",
";",
"return",
"predFuncValues",
".",
"BoolVal",
"(",
"index",
")",
";",
"}",
"public",
"virtual",
"int",
"Length",
"=>",
"context",
".",
"Reader",
".",
"MaxDoc",
";",
"}",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"o",
"==",
"null",
"||",
"GetType",
"(",
")",
"!=",
"o",
".",
"GetType",
"(",
")",
")",
"return",
"false",
";",
"PredicateValueSourceFilter",
"that",
"=",
"(",
"PredicateValueSourceFilter",
")",
"o",
";",
"if",
"(",
"!",
"predicateValueSource",
".",
"Equals",
"(",
"that",
".",
"predicateValueSource",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"{",
"return",
"predicateValueSource",
".",
"GetHashCode",
"(",
")",
";",
"}",
"}",
"internal",
"class",
"ShapeDocValueSource",
":",
"ValueSource",
"{",
"private",
"readonly",
"string",
"fieldName",
";",
"private",
"readonly",
"BinaryCodec",
"binaryCodec",
";",
"internal",
"ShapeDocValueSource",
"(",
"string",
"fieldName",
",",
"BinaryCodec",
"binaryCodec",
")",
"{",
"this",
".",
"fieldName",
"=",
"fieldName",
";",
"this",
".",
"binaryCodec",
"=",
"binaryCodec",
";",
"}",
"public",
"override",
"FunctionValues",
"GetValues",
"(",
"IDictionary",
"context",
",",
"AtomicReaderContext",
"readerContext",
")",
"{",
"BinaryDocValues",
"docValues",
"=",
"readerContext",
".",
"AtomicReader",
".",
"GetBinaryDocValues",
"(",
"fieldName",
")",
";",
"return",
"new",
"FuctionValuesAnonymousClass",
"(",
"this",
",",
"docValues",
")",
";",
"}",
"private",
"class",
"FuctionValuesAnonymousClass",
":",
"FunctionValues",
"{",
"private",
"readonly",
"ShapeDocValueSource",
"outerInstance",
";",
"private",
"readonly",
"BinaryDocValues",
"docValues",
";",
"public",
"FuctionValuesAnonymousClass",
"(",
"ShapeDocValueSource",
"outerInstance",
",",
"BinaryDocValues",
"docValues",
")",
"{",
"this",
".",
"outerInstance",
"=",
"outerInstance",
";",
"this",
".",
"docValues",
"=",
"docValues",
";",
"}",
"private",
"int",
"bytesRefDoc",
"=",
"-",
"1",
";",
"private",
"readonly",
"BytesRef",
"bytesRef",
"=",
"new",
"BytesRef",
"(",
")",
";",
"internal",
"bool",
"FillBytes",
"(",
"int",
"doc",
")",
"{",
"if",
"(",
"bytesRefDoc",
"!=",
"doc",
")",
"{",
"docValues",
".",
"Get",
"(",
"doc",
",",
"bytesRef",
")",
";",
"bytesRefDoc",
"=",
"doc",
";",
"}",
"return",
"bytesRef",
".",
"Length",
"!=",
"0",
";",
"}",
"public",
"override",
"bool",
"Exists",
"(",
"int",
"doc",
")",
"{",
"return",
"FillBytes",
"(",
"doc",
")",
";",
"}",
"public",
"override",
"bool",
"BytesVal",
"(",
"int",
"doc",
",",
"BytesRef",
"target",
")",
"{",
"if",
"(",
"FillBytes",
"(",
"doc",
")",
")",
"{",
"target",
".",
"Bytes",
"=",
"bytesRef",
".",
"Bytes",
";",
"target",
".",
"Offset",
"=",
"bytesRef",
".",
"Offset",
";",
"target",
".",
"Length",
"=",
"bytesRef",
".",
"Length",
";",
"return",
"true",
";",
"}",
"else",
"{",
"target",
".",
"Length",
"=",
"0",
";",
"return",
"false",
";",
"}",
"}",
"public",
"override",
"object",
"ObjectVal",
"(",
"int",
"docId",
")",
"{",
"if",
"(",
"!",
"FillBytes",
"(",
"docId",
")",
")",
"return",
"null",
";",
"BinaryReader",
"dataInput",
"=",
"new",
"BinaryReader",
"(",
"new",
"MemoryStream",
"(",
"bytesRef",
".",
"Bytes",
",",
"bytesRef",
".",
"Offset",
",",
"bytesRef",
".",
"Length",
")",
")",
";",
"try",
"{",
"return",
"outerInstance",
".",
"binaryCodec",
".",
"ReadShape",
"(",
"dataInput",
")",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"Exception",
"(",
"e",
".",
"ToString",
"(",
")",
",",
"e",
")",
";",
"}",
"}",
"public",
"override",
"Explanation",
"Explain",
"(",
"int",
"doc",
")",
"{",
"return",
"new",
"Explanation",
"(",
"float",
".",
"NaN",
",",
"ToString",
"(",
"doc",
")",
")",
";",
"}",
"public",
"override",
"string",
"ToString",
"(",
"int",
"doc",
")",
"{",
"return",
"outerInstance",
".",
"GetDescription",
"(",
")",
"+",
"\"",
"=",
"\"",
"+",
"ObjectVal",
"(",
"doc",
")",
";",
"}",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"o",
")",
"{",
"if",
"(",
"this",
"==",
"o",
")",
"return",
"true",
";",
"if",
"(",
"o",
"==",
"null",
"||",
"GetType",
"(",
")",
"!=",
"o",
".",
"GetType",
"(",
")",
")",
"return",
"false",
";",
"ShapeDocValueSource",
"that",
"=",
"(",
"ShapeDocValueSource",
")",
"o",
";",
"if",
"(",
"!",
"fieldName",
".",
"Equals",
"(",
"that",
".",
"fieldName",
",",
"StringComparison",
".",
"Ordinal",
")",
")",
"return",
"false",
";",
"return",
"true",
";",
"}",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"{",
"int",
"result",
"=",
"fieldName",
".",
"GetHashCode",
"(",
")",
";",
"return",
"result",
";",
"}",
"public",
"override",
"string",
"GetDescription",
"(",
")",
"{",
"return",
"\"",
"shapeDocVal(",
"\"",
"+",
"fieldName",
"+",
"\"",
")",
"\"",
";",
"}",
"}",
"}"
] |
A based on serializing a Shape stored into BinaryDocValues.
|
[
"A",
"based",
"on",
"serializing",
"a",
"Shape",
"stored",
"into",
"BinaryDocValues",
"."
] |
[
"/// <summary>",
"/// A cache heuristic for the buf size based on the last shape size.",
"/// </summary>",
"//TODO do we make this non-volatile since it's merely a heuristic?",
"//8KB default on first run",
"/// <summary>",
"/// Constructs the spatial strategy with its mandatory arguments.",
"/// </summary>",
"//50% headroom over last",
"//receiver of byteStream's bytes",
"//this is a hack to avoid redundant byte array copying by byteStream.toByteArray()",
"//cache heuristic",
"//TODO if makeShapeValueSource gets lifted to the top; this could become a generic impl.",
"/// <summary>",
"/// Returns a <see cref=\"Filter\"/> that should be used with <see cref=\"FilteredQuery.QUERY_FIRST_FILTER_STRATEGY\"/>.",
"/// Use in another manner is likely to result in an <see cref=\"NotSupportedException\"/>",
"/// to prevent misuse because the filter can't efficiently work via iteration.",
"/// </summary>",
"/// <summary>",
"/// Provides access to each shape per document as a ValueSource in which",
"/// <see cref=\"FunctionValues.ObjectVal(int)\"/> returns a <see cref=\"IShape\"/>.",
"/// </summary>",
"//TODO raise to SpatialStrategy",
"/// <summary>",
"/// This filter only supports returning a DocSet with a GetBits(). If you try to grab the",
"/// iterator then you'll get a <see cref=\"NotSupportedException\"/>.",
"/// </summary>",
"//we call boolVal(doc)",
"//Note that if you're truly bent on doing this, then see FunctionValues.getRangeScorer",
"//null Map context -- we simply don't have one. That's ok.",
"//PredicateValueSourceFilter",
"/// <summary>",
"/// Implements a <see cref=\"ValueSource\"/> by deserializing a <see cref=\"IShape\"/> in from <see cref=\"BinaryDocValues\"/> using <see cref=\"BinaryCodec\"/>.",
"/// </summary>",
"/// <seealso cref=\"MakeShapeValueSource()\"/>",
"//spatial4n",
"//scratch",
"//TODO truncate?",
"//ShapeDocValueSource"
] |
[
{
"param": "SpatialStrategy",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "SpatialStrategy",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,565
| 114
|
1010dd25f46298f94f6d561b35e7daa0d0bc3dcf
|
sebasgo/OpenMDAO
|
openmdao/visualization/n2_viewer/src/N2TreeNode.js
|
[
"Apache-2.0"
] |
JavaScript
|
N2TreeNode
|
/**
* Essentially the same as a JSON object from the model tree,
* with some utility functions.
* @typedef {N2TreeNode}
* @property {Object} dims The size and location of the node when drawn.
* @property {Object} prevDims The previous value of dims.
* @property {Object} solverDims The size and location of the node within the solver tree.
* @property {Object} prevSolverDims The previous value of solverDims.
* @property {Boolean} isMinimized Whether this node or a parent has been collapsed.
* @property {Number} nameWidthPx The width of the name in pixels as computed by N2Layout.
* @property {Boolean} manuallyExpanded If this node was right-clicked.
* @property {Number} depth The index of the column this node appears in.
*/
|
Essentially the same as a JSON object from the model tree,
with some utility functions.
@typedef {N2TreeNode}
@property {Object} dims The size and location of the node when drawn.
@property {Object} prevDims The previous value of dims.
@property {Object} solverDims The size and location of the node within the solver tree.
@property {Object} prevSolverDims The previous value of solverDims.
@property {Boolean} isMinimized Whether this node or a parent has been collapsed.
@property {Number} nameWidthPx The width of the name in pixels as computed by N2Layout.
@property {Boolean} manuallyExpanded If this node was right-clicked.
@property {Number} depth The index of the column this node appears in.
|
[
"Essentially",
"the",
"same",
"as",
"a",
"JSON",
"object",
"from",
"the",
"model",
"tree",
"with",
"some",
"utility",
"functions",
".",
"@typedef",
"{",
"N2TreeNode",
"}",
"@property",
"{",
"Object",
"}",
"dims",
"The",
"size",
"and",
"location",
"of",
"the",
"node",
"when",
"drawn",
".",
"@property",
"{",
"Object",
"}",
"prevDims",
"The",
"previous",
"value",
"of",
"dims",
".",
"@property",
"{",
"Object",
"}",
"solverDims",
"The",
"size",
"and",
"location",
"of",
"the",
"node",
"within",
"the",
"solver",
"tree",
".",
"@property",
"{",
"Object",
"}",
"prevSolverDims",
"The",
"previous",
"value",
"of",
"solverDims",
".",
"@property",
"{",
"Boolean",
"}",
"isMinimized",
"Whether",
"this",
"node",
"or",
"a",
"parent",
"has",
"been",
"collapsed",
".",
"@property",
"{",
"Number",
"}",
"nameWidthPx",
"The",
"width",
"of",
"the",
"name",
"in",
"pixels",
"as",
"computed",
"by",
"N2Layout",
".",
"@property",
"{",
"Boolean",
"}",
"manuallyExpanded",
"If",
"this",
"node",
"was",
"right",
"-",
"clicked",
".",
"@property",
"{",
"Number",
"}",
"depth",
"The",
"index",
"of",
"the",
"column",
"this",
"node",
"appears",
"in",
"."
] |
class N2TreeNode {
/**
* Absorb all the properties of the provided JSON object from the model tree.
* @param {Object} origNode The node to work from.
*/
constructor(origNode) {
// Merge all of the props from the original JSON tree node to us.
Object.assign(this, origNode);
this.sourceParentSet = new Set();
this.targetParentSet = new Set();
this.nameWidthPx = 1; // Set by N2Layout
this.numLeaves = 0; // Set by N2Layout
this.isMinimized = false;
this.manuallyExpanded = false;
this.childNames = new Set(); // Set by ModelData
this.depth = -1; // Set by ModelData
this.parent = null; // Set by ModelData
this.id = -1; // Set by ModelData
this.absPathName = ''; // Set by ModelData
this.numDescendants = 0; // Set by ModelData
// Solver names may be empty, so set them to "None" instead.
if (this.linear_solver == "") this.linear_solver = "None";
if (this.nonlinear_solver == "") this.nonlinear_solver = "None";
this.rootIndex = -1;
this.dims = {
'x': 1e-6,
'y': 1e-6,
'width': 1,
'height': 1
};
this.prevDims = {
'x': 1e-6,
'y': 1e-6,
'width': 1e-6,
'height': 1e-6
};
this.solverDims = {
'x': 1e-6,
'y': 1e-6,
'width': 1,
'height': 1
};
this.prevSolverDims = {
'x': 1e-6,
'y': 1e-6,
'width': 1e-6,
'height': 1e-6
};
}
/** Run when a node is collapsed. */
minimize() {
this.isMinimized = true;
}
/** Run when a node is restored. */
expand() {
this.isMinimized = false;
}
/**
* Create a backup of our position and other info.
* @param {boolean} solver Whether to use .dims or .solverDims.
* @param {number} leafNum Identify this as the nth leaf of the tree
*/
preserveDims(solver, leafNum) {
let dimProp = solver ? 'dims' : 'solverDims';
let prevDimProp = solver ? 'prevDims' : 'prevSolverDims';
Object.assign(this[prevDimProp], this[dimProp]);
if (this.rootIndex < 0) this.rootIndex = leafNum;
this.prevRootIndex = this.rootIndex;
}
/**
* Determine if the children array exists and has members.
* @param {string} [childrenPropName = 'children'] Usually children, but
* sometimes 'subsystem_children'
* @return {boolean} True if the children property is an Array and length > 0.
*/
hasChildren(childrenPropName = 'children') {
return (Array.isPopulatedArray(this[childrenPropName]));
}
/** True if this.type is 'input' or 'unconnected_input'. */
isInput() {
return this.type.match(inputRegex);
}
/** True if this is an input and connected. */
isConnectedInput() { return (this.type == 'input'); }
/** True if this an input and unconnected. */
isUnconnectedInput() { return (this.type == 'unconnected_input'); }
/** True if this is an input whose source is an auto-ivc'd output */
isAutoIvcInput() { return (this.type == 'autoivc_input'); }
/** True if this.type is 'output'. */
isOutput() { return (this.type == 'output'); }
/** True if this is the root node in the model */
isRoot() { return (this.type == 'root'); }
/** True if this is an output and it's not implicit */
isExplicitOutput() { return (this.isOutput() && !this.implicit); }
/** True if this is an output and it is implicit */
isImplicitOutput() { return (this.isOutput() && this.implicit); }
/** True if this.type is 'input', 'unconnected_input', or 'output'. */
isInputOrOutput() { return this.type.match(inputOrOutputRegex); }
/** True is this.type is 'subsystem' */
isSubsystem() { return (this.type == 'subsystem'); }
/** True if it's a subsystem and this.subsystem_type is 'group' */
isGroup() { return (this.isSubsystem() && this.subsystem_type == 'group'); }
/** True if it's a subsystem and this.subsystem_type is 'component' */
isComponent() { return (this.isSubsystem() && this.subsystem_type == 'component'); }
/** Not connectable if this is a input group or parents are minimized. */
isConnectable() {
if (this.isInputOrOutput() && !(this.hasChildren() ||
this.parent.isMinimized || this.parentComponent.isMinimized)) return true;
return this.isMinimized;
}
/** Return false if the node is minimized or hidden */
isVisible() {
return !(this.varIsHidden || this.isMinimized);
}
/**
* Look for the supplied node in the set of child names.
* @returns {Boolean} True if a match is found, otherwise false.
*/
hasNodeInChildren(compareNode) {
return this.childNames.has(compareNode.absPathName);
}
/** Look for the supplied node in the parentage of this one.
* @param {N2TreeNode} compareNode The node to look for.
* @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent.
* @returns {Boolean} True if the node is found, otherwise false.
*/
hasParent(compareNode, parentLimit = null) {
for (let obj = this.parent; obj != null && obj !== parentLimit; obj = obj.parent) {
if (obj === compareNode) {
return true;
}
}
return false;
}
/**
* Look for the supplied node in the lineage of this one.
* @param {N2TreeNode} compareNode The node to look for.
* @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent.
* @returns {Boolean} True if the node is found, otherwise false.
*/
hasNode(compareNode, parentLimit = null) {
if (this.type == 'root') return true;
if (this === compareNode) return true;
// Check parents first.
if (this.hasParent(compareNode, parentLimit)) return true;
return this.hasNodeInChildren(compareNode);
}
/**
* Add ourselves to the supplied array if we contain a cycleArrows property.
* @param {Array} arr The array to add to.
*/
_getNodesInChildrenWithCycleArrows(arr) {
if (this.cycleArrows) {
arr.push(this);
}
if (this.hasChildren()) {
for (let child of this.children) {
child._getNodesInChildrenWithCycleArrows(arr);
}
}
}
/**
* Populate an array with nodes in our lineage that contain a cycleArrows member.
* @returns {Array} The array containing all the found nodes with cycleArrows.
*/
getNodesWithCycleArrows() {
let arr = [];
// Check parents first.
for (let obj = this.parent; obj != null; obj = obj.parent) {
if (obj.cycleArrows) {
arr.push(obj);
}
}
// Check all descendants as well.
this._getNodesInChildrenWithCycleArrows(arr);
return arr;
}
/**
* Find the closest parent shared by two nodes; farthest should be tree root.
* @param {N2TreeNode} other Another node to compare parents with.
* @returns {N2TreeNode} The first common parent found.
*/
nearestCommonParent(other) {
for (let myParent = this.parent; myParent != null; myParent = myParent.parent)
for (let otherParent = other.parent; otherParent != null; otherParent = otherParent.parent)
if (myParent === otherParent) return myParent;
// Should never get here because root is parent of all
debugInfo("No common parent found between two nodes: ", this, other);
return null;
}
/**
* If the node has a lot of descendants and it wasn't manually expanded,
* minimize it.
* @param {Number} depthCount The number of nodes at the next depth down.
* @returns {Boolean} True if minimized here, false otherwise.
*/
minimizeIfLarge(depthCount) {
if (!(this.isRoot() || this.manuallyExpanded) &&
(this.depth >= (this.isComponent() ?
Precollapse.cmpDepthStart : Precollapse.grpDepthStart) &&
this.numDescendants > Precollapse.threshold &&
this.children.length > Precollapse.children - this.depth &&
depthCount > Precollapse.depthLimit)) {
debugInfo(`Precollapsing node ${this.absPathName}`)
this.minimize();
return true;
}
return false;
}
/**
* Convert an absolute path name to a string that's safe to use as an HTML id.
* @param {String} absPathName The name to convert.
* @returns {String} The HTML-safe id.
*/
static absPathToId(absPathName) {
return absPathName.replace(/[\.<> :]/g, function (c) {
return {
' ': '__',
'<': '_LT',
'>': '_GT',
'.': '_',
':': '-'
}[c];
})
}
}
|
[
"class",
"N2TreeNode",
"{",
"constructor",
"(",
"origNode",
")",
"{",
"Object",
".",
"assign",
"(",
"this",
",",
"origNode",
")",
";",
"this",
".",
"sourceParentSet",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"targetParentSet",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"nameWidthPx",
"=",
"1",
";",
"this",
".",
"numLeaves",
"=",
"0",
";",
"this",
".",
"isMinimized",
"=",
"false",
";",
"this",
".",
"manuallyExpanded",
"=",
"false",
";",
"this",
".",
"childNames",
"=",
"new",
"Set",
"(",
")",
";",
"this",
".",
"depth",
"=",
"-",
"1",
";",
"this",
".",
"parent",
"=",
"null",
";",
"this",
".",
"id",
"=",
"-",
"1",
";",
"this",
".",
"absPathName",
"=",
"''",
";",
"this",
".",
"numDescendants",
"=",
"0",
";",
"if",
"(",
"this",
".",
"linear_solver",
"==",
"\"\"",
")",
"this",
".",
"linear_solver",
"=",
"\"None\"",
";",
"if",
"(",
"this",
".",
"nonlinear_solver",
"==",
"\"\"",
")",
"this",
".",
"nonlinear_solver",
"=",
"\"None\"",
";",
"this",
".",
"rootIndex",
"=",
"-",
"1",
";",
"this",
".",
"dims",
"=",
"{",
"'x'",
":",
"1e-6",
",",
"'y'",
":",
"1e-6",
",",
"'width'",
":",
"1",
",",
"'height'",
":",
"1",
"}",
";",
"this",
".",
"prevDims",
"=",
"{",
"'x'",
":",
"1e-6",
",",
"'y'",
":",
"1e-6",
",",
"'width'",
":",
"1e-6",
",",
"'height'",
":",
"1e-6",
"}",
";",
"this",
".",
"solverDims",
"=",
"{",
"'x'",
":",
"1e-6",
",",
"'y'",
":",
"1e-6",
",",
"'width'",
":",
"1",
",",
"'height'",
":",
"1",
"}",
";",
"this",
".",
"prevSolverDims",
"=",
"{",
"'x'",
":",
"1e-6",
",",
"'y'",
":",
"1e-6",
",",
"'width'",
":",
"1e-6",
",",
"'height'",
":",
"1e-6",
"}",
";",
"}",
"minimize",
"(",
")",
"{",
"this",
".",
"isMinimized",
"=",
"true",
";",
"}",
"expand",
"(",
")",
"{",
"this",
".",
"isMinimized",
"=",
"false",
";",
"}",
"preserveDims",
"(",
"solver",
",",
"leafNum",
")",
"{",
"let",
"dimProp",
"=",
"solver",
"?",
"'dims'",
":",
"'solverDims'",
";",
"let",
"prevDimProp",
"=",
"solver",
"?",
"'prevDims'",
":",
"'prevSolverDims'",
";",
"Object",
".",
"assign",
"(",
"this",
"[",
"prevDimProp",
"]",
",",
"this",
"[",
"dimProp",
"]",
")",
";",
"if",
"(",
"this",
".",
"rootIndex",
"<",
"0",
")",
"this",
".",
"rootIndex",
"=",
"leafNum",
";",
"this",
".",
"prevRootIndex",
"=",
"this",
".",
"rootIndex",
";",
"}",
"hasChildren",
"(",
"childrenPropName",
"=",
"'children'",
")",
"{",
"return",
"(",
"Array",
".",
"isPopulatedArray",
"(",
"this",
"[",
"childrenPropName",
"]",
")",
")",
";",
"}",
"isInput",
"(",
")",
"{",
"return",
"this",
".",
"type",
".",
"match",
"(",
"inputRegex",
")",
";",
"}",
"isConnectedInput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'input'",
")",
";",
"}",
"isUnconnectedInput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'unconnected_input'",
")",
";",
"}",
"isAutoIvcInput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'autoivc_input'",
")",
";",
"}",
"isOutput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'output'",
")",
";",
"}",
"isRoot",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'root'",
")",
";",
"}",
"isExplicitOutput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"isOutput",
"(",
")",
"&&",
"!",
"this",
".",
"implicit",
")",
";",
"}",
"isImplicitOutput",
"(",
")",
"{",
"return",
"(",
"this",
".",
"isOutput",
"(",
")",
"&&",
"this",
".",
"implicit",
")",
";",
"}",
"isInputOrOutput",
"(",
")",
"{",
"return",
"this",
".",
"type",
".",
"match",
"(",
"inputOrOutputRegex",
")",
";",
"}",
"isSubsystem",
"(",
")",
"{",
"return",
"(",
"this",
".",
"type",
"==",
"'subsystem'",
")",
";",
"}",
"isGroup",
"(",
")",
"{",
"return",
"(",
"this",
".",
"isSubsystem",
"(",
")",
"&&",
"this",
".",
"subsystem_type",
"==",
"'group'",
")",
";",
"}",
"isComponent",
"(",
")",
"{",
"return",
"(",
"this",
".",
"isSubsystem",
"(",
")",
"&&",
"this",
".",
"subsystem_type",
"==",
"'component'",
")",
";",
"}",
"isConnectable",
"(",
")",
"{",
"if",
"(",
"this",
".",
"isInputOrOutput",
"(",
")",
"&&",
"!",
"(",
"this",
".",
"hasChildren",
"(",
")",
"||",
"this",
".",
"parent",
".",
"isMinimized",
"||",
"this",
".",
"parentComponent",
".",
"isMinimized",
")",
")",
"return",
"true",
";",
"return",
"this",
".",
"isMinimized",
";",
"}",
"isVisible",
"(",
")",
"{",
"return",
"!",
"(",
"this",
".",
"varIsHidden",
"||",
"this",
".",
"isMinimized",
")",
";",
"}",
"hasNodeInChildren",
"(",
"compareNode",
")",
"{",
"return",
"this",
".",
"childNames",
".",
"has",
"(",
"compareNode",
".",
"absPathName",
")",
";",
"}",
"hasParent",
"(",
"compareNode",
",",
"parentLimit",
"=",
"null",
")",
"{",
"for",
"(",
"let",
"obj",
"=",
"this",
".",
"parent",
";",
"obj",
"!=",
"null",
"&&",
"obj",
"!==",
"parentLimit",
";",
"obj",
"=",
"obj",
".",
"parent",
")",
"{",
"if",
"(",
"obj",
"===",
"compareNode",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}",
"hasNode",
"(",
"compareNode",
",",
"parentLimit",
"=",
"null",
")",
"{",
"if",
"(",
"this",
".",
"type",
"==",
"'root'",
")",
"return",
"true",
";",
"if",
"(",
"this",
"===",
"compareNode",
")",
"return",
"true",
";",
"if",
"(",
"this",
".",
"hasParent",
"(",
"compareNode",
",",
"parentLimit",
")",
")",
"return",
"true",
";",
"return",
"this",
".",
"hasNodeInChildren",
"(",
"compareNode",
")",
";",
"}",
"_getNodesInChildrenWithCycleArrows",
"(",
"arr",
")",
"{",
"if",
"(",
"this",
".",
"cycleArrows",
")",
"{",
"arr",
".",
"push",
"(",
"this",
")",
";",
"}",
"if",
"(",
"this",
".",
"hasChildren",
"(",
")",
")",
"{",
"for",
"(",
"let",
"child",
"of",
"this",
".",
"children",
")",
"{",
"child",
".",
"_getNodesInChildrenWithCycleArrows",
"(",
"arr",
")",
";",
"}",
"}",
"}",
"getNodesWithCycleArrows",
"(",
")",
"{",
"let",
"arr",
"=",
"[",
"]",
";",
"for",
"(",
"let",
"obj",
"=",
"this",
".",
"parent",
";",
"obj",
"!=",
"null",
";",
"obj",
"=",
"obj",
".",
"parent",
")",
"{",
"if",
"(",
"obj",
".",
"cycleArrows",
")",
"{",
"arr",
".",
"push",
"(",
"obj",
")",
";",
"}",
"}",
"this",
".",
"_getNodesInChildrenWithCycleArrows",
"(",
"arr",
")",
";",
"return",
"arr",
";",
"}",
"nearestCommonParent",
"(",
"other",
")",
"{",
"for",
"(",
"let",
"myParent",
"=",
"this",
".",
"parent",
";",
"myParent",
"!=",
"null",
";",
"myParent",
"=",
"myParent",
".",
"parent",
")",
"for",
"(",
"let",
"otherParent",
"=",
"other",
".",
"parent",
";",
"otherParent",
"!=",
"null",
";",
"otherParent",
"=",
"otherParent",
".",
"parent",
")",
"if",
"(",
"myParent",
"===",
"otherParent",
")",
"return",
"myParent",
";",
"debugInfo",
"(",
"\"No common parent found between two nodes: \"",
",",
"this",
",",
"other",
")",
";",
"return",
"null",
";",
"}",
"minimizeIfLarge",
"(",
"depthCount",
")",
"{",
"if",
"(",
"!",
"(",
"this",
".",
"isRoot",
"(",
")",
"||",
"this",
".",
"manuallyExpanded",
")",
"&&",
"(",
"this",
".",
"depth",
">=",
"(",
"this",
".",
"isComponent",
"(",
")",
"?",
"Precollapse",
".",
"cmpDepthStart",
":",
"Precollapse",
".",
"grpDepthStart",
")",
"&&",
"this",
".",
"numDescendants",
">",
"Precollapse",
".",
"threshold",
"&&",
"this",
".",
"children",
".",
"length",
">",
"Precollapse",
".",
"children",
"-",
"this",
".",
"depth",
"&&",
"depthCount",
">",
"Precollapse",
".",
"depthLimit",
")",
")",
"{",
"debugInfo",
"(",
"`",
"${",
"this",
".",
"absPathName",
"}",
"`",
")",
"this",
".",
"minimize",
"(",
")",
";",
"return",
"true",
";",
"}",
"return",
"false",
";",
"}",
"static",
"absPathToId",
"(",
"absPathName",
")",
"{",
"return",
"absPathName",
".",
"replace",
"(",
"/",
"[\\.<> :]",
"/",
"g",
",",
"function",
"(",
"c",
")",
"{",
"return",
"{",
"' '",
":",
"'__'",
",",
"'<'",
":",
"'_LT'",
",",
"'>'",
":",
"'_GT'",
",",
"'.'",
":",
"'_'",
",",
"':'",
":",
"'-'",
"}",
"[",
"c",
"]",
";",
"}",
")",
"}",
"}"
] |
Essentially the same as a JSON object from the model tree,
with some utility functions.
|
[
"Essentially",
"the",
"same",
"as",
"a",
"JSON",
"object",
"from",
"the",
"model",
"tree",
"with",
"some",
"utility",
"functions",
"."
] |
[
"/**\n * Absorb all the properties of the provided JSON object from the model tree.\n * @param {Object} origNode The node to work from.\n */",
"// Merge all of the props from the original JSON tree node to us.",
"// Set by N2Layout",
"// Set by N2Layout",
"// Set by ModelData",
"// Set by ModelData",
"// Set by ModelData",
"// Set by ModelData",
"// Set by ModelData",
"// Set by ModelData",
"// Solver names may be empty, so set them to \"None\" instead.",
"/** Run when a node is collapsed. */",
"/** Run when a node is restored. */",
"/**\n * Create a backup of our position and other info.\n * @param {boolean} solver Whether to use .dims or .solverDims.\n * @param {number} leafNum Identify this as the nth leaf of the tree\n */",
"/**\n * Determine if the children array exists and has members.\n * @param {string} [childrenPropName = 'children'] Usually children, but\n * sometimes 'subsystem_children'\n * @return {boolean} True if the children property is an Array and length > 0.\n */",
"/** True if this.type is 'input' or 'unconnected_input'. */",
"/** True if this is an input and connected. */",
"/** True if this an input and unconnected. */",
"/** True if this is an input whose source is an auto-ivc'd output */",
"/** True if this.type is 'output'. */",
"/** True if this is the root node in the model */",
"/** True if this is an output and it's not implicit */",
"/** True if this is an output and it is implicit */",
"/** True if this.type is 'input', 'unconnected_input', or 'output'. */",
"/** True is this.type is 'subsystem' */",
"/** True if it's a subsystem and this.subsystem_type is 'group' */",
"/** True if it's a subsystem and this.subsystem_type is 'component' */",
"/** Not connectable if this is a input group or parents are minimized. */",
"/** Return false if the node is minimized or hidden */",
"/**\n * Look for the supplied node in the set of child names.\n * @returns {Boolean} True if a match is found, otherwise false.\n */",
"/** Look for the supplied node in the parentage of this one.\n * @param {N2TreeNode} compareNode The node to look for.\n * @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent.\n * @returns {Boolean} True if the node is found, otherwise false.\n */",
"/**\n * Look for the supplied node in the lineage of this one.\n * @param {N2TreeNode} compareNode The node to look for.\n * @param {N2TreeNode} [parentLimit = null] Stop searching at this common parent.\n * @returns {Boolean} True if the node is found, otherwise false.\n */",
"// Check parents first.",
"/**\n * Add ourselves to the supplied array if we contain a cycleArrows property.\n * @param {Array} arr The array to add to.\n */",
"/**\n * Populate an array with nodes in our lineage that contain a cycleArrows member.\n * @returns {Array} The array containing all the found nodes with cycleArrows.\n */",
"// Check parents first.",
"// Check all descendants as well.",
"/**\n * Find the closest parent shared by two nodes; farthest should be tree root.\n * @param {N2TreeNode} other Another node to compare parents with.\n * @returns {N2TreeNode} The first common parent found.\n */",
"// Should never get here because root is parent of all",
"/**\n * If the node has a lot of descendants and it wasn't manually expanded,\n * minimize it.\n * @param {Number} depthCount The number of nodes at the next depth down.\n * @returns {Boolean} True if minimized here, false otherwise.\n */",
"/**\n * Convert an absolute path name to a string that's safe to use as an HTML id.\n * @param {String} absPathName The name to convert.\n * @returns {String} The HTML-safe id.\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 2,218
| 171
|
8b6c6852dbffe3275f4d3edf8ea8411c61521f9f
|
appfolio/rails_best_practices
|
lib/rails_best_practices/core/runner.rb
|
[
"MIT"
] |
Ruby
|
Runner
|
# Runner is the main class, it can check source code of a filename with all checks (according to the configuration).
#
# the check process is partitioned into two parts,
#
# 1. prepare process, it will do some preparations for further checking, such as remember the model associations.
# 2. review process, it does real check, if the source code violates some best practices, the violations will be notified.
|
Runner is the main class, it can check source code of a filename with all checks (according to the configuration).
the check process is partitioned into two parts.
1. prepare process, it will do some preparations for further checking, such as remember the model associations.
2. review process, it does real check, if the source code violates some best practices, the violations will be notified.
|
[
"Runner",
"is",
"the",
"main",
"class",
"it",
"can",
"check",
"source",
"code",
"of",
"a",
"filename",
"with",
"all",
"checks",
"(",
"according",
"to",
"the",
"configuration",
")",
".",
"the",
"check",
"process",
"is",
"partitioned",
"into",
"two",
"parts",
".",
"1",
".",
"prepare",
"process",
"it",
"will",
"do",
"some",
"preparations",
"for",
"further",
"checking",
"such",
"as",
"remember",
"the",
"model",
"associations",
".",
"2",
".",
"review",
"process",
"it",
"does",
"real",
"check",
"if",
"the",
"source",
"code",
"violates",
"some",
"best",
"practices",
"the",
"violations",
"will",
"be",
"notified",
"."
] |
class Runner
attr_reader :checks
attr_accessor :debug, :whiny, :color
# set the base path.
#
# @param [String] path the base path
def self.base_path=(path)
@base_path = path
end
# get the base path, by default, the base path is current path.
#
# @return [String] the base path
def self.base_path
@base_path || "."
end
# initialize the runner.
#
# @param [Hash] options pass the prepares and reviews.
def initialize(options={})
custom_config = File.join(Runner.base_path, 'config/rails_best_practices.yml')
@config = File.exists?(custom_config) ? custom_config : RailsBestPractices::Analyzer::DEFAULT_CONFIG
lexicals = Array(options[:lexicals])
prepares = Array(options[:prepares])
reviews = Array(options[:reviews])
@lexicals = lexicals.empty? ? load_lexicals : lexicals
@prepares = prepares.empty? ? load_prepares : prepares
@reviews = reviews.empty? ? load_reviews : reviews
load_plugin_reviews if reviews.empty?
@checker ||= CheckingVisitor.new(:prepares => @prepares, :reviews => @reviews, :lexicals => @lexicals)
@debug = false
@whiny = false
end
# lexical analysis the file.
#
# @param [String] filename name of the file
# @param [String] content content of the file
def lexical(filename, content)
puts filename if @debug
@checker.lexical(filename, content)
end
# lexical analysis the file.
#
# @param [String] filename
def lexical_file(filename)
lexical(filename, read_file(filename))
end
# parepare a file's content with filename.
#
# @param [String] filename name of the file
# @param [String] content content of the file
def prepare(filename, content)
puts filename if @debug
node = parse_ruby(filename, content)
if node
node.file = filename
node.prepare(@checker)
end
end
# parapare the file.
#
# @param [String] filename
def prepare_file(filename)
prepare(filename, read_file(filename))
end
# review a file's content with filename.
#
# @param [String] filename name of the file
# @param [String] content content of the file
def review(filename, content)
puts filename if @debug
content = parse_html_template(filename, content)
node = parse_ruby(filename, content)
if node
node.file = filename
node.review(@checker)
end
end
# review the file.
#
# @param [String] filename
def review_file(filename)
review(filename, read_file(filename))
end
# get all errors from lexicals and reviews.
#
# @return [Array] all errors from lexicals and reviews
def errors
(@reviews + @lexicals).collect {|check| check.errors}.flatten
end
def after_lexical; end
# provide a handler after all files reviewed.
def after_prepare
filename = "rails_best_practices.after_prepare"
content = "class RailsBestPractices::AfterPrepare; end"
node = parse_ruby(filename, content)
node.file = filename
node.prepare(@checker)
end
# provide a handler after all files reviewed.
def after_review
filename = "rails_best_practices.after_review"
content = "class RailsBestPractices::AfterReview; end"
node = parse_ruby(filename, content)
node.file = filename
node.review(@checker)
end
private
# parse ruby code.
#
# @param [String] filename is the filename of ruby file.
# @param [String] content is the source code of ruby file.
def parse_ruby(filename, content)
begin
Sexp.from_array(Ripper::SexpBuilder.new(content).parse)
rescue Exception => e
if @debug
warning = "#{filename} looks like it's not a valid Ruby file. Skipping..."
warning = warning.red if self.color
puts warning
end
raise e if @whiny
nil
end
end
# parse html tempalte code, erb, haml and slim.
#
# @param [String] filename is the filename of the erb, haml or slim code.
# @param [String] content is the source code of erb, haml or slim file.
def parse_html_template(filename, content)
if filename =~ /.*\.erb$|.*\.rhtml$/
content = Erubis::OnlyRuby.new(content).src
elsif filename =~ /.*\.haml$/
begin
require 'haml'
content = Haml::Engine.new(content, {:ugly => true}).precompiled
# remove \xxx characters
content.gsub!(/\\\d{3}/, '')
rescue LoadError
raise "In order to parse #{filename}, please install the haml gem"
rescue Haml::Error, SyntaxError
# do nothing, just ignore the wrong haml files.
end
elsif filename =~ /.*\.slim$/
begin
require 'slim'
content = Slim::Engine.new.call(content)
rescue LoadError
raise "In order to parse #{filename}, please install the slim gem"
rescue SyntaxError
# do nothing, just ignore the wrong slim files
end
end
content
end
# load all lexical checks.
def load_lexicals
checks_from_config.inject([]) { |active_checks, check|
begin
check_name, options = *check
klass = RailsBestPractices::Lexicals.const_get(check_name)
active_checks << (options.empty? ? klass.new : klass.new(options))
rescue
# the check does not exist in the Lexicals namepace.
end
active_checks
}
end
# load all prepares.
def load_prepares
Prepares.constants.map { |prepare| Prepares.const_get(prepare).new }
end
# load all reviews according to configuration.
def load_reviews
checks_from_config.inject([]) { |active_checks, check|
begin
check_name, options = *check
klass = RailsBestPractices::Reviews.const_get(check_name.gsub(/Check/, 'Review'))
active_checks << (options.empty? ? klass.new : klass.new(options))
rescue
# the check does not exist in the Reviews namepace.
end
active_checks
}
end
# load all plugin reviews.
def load_plugin_reviews
begin
plugins = File.join(Runner.base_path, 'lib', 'rails_best_practices', 'plugins', 'reviews')
if File.directory?(plugins)
Dir[File.expand_path(File.join(plugins, "*.rb"))].each do |review|
require review
end
if RailsBestPractices.constants.map(&:to_sym).include? :Plugins
RailsBestPractices::Plugins::Reviews.constants.each do |review|
@reviews << RailsBestPractices::Plugins::Reviews.const_get(review).new
end
end
end
end
end
# read the checks from yaml config.
def checks_from_config
@checks ||= YAML.load_file @config
end
# read the file content.
#
# @param [String] filename
# @return [String] file conent
def read_file(filename)
File.open(filename, "r:UTF-8") { |f| f.read }
end
end
|
[
"class",
"Runner",
"attr_reader",
":checks",
"attr_accessor",
":debug",
",",
":whiny",
",",
":color",
"def",
"self",
".",
"base_path",
"=",
"(",
"path",
")",
"@base_path",
"=",
"path",
"end",
"def",
"self",
".",
"base_path",
"@base_path",
"||",
"\".\"",
"end",
"def",
"initialize",
"(",
"options",
"=",
"{",
"}",
")",
"custom_config",
"=",
"File",
".",
"join",
"(",
"Runner",
".",
"base_path",
",",
"'config/rails_best_practices.yml'",
")",
"@config",
"=",
"File",
".",
"exists?",
"(",
"custom_config",
")",
"?",
"custom_config",
":",
"RailsBestPractices",
"::",
"Analyzer",
"::",
"DEFAULT_CONFIG",
"lexicals",
"=",
"Array",
"(",
"options",
"[",
":lexicals",
"]",
")",
"prepares",
"=",
"Array",
"(",
"options",
"[",
":prepares",
"]",
")",
"reviews",
"=",
"Array",
"(",
"options",
"[",
":reviews",
"]",
")",
"@lexicals",
"=",
"lexicals",
".",
"empty?",
"?",
"load_lexicals",
":",
"lexicals",
"@prepares",
"=",
"prepares",
".",
"empty?",
"?",
"load_prepares",
":",
"prepares",
"@reviews",
"=",
"reviews",
".",
"empty?",
"?",
"load_reviews",
":",
"reviews",
"load_plugin_reviews",
"if",
"reviews",
".",
"empty?",
"@checker",
"||=",
"CheckingVisitor",
".",
"new",
"(",
":prepares",
"=>",
"@prepares",
",",
":reviews",
"=>",
"@reviews",
",",
":lexicals",
"=>",
"@lexicals",
")",
"@debug",
"=",
"false",
"@whiny",
"=",
"false",
"end",
"def",
"lexical",
"(",
"filename",
",",
"content",
")",
"puts",
"filename",
"if",
"@debug",
"@checker",
".",
"lexical",
"(",
"filename",
",",
"content",
")",
"end",
"def",
"lexical_file",
"(",
"filename",
")",
"lexical",
"(",
"filename",
",",
"read_file",
"(",
"filename",
")",
")",
"end",
"def",
"prepare",
"(",
"filename",
",",
"content",
")",
"puts",
"filename",
"if",
"@debug",
"node",
"=",
"parse_ruby",
"(",
"filename",
",",
"content",
")",
"if",
"node",
"node",
".",
"file",
"=",
"filename",
"node",
".",
"prepare",
"(",
"@checker",
")",
"end",
"end",
"def",
"prepare_file",
"(",
"filename",
")",
"prepare",
"(",
"filename",
",",
"read_file",
"(",
"filename",
")",
")",
"end",
"def",
"review",
"(",
"filename",
",",
"content",
")",
"puts",
"filename",
"if",
"@debug",
"content",
"=",
"parse_html_template",
"(",
"filename",
",",
"content",
")",
"node",
"=",
"parse_ruby",
"(",
"filename",
",",
"content",
")",
"if",
"node",
"node",
".",
"file",
"=",
"filename",
"node",
".",
"review",
"(",
"@checker",
")",
"end",
"end",
"def",
"review_file",
"(",
"filename",
")",
"review",
"(",
"filename",
",",
"read_file",
"(",
"filename",
")",
")",
"end",
"def",
"errors",
"(",
"@reviews",
"+",
"@lexicals",
")",
".",
"collect",
"{",
"|",
"check",
"|",
"check",
".",
"errors",
"}",
".",
"flatten",
"end",
"def",
"after_lexical",
";",
"end",
"def",
"after_prepare",
"filename",
"=",
"\"rails_best_practices.after_prepare\"",
"content",
"=",
"\"class RailsBestPractices::AfterPrepare; end\"",
"node",
"=",
"parse_ruby",
"(",
"filename",
",",
"content",
")",
"node",
".",
"file",
"=",
"filename",
"node",
".",
"prepare",
"(",
"@checker",
")",
"end",
"def",
"after_review",
"filename",
"=",
"\"rails_best_practices.after_review\"",
"content",
"=",
"\"class RailsBestPractices::AfterReview; end\"",
"node",
"=",
"parse_ruby",
"(",
"filename",
",",
"content",
")",
"node",
".",
"file",
"=",
"filename",
"node",
".",
"review",
"(",
"@checker",
")",
"end",
"private",
"def",
"parse_ruby",
"(",
"filename",
",",
"content",
")",
"begin",
"Sexp",
".",
"from_array",
"(",
"Ripper",
"::",
"SexpBuilder",
".",
"new",
"(",
"content",
")",
".",
"parse",
")",
"rescue",
"Exception",
"=>",
"e",
"if",
"@debug",
"warning",
"=",
"\"#{filename} looks like it's not a valid Ruby file. Skipping...\"",
"warning",
"=",
"warning",
".",
"red",
"if",
"self",
".",
"color",
"puts",
"warning",
"end",
"raise",
"e",
"if",
"@whiny",
"nil",
"end",
"end",
"def",
"parse_html_template",
"(",
"filename",
",",
"content",
")",
"if",
"filename",
"=~",
"/",
".*",
"\\.",
"erb$|.*",
"\\.",
"rhtml$",
"/",
"content",
"=",
"Erubis",
"::",
"OnlyRuby",
".",
"new",
"(",
"content",
")",
".",
"src",
"elsif",
"filename",
"=~",
"/",
".*",
"\\.",
"haml$",
"/",
"begin",
"require",
"'haml'",
"content",
"=",
"Haml",
"::",
"Engine",
".",
"new",
"(",
"content",
",",
"{",
":ugly",
"=>",
"true",
"}",
")",
".",
"precompiled",
"content",
".",
"gsub!",
"(",
"/",
"\\\\",
"\\d",
"{3}",
"/",
",",
"''",
")",
"rescue",
"LoadError",
"raise",
"\"In order to parse #{filename}, please install the haml gem\"",
"rescue",
"Haml",
"::",
"Error",
",",
"SyntaxError",
"end",
"elsif",
"filename",
"=~",
"/",
".*",
"\\.",
"slim$",
"/",
"begin",
"require",
"'slim'",
"content",
"=",
"Slim",
"::",
"Engine",
".",
"new",
".",
"call",
"(",
"content",
")",
"rescue",
"LoadError",
"raise",
"\"In order to parse #{filename}, please install the slim gem\"",
"rescue",
"SyntaxError",
"end",
"end",
"content",
"end",
"def",
"load_lexicals",
"checks_from_config",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"active_checks",
",",
"check",
"|",
"begin",
"check_name",
",",
"options",
"=",
"*",
"check",
"klass",
"=",
"RailsBestPractices",
"::",
"Lexicals",
".",
"const_get",
"(",
"check_name",
")",
"active_checks",
"<<",
"(",
"options",
".",
"empty?",
"?",
"klass",
".",
"new",
":",
"klass",
".",
"new",
"(",
"options",
")",
")",
"rescue",
"end",
"active_checks",
"}",
"end",
"def",
"load_prepares",
"Prepares",
".",
"constants",
".",
"map",
"{",
"|",
"prepare",
"|",
"Prepares",
".",
"const_get",
"(",
"prepare",
")",
".",
"new",
"}",
"end",
"def",
"load_reviews",
"checks_from_config",
".",
"inject",
"(",
"[",
"]",
")",
"{",
"|",
"active_checks",
",",
"check",
"|",
"begin",
"check_name",
",",
"options",
"=",
"*",
"check",
"klass",
"=",
"RailsBestPractices",
"::",
"Reviews",
".",
"const_get",
"(",
"check_name",
".",
"gsub",
"(",
"/",
"Check",
"/",
",",
"'Review'",
")",
")",
"active_checks",
"<<",
"(",
"options",
".",
"empty?",
"?",
"klass",
".",
"new",
":",
"klass",
".",
"new",
"(",
"options",
")",
")",
"rescue",
"end",
"active_checks",
"}",
"end",
"def",
"load_plugin_reviews",
"begin",
"plugins",
"=",
"File",
".",
"join",
"(",
"Runner",
".",
"base_path",
",",
"'lib'",
",",
"'rails_best_practices'",
",",
"'plugins'",
",",
"'reviews'",
")",
"if",
"File",
".",
"directory?",
"(",
"plugins",
")",
"Dir",
"[",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"plugins",
",",
"\"*.rb\"",
")",
")",
"]",
".",
"each",
"do",
"|",
"review",
"|",
"require",
"review",
"end",
"if",
"RailsBestPractices",
".",
"constants",
".",
"map",
"(",
"&",
":to_sym",
")",
".",
"include?",
":Plugins",
"RailsBestPractices",
"::",
"Plugins",
"::",
"Reviews",
".",
"constants",
".",
"each",
"do",
"|",
"review",
"|",
"@reviews",
"<<",
"RailsBestPractices",
"::",
"Plugins",
"::",
"Reviews",
".",
"const_get",
"(",
"review",
")",
".",
"new",
"end",
"end",
"end",
"end",
"end",
"def",
"checks_from_config",
"@checks",
"||=",
"YAML",
".",
"load_file",
"@config",
"end",
"def",
"read_file",
"(",
"filename",
")",
"File",
".",
"open",
"(",
"filename",
",",
"\"r:UTF-8\"",
")",
"{",
"|",
"f",
"|",
"f",
".",
"read",
"}",
"end",
"end"
] |
Runner is the main class, it can check source code of a filename with all checks (according to the configuration).
|
[
"Runner",
"is",
"the",
"main",
"class",
"it",
"can",
"check",
"source",
"code",
"of",
"a",
"filename",
"with",
"all",
"checks",
"(",
"according",
"to",
"the",
"configuration",
")",
"."
] |
[
"# set the base path.",
"#",
"# @param [String] path the base path",
"# get the base path, by default, the base path is current path.",
"#",
"# @return [String] the base path",
"# initialize the runner.",
"#",
"# @param [Hash] options pass the prepares and reviews.",
"# lexical analysis the file.",
"#",
"# @param [String] filename name of the file",
"# @param [String] content content of the file",
"# lexical analysis the file.",
"#",
"# @param [String] filename",
"# parepare a file's content with filename.",
"#",
"# @param [String] filename name of the file",
"# @param [String] content content of the file",
"# parapare the file.",
"#",
"# @param [String] filename",
"# review a file's content with filename.",
"#",
"# @param [String] filename name of the file",
"# @param [String] content content of the file",
"# review the file.",
"#",
"# @param [String] filename",
"# get all errors from lexicals and reviews.",
"#",
"# @return [Array] all errors from lexicals and reviews",
"# provide a handler after all files reviewed.",
"# provide a handler after all files reviewed.",
"# parse ruby code.",
"#",
"# @param [String] filename is the filename of ruby file.",
"# @param [String] content is the source code of ruby file.",
"# parse html tempalte code, erb, haml and slim.",
"#",
"# @param [String] filename is the filename of the erb, haml or slim code.",
"# @param [String] content is the source code of erb, haml or slim file.",
"# remove \\xxx characters",
"# do nothing, just ignore the wrong haml files.",
"# do nothing, just ignore the wrong slim files",
"# load all lexical checks.",
"# the check does not exist in the Lexicals namepace.",
"# load all prepares.",
"# load all reviews according to configuration.",
"# the check does not exist in the Reviews namepace.",
"# load all plugin reviews.",
"# read the checks from yaml config.",
"# read the file content.",
"#",
"# @param [String] filename",
"# @return [String] file conent"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 18
| 1,722
| 87
|
5d1ac1d2e08241c581fe9c1a70d2a2a9562de23b
|
takipsizad/pyjs
|
pyjs/lib_trans/pycompiler/pyassem.py
|
[
"ECL-2.0",
"Apache-2.0"
] |
Python
|
LineAddrTable
|
lnotab
This class builds the lnotab, which is documented in compile.c.
Here's a brief recap:
For each SET_LINENO instruction after the first one, two bytes are
added to lnotab. (In some cases, multiple two-byte entries are
added.) The first byte is the distance in bytes between the
instruction for the last SET_LINENO and the current SET_LINENO.
The second byte is offset in line numbers. If either offset is
greater than 255, multiple two-byte entries are added -- see
compile.c for the delicate details.
|
lnotab
This class builds the lnotab, which is documented in compile.c.
Here's a brief recap.
For each SET_LINENO instruction after the first one, two bytes are
added to lnotab. (In some cases, multiple two-byte entries are
added.) The first byte is the distance in bytes between the
instruction for the last SET_LINENO and the current SET_LINENO.
The second byte is offset in line numbers. If either offset is
greater than 255, multiple two-byte entries are added -- see
compile.c for the delicate details.
|
[
"lnotab",
"This",
"class",
"builds",
"the",
"lnotab",
"which",
"is",
"documented",
"in",
"compile",
".",
"c",
".",
"Here",
"'",
"s",
"a",
"brief",
"recap",
".",
"For",
"each",
"SET_LINENO",
"instruction",
"after",
"the",
"first",
"one",
"two",
"bytes",
"are",
"added",
"to",
"lnotab",
".",
"(",
"In",
"some",
"cases",
"multiple",
"two",
"-",
"byte",
"entries",
"are",
"added",
".",
")",
"The",
"first",
"byte",
"is",
"the",
"distance",
"in",
"bytes",
"between",
"the",
"instruction",
"for",
"the",
"last",
"SET_LINENO",
"and",
"the",
"current",
"SET_LINENO",
".",
"The",
"second",
"byte",
"is",
"offset",
"in",
"line",
"numbers",
".",
"If",
"either",
"offset",
"is",
"greater",
"than",
"255",
"multiple",
"two",
"-",
"byte",
"entries",
"are",
"added",
"--",
"see",
"compile",
".",
"c",
"for",
"the",
"delicate",
"details",
"."
] |
class LineAddrTable:
"""lnotab
This class builds the lnotab, which is documented in compile.c.
Here's a brief recap:
For each SET_LINENO instruction after the first one, two bytes are
added to lnotab. (In some cases, multiple two-byte entries are
added.) The first byte is the distance in bytes between the
instruction for the last SET_LINENO and the current SET_LINENO.
The second byte is offset in line numbers. If either offset is
greater than 255, multiple two-byte entries are added -- see
compile.c for the delicate details.
"""
def __init__(self):
self.code = []
self.codeOffset = 0
self.firstline = 0
self.lastline = 0
self.lastoff = 0
self.lnotab = []
def addCode(self, *args):
for arg in args:
self.code.append(chr(arg))
self.codeOffset = self.codeOffset + len(args)
def nextLine(self, lineno):
if self.firstline == 0:
self.firstline = lineno
self.lastline = lineno
else:
# compute deltas
addr = self.codeOffset - self.lastoff
line = lineno - self.lastline
# Python assumes that lineno always increases with
# increasing bytecode address (lnotab is unsigned char).
# Depending on when SET_LINENO instructions are emitted
# this is not always true. Consider the code:
# a = (1,
# b)
# In the bytecode stream, the assignment to "a" occurs
# after the loading of "b". This works with the C Python
# compiler because it only generates a SET_LINENO instruction
# for the assignment.
if line >= 0:
push = self.lnotab.append
while addr > 255:
push(255); push(0)
addr -= 255
while line > 255:
push(addr); push(255)
line -= 255
addr = 0
if addr > 0 or line > 0:
push(addr); push(line)
self.lastline = lineno
self.lastoff = self.codeOffset
def getCode(self):
return ''.join(self.code)
def getTable(self):
return ''.join(map(chr, self.lnotab))
|
[
"class",
"LineAddrTable",
":",
"def",
"__init__",
"(",
"self",
")",
":",
"self",
".",
"code",
"=",
"[",
"]",
"self",
".",
"codeOffset",
"=",
"0",
"self",
".",
"firstline",
"=",
"0",
"self",
".",
"lastline",
"=",
"0",
"self",
".",
"lastoff",
"=",
"0",
"self",
".",
"lnotab",
"=",
"[",
"]",
"def",
"addCode",
"(",
"self",
",",
"*",
"args",
")",
":",
"for",
"arg",
"in",
"args",
":",
"self",
".",
"code",
".",
"append",
"(",
"chr",
"(",
"arg",
")",
")",
"self",
".",
"codeOffset",
"=",
"self",
".",
"codeOffset",
"+",
"len",
"(",
"args",
")",
"def",
"nextLine",
"(",
"self",
",",
"lineno",
")",
":",
"if",
"self",
".",
"firstline",
"==",
"0",
":",
"self",
".",
"firstline",
"=",
"lineno",
"self",
".",
"lastline",
"=",
"lineno",
"else",
":",
"addr",
"=",
"self",
".",
"codeOffset",
"-",
"self",
".",
"lastoff",
"line",
"=",
"lineno",
"-",
"self",
".",
"lastline",
"if",
"line",
">=",
"0",
":",
"push",
"=",
"self",
".",
"lnotab",
".",
"append",
"while",
"addr",
">",
"255",
":",
"push",
"(",
"255",
")",
";",
"push",
"(",
"0",
")",
"addr",
"-=",
"255",
"while",
"line",
">",
"255",
":",
"push",
"(",
"addr",
")",
";",
"push",
"(",
"255",
")",
"line",
"-=",
"255",
"addr",
"=",
"0",
"if",
"addr",
">",
"0",
"or",
"line",
">",
"0",
":",
"push",
"(",
"addr",
")",
";",
"push",
"(",
"line",
")",
"self",
".",
"lastline",
"=",
"lineno",
"self",
".",
"lastoff",
"=",
"self",
".",
"codeOffset",
"def",
"getCode",
"(",
"self",
")",
":",
"return",
"''",
".",
"join",
"(",
"self",
".",
"code",
")",
"def",
"getTable",
"(",
"self",
")",
":",
"return",
"''",
".",
"join",
"(",
"map",
"(",
"chr",
",",
"self",
".",
"lnotab",
")",
")"
] |
lnotab
This class builds the lnotab, which is documented in compile.c.
|
[
"lnotab",
"This",
"class",
"builds",
"the",
"lnotab",
"which",
"is",
"documented",
"in",
"compile",
".",
"c",
"."
] |
[
"\"\"\"lnotab\n\n This class builds the lnotab, which is documented in compile.c.\n Here's a brief recap:\n\n For each SET_LINENO instruction after the first one, two bytes are\n added to lnotab. (In some cases, multiple two-byte entries are\n added.) The first byte is the distance in bytes between the\n instruction for the last SET_LINENO and the current SET_LINENO.\n The second byte is offset in line numbers. If either offset is\n greater than 255, multiple two-byte entries are added -- see\n compile.c for the delicate details.\n \"\"\"",
"# compute deltas",
"# Python assumes that lineno always increases with",
"# increasing bytecode address (lnotab is unsigned char).",
"# Depending on when SET_LINENO instructions are emitted",
"# this is not always true. Consider the code:",
"# a = (1,",
"# b)",
"# In the bytecode stream, the assignment to \"a\" occurs",
"# after the loading of \"b\". This works with the C Python",
"# compiler because it only generates a SET_LINENO instruction",
"# for the assignment."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 545
| 137
|
1dca5e2bf3446c8ce3b01951e76069f08b1cf849
|
jmsytow/taxonaut
|
src/main/java/org/nomencurator/gui/swing/table/NameTreeTableStringModel.java
|
[
"Apache-2.0"
] |
Java
|
NameTreeTableStringModel
|
/**
* {@code NameTreeTableStringModel} is a {@link TableModel}
* wrapping a {@link NameTreeTableModel} to provide
* a table of {@link NameUsage}s' name literals with rank.
*
* @version 26 Aug. 2016
* @author Nozomi `James' Ytow
*/
|
NameTreeTableStringModel is a TableModel
wrapping a NameTreeTableModel to provide
a table of NameUsages' name literals with rank.
@version 26 Aug. 2016
@author Nozomi `James' Ytow
|
[
"NameTreeTableStringModel",
"is",
"a",
"TableModel",
"wrapping",
"a",
"NameTreeTableModel",
"to",
"provide",
"a",
"table",
"of",
"NameUsages",
"'",
"name",
"literals",
"with",
"rank",
".",
"@version",
"26",
"Aug",
".",
"2016",
"@author",
"Nozomi",
"`",
"James",
"'",
"Ytow"
] |
public class NameTreeTableStringModel
extends NameTreeTableModel
{
private static final long serialVersionUID = 621936144735796994L;
@Getter @Setter protected NameTreeTableModel model;
/**
* Constructs an 'empty' {@link NameTreeTableModel}.
*/
public NameTreeTableStringModel()
{
this(null);
}
/**
* Constructs a NameTreeTableStringModel wrapping {@code model}.
*
* @paraman model {@link NameTreeTableModel} to be wrapped.
*/
public NameTreeTableStringModel(NameTreeTableModel model)
{
setModel(model);
}
@Override
public Class<?> getColumnClass(int columnIndex)
{
return model == null ?
super.getColumnClass(columnIndex) :
model.getColumnClass(columnIndex);
}
@Override
public int getColumnCount()
{
return model == null ?
super.getColumnCount() :
model.getColumnCount();
}
@Override
public String getColumnName(int columnIndex)
{
return model == null ?
super.getColumnName(columnIndex) :
model.getColumnName(columnIndex);
}
@Override
public int getRowCount()
{
return model == null ?
super.getRowCount() :
model.getRowCount();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex)
{
if (model == null)
return super.getValueAt(rowIndex, columnIndex);
Object value = model.getValueAt(rowIndex, columnIndex);
if (value instanceof NameUsage) {
value = ((NameUsage)value).getRankedName();
}
else if (value instanceof NameTreeNode) {
value = ((NameTreeNode)value).getRankedName();
}
return value;
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex)
{
return model == null ?
super.isCellEditable(rowIndex, columnIndex) :
model.isCellEditable(rowIndex, columnIndex);
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
if (model != null)
model.setValueAt(aValue, rowIndex, columnIndex);
else
super.setValueAt(aValue, rowIndex, columnIndex);
}
}
|
[
"public",
"class",
"NameTreeTableStringModel",
"extends",
"NameTreeTableModel",
"{",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"621936144735796994L",
";",
"@",
"Getter",
"@",
"Setter",
"protected",
"NameTreeTableModel",
"model",
";",
"/**\n * Constructs an 'empty' {@link NameTreeTableModel}.\n */",
"public",
"NameTreeTableStringModel",
"(",
")",
"{",
"this",
"(",
"null",
")",
";",
"}",
"/**\n * Constructs a NameTreeTableStringModel wrapping {@code model}.\n *\n * @paraman model {@link NameTreeTableModel} to be wrapped.\n */",
"public",
"NameTreeTableStringModel",
"(",
"NameTreeTableModel",
"model",
")",
"{",
"setModel",
"(",
"model",
")",
";",
"}",
"@",
"Override",
"public",
"Class",
"<",
"?",
">",
"getColumnClass",
"(",
"int",
"columnIndex",
")",
"{",
"return",
"model",
"==",
"null",
"?",
"super",
".",
"getColumnClass",
"(",
"columnIndex",
")",
":",
"model",
".",
"getColumnClass",
"(",
"columnIndex",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getColumnCount",
"(",
")",
"{",
"return",
"model",
"==",
"null",
"?",
"super",
".",
"getColumnCount",
"(",
")",
":",
"model",
".",
"getColumnCount",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"getColumnName",
"(",
"int",
"columnIndex",
")",
"{",
"return",
"model",
"==",
"null",
"?",
"super",
".",
"getColumnName",
"(",
"columnIndex",
")",
":",
"model",
".",
"getColumnName",
"(",
"columnIndex",
")",
";",
"}",
"@",
"Override",
"public",
"int",
"getRowCount",
"(",
")",
"{",
"return",
"model",
"==",
"null",
"?",
"super",
".",
"getRowCount",
"(",
")",
":",
"model",
".",
"getRowCount",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Object",
"getValueAt",
"(",
"int",
"rowIndex",
",",
"int",
"columnIndex",
")",
"{",
"if",
"(",
"model",
"==",
"null",
")",
"return",
"super",
".",
"getValueAt",
"(",
"rowIndex",
",",
"columnIndex",
")",
";",
"Object",
"value",
"=",
"model",
".",
"getValueAt",
"(",
"rowIndex",
",",
"columnIndex",
")",
";",
"if",
"(",
"value",
"instanceof",
"NameUsage",
")",
"{",
"value",
"=",
"(",
"(",
"NameUsage",
")",
"value",
")",
".",
"getRankedName",
"(",
")",
";",
"}",
"else",
"if",
"(",
"value",
"instanceof",
"NameTreeNode",
")",
"{",
"value",
"=",
"(",
"(",
"NameTreeNode",
")",
"value",
")",
".",
"getRankedName",
"(",
")",
";",
"}",
"return",
"value",
";",
"}",
"@",
"Override",
"public",
"boolean",
"isCellEditable",
"(",
"int",
"rowIndex",
",",
"int",
"columnIndex",
")",
"{",
"return",
"model",
"==",
"null",
"?",
"super",
".",
"isCellEditable",
"(",
"rowIndex",
",",
"columnIndex",
")",
":",
"model",
".",
"isCellEditable",
"(",
"rowIndex",
",",
"columnIndex",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"setValueAt",
"(",
"Object",
"aValue",
",",
"int",
"rowIndex",
",",
"int",
"columnIndex",
")",
"{",
"if",
"(",
"model",
"!=",
"null",
")",
"model",
".",
"setValueAt",
"(",
"aValue",
",",
"rowIndex",
",",
"columnIndex",
")",
";",
"else",
"super",
".",
"setValueAt",
"(",
"aValue",
",",
"rowIndex",
",",
"columnIndex",
")",
";",
"}",
"}"
] |
{@code NameTreeTableStringModel} is a {@link TableModel}
wrapping a {@link NameTreeTableModel} to provide
a table of {@link NameUsage}s' name literals with rank.
|
[
"{",
"@code",
"NameTreeTableStringModel",
"}",
"is",
"a",
"{",
"@link",
"TableModel",
"}",
"wrapping",
"a",
"{",
"@link",
"NameTreeTableModel",
"}",
"to",
"provide",
"a",
"table",
"of",
"{",
"@link",
"NameUsage",
"}",
"s",
"'",
"name",
"literals",
"with",
"rank",
"."
] |
[] |
[
{
"param": "NameTreeTableModel",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "NameTreeTableModel",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 465
| 78
|
0811daae5534371a161188a96a19da744c0f7584
|
tbpg/google-cloud-dotnet
|
tools/Google.Cloud.Tools.TagReleases/Program.cs
|
[
"Apache-2.0"
] |
C#
|
Program
|
/// <summary>
/// Tool to tag releases on GitHub for any projects where there's no existing tag
/// with the currently-specified version.
///
/// Steps taken:
///
/// - Fetch all tags from GitHub
/// - Fetch API catalog from specified commit on GitHub
/// - Work out which packages would need to be tagged
/// - Check that there are no project references outside that package set
/// - Request confirmation of tagging
/// - Perform tagging
/// </summary>
|
Tool to tag releases on GitHub for any projects where there's no existing tag
with the currently-specified version.
Steps taken.
Fetch all tags from GitHub
Fetch API catalog from specified commit on GitHub
Work out which packages would need to be tagged
Check that there are no project references outside that package set
Request confirmation of tagging
Perform tagging
|
[
"Tool",
"to",
"tag",
"releases",
"on",
"GitHub",
"for",
"any",
"projects",
"where",
"there",
"'",
"s",
"no",
"existing",
"tag",
"with",
"the",
"currently",
"-",
"specified",
"version",
".",
"Steps",
"taken",
".",
"Fetch",
"all",
"tags",
"from",
"GitHub",
"Fetch",
"API",
"catalog",
"from",
"specified",
"commit",
"on",
"GitHub",
"Work",
"out",
"which",
"packages",
"would",
"need",
"to",
"be",
"tagged",
"Check",
"that",
"there",
"are",
"no",
"project",
"references",
"outside",
"that",
"package",
"set",
"Request",
"confirmation",
"of",
"tagging",
"Perform",
"tagging"
] |
internal class Program
{
private const string RepositoryOwner = "googleapis";
private const string RepositoryName = "google-cloud-dotnet";
private const string ApplicationName = "google-cloud-dotnet-tagreleases";
private readonly Config _config;
private readonly GitHubClient _client;
private Program(Config config)
{
_config = config;
_client = new GitHubClient(new ProductHeaderValue(ApplicationName))
{
Credentials = new Credentials(config.GitHubToken)
};
}
private static async Task<int> Main(string[] args)
{
try
{
var config = Config.FromCommandLine(args);
if (!config.IsValid)
{
config.DisplayUsage();
return 1;
}
var program = new Program(config);
await program.RunAsync();
return 0;
}
catch (UserErrorException e)
{
Console.WriteLine($"Configuration error: {e.Message}");
return 1;
}
catch (Exception e)
{
Console.WriteLine($"Error: {e}");
return 1;
}
}
private async Task RunAsync()
{
var catalog = await LoadCatalog();
var tags = await FetchTags();
var newReleases = ComputeNewReleases(catalog, tags);
if (!newReleases.Any())
{
Console.WriteLine($"No releases need to be created for {_config.Committish}. Exiting.");
return;
}
var commit = await FetchAndDisplayCommit();
CheckProjectReferences(newReleases);
if (ConfirmReleases(newReleases))
{
await CreateReleasesAsync(newReleases, commit);
}
}
private async Task<ApiCatalog> LoadCatalog()
{
var allContents = await _client.Repository.Content.GetAllContentsByRef(RepositoryOwner, RepositoryName, ApiCatalog.RelativeCatalogPath, _config.Committish);
var json = allContents.Single().Content;
return ApiCatalog.FromJson(json);
}
private async Task<List<string>> FetchTags()
{
Console.WriteLine($"Fetching all tags from GitHub");
var tags = await _client.Repository.GetAllTags(RepositoryOwner, RepositoryName, new ApiOptions { PageSize = 2000 });
Console.WriteLine($"Fetched {tags.Count} tags");
return tags.Select(tag => tag.Name).ToList();
}
private async Task<GitHubCommit> FetchAndDisplayCommit()
{
var commit = await _client.Repository.Commit.Get(RepositoryOwner, RepositoryName, _config.Committish);
Console.WriteLine($"Commit to tag: {commit.Sha}");
Console.WriteLine("---------");
Console.WriteLine(commit.Commit.Message);
Console.WriteLine("---------");
return commit;
}
private List<ApiMetadata> ComputeNewReleases(ApiCatalog catalog, List<string> tags)
{
var noChange = catalog.Apis.Where(api => tags.Contains($"{api.Id}-{api.Version}") || api.Version.EndsWith("00")).ToList();
return catalog.Apis.Except(noChange).ToList();
}
private void CheckProjectReferences(List<ApiMetadata> newReleases)
{
if (_config.SkipProjectReferenceCheck)
{
return;
}
var newReleaseNames = newReleases.Select(api => api.Id).ToList();
foreach (var api in newReleases)
{
var projectReferences = api.Dependencies.Where(p => p.Value == "project").Select(p => p.Key);
var badReferences = projectReferences.Except(newReleaseNames).ToList();
if (badReferences.Any())
{
throw new UserErrorException(
$"Project {api.Id} contains project references to projects outside the release set: {string.Join(", ", badReferences)}");
}
}
}
private bool ConfirmReleases(List<ApiMetadata> newReleases)
{
Console.WriteLine("APIs requiring a new release:");
newReleases.ForEach(api => Console.WriteLine($"{api.Id,-50} v{api.Version}"));
Console.Write("Go ahead and create releases? (y/n) ");
string response = Console.ReadLine();
return response == "y";
}
private async Task CreateReleasesAsync(List<ApiMetadata> newReleases, GitHubCommit commit)
{
var originalMessage = commit.Commit.Message;
var unwrappedMessage = string.Join("\n", UnwrapLines(originalMessage.Split('\n')));
Console.WriteLine("Creating releases with tags:");
foreach (var api in newReleases)
{
var tag = $"{api.Id}-{api.Version}";
var gitRelease = new NewRelease(tag)
{
Prerelease = !api.IsReleaseVersion,
Name = $"{api.Id} version {api.Version}",
TargetCommitish = commit.Sha,
Body = unwrappedMessage
};
await _client.Repository.Release.Create(RepositoryOwner, RepositoryName, gitRelease);
Console.WriteLine(tag);
}
}
private static IEnumerable<string> UnwrapLines(IEnumerable<string> lines)
{
var builder = new StringBuilder();
foreach (var line in lines)
{
bool emptyLine = string.IsNullOrWhiteSpace(line);
if (line.StartsWith("- ") || line.StartsWith("* ") || line.StartsWith(" ") || emptyLine)
{
if (builder.Length > 0)
{
yield return builder.ToString();
builder.Clear();
}
}
if (builder.Length > 0)
{
builder.Append(" ");
}
builder.Append(line);
if (line.EndsWith(" ") || emptyLine)
{
yield return builder.ToString();
builder.Clear();
}
}
if (builder.Length > 0)
{
yield return builder.ToString();
}
}
}
|
[
"internal",
"class",
"Program",
"{",
"private",
"const",
"string",
"RepositoryOwner",
"=",
"\"",
"googleapis",
"\"",
";",
"private",
"const",
"string",
"RepositoryName",
"=",
"\"",
"google-cloud-dotnet",
"\"",
";",
"private",
"const",
"string",
"ApplicationName",
"=",
"\"",
"google-cloud-dotnet-tagreleases",
"\"",
";",
"private",
"readonly",
"Config",
"_config",
";",
"private",
"readonly",
"GitHubClient",
"_client",
";",
"private",
"Program",
"(",
"Config",
"config",
")",
"{",
"_config",
"=",
"config",
";",
"_client",
"=",
"new",
"GitHubClient",
"(",
"new",
"ProductHeaderValue",
"(",
"ApplicationName",
")",
")",
"{",
"Credentials",
"=",
"new",
"Credentials",
"(",
"config",
".",
"GitHubToken",
")",
"}",
";",
"}",
"private",
"static",
"async",
"Task",
"<",
"int",
">",
"Main",
"(",
"string",
"[",
"]",
"args",
")",
"{",
"try",
"{",
"var",
"config",
"=",
"Config",
".",
"FromCommandLine",
"(",
"args",
")",
";",
"if",
"(",
"!",
"config",
".",
"IsValid",
")",
"{",
"config",
".",
"DisplayUsage",
"(",
")",
";",
"return",
"1",
";",
"}",
"var",
"program",
"=",
"new",
"Program",
"(",
"config",
")",
";",
"await",
"program",
".",
"RunAsync",
"(",
")",
";",
"return",
"0",
";",
"}",
"catch",
"(",
"UserErrorException",
"e",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"$\"",
"Configuration error: ",
"{",
"e",
".",
"Message",
"}",
"\"",
")",
";",
"return",
"1",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"$\"",
"Error: ",
"{",
"e",
"}",
"\"",
")",
";",
"return",
"1",
";",
"}",
"}",
"private",
"async",
"Task",
"RunAsync",
"(",
")",
"{",
"var",
"catalog",
"=",
"await",
"LoadCatalog",
"(",
")",
";",
"var",
"tags",
"=",
"await",
"FetchTags",
"(",
")",
";",
"var",
"newReleases",
"=",
"ComputeNewReleases",
"(",
"catalog",
",",
"tags",
")",
";",
"if",
"(",
"!",
"newReleases",
".",
"Any",
"(",
")",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"$\"",
"No releases need to be created for ",
"{",
"_config",
".",
"Committish",
"}",
". Exiting.",
"\"",
")",
";",
"return",
";",
"}",
"var",
"commit",
"=",
"await",
"FetchAndDisplayCommit",
"(",
")",
";",
"CheckProjectReferences",
"(",
"newReleases",
")",
";",
"if",
"(",
"ConfirmReleases",
"(",
"newReleases",
")",
")",
"{",
"await",
"CreateReleasesAsync",
"(",
"newReleases",
",",
"commit",
")",
";",
"}",
"}",
"private",
"async",
"Task",
"<",
"ApiCatalog",
">",
"LoadCatalog",
"(",
")",
"{",
"var",
"allContents",
"=",
"await",
"_client",
".",
"Repository",
".",
"Content",
".",
"GetAllContentsByRef",
"(",
"RepositoryOwner",
",",
"RepositoryName",
",",
"ApiCatalog",
".",
"RelativeCatalogPath",
",",
"_config",
".",
"Committish",
")",
";",
"var",
"json",
"=",
"allContents",
".",
"Single",
"(",
")",
".",
"Content",
";",
"return",
"ApiCatalog",
".",
"FromJson",
"(",
"json",
")",
";",
"}",
"private",
"async",
"Task",
"<",
"List",
"<",
"string",
">",
">",
"FetchTags",
"(",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"$\"",
"Fetching all tags from GitHub",
"\"",
")",
";",
"var",
"tags",
"=",
"await",
"_client",
".",
"Repository",
".",
"GetAllTags",
"(",
"RepositoryOwner",
",",
"RepositoryName",
",",
"new",
"ApiOptions",
"{",
"PageSize",
"=",
"2000",
"}",
")",
";",
"Console",
".",
"WriteLine",
"(",
"$\"",
"Fetched ",
"{",
"tags",
".",
"Count",
"}",
" tags",
"\"",
")",
";",
"return",
"tags",
".",
"Select",
"(",
"tag",
"=>",
"tag",
".",
"Name",
")",
".",
"ToList",
"(",
")",
";",
"}",
"private",
"async",
"Task",
"<",
"GitHubCommit",
">",
"FetchAndDisplayCommit",
"(",
")",
"{",
"var",
"commit",
"=",
"await",
"_client",
".",
"Repository",
".",
"Commit",
".",
"Get",
"(",
"RepositoryOwner",
",",
"RepositoryName",
",",
"_config",
".",
"Committish",
")",
";",
"Console",
".",
"WriteLine",
"(",
"$\"",
"Commit to tag: ",
"{",
"commit",
".",
"Sha",
"}",
"\"",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
"---------",
"\"",
")",
";",
"Console",
".",
"WriteLine",
"(",
"commit",
".",
"Commit",
".",
"Message",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
"---------",
"\"",
")",
";",
"return",
"commit",
";",
"}",
"private",
"List",
"<",
"ApiMetadata",
">",
"ComputeNewReleases",
"(",
"ApiCatalog",
"catalog",
",",
"List",
"<",
"string",
">",
"tags",
")",
"{",
"var",
"noChange",
"=",
"catalog",
".",
"Apis",
".",
"Where",
"(",
"api",
"=>",
"tags",
".",
"Contains",
"(",
"$\"",
"{",
"api",
".",
"Id",
"}",
"-",
"{",
"api",
".",
"Version",
"}",
"\"",
")",
"||",
"api",
".",
"Version",
".",
"EndsWith",
"(",
"\"",
"00",
"\"",
")",
")",
".",
"ToList",
"(",
")",
";",
"return",
"catalog",
".",
"Apis",
".",
"Except",
"(",
"noChange",
")",
".",
"ToList",
"(",
")",
";",
"}",
"private",
"void",
"CheckProjectReferences",
"(",
"List",
"<",
"ApiMetadata",
">",
"newReleases",
")",
"{",
"if",
"(",
"_config",
".",
"SkipProjectReferenceCheck",
")",
"{",
"return",
";",
"}",
"var",
"newReleaseNames",
"=",
"newReleases",
".",
"Select",
"(",
"api",
"=>",
"api",
".",
"Id",
")",
".",
"ToList",
"(",
")",
";",
"foreach",
"(",
"var",
"api",
"in",
"newReleases",
")",
"{",
"var",
"projectReferences",
"=",
"api",
".",
"Dependencies",
".",
"Where",
"(",
"p",
"=>",
"p",
".",
"Value",
"==",
"\"",
"project",
"\"",
")",
".",
"Select",
"(",
"p",
"=>",
"p",
".",
"Key",
")",
";",
"var",
"badReferences",
"=",
"projectReferences",
".",
"Except",
"(",
"newReleaseNames",
")",
".",
"ToList",
"(",
")",
";",
"if",
"(",
"badReferences",
".",
"Any",
"(",
")",
")",
"{",
"throw",
"new",
"UserErrorException",
"(",
"$\"",
"Project ",
"{",
"api",
".",
"Id",
"}",
" contains project references to projects outside the release set: ",
"{",
"string",
".",
"Join",
"(",
"\"",
", ",
"\"",
",",
"badReferences",
")",
"}",
"\"",
")",
";",
"}",
"}",
"}",
"private",
"bool",
"ConfirmReleases",
"(",
"List",
"<",
"ApiMetadata",
">",
"newReleases",
")",
"{",
"Console",
".",
"WriteLine",
"(",
"\"",
"APIs requiring a new release:",
"\"",
")",
";",
"newReleases",
".",
"ForEach",
"(",
"api",
"=>",
"Console",
".",
"WriteLine",
"(",
"$\"",
"{",
"api",
".",
"Id",
",",
"-",
"50",
"}",
" v",
"{",
"api",
".",
"Version",
"}",
"\"",
")",
")",
";",
"Console",
".",
"Write",
"(",
"\"",
"Go ahead and create releases? (y/n) ",
"\"",
")",
";",
"string",
"response",
"=",
"Console",
".",
"ReadLine",
"(",
")",
";",
"return",
"response",
"==",
"\"",
"y",
"\"",
";",
"}",
"private",
"async",
"Task",
"CreateReleasesAsync",
"(",
"List",
"<",
"ApiMetadata",
">",
"newReleases",
",",
"GitHubCommit",
"commit",
")",
"{",
"var",
"originalMessage",
"=",
"commit",
".",
"Commit",
".",
"Message",
";",
"var",
"unwrappedMessage",
"=",
"string",
".",
"Join",
"(",
"\"",
"\\n",
"\"",
",",
"UnwrapLines",
"(",
"originalMessage",
".",
"Split",
"(",
"'",
"\\n",
"'",
")",
")",
")",
";",
"Console",
".",
"WriteLine",
"(",
"\"",
"Creating releases with tags:",
"\"",
")",
";",
"foreach",
"(",
"var",
"api",
"in",
"newReleases",
")",
"{",
"var",
"tag",
"=",
"$\"",
"{",
"api",
".",
"Id",
"}",
"-",
"{",
"api",
".",
"Version",
"}",
"\"",
";",
"var",
"gitRelease",
"=",
"new",
"NewRelease",
"(",
"tag",
")",
"{",
"Prerelease",
"=",
"!",
"api",
".",
"IsReleaseVersion",
",",
"Name",
"=",
"$\"",
"{",
"api",
".",
"Id",
"}",
" version ",
"{",
"api",
".",
"Version",
"}",
"\"",
",",
"TargetCommitish",
"=",
"commit",
".",
"Sha",
",",
"Body",
"=",
"unwrappedMessage",
"}",
";",
"await",
"_client",
".",
"Repository",
".",
"Release",
".",
"Create",
"(",
"RepositoryOwner",
",",
"RepositoryName",
",",
"gitRelease",
")",
";",
"Console",
".",
"WriteLine",
"(",
"tag",
")",
";",
"}",
"}",
"private",
"static",
"IEnumerable",
"<",
"string",
">",
"UnwrapLines",
"(",
"IEnumerable",
"<",
"string",
">",
"lines",
")",
"{",
"var",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"foreach",
"(",
"var",
"line",
"in",
"lines",
")",
"{",
"bool",
"emptyLine",
"=",
"string",
".",
"IsNullOrWhiteSpace",
"(",
"line",
")",
";",
"if",
"(",
"line",
".",
"StartsWith",
"(",
"\"",
"- ",
"\"",
")",
"||",
"line",
".",
"StartsWith",
"(",
"\"",
"* ",
"\"",
")",
"||",
"line",
".",
"StartsWith",
"(",
"\"",
" ",
"\"",
")",
"||",
"emptyLine",
")",
"{",
"if",
"(",
"builder",
".",
"Length",
">",
"0",
")",
"{",
"yield",
"return",
"builder",
".",
"ToString",
"(",
")",
";",
"builder",
".",
"Clear",
"(",
")",
";",
"}",
"}",
"if",
"(",
"builder",
".",
"Length",
">",
"0",
")",
"{",
"builder",
".",
"Append",
"(",
"\"",
" ",
"\"",
")",
";",
"}",
"builder",
".",
"Append",
"(",
"line",
")",
";",
"if",
"(",
"line",
".",
"EndsWith",
"(",
"\"",
" ",
"\"",
")",
"||",
"emptyLine",
")",
"{",
"yield",
"return",
"builder",
".",
"ToString",
"(",
")",
";",
"builder",
".",
"Clear",
"(",
")",
";",
"}",
"}",
"if",
"(",
"builder",
".",
"Length",
">",
"0",
")",
"{",
"yield",
"return",
"builder",
".",
"ToString",
"(",
")",
";",
"}",
"}",
"}"
] |
Tool to tag releases on GitHub for any projects where there's no existing tag
with the currently-specified version.
|
[
"Tool",
"to",
"tag",
"releases",
"on",
"GitHub",
"for",
"any",
"projects",
"where",
"there",
"'",
"s",
"no",
"existing",
"tag",
"with",
"the",
"currently",
"-",
"specified",
"version",
"."
] |
[
"/// <summary>",
"/// Skeleton of execution, with no real business logic. This method has been",
"/// separated from <see cref=\"RunAsync\"/> for clarity.",
"/// </summary>",
"// We have a lot of tags - fetch a large number at a time to make this a lot quicker.",
"// Make sure it's clear which part of the output is the commit message.",
"/// <summary>",
"/// Check for invalid project references.",
"/// Project references (in production code) are okay so long as all the targets of the references",
"/// are also going to be released. If this is not the case, the dependencies within the target could be different",
"/// to the ones in the public package version, causing a dependency issue in the package we're about to publish.",
"/// (This caused issue #1280 for example.)",
"/// </remarks>",
"// We could parallelize, but there's very little point.",
"/// <summary>",
"/// Unwraps the given sequence of lines to be more suitable for a GitHub commit/release message.",
"/// (GitHub Markdown formatting breaks on newlines, which can be annoying.)",
"/// </summary>",
"// Don't unwrap lists or empty lines.",
"// Yield immediately for Markdown line breaks or empty lines",
"// Yield anything we still have"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,186
| 98
|
177e9632ddc61fed94e63cd4387bf15d0876b68c
|
mkallmayer/psychojs
|
js/core/Keyboard.js
|
[
"MIT"
] |
JavaScript
|
Keyboard
|
/**
* <p>This manager handles all keyboard events. It is a substitute for the keyboard component of EventManager. </p>
*
* @name module:core.Keyboard
* @class
* @param {Object} options
* @param {PsychoJS} options.psychoJS - the PsychoJS instance
* @param {number} [options.bufferSize= 10000] - the maximum size of the circular keyboard event buffer
* @param {boolean} [options.waitForStart= false] - whether or not to wait for a call to module:core.Keyboard#start
* before recording keyboard events
* @param {Clock} [options.clock= undefined] - an optional clock
* @param {boolean} options.autoLog - whether or not to log
*/
|
This manager handles all keyboard events. It is a substitute for the keyboard component of EventManager.
|
[
"This",
"manager",
"handles",
"all",
"keyboard",
"events",
".",
"It",
"is",
"a",
"substitute",
"for",
"the",
"keyboard",
"component",
"of",
"EventManager",
"."
] |
class Keyboard extends PsychObject {
constructor({
psychoJS,
bufferSize = 10000,
waitForStart = false,
clock,
autoLog = false,
} = {}) {
super(psychoJS);
if (typeof clock === 'undefined')
clock = new Clock(); //this._psychoJS.monotonicClock;
this._addAttributes(Keyboard, bufferSize, waitForStart, clock, autoLog);
// start recording key events if need be:
this._addAttribute('status', (waitForStart)?PsychoJS.Status.NOT_STARTED:PsychoJS.Status.STARTED);
// setup circular buffer:
this.clearEvents();
// add key listeners:
this._addKeyListeners();
}
/**
* Start recording keyboard events.
*
* @name module:core.Keyboard#start
* @function
* @public
*
*/
start() {
this._status = PsychoJS.Status.STARTED;
}
/**
* Stop recording keyboard events.
*
* @name module:core.Keyboard#stop
* @function
* @public
*
*/
stop() {
this._status = PsychoJS.Status.STOPPED;
}
/**
* @typedef Keyboard.KeyEvent
*
* @property {string} W3C key code
* @property {string} W3C key
* @property {string} pyglet key
* @property {module:core.Keyboard#KeyStatus} key status
* @property {number} timestamp (in seconds)
*/
/**
* Get the list of those keyboard events still in the buffer, i.e. those that have not been
* previously cleared by calls to getKeys with clear = true.
*
* @name module:core.Keyboard#getEvents
* @function
* @public
* @return {Keyboard.KeyEvent[]} the list of events still in the buffer
*/
getEvents() {
if (this._bufferLength === 0)
return [];
// iterate over the buffer, from start to end, and discard the null event:
let filteredEvents = [];
const bufferWrap = (this._bufferLength === this._bufferSize);
let i = bufferWrap ? this._bufferIndex : -1;
do {
i = (i + 1) % this._bufferSize;
const keyEvent = this._circularBuffer[i];
if (keyEvent)
filteredEvents.push(keyEvent);
} while (i !== this._bufferIndex);
return filteredEvents;
}
/**
* Get the list of keys pressed or pushed by the participant.
*
* @name module:core.Keyboard#getKeys
* @function
* @public
* @param {Object} options
* @param {string[]} [options.keyList= []]] - the list of keys to consider. If keyList is empty, we consider all keys.
* Note that we use pyglet keys here, to make the PsychoJs code more homogeneous with PsychoPy.
* @param {boolean} [options.waitRelease= true] - whether or not to include those keys pressed but not released. If
* waitRelease = false, key presses without a corresponding key release will have an undefined duration.
* @param {boolean} [options.clear= false] - whether or not to keep in the buffer the key presses or pushes for a subsequent call to getKeys. If a keyList has been given and clear = true, we only remove from the buffer those keys in keyList
* @return {KeyPress[]} the list of keys that were pressed (keydown followed by keyup) or pushed
* (keydown with no subsequent keyup at the time getKeys is called).
*/
getKeys({
keyList = [],
waitRelease = true,
clear = true
} = {}) {
// if nothing in the buffer, return immediately:
if (this._bufferLength === 0)
return [];
let keyPresses = [];
// iterate over the circular buffer, looking for keyup events:
const bufferWrap = (this._bufferLength === this._bufferSize);
let i = bufferWrap ? this._bufferIndex : -1;
do {
i = (i + 1) % this._bufferSize;
const keyEvent = this._circularBuffer[i];
if (keyEvent && keyEvent.status === Keyboard.KeyStatus.KEY_UP) {
// check that the key is in the keyList:
if (keyList.length === 0 || keyList.includes(keyEvent.pigletKey)) {
// look for a corresponding, preceding keydown event:
const precedingKeydownIndex = keyEvent.keydownIndex;
if (typeof precedingKeydownIndex !== 'undefined') {
const precedingKeydownEvent = this._circularBuffer[precedingKeydownIndex];
if (precedingKeydownEvent) {
// prepare KeyPress and add it to the array:
const tDown = precedingKeydownEvent.timestamp;
const keyPress = new KeyPress(keyEvent.code, tDown, keyEvent.pigletKey);
keyPress.rt = tDown - this._clock.getLastResetTime();
keyPress.duration = keyEvent.timestamp - precedingKeydownEvent.timestamp;
keyPresses.push(keyPress);
if (clear)
this._circularBuffer[precedingKeydownIndex] = null;
}
}
/* old approach: the circular buffer contains independent keydown and keyup events:
let j = i - 1;
do {
if (j === -1 && bufferWrap)
j = this._bufferSize - 1;
const precedingKeyEvent = this._circularBuffer[j];
if (precedingKeyEvent &&
(precedingKeyEvent.key === keyEvent.key) &&
(precedingKeyEvent.status === Keyboard.KeyStatus.KEY_DOWN)) {
duration = keyEvent.timestamp - precedingKeyEvent.timestamp;
if (clear)
// rather than modify the circular buffer, which is computationally expensive,
// we simply nullify the keyEvent:
this._circularBuffer[j] = null;
break;
}
j = j - 1;
} while ((bufferWrap && j !== i) || (j > -1));*/
if (clear)
this._circularBuffer[i] = null;
}
}
} while (i !== this._bufferIndex);
// if waitRelease = false, we iterate again over the map of unmatched keydown events:
if (!waitRelease) {
for (const unmatchedKeyDownIndex of this._unmatchedKeydownMap.values()) {
const keyEvent = this._circularBuffer[unmatchedKeyDownIndex];
if (keyEvent) {
// check that the key is in the keyList:
if (keyList.length === 0 || keyList.includes(keyEvent.pigletKey)) {
const tDown = keyEvent.timestamp;
const keyPress = new KeyPress(keyEvent.code, tDown, keyEvent.pigletKey);
keyPress.rt = tDown - this._clock.getLastResetTime();
keyPresses.push(keyPress);
if (clear) {
this._unmatchedKeydownMap.delete(keyEvent.code);
this._circularBuffer[unmatchedKeyDownIndex] = null;
}
}
}
}
/* old approach: the circular buffer contains independent keydown and keyup events:
let i = bufferWrap ? this._bufferIndex : -1;
do {
i = (i + 1) % this._bufferSize;
const keyEvent = this._circularBuffer[i];
if (keyEvent && keyEvent.status === Keyboard.KeyStatus.KEY_DOWN) {
// check that the key is in the keyList:
const pigletKey = EventManager.w3c2pyglet(keyEvent.code);
if (keyList.length === 0 || keyList.includes(pigletKey)) {
keyPresses.push(new KeyPress(keyEvent.code, keyEvent.timestamp, pigletKey));
if (clear)
// rather than modify the circular buffer, which is computationally expensive, we simply nullify
// the keyEvent:
this._circularBuffer[i] = null;
}
}
} while (i !== this._bufferIndex);*/
}
// if clear = true and the keyList is empty, we clear all the events:
if (clear && keyList.length === 0)
this.clearEvents();
return keyPresses;
}
clearEvents() {
// circular buffer of key events (keydown and keyup):
this._circularBuffer = new Array(this._bufferSize);
this._bufferLength = 0;
this._bufferIndex = -1;
this._previousKeydownKey = undefined;
// (code => circular buffer index) map of keydown events not yet matched to keyup events:
this._unmatchedKeydownMap = new Map();
}
/**
* Add key listeners to the document.
*
* @name module:core.Keyboard#_addKeyListeners
* @function
* @private
*/
_addKeyListeners() {
this._previousKeydownKey = undefined;
const self = this;
// add a keydown listener:
document.addEventListener("keydown", (event) => {
const timestamp = MonotonicClock.getReferenceTime(); // timestamp in seconds
if (this._status !== PsychoJS.Status.STARTED)
return;
// since keydown events will repeat as long as the key is pressed, we need to track the last pressed key:
if (event.key === self._previousKeydownKey)
return;
self._previousKeydownKey = event.key;
let code = event.code;
// take care of legacy Microsoft Edge:
if (typeof code === 'undefined')
code = EventManager.keycode2w3c(event.keyCode);
let pigletKey = EventManager.w3c2pyglet(code);
self._bufferIndex = (self._bufferIndex + 1) % self._bufferSize;
self._bufferLength = Math.min(self._bufferLength + 1, self._bufferSize);
self._circularBuffer[self._bufferIndex] = {
code,
key: event.key,
pigletKey,
status: Keyboard.KeyStatus.KEY_DOWN,
timestamp
};
self._unmatchedKeydownMap.set(event.code, self._bufferIndex);
self._psychoJS.logger.trace('keydown: ', event.key);
console.log(self._circularBuffer[self._bufferIndex]);
});
// add a keyup listener:
document.addEventListener("keyup", (event) => {
const timestamp = MonotonicClock.getReferenceTime(); // timestamp in seconds
if (this._status !== PsychoJS.Status.STARTED)
return;
self._previousKeydownKey = undefined;
let code = event.code;
// take care of legacy Microsoft Edge:
if (typeof code === 'undefined')
code = EventManager.keycode2w3c(event.keyCode);
let pigletKey = EventManager.w3c2pyglet(code);
self._bufferIndex = (self._bufferIndex + 1) % self._bufferSize;
self._bufferLength = Math.min(self._bufferLength + 1, self._bufferSize);
self._circularBuffer[self._bufferIndex] = {
code,
key: event.key,
pigletKey,
status: Keyboard.KeyStatus.KEY_UP,
timestamp
};
// get the corresponding keydown event
// note: if more keys are down than there are slots in the circular buffer, there might
// not be a corresponding keydown event
const correspondingKeydownIndex = self._unmatchedKeydownMap.get(event.code);
if (typeof correspondingKeydownIndex !== 'undefined') {
self._circularBuffer[self._bufferIndex].keydownIndex = correspondingKeydownIndex;
self._unmatchedKeydownMap.delete(event.code);
}
self._psychoJS.logger.trace('keyup: ', event.key);
console.log(self._circularBuffer[self._bufferIndex]);
});
}
}
|
[
"class",
"Keyboard",
"extends",
"PsychObject",
"{",
"constructor",
"(",
"{",
"psychoJS",
",",
"bufferSize",
"=",
"10000",
",",
"waitForStart",
"=",
"false",
",",
"clock",
",",
"autoLog",
"=",
"false",
",",
"}",
"=",
"{",
"}",
")",
"{",
"super",
"(",
"psychoJS",
")",
";",
"if",
"(",
"typeof",
"clock",
"===",
"'undefined'",
")",
"clock",
"=",
"new",
"Clock",
"(",
")",
";",
"this",
".",
"_addAttributes",
"(",
"Keyboard",
",",
"bufferSize",
",",
"waitForStart",
",",
"clock",
",",
"autoLog",
")",
";",
"this",
".",
"_addAttribute",
"(",
"'status'",
",",
"(",
"waitForStart",
")",
"?",
"PsychoJS",
".",
"Status",
".",
"NOT_STARTED",
":",
"PsychoJS",
".",
"Status",
".",
"STARTED",
")",
";",
"this",
".",
"clearEvents",
"(",
")",
";",
"this",
".",
"_addKeyListeners",
"(",
")",
";",
"}",
"start",
"(",
")",
"{",
"this",
".",
"_status",
"=",
"PsychoJS",
".",
"Status",
".",
"STARTED",
";",
"}",
"stop",
"(",
")",
"{",
"this",
".",
"_status",
"=",
"PsychoJS",
".",
"Status",
".",
"STOPPED",
";",
"}",
"getEvents",
"(",
")",
"{",
"if",
"(",
"this",
".",
"_bufferLength",
"===",
"0",
")",
"return",
"[",
"]",
";",
"let",
"filteredEvents",
"=",
"[",
"]",
";",
"const",
"bufferWrap",
"=",
"(",
"this",
".",
"_bufferLength",
"===",
"this",
".",
"_bufferSize",
")",
";",
"let",
"i",
"=",
"bufferWrap",
"?",
"this",
".",
"_bufferIndex",
":",
"-",
"1",
";",
"do",
"{",
"i",
"=",
"(",
"i",
"+",
"1",
")",
"%",
"this",
".",
"_bufferSize",
";",
"const",
"keyEvent",
"=",
"this",
".",
"_circularBuffer",
"[",
"i",
"]",
";",
"if",
"(",
"keyEvent",
")",
"filteredEvents",
".",
"push",
"(",
"keyEvent",
")",
";",
"}",
"while",
"(",
"i",
"!==",
"this",
".",
"_bufferIndex",
")",
";",
"return",
"filteredEvents",
";",
"}",
"getKeys",
"(",
"{",
"keyList",
"=",
"[",
"]",
",",
"waitRelease",
"=",
"true",
",",
"clear",
"=",
"true",
"}",
"=",
"{",
"}",
")",
"{",
"if",
"(",
"this",
".",
"_bufferLength",
"===",
"0",
")",
"return",
"[",
"]",
";",
"let",
"keyPresses",
"=",
"[",
"]",
";",
"const",
"bufferWrap",
"=",
"(",
"this",
".",
"_bufferLength",
"===",
"this",
".",
"_bufferSize",
")",
";",
"let",
"i",
"=",
"bufferWrap",
"?",
"this",
".",
"_bufferIndex",
":",
"-",
"1",
";",
"do",
"{",
"i",
"=",
"(",
"i",
"+",
"1",
")",
"%",
"this",
".",
"_bufferSize",
";",
"const",
"keyEvent",
"=",
"this",
".",
"_circularBuffer",
"[",
"i",
"]",
";",
"if",
"(",
"keyEvent",
"&&",
"keyEvent",
".",
"status",
"===",
"Keyboard",
".",
"KeyStatus",
".",
"KEY_UP",
")",
"{",
"if",
"(",
"keyList",
".",
"length",
"===",
"0",
"||",
"keyList",
".",
"includes",
"(",
"keyEvent",
".",
"pigletKey",
")",
")",
"{",
"const",
"precedingKeydownIndex",
"=",
"keyEvent",
".",
"keydownIndex",
";",
"if",
"(",
"typeof",
"precedingKeydownIndex",
"!==",
"'undefined'",
")",
"{",
"const",
"precedingKeydownEvent",
"=",
"this",
".",
"_circularBuffer",
"[",
"precedingKeydownIndex",
"]",
";",
"if",
"(",
"precedingKeydownEvent",
")",
"{",
"const",
"tDown",
"=",
"precedingKeydownEvent",
".",
"timestamp",
";",
"const",
"keyPress",
"=",
"new",
"KeyPress",
"(",
"keyEvent",
".",
"code",
",",
"tDown",
",",
"keyEvent",
".",
"pigletKey",
")",
";",
"keyPress",
".",
"rt",
"=",
"tDown",
"-",
"this",
".",
"_clock",
".",
"getLastResetTime",
"(",
")",
";",
"keyPress",
".",
"duration",
"=",
"keyEvent",
".",
"timestamp",
"-",
"precedingKeydownEvent",
".",
"timestamp",
";",
"keyPresses",
".",
"push",
"(",
"keyPress",
")",
";",
"if",
"(",
"clear",
")",
"this",
".",
"_circularBuffer",
"[",
"precedingKeydownIndex",
"]",
"=",
"null",
";",
"}",
"}",
"if",
"(",
"clear",
")",
"this",
".",
"_circularBuffer",
"[",
"i",
"]",
"=",
"null",
";",
"}",
"}",
"}",
"while",
"(",
"i",
"!==",
"this",
".",
"_bufferIndex",
")",
";",
"if",
"(",
"!",
"waitRelease",
")",
"{",
"for",
"(",
"const",
"unmatchedKeyDownIndex",
"of",
"this",
".",
"_unmatchedKeydownMap",
".",
"values",
"(",
")",
")",
"{",
"const",
"keyEvent",
"=",
"this",
".",
"_circularBuffer",
"[",
"unmatchedKeyDownIndex",
"]",
";",
"if",
"(",
"keyEvent",
")",
"{",
"if",
"(",
"keyList",
".",
"length",
"===",
"0",
"||",
"keyList",
".",
"includes",
"(",
"keyEvent",
".",
"pigletKey",
")",
")",
"{",
"const",
"tDown",
"=",
"keyEvent",
".",
"timestamp",
";",
"const",
"keyPress",
"=",
"new",
"KeyPress",
"(",
"keyEvent",
".",
"code",
",",
"tDown",
",",
"keyEvent",
".",
"pigletKey",
")",
";",
"keyPress",
".",
"rt",
"=",
"tDown",
"-",
"this",
".",
"_clock",
".",
"getLastResetTime",
"(",
")",
";",
"keyPresses",
".",
"push",
"(",
"keyPress",
")",
";",
"if",
"(",
"clear",
")",
"{",
"this",
".",
"_unmatchedKeydownMap",
".",
"delete",
"(",
"keyEvent",
".",
"code",
")",
";",
"this",
".",
"_circularBuffer",
"[",
"unmatchedKeyDownIndex",
"]",
"=",
"null",
";",
"}",
"}",
"}",
"}",
"}",
"if",
"(",
"clear",
"&&",
"keyList",
".",
"length",
"===",
"0",
")",
"this",
".",
"clearEvents",
"(",
")",
";",
"return",
"keyPresses",
";",
"}",
"clearEvents",
"(",
")",
"{",
"this",
".",
"_circularBuffer",
"=",
"new",
"Array",
"(",
"this",
".",
"_bufferSize",
")",
";",
"this",
".",
"_bufferLength",
"=",
"0",
";",
"this",
".",
"_bufferIndex",
"=",
"-",
"1",
";",
"this",
".",
"_previousKeydownKey",
"=",
"undefined",
";",
"this",
".",
"_unmatchedKeydownMap",
"=",
"new",
"Map",
"(",
")",
";",
"}",
"_addKeyListeners",
"(",
")",
"{",
"this",
".",
"_previousKeydownKey",
"=",
"undefined",
";",
"const",
"self",
"=",
"this",
";",
"document",
".",
"addEventListener",
"(",
"\"keydown\"",
",",
"(",
"event",
")",
"=>",
"{",
"const",
"timestamp",
"=",
"MonotonicClock",
".",
"getReferenceTime",
"(",
")",
";",
"if",
"(",
"this",
".",
"_status",
"!==",
"PsychoJS",
".",
"Status",
".",
"STARTED",
")",
"return",
";",
"if",
"(",
"event",
".",
"key",
"===",
"self",
".",
"_previousKeydownKey",
")",
"return",
";",
"self",
".",
"_previousKeydownKey",
"=",
"event",
".",
"key",
";",
"let",
"code",
"=",
"event",
".",
"code",
";",
"if",
"(",
"typeof",
"code",
"===",
"'undefined'",
")",
"code",
"=",
"EventManager",
".",
"keycode2w3c",
"(",
"event",
".",
"keyCode",
")",
";",
"let",
"pigletKey",
"=",
"EventManager",
".",
"w3c2pyglet",
"(",
"code",
")",
";",
"self",
".",
"_bufferIndex",
"=",
"(",
"self",
".",
"_bufferIndex",
"+",
"1",
")",
"%",
"self",
".",
"_bufferSize",
";",
"self",
".",
"_bufferLength",
"=",
"Math",
".",
"min",
"(",
"self",
".",
"_bufferLength",
"+",
"1",
",",
"self",
".",
"_bufferSize",
")",
";",
"self",
".",
"_circularBuffer",
"[",
"self",
".",
"_bufferIndex",
"]",
"=",
"{",
"code",
",",
"key",
":",
"event",
".",
"key",
",",
"pigletKey",
",",
"status",
":",
"Keyboard",
".",
"KeyStatus",
".",
"KEY_DOWN",
",",
"timestamp",
"}",
";",
"self",
".",
"_unmatchedKeydownMap",
".",
"set",
"(",
"event",
".",
"code",
",",
"self",
".",
"_bufferIndex",
")",
";",
"self",
".",
"_psychoJS",
".",
"logger",
".",
"trace",
"(",
"'keydown: '",
",",
"event",
".",
"key",
")",
";",
"console",
".",
"log",
"(",
"self",
".",
"_circularBuffer",
"[",
"self",
".",
"_bufferIndex",
"]",
")",
";",
"}",
")",
";",
"document",
".",
"addEventListener",
"(",
"\"keyup\"",
",",
"(",
"event",
")",
"=>",
"{",
"const",
"timestamp",
"=",
"MonotonicClock",
".",
"getReferenceTime",
"(",
")",
";",
"if",
"(",
"this",
".",
"_status",
"!==",
"PsychoJS",
".",
"Status",
".",
"STARTED",
")",
"return",
";",
"self",
".",
"_previousKeydownKey",
"=",
"undefined",
";",
"let",
"code",
"=",
"event",
".",
"code",
";",
"if",
"(",
"typeof",
"code",
"===",
"'undefined'",
")",
"code",
"=",
"EventManager",
".",
"keycode2w3c",
"(",
"event",
".",
"keyCode",
")",
";",
"let",
"pigletKey",
"=",
"EventManager",
".",
"w3c2pyglet",
"(",
"code",
")",
";",
"self",
".",
"_bufferIndex",
"=",
"(",
"self",
".",
"_bufferIndex",
"+",
"1",
")",
"%",
"self",
".",
"_bufferSize",
";",
"self",
".",
"_bufferLength",
"=",
"Math",
".",
"min",
"(",
"self",
".",
"_bufferLength",
"+",
"1",
",",
"self",
".",
"_bufferSize",
")",
";",
"self",
".",
"_circularBuffer",
"[",
"self",
".",
"_bufferIndex",
"]",
"=",
"{",
"code",
",",
"key",
":",
"event",
".",
"key",
",",
"pigletKey",
",",
"status",
":",
"Keyboard",
".",
"KeyStatus",
".",
"KEY_UP",
",",
"timestamp",
"}",
";",
"const",
"correspondingKeydownIndex",
"=",
"self",
".",
"_unmatchedKeydownMap",
".",
"get",
"(",
"event",
".",
"code",
")",
";",
"if",
"(",
"typeof",
"correspondingKeydownIndex",
"!==",
"'undefined'",
")",
"{",
"self",
".",
"_circularBuffer",
"[",
"self",
".",
"_bufferIndex",
"]",
".",
"keydownIndex",
"=",
"correspondingKeydownIndex",
";",
"self",
".",
"_unmatchedKeydownMap",
".",
"delete",
"(",
"event",
".",
"code",
")",
";",
"}",
"self",
".",
"_psychoJS",
".",
"logger",
".",
"trace",
"(",
"'keyup: '",
",",
"event",
".",
"key",
")",
";",
"console",
".",
"log",
"(",
"self",
".",
"_circularBuffer",
"[",
"self",
".",
"_bufferIndex",
"]",
")",
";",
"}",
")",
";",
"}",
"}"
] |
<p>This manager handles all keyboard events.
|
[
"<p",
">",
"This",
"manager",
"handles",
"all",
"keyboard",
"events",
"."
] |
[
"//this._psychoJS.monotonicClock;",
"// start recording key events if need be:",
"// setup circular buffer:",
"// add key listeners:",
"/**\n\t * Start recording keyboard events.\n\t *\n\t * @name module:core.Keyboard#start\n\t * @function\n\t * @public\n\t *\n\t */",
"/**\n\t * Stop recording keyboard events.\n\t *\n\t * @name module:core.Keyboard#stop\n\t * @function\n\t * @public\n\t *\n\t */",
"/**\n\t * @typedef Keyboard.KeyEvent\n\t *\n\t * @property {string} W3C key code\n\t * @property {string} W3C key\n\t * @property {string} pyglet key\n\t * @property {module:core.Keyboard#KeyStatus} key status\n\t * @property {number} timestamp (in seconds)\n\t */",
"/**\n\t * Get the list of those keyboard events still in the buffer, i.e. those that have not been\n\t * previously cleared by calls to getKeys with clear = true.\n\t *\n\t * @name module:core.Keyboard#getEvents\n\t * @function\n\t * @public\n\t * @return {Keyboard.KeyEvent[]} the list of events still in the buffer\n\t */",
"// iterate over the buffer, from start to end, and discard the null event:",
"/**\n\t * Get the list of keys pressed or pushed by the participant.\n\t *\n\t * @name module:core.Keyboard#getKeys\n\t * @function\n\t * @public\n\t * @param {Object} options\n\t * @param {string[]} [options.keyList= []]] - the list of keys to consider. If keyList is empty, we consider all keys.\n\t * Note that we use pyglet keys here, to make the PsychoJs code more homogeneous with PsychoPy.\n\t * @param {boolean} [options.waitRelease= true] - whether or not to include those keys pressed but not released. If\n\t * waitRelease = false, key presses without a corresponding key release will have an undefined duration.\n\t * @param {boolean} [options.clear= false] - whether or not to keep in the buffer the key presses or pushes for a subsequent call to getKeys. If a keyList has been given and clear = true, we only remove from the buffer those keys in keyList\n\t * @return {KeyPress[]} the list of keys that were pressed (keydown followed by keyup) or pushed\n\t * (keydown with no subsequent keyup at the time getKeys is called).\n\t */",
"// if nothing in the buffer, return immediately:",
"// iterate over the circular buffer, looking for keyup events:",
"// check that the key is in the keyList:",
"// look for a corresponding, preceding keydown event:",
"// prepare KeyPress and add it to the array:",
"/* old approach: the circular buffer contains independent keydown and keyup events:\n\t\t\t\t\tlet j = i - 1;\n\t\t\t\t\tdo {\n\t\t\t\t\t\tif (j === -1 && bufferWrap)\n\t\t\t\t\t\t\tj = this._bufferSize - 1;\n\n\t\t\t\t\t\tconst precedingKeyEvent = this._circularBuffer[j];\n\n\t\t\t\t\t\tif (precedingKeyEvent &&\n\t\t\t\t\t\t\t(precedingKeyEvent.key === keyEvent.key) &&\n\t\t\t\t\t\t\t(precedingKeyEvent.status === Keyboard.KeyStatus.KEY_DOWN)) {\n\t\t\t\t\t\t\tduration = keyEvent.timestamp - precedingKeyEvent.timestamp;\n\n\t\t\t\t\t\t\tif (clear)\n\t\t\t\t\t\t\t// rather than modify the circular buffer, which is computationally expensive,\n\t\t\t\t\t\t\t// we simply nullify the keyEvent:\n\t\t\t\t\t\t\t\tthis._circularBuffer[j] = null;\n\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tj = j - 1;\n\t\t\t\t\t} while ((bufferWrap && j !== i) || (j > -1));*/",
"// if waitRelease = false, we iterate again over the map of unmatched keydown events:",
"// check that the key is in the keyList:",
"/* old approach: the circular buffer contains independent keydown and keyup events:\n\t\t\tlet i = bufferWrap ? this._bufferIndex : -1;\n\t\t\tdo {\n\t\t\t\ti = (i + 1) % this._bufferSize;\n\n\t\t\t\tconst keyEvent = this._circularBuffer[i];\n\t\t\t\tif (keyEvent && keyEvent.status === Keyboard.KeyStatus.KEY_DOWN) {\n\t\t\t\t\t// check that the key is in the keyList:\n\t\t\t\t\tconst pigletKey = EventManager.w3c2pyglet(keyEvent.code);\n\t\t\t\t\tif (keyList.length === 0 || keyList.includes(pigletKey)) {\n\t\t\t\t\t\tkeyPresses.push(new KeyPress(keyEvent.code, keyEvent.timestamp, pigletKey));\n\n\t\t\t\t\t\tif (clear)\n\t\t\t\t\t\t\t// rather than modify the circular buffer, which is computationally expensive, we simply nullify\n\t\t\t\t\t\t\t// the keyEvent:\n\t\t\t\t\t\t\tthis._circularBuffer[i] = null;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} while (i !== this._bufferIndex);*/",
"// if clear = true and the keyList is empty, we clear all the events:",
"// circular buffer of key events (keydown and keyup):",
"// (code => circular buffer index) map of keydown events not yet matched to keyup events:",
"/**\n\t * Add key listeners to the document.\n\t *\n\t * @name module:core.Keyboard#_addKeyListeners\n\t * @function\n\t * @private\n\t */",
"// add a keydown listener:",
"// timestamp in seconds",
"// since keydown events will repeat as long as the key is pressed, we need to track the last pressed key:",
"// take care of legacy Microsoft Edge:",
"// add a keyup listener:",
"// timestamp in seconds",
"// take care of legacy Microsoft Edge:",
"// get the corresponding keydown event",
"// note: if more keys are down than there are slots in the circular buffer, there might",
"// not be a corresponding keydown event"
] |
[
{
"param": "PsychObject",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PsychObject",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 2,671
| 165
|
3da1d74a9e6270b40fecbd48136a6d03c2b71c03
|
Ramkarthik/google-api-dotnet-client
|
Src/Generated/Google.Apis.Appengine.v1beta/Google.Apis.Appengine.v1beta.cs
|
[
"Apache-2.0"
] |
C#
|
ListRequest
|
/// <summary>Lists operations that match the specified filter in the request. If the server doesn't support
/// this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding
/// to use different resource name schemes, such as users/operations. To override the binding, API services
/// can add a binding such as "/v1/{name=users}/operations" to their service configuration. For backwards
/// compatibility, the default name includes the operations collection id, however overriding users must
/// ensure the name binding is the parent resource, without the operations collection id.</summary>
|
Lists operations that match the specified filter in the request. If the server doesn't support
this method, it returns UNIMPLEMENTED.NOTE: the name binding allows API services to override the binding
to use different resource name schemes, such as users/operations. To override the binding, API services
can add a binding such as "/v1/{name=users}/operations" to their service configuration. For backwards
compatibility, the default name includes the operations collection id, however overriding users must
ensure the name binding is the parent resource, without the operations collection id.
|
[
"Lists",
"operations",
"that",
"match",
"the",
"specified",
"filter",
"in",
"the",
"request",
".",
"If",
"the",
"server",
"doesn",
"'",
"t",
"support",
"this",
"method",
"it",
"returns",
"UNIMPLEMENTED",
".",
"NOTE",
":",
"the",
"name",
"binding",
"allows",
"API",
"services",
"to",
"override",
"the",
"binding",
"to",
"use",
"different",
"resource",
"name",
"schemes",
"such",
"as",
"users",
"/",
"operations",
".",
"To",
"override",
"the",
"binding",
"API",
"services",
"can",
"add",
"a",
"binding",
"such",
"as",
"\"",
"/",
"v1",
"/",
"{",
"name",
"=",
"users",
"}",
"/",
"operations",
"\"",
"to",
"their",
"service",
"configuration",
".",
"For",
"backwards",
"compatibility",
"the",
"default",
"name",
"includes",
"the",
"operations",
"collection",
"id",
"however",
"overriding",
"users",
"must",
"ensure",
"the",
"name",
"binding",
"is",
"the",
"parent",
"resource",
"without",
"the",
"operations",
"collection",
"id",
"."
] |
public class ListRequest : AppengineBaseServiceRequest<Google.Apis.Appengine.v1beta.Data.ListOperationsResponse>
{
public ListRequest(Google.Apis.Services.IClientService service, string appsId)
: base(service)
{
AppsId = appsId;
InitParameters();
}
[Google.Apis.Util.RequestParameterAttribute("appsId", Google.Apis.Util.RequestParameterType.Path)]
public virtual string AppsId { get; private set; }
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
public override string MethodName
{
get { return "list"; }
}
public override string HttpMethod
{
get { return "GET"; }
}
public override string RestPath
{
get { return "v1beta/apps/{appsId}/operations"; }
}
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"appsId", new Google.Apis.Discovery.Parameter
{
Name = "appsId",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
|
[
"public",
"class",
"ListRequest",
":",
"AppengineBaseServiceRequest",
"<",
"Google",
".",
"Apis",
".",
"Appengine",
".",
"v1beta",
".",
"Data",
".",
"ListOperationsResponse",
">",
"{",
"public",
"ListRequest",
"(",
"Google",
".",
"Apis",
".",
"Services",
".",
"IClientService",
"service",
",",
"string",
"appsId",
")",
":",
"base",
"(",
"service",
")",
"{",
"AppsId",
"=",
"appsId",
";",
"InitParameters",
"(",
")",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"appsId",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Path",
")",
"]",
"public",
"virtual",
"string",
"AppsId",
"{",
"get",
";",
"private",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"filter",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"string",
"Filter",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"pageToken",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"string",
"PageToken",
"{",
"get",
";",
"set",
";",
"}",
"[",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterAttribute",
"(",
"\"",
"pageSize",
"\"",
",",
"Google",
".",
"Apis",
".",
"Util",
".",
"RequestParameterType",
".",
"Query",
")",
"]",
"public",
"virtual",
"System",
".",
"Nullable",
"<",
"int",
">",
"PageSize",
"{",
"get",
";",
"set",
";",
"}",
"public",
"override",
"string",
"MethodName",
"{",
"get",
"{",
"return",
"\"",
"list",
"\"",
";",
"}",
"}",
"public",
"override",
"string",
"HttpMethod",
"{",
"get",
"{",
"return",
"\"",
"GET",
"\"",
";",
"}",
"}",
"public",
"override",
"string",
"RestPath",
"{",
"get",
"{",
"return",
"\"",
"v1beta/apps/{appsId}/operations",
"\"",
";",
"}",
"}",
"protected",
"override",
"void",
"InitParameters",
"(",
")",
"{",
"base",
".",
"InitParameters",
"(",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"appsId",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"appsId",
"\"",
",",
"IsRequired",
"=",
"true",
",",
"ParameterType",
"=",
"\"",
"path",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"filter",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"filter",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"pageToken",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"pageToken",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"RequestParameters",
".",
"Add",
"(",
"\"",
"pageSize",
"\"",
",",
"new",
"Google",
".",
"Apis",
".",
"Discovery",
".",
"Parameter",
"{",
"Name",
"=",
"\"",
"pageSize",
"\"",
",",
"IsRequired",
"=",
"false",
",",
"ParameterType",
"=",
"\"",
"query",
"\"",
",",
"DefaultValue",
"=",
"null",
",",
"Pattern",
"=",
"null",
",",
"}",
")",
";",
"}",
"}"
] |
Lists operations that match the specified filter in the request.
|
[
"Lists",
"operations",
"that",
"match",
"the",
"specified",
"filter",
"in",
"the",
"request",
"."
] |
[
"/// <summary>Constructs a new List request.</summary>",
"/// <summary>Part of `name`. The name of the operation's parent resource.</summary>",
"/// <summary>The standard list filter.</summary>",
"/// <summary>The standard list page token.</summary>",
"/// <summary>The standard list page size.</summary>",
"///<summary>Gets the method name.</summary>",
"///<summary>Gets the HTTP method.</summary>",
"///<summary>Gets the REST path.</summary>",
"/// <summary>Initializes List parameter list.</summary>"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 472
| 127
|
adaa184544e82ba0cbf73d1524fef287603c06e8
|
xlxCLUxlx/BungieNetPlatform
|
src/BungieNetPlatform/Model/DestinyDefinitionsSocketsDestinySocketTypeDefinition.cs
|
[
"MIT"
] |
C#
|
DestinyDefinitionsSocketsDestinySocketTypeDefinition
|
/// <summary>
/// All Sockets have a \"Type\": a set of common properties that determine when the socket allows Plugs to be inserted, what Categories of Plugs can be inserted, and whether the socket is even visible at all given the current game/character/account state. See DestinyInventoryItemDefinition for more information about Socketed items and Plugs.
/// </summary>
|
All Sockets have a \"Type\": a set of common properties that determine when the socket allows Plugs to be inserted, what Categories of Plugs can be inserted, and whether the socket is even visible at all given the current game/character/account state. See DestinyInventoryItemDefinition for more information about Socketed items and Plugs.
|
[
"All",
"Sockets",
"have",
"a",
"\\",
"\"",
"Type",
"\\",
"\"",
":",
"a",
"set",
"of",
"common",
"properties",
"that",
"determine",
"when",
"the",
"socket",
"allows",
"Plugs",
"to",
"be",
"inserted",
"what",
"Categories",
"of",
"Plugs",
"can",
"be",
"inserted",
"and",
"whether",
"the",
"socket",
"is",
"even",
"visible",
"at",
"all",
"given",
"the",
"current",
"game",
"/",
"character",
"/",
"account",
"state",
".",
"See",
"DestinyInventoryItemDefinition",
"for",
"more",
"information",
"about",
"Socketed",
"items",
"and",
"Plugs",
"."
] |
[DataContract]
public partial class DestinyDefinitionsSocketsDestinySocketTypeDefinition : IEquatable<DestinyDefinitionsSocketsDestinySocketTypeDefinition>, IValidatableObject
{
public DestinyDefinitionsSocketsDestinySocketTypeDefinition(DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition DisplayProperties = default(DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition), DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition InsertAction = default(DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition), List<DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition> PlugWhitelist = default(List<DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition>), uint? SocketCategoryHash = default(uint?), DestinyDestinySocketVisibility Visibility = default(DestinyDestinySocketVisibility), uint? Hash = default(uint?), int? Index = default(int?), bool? Redacted = default(bool?))
{
this.DisplayProperties = DisplayProperties;
this.InsertAction = InsertAction;
this.PlugWhitelist = PlugWhitelist;
this.SocketCategoryHash = SocketCategoryHash;
this.Visibility = Visibility;
this.Hash = Hash;
this.Index = Index;
this.Redacted = Redacted;
}
[DataMember(Name="displayProperties", EmitDefaultValue=false)]
public DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition DisplayProperties { get; set; }
[DataMember(Name="insertAction", EmitDefaultValue=false)]
public DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition InsertAction { get; set; }
[DataMember(Name="plugWhitelist", EmitDefaultValue=false)]
public List<DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition> PlugWhitelist { get; set; }
[DataMember(Name="socketCategoryHash", EmitDefaultValue=false)]
public uint? SocketCategoryHash { get; set; }
[DataMember(Name="visibility", EmitDefaultValue=false)]
public DestinyDestinySocketVisibility Visibility { get; set; }
[DataMember(Name="hash", EmitDefaultValue=false)]
public uint? Hash { get; set; }
[DataMember(Name="index", EmitDefaultValue=false)]
public int? Index { get; set; }
[DataMember(Name="redacted", EmitDefaultValue=false)]
public bool? Redacted { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class DestinyDefinitionsSocketsDestinySocketTypeDefinition {\n");
sb.Append(" DisplayProperties: ").Append(DisplayProperties).Append("\n");
sb.Append(" InsertAction: ").Append(InsertAction).Append("\n");
sb.Append(" PlugWhitelist: ").Append(PlugWhitelist).Append("\n");
sb.Append(" SocketCategoryHash: ").Append(SocketCategoryHash).Append("\n");
sb.Append(" Visibility: ").Append(Visibility).Append("\n");
sb.Append(" Hash: ").Append(Hash).Append("\n");
sb.Append(" Index: ").Append(Index).Append("\n");
sb.Append(" Redacted: ").Append(Redacted).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
public override bool Equals(object input)
{
return this.Equals(input as DestinyDefinitionsSocketsDestinySocketTypeDefinition);
}
public bool Equals(DestinyDefinitionsSocketsDestinySocketTypeDefinition input)
{
if (input == null)
return false;
return
(
this.DisplayProperties == input.DisplayProperties ||
(this.DisplayProperties != null &&
this.DisplayProperties.Equals(input.DisplayProperties))
) &&
(
this.InsertAction == input.InsertAction ||
(this.InsertAction != null &&
this.InsertAction.Equals(input.InsertAction))
) &&
(
this.PlugWhitelist == input.PlugWhitelist ||
this.PlugWhitelist != null &&
this.PlugWhitelist.SequenceEqual(input.PlugWhitelist)
) &&
(
this.SocketCategoryHash == input.SocketCategoryHash ||
(this.SocketCategoryHash != null &&
this.SocketCategoryHash.Equals(input.SocketCategoryHash))
) &&
(
this.Visibility == input.Visibility ||
(this.Visibility != null &&
this.Visibility.Equals(input.Visibility))
) &&
(
this.Hash == input.Hash ||
(this.Hash != null &&
this.Hash.Equals(input.Hash))
) &&
(
this.Index == input.Index ||
(this.Index != null &&
this.Index.Equals(input.Index))
) &&
(
this.Redacted == input.Redacted ||
(this.Redacted != null &&
this.Redacted.Equals(input.Redacted))
);
}
public override int GetHashCode()
{
unchecked
{
int hashCode = 41;
if (this.DisplayProperties != null)
hashCode = hashCode * 59 + this.DisplayProperties.GetHashCode();
if (this.InsertAction != null)
hashCode = hashCode * 59 + this.InsertAction.GetHashCode();
if (this.PlugWhitelist != null)
hashCode = hashCode * 59 + this.PlugWhitelist.GetHashCode();
if (this.SocketCategoryHash != null)
hashCode = hashCode * 59 + this.SocketCategoryHash.GetHashCode();
if (this.Visibility != null)
hashCode = hashCode * 59 + this.Visibility.GetHashCode();
if (this.Hash != null)
hashCode = hashCode * 59 + this.Hash.GetHashCode();
if (this.Index != null)
hashCode = hashCode * 59 + this.Index.GetHashCode();
if (this.Redacted != null)
hashCode = hashCode * 59 + this.Redacted.GetHashCode();
return hashCode;
}
}
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
|
[
"[",
"DataContract",
"]",
"public",
"partial",
"class",
"DestinyDefinitionsSocketsDestinySocketTypeDefinition",
":",
"IEquatable",
"<",
"DestinyDefinitionsSocketsDestinySocketTypeDefinition",
">",
",",
"IValidatableObject",
"{",
"public",
"DestinyDefinitionsSocketsDestinySocketTypeDefinition",
"(",
"DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition",
"DisplayProperties",
"=",
"default",
"(",
"DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition",
")",
",",
"DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition",
"InsertAction",
"=",
"default",
"(",
"DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition",
")",
",",
"List",
"<",
"DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition",
">",
"PlugWhitelist",
"=",
"default",
"(",
"List",
"<",
"DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition",
">",
")",
",",
"uint",
"?",
"SocketCategoryHash",
"=",
"default",
"(",
"uint",
"?",
")",
",",
"DestinyDestinySocketVisibility",
"Visibility",
"=",
"default",
"(",
"DestinyDestinySocketVisibility",
")",
",",
"uint",
"?",
"Hash",
"=",
"default",
"(",
"uint",
"?",
")",
",",
"int",
"?",
"Index",
"=",
"default",
"(",
"int",
"?",
")",
",",
"bool",
"?",
"Redacted",
"=",
"default",
"(",
"bool",
"?",
")",
")",
"{",
"this",
".",
"DisplayProperties",
"=",
"DisplayProperties",
";",
"this",
".",
"InsertAction",
"=",
"InsertAction",
";",
"this",
".",
"PlugWhitelist",
"=",
"PlugWhitelist",
";",
"this",
".",
"SocketCategoryHash",
"=",
"SocketCategoryHash",
";",
"this",
".",
"Visibility",
"=",
"Visibility",
";",
"this",
".",
"Hash",
"=",
"Hash",
";",
"this",
".",
"Index",
"=",
"Index",
";",
"this",
".",
"Redacted",
"=",
"Redacted",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"displayProperties",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition",
"DisplayProperties",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"insertAction",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"DestinyDefinitionsSocketsDestinyInsertPlugActionDefinition",
"InsertAction",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"plugWhitelist",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"List",
"<",
"DestinyDefinitionsSocketsDestinyPlugWhitelistEntryDefinition",
">",
"PlugWhitelist",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"socketCategoryHash",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"uint",
"?",
"SocketCategoryHash",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"visibility",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"DestinyDestinySocketVisibility",
"Visibility",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"hash",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"uint",
"?",
"Hash",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"index",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"int",
"?",
"Index",
"{",
"get",
";",
"set",
";",
"}",
"[",
"DataMember",
"(",
"Name",
"=",
"\"",
"redacted",
"\"",
",",
"EmitDefaultValue",
"=",
"false",
")",
"]",
"public",
"bool",
"?",
"Redacted",
"{",
"get",
";",
"set",
";",
"}",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"var",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
"class DestinyDefinitionsSocketsDestinySocketTypeDefinition {",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" DisplayProperties: ",
"\"",
")",
".",
"Append",
"(",
"DisplayProperties",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" InsertAction: ",
"\"",
")",
".",
"Append",
"(",
"InsertAction",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" PlugWhitelist: ",
"\"",
")",
".",
"Append",
"(",
"PlugWhitelist",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" SocketCategoryHash: ",
"\"",
")",
".",
"Append",
"(",
"SocketCategoryHash",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" Visibility: ",
"\"",
")",
".",
"Append",
"(",
"Visibility",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" Hash: ",
"\"",
")",
".",
"Append",
"(",
"Hash",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" Index: ",
"\"",
")",
".",
"Append",
"(",
"Index",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
" Redacted: ",
"\"",
")",
".",
"Append",
"(",
"Redacted",
")",
".",
"Append",
"(",
"\"",
"\\n",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"\"",
"}",
"\\n",
"\"",
")",
";",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"public",
"string",
"ToJson",
"(",
")",
"{",
"return",
"JsonConvert",
".",
"SerializeObject",
"(",
"this",
",",
"Formatting",
".",
"Indented",
")",
";",
"}",
"public",
"override",
"bool",
"Equals",
"(",
"object",
"input",
")",
"{",
"return",
"this",
".",
"Equals",
"(",
"input",
"as",
"DestinyDefinitionsSocketsDestinySocketTypeDefinition",
")",
";",
"}",
"public",
"bool",
"Equals",
"(",
"DestinyDefinitionsSocketsDestinySocketTypeDefinition",
"input",
")",
"{",
"if",
"(",
"input",
"==",
"null",
")",
"return",
"false",
";",
"return",
"(",
"this",
".",
"DisplayProperties",
"==",
"input",
".",
"DisplayProperties",
"||",
"(",
"this",
".",
"DisplayProperties",
"!=",
"null",
"&&",
"this",
".",
"DisplayProperties",
".",
"Equals",
"(",
"input",
".",
"DisplayProperties",
")",
")",
")",
"&&",
"(",
"this",
".",
"InsertAction",
"==",
"input",
".",
"InsertAction",
"||",
"(",
"this",
".",
"InsertAction",
"!=",
"null",
"&&",
"this",
".",
"InsertAction",
".",
"Equals",
"(",
"input",
".",
"InsertAction",
")",
")",
")",
"&&",
"(",
"this",
".",
"PlugWhitelist",
"==",
"input",
".",
"PlugWhitelist",
"||",
"this",
".",
"PlugWhitelist",
"!=",
"null",
"&&",
"this",
".",
"PlugWhitelist",
".",
"SequenceEqual",
"(",
"input",
".",
"PlugWhitelist",
")",
")",
"&&",
"(",
"this",
".",
"SocketCategoryHash",
"==",
"input",
".",
"SocketCategoryHash",
"||",
"(",
"this",
".",
"SocketCategoryHash",
"!=",
"null",
"&&",
"this",
".",
"SocketCategoryHash",
".",
"Equals",
"(",
"input",
".",
"SocketCategoryHash",
")",
")",
")",
"&&",
"(",
"this",
".",
"Visibility",
"==",
"input",
".",
"Visibility",
"||",
"(",
"this",
".",
"Visibility",
"!=",
"null",
"&&",
"this",
".",
"Visibility",
".",
"Equals",
"(",
"input",
".",
"Visibility",
")",
")",
")",
"&&",
"(",
"this",
".",
"Hash",
"==",
"input",
".",
"Hash",
"||",
"(",
"this",
".",
"Hash",
"!=",
"null",
"&&",
"this",
".",
"Hash",
".",
"Equals",
"(",
"input",
".",
"Hash",
")",
")",
")",
"&&",
"(",
"this",
".",
"Index",
"==",
"input",
".",
"Index",
"||",
"(",
"this",
".",
"Index",
"!=",
"null",
"&&",
"this",
".",
"Index",
".",
"Equals",
"(",
"input",
".",
"Index",
")",
")",
")",
"&&",
"(",
"this",
".",
"Redacted",
"==",
"input",
".",
"Redacted",
"||",
"(",
"this",
".",
"Redacted",
"!=",
"null",
"&&",
"this",
".",
"Redacted",
".",
"Equals",
"(",
"input",
".",
"Redacted",
")",
")",
")",
";",
"}",
"public",
"override",
"int",
"GetHashCode",
"(",
")",
"{",
"unchecked",
"{",
"int",
"hashCode",
"=",
"41",
";",
"if",
"(",
"this",
".",
"DisplayProperties",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"DisplayProperties",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"InsertAction",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"InsertAction",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"PlugWhitelist",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"PlugWhitelist",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"SocketCategoryHash",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"SocketCategoryHash",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"Visibility",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"Visibility",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"Hash",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"Hash",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"Index",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"Index",
".",
"GetHashCode",
"(",
")",
";",
"if",
"(",
"this",
".",
"Redacted",
"!=",
"null",
")",
"hashCode",
"=",
"hashCode",
"*",
"59",
"+",
"this",
".",
"Redacted",
".",
"GetHashCode",
"(",
")",
";",
"return",
"hashCode",
";",
"}",
"}",
"IEnumerable",
"<",
"System",
".",
"ComponentModel",
".",
"DataAnnotations",
".",
"ValidationResult",
">",
"IValidatableObject",
".",
"Validate",
"(",
"ValidationContext",
"validationContext",
")",
"{",
"yield",
"break",
";",
"}",
"}"
] |
All Sockets have a \"Type\": a set of common properties that determine when the socket allows Plugs to be inserted, what Categories of Plugs can be inserted, and whether the socket is even visible at all given the current game/character/account state.
|
[
"All",
"Sockets",
"have",
"a",
"\\",
"\"",
"Type",
"\\",
"\"",
":",
"a",
"set",
"of",
"common",
"properties",
"that",
"determine",
"when",
"the",
"socket",
"allows",
"Plugs",
"to",
"be",
"inserted",
"what",
"Categories",
"of",
"Plugs",
"can",
"be",
"inserted",
"and",
"whether",
"the",
"socket",
"is",
"even",
"visible",
"at",
"all",
"given",
"the",
"current",
"game",
"/",
"character",
"/",
"account",
"state",
"."
] |
[
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"DestinyDefinitionsSocketsDestinySocketTypeDefinition\" /> class.",
"/// </summary>",
"/// <param name=\"DisplayProperties\">There are fields for this display data, but they appear to be unpopulated as of now. I am not sure where in the UI these would show if they even were populated, but I will continue to return this data in case it becomes useful..</param>",
"/// <param name=\"InsertAction\">Defines what happens when a plug is inserted into sockets of this type..</param>",
"/// <param name=\"PlugWhitelist\">A list of Plug \\"Categories\\" that are allowed to be plugged into sockets of this type. These should be compared against a given plug item's DestinyInventoryItemDefinition.plug.plugCategoryHash, which indicates the plug item's category. If the plug's category matches any whitelisted plug, or if the whitelist is empty, it is allowed to be inserted..</param>",
"/// <param name=\"SocketCategoryHash\">SocketCategoryHash.</param>",
"/// <param name=\"Visibility\">Visibility.</param>",
"/// <param name=\"Hash\">The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to..</param>",
"/// <param name=\"Index\">The index of the entity as it was found in the investment tables..</param>",
"/// <param name=\"Redacted\">If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry!.</param>",
"/// <summary>",
"/// There are fields for this display data, but they appear to be unpopulated as of now. I am not sure where in the UI these would show if they even were populated, but I will continue to return this data in case it becomes useful.",
"/// </summary>",
"/// <value>There are fields for this display data, but they appear to be unpopulated as of now. I am not sure where in the UI these would show if they even were populated, but I will continue to return this data in case it becomes useful.</value>",
"/// <summary>",
"/// Defines what happens when a plug is inserted into sockets of this type.",
"/// </summary>",
"/// <value>Defines what happens when a plug is inserted into sockets of this type.</value>",
"/// <summary>",
"/// A list of Plug \\"Categories\\" that are allowed to be plugged into sockets of this type. These should be compared against a given plug item's DestinyInventoryItemDefinition.plug.plugCategoryHash, which indicates the plug item's category. If the plug's category matches any whitelisted plug, or if the whitelist is empty, it is allowed to be inserted.",
"/// </summary>",
"/// <value>A list of Plug \\"Categories\\" that are allowed to be plugged into sockets of this type. These should be compared against a given plug item's DestinyInventoryItemDefinition.plug.plugCategoryHash, which indicates the plug item's category. If the plug's category matches any whitelisted plug, or if the whitelist is empty, it is allowed to be inserted.</value>",
"/// <summary>",
"/// Gets or Sets SocketCategoryHash",
"/// </summary>",
"/// <summary>",
"/// Gets or Sets Visibility",
"/// </summary>",
"/// <summary>",
"/// The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to.",
"/// </summary>",
"/// <value>The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to.</value>",
"/// <summary>",
"/// The index of the entity as it was found in the investment tables.",
"/// </summary>",
"/// <value>The index of the entity as it was found in the investment tables.</value>",
"/// <summary>",
"/// If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry!",
"/// </summary>",
"/// <value>If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry!</value>",
"/// <summary>",
"/// Returns the string presentation of the object",
"/// </summary>",
"/// <returns>String presentation of the object</returns>",
"/// <summary>",
"/// Returns the JSON string presentation of the object",
"/// </summary>",
"/// <returns>JSON string presentation of the object</returns>",
"/// <summary>",
"/// Returns true if objects are equal",
"/// </summary>",
"/// <param name=\"input\">Object to be compared</param>",
"/// <returns>Boolean</returns>",
"/// <summary>",
"/// Returns true if DestinyDefinitionsSocketsDestinySocketTypeDefinition instances are equal",
"/// </summary>",
"/// <param name=\"input\">Instance of DestinyDefinitionsSocketsDestinySocketTypeDefinition to be compared</param>",
"/// <returns>Boolean</returns>",
"/// <summary>",
"/// Gets the hash code",
"/// </summary>",
"/// <returns>Hash code</returns>",
"// Overflow is fine, just wrap",
"/// <summary>",
"/// To validate all properties of the instance",
"/// </summary>",
"/// <param name=\"validationContext\">Validation context</param>",
"/// <returns>Validation Result</returns>"
] |
[
{
"param": "IValidatableObject",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "IValidatableObject",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 21
| 1,238
| 85
|
17aefed26af1a3f4d5808d1a0354495914584d02
|
WCoetser/Trl.PegParser
|
Trl.PegParser/PegFacade.cs
|
[
"MIT"
] |
C#
|
PegFacade
|
/// <summary>
/// Facade for creating PEG parser, tying everything together.
///
/// NB: The purpose of this class is to avoid typing all the generic constraints repeatedly over and over.
///
/// </summary>
/// <typeparam name="TTokenTypeName">Enum to name tokens.</typeparam>
/// <typeparam name="TNonTerminalName">Enum used to name non-terminals and parsing rule heads.</typeparam>
/// <typeparam name="TActionResult">Result of evaluation a match, ex. numbers for a calculator or AST node type for a compiler.</typeparam>
|
Facade for creating PEG parser, tying everything together.
The purpose of this class is to avoid typing all the generic constraints repeatedly over and over.
|
[
"Facade",
"for",
"creating",
"PEG",
"parser",
"tying",
"everything",
"together",
".",
"The",
"purpose",
"of",
"this",
"class",
"is",
"to",
"avoid",
"typing",
"all",
"the",
"generic",
"constraints",
"repeatedly",
"over",
"and",
"over",
"."
] |
public class PegFacade<TTokenTypeName, TNonTerminalName, TActionResult>
where TTokenTypeName : Enum
where TNonTerminalName : Enum
{
public SemanticActionsFacade<TTokenTypeName, TNonTerminalName, TActionResult> DefaultSemanticActions { get; }
public OperatorFacade<TTokenTypeName, TNonTerminalName, TActionResult> Operators { get; }
public PegFacade()
{
DefaultSemanticActions = new SemanticActionsFacade<TTokenTypeName, TNonTerminalName, TActionResult>();
Operators = new OperatorFacade<TTokenTypeName, TNonTerminalName, TActionResult>(DefaultSemanticActions);
}
public Generator<TTokenTypeName, TNonTerminalName, TActionResult> ParserGenerator
=> new Generator<TTokenTypeName, TNonTerminalName, TActionResult>(this);
public TokenDefinition<TTokenTypeName> Token(TTokenTypeName tokenName, Regex tokenDefinition)
=> new TokenDefinition<TTokenTypeName>(tokenName, tokenDefinition);
public Tokenizer<TTokenTypeName> Tokenizer(IEnumerable<TokenDefinition<TTokenTypeName>> prioritizedTokenDefinitions)
=> new Tokenizer<TTokenTypeName>(prioritizedTokenDefinitions);
public Parser<TTokenTypeName, TNonTerminalName, TActionResult> Parser(TNonTerminalName startSymbol,
IEnumerable<ParsingRule<TTokenTypeName, TNonTerminalName, TActionResult>> grammerRules)
{
var semanticAction = DefaultSemanticActions.GetNonTerminalAction(startSymbol);
if (semanticAction == default)
{
semanticAction = DefaultSemanticActions.SemanticAction((_, subResults, matchedPeg) => subResults.FirstOrDefault());
}
return new Parser<TTokenTypeName, TNonTerminalName, TActionResult>(Operators.NonTerminal(startSymbol, semanticAction), grammerRules);
}
public ParsingRule<TTokenTypeName, TNonTerminalName, TActionResult> Rule(TNonTerminalName ruleHead,
IParsingOperator<TTokenTypeName, TNonTerminalName, TActionResult> ruleBody)
=> new ParsingRule<TTokenTypeName, TNonTerminalName, TActionResult>(ruleHead, ruleBody);
}
|
[
"public",
"class",
"PegFacade",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"where",
"TTokenTypeName",
":",
"Enum",
"where",
"TNonTerminalName",
":",
"Enum",
"{",
"public",
"SemanticActionsFacade",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"DefaultSemanticActions",
"{",
"get",
";",
"}",
"public",
"OperatorFacade",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"Operators",
"{",
"get",
";",
"}",
"public",
"PegFacade",
"(",
")",
"{",
"DefaultSemanticActions",
"=",
"new",
"SemanticActionsFacade",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"(",
")",
";",
"Operators",
"=",
"new",
"OperatorFacade",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"(",
"DefaultSemanticActions",
")",
";",
"}",
"public",
"Generator",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"ParserGenerator",
"=>",
"new",
"Generator",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"(",
"this",
")",
";",
"public",
"TokenDefinition",
"<",
"TTokenTypeName",
">",
"Token",
"(",
"TTokenTypeName",
"tokenName",
",",
"Regex",
"tokenDefinition",
")",
"=>",
"new",
"TokenDefinition",
"<",
"TTokenTypeName",
">",
"(",
"tokenName",
",",
"tokenDefinition",
")",
";",
"public",
"Tokenizer",
"<",
"TTokenTypeName",
">",
"Tokenizer",
"(",
"IEnumerable",
"<",
"TokenDefinition",
"<",
"TTokenTypeName",
">",
">",
"prioritizedTokenDefinitions",
")",
"=>",
"new",
"Tokenizer",
"<",
"TTokenTypeName",
">",
"(",
"prioritizedTokenDefinitions",
")",
";",
"public",
"Parser",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"Parser",
"(",
"TNonTerminalName",
"startSymbol",
",",
"IEnumerable",
"<",
"ParsingRule",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
">",
"grammerRules",
")",
"{",
"var",
"semanticAction",
"=",
"DefaultSemanticActions",
".",
"GetNonTerminalAction",
"(",
"startSymbol",
")",
";",
"if",
"(",
"semanticAction",
"==",
"default",
")",
"{",
"semanticAction",
"=",
"DefaultSemanticActions",
".",
"SemanticAction",
"(",
"(",
"_",
",",
"subResults",
",",
"matchedPeg",
")",
"=>",
"subResults",
".",
"FirstOrDefault",
"(",
")",
")",
";",
"}",
"return",
"new",
"Parser",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"(",
"Operators",
".",
"NonTerminal",
"(",
"startSymbol",
",",
"semanticAction",
")",
",",
"grammerRules",
")",
";",
"}",
"public",
"ParsingRule",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"Rule",
"(",
"TNonTerminalName",
"ruleHead",
",",
"IParsingOperator",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"ruleBody",
")",
"=>",
"new",
"ParsingRule",
"<",
"TTokenTypeName",
",",
"TNonTerminalName",
",",
"TActionResult",
">",
"(",
"ruleHead",
",",
"ruleBody",
")",
";",
"}"
] |
Facade for creating PEG parser, tying everything together.
|
[
"Facade",
"for",
"creating",
"PEG",
"parser",
"tying",
"everything",
"together",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": [
{
"identifier": "typeparam",
"docstring": "Enum to name tokens.",
"docstring_tokens": [
"Enum",
"to",
"name",
"tokens",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Enum used to name non-terminals and parsing rule heads.",
"docstring_tokens": [
"Enum",
"used",
"to",
"name",
"non",
"-",
"terminals",
"and",
"parsing",
"rule",
"heads",
"."
]
},
{
"identifier": "typeparam",
"docstring": "Result of evaluation a match, ex. numbers for a calculator or AST node type for a compiler.",
"docstring_tokens": [
"Result",
"of",
"evaluation",
"a",
"match",
"ex",
".",
"numbers",
"for",
"a",
"calculator",
"or",
"AST",
"node",
"type",
"for",
"a",
"compiler",
"."
]
}
]
}
| false
| 15
| 435
| 116
|
89a391a90b3e42e1819e7f801b7b9a3b6db3cb57
|
MohamedRaslan/screenpy
|
screenpy/questions/attribute.py
|
[
"MIT"
] |
Python
|
Attribute
|
Ask about an attribute on an element.
Abilities Required:
|BrowseTheWeb|
Examples::
the_actor.should(
See.the(
Attribute("value").of_the(NAME_INPUT), ReadsExactly("Jessica Walters")),
),
See.the(
Attribute("aria-label").of_the(BALLOONS), ContainsTheText("balloon")),
),
)
|
Ask about an attribute on an element.
|
[
"Ask",
"about",
"an",
"attribute",
"on",
"an",
"element",
"."
] |
class Attribute:
"""Ask about an attribute on an element.
Abilities Required:
|BrowseTheWeb|
Examples::
the_actor.should(
See.the(
Attribute("value").of_the(NAME_INPUT), ReadsExactly("Jessica Walters")),
),
See.the(
Attribute("aria-label").of_the(BALLOONS), ContainsTheText("balloon")),
),
)
"""
target: Optional[Target]
def of(self, target: Target) -> "Attribute":
"""Target the element to get the attribute from."""
self.target = target
return self
of_the = of
def of_all(self, target: Target) -> "Attribute":
"""Target the elements, plural, to get the attribute from."""
self.target = target
self.multi = True
return self
@beat('{} examines the "{attribute}" attribute of the {target}...')
def answered_by(self, the_actor: Actor) -> Union[str, List[Union[str, None]], None]:
"""Direct the actor to investigate the attribute on the element."""
if self.target is None:
raise UnableToAnswer(
"No Target given to Attribute to investigate. Supply a Target"
" with the `.of()`, `.of_the()`, or `.of_all()` method."
)
if self.multi:
elements = self.target.all_found_by(the_actor)
return [element.get_attribute(self.attribute) for element in elements]
return self.target.found_by(the_actor).get_attribute(self.attribute)
def __init__(self, attribute: str) -> None:
self.attribute = attribute
self.multi = False
self.target = None
|
[
"class",
"Attribute",
":",
"target",
":",
"Optional",
"[",
"Target",
"]",
"def",
"of",
"(",
"self",
",",
"target",
":",
"Target",
")",
"->",
"\"Attribute\"",
":",
"\"\"\"Target the element to get the attribute from.\"\"\"",
"self",
".",
"target",
"=",
"target",
"return",
"self",
"of_the",
"=",
"of",
"def",
"of_all",
"(",
"self",
",",
"target",
":",
"Target",
")",
"->",
"\"Attribute\"",
":",
"\"\"\"Target the elements, plural, to get the attribute from.\"\"\"",
"self",
".",
"target",
"=",
"target",
"self",
".",
"multi",
"=",
"True",
"return",
"self",
"@",
"beat",
"(",
"'{} examines the \"{attribute}\" attribute of the {target}...'",
")",
"def",
"answered_by",
"(",
"self",
",",
"the_actor",
":",
"Actor",
")",
"->",
"Union",
"[",
"str",
",",
"List",
"[",
"Union",
"[",
"str",
",",
"None",
"]",
"]",
",",
"None",
"]",
":",
"\"\"\"Direct the actor to investigate the attribute on the element.\"\"\"",
"if",
"self",
".",
"target",
"is",
"None",
":",
"raise",
"UnableToAnswer",
"(",
"\"No Target given to Attribute to investigate. Supply a Target\"",
"\" with the `.of()`, `.of_the()`, or `.of_all()` method.\"",
")",
"if",
"self",
".",
"multi",
":",
"elements",
"=",
"self",
".",
"target",
".",
"all_found_by",
"(",
"the_actor",
")",
"return",
"[",
"element",
".",
"get_attribute",
"(",
"self",
".",
"attribute",
")",
"for",
"element",
"in",
"elements",
"]",
"return",
"self",
".",
"target",
".",
"found_by",
"(",
"the_actor",
")",
".",
"get_attribute",
"(",
"self",
".",
"attribute",
")",
"def",
"__init__",
"(",
"self",
",",
"attribute",
":",
"str",
")",
"->",
"None",
":",
"self",
".",
"attribute",
"=",
"attribute",
"self",
".",
"multi",
"=",
"False",
"self",
".",
"target",
"=",
"None"
] |
Ask about an attribute on an element.
|
[
"Ask",
"about",
"an",
"attribute",
"on",
"an",
"element",
"."
] |
[
"\"\"\"Ask about an attribute on an element.\n\n Abilities Required:\n |BrowseTheWeb|\n\n Examples::\n\n the_actor.should(\n See.the(\n Attribute(\"value\").of_the(NAME_INPUT), ReadsExactly(\"Jessica Walters\")),\n ),\n See.the(\n Attribute(\"aria-label\").of_the(BALLOONS), ContainsTheText(\"balloon\")),\n ),\n )\n \"\"\"",
"\"\"\"Target the element to get the attribute from.\"\"\"",
"\"\"\"Target the elements, plural, to get the attribute from.\"\"\"",
"\"\"\"Direct the actor to investigate the attribute on the element.\"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 352
| 77
|
934eb022d840abddec6673131480d5ab78e812ae
|
iqoffee/basic-js
|
src/vigenere-cipher.js
|
[
"MIT"
] |
JavaScript
|
VigenereCipheringMachine
|
/**
* Implement class VigenereCipheringMachine that allows us to create
* direct and reverse ciphering machines according to task description
*
* @example
*
* const directMachine = new VigenereCipheringMachine();
*
* const reverseMachine = new VigenereCipheringMachine(false);
*
* directMachine.encrypt('attack at dawn!', 'alphonse') => 'AEIHQX SX DLLU!'
*
* directMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => 'ATTACK AT DAWN!'
*
* reverseMachine.encrypt('attack at dawn!', 'alphonse') => '!ULLD XS XQHIEA'
*
* reverseMachine.decrypt('AEIHQX SX DLLU!', 'alphonse') => '!NWAD TA KCATTA'
*
*/
|
Implement class VigenereCipheringMachine that allows us to create
direct and reverse ciphering machines according to task description
@example
const directMachine = new VigenereCipheringMachine().
const reverseMachine = new VigenereCipheringMachine(false).
|
[
"Implement",
"class",
"VigenereCipheringMachine",
"that",
"allows",
"us",
"to",
"create",
"direct",
"and",
"reverse",
"ciphering",
"machines",
"according",
"to",
"task",
"description",
"@example",
"const",
"directMachine",
"=",
"new",
"VigenereCipheringMachine",
"()",
".",
"const",
"reverseMachine",
"=",
"new",
"VigenereCipheringMachine",
"(",
"false",
")",
"."
] |
class VigenereCipheringMachine {
constructor(mode = true) {
this.mode = mode;
this.lengthLetters = 26;
this.start = 65;
}
config(str, key) {
if (!str || !key) {
throw new Error('Incorrect arguments!');
}
str = str.toUpperCase();
key = key.toUpperCase();
if (str.length > key.length) {
key = key.repeat(Math.ceil(str.length / key.length));
}
this.str = str;
this.key = key;
}
encrypt(str, key) {
this.config(str, key);
let res = '';
let indent = 0;
for (let i = 0; i < this.str.length; i++) {
const char = this.str.charCodeAt(i) - this.start;
const shift = this.key.charCodeAt(i - indent) - this.start;
if (char < 0 || char > this.lengthLetters) {
res += this.str[i];
indent++;
} else {
res += String.fromCharCode(
((char + shift) % this.lengthLetters) + this.start
);
}
}
return this.mode ? res : res.split('').reverse().join('');
}
decrypt(str, key) {
this.config(str, key);
let res = '';
let indent = 0;
for (let i = 0; i < this.str.length; i++) {
const char = this.str.charCodeAt(i) - this.start;
const shift = this.key.charCodeAt(i - indent) - this.start;
if (char < 0 || char > this.lengthLetters) {
res += this.str[i];
indent++;
} else {
res += String.fromCharCode(
((char - shift + this.lengthLetters) % this.lengthLetters) +
this.start
);
}
}
return this.mode ? res : res.split('').reverse().join('');
}
}
|
[
"class",
"VigenereCipheringMachine",
"{",
"constructor",
"(",
"mode",
"=",
"true",
")",
"{",
"this",
".",
"mode",
"=",
"mode",
";",
"this",
".",
"lengthLetters",
"=",
"26",
";",
"this",
".",
"start",
"=",
"65",
";",
"}",
"config",
"(",
"str",
",",
"key",
")",
"{",
"if",
"(",
"!",
"str",
"||",
"!",
"key",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Incorrect arguments!'",
")",
";",
"}",
"str",
"=",
"str",
".",
"toUpperCase",
"(",
")",
";",
"key",
"=",
"key",
".",
"toUpperCase",
"(",
")",
";",
"if",
"(",
"str",
".",
"length",
">",
"key",
".",
"length",
")",
"{",
"key",
"=",
"key",
".",
"repeat",
"(",
"Math",
".",
"ceil",
"(",
"str",
".",
"length",
"/",
"key",
".",
"length",
")",
")",
";",
"}",
"this",
".",
"str",
"=",
"str",
";",
"this",
".",
"key",
"=",
"key",
";",
"}",
"encrypt",
"(",
"str",
",",
"key",
")",
"{",
"this",
".",
"config",
"(",
"str",
",",
"key",
")",
";",
"let",
"res",
"=",
"''",
";",
"let",
"indent",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"str",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"char",
"=",
"this",
".",
"str",
".",
"charCodeAt",
"(",
"i",
")",
"-",
"this",
".",
"start",
";",
"const",
"shift",
"=",
"this",
".",
"key",
".",
"charCodeAt",
"(",
"i",
"-",
"indent",
")",
"-",
"this",
".",
"start",
";",
"if",
"(",
"char",
"<",
"0",
"||",
"char",
">",
"this",
".",
"lengthLetters",
")",
"{",
"res",
"+=",
"this",
".",
"str",
"[",
"i",
"]",
";",
"indent",
"++",
";",
"}",
"else",
"{",
"res",
"+=",
"String",
".",
"fromCharCode",
"(",
"(",
"(",
"char",
"+",
"shift",
")",
"%",
"this",
".",
"lengthLetters",
")",
"+",
"this",
".",
"start",
")",
";",
"}",
"}",
"return",
"this",
".",
"mode",
"?",
"res",
":",
"res",
".",
"split",
"(",
"''",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
"decrypt",
"(",
"str",
",",
"key",
")",
"{",
"this",
".",
"config",
"(",
"str",
",",
"key",
")",
";",
"let",
"res",
"=",
"''",
";",
"let",
"indent",
"=",
"0",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"this",
".",
"str",
".",
"length",
";",
"i",
"++",
")",
"{",
"const",
"char",
"=",
"this",
".",
"str",
".",
"charCodeAt",
"(",
"i",
")",
"-",
"this",
".",
"start",
";",
"const",
"shift",
"=",
"this",
".",
"key",
".",
"charCodeAt",
"(",
"i",
"-",
"indent",
")",
"-",
"this",
".",
"start",
";",
"if",
"(",
"char",
"<",
"0",
"||",
"char",
">",
"this",
".",
"lengthLetters",
")",
"{",
"res",
"+=",
"this",
".",
"str",
"[",
"i",
"]",
";",
"indent",
"++",
";",
"}",
"else",
"{",
"res",
"+=",
"String",
".",
"fromCharCode",
"(",
"(",
"(",
"char",
"-",
"shift",
"+",
"this",
".",
"lengthLetters",
")",
"%",
"this",
".",
"lengthLetters",
")",
"+",
"this",
".",
"start",
")",
";",
"}",
"}",
"return",
"this",
".",
"mode",
"?",
"res",
":",
"res",
".",
"split",
"(",
"''",
")",
".",
"reverse",
"(",
")",
".",
"join",
"(",
"''",
")",
";",
"}",
"}"
] |
Implement class VigenereCipheringMachine that allows us to create
direct and reverse ciphering machines according to task description
|
[
"Implement",
"class",
"VigenereCipheringMachine",
"that",
"allows",
"us",
"to",
"create",
"direct",
"and",
"reverse",
"ciphering",
"machines",
"according",
"to",
"task",
"description"
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 20
| 411
| 170
|
6c98ef481703ee5c8e67e53a86e4dc7fbd6694c1
|
mcimbora/infinispan
|
core/src/main/java/org/infinispan/transaction/totalorder/TotalOrderManager.java
|
[
"Apache-2.0"
] |
Java
|
TotalOrderManager
|
/**
* This class behaves as a synchronization point between incoming transactions (totally ordered) and between incoming
* transactions and state transfer.
* <p/>
* Main functions:
* <ul>
* <li>
* ensure an order between prepares before sending them to the thread pool, i.e. non-conflicting
* prepares can be processed concurrently;
* </li>
* <li>
* ensure that the state transfer waits for the previous delivered prepares;
* </li>
* <li>
* ensure that the prepare waits for state transfer in progress.
* </li>
* </ul>
*
* @author Pedro Ruivo
* @since 5.3
*/
|
This class behaves as a synchronization point between incoming transactions (totally ordered) and between incoming
transactions and state transfer.
Main functions:
ensure an order between prepares before sending them to the thread pool, i.e. non-conflicting
prepares can be processed concurrently;
ensure that the state transfer waits for the previous delivered prepares;
ensure that the prepare waits for state transfer in progress.
@author Pedro Ruivo
@since 5.3
|
[
"This",
"class",
"behaves",
"as",
"a",
"synchronization",
"point",
"between",
"incoming",
"transactions",
"(",
"totally",
"ordered",
")",
"and",
"between",
"incoming",
"transactions",
"and",
"state",
"transfer",
".",
"Main",
"functions",
":",
"ensure",
"an",
"order",
"between",
"prepares",
"before",
"sending",
"them",
"to",
"the",
"thread",
"pool",
"i",
".",
"e",
".",
"non",
"-",
"conflicting",
"prepares",
"can",
"be",
"processed",
"concurrently",
";",
"ensure",
"that",
"the",
"state",
"transfer",
"waits",
"for",
"the",
"previous",
"delivered",
"prepares",
";",
"ensure",
"that",
"the",
"prepare",
"waits",
"for",
"state",
"transfer",
"in",
"progress",
".",
"@author",
"Pedro",
"Ruivo",
"@since",
"5",
".",
"3"
] |
public class TotalOrderManager {
private static final Log log = LogFactory.getLog(TotalOrderManager.class);
/**
* this map is used to keep track of concurrent transactions.
*/
private final ConcurrentMap<Object, TotalOrderLatch> keysLocked;
private final AtomicReference<TotalOrderLatch> clear;
private final AtomicReference<TotalOrderLatch> stateTransferInProgress;
private BlockingTaskAwareExecutorService totalOrderExecutor;
public TotalOrderManager() {
keysLocked = CollectionFactory.makeConcurrentMap();
clear = new AtomicReference<TotalOrderLatch>(null);
stateTransferInProgress = new AtomicReference<TotalOrderLatch>(null);
}
@Inject
public void inject(@ComponentName(KnownComponentNames.TOTAL_ORDER_EXECUTOR) BlockingTaskAwareExecutorService totalOrderExecutor) {
this.totalOrderExecutor = totalOrderExecutor;
}
/**
* It ensures the validation order for the transaction corresponding to the prepare command. This allow the prepare
* command to be moved to a thread pool.
*
* @param state the total order prepare state
*/
public final void ensureOrder(TotalOrderRemoteTransactionState state, Object[] keysModified) throws InterruptedException {
//the retries due to state transfer re-uses the same state. we need that the keys previous locked to be release
//in order to insert it again in the keys locked.
//NOTE: this method does not need to be synchronized because it is invoked by a one thread at the time, namely
//the thread that is delivering the messages in total order.
state.awaitUntilReset();
TotalOrderLatch transactionSynchronizedBlock = new TotalOrderLatchImpl(state.getGlobalTransaction().globalId());
state.setTransactionSynchronizedBlock(transactionSynchronizedBlock);
if (keysModified == null) { //clear state
TotalOrderLatch oldClear = clear.get();
if (oldClear != null) {
state.addSynchronizedBlock(oldClear);
clear.set(transactionSynchronizedBlock);
}
//add all other "locks"
state.addAllSynchronizedBlocks(keysLocked.values());
keysLocked.clear();
state.addKeysLockedForClear();
} else {
TotalOrderLatch clearTx = clear.get();
if (clearTx != null) {
state.addSynchronizedBlock(clearTx);
}
//this will collect all the count down latch corresponding to the previous transactions in the queue
for (Object key : keysModified) {
TotalOrderLatch prevTx = keysLocked.put(key, transactionSynchronizedBlock);
if (prevTx != null) {
state.addSynchronizedBlock(prevTx);
}
state.addLockedKey(key);
}
}
TotalOrderLatch stateTransfer = stateTransferInProgress.get();
if (stateTransfer != null) {
state.addSynchronizedBlock(stateTransfer);
}
if (log.isTraceEnabled()) {
log.tracef("Transaction [%s] will wait for %s and locked %s", state.getGlobalTransaction().globalId(),
state.getConflictingTransactionBlocks(), state.getLockedKeys() == null ? "[ClearCommand]" :
state.getLockedKeys());
}
}
/**
* Release the locked key possibly unblock waiting prepares.
*
* @param state the state
*/
public final void release(TotalOrderRemoteTransactionState state) {
TotalOrderLatch synchronizedBlock = state.getTransactionSynchronizedBlock();
if (synchronizedBlock == null) {
//already released!
return;
}
Collection<Object> lockedKeys = state.getLockedKeys();
synchronizedBlock.unBlock();
if (lockedKeys == null) {
clear.compareAndSet(synchronizedBlock, null);
} else {
for (Object key : lockedKeys) {
keysLocked.remove(key, synchronizedBlock);
}
}
if (log.isTraceEnabled()) {
log.tracef("Release %s and locked keys %s. Checking pending tasks!", synchronizedBlock,
lockedKeys == null ? "[ClearCommand]" : lockedKeys);
}
state.reset();
}
/**
* It notifies that a state transfer is about to start.
*
* @param topologyId the new topology ID
* @return the current pending prepares
*/
public final Collection<TotalOrderLatch> notifyStateTransferStart(int topologyId) {
List<TotalOrderLatch> preparingTransactions = new ArrayList<TotalOrderLatch>(keysLocked.size());
preparingTransactions.addAll(keysLocked.values());
TotalOrderLatch clearBlock = clear.get();
if (clearBlock != null) {
preparingTransactions.add(clearBlock);
}
if (stateTransferInProgress.get() == null) {
stateTransferInProgress.set(new TotalOrderLatchImpl("StateTransfer-" + topologyId));
}
if (log.isTraceEnabled()) {
log.tracef("State Transfer start. It will wait for %s", preparingTransactions);
}
return preparingTransactions;
}
/**
* It notifies the end of the state transfer possibly unblock waiting prepares.
*/
public final void notifyStateTransferEnd() {
TotalOrderLatch block = stateTransferInProgress.getAndSet(null);
if (block != null) {
block.unBlock();
}
if (log.isTraceEnabled()) {
log.tracef("State Transfer finish. It will release %s", block);
}
totalOrderExecutor.checkForReadyTasks();
}
public final boolean hasAnyLockAcquired() {
return !keysLocked.isEmpty() || clear.get() != null;
}
}
|
[
"public",
"class",
"TotalOrderManager",
"{",
"private",
"static",
"final",
"Log",
"log",
"=",
"LogFactory",
".",
"getLog",
"(",
"TotalOrderManager",
".",
"class",
")",
";",
"/**\n * this map is used to keep track of concurrent transactions.\n */",
"private",
"final",
"ConcurrentMap",
"<",
"Object",
",",
"TotalOrderLatch",
">",
"keysLocked",
";",
"private",
"final",
"AtomicReference",
"<",
"TotalOrderLatch",
">",
"clear",
";",
"private",
"final",
"AtomicReference",
"<",
"TotalOrderLatch",
">",
"stateTransferInProgress",
";",
"private",
"BlockingTaskAwareExecutorService",
"totalOrderExecutor",
";",
"public",
"TotalOrderManager",
"(",
")",
"{",
"keysLocked",
"=",
"CollectionFactory",
".",
"makeConcurrentMap",
"(",
")",
";",
"clear",
"=",
"new",
"AtomicReference",
"<",
"TotalOrderLatch",
">",
"(",
"null",
")",
";",
"stateTransferInProgress",
"=",
"new",
"AtomicReference",
"<",
"TotalOrderLatch",
">",
"(",
"null",
")",
";",
"}",
"@",
"Inject",
"public",
"void",
"inject",
"(",
"@",
"ComponentName",
"(",
"KnownComponentNames",
".",
"TOTAL_ORDER_EXECUTOR",
")",
"BlockingTaskAwareExecutorService",
"totalOrderExecutor",
")",
"{",
"this",
".",
"totalOrderExecutor",
"=",
"totalOrderExecutor",
";",
"}",
"/**\n * It ensures the validation order for the transaction corresponding to the prepare command. This allow the prepare\n * command to be moved to a thread pool.\n *\n * @param state the total order prepare state\n */",
"public",
"final",
"void",
"ensureOrder",
"(",
"TotalOrderRemoteTransactionState",
"state",
",",
"Object",
"[",
"]",
"keysModified",
")",
"throws",
"InterruptedException",
"{",
"state",
".",
"awaitUntilReset",
"(",
")",
";",
"TotalOrderLatch",
"transactionSynchronizedBlock",
"=",
"new",
"TotalOrderLatchImpl",
"(",
"state",
".",
"getGlobalTransaction",
"(",
")",
".",
"globalId",
"(",
")",
")",
";",
"state",
".",
"setTransactionSynchronizedBlock",
"(",
"transactionSynchronizedBlock",
")",
";",
"if",
"(",
"keysModified",
"==",
"null",
")",
"{",
"TotalOrderLatch",
"oldClear",
"=",
"clear",
".",
"get",
"(",
")",
";",
"if",
"(",
"oldClear",
"!=",
"null",
")",
"{",
"state",
".",
"addSynchronizedBlock",
"(",
"oldClear",
")",
";",
"clear",
".",
"set",
"(",
"transactionSynchronizedBlock",
")",
";",
"}",
"state",
".",
"addAllSynchronizedBlocks",
"(",
"keysLocked",
".",
"values",
"(",
")",
")",
";",
"keysLocked",
".",
"clear",
"(",
")",
";",
"state",
".",
"addKeysLockedForClear",
"(",
")",
";",
"}",
"else",
"{",
"TotalOrderLatch",
"clearTx",
"=",
"clear",
".",
"get",
"(",
")",
";",
"if",
"(",
"clearTx",
"!=",
"null",
")",
"{",
"state",
".",
"addSynchronizedBlock",
"(",
"clearTx",
")",
";",
"}",
"for",
"(",
"Object",
"key",
":",
"keysModified",
")",
"{",
"TotalOrderLatch",
"prevTx",
"=",
"keysLocked",
".",
"put",
"(",
"key",
",",
"transactionSynchronizedBlock",
")",
";",
"if",
"(",
"prevTx",
"!=",
"null",
")",
"{",
"state",
".",
"addSynchronizedBlock",
"(",
"prevTx",
")",
";",
"}",
"state",
".",
"addLockedKey",
"(",
"key",
")",
";",
"}",
"}",
"TotalOrderLatch",
"stateTransfer",
"=",
"stateTransferInProgress",
".",
"get",
"(",
")",
";",
"if",
"(",
"stateTransfer",
"!=",
"null",
")",
"{",
"state",
".",
"addSynchronizedBlock",
"(",
"stateTransfer",
")",
";",
"}",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"tracef",
"(",
"\"",
"Transaction [%s] will wait for %s and locked %s",
"\"",
",",
"state",
".",
"getGlobalTransaction",
"(",
")",
".",
"globalId",
"(",
")",
",",
"state",
".",
"getConflictingTransactionBlocks",
"(",
")",
",",
"state",
".",
"getLockedKeys",
"(",
")",
"==",
"null",
"?",
"\"",
"[ClearCommand]",
"\"",
":",
"state",
".",
"getLockedKeys",
"(",
")",
")",
";",
"}",
"}",
"/**\n * Release the locked key possibly unblock waiting prepares.\n *\n * @param state the state\n */",
"public",
"final",
"void",
"release",
"(",
"TotalOrderRemoteTransactionState",
"state",
")",
"{",
"TotalOrderLatch",
"synchronizedBlock",
"=",
"state",
".",
"getTransactionSynchronizedBlock",
"(",
")",
";",
"if",
"(",
"synchronizedBlock",
"==",
"null",
")",
"{",
"return",
";",
"}",
"Collection",
"<",
"Object",
">",
"lockedKeys",
"=",
"state",
".",
"getLockedKeys",
"(",
")",
";",
"synchronizedBlock",
".",
"unBlock",
"(",
")",
";",
"if",
"(",
"lockedKeys",
"==",
"null",
")",
"{",
"clear",
".",
"compareAndSet",
"(",
"synchronizedBlock",
",",
"null",
")",
";",
"}",
"else",
"{",
"for",
"(",
"Object",
"key",
":",
"lockedKeys",
")",
"{",
"keysLocked",
".",
"remove",
"(",
"key",
",",
"synchronizedBlock",
")",
";",
"}",
"}",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"tracef",
"(",
"\"",
"Release %s and locked keys %s. Checking pending tasks!",
"\"",
",",
"synchronizedBlock",
",",
"lockedKeys",
"==",
"null",
"?",
"\"",
"[ClearCommand]",
"\"",
":",
"lockedKeys",
")",
";",
"}",
"state",
".",
"reset",
"(",
")",
";",
"}",
"/**\n * It notifies that a state transfer is about to start.\n *\n * @param topologyId the new topology ID\n * @return the current pending prepares\n */",
"public",
"final",
"Collection",
"<",
"TotalOrderLatch",
">",
"notifyStateTransferStart",
"(",
"int",
"topologyId",
")",
"{",
"List",
"<",
"TotalOrderLatch",
">",
"preparingTransactions",
"=",
"new",
"ArrayList",
"<",
"TotalOrderLatch",
">",
"(",
"keysLocked",
".",
"size",
"(",
")",
")",
";",
"preparingTransactions",
".",
"addAll",
"(",
"keysLocked",
".",
"values",
"(",
")",
")",
";",
"TotalOrderLatch",
"clearBlock",
"=",
"clear",
".",
"get",
"(",
")",
";",
"if",
"(",
"clearBlock",
"!=",
"null",
")",
"{",
"preparingTransactions",
".",
"add",
"(",
"clearBlock",
")",
";",
"}",
"if",
"(",
"stateTransferInProgress",
".",
"get",
"(",
")",
"==",
"null",
")",
"{",
"stateTransferInProgress",
".",
"set",
"(",
"new",
"TotalOrderLatchImpl",
"(",
"\"",
"StateTransfer-",
"\"",
"+",
"topologyId",
")",
")",
";",
"}",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"tracef",
"(",
"\"",
"State Transfer start. It will wait for %s",
"\"",
",",
"preparingTransactions",
")",
";",
"}",
"return",
"preparingTransactions",
";",
"}",
"/**\n * It notifies the end of the state transfer possibly unblock waiting prepares.\n */",
"public",
"final",
"void",
"notifyStateTransferEnd",
"(",
")",
"{",
"TotalOrderLatch",
"block",
"=",
"stateTransferInProgress",
".",
"getAndSet",
"(",
"null",
")",
";",
"if",
"(",
"block",
"!=",
"null",
")",
"{",
"block",
".",
"unBlock",
"(",
")",
";",
"}",
"if",
"(",
"log",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"log",
".",
"tracef",
"(",
"\"",
"State Transfer finish. It will release %s",
"\"",
",",
"block",
")",
";",
"}",
"totalOrderExecutor",
".",
"checkForReadyTasks",
"(",
")",
";",
"}",
"public",
"final",
"boolean",
"hasAnyLockAcquired",
"(",
")",
"{",
"return",
"!",
"keysLocked",
".",
"isEmpty",
"(",
")",
"||",
"clear",
".",
"get",
"(",
")",
"!=",
"null",
";",
"}",
"}"
] |
This class behaves as a synchronization point between incoming transactions (totally ordered) and between incoming
transactions and state transfer.
|
[
"This",
"class",
"behaves",
"as",
"a",
"synchronization",
"point",
"between",
"incoming",
"transactions",
"(",
"totally",
"ordered",
")",
"and",
"between",
"incoming",
"transactions",
"and",
"state",
"transfer",
"."
] |
[
"//the retries due to state transfer re-uses the same state. we need that the keys previous locked to be release",
"//in order to insert it again in the keys locked.",
"//NOTE: this method does not need to be synchronized because it is invoked by a one thread at the time, namely",
"//the thread that is delivering the messages in total order.",
"//clear state",
"//add all other \"locks\"",
"//this will collect all the count down latch corresponding to the previous transactions in the queue",
"//already released!"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 1,163
| 146
|
5dab8ef347daeae07aa3696a1cec2b852a1bdcce
|
tnoiret/ObjectCodeExporter
|
ObjectCodeExporter.Package/GetObjectCodePackage.cs
|
[
"MIT"
] |
C#
|
GetObjectCodePackage
|
/// <summary>
/// This is the class that implements the package exposed by this assembly.
/// </summary>
/// <remarks>
/// <para>
/// The minimum requirement for a class to be considered a valid package for Visual Studio
/// is to implement the IVsPackage interface and register itself with the shell.
/// This package uses the helper classes defined inside the Managed Package Framework (MPF)
/// to do it: it derives from the Package class that provides the implementation of the
/// IVsPackage interface and uses the registration attributes defined in the framework to
/// register itself and its components with the shell. These attributes tell the pkgdef creation
/// utility what data to put into .pkgdef file.
/// </para>
/// <para>
/// To get loaded into VS, the package must be referred by <Asset Type="Microsoft.VisualStudio.VsPackage" ...> in .vsixmanifest file.
/// </para>
/// </remarks>
|
This is the class that implements the package exposed by this assembly.
|
[
"This",
"is",
"the",
"class",
"that",
"implements",
"the",
"package",
"exposed",
"by",
"this",
"assembly",
"."
] |
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
[ProvideMenuResource("Menus.ctmenu", 1)]
[Guid(GetObjectCodePackage.PackageGuidString)]
[ProvideAutoLoad(VSConstants.UICONTEXT.NoSolution_string, PackageAutoLoadFlags.BackgroundLoad)]
[SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "pkgdef, VS and vsixmanifest are valid VS terms")]
public sealed class GetObjectCodePackage : AsyncPackage
{
public const string PackageGuidString = "77dd3d7f-6bc4-46cd-a437-5f17d94a3eb7";
public GetObjectCodePackage()
{
}
#region Package Members
const string DLL_VISUALIZER = "ObjectCodeExporter.Visualizer.dll";
const string DLL_CORE = "ObjectCodeExporter.dll";
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
await GetObjectCode.InitializeAsync(this);
string sourceFolderFullName = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (await GetServiceAsync(typeof(SVsShell)) is IVsShell shell)
{
shell.GetProperty((int)__VSSPROPID2.VSSPROPID_VisualStudioDir, out object path);
string destinationFolderFullName = Path.Combine((string)path, "Visualizers");
string sourceFileFullName = Path.Combine(sourceFolderFullName, DLL_VISUALIZER);
string destinationFileFullName = Path.Combine(destinationFolderFullName, DLL_VISUALIZER);
CopyFileIfNewerVersion(sourceFileFullName, destinationFileFullName);
string sourceFileFullNameCore = Path.Combine(sourceFolderFullName, DLL_CORE);
string destinationFileFullNameCore = Path.Combine(destinationFolderFullName, DLL_CORE);
CopyFileIfNewerVersion(sourceFileFullNameCore, destinationFileFullNameCore);
}
}
private void CopyFileIfNewerVersion(string sourceFileFullName, string destinationFileFullName)
{
FileVersionInfo destinationFileVersionInfo;
FileVersionInfo sourceFileVersionInfo;
bool copy = false;
if (File.Exists(destinationFileFullName))
{
sourceFileVersionInfo = FileVersionInfo.GetVersionInfo(sourceFileFullName);
destinationFileVersionInfo = FileVersionInfo.GetVersionInfo(destinationFileFullName);
if (sourceFileVersionInfo.FileMajorPart > destinationFileVersionInfo.FileMajorPart)
{
copy = true;
}
else if (sourceFileVersionInfo.FileMajorPart == destinationFileVersionInfo.FileMajorPart
&& sourceFileVersionInfo.FileMinorPart > destinationFileVersionInfo.FileMinorPart)
{
copy = true;
}
}
else
{
copy = true;
}
if (copy)
{
File.Copy(sourceFileFullName, destinationFileFullName, true);
}
}
#endregion
}
|
[
"[",
"PackageRegistration",
"(",
"UseManagedResourcesOnly",
"=",
"true",
",",
"AllowsBackgroundLoading",
"=",
"true",
")",
"]",
"[",
"InstalledProductRegistration",
"(",
"\"",
"#110",
"\"",
",",
"\"",
"#112",
"\"",
",",
"\"",
"1.0",
"\"",
",",
"IconResourceID",
"=",
"400",
")",
"]",
"[",
"ProvideMenuResource",
"(",
"\"",
"Menus.ctmenu",
"\"",
",",
"1",
")",
"]",
"[",
"Guid",
"(",
"GetObjectCodePackage",
".",
"PackageGuidString",
")",
"]",
"[",
"ProvideAutoLoad",
"(",
"VSConstants",
".",
"UICONTEXT",
".",
"NoSolution_string",
",",
"PackageAutoLoadFlags",
".",
"BackgroundLoad",
")",
"]",
"[",
"SuppressMessage",
"(",
"\"",
"StyleCop.CSharp.DocumentationRules",
"\"",
",",
"\"",
"SA1650:ElementDocumentationMustBeSpelledCorrectly",
"\"",
",",
"Justification",
"=",
"\"",
"pkgdef, VS and vsixmanifest are valid VS terms",
"\"",
")",
"]",
"public",
"sealed",
"class",
"GetObjectCodePackage",
":",
"AsyncPackage",
"{",
"public",
"const",
"string",
"PackageGuidString",
"=",
"\"",
"77dd3d7f-6bc4-46cd-a437-5f17d94a3eb7",
"\"",
";",
"public",
"GetObjectCodePackage",
"(",
")",
"{",
"}",
"region",
" Package Members",
"const",
"string",
"DLL_VISUALIZER",
"=",
"\"",
"ObjectCodeExporter.Visualizer.dll",
"\"",
";",
"const",
"string",
"DLL_CORE",
"=",
"\"",
"ObjectCodeExporter.dll",
"\"",
";",
"protected",
"override",
"async",
"Task",
"InitializeAsync",
"(",
"CancellationToken",
"cancellationToken",
",",
"IProgress",
"<",
"ServiceProgressData",
">",
"progress",
")",
"{",
"await",
"this",
".",
"JoinableTaskFactory",
".",
"SwitchToMainThreadAsync",
"(",
"cancellationToken",
")",
";",
"await",
"GetObjectCode",
".",
"InitializeAsync",
"(",
"this",
")",
";",
"string",
"sourceFolderFullName",
"=",
"Path",
".",
"GetDirectoryName",
"(",
"System",
".",
"Reflection",
".",
"Assembly",
".",
"GetExecutingAssembly",
"(",
")",
".",
"Location",
")",
";",
"if",
"(",
"await",
"GetServiceAsync",
"(",
"typeof",
"(",
"SVsShell",
")",
")",
"is",
"IVsShell",
"shell",
")",
"{",
"shell",
".",
"GetProperty",
"(",
"(",
"int",
")",
"__VSSPROPID2",
".",
"VSSPROPID_VisualStudioDir",
",",
"out",
"object",
"path",
")",
";",
"string",
"destinationFolderFullName",
"=",
"Path",
".",
"Combine",
"(",
"(",
"string",
")",
"path",
",",
"\"",
"Visualizers",
"\"",
")",
";",
"string",
"sourceFileFullName",
"=",
"Path",
".",
"Combine",
"(",
"sourceFolderFullName",
",",
"DLL_VISUALIZER",
")",
";",
"string",
"destinationFileFullName",
"=",
"Path",
".",
"Combine",
"(",
"destinationFolderFullName",
",",
"DLL_VISUALIZER",
")",
";",
"CopyFileIfNewerVersion",
"(",
"sourceFileFullName",
",",
"destinationFileFullName",
")",
";",
"string",
"sourceFileFullNameCore",
"=",
"Path",
".",
"Combine",
"(",
"sourceFolderFullName",
",",
"DLL_CORE",
")",
";",
"string",
"destinationFileFullNameCore",
"=",
"Path",
".",
"Combine",
"(",
"destinationFolderFullName",
",",
"DLL_CORE",
")",
";",
"CopyFileIfNewerVersion",
"(",
"sourceFileFullNameCore",
",",
"destinationFileFullNameCore",
")",
";",
"}",
"}",
"private",
"void",
"CopyFileIfNewerVersion",
"(",
"string",
"sourceFileFullName",
",",
"string",
"destinationFileFullName",
")",
"{",
"FileVersionInfo",
"destinationFileVersionInfo",
";",
"FileVersionInfo",
"sourceFileVersionInfo",
";",
"bool",
"copy",
"=",
"false",
";",
"if",
"(",
"File",
".",
"Exists",
"(",
"destinationFileFullName",
")",
")",
"{",
"sourceFileVersionInfo",
"=",
"FileVersionInfo",
".",
"GetVersionInfo",
"(",
"sourceFileFullName",
")",
";",
"destinationFileVersionInfo",
"=",
"FileVersionInfo",
".",
"GetVersionInfo",
"(",
"destinationFileFullName",
")",
";",
"if",
"(",
"sourceFileVersionInfo",
".",
"FileMajorPart",
">",
"destinationFileVersionInfo",
".",
"FileMajorPart",
")",
"{",
"copy",
"=",
"true",
";",
"}",
"else",
"if",
"(",
"sourceFileVersionInfo",
".",
"FileMajorPart",
"==",
"destinationFileVersionInfo",
".",
"FileMajorPart",
"&&",
"sourceFileVersionInfo",
".",
"FileMinorPart",
">",
"destinationFileVersionInfo",
".",
"FileMinorPart",
")",
"{",
"copy",
"=",
"true",
";",
"}",
"}",
"else",
"{",
"copy",
"=",
"true",
";",
"}",
"if",
"(",
"copy",
")",
"{",
"File",
".",
"Copy",
"(",
"sourceFileFullName",
",",
"destinationFileFullName",
",",
"true",
")",
";",
"}",
"}",
"endregion",
"}"
] |
This is the class that implements the package exposed by this assembly.
|
[
"This",
"is",
"the",
"class",
"that",
"implements",
"the",
"package",
"exposed",
"by",
"this",
"assembly",
"."
] |
[
"// Info on this package for Help/About",
"/// <summary>",
"/// GetObjectCodePackage GUID string.",
"/// </summary>",
"/// <summary>",
"/// Initializes a new instance of the <see cref=\"GetObjectCodePackage\"/> class.",
"/// </summary>",
"// Inside this method you can place any initialization code that does not require",
"// any Visual Studio service because at this point the package object is created but",
"// not sited yet inside Visual Studio environment. The place to do all the other",
"// initialization is the Initialize method.",
"/// <summary>",
"/// Initialization of the package; this method is called right after the package is sited, so this is the place",
"/// where you can put all the initialization code that rely on services provided by VisualStudio.",
"/// </summary>",
"/// <param name=\"cancellationToken\">A cancellation token to monitor for initialization cancellation, which can occur when VS is shutting down.</param>",
"/// <param name=\"progress\">A provider for progress updates.</param>",
"/// <returns>A task representing the async work of package initialization, or an already completed task if there is none. Do not return null from this method.</returns>",
"// When initialized asynchronously, the current thread may be a background thread at this point.",
"// Do any initialization that requires the UI thread after switching to the UI thread.",
"/// <summary>",
"/// Credit : https://github.com/visualstudioextensibility/VSX-Samples/tree/master/VSIXDebuggerVisualizer",
"/// </summary>",
"/// <param name=\"sourceFileFullName\">source file</param>",
"/// <param name=\"destinationFileFullName\">dest file</param>",
"// First time"
] |
[
{
"param": "AsyncPackage",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "AsyncPackage",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "The minimum requirement for a class to be considered a valid package for Visual Studio\nis to implement the IVsPackage interface and register itself with the shell.\nThis package uses the helper classes defined inside the Managed Package Framework (MPF)\nto do it: it derives from the Package class that provides the implementation of the\nIVsPackage interface and uses the registration attributes defined in the framework to\nregister itself and its components with the shell. These attributes tell the pkgdef creation\nutility what data to put into .pkgdef file.\n\nTo get loaded into VS, the package must be referred by in .vsixmanifest file.",
"docstring_tokens": [
"The",
"minimum",
"requirement",
"for",
"a",
"class",
"to",
"be",
"considered",
"a",
"valid",
"package",
"for",
"Visual",
"Studio",
"is",
"to",
"implement",
"the",
"IVsPackage",
"interface",
"and",
"register",
"itself",
"with",
"the",
"shell",
".",
"This",
"package",
"uses",
"the",
"helper",
"classes",
"defined",
"inside",
"the",
"Managed",
"Package",
"Framework",
"(",
"MPF",
")",
"to",
"do",
"it",
":",
"it",
"derives",
"from",
"the",
"Package",
"class",
"that",
"provides",
"the",
"implementation",
"of",
"the",
"IVsPackage",
"interface",
"and",
"uses",
"the",
"registration",
"attributes",
"defined",
"in",
"the",
"framework",
"to",
"register",
"itself",
"and",
"its",
"components",
"with",
"the",
"shell",
".",
"These",
"attributes",
"tell",
"the",
"pkgdef",
"creation",
"utility",
"what",
"data",
"to",
"put",
"into",
".",
"pkgdef",
"file",
".",
"To",
"get",
"loaded",
"into",
"VS",
"the",
"package",
"must",
"be",
"referred",
"by",
"in",
".",
"vsixmanifest",
"file",
"."
]
}
]
}
| false
| 16
| 661
| 196
|
310549f69c9270fc43679e0c7a28721b8dea2ac2
|
nakolas69/PowerShellGet
|
src/code/GetPSResourceRepository.cs
|
[
"MIT"
] |
C#
|
GetPSResourceRepository
|
/// <summary>
/// The Get-PSResourceRepository cmdlet replaces the Get-PSRepository cmdlet from V2.
/// It searches for the PowerShell module repositories that are registered for the current user.
/// By default it will return all registered repositories, or if the -Name parameter argument is specified then it wil return the repository with that name.
/// It returns PSRepositoryInfo objects which describe each resource item found.
/// </summary>
|
The Get-PSResourceRepository cmdlet replaces the Get-PSRepository cmdlet from V2.
It searches for the PowerShell module repositories that are registered for the current user.
By default it will return all registered repositories, or if the -Name parameter argument is specified then it wil return the repository with that name.
It returns PSRepositoryInfo objects which describe each resource item found.
|
[
"The",
"Get",
"-",
"PSResourceRepository",
"cmdlet",
"replaces",
"the",
"Get",
"-",
"PSRepository",
"cmdlet",
"from",
"V2",
".",
"It",
"searches",
"for",
"the",
"PowerShell",
"module",
"repositories",
"that",
"are",
"registered",
"for",
"the",
"current",
"user",
".",
"By",
"default",
"it",
"will",
"return",
"all",
"registered",
"repositories",
"or",
"if",
"the",
"-",
"Name",
"parameter",
"argument",
"is",
"specified",
"then",
"it",
"wil",
"return",
"the",
"repository",
"with",
"that",
"name",
".",
"It",
"returns",
"PSRepositoryInfo",
"objects",
"which",
"describe",
"each",
"resource",
"item",
"found",
"."
] |
[Cmdlet(VerbsCommon.Get,
"PSResourceRepository",
HelpUri = "<add>")]
public sealed
class GetPSResourceRepository : PSCmdlet
{
#region Parameters
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ArgumentCompleter(typeof(RepositoryNameCompleter))]
[ValidateNotNullOrEmpty]
public string[] Name { get; set; } = Utils.EmptyStrArray;
#endregion
#region Methods
protected override void BeginProcessing()
{
RepositorySettings.CheckRepositoryStore();
}
protected override void ProcessRecord()
{
string nameArrayAsString = (Name == null || !Name.Any() || string.Equals(Name[0], "*") || Name[0] == null) ? "all" : string.Join(", ", Name);
WriteVerbose(String.Format("reading repository: {0}. Calling Read() API now", nameArrayAsString));
List<PSRepositoryInfo> items = RepositorySettings.Read(Name, out string[] errorList);
foreach (string error in errorList)
{
WriteError(new ErrorRecord(
new PSInvalidOperationException(error),
"ErrorGettingSpecifiedRepo",
ErrorCategory.InvalidOperation,
this));
}
foreach (PSRepositoryInfo repo in items)
{
WriteObject(repo);
}
}
#endregion
}
|
[
"[",
"Cmdlet",
"(",
"VerbsCommon",
".",
"Get",
",",
"\"",
"PSResourceRepository",
"\"",
",",
"HelpUri",
"=",
"\"",
"<add>",
"\"",
")",
"]",
"public",
"sealed",
"class",
"GetPSResourceRepository",
":",
"PSCmdlet",
"{",
"region",
" Parameters",
"[",
"Parameter",
"(",
"Position",
"=",
"0",
",",
"ValueFromPipeline",
"=",
"true",
",",
"ValueFromPipelineByPropertyName",
"=",
"true",
")",
"]",
"[",
"ArgumentCompleter",
"(",
"typeof",
"(",
"RepositoryNameCompleter",
")",
")",
"]",
"[",
"ValidateNotNullOrEmpty",
"]",
"public",
"string",
"[",
"]",
"Name",
"{",
"get",
";",
"set",
";",
"}",
"=",
"Utils",
".",
"EmptyStrArray",
";",
"endregion",
"region",
" Methods",
"protected",
"override",
"void",
"BeginProcessing",
"(",
")",
"{",
"RepositorySettings",
".",
"CheckRepositoryStore",
"(",
")",
";",
"}",
"protected",
"override",
"void",
"ProcessRecord",
"(",
")",
"{",
"string",
"nameArrayAsString",
"=",
"(",
"Name",
"==",
"null",
"||",
"!",
"Name",
".",
"Any",
"(",
")",
"||",
"string",
".",
"Equals",
"(",
"Name",
"[",
"0",
"]",
",",
"\"",
"*",
"\"",
")",
"||",
"Name",
"[",
"0",
"]",
"==",
"null",
")",
"?",
"\"",
"all",
"\"",
":",
"string",
".",
"Join",
"(",
"\"",
", ",
"\"",
",",
"Name",
")",
";",
"WriteVerbose",
"(",
"String",
".",
"Format",
"(",
"\"",
"reading repository: {0}. Calling Read() API now",
"\"",
",",
"nameArrayAsString",
")",
")",
";",
"List",
"<",
"PSRepositoryInfo",
">",
"items",
"=",
"RepositorySettings",
".",
"Read",
"(",
"Name",
",",
"out",
"string",
"[",
"]",
"errorList",
")",
";",
"foreach",
"(",
"string",
"error",
"in",
"errorList",
")",
"{",
"WriteError",
"(",
"new",
"ErrorRecord",
"(",
"new",
"PSInvalidOperationException",
"(",
"error",
")",
",",
"\"",
"ErrorGettingSpecifiedRepo",
"\"",
",",
"ErrorCategory",
".",
"InvalidOperation",
",",
"this",
")",
")",
";",
"}",
"foreach",
"(",
"PSRepositoryInfo",
"repo",
"in",
"items",
")",
"{",
"WriteObject",
"(",
"repo",
")",
";",
"}",
"}",
"endregion",
"}"
] |
The Get-PSResourceRepository cmdlet replaces the Get-PSRepository cmdlet from V2.
|
[
"The",
"Get",
"-",
"PSResourceRepository",
"cmdlet",
"replaces",
"the",
"Get",
"-",
"PSRepository",
"cmdlet",
"from",
"V2",
"."
] |
[
"/// <summary>",
"/// Specifies the name(s) of a registered repository to find.",
"/// Supports wild card characters.",
"/// </summary>",
"// handle non-terminating errors"
] |
[
{
"param": "PSCmdlet",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PSCmdlet",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 295
| 88
|
fce0f11c3e5b67039865aae92b40df09462b231d
|
azraelrabbit/chromiumfx-orign-az
|
ChromiumFX/Generated/CfxClient.cs
|
[
"BSD-3-Clause"
] |
C#
|
CfxOnProcessMessageReceivedEventArgs
|
/// <summary>
/// Called when a new message is received from a different process. Return true
/// (1) if the message was handled or false (0) otherwise. Do not keep a
/// reference to or attempt to access the message outside of this callback.
/// </summary>
/// <remarks>
/// See also the original CEF documentation in
/// <see href="https://bitbucket.org/chromiumfx/chromiumfx/src/tip/cef/include/capi/cef_client_capi.h">cef/include/capi/cef_client_capi.h</see>.
/// </remarks>
|
Called when a new message is received from a different process. Return true
(1) if the message was handled or false (0) otherwise. Do not keep a
reference to or attempt to access the message outside of this callback.
|
[
"Called",
"when",
"a",
"new",
"message",
"is",
"received",
"from",
"a",
"different",
"process",
".",
"Return",
"true",
"(",
"1",
")",
"if",
"the",
"message",
"was",
"handled",
"or",
"false",
"(",
"0",
")",
"otherwise",
".",
"Do",
"not",
"keep",
"a",
"reference",
"to",
"or",
"attempt",
"to",
"access",
"the",
"message",
"outside",
"of",
"this",
"callback",
"."
] |
public class CfxOnProcessMessageReceivedEventArgs : CfxEventArgs {
internal IntPtr m_browser;
internal CfxBrowser m_browser_wrapped;
internal int m_source_process;
internal IntPtr m_message;
internal CfxProcessMessage m_message_wrapped;
internal bool m_returnValue;
private bool returnValueSet;
internal CfxOnProcessMessageReceivedEventArgs() {}
public CfxBrowser Browser {
get {
CheckAccess();
if(m_browser_wrapped == null) m_browser_wrapped = CfxBrowser.Wrap(m_browser);
return m_browser_wrapped;
}
}
public CfxProcessId SourceProcess {
get {
CheckAccess();
return (CfxProcessId)m_source_process;
}
}
public CfxProcessMessage Message {
get {
CheckAccess();
if(m_message_wrapped == null) m_message_wrapped = CfxProcessMessage.Wrap(m_message);
return m_message_wrapped;
}
}
public void SetReturnValue(bool returnValue) {
CheckAccess();
if(returnValueSet) {
throw new CfxException("The return value has already been set");
}
returnValueSet = true;
this.m_returnValue = returnValue;
}
public override string ToString() {
return String.Format("Browser={{{0}}}, SourceProcess={{{1}}}, Message={{{2}}}", Browser, SourceProcess, Message);
}
}
|
[
"public",
"class",
"CfxOnProcessMessageReceivedEventArgs",
":",
"CfxEventArgs",
"{",
"internal",
"IntPtr",
"m_browser",
";",
"internal",
"CfxBrowser",
"m_browser_wrapped",
";",
"internal",
"int",
"m_source_process",
";",
"internal",
"IntPtr",
"m_message",
";",
"internal",
"CfxProcessMessage",
"m_message_wrapped",
";",
"internal",
"bool",
"m_returnValue",
";",
"private",
"bool",
"returnValueSet",
";",
"internal",
"CfxOnProcessMessageReceivedEventArgs",
"(",
")",
"{",
"}",
"public",
"CfxBrowser",
"Browser",
"{",
"get",
"{",
"CheckAccess",
"(",
")",
";",
"if",
"(",
"m_browser_wrapped",
"==",
"null",
")",
"m_browser_wrapped",
"=",
"CfxBrowser",
".",
"Wrap",
"(",
"m_browser",
")",
";",
"return",
"m_browser_wrapped",
";",
"}",
"}",
"public",
"CfxProcessId",
"SourceProcess",
"{",
"get",
"{",
"CheckAccess",
"(",
")",
";",
"return",
"(",
"CfxProcessId",
")",
"m_source_process",
";",
"}",
"}",
"public",
"CfxProcessMessage",
"Message",
"{",
"get",
"{",
"CheckAccess",
"(",
")",
";",
"if",
"(",
"m_message_wrapped",
"==",
"null",
")",
"m_message_wrapped",
"=",
"CfxProcessMessage",
".",
"Wrap",
"(",
"m_message",
")",
";",
"return",
"m_message_wrapped",
";",
"}",
"}",
"public",
"void",
"SetReturnValue",
"(",
"bool",
"returnValue",
")",
"{",
"CheckAccess",
"(",
")",
";",
"if",
"(",
"returnValueSet",
")",
"{",
"throw",
"new",
"CfxException",
"(",
"\"",
"The return value has already been set",
"\"",
")",
";",
"}",
"returnValueSet",
"=",
"true",
";",
"this",
".",
"m_returnValue",
"=",
"returnValue",
";",
"}",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"return",
"String",
".",
"Format",
"(",
"\"",
"Browser={{{0}}}, SourceProcess={{{1}}}, Message={{{2}}}",
"\"",
",",
"Browser",
",",
"SourceProcess",
",",
"Message",
")",
";",
"}",
"}"
] |
Called when a new message is received from a different process.
|
[
"Called",
"when",
"a",
"new",
"message",
"is",
"received",
"from",
"a",
"different",
"process",
"."
] |
[
"/// <summary>",
"/// Get the Browser parameter for the <see cref=\"CfxClient.OnProcessMessageReceived\"/> callback.",
"/// </summary>",
"/// <summary>",
"/// Get the SourceProcess parameter for the <see cref=\"CfxClient.OnProcessMessageReceived\"/> callback.",
"/// </summary>",
"/// <summary>",
"/// Get the Message parameter for the <see cref=\"CfxClient.OnProcessMessageReceived\"/> callback.",
"/// </summary>",
"/// <summary>",
"/// Set the return value for the <see cref=\"CfxClient.OnProcessMessageReceived\"/> callback.",
"/// Calling SetReturnValue() more then once per callback or from different event handlers will cause an exception to be thrown.",
"/// </summary>"
] |
[
{
"param": "CfxEventArgs",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "CfxEventArgs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "remarks",
"docstring": "See also the original CEF documentation in\ncef/include/capi/cef_client_capi.h",
"docstring_tokens": [
"See",
"also",
"the",
"original",
"CEF",
"documentation",
"in",
"cef",
"/",
"include",
"/",
"capi",
"/",
"cef_client_capi",
".",
"h"
]
}
]
}
| false
| 13
| 298
| 121
|
0038a5ebc922db23499f04378a68062a9968ff03
|
vasac/coherence-dotnet-extend-client
|
src/Coherence.Core/Util/ServiceEventArgs.cs
|
[
"UPL-1.0",
"Apache-2.0"
] |
C#
|
ServiceEventArgs
|
/// <summary>
/// An event which indicates that a <see cref="IService"/> state has
/// changed:
/// <list type="bullet">
/// <item>a service is starting</item>
/// <item>a service has started</item>
/// <item>a service is stopping</item>
/// <item>a service has stopped</item>
/// </list>
/// </summary>
/// <author>Jason Howes 2007.11.12</author>
/// <author>Ana Cikic 2007.12.11</author>
/// <seealso cref="IService"/>
|
An event which indicates that a state has
changed:
a service is startinga service has starteda service is stoppinga service has stopped
|
[
"An",
"event",
"which",
"indicates",
"that",
"a",
"state",
"has",
"changed",
":",
"a",
"service",
"is",
"startinga",
"service",
"has",
"starteda",
"service",
"is",
"stoppinga",
"service",
"has",
"stopped"
] |
public class ServiceEventArgs : EventArgs
{
#region Properties
public virtual IService Service
{
get { return m_source; }
}
public virtual ServiceEventType EventType
{
get { return m_eventType; }
}
#endregion
#region Constructors
public ServiceEventArgs(IService service, ServiceEventType eventType)
{
m_source = service;
m_eventType = eventType;
}
#endregion
#region Object override methods
public override string ToString()
{
StringBuilder sb = new StringBuilder("ServiceEventArgs{");
sb.Append(DESCRIPTIONS[(int) EventType])
.Append(' ')
.Append(Service.GetType().Name)
.Append('}');
return sb.ToString();
}
#endregion
#region Data Members
private IService m_source;
private ServiceEventType m_eventType;
private static readonly string[] DESCRIPTIONS = {"<unknown>", "STARTING", "STARTED", "STOPPING", "STOPPED"};
#endregion
}
|
[
"public",
"class",
"ServiceEventArgs",
":",
"EventArgs",
"{",
"region",
" Properties",
"public",
"virtual",
"IService",
"Service",
"{",
"get",
"{",
"return",
"m_source",
";",
"}",
"}",
"public",
"virtual",
"ServiceEventType",
"EventType",
"{",
"get",
"{",
"return",
"m_eventType",
";",
"}",
"}",
"endregion",
"region",
" Constructors",
"public",
"ServiceEventArgs",
"(",
"IService",
"service",
",",
"ServiceEventType",
"eventType",
")",
"{",
"m_source",
"=",
"service",
";",
"m_eventType",
"=",
"eventType",
";",
"}",
"endregion",
"region",
" Object override methods",
"public",
"override",
"string",
"ToString",
"(",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
"\"",
"ServiceEventArgs{",
"\"",
")",
";",
"sb",
".",
"Append",
"(",
"DESCRIPTIONS",
"[",
"(",
"int",
")",
"EventType",
"]",
")",
".",
"Append",
"(",
"'",
" ",
"'",
")",
".",
"Append",
"(",
"Service",
".",
"GetType",
"(",
")",
".",
"Name",
")",
".",
"Append",
"(",
"'",
"}",
"'",
")",
";",
"return",
"sb",
".",
"ToString",
"(",
")",
";",
"}",
"endregion",
"region",
" Data Members",
"private",
"IService",
"m_source",
";",
"private",
"ServiceEventType",
"m_eventType",
";",
"private",
"static",
"readonly",
"string",
"[",
"]",
"DESCRIPTIONS",
"=",
"{",
"\"",
"<unknown>",
"\"",
",",
"\"",
"STARTING",
"\"",
",",
"\"",
"STARTED",
"\"",
",",
"\"",
"STOPPING",
"\"",
",",
"\"",
"STOPPED",
"\"",
"}",
";",
"endregion",
"}"
] |
An event which indicates that a state has
changed:
a service is startinga service has starteda service is stoppinga service has stopped
|
[
"An",
"event",
"which",
"indicates",
"that",
"a",
"state",
"has",
"changed",
":",
"a",
"service",
"is",
"startinga",
"service",
"has",
"starteda",
"service",
"is",
"stoppinga",
"service",
"has",
"stopped"
] |
[
"/// <summary>",
"/// Return the <see cref=\"IService\"/> that fired the event.",
"/// </summary>",
"/// <value>",
"/// A service that fired the event.",
"/// </value>",
"/// <summary>",
"/// Return this event's type.",
"/// </summary>",
"/// <remarks>",
"/// The event type is one of the <see cref=\"ServiceEventType\"/>",
"/// enumerated constants.",
"/// </remarks>",
"/// <value>",
"/// An event type.",
"/// </value>",
"/// <summary>",
"/// Constructs a new ServiceEventArgs.",
"/// </summary>",
"/// <param name=\"service\">",
"/// The <see cref=\"IService\"/> that fired the event.",
"/// </param>",
"/// <param name=\"eventType\">",
"/// This event's type, one of the <see cref=\"ServiceEventType\"/> enum",
"/// values.",
"/// </param>",
"/// <summary>",
"/// Returns a string representation of this ServiceEventArgs object.",
"/// </summary>",
"/// <returns>",
"/// A string representation of this ServiceEventArgs object.",
"/// </returns>",
"/// <summary>",
"/// IService object that fired the event.",
"/// </summary>",
"/// <summary>",
"/// This event's type.",
"/// </summary>",
"/// <summary>",
"/// Descriptions of the various event types.",
"/// </summary>"
] |
[
{
"param": "EventArgs",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "EventArgs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": [
{
"identifier": "author",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "author",
"docstring": null,
"docstring_tokens": [
"None"
]
},
{
"identifier": "seealso",
"docstring": null,
"docstring_tokens": [
"None"
]
}
]
}
| false
| 19
| 216
| 130
|
8835bb7bc023a58c5b9ce29662bb02321f7a4b69
|
kupl/starlab-benchmarks
|
Benchmarks_with_Functional_Bugs/Java/Bears-46/src/src/main/java/spoon/template/StatementTemplate.java
|
[
"MIT"
] |
Java
|
StatementTemplate
|
/**
* This class represents a template parameter that defines a statement list
* directly expressed in Java (no returns).
*
* <p>
* To define a new statement list template parameter, you must subclass this
* class and implement the {@link #statement()} method, which actually defines
* the Java statements. It corresponds to a
* {@link spoon.reflect.code.CtStatementList}.
*/
|
This class represents a template parameter that defines a statement list
directly expressed in Java (no returns).
To define a new statement list template parameter, you must subclass this
class and implement the #statement() method, which actually defines
the Java statements. It corresponds to a
spoon.reflect.code.CtStatementList.
|
[
"This",
"class",
"represents",
"a",
"template",
"parameter",
"that",
"defines",
"a",
"statement",
"list",
"directly",
"expressed",
"in",
"Java",
"(",
"no",
"returns",
")",
".",
"To",
"define",
"a",
"new",
"statement",
"list",
"template",
"parameter",
"you",
"must",
"subclass",
"this",
"class",
"and",
"implement",
"the",
"#statement",
"()",
"method",
"which",
"actually",
"defines",
"the",
"Java",
"statements",
".",
"It",
"corresponds",
"to",
"a",
"spoon",
".",
"reflect",
".",
"code",
".",
"CtStatementList",
"."
] |
public abstract class StatementTemplate extends AbstractTemplate<CtStatement> {
/**
* Creates a new statement list template parameter.
*/
public StatementTemplate() {
}
public CtStatement apply(CtType<?> targetType) {
CtClass<?> c = Substitution.getTemplateCtClass(targetType, this);
// we substitute the first statement of method statement
CtStatement result = c.getMethod("statement").getBody().getStatements().get(0).clone();
new SubstitutionVisitor(c.getFactory(), targetType, this).scan(result);
return result;
}
public Void S() {
return null;
}
/**
* This method must be implemented to define the template statement list.
*/
public abstract void statement() throws Throwable;
}
|
[
"public",
"abstract",
"class",
"StatementTemplate",
"extends",
"AbstractTemplate",
"<",
"CtStatement",
">",
"{",
"/**\n\t * Creates a new statement list template parameter.\n\t */",
"public",
"StatementTemplate",
"(",
")",
"{",
"}",
"public",
"CtStatement",
"apply",
"(",
"CtType",
"<",
"?",
">",
"targetType",
")",
"{",
"CtClass",
"<",
"?",
">",
"c",
"=",
"Substitution",
".",
"getTemplateCtClass",
"(",
"targetType",
",",
"this",
")",
";",
"CtStatement",
"result",
"=",
"c",
".",
"getMethod",
"(",
"\"",
"statement",
"\"",
")",
".",
"getBody",
"(",
")",
".",
"getStatements",
"(",
")",
".",
"get",
"(",
"0",
")",
".",
"clone",
"(",
")",
";",
"new",
"SubstitutionVisitor",
"(",
"c",
".",
"getFactory",
"(",
")",
",",
"targetType",
",",
"this",
")",
".",
"scan",
"(",
"result",
")",
";",
"return",
"result",
";",
"}",
"public",
"Void",
"S",
"(",
")",
"{",
"return",
"null",
";",
"}",
"/**\n\t * This method must be implemented to define the template statement list.\n\t */",
"public",
"abstract",
"void",
"statement",
"(",
")",
"throws",
"Throwable",
";",
"}"
] |
This class represents a template parameter that defines a statement list
directly expressed in Java (no returns).
|
[
"This",
"class",
"represents",
"a",
"template",
"parameter",
"that",
"defines",
"a",
"statement",
"list",
"directly",
"expressed",
"in",
"Java",
"(",
"no",
"returns",
")",
"."
] |
[
"// we substitute the first statement of method statement"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 14
| 158
| 80
|
67f49a38421603d5680f66302d305104a7f6377b
|
scorpio975/d-repr
|
pydrepr/drepr/models/parse_v1/resource_parser.py
|
[
"MIT"
] |
Python
|
ResourceParser
|
`resources` has two possible schemas
1. Shorthand when you have only one resource (`resource_id` is `default`): `resources: <resource_type>`
2. When you have multiple resources:
```
resources:
<resource_id>: <resource_conf>
# .. other resources ..
```
The `<resource_conf>` can either be:
a. `<resource_type>`, when other resource properties are all options
b. a dictionary as follows, when some properties require to define explicitly
```
<type>: <resource_type>
# .. other attributes ..
```
|
`resources` has two possible schemas
1.
The `` can either be:
a. ``, when other resource properties are all options
b.
|
[
"`",
"resources",
"`",
"has",
"two",
"possible",
"schemas",
"1",
".",
"The",
"`",
"`",
"can",
"either",
"be",
":",
"a",
".",
"`",
"`",
"when",
"other",
"resource",
"properties",
"are",
"all",
"options",
"b",
"."
] |
class ResourceParser:
"""
`resources` has two possible schemas
1. Shorthand when you have only one resource (`resource_id` is `default`): `resources: <resource_type>`
2. When you have multiple resources:
```
resources:
<resource_id>: <resource_conf>
# .. other resources ..
```
The `<resource_conf>` can either be:
a. `<resource_type>`, when other resource properties are all options
b. a dictionary as follows, when some properties require to define explicitly
```
<type>: <resource_type>
# .. other attributes ..
```
"""
DEFAULT_RESOURCE_ID = "default"
RESOURCE_TYPES = {rtype.value for rtype in ResourceType}
@classmethod
def parse(cls, resources: Union[str, dict]) -> List[Resource]:
if isinstance(resources, str):
return cls._parse_schema1(resources)
if isinstance(resources, dict):
return cls._parse_schema2(resources)
raise InputError(
f"Invalid type for `resources`, expect either a string or a dictionary. Get {type(resources)} instead")
@classmethod
def _parse_schema1(cls, resource_type: str) -> List[Resource]:
Validator.must_in(resource_type, cls.RESOURCE_TYPES, error_msg="Invalid resource type for `resources`")
resource_type = ResourceType(resource_type)
if resource_type == ResourceType.CSV:
resource_prop = CSVProp()
else:
resource_prop = None
return [Resource(cls.DEFAULT_RESOURCE_ID, resource_type, resource_prop)]
@classmethod
def _parse_schema2(cls, resources: dict) -> List[Resource]:
result = []
for resource_id, conf in resources.items():
trace = f"Parsing resource {resource_id}."
if isinstance(conf, str):
resource = cls._parse_schema1(conf)[0]
resource.id = resource_id
elif isinstance(conf, dict):
Validator.must_have(conf, "type", trace)
Validator.must_in(conf['type'], cls.RESOURCE_TYPES, f"{trace}\n\tParsing resource type")
resource_type = ResourceType(conf['type'])
if resource_type == ResourceType.CSV:
if 'delimiter' in conf:
if len(conf['delimiter']) != 1:
raise InputError(f"{trace}.\nERROR: Expect one character delimiter "
f"for CSV resource. Get `{conf['delimiter']}` instead")
resource_prop = CSVProp(conf['delimiter'])
else:
resource_prop = CSVProp()
else:
resource_prop = None
resource = Resource(resource_id, resource_type, resource_prop)
else:
raise InputError(f"{trace}.\nERROR: The configuration of a resource can either be string "
f"or dictionary. Get {type(conf)} instead")
result.append(resource)
return result
|
[
"class",
"ResourceParser",
":",
"DEFAULT_RESOURCE_ID",
"=",
"\"default\"",
"RESOURCE_TYPES",
"=",
"{",
"rtype",
".",
"value",
"for",
"rtype",
"in",
"ResourceType",
"}",
"@",
"classmethod",
"def",
"parse",
"(",
"cls",
",",
"resources",
":",
"Union",
"[",
"str",
",",
"dict",
"]",
")",
"->",
"List",
"[",
"Resource",
"]",
":",
"if",
"isinstance",
"(",
"resources",
",",
"str",
")",
":",
"return",
"cls",
".",
"_parse_schema1",
"(",
"resources",
")",
"if",
"isinstance",
"(",
"resources",
",",
"dict",
")",
":",
"return",
"cls",
".",
"_parse_schema2",
"(",
"resources",
")",
"raise",
"InputError",
"(",
"f\"Invalid type for `resources`, expect either a string or a dictionary. Get {type(resources)} instead\"",
")",
"@",
"classmethod",
"def",
"_parse_schema1",
"(",
"cls",
",",
"resource_type",
":",
"str",
")",
"->",
"List",
"[",
"Resource",
"]",
":",
"Validator",
".",
"must_in",
"(",
"resource_type",
",",
"cls",
".",
"RESOURCE_TYPES",
",",
"error_msg",
"=",
"\"Invalid resource type for `resources`\"",
")",
"resource_type",
"=",
"ResourceType",
"(",
"resource_type",
")",
"if",
"resource_type",
"==",
"ResourceType",
".",
"CSV",
":",
"resource_prop",
"=",
"CSVProp",
"(",
")",
"else",
":",
"resource_prop",
"=",
"None",
"return",
"[",
"Resource",
"(",
"cls",
".",
"DEFAULT_RESOURCE_ID",
",",
"resource_type",
",",
"resource_prop",
")",
"]",
"@",
"classmethod",
"def",
"_parse_schema2",
"(",
"cls",
",",
"resources",
":",
"dict",
")",
"->",
"List",
"[",
"Resource",
"]",
":",
"result",
"=",
"[",
"]",
"for",
"resource_id",
",",
"conf",
"in",
"resources",
".",
"items",
"(",
")",
":",
"trace",
"=",
"f\"Parsing resource {resource_id}.\"",
"if",
"isinstance",
"(",
"conf",
",",
"str",
")",
":",
"resource",
"=",
"cls",
".",
"_parse_schema1",
"(",
"conf",
")",
"[",
"0",
"]",
"resource",
".",
"id",
"=",
"resource_id",
"elif",
"isinstance",
"(",
"conf",
",",
"dict",
")",
":",
"Validator",
".",
"must_have",
"(",
"conf",
",",
"\"type\"",
",",
"trace",
")",
"Validator",
".",
"must_in",
"(",
"conf",
"[",
"'type'",
"]",
",",
"cls",
".",
"RESOURCE_TYPES",
",",
"f\"{trace}\\n\\tParsing resource type\"",
")",
"resource_type",
"=",
"ResourceType",
"(",
"conf",
"[",
"'type'",
"]",
")",
"if",
"resource_type",
"==",
"ResourceType",
".",
"CSV",
":",
"if",
"'delimiter'",
"in",
"conf",
":",
"if",
"len",
"(",
"conf",
"[",
"'delimiter'",
"]",
")",
"!=",
"1",
":",
"raise",
"InputError",
"(",
"f\"{trace}.\\nERROR: Expect one character delimiter \"",
"f\"for CSV resource. Get `{conf['delimiter']}` instead\"",
")",
"resource_prop",
"=",
"CSVProp",
"(",
"conf",
"[",
"'delimiter'",
"]",
")",
"else",
":",
"resource_prop",
"=",
"CSVProp",
"(",
")",
"else",
":",
"resource_prop",
"=",
"None",
"resource",
"=",
"Resource",
"(",
"resource_id",
",",
"resource_type",
",",
"resource_prop",
")",
"else",
":",
"raise",
"InputError",
"(",
"f\"{trace}.\\nERROR: The configuration of a resource can either be string \"",
"f\"or dictionary. Get {type(conf)} instead\"",
")",
"result",
".",
"append",
"(",
"resource",
")",
"return",
"result"
] |
`resources` has two possible schemas
1.
|
[
"`",
"resources",
"`",
"has",
"two",
"possible",
"schemas",
"1",
"."
] |
[
"\"\"\"\n `resources` has two possible schemas\n\n 1. Shorthand when you have only one resource (`resource_id` is `default`): `resources: <resource_type>`\n 2. When you have multiple resources:\n ```\n resources:\n <resource_id>: <resource_conf>\n # .. other resources ..\n ```\n\n The `<resource_conf>` can either be:\n a. `<resource_type>`, when other resource properties are all options\n b. a dictionary as follows, when some properties require to define explicitly\n ```\n <type>: <resource_type>\n # .. other attributes ..\n ```\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 25
| 606
| 132
|
5ab8c5e7fbf118522e1de821d2832bddea187f57
|
robinroos/ikasan
|
ikasaneip/component/endpoint/filetransfer/ftp/src/main/java/org/ikasan/connector/ftp/outbound/FTPManagedConnection.java
|
[
"BSD-3-Clause"
] |
Java
|
FTPManagedConnection
|
/**
* This EJB implements the ManagedConnection for the FTP resource adapter. This
* is a representation of a real, physical connection to the server, so it has
* an object instance variable which remains allocated to a server for the life
* of this object. This class is responsible for creating virtual connections,
* of class EISConnection, when the application server calls getConnection()
*
* It extends a (1 Phase Commit and 2 Phase commit) managed connection
*
* TODO Max retry attempts is really a client parameter, which brings us the
* question of whether we even want to open a connection at this stage
*
* @author Ikasan Development Team
*/
|
This EJB implements the ManagedConnection for the FTP resource adapter. This
is a representation of a real, physical connection to the server, so it has
an object instance variable which remains allocated to a server for the life
of this object. This class is responsible for creating virtual connections,
of class EISConnection, when the application server calls getConnection()
It extends a (1 Phase Commit and 2 Phase commit) managed connection
@author Ikasan Development Team
|
[
"This",
"EJB",
"implements",
"the",
"ManagedConnection",
"for",
"the",
"FTP",
"resource",
"adapter",
".",
"This",
"is",
"a",
"representation",
"of",
"a",
"real",
"physical",
"connection",
"to",
"the",
"server",
"so",
"it",
"has",
"an",
"object",
"instance",
"variable",
"which",
"remains",
"allocated",
"to",
"a",
"server",
"for",
"the",
"life",
"of",
"this",
"object",
".",
"This",
"class",
"is",
"responsible",
"for",
"creating",
"virtual",
"connections",
"of",
"class",
"EISConnection",
"when",
"the",
"application",
"server",
"calls",
"getConnection",
"()",
"It",
"extends",
"a",
"(",
"1",
"Phase",
"Commit",
"and",
"2",
"Phase",
"commit",
")",
"managed",
"connection",
"@author",
"Ikasan",
"Development",
"Team"
] |
public class FTPManagedConnection extends TransactionalCommandConnection implements Serializable
{
/** Generated GUID */
private static final long serialVersionUID = 8623781620439053263L;
/** The logger instance. */
public static Logger logger = LoggerFactory.getLogger(FTPManagedConnection.class);
/** Common library used by both inbound and outbound connectors */
private FileTransferProtocol ftpClient;
/**
* The client specific connection spec used to override the MFC values where
* necessary.
*/
private FTPConnectionRequestInfo fcri;
private String clientID;
/**
* Constructor, sets the managed connection factory and the hibernate filter
* table
*
* client ID sits on EISManagedConnection
*
* @param fcri connection request info
*/
public FTPManagedConnection(FTPConnectionRequestInfo fcri)
{
logger.debug("Called constructor."); //$NON-NLS-1$
this.fcri = fcri;
this.clientID = this.fcri.getClientID();
instanceCount++;
instanceOrdinal = instanceCount;
}
/**
* Create a virtual connection (a BaseFileTransferConnection object) and
* add it to the list of managed instances before returning it to the client.
*
* @param fileChunkDao
* @param baseFileTransferDao
* @return
*/
public Object getConnection( FileChunkDao fileChunkDao, BaseFileTransferDao baseFileTransferDao, int testtodo) {
return getConnection(fileChunkDao, baseFileTransferDao, null);
}
/**
* Create a virtual connection (a BaseFileTransferConnection object) and
* add it to the list of managed instances before returning it to the client.
*
* @param fileChunkDao
* @param baseFileTransferDao
* @param duplicatesFileCache
* @return
*/
public Object getConnection( FileChunkDao fileChunkDao, BaseFileTransferDao baseFileTransferDao,
Cache<String, Boolean> duplicatesFileCache)
{
logger.debug("Called getConnection()"); //$NON-NLS-1$
BaseFileTransferConnection connection = new FTPConnectionImpl(this, fileChunkDao, baseFileTransferDao,
duplicatesFileCache);
return connection;
}
public String getClientID()
{
return clientID;
}
// ////////////////////////////////////////
// Connection API Calls
// ////////////////////////////////////////
/**
* openSession initiates the physical connection to the server and logs us
* in. This method is called by FTPManagedConnectionFactory immediately
* after creating the instance of this class.
*
* In this implementation of an FTP connector there is no real concept of a
* session (a connection is made per method call), openSession is left here
* as it initialises the ftpClient and also provides a starting point for
* true session functionality to be added if required
*
* @throws ResourceException Exception thrown by Connector
*/
public void openSession() throws ResourceException
{
logger.debug("Called openSession."); //$NON-NLS-1$
createFTPClient();
this.ftpClient.echoConfig();
}
/*
* Helper Methods /
*/
/**
* Close the FileTransferProtocolClient session
*/
protected void closeSession()
{
if(this.ftpClient == null)
{
logger.debug("FTPClient is null. Closing Session aborted."); //$NON-NLS-1$
}
else
{
if(this.ftpClient.isConnected())
{
logger.debug("Closing FTP connection!"); //$NON-NLS-1$
this.ftpClient.disconnect();
logger.debug("Disconnected from FTP host."); //$NON-NLS-1$
}
else
{
logger.info("Client was already disconnected. Closing Session aborted."); //$NON-NLS-1$
}
}
}
/**
* Creates the FileTransferProtocolClient based off the properties from the
* ConnectionRequestInfo, and opens the connection
*
* @throws ResourceException Exception thrown by connector
*/
private void createFTPClient() throws ResourceException
{
logger.debug("Called createFTPClient \n"
+ "active [" + this.fcri.getActive() + "]\n"
+ "host [" + this.fcri.getRemoteHostname() + "]\n"
+ "maxretry [" + this.fcri.getMaxRetryAttempts() + "]\n"
+ "password [" + this.fcri.getPassword() + "]\n"
+ "port [" + this.fcri.getRemotePort() + "]\n"
+ "user [" + this.fcri.getUsername() + "]");
// Active
boolean active = this.fcri.getActive();
// Hostname
String remoteHostname = null;
if(this.fcri.getRemoteHostname() != null)
{
remoteHostname = this.fcri.getRemoteHostname();
}
else
{
throw new ResourceException("Remote hostname is null."); //$NON-NLS-1$
}
// Max retry attempts (Integer unboxes to int)
int maxRetryAttempts;
if(this.fcri.getMaxRetryAttempts() != null)
{
maxRetryAttempts = this.fcri.getMaxRetryAttempts();
}
else
{
throw new ResourceException("max retry attempts is null"); //$NON-NLS-1$
}
// Password
String password;
if(this.fcri.getPassword() != null)
{
password = this.fcri.getPassword();
}
else
{
throw new ResourceException("password is null"); //$NON-NLS-1$
}
// Port (Integer unboxes to int)
int remotePort;
if(this.fcri.getRemotePort() != null)
{
remotePort = this.fcri.getRemotePort();
}
else
{
throw new ResourceException("Remote port is null"); //$NON-NLS-1$
}
// Username
String username = null;
if(this.fcri.getUsername() != null)
{
username = this.fcri.getUsername();
}
else
{
throw new ResourceException("username is null"); //$NON-NLS-1$
}
String localHostname = "localhost";
String systemKey = this.fcri.getSystemKey();
Integer connectionTimeout = this.fcri.getConnectionTimeout();
Integer dataTimeout = this.fcri.getDataTimeout();
Integer soTimeout = this.fcri.getSocketTimeout();
// Create a FileTransferProtocolClient
if (fcri.getFTPS()) {
Boolean FTPS = true;
Integer ftpsPort = fcri.getFtpsPort();
String ftpsProtocol = fcri.getFtpsProtocol();
Boolean ftpsIsImplicit = fcri.getFtpsIsImplicit();
String ftpsKeyStoreFilePath = fcri.getFtpsKeyStoreFilePath();
String ftpsKeyStoreFilePassword = fcri.getFtpsKeyStoreFilePassword();
this.ftpClient = new FileTransferProtocolSSLClient(active, remoteHostname, localHostname, maxRetryAttempts, password, remotePort, username, systemKey,
connectionTimeout, dataTimeout, soTimeout,
FTPS, ftpsPort, ftpsProtocol, ftpsIsImplicit, ftpsKeyStoreFilePath, ftpsKeyStoreFilePassword);
} else {
this.ftpClient = new FileTransferProtocolClient(active, remoteHostname, localHostname, maxRetryAttempts, password, remotePort, username, systemKey,
connectionTimeout, dataTimeout, soTimeout);
}
try
{
this.ftpClient.validateConstructorArgs();
}
catch (ClientInitialisationException e)
{
throw new ResourceException(e);
}
// attempts to open the connection
try
{
ftpClient.connect();
}
catch (ClientConnectionException e)
{
throw new ResourceException("Failed to open connection when creating FTPManagedConnection", e); //$NON-NLS-1$
}
// attempts to login
try
{
ftpClient.login();
}
catch (ClientConnectionException e)
{
throw new ResourceException("Failed to login when creating FTPManagedConnection", e); //$NON-NLS-1$
}
}
// /////////////////////////////////////
// TXN API calls
// /////////////////////////////////////
/**
* Deal with forgetting this unit of work as a txn, in this case do nothing
*
* @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#forget(javax.transaction.xa.Xid)
*/
@Override
public void forget(Xid arg0)
{
logger.info("in forget"); //$NON-NLS-1$
}
/**
* Return the Transaction timeout, always set to 0
*
* @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getTransactionTimeout()
* @return 0
*/
@Override
public int getTransactionTimeout()
{
logger.debug("in getTransactionTimeout"); //$NON-NLS-1$
return 0;
}
/**
* Get the XA resource for this managed connection, in this case, itself.
*
* @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getXAResource()
*/
@Override
public XAResource getXAResource()
{
logger.debug("in getXAResource"); //$NON-NLS-1$
return this;
}
/**
* Return whether or not this resource manager is the same, always return
* false
*
* @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#isSameRM(javax.transaction.xa.XAResource)
* @return false
*/
@Override
public boolean isSameRM(XAResource arg0)
{
logger.debug("in isSameRM"); //$NON-NLS-1$
return false;
}
/**
* Set the txn timeout, always return false
*
* @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#setTransactionTimeout(int)
* @return false
*/
@Override
public boolean setTransactionTimeout(int arg0)
{
logger.debug("in setTransactionTimeout"); //$NON-NLS-1$
return false;
}
@Override
protected TransactionalResource getTransactionalResource()
{
return ftpClient;
}
/**
* Hook method to allow any connector specific post rollback functionality
*
* @param arg0 Transaction Id
*/
@Override
protected void postRollback(Xid arg0)
{
logger.info("in postRollback"); //$NON-NLS-1$
}
/**
* Hook method to allow any connector specific post commit functionality
*
* @param arg0 Transaction Id
*/
@Override
protected void postCommit(Xid arg0)
{
logger.info("in postCommit"); //$NON-NLS-1$
}
@Override
protected boolean cleanupJournalOnComplete()
{
return fcri.cleanupJournalOnComplete();
}
}
|
[
"public",
"class",
"FTPManagedConnection",
"extends",
"TransactionalCommandConnection",
"implements",
"Serializable",
"{",
"/** Generated GUID */",
"private",
"static",
"final",
"long",
"serialVersionUID",
"=",
"8623781620439053263L",
";",
"/** The logger instance. */",
"public",
"static",
"Logger",
"logger",
"=",
"LoggerFactory",
".",
"getLogger",
"(",
"FTPManagedConnection",
".",
"class",
")",
";",
"/** Common library used by both inbound and outbound connectors */",
"private",
"FileTransferProtocol",
"ftpClient",
";",
"/**\n * The client specific connection spec used to override the MFC values where \n * necessary.\n */",
"private",
"FTPConnectionRequestInfo",
"fcri",
";",
"private",
"String",
"clientID",
";",
"/**\n * Constructor, sets the managed connection factory and the hibernate filter\n * table\n * \n * client ID sits on EISManagedConnection\n * \n * @param fcri connection request info\n */",
"public",
"FTPManagedConnection",
"(",
"FTPConnectionRequestInfo",
"fcri",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Called constructor.",
"\"",
")",
";",
"this",
".",
"fcri",
"=",
"fcri",
";",
"this",
".",
"clientID",
"=",
"this",
".",
"fcri",
".",
"getClientID",
"(",
")",
";",
"instanceCount",
"++",
";",
"instanceOrdinal",
"=",
"instanceCount",
";",
"}",
"/**\n * Create a virtual connection (a BaseFileTransferConnection object) and\n * add it to the list of managed instances before returning it to the client.\n *\n * @param fileChunkDao\n * @param baseFileTransferDao\n * @return\n */",
"public",
"Object",
"getConnection",
"(",
"FileChunkDao",
"fileChunkDao",
",",
"BaseFileTransferDao",
"baseFileTransferDao",
",",
"int",
"testtodo",
")",
"{",
"return",
"getConnection",
"(",
"fileChunkDao",
",",
"baseFileTransferDao",
",",
"null",
")",
";",
"}",
"/**\n * Create a virtual connection (a BaseFileTransferConnection object) and\n * add it to the list of managed instances before returning it to the client.\n *\n * @param fileChunkDao\n * @param baseFileTransferDao\n * @param duplicatesFileCache\n * @return\n */",
"public",
"Object",
"getConnection",
"(",
"FileChunkDao",
"fileChunkDao",
",",
"BaseFileTransferDao",
"baseFileTransferDao",
",",
"Cache",
"<",
"String",
",",
"Boolean",
">",
"duplicatesFileCache",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Called getConnection()",
"\"",
")",
";",
"BaseFileTransferConnection",
"connection",
"=",
"new",
"FTPConnectionImpl",
"(",
"this",
",",
"fileChunkDao",
",",
"baseFileTransferDao",
",",
"duplicatesFileCache",
")",
";",
"return",
"connection",
";",
"}",
"public",
"String",
"getClientID",
"(",
")",
"{",
"return",
"clientID",
";",
"}",
"/**\n * openSession initiates the physical connection to the server and logs us\n * in. This method is called by FTPManagedConnectionFactory immediately\n * after creating the instance of this class.\n * \n * In this implementation of an FTP connector there is no real concept of a\n * session (a connection is made per method call), openSession is left here\n * as it initialises the ftpClient and also provides a starting point for\n * true session functionality to be added if required\n * \n * @throws ResourceException Exception thrown by Connector\n */",
"public",
"void",
"openSession",
"(",
")",
"throws",
"ResourceException",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Called openSession.",
"\"",
")",
";",
"createFTPClient",
"(",
")",
";",
"this",
".",
"ftpClient",
".",
"echoConfig",
"(",
")",
";",
"}",
"/*\n * Helper Methods /\n */",
"/**\n * Close the FileTransferProtocolClient session\n */",
"protected",
"void",
"closeSession",
"(",
")",
"{",
"if",
"(",
"this",
".",
"ftpClient",
"==",
"null",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"FTPClient is null. Closing Session aborted.",
"\"",
")",
";",
"}",
"else",
"{",
"if",
"(",
"this",
".",
"ftpClient",
".",
"isConnected",
"(",
")",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Closing FTP connection!",
"\"",
")",
";",
"this",
".",
"ftpClient",
".",
"disconnect",
"(",
")",
";",
"logger",
".",
"debug",
"(",
"\"",
"Disconnected from FTP host.",
"\"",
")",
";",
"}",
"else",
"{",
"logger",
".",
"info",
"(",
"\"",
"Client was already disconnected. Closing Session aborted.",
"\"",
")",
";",
"}",
"}",
"}",
"/**\n * Creates the FileTransferProtocolClient based off the properties from the\n * ConnectionRequestInfo, and opens the connection\n * \n * @throws ResourceException Exception thrown by connector\n */",
"private",
"void",
"createFTPClient",
"(",
")",
"throws",
"ResourceException",
"{",
"logger",
".",
"debug",
"(",
"\"",
"Called createFTPClient ",
"\\n",
"\"",
"+",
"\"",
"active [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getActive",
"(",
")",
"+",
"\"",
"]",
"\\n",
"\"",
"+",
"\"",
"host [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getRemoteHostname",
"(",
")",
"+",
"\"",
"]",
"\\n",
"\"",
"+",
"\"",
"maxretry [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getMaxRetryAttempts",
"(",
")",
"+",
"\"",
"]",
"\\n",
"\"",
"+",
"\"",
"password [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getPassword",
"(",
")",
"+",
"\"",
"]",
"\\n",
"\"",
"+",
"\"",
"port [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getRemotePort",
"(",
")",
"+",
"\"",
"]",
"\\n",
"\"",
"+",
"\"",
"user [",
"\"",
"+",
"this",
".",
"fcri",
".",
"getUsername",
"(",
")",
"+",
"\"",
"]",
"\"",
")",
";",
"boolean",
"active",
"=",
"this",
".",
"fcri",
".",
"getActive",
"(",
")",
";",
"String",
"remoteHostname",
"=",
"null",
";",
"if",
"(",
"this",
".",
"fcri",
".",
"getRemoteHostname",
"(",
")",
"!=",
"null",
")",
"{",
"remoteHostname",
"=",
"this",
".",
"fcri",
".",
"getRemoteHostname",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"Remote hostname is null.",
"\"",
")",
";",
"}",
"int",
"maxRetryAttempts",
";",
"if",
"(",
"this",
".",
"fcri",
".",
"getMaxRetryAttempts",
"(",
")",
"!=",
"null",
")",
"{",
"maxRetryAttempts",
"=",
"this",
".",
"fcri",
".",
"getMaxRetryAttempts",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"max retry attempts is null",
"\"",
")",
";",
"}",
"String",
"password",
";",
"if",
"(",
"this",
".",
"fcri",
".",
"getPassword",
"(",
")",
"!=",
"null",
")",
"{",
"password",
"=",
"this",
".",
"fcri",
".",
"getPassword",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"password is null",
"\"",
")",
";",
"}",
"int",
"remotePort",
";",
"if",
"(",
"this",
".",
"fcri",
".",
"getRemotePort",
"(",
")",
"!=",
"null",
")",
"{",
"remotePort",
"=",
"this",
".",
"fcri",
".",
"getRemotePort",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"Remote port is null",
"\"",
")",
";",
"}",
"String",
"username",
"=",
"null",
";",
"if",
"(",
"this",
".",
"fcri",
".",
"getUsername",
"(",
")",
"!=",
"null",
")",
"{",
"username",
"=",
"this",
".",
"fcri",
".",
"getUsername",
"(",
")",
";",
"}",
"else",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"username is null",
"\"",
")",
";",
"}",
"String",
"localHostname",
"=",
"\"",
"localhost",
"\"",
";",
"String",
"systemKey",
"=",
"this",
".",
"fcri",
".",
"getSystemKey",
"(",
")",
";",
"Integer",
"connectionTimeout",
"=",
"this",
".",
"fcri",
".",
"getConnectionTimeout",
"(",
")",
";",
"Integer",
"dataTimeout",
"=",
"this",
".",
"fcri",
".",
"getDataTimeout",
"(",
")",
";",
"Integer",
"soTimeout",
"=",
"this",
".",
"fcri",
".",
"getSocketTimeout",
"(",
")",
";",
"if",
"(",
"fcri",
".",
"getFTPS",
"(",
")",
")",
"{",
"Boolean",
"FTPS",
"=",
"true",
";",
"Integer",
"ftpsPort",
"=",
"fcri",
".",
"getFtpsPort",
"(",
")",
";",
"String",
"ftpsProtocol",
"=",
"fcri",
".",
"getFtpsProtocol",
"(",
")",
";",
"Boolean",
"ftpsIsImplicit",
"=",
"fcri",
".",
"getFtpsIsImplicit",
"(",
")",
";",
"String",
"ftpsKeyStoreFilePath",
"=",
"fcri",
".",
"getFtpsKeyStoreFilePath",
"(",
")",
";",
"String",
"ftpsKeyStoreFilePassword",
"=",
"fcri",
".",
"getFtpsKeyStoreFilePassword",
"(",
")",
";",
"this",
".",
"ftpClient",
"=",
"new",
"FileTransferProtocolSSLClient",
"(",
"active",
",",
"remoteHostname",
",",
"localHostname",
",",
"maxRetryAttempts",
",",
"password",
",",
"remotePort",
",",
"username",
",",
"systemKey",
",",
"connectionTimeout",
",",
"dataTimeout",
",",
"soTimeout",
",",
"FTPS",
",",
"ftpsPort",
",",
"ftpsProtocol",
",",
"ftpsIsImplicit",
",",
"ftpsKeyStoreFilePath",
",",
"ftpsKeyStoreFilePassword",
")",
";",
"}",
"else",
"{",
"this",
".",
"ftpClient",
"=",
"new",
"FileTransferProtocolClient",
"(",
"active",
",",
"remoteHostname",
",",
"localHostname",
",",
"maxRetryAttempts",
",",
"password",
",",
"remotePort",
",",
"username",
",",
"systemKey",
",",
"connectionTimeout",
",",
"dataTimeout",
",",
"soTimeout",
")",
";",
"}",
"try",
"{",
"this",
".",
"ftpClient",
".",
"validateConstructorArgs",
"(",
")",
";",
"}",
"catch",
"(",
"ClientInitialisationException",
"e",
")",
"{",
"throw",
"new",
"ResourceException",
"(",
"e",
")",
";",
"}",
"try",
"{",
"ftpClient",
".",
"connect",
"(",
")",
";",
"}",
"catch",
"(",
"ClientConnectionException",
"e",
")",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"Failed to open connection when creating FTPManagedConnection",
"\"",
",",
"e",
")",
";",
"}",
"try",
"{",
"ftpClient",
".",
"login",
"(",
")",
";",
"}",
"catch",
"(",
"ClientConnectionException",
"e",
")",
"{",
"throw",
"new",
"ResourceException",
"(",
"\"",
"Failed to login when creating FTPManagedConnection",
"\"",
",",
"e",
")",
";",
"}",
"}",
"/**\n * Deal with forgetting this unit of work as a txn, in this case do nothing\n * \n * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#forget(javax.transaction.xa.Xid)\n */",
"@",
"Override",
"public",
"void",
"forget",
"(",
"Xid",
"arg0",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"in forget",
"\"",
")",
";",
"}",
"/**\n * Return the Transaction timeout, always set to 0\n * \n * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getTransactionTimeout()\n * @return 0\n */",
"@",
"Override",
"public",
"int",
"getTransactionTimeout",
"(",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"in getTransactionTimeout",
"\"",
")",
";",
"return",
"0",
";",
"}",
"/**\n * Get the XA resource for this managed connection, in this case, itself.\n * \n * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#getXAResource()\n */",
"@",
"Override",
"public",
"XAResource",
"getXAResource",
"(",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"in getXAResource",
"\"",
")",
";",
"return",
"this",
";",
"}",
"/**\n * Return whether or not this resource manager is the same, always return\n * false\n * \n * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#isSameRM(javax.transaction.xa.XAResource)\n * @return false\n */",
"@",
"Override",
"public",
"boolean",
"isSameRM",
"(",
"XAResource",
"arg0",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"in isSameRM",
"\"",
")",
";",
"return",
"false",
";",
"}",
"/**\n * Set the txn timeout, always return false\n * \n * @see org.ikasan.connector.base.outbound.xa.EISXAManagedConnection#setTransactionTimeout(int)\n * @return false\n */",
"@",
"Override",
"public",
"boolean",
"setTransactionTimeout",
"(",
"int",
"arg0",
")",
"{",
"logger",
".",
"debug",
"(",
"\"",
"in setTransactionTimeout",
"\"",
")",
";",
"return",
"false",
";",
"}",
"@",
"Override",
"protected",
"TransactionalResource",
"getTransactionalResource",
"(",
")",
"{",
"return",
"ftpClient",
";",
"}",
"/**\n * Hook method to allow any connector specific post rollback functionality\n * \n * @param arg0 Transaction Id\n */",
"@",
"Override",
"protected",
"void",
"postRollback",
"(",
"Xid",
"arg0",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"in postRollback",
"\"",
")",
";",
"}",
"/**\n * Hook method to allow any connector specific post commit functionality\n * \n * @param arg0 Transaction Id\n */",
"@",
"Override",
"protected",
"void",
"postCommit",
"(",
"Xid",
"arg0",
")",
"{",
"logger",
".",
"info",
"(",
"\"",
"in postCommit",
"\"",
")",
";",
"}",
"@",
"Override",
"protected",
"boolean",
"cleanupJournalOnComplete",
"(",
")",
"{",
"return",
"fcri",
".",
"cleanupJournalOnComplete",
"(",
")",
";",
"}",
"}"
] |
This EJB implements the ManagedConnection for the FTP resource adapter.
|
[
"This",
"EJB",
"implements",
"the",
"ManagedConnection",
"for",
"the",
"FTP",
"resource",
"adapter",
"."
] |
[
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"// ////////////////////////////////////////",
"// Connection API Calls",
"// ////////////////////////////////////////",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"// Active",
"// Hostname",
"//$NON-NLS-1$",
"// Max retry attempts (Integer unboxes to int)",
"//$NON-NLS-1$",
"// Password",
"//$NON-NLS-1$",
"// Port (Integer unboxes to int)",
"//$NON-NLS-1$",
"// Username",
"//$NON-NLS-1$",
"// Create a FileTransferProtocolClient",
"// attempts to open the connection",
"//$NON-NLS-1$",
"// attempts to login",
"//$NON-NLS-1$",
"// /////////////////////////////////////",
"// TXN API calls",
"// /////////////////////////////////////",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$",
"//$NON-NLS-1$"
] |
[
{
"param": "TransactionalCommandConnection",
"type": null
},
{
"param": "Serializable",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "TransactionalCommandConnection",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "Serializable",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 27
| 2,404
| 141
|
31f9cccc35949dbabc10873d12f08c2f7a532da9
|
ArdaOzcan/JPEG-to-PDF
|
ui.py
|
[
"MIT"
] |
Python
|
Theme
|
A class for holding three colors
Three colors are: bg_color, mid_color and fg_color.
Mostly, only bg_color and fg_color is used but mid_color was also added
to create more depth with some widgets.
Methods:
@staticmethod
load_from_json(fp) -- load a json file, convert it to a Theme object and return it
|
A class for holding three colors
Three colors are: bg_color, mid_color and fg_color.
Mostly, only bg_color and fg_color is used but mid_color was also added
to create more depth with some widgets.
@staticmethod
load_from_json(fp) -- load a json file, convert it to a Theme object and return it
|
[
"A",
"class",
"for",
"holding",
"three",
"colors",
"Three",
"colors",
"are",
":",
"bg_color",
"mid_color",
"and",
"fg_color",
".",
"Mostly",
"only",
"bg_color",
"and",
"fg_color",
"is",
"used",
"but",
"mid_color",
"was",
"also",
"added",
"to",
"create",
"more",
"depth",
"with",
"some",
"widgets",
".",
"@staticmethod",
"load_from_json",
"(",
"fp",
")",
"--",
"load",
"a",
"json",
"file",
"convert",
"it",
"to",
"a",
"Theme",
"object",
"and",
"return",
"it"
] |
class Theme:
"""A class for holding three colors
Three colors are: bg_color, mid_color and fg_color.
Mostly, only bg_color and fg_color is used but mid_color was also added
to create more depth with some widgets.
Methods:
@staticmethod
load_from_json(fp) -- load a json file, convert it to a Theme object and return it
"""
def __init__(self, source_file, fg_color="#BBBBBB", mid_color="#252525", bg_color="#151515"):
"""Initiate method for Theme
Positional arguments:
source_file -- source file path of the theme
Keyword arguments:
fg_color -- foreground color
mid_color -- a color between bg_color and fg_color
bg_color -- background color
"""
self.fg_color = fg_color
self.mid_color = mid_color
self.bg_color = bg_color
self.source_file = source_file
@staticmethod
def load_from_json(fp):
"""Load a json file, convert it to a Theme object and return it
If no file named fp was found then source_file is set to None
and the program uses the hard coded colors.
"""
import json
t = Theme(fp)
try:
with open(fp, 'r') as file:
t_dict = json.load(file)
t.bg_color = t_dict['bg_color']
t.mid_color = t_dict['mid_color']
t.fg_color = t_dict['fg_color']
except FileNotFoundError:
t.fg_color = "#BBBBBB"
t.mid_color = "#252525"
t.bg_color = "#151515"
t.source_file = None
return t
|
[
"class",
"Theme",
":",
"def",
"__init__",
"(",
"self",
",",
"source_file",
",",
"fg_color",
"=",
"\"#BBBBBB\"",
",",
"mid_color",
"=",
"\"#252525\"",
",",
"bg_color",
"=",
"\"#151515\"",
")",
":",
"\"\"\"Initiate method for Theme\r\n\r\n Positional arguments:\r\n source_file -- source file path of the theme\r\n\r\n Keyword arguments:\r\n fg_color -- foreground color\r\n mid_color -- a color between bg_color and fg_color\r\n bg_color -- background color\r\n\r\n \"\"\"",
"self",
".",
"fg_color",
"=",
"fg_color",
"self",
".",
"mid_color",
"=",
"mid_color",
"self",
".",
"bg_color",
"=",
"bg_color",
"self",
".",
"source_file",
"=",
"source_file",
"@",
"staticmethod",
"def",
"load_from_json",
"(",
"fp",
")",
":",
"\"\"\"Load a json file, convert it to a Theme object and return it\r\n\r\n If no file named fp was found then source_file is set to None \r\n and the program uses the hard coded colors.\r\n \"\"\"",
"import",
"json",
"t",
"=",
"Theme",
"(",
"fp",
")",
"try",
":",
"with",
"open",
"(",
"fp",
",",
"'r'",
")",
"as",
"file",
":",
"t_dict",
"=",
"json",
".",
"load",
"(",
"file",
")",
"t",
".",
"bg_color",
"=",
"t_dict",
"[",
"'bg_color'",
"]",
"t",
".",
"mid_color",
"=",
"t_dict",
"[",
"'mid_color'",
"]",
"t",
".",
"fg_color",
"=",
"t_dict",
"[",
"'fg_color'",
"]",
"except",
"FileNotFoundError",
":",
"t",
".",
"fg_color",
"=",
"\"#BBBBBB\"",
"t",
".",
"mid_color",
"=",
"\"#252525\"",
"t",
".",
"bg_color",
"=",
"\"#151515\"",
"t",
".",
"source_file",
"=",
"None",
"return",
"t"
] |
A class for holding three colors
Three colors are: bg_color, mid_color and fg_color.
|
[
"A",
"class",
"for",
"holding",
"three",
"colors",
"Three",
"colors",
"are",
":",
"bg_color",
"mid_color",
"and",
"fg_color",
"."
] |
[
"\"\"\"A class for holding three colors\r\n\r\n Three colors are: bg_color, mid_color and fg_color.\r\n Mostly, only bg_color and fg_color is used but mid_color was also added\r\n to create more depth with some widgets.\r\n\r\n Methods:\r\n\r\n @staticmethod\r\n load_from_json(fp) -- load a json file, convert it to a Theme object and return it\r\n\r\n \"\"\"",
"\"\"\"Initiate method for Theme\r\n\r\n Positional arguments:\r\n source_file -- source file path of the theme\r\n\r\n Keyword arguments:\r\n fg_color -- foreground color\r\n mid_color -- a color between bg_color and fg_color\r\n bg_color -- background color\r\n\r\n \"\"\"",
"\"\"\"Load a json file, convert it to a Theme object and return it\r\n\r\n If no file named fp was found then source_file is set to None \r\n and the program uses the hard coded colors.\r\n \"\"\""
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 382
| 78
|
0e1826c5399d6a523f43849df10c4eeeaeaac8bc
|
ppatierno/rhte-2019
|
kstreams-enricher/src/main/java/io/strimzi/streams/serde/ChangeEventAwareJsonSerde.java
|
[
"Apache-2.0"
] |
Java
|
ChangeEventAwareJsonSerde
|
/**
* A {@link Serde} that (de-)serializes JSON. The {@link Deserializer} supports Debezium's CDC message format, i.e. for
* such messages the values to be deserialized will be unwrapped from the {@code id} field (for keys) or from the
* {@code after} field.
*
* @author Gunnar Morling
*
* @param <T> The object type
*/
|
A Serde that (de-)serializes JSON. The Deserializer supports Debezium's CDC message format, i.e. for
such messages the values to be deserialized will be unwrapped from the id field (for keys) or from the
after field.
@author Gunnar Morling
@param The object type
|
[
"A",
"Serde",
"that",
"(",
"de",
"-",
")",
"serializes",
"JSON",
".",
"The",
"Deserializer",
"supports",
"Debezium",
"'",
"s",
"CDC",
"message",
"format",
"i",
".",
"e",
".",
"for",
"such",
"messages",
"the",
"values",
"to",
"be",
"deserialized",
"will",
"be",
"unwrapped",
"from",
"the",
"id",
"field",
"(",
"for",
"keys",
")",
"or",
"from",
"the",
"after",
"field",
".",
"@author",
"Gunnar",
"Morling",
"@param",
"The",
"object",
"type"
] |
public class ChangeEventAwareJsonSerde<T> implements Serde<T> {
private final ObjectMapper mapper;
private final ObjectReader reader;
private boolean isKey;
public ChangeEventAwareJsonSerde(Class<T> objectType) {
mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
this.reader = mapper.readerFor(objectType);
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
this.isKey = isKey;
}
@Override
public void close() {
}
@Override
public Serializer<T> serializer() {
return new JsonSerializer();
}
@Override
public Deserializer<T> deserializer() {
return new JsonDeserializer();
}
private final class JsonDeserializer implements Deserializer<T> {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
}
@Override
public T deserialize(String topic, byte[] data) {
if (data == null) {
return null;
}
try {
JsonNode node = mapper.readTree(data);
if (isKey) {
if (node.isObject()) {
if (node.has("payload")) {
return reader.readValue(node.get("payload").get("id"));
}
else {
return reader.readValue(node.get("id"));
}
}
else {
return reader.readValue(node);
}
}
else {
JsonNode payload = node.get("payload");
if (payload != null) {
return reader.readValue(payload.get("after"));
}
else {
if (node.has("before") && node.has("after") && node.has("source")) {
return reader.readValue(node.get("after"));
}
else {
return reader.readValue(node);
}
}
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
}
}
private final class JsonSerializer implements Serializer<T> {
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
}
@Override
public byte[] serialize(String topic, T data) {
try {
return mapper.writeValueAsBytes(data);
}
catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
@Override
public void close() {
}
}
}
|
[
"public",
"class",
"ChangeEventAwareJsonSerde",
"<",
"T",
">",
"implements",
"Serde",
"<",
"T",
">",
"{",
"private",
"final",
"ObjectMapper",
"mapper",
";",
"private",
"final",
"ObjectReader",
"reader",
";",
"private",
"boolean",
"isKey",
";",
"public",
"ChangeEventAwareJsonSerde",
"(",
"Class",
"<",
"T",
">",
"objectType",
")",
"{",
"mapper",
"=",
"new",
"ObjectMapper",
"(",
")",
";",
"mapper",
".",
"registerModule",
"(",
"new",
"JavaTimeModule",
"(",
")",
")",
";",
"this",
".",
"reader",
"=",
"mapper",
".",
"readerFor",
"(",
"objectType",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"configure",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"configs",
",",
"boolean",
"isKey",
")",
"{",
"this",
".",
"isKey",
"=",
"isKey",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"}",
"@",
"Override",
"public",
"Serializer",
"<",
"T",
">",
"serializer",
"(",
")",
"{",
"return",
"new",
"JsonSerializer",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"Deserializer",
"<",
"T",
">",
"deserializer",
"(",
")",
"{",
"return",
"new",
"JsonDeserializer",
"(",
")",
";",
"}",
"private",
"final",
"class",
"JsonDeserializer",
"implements",
"Deserializer",
"<",
"T",
">",
"{",
"@",
"Override",
"public",
"void",
"configure",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"configs",
",",
"boolean",
"isKey",
")",
"{",
"}",
"@",
"Override",
"public",
"T",
"deserialize",
"(",
"String",
"topic",
",",
"byte",
"[",
"]",
"data",
")",
"{",
"if",
"(",
"data",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"try",
"{",
"JsonNode",
"node",
"=",
"mapper",
".",
"readTree",
"(",
"data",
")",
";",
"if",
"(",
"isKey",
")",
"{",
"if",
"(",
"node",
".",
"isObject",
"(",
")",
")",
"{",
"if",
"(",
"node",
".",
"has",
"(",
"\"",
"payload",
"\"",
")",
")",
"{",
"return",
"reader",
".",
"readValue",
"(",
"node",
".",
"get",
"(",
"\"",
"payload",
"\"",
")",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"}",
"else",
"{",
"return",
"reader",
".",
"readValue",
"(",
"node",
".",
"get",
"(",
"\"",
"id",
"\"",
")",
")",
";",
"}",
"}",
"else",
"{",
"return",
"reader",
".",
"readValue",
"(",
"node",
")",
";",
"}",
"}",
"else",
"{",
"JsonNode",
"payload",
"=",
"node",
".",
"get",
"(",
"\"",
"payload",
"\"",
")",
";",
"if",
"(",
"payload",
"!=",
"null",
")",
"{",
"return",
"reader",
".",
"readValue",
"(",
"payload",
".",
"get",
"(",
"\"",
"after",
"\"",
")",
")",
";",
"}",
"else",
"{",
"if",
"(",
"node",
".",
"has",
"(",
"\"",
"before",
"\"",
")",
"&&",
"node",
".",
"has",
"(",
"\"",
"after",
"\"",
")",
"&&",
"node",
".",
"has",
"(",
"\"",
"source",
"\"",
")",
")",
"{",
"return",
"reader",
".",
"readValue",
"(",
"node",
".",
"get",
"(",
"\"",
"after",
"\"",
")",
")",
";",
"}",
"else",
"{",
"return",
"reader",
".",
"readValue",
"(",
"node",
")",
";",
"}",
"}",
"}",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"}",
"}",
"private",
"final",
"class",
"JsonSerializer",
"implements",
"Serializer",
"<",
"T",
">",
"{",
"@",
"Override",
"public",
"void",
"configure",
"(",
"Map",
"<",
"String",
",",
"?",
">",
"configs",
",",
"boolean",
"isKey",
")",
"{",
"}",
"@",
"Override",
"public",
"byte",
"[",
"]",
"serialize",
"(",
"String",
"topic",
",",
"T",
"data",
")",
"{",
"try",
"{",
"return",
"mapper",
".",
"writeValueAsBytes",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"JsonProcessingException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"}",
"}",
"}"
] |
A {@link Serde} that (de-)serializes JSON.
|
[
"A",
"{",
"@link",
"Serde",
"}",
"that",
"(",
"de",
"-",
")",
"serializes",
"JSON",
"."
] |
[] |
[
{
"param": "Serde<T>",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "Serde<T>",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 22
| 511
| 92
|
229a044f1a0307e7d138ec0b3b0a427d54031461
|
om-sharma/java-driver
|
core/src/main/java/com/datastax/oss/driver/internal/core/protocol/SnappyCompressor.java
|
[
"Apache-2.0"
] |
Java
|
SnappyCompressor
|
/**
* @implNote The Snappy protocol already encodes the uncompressed length in the compressed payload,
* so {@link #compress(ByteBuf)} and {@link #compressWithoutLength(ByteBuf)} produce the same
* output for this compressor. The corresponding parameters {@code
* prependWithUncompressedLength} and {@code uncompressedLength} are ignored by their respective
* methods.
*/
|
@implNote The Snappy protocol already encodes the uncompressed length in the compressed payload,
so #compress(ByteBuf) and #compressWithoutLength(ByteBuf) produce the same
output for this compressor. The corresponding parameters {@code
prependWithUncompressedLength} and uncompressedLength are ignored by their respective
methods.
|
[
"@implNote",
"The",
"Snappy",
"protocol",
"already",
"encodes",
"the",
"uncompressed",
"length",
"in",
"the",
"compressed",
"payload",
"so",
"#compress",
"(",
"ByteBuf",
")",
"and",
"#compressWithoutLength",
"(",
"ByteBuf",
")",
"produce",
"the",
"same",
"output",
"for",
"this",
"compressor",
".",
"The",
"corresponding",
"parameters",
"{",
"@code",
"prependWithUncompressedLength",
"}",
"and",
"uncompressedLength",
"are",
"ignored",
"by",
"their",
"respective",
"methods",
"."
] |
@ThreadSafe
public class SnappyCompressor extends ByteBufCompressor {
public SnappyCompressor(@SuppressWarnings("unused") DriverContext context) {
if (!DefaultDependencyChecker.isPresent(Dependency.SNAPPY)) {
throw new IllegalStateException(
"Could not find the Snappy library on the classpath "
+ "(the driver declares it as an optional dependency, "
+ "so you need to declare it explicitly)");
}
}
@Override
public String algorithm() {
return "snappy";
}
@Override
protected ByteBuf compressDirect(
ByteBuf input, /*ignored*/ boolean prependWithUncompressedLength) {
int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
// If the input is direct we will allocate a direct output buffer as well as this will allow us
// to use Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
ByteBuf output = input.alloc().directBuffer(maxCompressedLength);
try {
ByteBuffer in = inputNioBuffer(input);
// Increase reader index.
input.readerIndex(input.writerIndex());
ByteBuffer out = outputNioBuffer(output);
int written = Snappy.compress(in, out);
// Set the writer index so the amount of written bytes is reflected
output.writerIndex(output.writerIndex() + written);
return output;
} catch (IOException e) {
// release output buffer so we not leak and rethrow exception.
output.release();
throw new RuntimeException(e);
}
}
@Override
protected ByteBuf compressHeap(ByteBuf input, /*ignored*/ boolean prependWithUncompressedLength) {
int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes());
int inOffset = input.arrayOffset() + input.readerIndex();
byte[] in = input.array();
int len = input.readableBytes();
// Increase reader index.
input.readerIndex(input.writerIndex());
// Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and
// so can eliminate the overhead of allocate a new byte[].
ByteBuf output = input.alloc().heapBuffer(maxCompressedLength);
try {
// Calculate the correct offset.
int offset = output.arrayOffset() + output.writerIndex();
byte[] out = output.array();
int written = Snappy.compress(in, inOffset, len, out, offset);
// Increase the writerIndex with the written bytes.
output.writerIndex(output.writerIndex() + written);
return output;
} catch (IOException e) {
// release output buffer so we not leak and rethrow exception.
output.release();
throw new RuntimeException(e);
}
}
@Override
protected int readUncompressedLength(ByteBuf compressed) {
// Since compress methods don't actually prepend with a length, we have nothing to read here.
// Return a bogus length (it will be ignored by the decompress methods, so the actual value
// doesn't matter).
return -1;
}
@Override
protected ByteBuf decompressDirect(ByteBuf input, /*ignored*/ int uncompressedLength) {
ByteBuffer in = inputNioBuffer(input);
// Increase reader index.
input.readerIndex(input.writerIndex());
ByteBuf output = null;
try {
if (!Snappy.isValidCompressedBuffer(in)) {
throw new IllegalArgumentException(
"Provided frame does not appear to be Snappy compressed");
}
// If the input is direct we will allocate a direct output buffer as well as this will allow
// us to use Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.
output = input.alloc().directBuffer(Snappy.uncompressedLength(in));
ByteBuffer out = outputNioBuffer(output);
int size = Snappy.uncompress(in, out);
// Set the writer index so the amount of written bytes is reflected
output.writerIndex(output.writerIndex() + size);
return output;
} catch (IOException e) {
// release output buffer so we not leak and rethrow exception.
if (output != null) {
output.release();
}
throw new RuntimeException(e);
}
}
@Override
protected ByteBuf decompressHeap(ByteBuf input, /*ignored*/ int uncompressedLength) {
// Not a direct buffer so use byte arrays...
int inOffset = input.arrayOffset() + input.readerIndex();
byte[] in = input.array();
int len = input.readableBytes();
// Increase reader index.
input.readerIndex(input.writerIndex());
ByteBuf output = null;
try {
if (!Snappy.isValidCompressedBuffer(in, inOffset, len)) {
throw new IllegalArgumentException(
"Provided frame does not appear to be Snappy compressed");
}
// Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and
// so can eliminate the overhead of allocate a new byte[].
output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len));
// Calculate the correct offset.
int offset = output.arrayOffset() + output.writerIndex();
byte[] out = output.array();
int written = Snappy.uncompress(in, inOffset, len, out, offset);
// Increase the writerIndex with the written bytes.
output.writerIndex(output.writerIndex() + written);
return output;
} catch (IOException e) {
// release output buffer so we not leak and rethrow exception.
if (output != null) {
output.release();
}
throw new RuntimeException(e);
}
}
}
|
[
"@",
"ThreadSafe",
"public",
"class",
"SnappyCompressor",
"extends",
"ByteBufCompressor",
"{",
"public",
"SnappyCompressor",
"(",
"@",
"SuppressWarnings",
"(",
"\"",
"unused",
"\"",
")",
"DriverContext",
"context",
")",
"{",
"if",
"(",
"!",
"DefaultDependencyChecker",
".",
"isPresent",
"(",
"Dependency",
".",
"SNAPPY",
")",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"",
"Could not find the Snappy library on the classpath ",
"\"",
"+",
"\"",
"(the driver declares it as an optional dependency, ",
"\"",
"+",
"\"",
"so you need to declare it explicitly)",
"\"",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"String",
"algorithm",
"(",
")",
"{",
"return",
"\"",
"snappy",
"\"",
";",
"}",
"@",
"Override",
"protected",
"ByteBuf",
"compressDirect",
"(",
"ByteBuf",
"input",
",",
"/*ignored*/",
"boolean",
"prependWithUncompressedLength",
")",
"{",
"int",
"maxCompressedLength",
"=",
"Snappy",
".",
"maxCompressedLength",
"(",
"input",
".",
"readableBytes",
"(",
")",
")",
";",
"ByteBuf",
"output",
"=",
"input",
".",
"alloc",
"(",
")",
".",
"directBuffer",
"(",
"maxCompressedLength",
")",
";",
"try",
"{",
"ByteBuffer",
"in",
"=",
"inputNioBuffer",
"(",
"input",
")",
";",
"input",
".",
"readerIndex",
"(",
"input",
".",
"writerIndex",
"(",
")",
")",
";",
"ByteBuffer",
"out",
"=",
"outputNioBuffer",
"(",
"output",
")",
";",
"int",
"written",
"=",
"Snappy",
".",
"compress",
"(",
"in",
",",
"out",
")",
";",
"output",
".",
"writerIndex",
"(",
"output",
".",
"writerIndex",
"(",
")",
"+",
"written",
")",
";",
"return",
"output",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"output",
".",
"release",
"(",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"ByteBuf",
"compressHeap",
"(",
"ByteBuf",
"input",
",",
"/*ignored*/",
"boolean",
"prependWithUncompressedLength",
")",
"{",
"int",
"maxCompressedLength",
"=",
"Snappy",
".",
"maxCompressedLength",
"(",
"input",
".",
"readableBytes",
"(",
")",
")",
";",
"int",
"inOffset",
"=",
"input",
".",
"arrayOffset",
"(",
")",
"+",
"input",
".",
"readerIndex",
"(",
")",
";",
"byte",
"[",
"]",
"in",
"=",
"input",
".",
"array",
"(",
")",
";",
"int",
"len",
"=",
"input",
".",
"readableBytes",
"(",
")",
";",
"input",
".",
"readerIndex",
"(",
"input",
".",
"writerIndex",
"(",
")",
")",
";",
"ByteBuf",
"output",
"=",
"input",
".",
"alloc",
"(",
")",
".",
"heapBuffer",
"(",
"maxCompressedLength",
")",
";",
"try",
"{",
"int",
"offset",
"=",
"output",
".",
"arrayOffset",
"(",
")",
"+",
"output",
".",
"writerIndex",
"(",
")",
";",
"byte",
"[",
"]",
"out",
"=",
"output",
".",
"array",
"(",
")",
";",
"int",
"written",
"=",
"Snappy",
".",
"compress",
"(",
"in",
",",
"inOffset",
",",
"len",
",",
"out",
",",
"offset",
")",
";",
"output",
".",
"writerIndex",
"(",
"output",
".",
"writerIndex",
"(",
")",
"+",
"written",
")",
";",
"return",
"output",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"output",
".",
"release",
"(",
")",
";",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"int",
"readUncompressedLength",
"(",
"ByteBuf",
"compressed",
")",
"{",
"return",
"-",
"1",
";",
"}",
"@",
"Override",
"protected",
"ByteBuf",
"decompressDirect",
"(",
"ByteBuf",
"input",
",",
"/*ignored*/",
"int",
"uncompressedLength",
")",
"{",
"ByteBuffer",
"in",
"=",
"inputNioBuffer",
"(",
"input",
")",
";",
"input",
".",
"readerIndex",
"(",
"input",
".",
"writerIndex",
"(",
")",
")",
";",
"ByteBuf",
"output",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"!",
"Snappy",
".",
"isValidCompressedBuffer",
"(",
"in",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Provided frame does not appear to be Snappy compressed",
"\"",
")",
";",
"}",
"output",
"=",
"input",
".",
"alloc",
"(",
")",
".",
"directBuffer",
"(",
"Snappy",
".",
"uncompressedLength",
"(",
"in",
")",
")",
";",
"ByteBuffer",
"out",
"=",
"outputNioBuffer",
"(",
"output",
")",
";",
"int",
"size",
"=",
"Snappy",
".",
"uncompress",
"(",
"in",
",",
"out",
")",
";",
"output",
".",
"writerIndex",
"(",
"output",
".",
"writerIndex",
"(",
")",
"+",
"size",
")",
";",
"return",
"output",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"output",
"!=",
"null",
")",
"{",
"output",
".",
"release",
"(",
")",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"@",
"Override",
"protected",
"ByteBuf",
"decompressHeap",
"(",
"ByteBuf",
"input",
",",
"/*ignored*/",
"int",
"uncompressedLength",
")",
"{",
"int",
"inOffset",
"=",
"input",
".",
"arrayOffset",
"(",
")",
"+",
"input",
".",
"readerIndex",
"(",
")",
";",
"byte",
"[",
"]",
"in",
"=",
"input",
".",
"array",
"(",
")",
";",
"int",
"len",
"=",
"input",
".",
"readableBytes",
"(",
")",
";",
"input",
".",
"readerIndex",
"(",
"input",
".",
"writerIndex",
"(",
")",
")",
";",
"ByteBuf",
"output",
"=",
"null",
";",
"try",
"{",
"if",
"(",
"!",
"Snappy",
".",
"isValidCompressedBuffer",
"(",
"in",
",",
"inOffset",
",",
"len",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"",
"Provided frame does not appear to be Snappy compressed",
"\"",
")",
";",
"}",
"output",
"=",
"input",
".",
"alloc",
"(",
")",
".",
"heapBuffer",
"(",
"Snappy",
".",
"uncompressedLength",
"(",
"in",
",",
"inOffset",
",",
"len",
")",
")",
";",
"int",
"offset",
"=",
"output",
".",
"arrayOffset",
"(",
")",
"+",
"output",
".",
"writerIndex",
"(",
")",
";",
"byte",
"[",
"]",
"out",
"=",
"output",
".",
"array",
"(",
")",
";",
"int",
"written",
"=",
"Snappy",
".",
"uncompress",
"(",
"in",
",",
"inOffset",
",",
"len",
",",
"out",
",",
"offset",
")",
";",
"output",
".",
"writerIndex",
"(",
"output",
".",
"writerIndex",
"(",
")",
"+",
"written",
")",
";",
"return",
"output",
";",
"}",
"catch",
"(",
"IOException",
"e",
")",
"{",
"if",
"(",
"output",
"!=",
"null",
")",
"{",
"output",
".",
"release",
"(",
")",
";",
"}",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}"
] |
@implNote The Snappy protocol already encodes the uncompressed length in the compressed payload,
so {@link #compress(ByteBuf)} and {@link #compressWithoutLength(ByteBuf)} produce the same
output for this compressor.
|
[
"@implNote",
"The",
"Snappy",
"protocol",
"already",
"encodes",
"the",
"uncompressed",
"length",
"in",
"the",
"compressed",
"payload",
"so",
"{",
"@link",
"#compress",
"(",
"ByteBuf",
")",
"}",
"and",
"{",
"@link",
"#compressWithoutLength",
"(",
"ByteBuf",
")",
"}",
"produce",
"the",
"same",
"output",
"for",
"this",
"compressor",
"."
] |
[
"// If the input is direct we will allocate a direct output buffer as well as this will allow us",
"// to use Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.",
"// Increase reader index.",
"// Set the writer index so the amount of written bytes is reflected",
"// release output buffer so we not leak and rethrow exception.",
"// Increase reader index.",
"// Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and",
"// so can eliminate the overhead of allocate a new byte[].",
"// Calculate the correct offset.",
"// Increase the writerIndex with the written bytes.",
"// release output buffer so we not leak and rethrow exception.",
"// Since compress methods don't actually prepend with a length, we have nothing to read here.",
"// Return a bogus length (it will be ignored by the decompress methods, so the actual value",
"// doesn't matter).",
"// Increase reader index.",
"// If the input is direct we will allocate a direct output buffer as well as this will allow",
"// us to use Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies.",
"// Set the writer index so the amount of written bytes is reflected",
"// release output buffer so we not leak and rethrow exception.",
"// Not a direct buffer so use byte arrays...",
"// Increase reader index.",
"// Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and",
"// so can eliminate the overhead of allocate a new byte[].",
"// Calculate the correct offset.",
"// Increase the writerIndex with the written bytes.",
"// release output buffer so we not leak and rethrow exception."
] |
[
{
"param": "ByteBufCompressor",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "ByteBufCompressor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 13
| 1,197
| 82
|
b48135ed3e8550139df18d52a1f6adc7b8713750
|
jcoletaylor/tasker
|
app/models/tasker/dependent_system_object_map.rb
|
[
"MIT"
] |
Ruby
|
Tasker
|
# == Schema Information
#
# Table name: dependent_system_object_maps
#
# remote_id_one :string(128) not null
# remote_id_two :string(128) not null
# created_at :datetime not null
# updated_at :datetime not null
# dependent_system_object_map_id :bigint not null, primary key
# dependent_system_one_id :integer not null
# dependent_system_two_id :integer not null
#
# Indexes
#
# dependent_system_object_maps_dependent_system_one_id_dependent_ (dependent_system_one_id,dependent_system_two_id,remote_id_one,remote_id_two) UNIQUE
# dependent_system_object_maps_dependent_system_one_id_index (dependent_system_one_id)
# dependent_system_object_maps_dependent_system_two_id_index (dependent_system_two_id)
# dependent_system_object_maps_remote_id_one_index (remote_id_one)
# dependent_system_object_maps_remote_id_two_index (remote_id_two)
#
# Foreign Keys
#
# dependent_system_object_maps_dependent_system_one_id_foreign (dependent_system_one_id => dependent_systems.dependent_system_id)
# dependent_system_object_maps_dependent_system_two_id_foreign (dependent_system_two_id => dependent_systems.dependent_system_id)
#
|
Schema Information
Table name: dependent_system_object_maps
Indexes
Foreign Keys
|
[
"Schema",
"Information",
"Table",
"name",
":",
"dependent_system_object_maps",
"Indexes",
"Foreign",
"Keys"
] |
module Tasker
class DependentSystemObjectMap < ApplicationRecord
self.primary_key = :dependent_system_object_map_id
belongs_to :dependent_system_one, class_name: 'Tasker::DependentSystem'
belongs_to :dependent_system_two, class_name: 'Tasker::DependentSystem'
validates :remote_id_one, presence: true
validates :remote_id_two, presence: true
validates :dependent_system_one_id, presence: true
validates :dependent_system_two_id, presence: true
def self.find_or_create(
system_one_name, system_one_id,
system_two_name, system_two_id
)
system_one = Tasker::DependentSystem.find_or_create_by!(name: system_one_name)
system_two = Tasker::DependentSystem.find_or_create_by!(name: system_two_name)
# these could be in either order
inst = where(
remote_id_one: system_one_id,
remote_id_two: system_two_id,
dependent_system_one_id: system_one.dependent_system_id,
dependent_system_two_id: system_two.dependent_system_id
).or(
where(
remote_id_one: system_two_id,
remote_id_two: system_one_id,
dependent_system_one_id: system_two.dependent_system_id,
dependent_system_two_id: system_one.dependent_system_id
)
).first
inst ||= create(
remote_id_one: system_one_id,
remote_id_two: system_two_id,
dependent_system_one: system_one,
dependent_system_two: system_two
)
inst
end
end
end
|
[
"module",
"Tasker",
"class",
"DependentSystemObjectMap",
"<",
"ApplicationRecord",
"self",
".",
"primary_key",
"=",
":dependent_system_object_map_id",
"belongs_to",
":dependent_system_one",
",",
"class_name",
":",
"'Tasker::DependentSystem'",
"belongs_to",
":dependent_system_two",
",",
"class_name",
":",
"'Tasker::DependentSystem'",
"validates",
":remote_id_one",
",",
"presence",
":",
"true",
"validates",
":remote_id_two",
",",
"presence",
":",
"true",
"validates",
":dependent_system_one_id",
",",
"presence",
":",
"true",
"validates",
":dependent_system_two_id",
",",
"presence",
":",
"true",
"def",
"self",
".",
"find_or_create",
"(",
"system_one_name",
",",
"system_one_id",
",",
"system_two_name",
",",
"system_two_id",
")",
"system_one",
"=",
"Tasker",
"::",
"DependentSystem",
".",
"find_or_create_by!",
"(",
"name",
":",
"system_one_name",
")",
"system_two",
"=",
"Tasker",
"::",
"DependentSystem",
".",
"find_or_create_by!",
"(",
"name",
":",
"system_two_name",
")",
"inst",
"=",
"where",
"(",
"remote_id_one",
":",
"system_one_id",
",",
"remote_id_two",
":",
"system_two_id",
",",
"dependent_system_one_id",
":",
"system_one",
".",
"dependent_system_id",
",",
"dependent_system_two_id",
":",
"system_two",
".",
"dependent_system_id",
")",
".",
"or",
"(",
"where",
"(",
"remote_id_one",
":",
"system_two_id",
",",
"remote_id_two",
":",
"system_one_id",
",",
"dependent_system_one_id",
":",
"system_two",
".",
"dependent_system_id",
",",
"dependent_system_two_id",
":",
"system_one",
".",
"dependent_system_id",
")",
")",
".",
"first",
"inst",
"||=",
"create",
"(",
"remote_id_one",
":",
"system_one_id",
",",
"remote_id_two",
":",
"system_two_id",
",",
"dependent_system_one",
":",
"system_one",
",",
"dependent_system_two",
":",
"system_two",
")",
"inst",
"end",
"end",
"end"
] |
Schema Information
Table name: dependent_system_object_maps
|
[
"Schema",
"Information",
"Table",
"name",
":",
"dependent_system_object_maps"
] |
[
"# these could be in either order"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 15
| 345
| 287
|
44f83ad31bd11ced3f1b2d39ba0553e3c5b9e5ed
|
LiScI-Lab/Guardian-of-Times
|
app/controllers/concerns/progress_filter.rb
|
[
"Apache-2.0"
] |
Ruby
|
ProgressFilter
|
############
##
## Copyright 2018 M. Hoppe & N. Justus
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
############
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module ProgressFilter
include ActiveSupport::Concern
def get_filtered_progresses(model_with_progresses)
month_filter = params[:filter][:month].select {|e| not e.blank?}.map {|str| Date.parse(str)} if params[:filter] and params[:filter][:month]
tag_list = params[:filter][:tag_list] if params[:filter]
member_filter = params[:filter][:member_id].select {|e| not e.blank?} if params[:filter] and params[:filter][:member_id]
progresses = if month_filter&.any?
model_with_progresses.progresses.in_months(month_filter)
else
model_with_progresses.progresses
end
progresses = if member_filter&.any?
progresses
.joins(:member)
.joins(:user)
.where(member: member_filter)
else
progresses
end
if tag_list and not tag_list.blank?
progresses.tagged_with(tag_list, any: true)
else
progresses
end
end
end
|
[
"module",
"ProgressFilter",
"include",
"ActiveSupport",
"::",
"Concern",
"def",
"get_filtered_progresses",
"(",
"model_with_progresses",
")",
"month_filter",
"=",
"params",
"[",
":filter",
"]",
"[",
":month",
"]",
".",
"select",
"{",
"|",
"e",
"|",
"not",
"e",
".",
"blank?",
"}",
".",
"map",
"{",
"|",
"str",
"|",
"Date",
".",
"parse",
"(",
"str",
")",
"}",
"if",
"params",
"[",
":filter",
"]",
"and",
"params",
"[",
":filter",
"]",
"[",
":month",
"]",
"tag_list",
"=",
"params",
"[",
":filter",
"]",
"[",
":tag_list",
"]",
"if",
"params",
"[",
":filter",
"]",
"member_filter",
"=",
"params",
"[",
":filter",
"]",
"[",
":member_id",
"]",
".",
"select",
"{",
"|",
"e",
"|",
"not",
"e",
".",
"blank?",
"}",
"if",
"params",
"[",
":filter",
"]",
"and",
"params",
"[",
":filter",
"]",
"[",
":member_id",
"]",
"progresses",
"=",
"if",
"month_filter",
"&.",
"any?",
"model_with_progresses",
".",
"progresses",
".",
"in_months",
"(",
"month_filter",
")",
"else",
"model_with_progresses",
".",
"progresses",
"end",
"progresses",
"=",
"if",
"member_filter",
"&.",
"any?",
"progresses",
".",
"joins",
"(",
":member",
")",
".",
"joins",
"(",
":user",
")",
".",
"where",
"(",
"member",
":",
"member_filter",
")",
"else",
"progresses",
"end",
"if",
"tag_list",
"and",
"not",
"tag_list",
".",
"blank?",
"progresses",
".",
"tagged_with",
"(",
"tag_list",
",",
"any",
":",
"true",
")",
"else",
"progresses",
"end",
"end",
"end"
] |
Copyright 2018 M. Hoppe & N. Justus
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
|
[
"Copyright",
"2018",
"M",
".",
"Hoppe",
"&",
"N",
".",
"Justus",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 224
| 141
|
fe0dc30e3e08171b3264ec4946ffd82e89eb6a83
|
shilad/wikibrain
|
wikibrain-core/src/main/java/org/wikibrain/core/dao/DaoFilter.java
|
[
"Apache-2.0"
] |
Java
|
DaoFilter
|
/**
*
* A helper class for specifying complex queries. To use, instantiate a new instance,
* than call the various set methods in a chain to set the filters. Not all filters
* are applied to all objects. Possible filters are, with the objects that use them:
* <p>
* - Language collection (LocalPage, RawPage, LocalLink, Redirect, LocalCategoryMember) <p>
* - NameSpace collection (LocalPage, RawPage, UniversalPage) <p>
* - Redirect flag (LocalPage, RawPage) <p>
* - Disambiguation flag (LocalPage, RawPage) <p>
* - LocationType collection (LocalLink) <p>
* - Source ID collection (LocalLink, Redirect, UniversalLink) <p>
* - Dest ID collection (LocalLink, Redirect, UniversalLink) <p>
* - Parseable flag (LocalLink, Redirect) <p>
* - Algorithm ID collection (UniversalPage, UniversalLink) <p>
* - Limit (All get() methods, but no getCount() methods<p>
*
* Collections are specified as a collection of acceptable entries, while flags are
* booleans set to true, false, or null. Flags and collections set to null will be
* ignored when the search is executed.
*
* A call might look something like:
* DaoFilter df = new DaoFilter()
* .setLanguages(languageSet)
* .setNameSpace(nameSpaces)
* .setRedirect(true)
* .setDisambig(false);
*
* @author Ari Weiland
*
*/
|
A helper class for specifying complex queries. To use, instantiate a new instance,
than call the various set methods in a chain to set the filters. Not all filters
are applied to all objects.
Collections are specified as a collection of acceptable entries, while flags are
booleans set to true, false, or null. Flags and collections set to null will be
ignored when the search is executed.
@author Ari Weiland
|
[
"A",
"helper",
"class",
"for",
"specifying",
"complex",
"queries",
".",
"To",
"use",
"instantiate",
"a",
"new",
"instance",
"than",
"call",
"the",
"various",
"set",
"methods",
"in",
"a",
"chain",
"to",
"set",
"the",
"filters",
".",
"Not",
"all",
"filters",
"are",
"applied",
"to",
"all",
"objects",
".",
"Collections",
"are",
"specified",
"as",
"a",
"collection",
"of",
"acceptable",
"entries",
"while",
"flags",
"are",
"booleans",
"set",
"to",
"true",
"false",
"or",
"null",
".",
"Flags",
"and",
"collections",
"set",
"to",
"null",
"will",
"be",
"ignored",
"when",
"the",
"search",
"is",
"executed",
".",
"@author",
"Ari",
"Weiland"
] |
public class DaoFilter {
private Collection<Short> langIds;
private Collection<Short> nsIds;
private Boolean isRedirect;
private Boolean isDisambig;
private Boolean hasDest;
private Collection<Short> locTypeIds;
private Collection<Integer> sourceIds;
private Collection<Integer> destIds;
private Boolean isParseable;
private Integer limit;
public DaoFilter() {
langIds = null;
nsIds = null;
isRedirect = null;
isDisambig = null;
sourceIds = null;
destIds = null;
locTypeIds = null;
isParseable = null;
hasDest = null;
}
public Collection<Short> getLangIds() {
return langIds;
}
public Collection<Short> getNameSpaceIds() {
return nsIds;
}
public Boolean isRedirect() {
return isRedirect;
}
public Boolean isDisambig() {
return isDisambig;
}
public Collection<Short> getLocTypes() {
return locTypeIds;
}
public Collection<Integer> getSourceIds() {
return sourceIds;
}
public Collection<Integer> getDestIds() {
return destIds;
}
public Boolean isParseable() {
return isParseable;
}
/**
* Sets the language filter to the specified LanguageSet.
* Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.
* @param languages
* @return
*/
public DaoFilter setLanguages(LanguageSet languages) {
return setLanguages(languages.getLanguages());
}
/**
* Sets the language filter to the specified collection of languages.
* Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.
* @param languages
* @return
*/
public DaoFilter setLanguages(Collection<Language> languages) {
Collection<Short> temp = new ArrayList<Short>();
if (languages==null || languages.isEmpty()) {
temp = null;
}
else {
for (Language l : languages) {
temp.add(l.getId());
}
}
this.langIds = temp;
return this;
}
/**
* Sets the language filter to the specified language.
* Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.
* @param language
* @return
*/
public DaoFilter setLanguages(Language language) {
return setLanguages(Arrays.asList(language));
}
/**
* Sets the namespace filter to the specified collection of namespace constants.
* Used by LocalPage, RawPage, and UniversalPage.
* @param nameSpaces
* @return
*/
public DaoFilter setNameSpaces(Collection<NameSpace> nameSpaces) {
Collection<Short> temp = new ArrayList<Short>();
if (nameSpaces == null || nameSpaces.isEmpty()) {
temp = null;
}
else {
for (NameSpace ns : nameSpaces) {
temp.add(ns.getArbitraryId());
}
}
this.nsIds = temp;
return this;
}
/**
* Sets the namespace filter to the specified namespace constant.
* Used by LocalPage, RawPage, and UniversalPage.
* @param nameSpaces
* @return
*/
public DaoFilter setNameSpaces(NameSpace nameSpaces) {
return setNameSpaces(Arrays.asList(nameSpaces));
}
/**
* Sets the redirect flag.
* Used by LocalPage and RawPage.
* @param redirect
* @return
*/
public DaoFilter setRedirect(Boolean redirect) {
this.isRedirect = redirect;
return this;
}
/**
* Sets the disambiguation flag.
* Used by LocalPage and RawPage.
* @param disambig
* @return
*/
public DaoFilter setDisambig(Boolean disambig) {
this.isDisambig = disambig;
return this;
}
/**
* Whether or not links, etc. are required to have destinations.
* @param hasDest
*/
public DaoFilter setHasDest(Boolean hasDest) {
this.hasDest = hasDest;
return this;
}
public Boolean getHasDest() {
return hasDest;
}
/**
* Sets the Location Type filter for a LocalLink to the specified array.
* Used only by LocalLink.
* @param locTypes
* @return
*/
public DaoFilter setLocTypeIds(LocalLink.LocationType[] locTypes) {
return setLocTypeIds(Arrays.asList(locTypes));
}
/**
* Sets the Location Type filter for a LocalLink to the specified collection.
* Used only by LocalLink.
* @param locTypes
* @return
*/
public DaoFilter setLocTypeIds(Collection<LocalLink.LocationType> locTypes) {
Collection<Short> temp = new ArrayList<Short>();
if (locTypes == null || locTypes.isEmpty()) {
temp = null;
}
else {
for (LocalLink.LocationType lt : locTypes) {
temp.add((short)lt.ordinal());
}
}
this.locTypeIds = temp;
return this;
}
/**
* Sets the SourceIds filter to the specified collection.
* Used by LocalLink, UniversalLink, and Redirect.
* @param sourceIds
* @return
*/
public DaoFilter setSourceIds(Collection<Integer> sourceIds) {
this.sourceIds = sourceIds;
return this;
}
/**
* Sets the SourceIds filter to the specified source ID.
* Used by LocalLink, UniversalLink, and Redirect.
* @param sourceId
* @return
*/
public DaoFilter setSourceIds(int sourceId) {
return setSourceIds(Arrays.asList(sourceId));
}
/**
* Sets the DestinationIds filter to the specified collection.
* Used by LocalLink, UniversalLink, and Redirect.
* @param destIds
* @return
*/
public DaoFilter setDestIds(Collection<Integer> destIds) {
this.destIds = destIds;
return this;
}
/**
* Sets the DestinationIds filter to the specified destination ID.
* Used by LocalLink, UniversalLink, and Redirect.
* @param destId
* @return
*/
public DaoFilter setDestIds(int destId) {
return setDestIds(Arrays.asList(destId));
}
/**
* Sets the Parseable flag.
* Used by LocalLink and Redirect.
* @param parseable
* @return
*/
public DaoFilter setParseable(Boolean parseable) {
isParseable = parseable;
return this;
}
/**
* @param limit The maximum number of results returned by queries
* @return
*/
public DaoFilter setLimit(int limit) {
this.limit = limit;
return this;
}
/**
* @return Limit, or null
*/
public Integer getLimit() {
return limit;
}
/**
* @return Limit, or Integer.MAX_VALUE if it is null
*/
public Integer getLimitOrInfinity() {
return limit == null ? Integer.MAX_VALUE : limit;
}
/**
* Returns true if and only if the page is valid within the
* parameters of this DaoFilter.
* @param page
* @return
*/
public boolean isValidLocalPage(LocalPage page) {
return page != null
&& (langIds == null || langIds.contains(page.getLanguage().getId()))
&& (nsIds == null || nsIds.contains(page.getNameSpace().getArbitraryId()))
&& (isRedirect == null || isRedirect == page.isRedirect())
&& (isDisambig == null || isDisambig == page.isDisambig());
}
public static DaoFilter normalPageFilter(Language language) {
return new DaoFilter()
.setDisambig(false)
.setRedirect(false)
.setNameSpaces(NameSpace.ARTICLE)
.setLanguages(language);
}
}
|
[
"public",
"class",
"DaoFilter",
"{",
"private",
"Collection",
"<",
"Short",
">",
"langIds",
";",
"private",
"Collection",
"<",
"Short",
">",
"nsIds",
";",
"private",
"Boolean",
"isRedirect",
";",
"private",
"Boolean",
"isDisambig",
";",
"private",
"Boolean",
"hasDest",
";",
"private",
"Collection",
"<",
"Short",
">",
"locTypeIds",
";",
"private",
"Collection",
"<",
"Integer",
">",
"sourceIds",
";",
"private",
"Collection",
"<",
"Integer",
">",
"destIds",
";",
"private",
"Boolean",
"isParseable",
";",
"private",
"Integer",
"limit",
";",
"public",
"DaoFilter",
"(",
")",
"{",
"langIds",
"=",
"null",
";",
"nsIds",
"=",
"null",
";",
"isRedirect",
"=",
"null",
";",
"isDisambig",
"=",
"null",
";",
"sourceIds",
"=",
"null",
";",
"destIds",
"=",
"null",
";",
"locTypeIds",
"=",
"null",
";",
"isParseable",
"=",
"null",
";",
"hasDest",
"=",
"null",
";",
"}",
"public",
"Collection",
"<",
"Short",
">",
"getLangIds",
"(",
")",
"{",
"return",
"langIds",
";",
"}",
"public",
"Collection",
"<",
"Short",
">",
"getNameSpaceIds",
"(",
")",
"{",
"return",
"nsIds",
";",
"}",
"public",
"Boolean",
"isRedirect",
"(",
")",
"{",
"return",
"isRedirect",
";",
"}",
"public",
"Boolean",
"isDisambig",
"(",
")",
"{",
"return",
"isDisambig",
";",
"}",
"public",
"Collection",
"<",
"Short",
">",
"getLocTypes",
"(",
")",
"{",
"return",
"locTypeIds",
";",
"}",
"public",
"Collection",
"<",
"Integer",
">",
"getSourceIds",
"(",
")",
"{",
"return",
"sourceIds",
";",
"}",
"public",
"Collection",
"<",
"Integer",
">",
"getDestIds",
"(",
")",
"{",
"return",
"destIds",
";",
"}",
"public",
"Boolean",
"isParseable",
"(",
")",
"{",
"return",
"isParseable",
";",
"}",
"/**\n * Sets the language filter to the specified LanguageSet.\n * Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.\n * @param languages\n * @return\n */",
"public",
"DaoFilter",
"setLanguages",
"(",
"LanguageSet",
"languages",
")",
"{",
"return",
"setLanguages",
"(",
"languages",
".",
"getLanguages",
"(",
")",
")",
";",
"}",
"/**\n * Sets the language filter to the specified collection of languages.\n * Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.\n * @param languages\n * @return\n */",
"public",
"DaoFilter",
"setLanguages",
"(",
"Collection",
"<",
"Language",
">",
"languages",
")",
"{",
"Collection",
"<",
"Short",
">",
"temp",
"=",
"new",
"ArrayList",
"<",
"Short",
">",
"(",
")",
";",
"if",
"(",
"languages",
"==",
"null",
"||",
"languages",
".",
"isEmpty",
"(",
")",
")",
"{",
"temp",
"=",
"null",
";",
"}",
"else",
"{",
"for",
"(",
"Language",
"l",
":",
"languages",
")",
"{",
"temp",
".",
"add",
"(",
"l",
".",
"getId",
"(",
")",
")",
";",
"}",
"}",
"this",
".",
"langIds",
"=",
"temp",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the language filter to the specified language.\n * Used by LocalPage, RawPage, LocalLink, Redirect, and LocalCategoryMember.\n * @param language\n * @return\n */",
"public",
"DaoFilter",
"setLanguages",
"(",
"Language",
"language",
")",
"{",
"return",
"setLanguages",
"(",
"Arrays",
".",
"asList",
"(",
"language",
")",
")",
";",
"}",
"/**\n * Sets the namespace filter to the specified collection of namespace constants.\n * Used by LocalPage, RawPage, and UniversalPage.\n * @param nameSpaces\n * @return\n */",
"public",
"DaoFilter",
"setNameSpaces",
"(",
"Collection",
"<",
"NameSpace",
">",
"nameSpaces",
")",
"{",
"Collection",
"<",
"Short",
">",
"temp",
"=",
"new",
"ArrayList",
"<",
"Short",
">",
"(",
")",
";",
"if",
"(",
"nameSpaces",
"==",
"null",
"||",
"nameSpaces",
".",
"isEmpty",
"(",
")",
")",
"{",
"temp",
"=",
"null",
";",
"}",
"else",
"{",
"for",
"(",
"NameSpace",
"ns",
":",
"nameSpaces",
")",
"{",
"temp",
".",
"add",
"(",
"ns",
".",
"getArbitraryId",
"(",
")",
")",
";",
"}",
"}",
"this",
".",
"nsIds",
"=",
"temp",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the namespace filter to the specified namespace constant.\n * Used by LocalPage, RawPage, and UniversalPage.\n * @param nameSpaces\n * @return\n */",
"public",
"DaoFilter",
"setNameSpaces",
"(",
"NameSpace",
"nameSpaces",
")",
"{",
"return",
"setNameSpaces",
"(",
"Arrays",
".",
"asList",
"(",
"nameSpaces",
")",
")",
";",
"}",
"/**\n * Sets the redirect flag.\n * Used by LocalPage and RawPage.\n * @param redirect\n * @return\n */",
"public",
"DaoFilter",
"setRedirect",
"(",
"Boolean",
"redirect",
")",
"{",
"this",
".",
"isRedirect",
"=",
"redirect",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the disambiguation flag.\n * Used by LocalPage and RawPage.\n * @param disambig\n * @return\n */",
"public",
"DaoFilter",
"setDisambig",
"(",
"Boolean",
"disambig",
")",
"{",
"this",
".",
"isDisambig",
"=",
"disambig",
";",
"return",
"this",
";",
"}",
"/**\n * Whether or not links, etc. are required to have destinations.\n * @param hasDest\n */",
"public",
"DaoFilter",
"setHasDest",
"(",
"Boolean",
"hasDest",
")",
"{",
"this",
".",
"hasDest",
"=",
"hasDest",
";",
"return",
"this",
";",
"}",
"public",
"Boolean",
"getHasDest",
"(",
")",
"{",
"return",
"hasDest",
";",
"}",
"/**\n * Sets the Location Type filter for a LocalLink to the specified array.\n * Used only by LocalLink.\n * @param locTypes\n * @return\n */",
"public",
"DaoFilter",
"setLocTypeIds",
"(",
"LocalLink",
".",
"LocationType",
"[",
"]",
"locTypes",
")",
"{",
"return",
"setLocTypeIds",
"(",
"Arrays",
".",
"asList",
"(",
"locTypes",
")",
")",
";",
"}",
"/**\n * Sets the Location Type filter for a LocalLink to the specified collection.\n * Used only by LocalLink.\n * @param locTypes\n * @return\n */",
"public",
"DaoFilter",
"setLocTypeIds",
"(",
"Collection",
"<",
"LocalLink",
".",
"LocationType",
">",
"locTypes",
")",
"{",
"Collection",
"<",
"Short",
">",
"temp",
"=",
"new",
"ArrayList",
"<",
"Short",
">",
"(",
")",
";",
"if",
"(",
"locTypes",
"==",
"null",
"||",
"locTypes",
".",
"isEmpty",
"(",
")",
")",
"{",
"temp",
"=",
"null",
";",
"}",
"else",
"{",
"for",
"(",
"LocalLink",
".",
"LocationType",
"lt",
":",
"locTypes",
")",
"{",
"temp",
".",
"add",
"(",
"(",
"short",
")",
"lt",
".",
"ordinal",
"(",
")",
")",
";",
"}",
"}",
"this",
".",
"locTypeIds",
"=",
"temp",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the SourceIds filter to the specified collection.\n * Used by LocalLink, UniversalLink, and Redirect.\n * @param sourceIds\n * @return\n */",
"public",
"DaoFilter",
"setSourceIds",
"(",
"Collection",
"<",
"Integer",
">",
"sourceIds",
")",
"{",
"this",
".",
"sourceIds",
"=",
"sourceIds",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the SourceIds filter to the specified source ID.\n * Used by LocalLink, UniversalLink, and Redirect.\n * @param sourceId\n * @return\n */",
"public",
"DaoFilter",
"setSourceIds",
"(",
"int",
"sourceId",
")",
"{",
"return",
"setSourceIds",
"(",
"Arrays",
".",
"asList",
"(",
"sourceId",
")",
")",
";",
"}",
"/**\n * Sets the DestinationIds filter to the specified collection.\n * Used by LocalLink, UniversalLink, and Redirect.\n * @param destIds\n * @return\n */",
"public",
"DaoFilter",
"setDestIds",
"(",
"Collection",
"<",
"Integer",
">",
"destIds",
")",
"{",
"this",
".",
"destIds",
"=",
"destIds",
";",
"return",
"this",
";",
"}",
"/**\n * Sets the DestinationIds filter to the specified destination ID.\n * Used by LocalLink, UniversalLink, and Redirect.\n * @param destId\n * @return\n */",
"public",
"DaoFilter",
"setDestIds",
"(",
"int",
"destId",
")",
"{",
"return",
"setDestIds",
"(",
"Arrays",
".",
"asList",
"(",
"destId",
")",
")",
";",
"}",
"/**\n * Sets the Parseable flag.\n * Used by LocalLink and Redirect.\n * @param parseable\n * @return\n */",
"public",
"DaoFilter",
"setParseable",
"(",
"Boolean",
"parseable",
")",
"{",
"isParseable",
"=",
"parseable",
";",
"return",
"this",
";",
"}",
"/**\n * @param limit The maximum number of results returned by queries\n * @return\n */",
"public",
"DaoFilter",
"setLimit",
"(",
"int",
"limit",
")",
"{",
"this",
".",
"limit",
"=",
"limit",
";",
"return",
"this",
";",
"}",
"/**\n * @return Limit, or null\n */",
"public",
"Integer",
"getLimit",
"(",
")",
"{",
"return",
"limit",
";",
"}",
"/**\n * @return Limit, or Integer.MAX_VALUE if it is null\n */",
"public",
"Integer",
"getLimitOrInfinity",
"(",
")",
"{",
"return",
"limit",
"==",
"null",
"?",
"Integer",
".",
"MAX_VALUE",
":",
"limit",
";",
"}",
"/**\n * Returns true if and only if the page is valid within the\n * parameters of this DaoFilter.\n * @param page\n * @return\n */",
"public",
"boolean",
"isValidLocalPage",
"(",
"LocalPage",
"page",
")",
"{",
"return",
"page",
"!=",
"null",
"&&",
"(",
"langIds",
"==",
"null",
"||",
"langIds",
".",
"contains",
"(",
"page",
".",
"getLanguage",
"(",
")",
".",
"getId",
"(",
")",
")",
")",
"&&",
"(",
"nsIds",
"==",
"null",
"||",
"nsIds",
".",
"contains",
"(",
"page",
".",
"getNameSpace",
"(",
")",
".",
"getArbitraryId",
"(",
")",
")",
")",
"&&",
"(",
"isRedirect",
"==",
"null",
"||",
"isRedirect",
"==",
"page",
".",
"isRedirect",
"(",
")",
")",
"&&",
"(",
"isDisambig",
"==",
"null",
"||",
"isDisambig",
"==",
"page",
".",
"isDisambig",
"(",
")",
")",
";",
"}",
"public",
"static",
"DaoFilter",
"normalPageFilter",
"(",
"Language",
"language",
")",
"{",
"return",
"new",
"DaoFilter",
"(",
")",
".",
"setDisambig",
"(",
"false",
")",
".",
"setRedirect",
"(",
"false",
")",
".",
"setNameSpaces",
"(",
"NameSpace",
".",
"ARTICLE",
")",
".",
"setLanguages",
"(",
"language",
")",
";",
"}",
"}"
] |
A helper class for specifying complex queries.
|
[
"A",
"helper",
"class",
"for",
"specifying",
"complex",
"queries",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 1,759
| 337
|
132856e2deb7bafd5dcf133397155e4385df6653
|
bmad4ever/ArucoUnity
|
Assets/ArucoUnity/Scripts/Cameras/Undistortions/Omnidir/OmnidirCameraUndistortionGeneric.cs
|
[
"BSD-3-Clause"
] |
C#
|
OmnidirCameraUndistortionGeneric
|
/// <summary>
/// Manages the undistortion and rectification process for fisheye and omnidir <see cref="ArucoCamera"/>.
///
/// See the OpenCV's ccalib module documentation for more information:
/// http://docs.opencv.org/3.4/dd/d12/tutorial_omnidir_calib_main.html
/// </summary>
|
Manages the undistortion and rectification process for fisheye and omnidir .
|
[
"Manages",
"the",
"undistortion",
"and",
"rectification",
"process",
"for",
"fisheye",
"and",
"omnidir",
"."
] |
public abstract class OmnidirCameraUndistortionGeneric<T> : ArucoCameraUndistortionGeneric<T>
where T : ArucoCamera
{
public enum RectificationTypes
{
Perspective,
Cylindrical,
LongitudeLatitude,
Stereographic
}
protected const float minPerspectiveFov = 1f;
protected const float maxPerspectiveFov = 179f;
[SerializeField]
[Tooltip("The algorithm to use for the recitification of the images.")]
private RectificationTypes rectificationType = RectificationTypes.Perspective;
[SerializeField]
[Tooltip("The desired field of view for the Unity cameras shooting the undistorted and rectified images.")]
[Range(1f, 179f)]
private float[] perspectiveFieldOfViews;
public RectificationTypes RectificationType { get { return rectificationType; } set { rectificationType = value; } }
public float[] PerspectiveFieldOfViews { get { return perspectiveFieldOfViews; } set { perspectiveFieldOfViews = value; } }
protected Dictionary<RectificationTypes, Cv.Omnidir.Rectifify> rectifyFlags = new Dictionary<RectificationTypes, Cv.Omnidir.Rectifify>()
{
{ RectificationTypes.Perspective, Cv.Omnidir.Rectifify.Perspective },
{ RectificationTypes.Cylindrical, Cv.Omnidir.Rectifify.Cylindrical },
{ RectificationTypes.LongitudeLatitude, Cv.Omnidir.Rectifify.Longlati },
{ RectificationTypes.Stereographic, Cv.Omnidir.Rectifify.Stereographic }
};
protected virtual void OnValidate()
{
if (ArucoCamera != null && perspectiveFieldOfViews != null && perspectiveFieldOfViews.Length != ArucoCamera.CameraNumber)
{
Array.Resize(ref perspectiveFieldOfViews, ArucoCamera.CameraNumber);
}
}
protected override void Configuring()
{
base.Configuring();
if (PerspectiveFieldOfViews.Length != ArucoCamera.CameraNumber)
{
throw new Exception("The number of cameras for the perspective desired field of view must be equal to the number of cameras in" +
"ArucoCamera");
}
}
protected override void InitializeRectification()
{
for (int cameraId = 0; cameraId < CameraParameters.CameraNumber; cameraId++)
{
float imageWidth = CameraParameters.ImageWidths[cameraId];
float imageHeight = CameraParameters.ImageHeights[cameraId];
if (RectificationType == RectificationTypes.Perspective)
{
float cameraFocalLength = imageHeight / (2f * Mathf.Tan(0.5f * PerspectiveFieldOfViews[cameraId] * Mathf.Deg2Rad));
RectifiedCameraMatrices[cameraId] = new Cv.Mat(3, 3, Cv.Type.CV_64F, new double[9] {
cameraFocalLength, 0, imageWidth / 2,
0, cameraFocalLength, imageHeight / 2,
0, 0, 1
}).Clone();
}
else
{
RectifiedCameraMatrices[cameraId] = new Cv.Mat(3, 3, Cv.Type.CV_64F, new double[9] {
imageWidth / 3.1415, 0, 0,
0, imageHeight / 3.1415, 0,
0, 0, 1
}).Clone();
}
RectificationMatrices[cameraId] = noRectificationMatrix;
}
}
protected override void InitializeUndistortionMaps()
{
for (int cameraId = 0; cameraId < CameraParameters.CameraNumber; cameraId++)
{
Cv.Omnidir.InitUndistortRectifyMap(CameraParameters.CameraMatrices[cameraId], CameraParameters.DistCoeffs[cameraId],
CameraParameters.OmnidirXis[cameraId], RectificationMatrices[cameraId], RectifiedCameraMatrices[cameraId],
ArucoCamera.Images[cameraId].Size, Cv.Type.CV_16SC2, out UndistortionRectificationMaps[cameraId][0],
out UndistortionRectificationMaps[cameraId][1], rectifyFlags[RectificationType]);
}
}
}
|
[
"public",
"abstract",
"class",
"OmnidirCameraUndistortionGeneric",
"<",
"T",
">",
":",
"ArucoCameraUndistortionGeneric",
"<",
"T",
">",
"where",
"T",
":",
"ArucoCamera",
"{",
"public",
"enum",
"RectificationTypes",
"{",
"Perspective",
",",
"Cylindrical",
",",
"LongitudeLatitude",
",",
"Stereographic",
"}",
"protected",
"const",
"float",
"minPerspectiveFov",
"=",
"1f",
";",
"protected",
"const",
"float",
"maxPerspectiveFov",
"=",
"179f",
";",
"[",
"SerializeField",
"]",
"[",
"Tooltip",
"(",
"\"",
"The algorithm to use for the recitification of the images.",
"\"",
")",
"]",
"private",
"RectificationTypes",
"rectificationType",
"=",
"RectificationTypes",
".",
"Perspective",
";",
"[",
"SerializeField",
"]",
"[",
"Tooltip",
"(",
"\"",
"The desired field of view for the Unity cameras shooting the undistorted and rectified images.",
"\"",
")",
"]",
"[",
"Range",
"(",
"1f",
",",
"179f",
")",
"]",
"private",
"float",
"[",
"]",
"perspectiveFieldOfViews",
";",
"public",
"RectificationTypes",
"RectificationType",
"{",
"get",
"{",
"return",
"rectificationType",
";",
"}",
"set",
"{",
"rectificationType",
"=",
"value",
";",
"}",
"}",
"public",
"float",
"[",
"]",
"PerspectiveFieldOfViews",
"{",
"get",
"{",
"return",
"perspectiveFieldOfViews",
";",
"}",
"set",
"{",
"perspectiveFieldOfViews",
"=",
"value",
";",
"}",
"}",
"protected",
"Dictionary",
"<",
"RectificationTypes",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
">",
"rectifyFlags",
"=",
"new",
"Dictionary",
"<",
"RectificationTypes",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
">",
"(",
")",
"{",
"{",
"RectificationTypes",
".",
"Perspective",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
".",
"Perspective",
"}",
",",
"{",
"RectificationTypes",
".",
"Cylindrical",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
".",
"Cylindrical",
"}",
",",
"{",
"RectificationTypes",
".",
"LongitudeLatitude",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
".",
"Longlati",
"}",
",",
"{",
"RectificationTypes",
".",
"Stereographic",
",",
"Cv",
".",
"Omnidir",
".",
"Rectifify",
".",
"Stereographic",
"}",
"}",
";",
"protected",
"virtual",
"void",
"OnValidate",
"(",
")",
"{",
"if",
"(",
"ArucoCamera",
"!=",
"null",
"&&",
"perspectiveFieldOfViews",
"!=",
"null",
"&&",
"perspectiveFieldOfViews",
".",
"Length",
"!=",
"ArucoCamera",
".",
"CameraNumber",
")",
"{",
"Array",
".",
"Resize",
"(",
"ref",
"perspectiveFieldOfViews",
",",
"ArucoCamera",
".",
"CameraNumber",
")",
";",
"}",
"}",
"protected",
"override",
"void",
"Configuring",
"(",
")",
"{",
"base",
".",
"Configuring",
"(",
")",
";",
"if",
"(",
"PerspectiveFieldOfViews",
".",
"Length",
"!=",
"ArucoCamera",
".",
"CameraNumber",
")",
"{",
"throw",
"new",
"Exception",
"(",
"\"",
"The number of cameras for the perspective desired field of view must be equal to the number of cameras in",
"\"",
"+",
"\"",
"ArucoCamera",
"\"",
")",
";",
"}",
"}",
"protected",
"override",
"void",
"InitializeRectification",
"(",
")",
"{",
"for",
"(",
"int",
"cameraId",
"=",
"0",
";",
"cameraId",
"<",
"CameraParameters",
".",
"CameraNumber",
";",
"cameraId",
"++",
")",
"{",
"float",
"imageWidth",
"=",
"CameraParameters",
".",
"ImageWidths",
"[",
"cameraId",
"]",
";",
"float",
"imageHeight",
"=",
"CameraParameters",
".",
"ImageHeights",
"[",
"cameraId",
"]",
";",
"if",
"(",
"RectificationType",
"==",
"RectificationTypes",
".",
"Perspective",
")",
"{",
"float",
"cameraFocalLength",
"=",
"imageHeight",
"/",
"(",
"2f",
"*",
"Mathf",
".",
"Tan",
"(",
"0.5f",
"*",
"PerspectiveFieldOfViews",
"[",
"cameraId",
"]",
"*",
"Mathf",
".",
"Deg2Rad",
")",
")",
";",
"RectifiedCameraMatrices",
"[",
"cameraId",
"]",
"=",
"new",
"Cv",
".",
"Mat",
"(",
"3",
",",
"3",
",",
"Cv",
".",
"Type",
".",
"CV_64F",
",",
"new",
"double",
"[",
"9",
"]",
"{",
"cameraFocalLength",
",",
"0",
",",
"imageWidth",
"/",
"2",
",",
"0",
",",
"cameraFocalLength",
",",
"imageHeight",
"/",
"2",
",",
"0",
",",
"0",
",",
"1",
"}",
")",
".",
"Clone",
"(",
")",
";",
"}",
"else",
"{",
"RectifiedCameraMatrices",
"[",
"cameraId",
"]",
"=",
"new",
"Cv",
".",
"Mat",
"(",
"3",
",",
"3",
",",
"Cv",
".",
"Type",
".",
"CV_64F",
",",
"new",
"double",
"[",
"9",
"]",
"{",
"imageWidth",
"/",
"3.1415",
",",
"0",
",",
"0",
",",
"0",
",",
"imageHeight",
"/",
"3.1415",
",",
"0",
",",
"0",
",",
"0",
",",
"1",
"}",
")",
".",
"Clone",
"(",
")",
";",
"}",
"RectificationMatrices",
"[",
"cameraId",
"]",
"=",
"noRectificationMatrix",
";",
"}",
"}",
"protected",
"override",
"void",
"InitializeUndistortionMaps",
"(",
")",
"{",
"for",
"(",
"int",
"cameraId",
"=",
"0",
";",
"cameraId",
"<",
"CameraParameters",
".",
"CameraNumber",
";",
"cameraId",
"++",
")",
"{",
"Cv",
".",
"Omnidir",
".",
"InitUndistortRectifyMap",
"(",
"CameraParameters",
".",
"CameraMatrices",
"[",
"cameraId",
"]",
",",
"CameraParameters",
".",
"DistCoeffs",
"[",
"cameraId",
"]",
",",
"CameraParameters",
".",
"OmnidirXis",
"[",
"cameraId",
"]",
",",
"RectificationMatrices",
"[",
"cameraId",
"]",
",",
"RectifiedCameraMatrices",
"[",
"cameraId",
"]",
",",
"ArucoCamera",
".",
"Images",
"[",
"cameraId",
"]",
".",
"Size",
",",
"Cv",
".",
"Type",
".",
"CV_16SC2",
",",
"out",
"UndistortionRectificationMaps",
"[",
"cameraId",
"]",
"[",
"0",
"]",
",",
"out",
"UndistortionRectificationMaps",
"[",
"cameraId",
"]",
"[",
"1",
"]",
",",
"rectifyFlags",
"[",
"RectificationType",
"]",
")",
";",
"}",
"}",
"}"
] |
Manages the undistortion and rectification process for fisheye and omnidir .
|
[
"Manages",
"the",
"undistortion",
"and",
"rectification",
"process",
"for",
"fisheye",
"and",
"omnidir",
"."
] |
[
"/// <summary>",
"/// The different algorithms to use for the undistortion of the images.",
"/// </summary>",
"// Constants",
"// Editor fields",
"// Properties",
"/// <summary>",
"/// Gets or sets the algorithm to use for the rectification of the images. See this tutorial for illustrated examples:",
"/// https://docs.opencv.org/3.4/dd/d12/tutorial_omnidir_calib_main.html",
"/// </summary>",
"/// <summary>",
"/// Gets or sets the desired field of view for the Unity cameras shooting the undistorted and rectified images.",
"/// </summary>",
"// Variables",
"// MonoBehaviour methods",
"/// <summary>",
"/// Resizes the length of the <see cref=\"perspectiveFieldOfViews\"/> editor field to <see cref=\"ArucoCamera.CameraNumber\"/> if different.",
"/// </summary>",
"// ConfigurableController methods",
"/// <summary>",
"/// Throw exception if <see cref=\"PerspectiveFieldOfViews\"/> length is different than <see cref=\"ArucoCamera.CameraNumber\"/>.",
"/// </summary>",
"// ArucoCameraUndistortion methods",
"/// <summary>",
"/// Initializes the <see cref=\"RectifiedCameraMatrices\"/> using the <see cref=\"PerspectiveFieldOfViews\"/> values for perspective rectification",
"/// or uses the recommended values: https://docs.opencv.org/3.3.1/dd/d12/tutorial_omnidir_calib_main.html. Initializes the",
"/// <see cref=\"RectificationMatrices\"/> to identity matrix.",
"/// </summary>",
"// Uses the camera matrix recommended values: https://docs.opencv.org/3.3.1/dd/d12/tutorial_omnidir_calib_main.html"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 23
| 951
| 78
|
baa915f080edd2ed8fe81211193a194185cec905
|
saadshams/puremvc-js-multicore-framework
|
src/main/org/puremvc/multicore/patterns/observer/Notification.js
|
[
"Apache-2.0"
] |
JavaScript
|
Notification
|
/**
*
* A base <code>INotification</code> implementation.
*
* <P>PureMVC does not rely upon underlying event models such
* as the one provided with Flash, and ActionScript 3 does
* not have an inherent event model.</P>
*
* <P>The Observer Pattern as implemented within PureMVC exists
* to support event-driven communication between the
* application and the actors of the MVC triad.</P>
*
* <P>Notifications are not meant to be a replacement for Events
* in Flex/Flash/Apollo. Generally, <code>IMediator</code> implementors
* place event listeners on their view components, which they
* then handle in the usual way. This may lead to the broadcast of <code>Notification</code>s to
* trigger <code>ICommand</code>s or to communicate with other <code>IMediators</code>. <code>IProxy</code> and <code>ICommand</code>
* instances communicate with each other and <code>IMediator</code>s
* by broadcasting <code>INotification</code>s.</P>
*
* <P>A key difference between Flash <code>Event</code>s and PureMVC
* <code>Notification</code>s is that <code>Event</code>s follow the
* 'Chain of Responsibility' pattern, 'bubbling' up the display hierarchy
* until some parent component handles the <code>Event</code>, while
* PureMVC <code>Notification</code>s follow a 'Publish/Subscribe'
* pattern. PureMVC classes need not be related to each other in a
* parent/child relationship in order to communicate with one another
* using <code>Notification</code>s.</P>
*
* @typedef {puremvc.INotification} INotification
* @typedef {puremvc.Notification} Notification
*
* @class puremvc.Notification
* @implements puremvc.INotification
*/
|
A base INotification implementation.
PureMVC does not rely upon underlying event models such
as the one provided with Flash, and ActionScript 3 does
not have an inherent event model.
The Observer Pattern as implemented within PureMVC exists
to support event-driven communication between the
application and the actors of the MVC triad.
Notifications are not meant to be a replacement for Events
in Flex/Flash/Apollo. Generally, IMediator implementors
place event listeners on their view components, which they
then handle in the usual way. This may lead to the broadcast of Notifications to
trigger ICommands or to communicate with other IMediators.
|
[
"A",
"base",
"INotification",
"implementation",
".",
"PureMVC",
"does",
"not",
"rely",
"upon",
"underlying",
"event",
"models",
"such",
"as",
"the",
"one",
"provided",
"with",
"Flash",
"and",
"ActionScript",
"3",
"does",
"not",
"have",
"an",
"inherent",
"event",
"model",
".",
"The",
"Observer",
"Pattern",
"as",
"implemented",
"within",
"PureMVC",
"exists",
"to",
"support",
"event",
"-",
"driven",
"communication",
"between",
"the",
"application",
"and",
"the",
"actors",
"of",
"the",
"MVC",
"triad",
".",
"Notifications",
"are",
"not",
"meant",
"to",
"be",
"a",
"replacement",
"for",
"Events",
"in",
"Flex",
"/",
"Flash",
"/",
"Apollo",
".",
"Generally",
"IMediator",
"implementors",
"place",
"event",
"listeners",
"on",
"their",
"view",
"components",
"which",
"they",
"then",
"handle",
"in",
"the",
"usual",
"way",
".",
"This",
"may",
"lead",
"to",
"the",
"broadcast",
"of",
"Notifications",
"to",
"trigger",
"ICommands",
"or",
"to",
"communicate",
"with",
"other",
"IMediators",
"."
] |
class Notification /*extends INotification*/ {
/**
* Constructor.
*
* @constructor
* @param {string} name
* @param {Object} [body] body
* @param {string} [type] type
*/
constructor(name, body = null, type = "") {
// super();
/** @private */
this.name = name;
/** @private */
this.body = body;
/** @private */
this.type = type;
}
/**
* Get the name of the <code>Notification</code> instance.
*
* @returns {string}
*/
getName() {
return this.name;
}
/**
* Set the body of the <code>Notification</code> instance.
*
* @param {Object} body
*/
setBody(body) {
this.body = body;
}
/**
* Get the body of the <code>Notification</code> instance.
*
* @returns {Object}
*/
getBody() {
return this.body;
}
/**
* Set the type of the <code>Notification</code> instance.
*
* @param {string} type
*/
setType(type) {
this.type = type;
}
/**
* Get the type of the <code>Notification</code> instance.
*
* @returns {string}
*/
getType() {
return this.type;
}
/**
* Get the string representation of the <code>Notification</code> instance.
*
* @returns {string}
*/
toString() {
let str= "Notification Name: " + this.name;
str+= "\nBody:" + ((this.body == null ) ? "null" : this.body.toString());
str+= "\nType:" + ((this.type == null ) ? "null" : this.type);
return str;
}
}
|
[
"class",
"Notification",
"{",
"constructor",
"(",
"name",
",",
"body",
"=",
"null",
",",
"type",
"=",
"\"\"",
")",
"{",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"body",
"=",
"body",
";",
"this",
".",
"type",
"=",
"type",
";",
"}",
"getName",
"(",
")",
"{",
"return",
"this",
".",
"name",
";",
"}",
"setBody",
"(",
"body",
")",
"{",
"this",
".",
"body",
"=",
"body",
";",
"}",
"getBody",
"(",
")",
"{",
"return",
"this",
".",
"body",
";",
"}",
"setType",
"(",
"type",
")",
"{",
"this",
".",
"type",
"=",
"type",
";",
"}",
"getType",
"(",
")",
"{",
"return",
"this",
".",
"type",
";",
"}",
"toString",
"(",
")",
"{",
"let",
"str",
"=",
"\"Notification Name: \"",
"+",
"this",
".",
"name",
";",
"str",
"+=",
"\"\\nBody:\"",
"+",
"(",
"(",
"this",
".",
"body",
"==",
"null",
")",
"?",
"\"null\"",
":",
"this",
".",
"body",
".",
"toString",
"(",
")",
")",
";",
"str",
"+=",
"\"\\nType:\"",
"+",
"(",
"(",
"this",
".",
"type",
"==",
"null",
")",
"?",
"\"null\"",
":",
"this",
".",
"type",
")",
";",
"return",
"str",
";",
"}",
"}"
] |
A base <code>INotification</code> implementation.
|
[
"A",
"base",
"<code",
">",
"INotification<",
"/",
"code",
">",
"implementation",
"."
] |
[
"/*extends INotification*/",
"/**\n * Constructor.\n *\n * @constructor\n * @param {string} name\n * @param {Object} [body] body\n * @param {string} [type] type\n */",
"// super();",
"/** @private */",
"/** @private */",
"/** @private */",
"/**\n * Get the name of the <code>Notification</code> instance.\n *\n * @returns {string}\n */",
"/**\n * Set the body of the <code>Notification</code> instance.\n *\n * @param {Object} body\n */",
"/**\n * Get the body of the <code>Notification</code> instance.\n *\n * @returns {Object}\n */",
"/**\n * Set the type of the <code>Notification</code> instance.\n *\n * @param {string} type\n */",
"/**\n * Get the type of the <code>Notification</code> instance.\n *\n * @returns {string}\n */",
"/**\n * Get the string representation of the <code>Notification</code> instance.\n *\n * @returns {string}\n */"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 13
| 417
| 415
|
bd129f8d7f84d31b69cdb07f7725ac5823373ecb
|
prof-spock/LilypondToBandVideoConverter
|
lilypondtobvc/src/basemodules/tablefile.py
|
[
"MIT"
] |
Python
|
TableFile
|
Provides reading from a text file containing several tables with
fields separated by a specific character; the assumption is
that table rows are defined by a trailing newline, but some
consolidation is done for newlines embedded in string fields;
the only service offered is to read some text file given by
name and return a mapping from table name to a list of table
rows with mappings from key to values
|
Provides reading from a text file containing several tables with
fields separated by a specific character; the assumption is
that table rows are defined by a trailing newline, but some
consolidation is done for newlines embedded in string fields;
the only service offered is to read some text file given by
name and return a mapping from table name to a list of table
rows with mappings from key to values
|
[
"Provides",
"reading",
"from",
"a",
"text",
"file",
"containing",
"several",
"tables",
"with",
"fields",
"separated",
"by",
"a",
"specific",
"character",
";",
"the",
"assumption",
"is",
"that",
"table",
"rows",
"are",
"defined",
"by",
"a",
"trailing",
"newline",
"but",
"some",
"consolidation",
"is",
"done",
"for",
"newlines",
"embedded",
"in",
"string",
"fields",
";",
"the",
"only",
"service",
"offered",
"is",
"to",
"read",
"some",
"text",
"file",
"given",
"by",
"name",
"and",
"return",
"a",
"mapping",
"from",
"table",
"name",
"to",
"a",
"list",
"of",
"table",
"rows",
"with",
"mappings",
"from",
"key",
"to",
"values"
] |
class TableFile:
"""Provides reading from a text file containing several tables with
fields separated by a specific character; the assumption is
that table rows are defined by a trailing newline, but some
consolidation is done for newlines embedded in string fields;
the only service offered is to read some text file given by
name and return a mapping from table name to a list of table
rows with mappings from key to values"""
#--------------------
# INTERNAL FEATURES
#--------------------
# the name of the synthesized field containing the line number in
# the physical file
_lineNumberFieldName = "LINENUM"
#--------------------
@classmethod
def _combineToLogicalLines (cls,
physicalLineList : StringList) -> Tuple:
"""Combines physical lines in <physicalLineList> into logical
lines; when some field value is broken across lines that
line is merged and the line break is represented by a
newline character"""
Logging.trace(">>")
physicalLineListLength = len(physicalLineList)
lineList = []
logicalLine = ""
# a line is broken when it ends in some non-whitespace character
# that follows a double quote without a tab
continuationRegexp = re.compile(r"\t\" *[^\t \"][^\t\"]*$")
physicalLineNumberList = []
firstPhysicalLineNumber = 1
for i in range(physicalLineListLength):
line = physicalLineList[i].rstrip("\n")
logicalLine += ("" if logicalLine == "" else "\n") + line
if continuationRegexp.search(logicalLine):
Logging.trace("--: line %d is continued", i + 1)
else:
lineList.append(logicalLine)
physicalLineNumberList.append(firstPhysicalLineNumber)
firstPhysicalLineNumber = i + 2
logicalLine = ""
if logicalLine > "":
lineList.append(logicalLine)
physicalLineNumberList.append(firstPhysicalLineNumber)
Logging.trace("<<")
return (lineList, physicalLineNumberList)
#--------------------
# EXPORTED FEATURES
#--------------------
def __init__ (self,
commentIndicator : String,
tableNameIndicator : String,
fieldSeparator : String):
"""Sets up table file with technical parameters <commentIndicator>,
<tableNameIndicator> and <fieldSeparator> for subsequent
read or write of a file"""
Logging.trace(">>: commentIndicator = %r, tableNameIndicator = %r,"
+ " fieldSeparator = %r",
commentIndicator, tableNameIndicator, fieldSeparator)
self._commentIndicator = commentIndicator
self._tableNameIndicator = tableNameIndicator
self._fieldSeparator = fieldSeparator
Logging.trace("<<")
#--------------------
def read (self,
fileName : String) -> StringMap:
"""Reads tabular data from a self-describing TSV text file; the
structure returned is a map from table name to lists of element
entries; each element entry is a mapping from field name to
associated value"""
Logging.trace(">>: %r", fileName)
cls = self.__class__
# read lines from file
file = UTF8File(fileName, "r")
physicalLineList = file.readlines()
file.close()
# <lineList> is a list of line _without_ terminating newlines
lineList, physicalLineNumberList = \
cls._combineToLogicalLines(physicalLineList)
# traverse logical lines and split them into the table data
result = {}
previousLineWasTableName = False
separator = self._fieldSeparator
for i, line in enumerate(lineList):
lineNumber = physicalLineNumberList[i]
Logging.trace("--: line %05d: %r",
lineNumber, line.replace("\n", "#"))
if len(line) == 0 or line.startswith(self._commentIndicator):
pass
elif line.startswith(self._tableNameIndicator):
# line contains table name
tableName = line[len(self._tableNameIndicator):].strip()
result[tableName] = []
elementList = result[tableName]
previousLineWasTableName = True
Logging.trace("--: new table - %r", tableName)
elif previousLineWasTableName:
# line contains the tab-separated table headings
line = "%s%s%s" % (cls._lineNumberFieldName,
separator, line)
headingList = splitAndStrip(line, separator)
previousLineWasTableName = False
Logging.trace("--: headings = %r", headingList)
else:
# line (hopefully) contains an element
line = "%d%s%s" % (lineNumber, separator, line)
valueList = splitAndStrip(line, separator)
element = {}
count = min(len(headingList), len(valueList))
if len(headingList) != len(valueList):
Logging.traceError("length mismatch in physical"
+ " line %d",
lineNumber)
for j in range(count):
key = headingList[j]
value = valueList[j]
element[key] = value
elementList.append(element)
Logging.trace("--: new element = %r", element)
Logging.trace("<<")
return result
|
[
"class",
"TableFile",
":",
"_lineNumberFieldName",
"=",
"\"LINENUM\"",
"@",
"classmethod",
"def",
"_combineToLogicalLines",
"(",
"cls",
",",
"physicalLineList",
":",
"StringList",
")",
"->",
"Tuple",
":",
"\"\"\"Combines physical lines in <physicalLineList> into logical\n lines; when some field value is broken across lines that\n line is merged and the line break is represented by a\n newline character\"\"\"",
"Logging",
".",
"trace",
"(",
"\">>\"",
")",
"physicalLineListLength",
"=",
"len",
"(",
"physicalLineList",
")",
"lineList",
"=",
"[",
"]",
"logicalLine",
"=",
"\"\"",
"continuationRegexp",
"=",
"re",
".",
"compile",
"(",
"r\"\\t\\\" *[^\\t \\\"][^\\t\\\"]*$\"",
")",
"physicalLineNumberList",
"=",
"[",
"]",
"firstPhysicalLineNumber",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"physicalLineListLength",
")",
":",
"line",
"=",
"physicalLineList",
"[",
"i",
"]",
".",
"rstrip",
"(",
"\"\\n\"",
")",
"logicalLine",
"+=",
"(",
"\"\"",
"if",
"logicalLine",
"==",
"\"\"",
"else",
"\"\\n\"",
")",
"+",
"line",
"if",
"continuationRegexp",
".",
"search",
"(",
"logicalLine",
")",
":",
"Logging",
".",
"trace",
"(",
"\"--: line %d is continued\"",
",",
"i",
"+",
"1",
")",
"else",
":",
"lineList",
".",
"append",
"(",
"logicalLine",
")",
"physicalLineNumberList",
".",
"append",
"(",
"firstPhysicalLineNumber",
")",
"firstPhysicalLineNumber",
"=",
"i",
"+",
"2",
"logicalLine",
"=",
"\"\"",
"if",
"logicalLine",
">",
"\"\"",
":",
"lineList",
".",
"append",
"(",
"logicalLine",
")",
"physicalLineNumberList",
".",
"append",
"(",
"firstPhysicalLineNumber",
")",
"Logging",
".",
"trace",
"(",
"\"<<\"",
")",
"return",
"(",
"lineList",
",",
"physicalLineNumberList",
")",
"def",
"__init__",
"(",
"self",
",",
"commentIndicator",
":",
"String",
",",
"tableNameIndicator",
":",
"String",
",",
"fieldSeparator",
":",
"String",
")",
":",
"\"\"\"Sets up table file with technical parameters <commentIndicator>,\n <tableNameIndicator> and <fieldSeparator> for subsequent\n read or write of a file\"\"\"",
"Logging",
".",
"trace",
"(",
"\">>: commentIndicator = %r, tableNameIndicator = %r,\"",
"+",
"\" fieldSeparator = %r\"",
",",
"commentIndicator",
",",
"tableNameIndicator",
",",
"fieldSeparator",
")",
"self",
".",
"_commentIndicator",
"=",
"commentIndicator",
"self",
".",
"_tableNameIndicator",
"=",
"tableNameIndicator",
"self",
".",
"_fieldSeparator",
"=",
"fieldSeparator",
"Logging",
".",
"trace",
"(",
"\"<<\"",
")",
"def",
"read",
"(",
"self",
",",
"fileName",
":",
"String",
")",
"->",
"StringMap",
":",
"\"\"\"Reads tabular data from a self-describing TSV text file; the\n structure returned is a map from table name to lists of element\n entries; each element entry is a mapping from field name to\n associated value\"\"\"",
"Logging",
".",
"trace",
"(",
"\">>: %r\"",
",",
"fileName",
")",
"cls",
"=",
"self",
".",
"__class__",
"file",
"=",
"UTF8File",
"(",
"fileName",
",",
"\"r\"",
")",
"physicalLineList",
"=",
"file",
".",
"readlines",
"(",
")",
"file",
".",
"close",
"(",
")",
"lineList",
",",
"physicalLineNumberList",
"=",
"cls",
".",
"_combineToLogicalLines",
"(",
"physicalLineList",
")",
"result",
"=",
"{",
"}",
"previousLineWasTableName",
"=",
"False",
"separator",
"=",
"self",
".",
"_fieldSeparator",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"lineList",
")",
":",
"lineNumber",
"=",
"physicalLineNumberList",
"[",
"i",
"]",
"Logging",
".",
"trace",
"(",
"\"--: line %05d: %r\"",
",",
"lineNumber",
",",
"line",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"#\"",
")",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
"or",
"line",
".",
"startswith",
"(",
"self",
".",
"_commentIndicator",
")",
":",
"pass",
"elif",
"line",
".",
"startswith",
"(",
"self",
".",
"_tableNameIndicator",
")",
":",
"tableName",
"=",
"line",
"[",
"len",
"(",
"self",
".",
"_tableNameIndicator",
")",
":",
"]",
".",
"strip",
"(",
")",
"result",
"[",
"tableName",
"]",
"=",
"[",
"]",
"elementList",
"=",
"result",
"[",
"tableName",
"]",
"previousLineWasTableName",
"=",
"True",
"Logging",
".",
"trace",
"(",
"\"--: new table - %r\"",
",",
"tableName",
")",
"elif",
"previousLineWasTableName",
":",
"line",
"=",
"\"%s%s%s\"",
"%",
"(",
"cls",
".",
"_lineNumberFieldName",
",",
"separator",
",",
"line",
")",
"headingList",
"=",
"splitAndStrip",
"(",
"line",
",",
"separator",
")",
"previousLineWasTableName",
"=",
"False",
"Logging",
".",
"trace",
"(",
"\"--: headings = %r\"",
",",
"headingList",
")",
"else",
":",
"line",
"=",
"\"%d%s%s\"",
"%",
"(",
"lineNumber",
",",
"separator",
",",
"line",
")",
"valueList",
"=",
"splitAndStrip",
"(",
"line",
",",
"separator",
")",
"element",
"=",
"{",
"}",
"count",
"=",
"min",
"(",
"len",
"(",
"headingList",
")",
",",
"len",
"(",
"valueList",
")",
")",
"if",
"len",
"(",
"headingList",
")",
"!=",
"len",
"(",
"valueList",
")",
":",
"Logging",
".",
"traceError",
"(",
"\"length mismatch in physical\"",
"+",
"\" line %d\"",
",",
"lineNumber",
")",
"for",
"j",
"in",
"range",
"(",
"count",
")",
":",
"key",
"=",
"headingList",
"[",
"j",
"]",
"value",
"=",
"valueList",
"[",
"j",
"]",
"element",
"[",
"key",
"]",
"=",
"value",
"elementList",
".",
"append",
"(",
"element",
")",
"Logging",
".",
"trace",
"(",
"\"--: new element = %r\"",
",",
"element",
")",
"Logging",
".",
"trace",
"(",
"\"<<\"",
")",
"return",
"result"
] |
Provides reading from a text file containing several tables with
fields separated by a specific character; the assumption is
that table rows are defined by a trailing newline, but some
consolidation is done for newlines embedded in string fields;
the only service offered is to read some text file given by
name and return a mapping from table name to a list of table
rows with mappings from key to values
|
[
"Provides",
"reading",
"from",
"a",
"text",
"file",
"containing",
"several",
"tables",
"with",
"fields",
"separated",
"by",
"a",
"specific",
"character",
";",
"the",
"assumption",
"is",
"that",
"table",
"rows",
"are",
"defined",
"by",
"a",
"trailing",
"newline",
"but",
"some",
"consolidation",
"is",
"done",
"for",
"newlines",
"embedded",
"in",
"string",
"fields",
";",
"the",
"only",
"service",
"offered",
"is",
"to",
"read",
"some",
"text",
"file",
"given",
"by",
"name",
"and",
"return",
"a",
"mapping",
"from",
"table",
"name",
"to",
"a",
"list",
"of",
"table",
"rows",
"with",
"mappings",
"from",
"key",
"to",
"values"
] |
[
"\"\"\"Provides reading from a text file containing several tables with\n fields separated by a specific character; the assumption is\n that table rows are defined by a trailing newline, but some\n consolidation is done for newlines embedded in string fields;\n the only service offered is to read some text file given by\n name and return a mapping from table name to a list of table\n rows with mappings from key to values\"\"\"",
"#--------------------",
"# INTERNAL FEATURES",
"#--------------------",
"# the name of the synthesized field containing the line number in",
"# the physical file",
"#--------------------",
"\"\"\"Combines physical lines in <physicalLineList> into logical\n lines; when some field value is broken across lines that\n line is merged and the line break is represented by a\n newline character\"\"\"",
"# a line is broken when it ends in some non-whitespace character",
"# that follows a double quote without a tab",
"#--------------------",
"# EXPORTED FEATURES",
"#--------------------",
"\"\"\"Sets up table file with technical parameters <commentIndicator>,\n <tableNameIndicator> and <fieldSeparator> for subsequent\n read or write of a file\"\"\"",
"#--------------------",
"\"\"\"Reads tabular data from a self-describing TSV text file; the\n structure returned is a map from table name to lists of element\n entries; each element entry is a mapping from field name to\n associated value\"\"\"",
"# read lines from file",
"# <lineList> is a list of line _without_ terminating newlines",
"# traverse logical lines and split them into the table data",
"# line contains table name",
"# line contains the tab-separated table headings",
"# line (hopefully) contains an element"
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 19
| 1,122
| 86
|
e4b5bf7f65624c523c53cc257fc8524a464340f9
|
fakeNetflix/facebook-repo-taste-tester
|
lib/taste_tester/tunnel.rb
|
[
"Apache-2.0"
] |
Ruby
|
TasteTester
|
# Copyright 2013-present Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module TasteTester
# Thin ssh tunnel wrapper
class Tunnel
include TasteTester::Logging
include BetweenMeals::Util
attr_reader :port
def initialize(host, server)
@host = host
@server = server
if TasteTester::Config.testing_until
@delta_secs = TasteTester::Config.testing_until.strftime('%s').to_i -
Time.now.strftime('%s').to_i
else
@delta_secs = TasteTester::Config.testing_time
end
end
def run
@port = TasteTester::Config.tunnel_port
logger.info("Setting up tunnel on port #{@port}")
exec!(cmd, logger)
rescue StandardError => e
logger.error "Failed bringing up ssh tunnel: #{e}"
exit(1)
end
def cmd
@max_ping = @delta_secs / 10
pid = '$$'
@ts = TasteTester::Config.testing_end_time.strftime('%y%m%d%H%M.%S')
cmds = "ps -o pgid= -p $(ps -o ppid= -p #{pid}) | sed \"s| ||g\" " +
" > #{TasteTester::Config.timestamp_file} &&" +
" touch -t #{@ts} #{TasteTester::Config.timestamp_file} &&" +
" sleep #{@delta_secs}"
# As great as it would be to have ExitOnForwardFailure=yes,
# we had multiple cases of tunnels dying
# if -f and ExitOnForwardFailure are used together.
# In most cases the first request from chef was "breaking" the tunnel,
# in a way that port was still open, but subsequent requests were hanging.
# This is reproducible and should be looked into.
cmd = "#{TasteTester::Config.ssh_command} " +
"-o ConnectTimeout=#{TasteTester::Config.ssh_connect_timeout} " +
'-T -o BatchMode=yes ' +
'-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' +
"-o ServerAliveInterval=10 -o ServerAliveCountMax=#{@max_ping} " +
"-f -R #{@port}:localhost:#{@server.port} "
if TasteTester::Config.user != 'root'
cc = Base64.encode64(cmds).delete("\n")
cmd += "#{TasteTester::Config.user}@#{@host} \"echo '#{cc}' | base64" +
' --decode | sudo bash -x"'
else
cmd += "root@#{@host} '#{cmds}'"
end
cmd
end
def self.kill(name)
ssh = TasteTester::SSH.new(name)
# Since commands are &&'d together, and we're using &&, we need to
# surround this in paryns, and make sure as a whole it evaluates
# to true so it doesn't mess up other things... even though this is
# the only thing we're currently executing in this SSH.
if TasteTester::Config.user != 'root'
sudo = 'sudo '
end
cmd = "( [ -s #{TasteTester::Config.timestamp_file} ]" +
" && #{sudo}kill -9 -- " +
"-\$(cat #{TasteTester::Config.timestamp_file}) 2>/dev/null; " +
' true )'
ssh << cmd
ssh.run!
end
end
end
|
[
"module",
"TasteTester",
"class",
"Tunnel",
"include",
"TasteTester",
"::",
"Logging",
"include",
"BetweenMeals",
"::",
"Util",
"attr_reader",
":port",
"def",
"initialize",
"(",
"host",
",",
"server",
")",
"@host",
"=",
"host",
"@server",
"=",
"server",
"if",
"TasteTester",
"::",
"Config",
".",
"testing_until",
"@delta_secs",
"=",
"TasteTester",
"::",
"Config",
".",
"testing_until",
".",
"strftime",
"(",
"'%s'",
")",
".",
"to_i",
"-",
"Time",
".",
"now",
".",
"strftime",
"(",
"'%s'",
")",
".",
"to_i",
"else",
"@delta_secs",
"=",
"TasteTester",
"::",
"Config",
".",
"testing_time",
"end",
"end",
"def",
"run",
"@port",
"=",
"TasteTester",
"::",
"Config",
".",
"tunnel_port",
"logger",
".",
"info",
"(",
"\"Setting up tunnel on port #{@port}\"",
")",
"exec!",
"(",
"cmd",
",",
"logger",
")",
"rescue",
"StandardError",
"=>",
"e",
"logger",
".",
"error",
"\"Failed bringing up ssh tunnel: #{e}\"",
"exit",
"(",
"1",
")",
"end",
"def",
"cmd",
"@max_ping",
"=",
"@delta_secs",
"/",
"10",
"pid",
"=",
"'$$'",
"@ts",
"=",
"TasteTester",
"::",
"Config",
".",
"testing_end_time",
".",
"strftime",
"(",
"'%y%m%d%H%M.%S'",
")",
"cmds",
"=",
"\"ps -o pgid= -p $(ps -o ppid= -p #{pid}) | sed \\\"s| ||g\\\" \"",
"+",
"\" > #{TasteTester::Config.timestamp_file} &&\"",
"+",
"\" touch -t #{@ts} #{TasteTester::Config.timestamp_file} &&\"",
"+",
"\" sleep #{@delta_secs}\"",
"cmd",
"=",
"\"#{TasteTester::Config.ssh_command} \"",
"+",
"\"-o ConnectTimeout=#{TasteTester::Config.ssh_connect_timeout} \"",
"+",
"'-T -o BatchMode=yes '",
"+",
"'-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no '",
"+",
"\"-o ServerAliveInterval=10 -o ServerAliveCountMax=#{@max_ping} \"",
"+",
"\"-f -R #{@port}:localhost:#{@server.port} \"",
"if",
"TasteTester",
"::",
"Config",
".",
"user",
"!=",
"'root'",
"cc",
"=",
"Base64",
".",
"encode64",
"(",
"cmds",
")",
".",
"delete",
"(",
"\"\\n\"",
")",
"cmd",
"+=",
"\"#{TasteTester::Config.user}@#{@host} \\\"echo '#{cc}' | base64\"",
"+",
"' --decode | sudo bash -x\"'",
"else",
"cmd",
"+=",
"\"root@#{@host} '#{cmds}'\"",
"end",
"cmd",
"end",
"def",
"self",
".",
"kill",
"(",
"name",
")",
"ssh",
"=",
"TasteTester",
"::",
"SSH",
".",
"new",
"(",
"name",
")",
"if",
"TasteTester",
"::",
"Config",
".",
"user",
"!=",
"'root'",
"sudo",
"=",
"'sudo '",
"end",
"cmd",
"=",
"\"( [ -s #{TasteTester::Config.timestamp_file} ]\"",
"+",
"\" && #{sudo}kill -9 -- \"",
"+",
"\"-\\$(cat #{TasteTester::Config.timestamp_file}) 2>/dev/null; \"",
"+",
"' true )'",
"ssh",
"<<",
"cmd",
"ssh",
".",
"run!",
"end",
"end",
"end"
] |
Copyright 2013-present Facebook
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
|
[
"Copyright",
"2013",
"-",
"present",
"Facebook",
"Licensed",
"under",
"the",
"Apache",
"License",
"Version",
"2",
".",
"0",
"(",
"the",
"\"",
"License",
"\"",
")",
";",
"you",
"may",
"not",
"use",
"this",
"file",
"except",
"in",
"compliance",
"with",
"the",
"License",
"."
] |
[
"# Thin ssh tunnel wrapper",
"# As great as it would be to have ExitOnForwardFailure=yes,",
"# we had multiple cases of tunnels dying",
"# if -f and ExitOnForwardFailure are used together.",
"# In most cases the first request from chef was \"breaking\" the tunnel,",
"# in a way that port was still open, but subsequent requests were hanging.",
"# This is reproducible and should be looked into.",
"# Since commands are &&'d together, and we're using &&, we need to",
"# surround this in paryns, and make sure as a whole it evaluates",
"# to true so it doesn't mess up other things... even though this is",
"# the only thing we're currently executing in this SSH."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 748
| 130
|
6bfa780f448377c58ba44160564a14f81393d587
|
XandraAI/syn-speech
|
Syn.Speech/FrontEnds/EndPoint/WienerFilter.cs
|
[
"BSD-3-Clause"
] |
C#
|
WienerFilter
|
/// <summary>
/// The noise Wiener filter. Parameters are taken from the article
/// "An Effective Subband OSF-Based VAD With Noise Reduction
/// for Robust Speech Recognition" by Ramirez et all. IEEE
/// Transactions on Speech And Audio Processing, Vol 13, No 6, 2005
/// <br />
/// Subband VAD is not implemented yet, default endpointer is used.
/// The frontend configuration with filtering should look like:
/// <br /><br />
/// <item>audioFileDataSource </item><br />
/// <item>dataBlocker </item><br />
/// <item>preemphasizer </item><br />
/// <item>windower </item><br />
/// <item>fft </item><br />
/// <item>wiener </item><br />
/// <item>speechClassifier </item><br />
/// <item>speechMarker </item><br />
/// <item>nonSpeechDataFilter </item><br />
/// <item>melFilterBank </item><br />
/// <item>dct </item><br />
/// <item>liveCMN </item><br />
/// <item>featureExtraction </item><br />
/// </summary>
|
The noise Wiener filter. Parameters are taken from the article
"An Effective Subband OSF-Based VAD With Noise Reduction
for Robust Speech Recognition" by Ramirez et all. IEEE
Transactions on Speech And Audio Processing, Vol 13, No 6, 2005
Subband VAD is not implemented yet, default endpointer is used.
The frontend configuration with filtering should look like.
audioFileDataSource
dataBlocker
preemphasizer
windower
fft
wiener
speechClassifier
speechMarker
nonSpeechDataFilter
melFilterBank
dct
liveCMN
featureExtraction
|
[
"The",
"noise",
"Wiener",
"filter",
".",
"Parameters",
"are",
"taken",
"from",
"the",
"article",
"\"",
"An",
"Effective",
"Subband",
"OSF",
"-",
"Based",
"VAD",
"With",
"Noise",
"Reduction",
"for",
"Robust",
"Speech",
"Recognition",
"\"",
"by",
"Ramirez",
"et",
"all",
".",
"IEEE",
"Transactions",
"on",
"Speech",
"And",
"Audio",
"Processing",
"Vol",
"13",
"No",
"6",
"2005",
"Subband",
"VAD",
"is",
"not",
"implemented",
"yet",
"default",
"endpointer",
"is",
"used",
".",
"The",
"frontend",
"configuration",
"with",
"filtering",
"should",
"look",
"like",
".",
"audioFileDataSource",
"dataBlocker",
"preemphasizer",
"windower",
"fft",
"wiener",
"speechClassifier",
"speechMarker",
"nonSpeechDataFilter",
"melFilterBank",
"dct",
"liveCMN",
"featureExtraction"
] |
public class WienerFilter : BaseDataProcessor
{
double[] _prevNoise;
double[] _prevSignal;
double[] _prevInput;
private const double Lambda = 0.99;
private const double Gamma = 0.98;
private const double EtaMin = 1e-2;
protected AbstractVoiceActivityDetector Classifier;
[S4Component(Type = typeof(AbstractVoiceActivityDetector))]
public static string PropClassifier = "classifier";
public override void NewProperties(PropertySheet ps)
{
base.NewProperties(ps);
Classifier = (AbstractVoiceActivityDetector)ps.GetComponent(PropClassifier);
}
public override IData GetData()
{
IData inputData = Predecessor.GetData();
if (!(inputData is DoubleData))
{
_prevNoise = null;
_prevSignal = null;
_prevInput = null;
return inputData;
}
DoubleData inputDoubleData = (DoubleData)inputData;
double[] input = inputDoubleData.Values;
int length = input.Length;
if (_prevNoise == null)
{
_prevNoise = new double[length];
_prevSignal = new double[length];
_prevInput = new double[length];
return inputData;
}
double[] smoothedInput = Smooth(input);
double[] noise = EstimateNoise(smoothedInput);
double[] signal = Filter(input, smoothedInput, noise);
Array.Copy(noise, 0, _prevNoise, 0, length);
Array.Copy(signal, 0, _prevSignal, 0, length);
Array.Copy(input, 0, _prevInput, 0, length);
DoubleData outputData = new DoubleData(signal, inputDoubleData.SampleRate,
inputDoubleData.FirstSampleNumber);
return outputData;
}
private double[] Filter(double[] input, double[] smoothedInput, double[] noise)
{
int length = input.Length;
double[] signal = new double[length];
for (int i = 0; i < length; i++)
{
double max = Math.Max(smoothedInput[i] - noise[i], 0);
double s = Gamma * _prevSignal[i] + (1 - Gamma) * max;
double eta = Math.Max(s / noise[i], EtaMin);
signal[i] = eta / (1 + eta) * input[i];
}
return signal;
}
private double[] EstimateNoise(double[] smoothedInput)
{
int length = smoothedInput.Length;
double[] noise = new double[length];
for (int i = 0; i < length; i++)
{
if (Classifier.IsSpeech)
{
noise[i] = _prevNoise[i];
}
else
{
noise[i] = Lambda * _prevNoise[i] + (1 - Lambda)
* smoothedInput[i];
}
}
return noise;
}
private double[] Smooth(double[] input)
{
int length = input.Length;
double[] smoothedInput = new double[length];
for (int i = 1; i < length - 1; i++)
{
smoothedInput[i] = (input[i] + input[i - 1] + input[i + 1] + _prevInput[i]) / 4;
}
smoothedInput[0] = (input[0] + input[1] + _prevInput[0]) / 3;
smoothedInput[length - 1] = (input[length - 1] + input[length - 2] + _prevInput[length - 1]) / 3;
return smoothedInput;
}
}
|
[
"public",
"class",
"WienerFilter",
":",
"BaseDataProcessor",
"{",
"double",
"[",
"]",
"_prevNoise",
";",
"double",
"[",
"]",
"_prevSignal",
";",
"double",
"[",
"]",
"_prevInput",
";",
"private",
"const",
"double",
"Lambda",
"=",
"0.99",
";",
"private",
"const",
"double",
"Gamma",
"=",
"0.98",
";",
"private",
"const",
"double",
"EtaMin",
"=",
"1e-2",
";",
"protected",
"AbstractVoiceActivityDetector",
"Classifier",
";",
"[",
"S4Component",
"(",
"Type",
"=",
"typeof",
"(",
"AbstractVoiceActivityDetector",
")",
")",
"]",
"public",
"static",
"string",
"PropClassifier",
"=",
"\"",
"classifier",
"\"",
";",
"public",
"override",
"void",
"NewProperties",
"(",
"PropertySheet",
"ps",
")",
"{",
"base",
".",
"NewProperties",
"(",
"ps",
")",
";",
"Classifier",
"=",
"(",
"AbstractVoiceActivityDetector",
")",
"ps",
".",
"GetComponent",
"(",
"PropClassifier",
")",
";",
"}",
"public",
"override",
"IData",
"GetData",
"(",
")",
"{",
"IData",
"inputData",
"=",
"Predecessor",
".",
"GetData",
"(",
")",
";",
"if",
"(",
"!",
"(",
"inputData",
"is",
"DoubleData",
")",
")",
"{",
"_prevNoise",
"=",
"null",
";",
"_prevSignal",
"=",
"null",
";",
"_prevInput",
"=",
"null",
";",
"return",
"inputData",
";",
"}",
"DoubleData",
"inputDoubleData",
"=",
"(",
"DoubleData",
")",
"inputData",
";",
"double",
"[",
"]",
"input",
"=",
"inputDoubleData",
".",
"Values",
";",
"int",
"length",
"=",
"input",
".",
"Length",
";",
"if",
"(",
"_prevNoise",
"==",
"null",
")",
"{",
"_prevNoise",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"_prevSignal",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"_prevInput",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"return",
"inputData",
";",
"}",
"double",
"[",
"]",
"smoothedInput",
"=",
"Smooth",
"(",
"input",
")",
";",
"double",
"[",
"]",
"noise",
"=",
"EstimateNoise",
"(",
"smoothedInput",
")",
";",
"double",
"[",
"]",
"signal",
"=",
"Filter",
"(",
"input",
",",
"smoothedInput",
",",
"noise",
")",
";",
"Array",
".",
"Copy",
"(",
"noise",
",",
"0",
",",
"_prevNoise",
",",
"0",
",",
"length",
")",
";",
"Array",
".",
"Copy",
"(",
"signal",
",",
"0",
",",
"_prevSignal",
",",
"0",
",",
"length",
")",
";",
"Array",
".",
"Copy",
"(",
"input",
",",
"0",
",",
"_prevInput",
",",
"0",
",",
"length",
")",
";",
"DoubleData",
"outputData",
"=",
"new",
"DoubleData",
"(",
"signal",
",",
"inputDoubleData",
".",
"SampleRate",
",",
"inputDoubleData",
".",
"FirstSampleNumber",
")",
";",
"return",
"outputData",
";",
"}",
"private",
"double",
"[",
"]",
"Filter",
"(",
"double",
"[",
"]",
"input",
",",
"double",
"[",
"]",
"smoothedInput",
",",
"double",
"[",
"]",
"noise",
")",
"{",
"int",
"length",
"=",
"input",
".",
"Length",
";",
"double",
"[",
"]",
"signal",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"double",
"max",
"=",
"Math",
".",
"Max",
"(",
"smoothedInput",
"[",
"i",
"]",
"-",
"noise",
"[",
"i",
"]",
",",
"0",
")",
";",
"double",
"s",
"=",
"Gamma",
"*",
"_prevSignal",
"[",
"i",
"]",
"+",
"(",
"1",
"-",
"Gamma",
")",
"*",
"max",
";",
"double",
"eta",
"=",
"Math",
".",
"Max",
"(",
"s",
"/",
"noise",
"[",
"i",
"]",
",",
"EtaMin",
")",
";",
"signal",
"[",
"i",
"]",
"=",
"eta",
"/",
"(",
"1",
"+",
"eta",
")",
"*",
"input",
"[",
"i",
"]",
";",
"}",
"return",
"signal",
";",
"}",
"private",
"double",
"[",
"]",
"EstimateNoise",
"(",
"double",
"[",
"]",
"smoothedInput",
")",
"{",
"int",
"length",
"=",
"smoothedInput",
".",
"Length",
";",
"double",
"[",
"]",
"noise",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"Classifier",
".",
"IsSpeech",
")",
"{",
"noise",
"[",
"i",
"]",
"=",
"_prevNoise",
"[",
"i",
"]",
";",
"}",
"else",
"{",
"noise",
"[",
"i",
"]",
"=",
"Lambda",
"*",
"_prevNoise",
"[",
"i",
"]",
"+",
"(",
"1",
"-",
"Lambda",
")",
"*",
"smoothedInput",
"[",
"i",
"]",
";",
"}",
"}",
"return",
"noise",
";",
"}",
"private",
"double",
"[",
"]",
"Smooth",
"(",
"double",
"[",
"]",
"input",
")",
"{",
"int",
"length",
"=",
"input",
".",
"Length",
";",
"double",
"[",
"]",
"smoothedInput",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"length",
"-",
"1",
";",
"i",
"++",
")",
"{",
"smoothedInput",
"[",
"i",
"]",
"=",
"(",
"input",
"[",
"i",
"]",
"+",
"input",
"[",
"i",
"-",
"1",
"]",
"+",
"input",
"[",
"i",
"+",
"1",
"]",
"+",
"_prevInput",
"[",
"i",
"]",
")",
"/",
"4",
";",
"}",
"smoothedInput",
"[",
"0",
"]",
"=",
"(",
"input",
"[",
"0",
"]",
"+",
"input",
"[",
"1",
"]",
"+",
"_prevInput",
"[",
"0",
"]",
")",
"/",
"3",
";",
"smoothedInput",
"[",
"length",
"-",
"1",
"]",
"=",
"(",
"input",
"[",
"length",
"-",
"1",
"]",
"+",
"input",
"[",
"length",
"-",
"2",
"]",
"+",
"_prevInput",
"[",
"length",
"-",
"1",
"]",
")",
"/",
"3",
";",
"return",
"smoothedInput",
";",
"}",
"}"
] |
The noise Wiener filter.
|
[
"The",
"noise",
"Wiener",
"filter",
"."
] |
[
"/// <summary>",
"/// The name of the transform matrix file.",
"/// </summary>",
"/* signal, reset smoother */",
"/* no previous data, just return input */"
] |
[
{
"param": "BaseDataProcessor",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "BaseDataProcessor",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 18
| 779
| 338
|
3c642be86aa9ca687a598432e2f1c563157c9d01
|
cruizer/dup-composer
|
dupcomposer/backup_config.py
|
[
"MIT"
] |
Python
|
BackupSource
|
Path object for the source, backup and restore target.
:param source_path: The path to be backed up.
:type source_path: str
:param config: raw config data for the target of the backup/restore.
:type config: dict
:param provider: The URL scheme target to backup to / restore from.
:type provider: class:`BackupProviderLocal`, class:`BackupProviderS3`,
class:`BackupProviderSSH`
:raises ValueError: if the source or backup path is empty.
|
Path object for the source, backup and restore target.
|
[
"Path",
"object",
"for",
"the",
"source",
"backup",
"and",
"restore",
"target",
"."
] |
class BackupSource:
"""Path object for the source, backup and restore target.
:param source_path: The path to be backed up.
:type source_path: str
:param config: raw config data for the target of the backup/restore.
:type config: dict
:param provider: The URL scheme target to backup to / restore from.
:type provider: class:`BackupProviderLocal`, class:`BackupProviderS3`,
class:`BackupProviderSSH`
:raises ValueError: if the source or backup path is empty.
"""
def __init__(self, source_path, config, provider):
self.source_path = source_path
self.backup_path = config['backup_path']
self.restore_path = config.get('restore_path', None)
self.provider = provider
if (len(self.source_path) == 0 or
len(self.backup_path) == 0):
raise ValueError('Empty path is not allowed.')
self._check_forbidden_chars()
self.filters = BackupPathFilter(config.get('filters', None))
def get_cmd(self, mode='backup'):
"""Get the source and target path for the given action.
The provider will append the backup_path to the provider URL
scheme, to form the fully qualified path to backup to or
restore from.
:param mode: Duplicity command, either 'backup' or 'restore'.
:type mode: str
:raises ValueError: if the mode is neither 'backup' nor 'restore',
or if no restore path is defined and we do
a restore.
:return: A list of the source and backup; backup and restore
path, depending on the mode (action).
:rtype: list
"""
# The Duplicity action is determined by the URL / path order.
if mode == 'backup':
cmd = self.filters.get_cmd()
cmd.extend([self.source_path, self.provider.get_cmd(self.backup_path)])
return cmd
# Include / exclude not supported for restore!
elif mode == 'restore':
if not self.restore_path:
raise ValueError('Restore path is not defined in the configuration.')
return [self.provider.get_cmd(self.backup_path),
self.restore_path]
else:
raise ValueError('Invalid mode parameter.')
def _check_forbidden_chars(self):
# Detect control chars + backslash
for p in [self.source_path,
self.backup_path,
self.restore_path]:
# In case restore_path is empty
if not p: continue
if (p[0] == '-' or
re.search(r'[\x00-\x1f\x7f\\]', p)):
raise ValueError('Leading hyphens, control characters '
'and backslash are not allowed in '
'the path configuration.')
|
[
"class",
"BackupSource",
":",
"def",
"__init__",
"(",
"self",
",",
"source_path",
",",
"config",
",",
"provider",
")",
":",
"self",
".",
"source_path",
"=",
"source_path",
"self",
".",
"backup_path",
"=",
"config",
"[",
"'backup_path'",
"]",
"self",
".",
"restore_path",
"=",
"config",
".",
"get",
"(",
"'restore_path'",
",",
"None",
")",
"self",
".",
"provider",
"=",
"provider",
"if",
"(",
"len",
"(",
"self",
".",
"source_path",
")",
"==",
"0",
"or",
"len",
"(",
"self",
".",
"backup_path",
")",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'Empty path is not allowed.'",
")",
"self",
".",
"_check_forbidden_chars",
"(",
")",
"self",
".",
"filters",
"=",
"BackupPathFilter",
"(",
"config",
".",
"get",
"(",
"'filters'",
",",
"None",
")",
")",
"def",
"get_cmd",
"(",
"self",
",",
"mode",
"=",
"'backup'",
")",
":",
"\"\"\"Get the source and target path for the given action.\n\n The provider will append the backup_path to the provider URL\n scheme, to form the fully qualified path to backup to or\n restore from.\n\n :param mode: Duplicity command, either 'backup' or 'restore'.\n :type mode: str\n :raises ValueError: if the mode is neither 'backup' nor 'restore',\n or if no restore path is defined and we do\n a restore.\n :return: A list of the source and backup; backup and restore\n path, depending on the mode (action).\n :rtype: list\n \"\"\"",
"if",
"mode",
"==",
"'backup'",
":",
"cmd",
"=",
"self",
".",
"filters",
".",
"get_cmd",
"(",
")",
"cmd",
".",
"extend",
"(",
"[",
"self",
".",
"source_path",
",",
"self",
".",
"provider",
".",
"get_cmd",
"(",
"self",
".",
"backup_path",
")",
"]",
")",
"return",
"cmd",
"elif",
"mode",
"==",
"'restore'",
":",
"if",
"not",
"self",
".",
"restore_path",
":",
"raise",
"ValueError",
"(",
"'Restore path is not defined in the configuration.'",
")",
"return",
"[",
"self",
".",
"provider",
".",
"get_cmd",
"(",
"self",
".",
"backup_path",
")",
",",
"self",
".",
"restore_path",
"]",
"else",
":",
"raise",
"ValueError",
"(",
"'Invalid mode parameter.'",
")",
"def",
"_check_forbidden_chars",
"(",
"self",
")",
":",
"for",
"p",
"in",
"[",
"self",
".",
"source_path",
",",
"self",
".",
"backup_path",
",",
"self",
".",
"restore_path",
"]",
":",
"if",
"not",
"p",
":",
"continue",
"if",
"(",
"p",
"[",
"0",
"]",
"==",
"'-'",
"or",
"re",
".",
"search",
"(",
"r'[\\x00-\\x1f\\x7f\\\\]'",
",",
"p",
")",
")",
":",
"raise",
"ValueError",
"(",
"'Leading hyphens, control characters '",
"'and backslash are not allowed in '",
"'the path configuration.'",
")"
] |
Path object for the source, backup and restore target.
|
[
"Path",
"object",
"for",
"the",
"source",
"backup",
"and",
"restore",
"target",
"."
] |
[
"\"\"\"Path object for the source, backup and restore target.\n\n :param source_path: The path to be backed up.\n :type source_path: str\n :param config: raw config data for the target of the backup/restore.\n :type config: dict\n :param provider: The URL scheme target to backup to / restore from.\n :type provider: class:`BackupProviderLocal`, class:`BackupProviderS3`,\n class:`BackupProviderSSH`\n :raises ValueError: if the source or backup path is empty.\n \"\"\"",
"\"\"\"Get the source and target path for the given action.\n\n The provider will append the backup_path to the provider URL\n scheme, to form the fully qualified path to backup to or\n restore from.\n\n :param mode: Duplicity command, either 'backup' or 'restore'.\n :type mode: str\n :raises ValueError: if the mode is neither 'backup' nor 'restore',\n or if no restore path is defined and we do\n a restore.\n :return: A list of the source and backup; backup and restore\n path, depending on the mode (action).\n :rtype: list\n \"\"\"",
"# The Duplicity action is determined by the URL / path order.",
"# Include / exclude not supported for restore!",
"# Detect control chars + backslash",
"# In case restore_path is empty"
] |
[] |
{
"returns": [],
"raises": [
{
"docstring": "if the source or backup path is empty.",
"docstring_tokens": [
"if",
"the",
"source",
"or",
"backup",
"path",
"is",
"empty",
"."
],
"type": "ValueError"
}
],
"params": [],
"outlier_params": [
{
"identifier": "source_path",
"type": null,
"docstring": "The path to be backed up.",
"docstring_tokens": [
"The",
"path",
"to",
"be",
"backed",
"up",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "config",
"type": null,
"docstring": "raw config data for the target of the backup/restore.",
"docstring_tokens": [
"raw",
"config",
"data",
"for",
"the",
"target",
"of",
"the",
"backup",
"/",
"restore",
"."
],
"default": null,
"is_optional": null
},
{
"identifier": "provider",
"type": null,
"docstring": "The URL scheme target to backup to / restore from.",
"docstring_tokens": [
"The",
"URL",
"scheme",
"target",
"to",
"backup",
"to",
"/",
"restore",
"from",
"."
],
"default": null,
"is_optional": null
}
],
"others": []
}
| false
| 14
| 600
| 112
|
b56cae8c41eeccbbbef1cee8d5aa7efa27ae4219
|
edwards695/collide
|
deps/vert.x-1.1.0.final/lib/ruby/core/streams.rb
|
[
"Apache-2.0"
] |
Ruby
|
Vertx
|
# Copyright 2011 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
|
[
"Unless",
"required",
"by",
"applicable",
"law",
"or",
"agreed",
"to",
"in",
"writing",
"software",
"distributed",
"under",
"the",
"License",
"is",
"distributed",
"on",
"an",
"\"",
"AS",
"IS",
"\"",
"BASIS",
"WITHOUT",
"WARRANTIES",
"OR",
"CONDITIONS",
"OF",
"ANY",
"KIND",
"either",
"express",
"or",
"implied",
".",
"See",
"the",
"License",
"for",
"the",
"specific",
"language",
"governing",
"permissions",
"and",
"limitations",
"under",
"the",
"License",
"."
] |
module Vertx
# A mixin module which represents a stream of data that can be written to.
#
# Any class that mixes in this module can be used by a {Pump} to pump data from a {ReadStream} to it.
#
# @author {http://tfox.org Tim Fox}
module WriteStream
# Write some data to the stream. The data is put on an internal write queue, and the write actually happens
# asynchronously. To avoid running out of memory by putting too much on the write queue,
# check the {#write_queue_full?} method before writing. This is done automatically if using a {Pump}.
# @param [Buffer]. The buffer to write.
def write_buffer(buff)
@j_del.writeBuffer(buff._to_java_buffer)
end
# Set the maximum size of the write queue. You will still be able to write to the stream even
# if there is more data than this in the write queue. This is used as an indicator by classes such as
# {Pump} to provide flow control.
# @param [FixNum] size. The maximum size, in bytes.
def write_queue_max_size=(size)
@j_del.setWriteQueueMaxSize(size)
end
# Is the write queue full?
# @return [Boolean] true if there are more bytes in the write queue than the max write queue size.
def write_queue_full?
@j_del.writeQueueFull
end
# Set a drain handler on the stream. If the write queue is full, then the handler will be called when the write
# queue has been reduced to maxSize / 2. See {Pump} for an example of this being used.
# @param [Block] hndlr. The drain handler
def drain_handler(&hndlr)
@j_del.drainHandler(hndlr)
end
# Set an execption handler on the stream.
# @param [Block] hndlr. The exception handler
def exception_handler(&hndlr)
@j_del.exceptionHandler(hndlr)
end
# @private
def _to_write_stream
@j_del
end
end
# A mixin module which represents a stream of data that can be read from.
#
# Any class that mixes in this module can be used by a {Pump} to pump data from a {ReadStream} to it.
#
# @author {http://tfox.org Tim Fox}
module ReadStream
# Set a data handler. As data is read, the handler will be called with the data.
# @param [Block] hndlr. The data handler
def data_handler(proc = nil, &hndlr)
hndlr = proc if proc
@j_del.dataHandler(Proc.new { |j_buff|
hndlr.call(Buffer.new(j_buff))
})
end
# Pause the ReadStream. After calling this, the ReadStream will aim to send no more data to the {#data_handler}
def pause
@j_del.pause
end
# Resume reading. If the ReadStream has been paused, reading will recommence on it.
def resume
@j_del.resume
end
# Set an execption handler on the stream.
# @param [Block] hndlr. The exception handler
def exception_handler(&hndlr)
@j_del.exceptionHandler(hndlr)
end
# Set an end handler on the stream. Once the stream has ended, and there is no more data to be read, this handler will be called.
# @param [Block] hndlr. The exception handler
def end_handler(&hndlr)
@j_del.endHandler(hndlr)
end
# @private
def _to_read_stream
@j_del
end
end
# Pumps data from a {ReadStream} to a {WriteStream} and performs flow control where necessary to
# prevent the write stream from getting overloaded.
#
# Instances of this class read bytes from a ReadStream and write them to a WriteStream. If data
# can be read faster than it can be written this could result in the write queue of the WriteStream growing
# without bound, eventually causing it to exhaust all available RAM.
# To prevent this, after each write, instances of this class check whether the write queue of the WriteStream
# is full, and if so, the ReadStream is paused, and a {WriteStream#drain_handler} is set on the WriteStream.
# When the WriteStream has processed half of its backlog, the drain_handler will be called,
# which results in the pump resuming the ReadStream.
#
# This class can be used to pump from any {ReadStream} to any { WriteStream},
# e.g. from an {HttpServerRequest} to an {AsyncFile}, or from {NetSocket} to a {WebSocket}.
#
# @author {http://tfox.org Tim Fox}
class Pump
def initialize(read_stream, write_stream)
raise "read_stream is not a ReadStream" if !read_stream.is_a? ReadStream
raise "write_stream is not a WriteStream" if !write_stream.is_a? WriteStream
j_rs = read_stream._to_read_stream
j_ws = write_stream._to_write_stream
@j_pump = org.vertx.java.core.streams.Pump.createPump(j_rs, j_ws)
end
# Set the write queue max size
# @param [FixNum] The write queue max size
def write_queue_max_size=(val)
@j_pump.setWriteQueueMaxSize(val)
end
# Start the Pump. The Pump can be started and stopped multiple times.
def start
@j_pump.start
end
# Stop the Pump. The Pump can be started and stopped multiple times.
def stop
@j_pump.stop
end
# @return [FixNum] Return the total number of bytes pumped by this pump.
def bytes_pumped
@j_pump.getBytesPumped
end
end
end
|
[
"module",
"Vertx",
"module",
"WriteStream",
"def",
"write_buffer",
"(",
"buff",
")",
"@j_del",
".",
"writeBuffer",
"(",
"buff",
".",
"_to_java_buffer",
")",
"end",
"def",
"write_queue_max_size",
"=",
"(",
"size",
")",
"@j_del",
".",
"setWriteQueueMaxSize",
"(",
"size",
")",
"end",
"def",
"write_queue_full?",
"@j_del",
".",
"writeQueueFull",
"end",
"def",
"drain_handler",
"(",
"&",
"hndlr",
")",
"@j_del",
".",
"drainHandler",
"(",
"hndlr",
")",
"end",
"def",
"exception_handler",
"(",
"&",
"hndlr",
")",
"@j_del",
".",
"exceptionHandler",
"(",
"hndlr",
")",
"end",
"def",
"_to_write_stream",
"@j_del",
"end",
"end",
"module",
"ReadStream",
"def",
"data_handler",
"(",
"proc",
"=",
"nil",
",",
"&",
"hndlr",
")",
"hndlr",
"=",
"proc",
"if",
"proc",
"@j_del",
".",
"dataHandler",
"(",
"Proc",
".",
"new",
"{",
"|",
"j_buff",
"|",
"hndlr",
".",
"call",
"(",
"Buffer",
".",
"new",
"(",
"j_buff",
")",
")",
"}",
")",
"end",
"def",
"pause",
"@j_del",
".",
"pause",
"end",
"def",
"resume",
"@j_del",
".",
"resume",
"end",
"def",
"exception_handler",
"(",
"&",
"hndlr",
")",
"@j_del",
".",
"exceptionHandler",
"(",
"hndlr",
")",
"end",
"def",
"end_handler",
"(",
"&",
"hndlr",
")",
"@j_del",
".",
"endHandler",
"(",
"hndlr",
")",
"end",
"def",
"_to_read_stream",
"@j_del",
"end",
"end",
"class",
"Pump",
"def",
"initialize",
"(",
"read_stream",
",",
"write_stream",
")",
"raise",
"\"read_stream is not a ReadStream\"",
"if",
"!",
"read_stream",
".",
"is_a?",
"ReadStream",
"raise",
"\"write_stream is not a WriteStream\"",
"if",
"!",
"write_stream",
".",
"is_a?",
"WriteStream",
"j_rs",
"=",
"read_stream",
".",
"_to_read_stream",
"j_ws",
"=",
"write_stream",
".",
"_to_write_stream",
"@j_pump",
"=",
"org",
".",
"vertx",
".",
"java",
".",
"core",
".",
"streams",
".",
"Pump",
".",
"createPump",
"(",
"j_rs",
",",
"j_ws",
")",
"end",
"def",
"write_queue_max_size",
"=",
"(",
"val",
")",
"@j_pump",
".",
"setWriteQueueMaxSize",
"(",
"val",
")",
"end",
"def",
"start",
"@j_pump",
".",
"start",
"end",
"def",
"stop",
"@j_pump",
".",
"stop",
"end",
"def",
"bytes_pumped",
"@j_pump",
".",
"getBytesPumped",
"end",
"end",
"end"
] |
Copyright 2011 the original author or authors.
|
[
"Copyright",
"2011",
"the",
"original",
"author",
"or",
"authors",
"."
] |
[
"# A mixin module which represents a stream of data that can be written to.",
"#",
"# Any class that mixes in this module can be used by a {Pump} to pump data from a {ReadStream} to it.",
"#",
"# @author {http://tfox.org Tim Fox}",
"# Write some data to the stream. The data is put on an internal write queue, and the write actually happens",
"# asynchronously. To avoid running out of memory by putting too much on the write queue,",
"# check the {#write_queue_full?} method before writing. This is done automatically if using a {Pump}.",
"# @param [Buffer]. The buffer to write.",
"# Set the maximum size of the write queue. You will still be able to write to the stream even",
"# if there is more data than this in the write queue. This is used as an indicator by classes such as",
"# {Pump} to provide flow control.",
"# @param [FixNum] size. The maximum size, in bytes.",
"# Is the write queue full?",
"# @return [Boolean] true if there are more bytes in the write queue than the max write queue size.",
"# Set a drain handler on the stream. If the write queue is full, then the handler will be called when the write",
"# queue has been reduced to maxSize / 2. See {Pump} for an example of this being used.",
"# @param [Block] hndlr. The drain handler",
"# Set an execption handler on the stream.",
"# @param [Block] hndlr. The exception handler",
"# @private",
"# A mixin module which represents a stream of data that can be read from.",
"#",
"# Any class that mixes in this module can be used by a {Pump} to pump data from a {ReadStream} to it.",
"#",
"# @author {http://tfox.org Tim Fox}",
"# Set a data handler. As data is read, the handler will be called with the data.",
"# @param [Block] hndlr. The data handler",
"# Pause the ReadStream. After calling this, the ReadStream will aim to send no more data to the {#data_handler}",
"# Resume reading. If the ReadStream has been paused, reading will recommence on it.",
"# Set an execption handler on the stream.",
"# @param [Block] hndlr. The exception handler",
"# Set an end handler on the stream. Once the stream has ended, and there is no more data to be read, this handler will be called.",
"# @param [Block] hndlr. The exception handler",
"# @private",
"# Pumps data from a {ReadStream} to a {WriteStream} and performs flow control where necessary to",
"# prevent the write stream from getting overloaded.",
"#",
"# Instances of this class read bytes from a ReadStream and write them to a WriteStream. If data",
"# can be read faster than it can be written this could result in the write queue of the WriteStream growing",
"# without bound, eventually causing it to exhaust all available RAM.",
"# To prevent this, after each write, instances of this class check whether the write queue of the WriteStream",
"# is full, and if so, the ReadStream is paused, and a {WriteStream#drain_handler} is set on the WriteStream.",
"# When the WriteStream has processed half of its backlog, the drain_handler will be called,",
"# which results in the pump resuming the ReadStream.",
"#",
"# This class can be used to pump from any {ReadStream} to any { WriteStream},",
"# e.g. from an {HttpServerRequest} to an {AsyncFile}, or from {NetSocket} to a {WebSocket}.",
"#",
"# @author {http://tfox.org Tim Fox}",
"# Set the write queue max size",
"# @param [FixNum] The write queue max size",
"# Start the Pump. The Pump can be started and stopped multiple times.",
"# Stop the Pump. The Pump can be started and stopped multiple times.",
"# @return [FixNum] Return the total number of bytes pumped by this pump."
] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 16
| 1,356
| 133
|
70235d0a0c8160a624ee7d6b8ac48cfd166cbdac
|
robinxdroid/XDroidAnimation
|
XDroidAnimation/src/com/xdroid/animation/anim/TransferAnimation.java
|
[
"Apache-2.0"
] |
Java
|
TransferAnimation
|
/**
* This animation transfers the view to another view provided by the user
* through scaling and translation. The view is scaled to the same size and is
* translated to the same position as the destination view.
*
* @author Robin
* @since 2015-07-31 17:59:58
*
*/
|
This animation transfers the view to another view provided by the user
through scaling and translation. The view is scaled to the same size and is
translated to the same position as the destination view.
|
[
"This",
"animation",
"transfers",
"the",
"view",
"to",
"another",
"view",
"provided",
"by",
"the",
"user",
"through",
"scaling",
"and",
"translation",
".",
"The",
"view",
"is",
"scaled",
"to",
"the",
"same",
"size",
"and",
"is",
"translated",
"to",
"the",
"same",
"position",
"as",
"the",
"destination",
"view",
"."
] |
public class TransferAnimation extends AnimationBase<TransferAnimation>{
View destinationView;
int transX, transY;
float scaleX, scaleY;
ViewGroup parentView;
/*
* ==================================================================
* Constructor
* ==================================================================
*/
public TransferAnimation(View targetView) {
this.targetView = targetView;
destinationView = null;
interpolator = new AccelerateDecelerateInterpolator();
duration = Duration.DURATION_LONG;
listener = null;
}
/*
* ==================================================================
* Override CombinableMethod
* ==================================================================
*/
@Override
public void animate() {
ViewHelper.setClipChildren(targetView, false);
parentView = (ViewGroup) targetView.getParent();
targetView.animate().scaleX(scaleX).scaleY(scaleY).translationX(transX).translationY(transY)
.setInterpolator(interpolator).setDuration(duration).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
if (listener != null) {
listener.onAnimationStart(animation);
}
}
@Override
public void onAnimationEnd(Animator animation) {
if (listener != null) {
listener.onAnimationEnd(animation);
}
}
@Override
public void onAnimationCancel(Animator animation) {
if (listener != null) {
listener.onAnimationCancel(animation);
}
}
@Override
public void onAnimationRepeat(Animator animation) {
if (listener != null) {
listener.onAnimationRepeat(animation);
}
}
});
}
@Override
public AnimatorSet createAnimatorSet() {
return null;
}
/*
* ==================================================================
* Getter And Setter
* ==================================================================
*/
/**
* @return The destination view to transfer the original view to.
*/
public View getDestinationView() {
return destinationView;
}
/**
* @param The
* destination view to set to transfer the original view to.
* @return TransferAnimation
*/
public TransferAnimation setDestinationView(View destinationView) {
this.destinationView = destinationView;
scaleX = (float) destinationView.getWidth() / ((float) targetView.getWidth());
scaleY = (float) destinationView.getHeight() / ((float) targetView.getHeight());
int[] locationDest = new int[2], locationView = new int[2];
targetView.getLocationOnScreen(locationView);
destinationView.getLocationOnScreen(locationDest);
transX = locationDest[0] - locationView[0];
transY = locationDest[1] - locationView[1];
transX = transX - targetView.getWidth() / 2 + destinationView.getWidth() / 2;
transY = transY - targetView.getHeight() / 2 + destinationView.getHeight() / 2;
return this;
}
public int getTransX() {
return transX;
}
public void setTransX(int transX) {
this.transX = transX;
}
public int getTransY() {
return transY;
}
public void setTransY(int transY) {
this.transY = transY;
}
public float getScaleX() {
return scaleX;
}
public void setScaleX(float scaleX) {
this.scaleX = scaleX;
}
public float getScaleY() {
return scaleY;
}
public void setScaleY(float scaleY) {
this.scaleY = scaleY;
}
}
|
[
"public",
"class",
"TransferAnimation",
"extends",
"AnimationBase",
"<",
"TransferAnimation",
">",
"{",
"View",
"destinationView",
";",
"int",
"transX",
",",
"transY",
";",
"float",
"scaleX",
",",
"scaleY",
";",
"ViewGroup",
"parentView",
";",
"/*\n\t * ==================================================================\n\t * Constructor\n\t * ==================================================================\n\t */",
"public",
"TransferAnimation",
"(",
"View",
"targetView",
")",
"{",
"this",
".",
"targetView",
"=",
"targetView",
";",
"destinationView",
"=",
"null",
";",
"interpolator",
"=",
"new",
"AccelerateDecelerateInterpolator",
"(",
")",
";",
"duration",
"=",
"Duration",
".",
"DURATION_LONG",
";",
"listener",
"=",
"null",
";",
"}",
"/*\n\t * ==================================================================\n\t * Override CombinableMethod\n\t * ==================================================================\n\t */",
"@",
"Override",
"public",
"void",
"animate",
"(",
")",
"{",
"ViewHelper",
".",
"setClipChildren",
"(",
"targetView",
",",
"false",
")",
";",
"parentView",
"=",
"(",
"ViewGroup",
")",
"targetView",
".",
"getParent",
"(",
")",
";",
"targetView",
".",
"animate",
"(",
")",
".",
"scaleX",
"(",
"scaleX",
")",
".",
"scaleY",
"(",
"scaleY",
")",
".",
"translationX",
"(",
"transX",
")",
".",
"translationY",
"(",
"transY",
")",
".",
"setInterpolator",
"(",
"interpolator",
")",
".",
"setDuration",
"(",
"duration",
")",
".",
"setListener",
"(",
"new",
"AnimatorListenerAdapter",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"onAnimationStart",
"(",
"Animator",
"animation",
")",
"{",
"if",
"(",
"listener",
"!=",
"null",
")",
"{",
"listener",
".",
"onAnimationStart",
"(",
"animation",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onAnimationEnd",
"(",
"Animator",
"animation",
")",
"{",
"if",
"(",
"listener",
"!=",
"null",
")",
"{",
"listener",
".",
"onAnimationEnd",
"(",
"animation",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onAnimationCancel",
"(",
"Animator",
"animation",
")",
"{",
"if",
"(",
"listener",
"!=",
"null",
")",
"{",
"listener",
".",
"onAnimationCancel",
"(",
"animation",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"void",
"onAnimationRepeat",
"(",
"Animator",
"animation",
")",
"{",
"if",
"(",
"listener",
"!=",
"null",
")",
"{",
"listener",
".",
"onAnimationRepeat",
"(",
"animation",
")",
";",
"}",
"}",
"}",
")",
";",
"}",
"@",
"Override",
"public",
"AnimatorSet",
"createAnimatorSet",
"(",
")",
"{",
"return",
"null",
";",
"}",
"/*\n\t * ================================================================== \n\t * Getter And Setter\n\t * ==================================================================\n\t */",
"/**\n\t * @return The destination view to transfer the original view to.\n\t */",
"public",
"View",
"getDestinationView",
"(",
")",
"{",
"return",
"destinationView",
";",
"}",
"/**\n\t * @param The\n\t * destination view to set to transfer the original view to.\n\t * @return TransferAnimation\n\t */",
"public",
"TransferAnimation",
"setDestinationView",
"(",
"View",
"destinationView",
")",
"{",
"this",
".",
"destinationView",
"=",
"destinationView",
";",
"scaleX",
"=",
"(",
"float",
")",
"destinationView",
".",
"getWidth",
"(",
")",
"/",
"(",
"(",
"float",
")",
"targetView",
".",
"getWidth",
"(",
")",
")",
";",
"scaleY",
"=",
"(",
"float",
")",
"destinationView",
".",
"getHeight",
"(",
")",
"/",
"(",
"(",
"float",
")",
"targetView",
".",
"getHeight",
"(",
")",
")",
";",
"int",
"[",
"]",
"locationDest",
"=",
"new",
"int",
"[",
"2",
"]",
",",
"locationView",
"=",
"new",
"int",
"[",
"2",
"]",
";",
"targetView",
".",
"getLocationOnScreen",
"(",
"locationView",
")",
";",
"destinationView",
".",
"getLocationOnScreen",
"(",
"locationDest",
")",
";",
"transX",
"=",
"locationDest",
"[",
"0",
"]",
"-",
"locationView",
"[",
"0",
"]",
";",
"transY",
"=",
"locationDest",
"[",
"1",
"]",
"-",
"locationView",
"[",
"1",
"]",
";",
"transX",
"=",
"transX",
"-",
"targetView",
".",
"getWidth",
"(",
")",
"/",
"2",
"+",
"destinationView",
".",
"getWidth",
"(",
")",
"/",
"2",
";",
"transY",
"=",
"transY",
"-",
"targetView",
".",
"getHeight",
"(",
")",
"/",
"2",
"+",
"destinationView",
".",
"getHeight",
"(",
")",
"/",
"2",
";",
"return",
"this",
";",
"}",
"public",
"int",
"getTransX",
"(",
")",
"{",
"return",
"transX",
";",
"}",
"public",
"void",
"setTransX",
"(",
"int",
"transX",
")",
"{",
"this",
".",
"transX",
"=",
"transX",
";",
"}",
"public",
"int",
"getTransY",
"(",
")",
"{",
"return",
"transY",
";",
"}",
"public",
"void",
"setTransY",
"(",
"int",
"transY",
")",
"{",
"this",
".",
"transY",
"=",
"transY",
";",
"}",
"public",
"float",
"getScaleX",
"(",
")",
"{",
"return",
"scaleX",
";",
"}",
"public",
"void",
"setScaleX",
"(",
"float",
"scaleX",
")",
"{",
"this",
".",
"scaleX",
"=",
"scaleX",
";",
"}",
"public",
"float",
"getScaleY",
"(",
")",
"{",
"return",
"scaleY",
";",
"}",
"public",
"void",
"setScaleY",
"(",
"float",
"scaleY",
")",
"{",
"this",
".",
"scaleY",
"=",
"scaleY",
";",
"}",
"}"
] |
This animation transfers the view to another view provided by the user
through scaling and translation.
|
[
"This",
"animation",
"transfers",
"the",
"view",
"to",
"another",
"view",
"provided",
"by",
"the",
"user",
"through",
"scaling",
"and",
"translation",
"."
] |
[] |
[] |
{
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
}
| false
| 17
| 755
| 77
|
881fe2de011fabd6af18f4d15f8a10171675d346
|
JohnLCaron/netcdf-java
|
cdm/src/main/java/ucar/nc2/ft/point/PointIteratorFromStructureData.java
|
[
"BSD-3-Clause"
] |
Java
|
PointIteratorFromStructureData
|
/**
* A PointFeatureIterator which uses a StructureDataIterator to iterate over members of a Structure,
* with optional filtering and calculation of time range and bounding box.
* <p>
* Subclass must implement makeFeature() to turn the StructureData into a PointFeature.
*
* @author caron
* @since Feb 29, 2008
*/
|
A PointFeatureIterator which uses a StructureDataIterator to iterate over members of a Structure,
with optional filtering and calculation of time range and bounding box.
Subclass must implement makeFeature() to turn the StructureData into a PointFeature.
@author caron
@since Feb 29, 2008
|
[
"A",
"PointFeatureIterator",
"which",
"uses",
"a",
"StructureDataIterator",
"to",
"iterate",
"over",
"members",
"of",
"a",
"Structure",
"with",
"optional",
"filtering",
"and",
"calculation",
"of",
"time",
"range",
"and",
"bounding",
"box",
".",
"Subclass",
"must",
"implement",
"makeFeature",
"()",
"to",
"turn",
"the",
"StructureData",
"into",
"a",
"PointFeature",
".",
"@author",
"caron",
"@since",
"Feb",
"29",
"2008"
] |
public abstract class PointIteratorFromStructureData extends PointIteratorAbstract {
// makeFeature may return null, if so then skip it and go to next iteration
protected abstract PointFeature makeFeature(int recnum, StructureData sdata) throws IOException;
private PointFeatureIterator.Filter filter;
private StructureDataIterator structIter;
private PointFeature feature = null; // hasNext must cache
private boolean finished = false;
/**
* Constructor
*
* @param structIter original iterator
* @param filter optional filter
*/
public PointIteratorFromStructureData(StructureDataIterator structIter, PointFeatureIterator.Filter filter) {
this.structIter = structIter;
this.filter = filter;
}
@Override
public boolean hasNext() {
try {
while (true) {
StructureData sdata = nextStructureData();
if (sdata == null)
break;
feature = makeFeature(structIter.getCurrentRecno(), sdata);
if (feature == null)
continue;
if (feature.getLocation().isMissing()) {
continue;
}
if (filter == null || filter.filter(feature))
return true;
}
// all done
feature = null;
close();
return false;
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
@Override
public PointFeature next() {
if (feature == null)
return null;
calcBounds(feature);
return feature;
}
@Override
public void close() {
if (finished)
return;
finishCalcBounds();
finished = true;
structIter.close();
}
private StructureData nextStructureData() throws IOException {
return structIter.hasNext() ? structIter.next() : null;
}
}
|
[
"public",
"abstract",
"class",
"PointIteratorFromStructureData",
"extends",
"PointIteratorAbstract",
"{",
"protected",
"abstract",
"PointFeature",
"makeFeature",
"(",
"int",
"recnum",
",",
"StructureData",
"sdata",
")",
"throws",
"IOException",
";",
"private",
"PointFeatureIterator",
".",
"Filter",
"filter",
";",
"private",
"StructureDataIterator",
"structIter",
";",
"private",
"PointFeature",
"feature",
"=",
"null",
";",
"private",
"boolean",
"finished",
"=",
"false",
";",
"/**\n * Constructor\n *\n * @param structIter original iterator\n * @param filter optional filter\n */",
"public",
"PointIteratorFromStructureData",
"(",
"StructureDataIterator",
"structIter",
",",
"PointFeatureIterator",
".",
"Filter",
"filter",
")",
"{",
"this",
".",
"structIter",
"=",
"structIter",
";",
"this",
".",
"filter",
"=",
"filter",
";",
"}",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"try",
"{",
"while",
"(",
"true",
")",
"{",
"StructureData",
"sdata",
"=",
"nextStructureData",
"(",
")",
";",
"if",
"(",
"sdata",
"==",
"null",
")",
"break",
";",
"feature",
"=",
"makeFeature",
"(",
"structIter",
".",
"getCurrentRecno",
"(",
")",
",",
"sdata",
")",
";",
"if",
"(",
"feature",
"==",
"null",
")",
"continue",
";",
"if",
"(",
"feature",
".",
"getLocation",
"(",
")",
".",
"isMissing",
"(",
")",
")",
"{",
"continue",
";",
"}",
"if",
"(",
"filter",
"==",
"null",
"||",
"filter",
".",
"filter",
"(",
"feature",
")",
")",
"return",
"true",
";",
"}",
"feature",
"=",
"null",
";",
"close",
"(",
")",
";",
"return",
"false",
";",
"}",
"catch",
"(",
"IOException",
"ioe",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ioe",
")",
";",
"}",
"}",
"@",
"Override",
"public",
"PointFeature",
"next",
"(",
")",
"{",
"if",
"(",
"feature",
"==",
"null",
")",
"return",
"null",
";",
"calcBounds",
"(",
"feature",
")",
";",
"return",
"feature",
";",
"}",
"@",
"Override",
"public",
"void",
"close",
"(",
")",
"{",
"if",
"(",
"finished",
")",
"return",
";",
"finishCalcBounds",
"(",
")",
";",
"finished",
"=",
"true",
";",
"structIter",
".",
"close",
"(",
")",
";",
"}",
"private",
"StructureData",
"nextStructureData",
"(",
")",
"throws",
"IOException",
"{",
"return",
"structIter",
".",
"hasNext",
"(",
")",
"?",
"structIter",
".",
"next",
"(",
")",
":",
"null",
";",
"}",
"}"
] |
A PointFeatureIterator which uses a StructureDataIterator to iterate over members of a Structure,
with optional filtering and calculation of time range and bounding box.
|
[
"A",
"PointFeatureIterator",
"which",
"uses",
"a",
"StructureDataIterator",
"to",
"iterate",
"over",
"members",
"of",
"a",
"Structure",
"with",
"optional",
"filtering",
"and",
"calculation",
"of",
"time",
"range",
"and",
"bounding",
"box",
"."
] |
[
"// makeFeature may return null, if so then skip it and go to next iteration",
"// hasNext must cache",
"// all done"
] |
[
{
"param": "PointIteratorAbstract",
"type": null
}
] |
{
"returns": [],
"raises": [],
"params": [
{
"identifier": "PointIteratorAbstract",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
}
| false
| 15
| 380
| 77
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.