repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java
AbstractExecutableMemberWriter.addParameters
protected void addParameters(ExecutableElement member, Content htmltree, int indentSize) { addParameters(member, true, htmltree, indentSize); }
java
protected void addParameters(ExecutableElement member, Content htmltree, int indentSize) { addParameters(member, true, htmltree, indentSize); }
[ "protected", "void", "addParameters", "(", "ExecutableElement", "member", ",", "Content", "htmltree", ",", "int", "indentSize", ")", "{", "addParameters", "(", "member", ",", "true", ",", "htmltree", ",", "indentSize", ")", ";", "}" ]
Add all the parameters for the executable member. @param member the member to write parameters for. @param htmltree the content tree to which the parameters information will be added.
[ "Add", "all", "the", "parameters", "for", "the", "executable", "member", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java#L189-L191
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/bcc/BccClient.java
BccClient.attachVolume
public AttachVolumeResponse attachVolume(String volumeId, String instanceId) { return attachVolume(new AttachVolumeRequest().withVolumeId(volumeId).withInstanceId(instanceId)); }
java
public AttachVolumeResponse attachVolume(String volumeId, String instanceId) { return attachVolume(new AttachVolumeRequest().withVolumeId(volumeId).withInstanceId(instanceId)); }
[ "public", "AttachVolumeResponse", "attachVolume", "(", "String", "volumeId", ",", "String", "instanceId", ")", "{", "return", "attachVolume", "(", "new", "AttachVolumeRequest", "(", ")", ".", "withVolumeId", "(", "volumeId", ")", ".", "withInstanceId", "(", "instanceId", ")", ")", ";", "}" ]
Attaching the specified volume to a specified instance. You can attach the specified volume to a specified instance only when the volume is Available and the instance is Running or Stopped , otherwise,it's will get <code>409</code> errorCode. @param volumeId The id of the volume which will be attached to specified instance. @param instanceId The id of the instance which will be attached with a volume. @return The response containing the volume-instance attach relation.
[ "Attaching", "the", "specified", "volume", "to", "a", "specified", "instance", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/bcc/BccClient.java#L963-L965
VoltDB/voltdb
src/frontend/org/voltdb/iv2/InitiatorMailbox.java
InitiatorMailbox.repairReplicasWith
void repairReplicasWith(List<Long> needsRepair, VoltMessage repairWork) { //For an SpInitiator the lock should already have been acquire since //this method is reach via SpPromoteAlgo.deliver which is reached by InitiatorMailbox.deliver //which should already have acquire the lock assert(Thread.holdsLock(this)); repairReplicasWithInternal(needsRepair, repairWork); }
java
void repairReplicasWith(List<Long> needsRepair, VoltMessage repairWork) { //For an SpInitiator the lock should already have been acquire since //this method is reach via SpPromoteAlgo.deliver which is reached by InitiatorMailbox.deliver //which should already have acquire the lock assert(Thread.holdsLock(this)); repairReplicasWithInternal(needsRepair, repairWork); }
[ "void", "repairReplicasWith", "(", "List", "<", "Long", ">", "needsRepair", ",", "VoltMessage", "repairWork", ")", "{", "//For an SpInitiator the lock should already have been acquire since", "//this method is reach via SpPromoteAlgo.deliver which is reached by InitiatorMailbox.deliver", "//which should already have acquire the lock", "assert", "(", "Thread", ".", "holdsLock", "(", "this", ")", ")", ";", "repairReplicasWithInternal", "(", "needsRepair", ",", "repairWork", ")", ";", "}" ]
Create a real repair message from the msg repair log contents and instruct the message handler to execute a repair. Single partition work needs to do duplicate counting; MPI can simply broadcast the repair to the needs repair units -- where the SP will do the rest.
[ "Create", "a", "real", "repair", "message", "from", "the", "msg", "repair", "log", "contents", "and", "instruct", "the", "message", "handler", "to", "execute", "a", "repair", ".", "Single", "partition", "work", "needs", "to", "do", "duplicate", "counting", ";", "MPI", "can", "simply", "broadcast", "the", "repair", "to", "the", "needs", "repair", "units", "--", "where", "the", "SP", "will", "do", "the", "rest", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/iv2/InitiatorMailbox.java#L591-L598
ops4j/org.ops4j.pax.exam1
pax-exam-container-rbc-client/src/main/java/org/ops4j/pax/exam/rbc/client/RemoteBundleContextClient.java
RemoteBundleContextClient.getService
@SuppressWarnings( "unchecked" ) public <T> T getService( final Class<T> serviceType, final long timeoutInMillis ) { return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[]{ serviceType }, new InvocationHandler() { /** * {@inheritDoc} * Delegates the call to remote bundle context. */ public Object invoke( final Object proxy, final Method method, final Object[] params ) throws Throwable { try { return getRemoteBundleContext().remoteCall( method.getDeclaringClass(), method.getName(), method.getParameterTypes(), timeoutInMillis, params ); } catch( InvocationTargetException e ) { throw e.getCause(); } catch( RemoteException e ) { throw new TestContainerException( "Remote exception", e ); } catch( Exception e ) { throw new TestContainerException( "Invocation exception", e ); } } } ); }
java
@SuppressWarnings( "unchecked" ) public <T> T getService( final Class<T> serviceType, final long timeoutInMillis ) { return (T) Proxy.newProxyInstance( getClass().getClassLoader(), new Class<?>[]{ serviceType }, new InvocationHandler() { /** * {@inheritDoc} * Delegates the call to remote bundle context. */ public Object invoke( final Object proxy, final Method method, final Object[] params ) throws Throwable { try { return getRemoteBundleContext().remoteCall( method.getDeclaringClass(), method.getName(), method.getParameterTypes(), timeoutInMillis, params ); } catch( InvocationTargetException e ) { throw e.getCause(); } catch( RemoteException e ) { throw new TestContainerException( "Remote exception", e ); } catch( Exception e ) { throw new TestContainerException( "Invocation exception", e ); } } } ); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "getService", "(", "final", "Class", "<", "T", ">", "serviceType", ",", "final", "long", "timeoutInMillis", ")", "{", "return", "(", "T", ")", "Proxy", ".", "newProxyInstance", "(", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ",", "new", "Class", "<", "?", ">", "[", "]", "{", "serviceType", "}", ",", "new", "InvocationHandler", "(", ")", "{", "/**\n * {@inheritDoc}\n * Delegates the call to remote bundle context.\n */", "public", "Object", "invoke", "(", "final", "Object", "proxy", ",", "final", "Method", "method", ",", "final", "Object", "[", "]", "params", ")", "throws", "Throwable", "{", "try", "{", "return", "getRemoteBundleContext", "(", ")", ".", "remoteCall", "(", "method", ".", "getDeclaringClass", "(", ")", ",", "method", ".", "getName", "(", ")", ",", "method", ".", "getParameterTypes", "(", ")", ",", "timeoutInMillis", ",", "params", ")", ";", "}", "catch", "(", "InvocationTargetException", "e", ")", "{", "throw", "e", ".", "getCause", "(", ")", ";", "}", "catch", "(", "RemoteException", "e", ")", "{", "throw", "new", "TestContainerException", "(", "\"Remote exception\"", ",", "e", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "TestContainerException", "(", "\"Invocation exception\"", ",", "e", ")", ";", "}", "}", "}", ")", ";", "}" ]
{@inheritDoc} Returns a dynamic proxy in place of the actual service, forwarding the calls via the remote bundle context.
[ "{" ]
train
https://github.com/ops4j/org.ops4j.pax.exam1/blob/7c8742208117ff91bd24bcd3a185d2d019f7000f/pax-exam-container-rbc-client/src/main/java/org/ops4j/pax/exam/rbc/client/RemoteBundleContextClient.java#L91-L134
soulwarelabs/jCommons-API
src/main/java/com/soulwarelabs/jcommons/data/Version.java
Version.append
public Version append(int number, String label) { validateNumber(number); return appendNumber(number, label); }
java
public Version append(int number, String label) { validateNumber(number); return appendNumber(number, label); }
[ "public", "Version", "append", "(", "int", "number", ",", "String", "label", ")", "{", "validateNumber", "(", "number", ")", ";", "return", "appendNumber", "(", "number", ",", "label", ")", ";", "}" ]
Adds a new version number. @param number version number (not negative). @param label version number label (optional). @return version descriptor. @throws IllegalArgumentException if version number is illegal. @since v1.1.0
[ "Adds", "a", "new", "version", "number", "." ]
train
https://github.com/soulwarelabs/jCommons-API/blob/57795ae28aea144e68502149506ec99dd67f0c67/src/main/java/com/soulwarelabs/jcommons/data/Version.java#L408-L411
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VpnConnectionsInner.java
VpnConnectionsInner.createOrUpdate
public VpnConnectionInner createOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().last().body(); }
java
public VpnConnectionInner createOrUpdate(String resourceGroupName, String gatewayName, String connectionName, VpnConnectionInner vpnConnectionParameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, gatewayName, connectionName, vpnConnectionParameters).toBlocking().last().body(); }
[ "public", "VpnConnectionInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "gatewayName", ",", "String", "connectionName", ",", "VpnConnectionInner", "vpnConnectionParameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "gatewayName", ",", "connectionName", ",", "vpnConnectionParameters", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. @param resourceGroupName The resource group name of the VpnGateway. @param gatewayName The name of the gateway. @param connectionName The name of the connection. @param vpnConnectionParameters Parameters supplied to create or Update a VPN Connection. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the VpnConnectionInner object if successful.
[ "Creates", "a", "vpn", "connection", "to", "a", "scalable", "vpn", "gateway", "if", "it", "doesn", "t", "exist", "else", "updates", "the", "existing", "connection", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VpnConnectionsInner.java#L197-L199
Activiti/Activiti
activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java
VariableScopeImpl.createVariableLocal
protected void createVariableLocal(String variableName, Object value, ExecutionEntity sourceActivityExecution) { ensureVariableInstancesInitialized(); if (variableInstances.containsKey(variableName)) { throw new ActivitiException("variable '" + variableName + "' already exists. Use setVariableLocal if you want to overwrite the value"); } createVariableInstance(variableName, value, sourceActivityExecution); }
java
protected void createVariableLocal(String variableName, Object value, ExecutionEntity sourceActivityExecution) { ensureVariableInstancesInitialized(); if (variableInstances.containsKey(variableName)) { throw new ActivitiException("variable '" + variableName + "' already exists. Use setVariableLocal if you want to overwrite the value"); } createVariableInstance(variableName, value, sourceActivityExecution); }
[ "protected", "void", "createVariableLocal", "(", "String", "variableName", ",", "Object", "value", ",", "ExecutionEntity", "sourceActivityExecution", ")", "{", "ensureVariableInstancesInitialized", "(", ")", ";", "if", "(", "variableInstances", ".", "containsKey", "(", "variableName", ")", ")", "{", "throw", "new", "ActivitiException", "(", "\"variable '\"", "+", "variableName", "+", "\"' already exists. Use setVariableLocal if you want to overwrite the value\"", ")", ";", "}", "createVariableInstance", "(", "variableName", ",", "value", ",", "sourceActivityExecution", ")", ";", "}" ]
only called when a new variable is created on this variable scope. This method is also responsible for propagating the creation of this variable to the history.
[ "only", "called", "when", "a", "new", "variable", "is", "created", "on", "this", "variable", "scope", ".", "This", "method", "is", "also", "responsible", "for", "propagating", "the", "creation", "of", "this", "variable", "to", "the", "history", "." ]
train
https://github.com/Activiti/Activiti/blob/82e2b2cd2083b2f734ca0efc7815389c0f2517d9/activiti-engine/src/main/java/org/activiti/engine/impl/persistence/entity/VariableScopeImpl.java#L782-L790
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/base64/Base64.java
Base64.encodeFileToFile
public static void encodeFileToFile (@Nonnull final String infile, @Nonnull final File aFile) throws IOException { final String encoded = encodeFromFile (infile); try (final OutputStream out = FileHelper.getBufferedOutputStream (aFile)) { // Strict, 7-bit output. out.write (encoded.getBytes (PREFERRED_ENCODING)); } }
java
public static void encodeFileToFile (@Nonnull final String infile, @Nonnull final File aFile) throws IOException { final String encoded = encodeFromFile (infile); try (final OutputStream out = FileHelper.getBufferedOutputStream (aFile)) { // Strict, 7-bit output. out.write (encoded.getBytes (PREFERRED_ENCODING)); } }
[ "public", "static", "void", "encodeFileToFile", "(", "@", "Nonnull", "final", "String", "infile", ",", "@", "Nonnull", "final", "File", "aFile", ")", "throws", "IOException", "{", "final", "String", "encoded", "=", "encodeFromFile", "(", "infile", ")", ";", "try", "(", "final", "OutputStream", "out", "=", "FileHelper", ".", "getBufferedOutputStream", "(", "aFile", ")", ")", "{", "// Strict, 7-bit output.", "out", ".", "write", "(", "encoded", ".", "getBytes", "(", "PREFERRED_ENCODING", ")", ")", ";", "}", "}" ]
Reads <code>infile</code> and encodes it to <code>outfile</code>. @param infile Input file @param aFile Output file @throws IOException if there is an error @since 2.2
[ "Reads", "<code", ">", "infile<", "/", "code", ">", "and", "encodes", "it", "to", "<code", ">", "outfile<", "/", "code", ">", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2498-L2506
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/context/AuditorModuleContext.java
AuditorModuleContext.getAuditor
public IHEAuditor getAuditor(String className, boolean useContextAuditorRegistry) { return getAuditor(AuditorFactory.getAuditorClassForClassName(className),useContextAuditorRegistry); }
java
public IHEAuditor getAuditor(String className, boolean useContextAuditorRegistry) { return getAuditor(AuditorFactory.getAuditorClassForClassName(className),useContextAuditorRegistry); }
[ "public", "IHEAuditor", "getAuditor", "(", "String", "className", ",", "boolean", "useContextAuditorRegistry", ")", "{", "return", "getAuditor", "(", "AuditorFactory", ".", "getAuditorClassForClassName", "(", "className", ")", ",", "useContextAuditorRegistry", ")", ";", "}" ]
Get an IHE Auditor instance from a fully-qualified class name @param className Auditor class to use @param useContextAuditorRegistry Whether to reuse cached auditors from context @return Auditor instance
[ "Get", "an", "IHE", "Auditor", "instance", "from", "a", "fully", "-", "qualified", "class", "name" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/context/AuditorModuleContext.java#L287-L290
Domo42/saga-lib
saga-lib/src/main/java/com/codebullets/sagalib/processing/invocation/SagaExecutionErrorsException.java
SagaExecutionErrorsException.rethrowOrThrowIfMultiple
public static void rethrowOrThrowIfMultiple(final String message, final Collection<Exception> errors) throws Exception { int exceptionsCount = errors.size(); switch (exceptionsCount) { case 0: // no error -> do nothing break; case 1: // single error -> rethrow original exception throw errors.iterator().next(); default: throw new SagaExecutionErrorsException(message, errors); } }
java
public static void rethrowOrThrowIfMultiple(final String message, final Collection<Exception> errors) throws Exception { int exceptionsCount = errors.size(); switch (exceptionsCount) { case 0: // no error -> do nothing break; case 1: // single error -> rethrow original exception throw errors.iterator().next(); default: throw new SagaExecutionErrorsException(message, errors); } }
[ "public", "static", "void", "rethrowOrThrowIfMultiple", "(", "final", "String", "message", ",", "final", "Collection", "<", "Exception", ">", "errors", ")", "throws", "Exception", "{", "int", "exceptionsCount", "=", "errors", ".", "size", "(", ")", ";", "switch", "(", "exceptionsCount", ")", "{", "case", "0", ":", "// no error -> do nothing", "break", ";", "case", "1", ":", "// single error -> rethrow original exception", "throw", "errors", ".", "iterator", "(", ")", ".", "next", "(", ")", ";", "default", ":", "throw", "new", "SagaExecutionErrorsException", "(", "message", ",", "errors", ")", ";", "}", "}" ]
Checks the provided errors list for the number of instances. If no error is reported does nothing. In case of a single error the original exception is thrown, in case multiple errors, encapsulate the list into a new thrown {@link SagaExecutionErrorsException} @throws Exception Throws the original exception or a new {@link SagaExecutionErrorsException}
[ "Checks", "the", "provided", "errors", "list", "for", "the", "number", "of", "instances", ".", "If", "no", "error", "is", "reported", "does", "nothing", ".", "In", "case", "of", "a", "single", "error", "the", "original", "exception", "is", "thrown", "in", "case", "multiple", "errors", "encapsulate", "the", "list", "into", "a", "new", "thrown", "{", "@link", "SagaExecutionErrorsException", "}" ]
train
https://github.com/Domo42/saga-lib/blob/c8f232e2a51fcb6a3fe0082cfbf105c1e6bf90ef/saga-lib/src/main/java/com/codebullets/sagalib/processing/invocation/SagaExecutionErrorsException.java#L73-L85
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/parser/ParseUtils.java
ParseUtils.getCompiledPage
private static EngProcessedPage getCompiledPage(String text, String title, long revision) throws LinkTargetException, EngineException, FileNotFoundException, JAXBException { WikiConfig config = DefaultConfigEnWp.generate(); PageTitle pageTitle = PageTitle.make(config, title); PageId pageId = new PageId(pageTitle, revision); // Compile the retrieved page WtEngineImpl engine = new WtEngineImpl(config); // Compile the retrieved page return engine.postprocess(pageId, text, null); }
java
private static EngProcessedPage getCompiledPage(String text, String title, long revision) throws LinkTargetException, EngineException, FileNotFoundException, JAXBException { WikiConfig config = DefaultConfigEnWp.generate(); PageTitle pageTitle = PageTitle.make(config, title); PageId pageId = new PageId(pageTitle, revision); // Compile the retrieved page WtEngineImpl engine = new WtEngineImpl(config); // Compile the retrieved page return engine.postprocess(pageId, text, null); }
[ "private", "static", "EngProcessedPage", "getCompiledPage", "(", "String", "text", ",", "String", "title", ",", "long", "revision", ")", "throws", "LinkTargetException", ",", "EngineException", ",", "FileNotFoundException", ",", "JAXBException", "{", "WikiConfig", "config", "=", "DefaultConfigEnWp", ".", "generate", "(", ")", ";", "PageTitle", "pageTitle", "=", "PageTitle", ".", "make", "(", "config", ",", "title", ")", ";", "PageId", "pageId", "=", "new", "PageId", "(", "pageTitle", ",", "revision", ")", ";", "// Compile the retrieved page", "WtEngineImpl", "engine", "=", "new", "WtEngineImpl", "(", "config", ")", ";", "// Compile the retrieved page", "return", "engine", ".", "postprocess", "(", "pageId", ",", "text", ",", "null", ")", ";", "}" ]
Returns CompiledPage produced by the SWEBLE parser using the SimpleWikiConfiguration. @return the parsed page @throws LinkTargetException @throws EngineException if the wiki page could not be compiled by the parser @throws JAXBException @throws FileNotFoundException
[ "Returns", "CompiledPage", "produced", "by", "the", "SWEBLE", "parser", "using", "the", "SimpleWikiConfiguration", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/templates/parser/ParseUtils.java#L107-L117
feedzai/pdb
src/main/java/com/feedzai/commons/sql/abstraction/util/AESHelper.java
AESHelper.decryptFile
public static byte[] decryptFile(String path, String key) { try { byte[] buf = readFile(path); return decrypt(buf, key); } catch (final Exception e) { logger.warn("Could not decrypt file {}", path, e); return null; } }
java
public static byte[] decryptFile(String path, String key) { try { byte[] buf = readFile(path); return decrypt(buf, key); } catch (final Exception e) { logger.warn("Could not decrypt file {}", path, e); return null; } }
[ "public", "static", "byte", "[", "]", "decryptFile", "(", "String", "path", ",", "String", "key", ")", "{", "try", "{", "byte", "[", "]", "buf", "=", "readFile", "(", "path", ")", ";", "return", "decrypt", "(", "buf", ",", "key", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "logger", ".", "warn", "(", "\"Could not decrypt file {}\"", ",", "path", ",", "e", ")", ";", "return", "null", ";", "}", "}" ]
Decrypts a file encrypted by {@link #encryptToFile(String, byte[], String)} method. @param path The file path to decrypt. @param key The key. @return A decrypted byte[].
[ "Decrypts", "a", "file", "encrypted", "by", "{", "@link", "#encryptToFile", "(", "String", "byte", "[]", "String", ")", "}", "method", "." ]
train
https://github.com/feedzai/pdb/blob/fe07ca08417e0ddcd620a36aa1fdbca7f338be98/src/main/java/com/feedzai/commons/sql/abstraction/util/AESHelper.java#L125-L133
EdwardRaff/JSAT
JSAT/src/jsat/io/LIBSVMLoader.java
LIBSVMLoader.loadR
public static RegressionDataSet loadR(File file, double sparseRatio, int vectorLength) throws FileNotFoundException, IOException { return loadR(new FileReader(file), sparseRatio, vectorLength); }
java
public static RegressionDataSet loadR(File file, double sparseRatio, int vectorLength) throws FileNotFoundException, IOException { return loadR(new FileReader(file), sparseRatio, vectorLength); }
[ "public", "static", "RegressionDataSet", "loadR", "(", "File", "file", ",", "double", "sparseRatio", ",", "int", "vectorLength", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "return", "loadR", "(", "new", "FileReader", "(", "file", ")", ",", "sparseRatio", ",", "vectorLength", ")", ";", "}" ]
Loads a new regression data set from a LIBSVM file, assuming the label is a numeric target value to predict @param file the file to load @param sparseRatio the fraction of non zero values to qualify a data point as sparse @param vectorLength the pre-determined length of each vector. If given a negative value, the largest non-zero index observed in the data will be used as the length. @return a regression data set @throws FileNotFoundException if the file was not found @throws IOException if an error occurred reading the input stream
[ "Loads", "a", "new", "regression", "data", "set", "from", "a", "LIBSVM", "file", "assuming", "the", "label", "is", "a", "numeric", "target", "value", "to", "predict" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/io/LIBSVMLoader.java#L98-L101
raydac/meta
meta-utils/src/main/java/com/igormaznitsa/meta/common/utils/TimeGuard.java
TimeGuard.checkPoint
@Weight(value = Weight.Unit.VARIABLE, comment = "Depends on the current call stack depth") public static void checkPoint(@Nonnull final String timePointName) { final long time = System.currentTimeMillis(); final int stackDepth = ThreadUtils.stackDepth(); final List<TimeData> list = REGISTRY.get(); final Iterator<TimeData> iterator = list.iterator(); boolean detected = false; while (iterator.hasNext()) { final TimeData timeWatchItem = iterator.next(); if (timeWatchItem.isTimePoint() && timeWatchItem.getDetectedStackDepth() >= stackDepth && timePointName.equals(timeWatchItem.getAlertMessage())) { detected |= true; final long detectedDelay = time - timeWatchItem.getCreationTimeInMilliseconds(); try { timeWatchItem.getAlertListener().onTimeAlert(detectedDelay, timeWatchItem); } catch (Exception ex) { final UnexpectedProcessingError error = new UnexpectedProcessingError("Error during time point processing", ex); MetaErrorListeners.fireError(error.getMessage(), error); } finally { iterator.remove(); } } } if (!detected) { throw new IllegalStateException("Can't find time point [" + timePointName + ']'); } }
java
@Weight(value = Weight.Unit.VARIABLE, comment = "Depends on the current call stack depth") public static void checkPoint(@Nonnull final String timePointName) { final long time = System.currentTimeMillis(); final int stackDepth = ThreadUtils.stackDepth(); final List<TimeData> list = REGISTRY.get(); final Iterator<TimeData> iterator = list.iterator(); boolean detected = false; while (iterator.hasNext()) { final TimeData timeWatchItem = iterator.next(); if (timeWatchItem.isTimePoint() && timeWatchItem.getDetectedStackDepth() >= stackDepth && timePointName.equals(timeWatchItem.getAlertMessage())) { detected |= true; final long detectedDelay = time - timeWatchItem.getCreationTimeInMilliseconds(); try { timeWatchItem.getAlertListener().onTimeAlert(detectedDelay, timeWatchItem); } catch (Exception ex) { final UnexpectedProcessingError error = new UnexpectedProcessingError("Error during time point processing", ex); MetaErrorListeners.fireError(error.getMessage(), error); } finally { iterator.remove(); } } } if (!detected) { throw new IllegalStateException("Can't find time point [" + timePointName + ']'); } }
[ "@", "Weight", "(", "value", "=", "Weight", ".", "Unit", ".", "VARIABLE", ",", "comment", "=", "\"Depends on the current call stack depth\"", ")", "public", "static", "void", "checkPoint", "(", "@", "Nonnull", "final", "String", "timePointName", ")", "{", "final", "long", "time", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "final", "int", "stackDepth", "=", "ThreadUtils", ".", "stackDepth", "(", ")", ";", "final", "List", "<", "TimeData", ">", "list", "=", "REGISTRY", ".", "get", "(", ")", ";", "final", "Iterator", "<", "TimeData", ">", "iterator", "=", "list", ".", "iterator", "(", ")", ";", "boolean", "detected", "=", "false", ";", "while", "(", "iterator", ".", "hasNext", "(", ")", ")", "{", "final", "TimeData", "timeWatchItem", "=", "iterator", ".", "next", "(", ")", ";", "if", "(", "timeWatchItem", ".", "isTimePoint", "(", ")", "&&", "timeWatchItem", ".", "getDetectedStackDepth", "(", ")", ">=", "stackDepth", "&&", "timePointName", ".", "equals", "(", "timeWatchItem", ".", "getAlertMessage", "(", ")", ")", ")", "{", "detected", "|=", "true", ";", "final", "long", "detectedDelay", "=", "time", "-", "timeWatchItem", ".", "getCreationTimeInMilliseconds", "(", ")", ";", "try", "{", "timeWatchItem", ".", "getAlertListener", "(", ")", ".", "onTimeAlert", "(", "detectedDelay", ",", "timeWatchItem", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "final", "UnexpectedProcessingError", "error", "=", "new", "UnexpectedProcessingError", "(", "\"Error during time point processing\"", ",", "ex", ")", ";", "MetaErrorListeners", ".", "fireError", "(", "error", ".", "getMessage", "(", ")", ",", "error", ")", ";", "}", "finally", "{", "iterator", ".", "remove", "(", ")", ";", "}", "}", "}", "if", "(", "!", "detected", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Can't find time point [\"", "+", "timePointName", "+", "'", "'", ")", ";", "}", "}" ]
Check named time point(s). Listener registered for the point will be notified and the point will be removed. @param timePointName the name of time point @since 1.0
[ "Check", "named", "time", "point", "(", "s", ")", ".", "Listener", "registered", "for", "the", "point", "will", "be", "notified", "and", "the", "point", "will", "be", "removed", "." ]
train
https://github.com/raydac/meta/blob/0607320ecd0734d69e6496a2714255b64adae435/meta-utils/src/main/java/com/igormaznitsa/meta/common/utils/TimeGuard.java#L255-L284
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java
SpringPlugin.bytesWithInstanceCreationCaptured
private byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) { ClassReader cr = new ClassReader(bytes); ClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; }
java
private byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) { ClassReader cr = new ClassReader(bytes); ClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; }
[ "private", "byte", "[", "]", "bytesWithInstanceCreationCaptured", "(", "byte", "[", "]", "bytes", ",", "String", "classToCall", ",", "String", "methodToCall", ")", "{", "ClassReader", "cr", "=", "new", "ClassReader", "(", "bytes", ")", ";", "ClassVisitingConstructorAppender", "ca", "=", "new", "ClassVisitingConstructorAppender", "(", "classToCall", ",", "methodToCall", ")", ";", "cr", ".", "accept", "(", "ca", ",", "0", ")", ";", "byte", "[", "]", "newbytes", "=", "ca", ".", "getBytes", "(", ")", ";", "return", "newbytes", ";", "}" ]
Modify the supplied bytes such that constructors are intercepted and will invoke the specified class/method so that the instances can be tracked. @return modified bytes for the class
[ "Modify", "the", "supplied", "bytes", "such", "that", "constructors", "are", "intercepted", "and", "will", "invoke", "the", "specified", "class", "/", "method", "so", "that", "the", "instances", "can", "be", "tracked", "." ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java#L515-L521
apache/flink
flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/gateway/local/ProgramDeployer.java
ProgramDeployer.deployJob
private <T> void deployJob(ExecutionContext<T> context, JobGraph jobGraph, Result<T> result) { // create or retrieve cluster and deploy job try (final ClusterDescriptor<T> clusterDescriptor = context.createClusterDescriptor()) { try { // new cluster if (context.getClusterId() == null) { deployJobOnNewCluster(clusterDescriptor, jobGraph, result, context.getClassLoader()); } // reuse existing cluster else { deployJobOnExistingCluster(context.getClusterId(), clusterDescriptor, jobGraph, result); } } catch (Exception e) { throw new SqlExecutionException("Could not retrieve or create a cluster.", e); } } catch (SqlExecutionException e) { throw e; } catch (Exception e) { throw new SqlExecutionException("Could not locate a cluster.", e); } }
java
private <T> void deployJob(ExecutionContext<T> context, JobGraph jobGraph, Result<T> result) { // create or retrieve cluster and deploy job try (final ClusterDescriptor<T> clusterDescriptor = context.createClusterDescriptor()) { try { // new cluster if (context.getClusterId() == null) { deployJobOnNewCluster(clusterDescriptor, jobGraph, result, context.getClassLoader()); } // reuse existing cluster else { deployJobOnExistingCluster(context.getClusterId(), clusterDescriptor, jobGraph, result); } } catch (Exception e) { throw new SqlExecutionException("Could not retrieve or create a cluster.", e); } } catch (SqlExecutionException e) { throw e; } catch (Exception e) { throw new SqlExecutionException("Could not locate a cluster.", e); } }
[ "private", "<", "T", ">", "void", "deployJob", "(", "ExecutionContext", "<", "T", ">", "context", ",", "JobGraph", "jobGraph", ",", "Result", "<", "T", ">", "result", ")", "{", "// create or retrieve cluster and deploy job", "try", "(", "final", "ClusterDescriptor", "<", "T", ">", "clusterDescriptor", "=", "context", ".", "createClusterDescriptor", "(", ")", ")", "{", "try", "{", "// new cluster", "if", "(", "context", ".", "getClusterId", "(", ")", "==", "null", ")", "{", "deployJobOnNewCluster", "(", "clusterDescriptor", ",", "jobGraph", ",", "result", ",", "context", ".", "getClassLoader", "(", ")", ")", ";", "}", "// reuse existing cluster", "else", "{", "deployJobOnExistingCluster", "(", "context", ".", "getClusterId", "(", ")", ",", "clusterDescriptor", ",", "jobGraph", ",", "result", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SqlExecutionException", "(", "\"Could not retrieve or create a cluster.\"", ",", "e", ")", ";", "}", "}", "catch", "(", "SqlExecutionException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "SqlExecutionException", "(", "\"Could not locate a cluster.\"", ",", "e", ")", ";", "}", "}" ]
Deploys a job. Depending on the deployment creates a new job cluster. It saves the cluster id in the result and blocks until job completion.
[ "Deploys", "a", "job", ".", "Depending", "on", "the", "deployment", "creates", "a", "new", "job", "cluster", ".", "It", "saves", "the", "cluster", "id", "in", "the", "result", "and", "blocks", "until", "job", "completion", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/gateway/local/ProgramDeployer.java#L89-L109
JDBDT/jdbdt
src/main/java/org/jdbdt/Log.java
Log.write
void write(CallInfo callInfo, SQLException e) { Element rootNode = root(callInfo); Element exNode = createNode(rootNode, DATABASE_EXCEPTION_TAG); StringWriter sw = new StringWriter(); sw.append('\n'); e.printStackTrace(new PrintWriter(sw)); exNode.appendChild(xmlDoc.createCDATASection(sw.toString())); flush(rootNode); }
java
void write(CallInfo callInfo, SQLException e) { Element rootNode = root(callInfo); Element exNode = createNode(rootNode, DATABASE_EXCEPTION_TAG); StringWriter sw = new StringWriter(); sw.append('\n'); e.printStackTrace(new PrintWriter(sw)); exNode.appendChild(xmlDoc.createCDATASection(sw.toString())); flush(rootNode); }
[ "void", "write", "(", "CallInfo", "callInfo", ",", "SQLException", "e", ")", "{", "Element", "rootNode", "=", "root", "(", "callInfo", ")", ";", "Element", "exNode", "=", "createNode", "(", "rootNode", ",", "DATABASE_EXCEPTION_TAG", ")", ";", "StringWriter", "sw", "=", "new", "StringWriter", "(", ")", ";", "sw", ".", "append", "(", "'", "'", ")", ";", "e", ".", "printStackTrace", "(", "new", "PrintWriter", "(", "sw", ")", ")", ";", "exNode", ".", "appendChild", "(", "xmlDoc", ".", "createCDATASection", "(", "sw", ".", "toString", "(", ")", ")", ")", ";", "flush", "(", "rootNode", ")", ";", "}" ]
Report a database exception onto the log. @param callInfo Call info. @param e Database exception.
[ "Report", "a", "database", "exception", "onto", "the", "log", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/Log.java#L180-L188
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierApplications.java
TypeQualifierApplications.getEffectiveTypeQualifierAnnotation
public static @CheckForNull TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation(final XMethod xmethod, final int parameter, TypeQualifierValue<?> typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, xmethod, parameter); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { @Override public TypeQualifierAnnotation compute(TypeQualifierValue<?> tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, xmethod, parameter); } @Override public String toString() { return "parameter " + parameter + " of " + xmethod; } }); } return tqa; }
java
public static @CheckForNull TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation(final XMethod xmethod, final int parameter, TypeQualifierValue<?> typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, xmethod, parameter); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { @Override public TypeQualifierAnnotation compute(TypeQualifierValue<?> tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, xmethod, parameter); } @Override public String toString() { return "parameter " + parameter + " of " + xmethod; } }); } return tqa; }
[ "public", "static", "@", "CheckForNull", "TypeQualifierAnnotation", "getEffectiveTypeQualifierAnnotation", "(", "final", "XMethod", "xmethod", ",", "final", "int", "parameter", ",", "TypeQualifierValue", "<", "?", ">", "typeQualifierValue", ")", "{", "TypeQualifierAnnotation", "tqa", "=", "computeEffectiveTypeQualifierAnnotation", "(", "typeQualifierValue", ",", "xmethod", ",", "parameter", ")", ";", "if", "(", "CHECK_EXCLUSIVE", "&&", "tqa", "==", "null", "&&", "typeQualifierValue", ".", "isExclusiveQualifier", "(", ")", ")", "{", "tqa", "=", "computeExclusiveQualifier", "(", "typeQualifierValue", ",", "new", "ComputeEffectiveTypeQualifierAnnotation", "(", ")", "{", "@", "Override", "public", "TypeQualifierAnnotation", "compute", "(", "TypeQualifierValue", "<", "?", ">", "tqv", ")", "{", "return", "computeEffectiveTypeQualifierAnnotation", "(", "tqv", ",", "xmethod", ",", "parameter", ")", ";", "}", "@", "Override", "public", "String", "toString", "(", ")", "{", "return", "\"parameter \"", "+", "parameter", "+", "\" of \"", "+", "xmethod", ";", "}", "}", ")", ";", "}", "return", "tqa", ";", "}" ]
Get the effective TypeQualifierAnnotation on given method parameter. Takes into account inherited and default (outer scope) annotations. Also takes exclusive qualifiers into account. @param xmethod a method @param parameter a parameter (0 == first parameter) @param typeQualifierValue the kind of TypeQualifierValue we are looking for @return effective TypeQualifierAnnotation on the parameter, or null if there is no effective TypeQualifierAnnotation
[ "Get", "the", "effective", "TypeQualifierAnnotation", "on", "given", "method", "parameter", ".", "Takes", "into", "account", "inherited", "and", "default", "(", "outer", "scope", ")", "annotations", ".", "Also", "takes", "exclusive", "qualifiers", "into", "account", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierApplications.java#L763-L784
f2prateek/dart
henson/src/main/java/dart/henson/Bundler.java
Bundler.putCharSequenceArrayList
public Bundler putCharSequenceArrayList(String key, ArrayList<CharSequence> value) { delegate.putCharSequenceArrayList(key, value); return this; }
java
public Bundler putCharSequenceArrayList(String key, ArrayList<CharSequence> value) { delegate.putCharSequenceArrayList(key, value); return this; }
[ "public", "Bundler", "putCharSequenceArrayList", "(", "String", "key", ",", "ArrayList", "<", "CharSequence", ">", "value", ")", "{", "delegate", ".", "putCharSequenceArrayList", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts an ArrayList<CharSequence> value into the mapping of the underlying Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList<CharSequence> object, or null @return this bundler instance to chain method calls
[ "Inserts", "an", "ArrayList<CharSequence", ">", "value", "into", "the", "mapping", "of", "the", "underlying", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/f2prateek/dart/blob/7163b1b148e5141817975ae7dad99d58a8589aeb/henson/src/main/java/dart/henson/Bundler.java#L309-L312
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/commons/FileUtils.java
FileUtils.getTempFileFor
public static File getTempFileFor(File file) { File parent = file.getParentFile(); String name = file.getName(); File result; int index = 0; do { result = new File(parent, name + "_" + index++); } while (result.exists()); return result; }
java
public static File getTempFileFor(File file) { File parent = file.getParentFile(); String name = file.getName(); File result; int index = 0; do { result = new File(parent, name + "_" + index++); } while (result.exists()); return result; }
[ "public", "static", "File", "getTempFileFor", "(", "File", "file", ")", "{", "File", "parent", "=", "file", ".", "getParentFile", "(", ")", ";", "String", "name", "=", "file", ".", "getName", "(", ")", ";", "File", "result", ";", "int", "index", "=", "0", ";", "do", "{", "result", "=", "new", "File", "(", "parent", ",", "name", "+", "\"_\"", "+", "index", "++", ")", ";", "}", "while", "(", "result", ".", "exists", "(", ")", ")", ";", "return", "result", ";", "}" ]
Find a non-existing file in the same directory using the same name as prefix. @param file file used for the name and location (it is not read or written). @return a non-existing file in the same directory using the same name as prefix.
[ "Find", "a", "non", "-", "existing", "file", "in", "the", "same", "directory", "using", "the", "same", "name", "as", "prefix", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/commons/FileUtils.java#L69-L79
geomajas/geomajas-project-client-gwt2
plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java
TileBasedLayerClient.createOsmMap
public MapConfiguration createOsmMap(int nrOfLevels) { MapConfiguration configuration = new MapConfigurationImpl(); Bbox bounds = new Bbox(-OSM_HALF_WIDTH, -OSM_HALF_WIDTH, 2 * OSM_HALF_WIDTH, 2 * OSM_HALF_WIDTH); configuration.setCrs(OSM_EPSG, CrsType.METRIC); configuration.setHintValue(MapConfiguration.INITIAL_BOUNDS, bounds); configuration.setMaxBounds(Bbox.ALL); List<Double> resolutions = new ArrayList<Double>(); for (int i = 0; i < nrOfLevels; i++) { resolutions.add(OSM_HALF_WIDTH / (OSM_TILE_SIZE * Math.pow(2, i - 1))); } configuration.setResolutions(resolutions); return configuration; }
java
public MapConfiguration createOsmMap(int nrOfLevels) { MapConfiguration configuration = new MapConfigurationImpl(); Bbox bounds = new Bbox(-OSM_HALF_WIDTH, -OSM_HALF_WIDTH, 2 * OSM_HALF_WIDTH, 2 * OSM_HALF_WIDTH); configuration.setCrs(OSM_EPSG, CrsType.METRIC); configuration.setHintValue(MapConfiguration.INITIAL_BOUNDS, bounds); configuration.setMaxBounds(Bbox.ALL); List<Double> resolutions = new ArrayList<Double>(); for (int i = 0; i < nrOfLevels; i++) { resolutions.add(OSM_HALF_WIDTH / (OSM_TILE_SIZE * Math.pow(2, i - 1))); } configuration.setResolutions(resolutions); return configuration; }
[ "public", "MapConfiguration", "createOsmMap", "(", "int", "nrOfLevels", ")", "{", "MapConfiguration", "configuration", "=", "new", "MapConfigurationImpl", "(", ")", ";", "Bbox", "bounds", "=", "new", "Bbox", "(", "-", "OSM_HALF_WIDTH", ",", "-", "OSM_HALF_WIDTH", ",", "2", "*", "OSM_HALF_WIDTH", ",", "2", "*", "OSM_HALF_WIDTH", ")", ";", "configuration", ".", "setCrs", "(", "OSM_EPSG", ",", "CrsType", ".", "METRIC", ")", ";", "configuration", ".", "setHintValue", "(", "MapConfiguration", ".", "INITIAL_BOUNDS", ",", "bounds", ")", ";", "configuration", ".", "setMaxBounds", "(", "Bbox", ".", "ALL", ")", ";", "List", "<", "Double", ">", "resolutions", "=", "new", "ArrayList", "<", "Double", ">", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nrOfLevels", ";", "i", "++", ")", "{", "resolutions", ".", "add", "(", "OSM_HALF_WIDTH", "/", "(", "OSM_TILE_SIZE", "*", "Math", ".", "pow", "(", "2", ",", "i", "-", "1", ")", ")", ")", ";", "}", "configuration", ".", "setResolutions", "(", "resolutions", ")", ";", "return", "configuration", ";", "}" ]
Create an OSM compliant map configuration with this number of zoom levels. @param nrOfLevels @return
[ "Create", "an", "OSM", "compliant", "map", "configuration", "with", "this", "number", "of", "zoom", "levels", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L94-L106
graknlabs/grakn
server/src/graql/executor/ComputeExecutor.java
ComputeExecutor.initStatisticsVertexProgram
private VertexProgram initStatisticsVertexProgram(GraqlCompute query, Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) { if (query.method().equals(MEDIAN)) return new MedianVertexProgram(targetTypes, targetDataType); else return new DegreeStatisticsVertexProgram(targetTypes); }
java
private VertexProgram initStatisticsVertexProgram(GraqlCompute query, Set<LabelId> targetTypes, AttributeType.DataType<?> targetDataType) { if (query.method().equals(MEDIAN)) return new MedianVertexProgram(targetTypes, targetDataType); else return new DegreeStatisticsVertexProgram(targetTypes); }
[ "private", "VertexProgram", "initStatisticsVertexProgram", "(", "GraqlCompute", "query", ",", "Set", "<", "LabelId", ">", "targetTypes", ",", "AttributeType", ".", "DataType", "<", "?", ">", "targetDataType", ")", "{", "if", "(", "query", ".", "method", "(", ")", ".", "equals", "(", "MEDIAN", ")", ")", "return", "new", "MedianVertexProgram", "(", "targetTypes", ",", "targetDataType", ")", ";", "else", "return", "new", "DegreeStatisticsVertexProgram", "(", "targetTypes", ")", ";", "}" ]
Helper method to intialise the vertex program for compute statistics queries @param query representing the compute query @param targetTypes representing the attribute types in which the statistics computation is targeted for @param targetDataType representing the data type of the target attribute types @return an object which is a subclass of VertexProgram
[ "Helper", "method", "to", "intialise", "the", "vertex", "program", "for", "compute", "statistics", "queries" ]
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L263-L266
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/model/monitor/ServiceLevelAgreement.java
ServiceLevelAgreement.unitsToSeconds
public static int unitsToSeconds(String interval, String unit) { if (interval == null || interval.isEmpty()) return 0; else if (unit == null) return (int)(Double.parseDouble(interval)); else if (unit.equals(INTERVAL_DAYS)) return (int)(Double.parseDouble(interval)*86400); else if (unit.equals(INTERVAL_HOURS)) return (int)(Double.parseDouble(interval)*3600); else if (unit.equals(INTERVAL_MINUTES)) return (int)(Double.parseDouble(interval)*60); else return (int)(Double.parseDouble(interval)); }
java
public static int unitsToSeconds(String interval, String unit) { if (interval == null || interval.isEmpty()) return 0; else if (unit == null) return (int)(Double.parseDouble(interval)); else if (unit.equals(INTERVAL_DAYS)) return (int)(Double.parseDouble(interval)*86400); else if (unit.equals(INTERVAL_HOURS)) return (int)(Double.parseDouble(interval)*3600); else if (unit.equals(INTERVAL_MINUTES)) return (int)(Double.parseDouble(interval)*60); else return (int)(Double.parseDouble(interval)); }
[ "public", "static", "int", "unitsToSeconds", "(", "String", "interval", ",", "String", "unit", ")", "{", "if", "(", "interval", "==", "null", "||", "interval", ".", "isEmpty", "(", ")", ")", "return", "0", ";", "else", "if", "(", "unit", "==", "null", ")", "return", "(", "int", ")", "(", "Double", ".", "parseDouble", "(", "interval", ")", ")", ";", "else", "if", "(", "unit", ".", "equals", "(", "INTERVAL_DAYS", ")", ")", "return", "(", "int", ")", "(", "Double", ".", "parseDouble", "(", "interval", ")", "*", "86400", ")", ";", "else", "if", "(", "unit", ".", "equals", "(", "INTERVAL_HOURS", ")", ")", "return", "(", "int", ")", "(", "Double", ".", "parseDouble", "(", "interval", ")", "*", "3600", ")", ";", "else", "if", "(", "unit", ".", "equals", "(", "INTERVAL_MINUTES", ")", ")", "return", "(", "int", ")", "(", "Double", ".", "parseDouble", "(", "interval", ")", "*", "60", ")", ";", "else", "return", "(", "int", ")", "(", "Double", ".", "parseDouble", "(", "interval", ")", ")", ";", "}" ]
Convert interval of specified unit to seconds @param interval @param unit @return
[ "Convert", "interval", "of", "specified", "unit", "to", "seconds" ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/model/monitor/ServiceLevelAgreement.java#L68-L75
google/j2objc
jre_emul/android/platform/libcore/luni/src/objc/java/libcore/icu/TimeZoneNames.java
TimeZoneNames.fillZoneStrings
private static void fillZoneStrings(String localeId, String[][] result) { for (int i = 0; i < result.length; i++) { fillZoneStringNames(localeId, result[i]); } }
java
private static void fillZoneStrings(String localeId, String[][] result) { for (int i = 0; i < result.length; i++) { fillZoneStringNames(localeId, result[i]); } }
[ "private", "static", "void", "fillZoneStrings", "(", "String", "localeId", ",", "String", "[", "]", "[", "]", "result", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "result", ".", "length", ";", "i", "++", ")", "{", "fillZoneStringNames", "(", "localeId", ",", "result", "[", "i", "]", ")", ";", "}", "}" ]
/* J2ObjC: unused. public static native String getExemplarLocation(String locale, String tz);
[ "/", "*", "J2ObjC", ":", "unused", ".", "public", "static", "native", "String", "getExemplarLocation", "(", "String", "locale", "String", "tz", ")", ";" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/objc/java/libcore/icu/TimeZoneNames.java#L164-L168
JodaOrg/joda-money
src/main/java/org/joda/money/BigMoney.java
BigMoney.minusRetainScale
public BigMoney minusRetainScale(BigMoneyProvider moneyToSubtract, RoundingMode roundingMode) { BigMoney toSubtract = checkCurrencyEqual(moneyToSubtract); return minusRetainScale(toSubtract.getAmount(), roundingMode); }
java
public BigMoney minusRetainScale(BigMoneyProvider moneyToSubtract, RoundingMode roundingMode) { BigMoney toSubtract = checkCurrencyEqual(moneyToSubtract); return minusRetainScale(toSubtract.getAmount(), roundingMode); }
[ "public", "BigMoney", "minusRetainScale", "(", "BigMoneyProvider", "moneyToSubtract", ",", "RoundingMode", "roundingMode", ")", "{", "BigMoney", "toSubtract", "=", "checkCurrencyEqual", "(", "moneyToSubtract", ")", ";", "return", "minusRetainScale", "(", "toSubtract", ".", "getAmount", "(", ")", ",", "roundingMode", ")", ";", "}" ]
Returns a copy of this monetary value with the amount in the same currency subtracted retaining the scale by rounding the result. <p> The scale of the result will be the same as the scale of this instance. For example,'USD 25.95' minus 'USD 3.029' gives 'USD 22.92 with most rounding modes. <p> This instance is immutable and unaffected by this method. @param moneyToSubtract the monetary value to add, not null @param roundingMode the rounding mode to use to adjust the scale, not null @return the new instance with the input amount subtracted, never null
[ "Returns", "a", "copy", "of", "this", "monetary", "value", "with", "the", "amount", "in", "the", "same", "currency", "subtracted", "retaining", "the", "scale", "by", "rounding", "the", "result", ".", "<p", ">", "The", "scale", "of", "the", "result", "will", "be", "the", "same", "as", "the", "scale", "of", "this", "instance", ".", "For", "example", "USD", "25", ".", "95", "minus", "USD", "3", ".", "029", "gives", "USD", "22", ".", "92", "with", "most", "rounding", "modes", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "." ]
train
https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L1179-L1182
jbundle/jbundle
thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/base/PDatabase.java
PDatabase.getPTable
public synchronized PTable getPTable(FieldList record, boolean bCreateIfNotFound, boolean bEnableGridAccess) { Object objKey = this.generateKey(record); PTable physicalTable = (PTable)m_htTableList.get(objKey); if (bCreateIfNotFound) if (physicalTable == null) physicalTable = this.makeNewPTable(record, objKey); if (bEnableGridAccess) new GridMemoryFieldTable(record, physicalTable, null); return physicalTable; }
java
public synchronized PTable getPTable(FieldList record, boolean bCreateIfNotFound, boolean bEnableGridAccess) { Object objKey = this.generateKey(record); PTable physicalTable = (PTable)m_htTableList.get(objKey); if (bCreateIfNotFound) if (physicalTable == null) physicalTable = this.makeNewPTable(record, objKey); if (bEnableGridAccess) new GridMemoryFieldTable(record, physicalTable, null); return physicalTable; }
[ "public", "synchronized", "PTable", "getPTable", "(", "FieldList", "record", ",", "boolean", "bCreateIfNotFound", ",", "boolean", "bEnableGridAccess", ")", "{", "Object", "objKey", "=", "this", ".", "generateKey", "(", "record", ")", ";", "PTable", "physicalTable", "=", "(", "PTable", ")", "m_htTableList", ".", "get", "(", "objKey", ")", ";", "if", "(", "bCreateIfNotFound", ")", "if", "(", "physicalTable", "==", "null", ")", "physicalTable", "=", "this", ".", "makeNewPTable", "(", "record", ",", "objKey", ")", ";", "if", "(", "bEnableGridAccess", ")", "new", "GridMemoryFieldTable", "(", "record", ",", "physicalTable", ",", "null", ")", ";", "return", "physicalTable", ";", "}" ]
Get the physical table that matches this BaseTable and create it if it doesn't exist. Note: If the bCreateIfNotFound flag was set, create the new table or bump the use count. @param table The table to create a raw data table from. @return The raw data table (creates a new one if it doesn't already exist).
[ "Get", "the", "physical", "table", "that", "matches", "this", "BaseTable", "and", "create", "it", "if", "it", "doesn", "t", "exist", ".", "Note", ":", "If", "the", "bCreateIfNotFound", "flag", "was", "set", "create", "the", "new", "table", "or", "bump", "the", "use", "count", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/thin/base/db/base/src/main/java/org/jbundle/thin/base/db/mem/base/PDatabase.java#L265-L275
davetcc/tcMenu
tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/domain/state/MenuTree.java
MenuTree.changeItem
public <T> void changeItem(MenuItem<T> item, MenuState<T> menuState) { menuStates.put(item.getId(), menuState); }
java
public <T> void changeItem(MenuItem<T> item, MenuState<T> menuState) { menuStates.put(item.getId(), menuState); }
[ "public", "<", "T", ">", "void", "changeItem", "(", "MenuItem", "<", "T", ">", "item", ",", "MenuState", "<", "T", ">", "menuState", ")", "{", "menuStates", ".", "put", "(", "item", ".", "getId", "(", ")", ",", "menuState", ")", ";", "}" ]
Change the value that's associated with a menu item. if you are changing a value, just send a command to the device, it will automatically update the tree. @param item the item to change @param menuState the new state @param <T> the type of the state, picked up automatically
[ "Change", "the", "value", "that", "s", "associated", "with", "a", "menu", "item", ".", "if", "you", "are", "changing", "a", "value", "just", "send", "a", "command", "to", "the", "device", "it", "will", "automatically", "update", "the", "tree", "." ]
train
https://github.com/davetcc/tcMenu/blob/61546e4b982b25ceaff384073fe9ec1fff55e64a/tcMenuJavaApi/src/main/java/com/thecoderscorner/menu/domain/state/MenuTree.java#L258-L260
RestComm/media-core
stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java
StunMessage.setTransactionID
public void setTransactionID(byte[] tranID) throws StunException { if (tranID == null || (tranID.length != TRANSACTION_ID_LENGTH && tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) throw new StunException(StunException.ILLEGAL_ARGUMENT, "Invalid transaction id length"); int tranIDLength = tranID.length; this.transactionID = new byte[tranIDLength]; System.arraycopy(tranID, 0, this.transactionID, 0, tranIDLength); }
java
public void setTransactionID(byte[] tranID) throws StunException { if (tranID == null || (tranID.length != TRANSACTION_ID_LENGTH && tranID.length != RFC3489_TRANSACTION_ID_LENGTH)) throw new StunException(StunException.ILLEGAL_ARGUMENT, "Invalid transaction id length"); int tranIDLength = tranID.length; this.transactionID = new byte[tranIDLength]; System.arraycopy(tranID, 0, this.transactionID, 0, tranIDLength); }
[ "public", "void", "setTransactionID", "(", "byte", "[", "]", "tranID", ")", "throws", "StunException", "{", "if", "(", "tranID", "==", "null", "||", "(", "tranID", ".", "length", "!=", "TRANSACTION_ID_LENGTH", "&&", "tranID", ".", "length", "!=", "RFC3489_TRANSACTION_ID_LENGTH", ")", ")", "throw", "new", "StunException", "(", "StunException", ".", "ILLEGAL_ARGUMENT", ",", "\"Invalid transaction id length\"", ")", ";", "int", "tranIDLength", "=", "tranID", ".", "length", ";", "this", ".", "transactionID", "=", "new", "byte", "[", "tranIDLength", "]", ";", "System", ".", "arraycopy", "(", "tranID", ",", "0", ",", "this", ".", "transactionID", ",", "0", ",", "tranIDLength", ")", ";", "}" ]
Copies the specified tranID and sets it as this message's transactionID. @param tranID the transaction id to set in this message. @throws StunException ILLEGAL_ARGUMENT if the transaction id is not valid.
[ "Copies", "the", "specified", "tranID", "and", "sets", "it", "as", "this", "message", "s", "transactionID", "." ]
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/stun/src/main/java/org/restcomm/media/core/stun/messages/StunMessage.java#L439-L446
BlueBrain/bluima
modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/GIS.java
GIS.trainModel
public static GISModel trainModel(int iterations, DataIndexer indexer, boolean printMessagesWhileTraining, boolean smoothing) { GISTrainer trainer = new GISTrainer(printMessagesWhileTraining); trainer.setSmoothing(smoothing); trainer.setSmoothingObservation(SMOOTHING_OBSERVATION); return trainer.trainModel(iterations, indexer); }
java
public static GISModel trainModel(int iterations, DataIndexer indexer, boolean printMessagesWhileTraining, boolean smoothing) { GISTrainer trainer = new GISTrainer(printMessagesWhileTraining); trainer.setSmoothing(smoothing); trainer.setSmoothingObservation(SMOOTHING_OBSERVATION); return trainer.trainModel(iterations, indexer); }
[ "public", "static", "GISModel", "trainModel", "(", "int", "iterations", ",", "DataIndexer", "indexer", ",", "boolean", "printMessagesWhileTraining", ",", "boolean", "smoothing", ")", "{", "GISTrainer", "trainer", "=", "new", "GISTrainer", "(", "printMessagesWhileTraining", ")", ";", "trainer", ".", "setSmoothing", "(", "smoothing", ")", ";", "trainer", ".", "setSmoothingObservation", "(", "SMOOTHING_OBSERVATION", ")", ";", "return", "trainer", ".", "trainModel", "(", "iterations", ",", "indexer", ")", ";", "}" ]
Train a model using the GIS algorithm. @param iterations The number of GIS iterations to perform. @param indexer The object which will be used for event compilation. @param printMessagesWhileTraining Determines whether training status messages are written to STDOUT. @param smoothing Defines whether the created trainer will use smoothing while training the model. @return The newly trained model, which can be used immediately or saved to disk using an opennlp.maxent.io.GISModelWriter object.
[ "Train", "a", "model", "using", "the", "GIS", "algorithm", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_opennlp/src/main/java/ch/epfl/bbp/shaded/opennlp/maxent/GIS.java#L130-L135
dita-ot/dita-ot
src/main/plugins/org.dita.eclipsehelp/src/main/java/org/dita/dost/writer/EclipseIndexWriter.java
EclipseIndexWriter.outputIndexTermStartElement
private void outputIndexTermStartElement(final IndexTerm term, final XMLStreamWriter serializer, final boolean indexsee) throws XMLStreamException { //RFE 2987769 Eclipse index-see if (indexsee){ if (term.getTermPrefix() != null) { inIndexsee = true; serializer.writeStartElement("see"); serializer.writeAttribute("keyword", term.getTermName()); } else if (inIndexsee) { // subterm of an indexsee. serializer.writeStartElement("subpath"); serializer.writeAttribute("keyword", term.getTermName()); serializer.writeEndElement(); // subpath } else { serializer.writeStartElement("entry"); serializer.writeAttribute("keyword", term.getTermName()); outputIndexEntryEclipseIndexsee(term, serializer); } } else { serializer.writeStartElement("entry"); serializer.writeAttribute("keyword", term.getTermFullName()); outputIndexEntry(term, serializer); } }
java
private void outputIndexTermStartElement(final IndexTerm term, final XMLStreamWriter serializer, final boolean indexsee) throws XMLStreamException { //RFE 2987769 Eclipse index-see if (indexsee){ if (term.getTermPrefix() != null) { inIndexsee = true; serializer.writeStartElement("see"); serializer.writeAttribute("keyword", term.getTermName()); } else if (inIndexsee) { // subterm of an indexsee. serializer.writeStartElement("subpath"); serializer.writeAttribute("keyword", term.getTermName()); serializer.writeEndElement(); // subpath } else { serializer.writeStartElement("entry"); serializer.writeAttribute("keyword", term.getTermName()); outputIndexEntryEclipseIndexsee(term, serializer); } } else { serializer.writeStartElement("entry"); serializer.writeAttribute("keyword", term.getTermFullName()); outputIndexEntry(term, serializer); } }
[ "private", "void", "outputIndexTermStartElement", "(", "final", "IndexTerm", "term", ",", "final", "XMLStreamWriter", "serializer", ",", "final", "boolean", "indexsee", ")", "throws", "XMLStreamException", "{", "//RFE 2987769 Eclipse index-see", "if", "(", "indexsee", ")", "{", "if", "(", "term", ".", "getTermPrefix", "(", ")", "!=", "null", ")", "{", "inIndexsee", "=", "true", ";", "serializer", ".", "writeStartElement", "(", "\"see\"", ")", ";", "serializer", ".", "writeAttribute", "(", "\"keyword\"", ",", "term", ".", "getTermName", "(", ")", ")", ";", "}", "else", "if", "(", "inIndexsee", ")", "{", "// subterm of an indexsee.", "serializer", ".", "writeStartElement", "(", "\"subpath\"", ")", ";", "serializer", ".", "writeAttribute", "(", "\"keyword\"", ",", "term", ".", "getTermName", "(", ")", ")", ";", "serializer", ".", "writeEndElement", "(", ")", ";", "// subpath", "}", "else", "{", "serializer", ".", "writeStartElement", "(", "\"entry\"", ")", ";", "serializer", ".", "writeAttribute", "(", "\"keyword\"", ",", "term", ".", "getTermName", "(", ")", ")", ";", "outputIndexEntryEclipseIndexsee", "(", "term", ",", "serializer", ")", ";", "}", "}", "else", "{", "serializer", ".", "writeStartElement", "(", "\"entry\"", ")", ";", "serializer", ".", "writeAttribute", "(", "\"keyword\"", ",", "term", ".", "getTermFullName", "(", ")", ")", ";", "outputIndexEntry", "(", "term", ",", "serializer", ")", ";", "}", "}" ]
/* Logic for adding various start index entry elements for Eclipse help. @param term The indexterm to be processed. @param printWriter The Writer used for writing content to disk. @param indexsee Boolean value for using the new markup for see references.
[ "/", "*", "Logic", "for", "adding", "various", "start", "index", "entry", "elements", "for", "Eclipse", "help", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/plugins/org.dita.eclipsehelp/src/main/java/org/dita/dost/writer/EclipseIndexWriter.java#L316-L337
alkacon/opencms-core
src/org/opencms/ade/containerpage/CmsContainerpageService.java
CmsContainerpageService.isEditSmallElements
private boolean isEditSmallElements(HttpServletRequest request, CmsObject cms) { CmsUser user = cms.getRequestContext().getCurrentUser(); String editSmallElementsStr = (String)(user.getAdditionalInfo().get(ADDINFO_EDIT_SMALL_ELEMENTS)); if (editSmallElementsStr == null) { return true; } else { return Boolean.valueOf(editSmallElementsStr).booleanValue(); } }
java
private boolean isEditSmallElements(HttpServletRequest request, CmsObject cms) { CmsUser user = cms.getRequestContext().getCurrentUser(); String editSmallElementsStr = (String)(user.getAdditionalInfo().get(ADDINFO_EDIT_SMALL_ELEMENTS)); if (editSmallElementsStr == null) { return true; } else { return Boolean.valueOf(editSmallElementsStr).booleanValue(); } }
[ "private", "boolean", "isEditSmallElements", "(", "HttpServletRequest", "request", ",", "CmsObject", "cms", ")", "{", "CmsUser", "user", "=", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ";", "String", "editSmallElementsStr", "=", "(", "String", ")", "(", "user", ".", "getAdditionalInfo", "(", ")", ".", "get", "(", "ADDINFO_EDIT_SMALL_ELEMENTS", ")", ")", ";", "if", "(", "editSmallElementsStr", "==", "null", ")", "{", "return", "true", ";", "}", "else", "{", "return", "Boolean", ".", "valueOf", "(", "editSmallElementsStr", ")", ".", "booleanValue", "(", ")", ";", "}", "}" ]
Checks if small elements in a container page should be initially editable.<p> @param request the current request @param cms the current CMS context @return true if small elements should be initially editable
[ "Checks", "if", "small", "elements", "in", "a", "container", "page", "should", "be", "initially", "editable", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsContainerpageService.java#L2739-L2748
qiniu/java-sdk
src/main/java/com/qiniu/storage/UploadManager.java
UploadManager.put
public Response put(File file, String key, String token) throws QiniuException { return put(file, key, token, null, null, false); }
java
public Response put(File file, String key, String token) throws QiniuException { return put(file, key, token, null, null, false); }
[ "public", "Response", "put", "(", "File", "file", ",", "String", "key", ",", "String", "token", ")", "throws", "QiniuException", "{", "return", "put", "(", "file", ",", "key", ",", "token", ",", "null", ",", "null", ",", "false", ")", ";", "}" ]
上传文件 @param file 上传的文件对象 @param key 上传文件保存的文件名 @param token 上传凭证
[ "上传文件" ]
train
https://github.com/qiniu/java-sdk/blob/6c05f3fb718403a496c725b048e9241f80171499/src/main/java/com/qiniu/storage/UploadManager.java#L185-L187
mapbox/mapbox-navigation-android
libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorThreadListener.java
RouteProcessorThreadListener.onCheckFasterRoute
@Override public void onCheckFasterRoute(Location location, RouteProgress routeProgress, boolean checkFasterRoute) { if (checkFasterRoute) { routeFetcher.findRouteFromRouteProgress(location, routeProgress); } }
java
@Override public void onCheckFasterRoute(Location location, RouteProgress routeProgress, boolean checkFasterRoute) { if (checkFasterRoute) { routeFetcher.findRouteFromRouteProgress(location, routeProgress); } }
[ "@", "Override", "public", "void", "onCheckFasterRoute", "(", "Location", "location", ",", "RouteProgress", "routeProgress", ",", "boolean", "checkFasterRoute", ")", "{", "if", "(", "checkFasterRoute", ")", "{", "routeFetcher", ".", "findRouteFromRouteProgress", "(", "location", ",", "routeProgress", ")", ";", "}", "}" ]
RouteListener from the {@link RouteProcessorBackgroundThread} - if fired with checkFasterRoute set to true, a new {@link DirectionsRoute} should be fetched with {@link RouteFetcher}. @param location to create a new origin @param routeProgress for various {@link com.mapbox.api.directions.v5.models.LegStep} data @param checkFasterRoute true if should check for faster route, false otherwise
[ "RouteListener", "from", "the", "{", "@link", "RouteProcessorBackgroundThread", "}", "-", "if", "fired", "with", "checkFasterRoute", "set", "to", "true", "a", "new", "{", "@link", "DirectionsRoute", "}", "should", "be", "fetched", "with", "{", "@link", "RouteFetcher", "}", "." ]
train
https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/navigation/RouteProcessorThreadListener.java#L69-L74
PSDev/LicensesDialog
licensesdialog/src/main/java/de/psdev/licensesdialog/LicenseResolver.java
LicenseResolver.read
public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", trimmedLicense)); } }
java
public static License read(final String license) { final String trimmedLicense = license.trim(); if (sLicenses.containsKey(trimmedLicense)) { return sLicenses.get(trimmedLicense); } else { throw new IllegalStateException(String.format("no such license available: %s, did you forget to register it?", trimmedLicense)); } }
[ "public", "static", "License", "read", "(", "final", "String", "license", ")", "{", "final", "String", "trimmedLicense", "=", "license", ".", "trim", "(", ")", ";", "if", "(", "sLicenses", ".", "containsKey", "(", "trimmedLicense", ")", ")", "{", "return", "sLicenses", ".", "get", "(", "trimmedLicense", ")", ";", "}", "else", "{", "throw", "new", "IllegalStateException", "(", "String", ".", "format", "(", "\"no such license available: %s, did you forget to register it?\"", ",", "trimmedLicense", ")", ")", ";", "}", "}" ]
Get a license by name @param license license name @return License @throws java.lang.IllegalStateException when unknown license is requested
[ "Get", "a", "license", "by", "name" ]
train
https://github.com/PSDev/LicensesDialog/blob/c09b669cbf8f70bf5509da4b0b57910a1f5dcba8/licensesdialog/src/main/java/de/psdev/licensesdialog/LicenseResolver.java#L83-L90
xqbase/util
util/src/main/java/com/xqbase/util/Bytes.java
Bytes.setShort
public static void setShort(int n, byte[] b, int off, boolean littleEndian) { if (littleEndian) { b[off] = (byte) n; b[off + 1] = (byte) (n >>> 8); } else { b[off] = (byte) (n >>> 8); b[off + 1] = (byte) n; } }
java
public static void setShort(int n, byte[] b, int off, boolean littleEndian) { if (littleEndian) { b[off] = (byte) n; b[off + 1] = (byte) (n >>> 8); } else { b[off] = (byte) (n >>> 8); b[off + 1] = (byte) n; } }
[ "public", "static", "void", "setShort", "(", "int", "n", ",", "byte", "[", "]", "b", ",", "int", "off", ",", "boolean", "littleEndian", ")", "{", "if", "(", "littleEndian", ")", "{", "b", "[", "off", "]", "=", "(", "byte", ")", "n", ";", "b", "[", "off", "+", "1", "]", "=", "(", "byte", ")", "(", "n", ">>>", "8", ")", ";", "}", "else", "{", "b", "[", "off", "]", "=", "(", "byte", ")", "(", "n", ">>>", "8", ")", ";", "b", "[", "off", "+", "1", "]", "=", "(", "byte", ")", "n", ";", "}", "}" ]
Store a <b>short</b> number into a byte array in a given byte order
[ "Store", "a", "<b", ">", "short<", "/", "b", ">", "number", "into", "a", "byte", "array", "in", "a", "given", "byte", "order" ]
train
https://github.com/xqbase/util/blob/e7b9167b6c701b9eec988a9d1e68446cef5ef420/util/src/main/java/com/xqbase/util/Bytes.java#L108-L116
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/AuditorFactory.java
AuditorFactory.getAuditor
public static IHEAuditor getAuditor(String className, boolean useGlobalConfig, boolean useGlobalContext) { Class<? extends IHEAuditor> clazz = AuditorFactory.getAuditorClassForClassName(className); return getAuditor(clazz,useGlobalConfig, useGlobalContext); }
java
public static IHEAuditor getAuditor(String className, boolean useGlobalConfig, boolean useGlobalContext) { Class<? extends IHEAuditor> clazz = AuditorFactory.getAuditorClassForClassName(className); return getAuditor(clazz,useGlobalConfig, useGlobalContext); }
[ "public", "static", "IHEAuditor", "getAuditor", "(", "String", "className", ",", "boolean", "useGlobalConfig", ",", "boolean", "useGlobalContext", ")", "{", "Class", "<", "?", "extends", "IHEAuditor", ">", "clazz", "=", "AuditorFactory", ".", "getAuditorClassForClassName", "(", "className", ")", ";", "return", "getAuditor", "(", "clazz", ",", "useGlobalConfig", ",", "useGlobalContext", ")", ";", "}" ]
Get an auditor instance for the specified auditor class name. Auditor will use a standalone configuration or context if a non-global configuration / context is requested. If a standalone configuration is requested, the existing global configuration is cloned and used as the base configuration. @param className Class name of the auditor class to instantiate @param useGlobalConfig Whether to use the global (true) or standalone (false) config @param useGlobalContext Whether to use the global (true) or standalone (false) context @return Instance of an IHE Auditor
[ "Get", "an", "auditor", "instance", "for", "the", "specified", "auditor", "class", "name", ".", "Auditor", "will", "use", "a", "standalone", "configuration", "or", "context", "if", "a", "non", "-", "global", "configuration", "/", "context", "is", "requested", ".", "If", "a", "standalone", "configuration", "is", "requested", "the", "existing", "global", "configuration", "is", "cloned", "and", "used", "as", "the", "base", "configuration", "." ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/AuditorFactory.java#L139-L143
playn/playn
core/src/playn/core/Surface.java
Surface.drawLine
public Surface drawLine (XY a, XY b, float width) { return drawLine(a.x(), a.y(), b.x(), b.y(), width); }
java
public Surface drawLine (XY a, XY b, float width) { return drawLine(a.x(), a.y(), b.x(), b.y(), width); }
[ "public", "Surface", "drawLine", "(", "XY", "a", ",", "XY", "b", ",", "float", "width", ")", "{", "return", "drawLine", "(", "a", ".", "x", "(", ")", ",", "a", ".", "y", "(", ")", ",", "b", ".", "x", "(", ")", ",", "b", ".", "y", "(", ")", ",", "width", ")", ";", "}" ]
Fills a line between the specified coordinates, of the specified display unit width.
[ "Fills", "a", "line", "between", "the", "specified", "coordinates", "of", "the", "specified", "display", "unit", "width", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/Surface.java#L346-L348
xcesco/kripton
kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java
XMLSerializer.writeAttribute
public void writeAttribute(String namespaceURI, String localName, String value) throws Exception { this.attribute(namespaceURI, localName, value.toString()); }
java
public void writeAttribute(String namespaceURI, String localName, String value) throws Exception { this.attribute(namespaceURI, localName, value.toString()); }
[ "public", "void", "writeAttribute", "(", "String", "namespaceURI", ",", "String", "localName", ",", "String", "value", ")", "throws", "Exception", "{", "this", ".", "attribute", "(", "namespaceURI", ",", "localName", ",", "value", ".", "toString", "(", ")", ")", ";", "}" ]
Write attribute. @param namespaceURI the namespace URI @param localName the local name @param value the value @throws Exception the exception
[ "Write", "attribute", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton/src/main/java/com/abubusoft/kripton/xml/XMLSerializer.java#L1694-L1696
threerings/nenya
core/src/main/java/com/threerings/media/animation/AnimationSequencer.java
AnimationSequencer.startAnimation
protected void startAnimation (Animation anim, long tickStamp) { // account for any view scrolling that happened before this animation // was actually added to the view if (_vdx != 0 || _vdy != 0) { anim.viewLocationDidChange(_vdx, _vdy); } _animmgr.registerAnimation(anim); }
java
protected void startAnimation (Animation anim, long tickStamp) { // account for any view scrolling that happened before this animation // was actually added to the view if (_vdx != 0 || _vdy != 0) { anim.viewLocationDidChange(_vdx, _vdy); } _animmgr.registerAnimation(anim); }
[ "protected", "void", "startAnimation", "(", "Animation", "anim", ",", "long", "tickStamp", ")", "{", "// account for any view scrolling that happened before this animation", "// was actually added to the view", "if", "(", "_vdx", "!=", "0", "||", "_vdy", "!=", "0", ")", "{", "anim", ".", "viewLocationDidChange", "(", "_vdx", ",", "_vdy", ")", ";", "}", "_animmgr", ".", "registerAnimation", "(", "anim", ")", ";", "}" ]
Called when the time comes to start an animation. Derived classes may override this method and pass the animation on to their animation manager and do whatever else they need to do with operating animations. The default implementation simply adds them to the media panel supplied when we were constructed. @param anim the animation to be displayed. @param tickStamp the timestamp at which this animation was fired.
[ "Called", "when", "the", "time", "comes", "to", "start", "an", "animation", ".", "Derived", "classes", "may", "override", "this", "method", "and", "pass", "the", "animation", "on", "to", "their", "animation", "manager", "and", "do", "whatever", "else", "they", "need", "to", "do", "with", "operating", "animations", ".", "The", "default", "implementation", "simply", "adds", "them", "to", "the", "media", "panel", "supplied", "when", "we", "were", "constructed", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/animation/AnimationSequencer.java#L189-L198
xmlunit/xmlunit
xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/jaxp13/Jaxp13XpathEngine.java
Jaxp13XpathEngine.getMatchingNodes
public NodeList getMatchingNodes(String select, Document document) throws XpathException { try { return new NodeListForIterable(engine .selectNodes(select, new DOMSource(document)) ); } catch (XMLUnitException ex) { throw new XpathException(ex.getCause()); } }
java
public NodeList getMatchingNodes(String select, Document document) throws XpathException { try { return new NodeListForIterable(engine .selectNodes(select, new DOMSource(document)) ); } catch (XMLUnitException ex) { throw new XpathException(ex.getCause()); } }
[ "public", "NodeList", "getMatchingNodes", "(", "String", "select", ",", "Document", "document", ")", "throws", "XpathException", "{", "try", "{", "return", "new", "NodeListForIterable", "(", "engine", ".", "selectNodes", "(", "select", ",", "new", "DOMSource", "(", "document", ")", ")", ")", ";", "}", "catch", "(", "XMLUnitException", "ex", ")", "{", "throw", "new", "XpathException", "(", "ex", ".", "getCause", "(", ")", ")", ";", "}", "}" ]
Execute the specified xpath syntax <code>select</code> expression on the specified document and return the list of nodes (could have length zero) that match @param select @param document @return list of matching nodes
[ "Execute", "the", "specified", "xpath", "syntax", "<code", ">", "select<", "/", "code", ">", "expression", "on", "the", "specified", "document", "and", "return", "the", "list", "of", "nodes", "(", "could", "have", "length", "zero", ")", "that", "match" ]
train
https://github.com/xmlunit/xmlunit/blob/fe3d701d43f57ee83dcba336e4c1555619d3084b/xmlunit-legacy/src/main/java/org/custommonkey/xmlunit/jaxp13/Jaxp13XpathEngine.java#L91-L101
apache/flink
flink-core/src/main/java/org/apache/flink/types/Record.java
Record.getField
@SuppressWarnings("unchecked") public <T extends Value> T getField(final int fieldNum, final Class<T> type) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(fieldNum + " for range [0.." + (this.numFields - 1) + "]"); } // get offset and check for null final int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; // get an instance, either from the instance cache or create a new one final Value oldField = this.readFields[fieldNum]; final T field; if (oldField != null && oldField.getClass() == type) { field = (T) oldField; } else { field = InstantiationUtil.instantiate(type, Value.class); this.readFields[fieldNum] = field; } // deserialize deserialize(field, offset, limit, fieldNum); return field; }
java
@SuppressWarnings("unchecked") public <T extends Value> T getField(final int fieldNum, final Class<T> type) { // range check if (fieldNum < 0 || fieldNum >= this.numFields) { throw new IndexOutOfBoundsException(fieldNum + " for range [0.." + (this.numFields - 1) + "]"); } // get offset and check for null final int offset = this.offsets[fieldNum]; if (offset == NULL_INDICATOR_OFFSET) { return null; } else if (offset == MODIFIED_INDICATOR_OFFSET) { // value that has been set is new or modified return (T) this.writeFields[fieldNum]; } final int limit = offset + this.lengths[fieldNum]; // get an instance, either from the instance cache or create a new one final Value oldField = this.readFields[fieldNum]; final T field; if (oldField != null && oldField.getClass() == type) { field = (T) oldField; } else { field = InstantiationUtil.instantiate(type, Value.class); this.readFields[fieldNum] = field; } // deserialize deserialize(field, offset, limit, fieldNum); return field; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", "extends", "Value", ">", "T", "getField", "(", "final", "int", "fieldNum", ",", "final", "Class", "<", "T", ">", "type", ")", "{", "// range check", "if", "(", "fieldNum", "<", "0", "||", "fieldNum", ">=", "this", ".", "numFields", ")", "{", "throw", "new", "IndexOutOfBoundsException", "(", "fieldNum", "+", "\" for range [0..\"", "+", "(", "this", ".", "numFields", "-", "1", ")", "+", "\"]\"", ")", ";", "}", "// get offset and check for null", "final", "int", "offset", "=", "this", ".", "offsets", "[", "fieldNum", "]", ";", "if", "(", "offset", "==", "NULL_INDICATOR_OFFSET", ")", "{", "return", "null", ";", "}", "else", "if", "(", "offset", "==", "MODIFIED_INDICATOR_OFFSET", ")", "{", "// value that has been set is new or modified", "return", "(", "T", ")", "this", ".", "writeFields", "[", "fieldNum", "]", ";", "}", "final", "int", "limit", "=", "offset", "+", "this", ".", "lengths", "[", "fieldNum", "]", ";", "// get an instance, either from the instance cache or create a new one", "final", "Value", "oldField", "=", "this", ".", "readFields", "[", "fieldNum", "]", ";", "final", "T", "field", ";", "if", "(", "oldField", "!=", "null", "&&", "oldField", ".", "getClass", "(", ")", "==", "type", ")", "{", "field", "=", "(", "T", ")", "oldField", ";", "}", "else", "{", "field", "=", "InstantiationUtil", ".", "instantiate", "(", "type", ",", "Value", ".", "class", ")", ";", "this", ".", "readFields", "[", "fieldNum", "]", "=", "field", ";", "}", "// deserialize", "deserialize", "(", "field", ",", "offset", ",", "limit", ",", "fieldNum", ")", ";", "return", "field", ";", "}" ]
Gets the field at the given position from the record. This method checks internally, if this instance of the record has previously returned a value for this field. If so, it reuses the object, if not, it creates one from the supplied class. @param <T> The type of the field. @param fieldNum The logical position of the field. @param type The type of the field as a class. This class is used to instantiate a value object, if none had previously been instantiated. @return The field at the given position, or null, if the field was null. @throws IndexOutOfBoundsException Thrown, if the field number is negative or larger or equal to the number of fields in this record.
[ "Gets", "the", "field", "at", "the", "given", "position", "from", "the", "record", ".", "This", "method", "checks", "internally", "if", "this", "instance", "of", "the", "record", "has", "previously", "returned", "a", "value", "for", "this", "field", ".", "If", "so", "it", "reuses", "the", "object", "if", "not", "it", "creates", "one", "from", "the", "supplied", "class", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/types/Record.java#L222-L255
b3dgs/lionengine
lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java
NetworkMessageEntity.addAction
public void addAction(M element, char value) { actions.put(element, Character.valueOf(value)); }
java
public void addAction(M element, char value) { actions.put(element, Character.valueOf(value)); }
[ "public", "void", "addAction", "(", "M", "element", ",", "char", "value", ")", "{", "actions", ".", "put", "(", "element", ",", "Character", ".", "valueOf", "(", "value", ")", ")", ";", "}" ]
Add an action. @param element The action type. @param value The action value.
[ "Add", "an", "action", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java#L122-L125
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanMetaDataInfo.java
TEBeanMetaDataInfo.writeMethodInfo
private static void writeMethodInfo(StringBuffer sbuf, EJBMethodInfoImpl methodInfos[]) { if (methodInfos == null) { sbuf.append("" + -1).append(DataDelimiter); } else { int size = methodInfos.length; sbuf.append("" + size).append(DataDelimiter); for (int i = 0; i < size; ++i) { EJBMethodInfoImpl info = methodInfos[i]; sbuf .append(i).append(DataDelimiter) .append(info.getMethodName()).append(DataDelimiter) .append(info.getJDIMethodSignature()).append(DataDelimiter) .append(info.getTransactionAttribute().getValue()).append(DataDelimiter) .append(info.getActivitySessionAttribute().getValue()).append(DataDelimiter) .append(info.getIsolationLevel()).append(DataDelimiter) .append(info.getReadOnlyAttribute() ? "true" : "false").append(DataDelimiter); } } }
java
private static void writeMethodInfo(StringBuffer sbuf, EJBMethodInfoImpl methodInfos[]) { if (methodInfos == null) { sbuf.append("" + -1).append(DataDelimiter); } else { int size = methodInfos.length; sbuf.append("" + size).append(DataDelimiter); for (int i = 0; i < size; ++i) { EJBMethodInfoImpl info = methodInfos[i]; sbuf .append(i).append(DataDelimiter) .append(info.getMethodName()).append(DataDelimiter) .append(info.getJDIMethodSignature()).append(DataDelimiter) .append(info.getTransactionAttribute().getValue()).append(DataDelimiter) .append(info.getActivitySessionAttribute().getValue()).append(DataDelimiter) .append(info.getIsolationLevel()).append(DataDelimiter) .append(info.getReadOnlyAttribute() ? "true" : "false").append(DataDelimiter); } } }
[ "private", "static", "void", "writeMethodInfo", "(", "StringBuffer", "sbuf", ",", "EJBMethodInfoImpl", "methodInfos", "[", "]", ")", "{", "if", "(", "methodInfos", "==", "null", ")", "{", "sbuf", ".", "append", "(", "\"\"", "+", "-", "1", ")", ".", "append", "(", "DataDelimiter", ")", ";", "}", "else", "{", "int", "size", "=", "methodInfos", ".", "length", ";", "sbuf", ".", "append", "(", "\"\"", "+", "size", ")", ".", "append", "(", "DataDelimiter", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "++", "i", ")", "{", "EJBMethodInfoImpl", "info", "=", "methodInfos", "[", "i", "]", ";", "sbuf", ".", "append", "(", "i", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getMethodName", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getJDIMethodSignature", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getTransactionAttribute", "(", ")", ".", "getValue", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getActivitySessionAttribute", "(", ")", ".", "getValue", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getIsolationLevel", "(", ")", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "info", ".", "getReadOnlyAttribute", "(", ")", "?", "\"true\"", ":", "\"false\"", ")", ".", "append", "(", "DataDelimiter", ")", ";", "}", "}", "}" ]
Writes all the method info data representd by <i>methodInfos</i> to <i>sbuf</i>
[ "Writes", "all", "the", "method", "info", "data", "representd", "by", "<i", ">", "methodInfos<", "/", "i", ">", "to", "<i", ">", "sbuf<", "/", "i", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanMetaDataInfo.java#L51-L73
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/template/TemplateGenerator.java
TemplateGenerator.generateTemplate
public static void generateTemplate( Reader readerTemplate, Writer writerOut, ISymbolTable symTable, boolean strict) throws TemplateParseException { TemplateGenerator te = new TemplateGenerator( readerTemplate); te.setDisableAlternative(strict); te.execute( writerOut, symTable); }
java
public static void generateTemplate( Reader readerTemplate, Writer writerOut, ISymbolTable symTable, boolean strict) throws TemplateParseException { TemplateGenerator te = new TemplateGenerator( readerTemplate); te.setDisableAlternative(strict); te.execute( writerOut, symTable); }
[ "public", "static", "void", "generateTemplate", "(", "Reader", "readerTemplate", ",", "Writer", "writerOut", ",", "ISymbolTable", "symTable", ",", "boolean", "strict", ")", "throws", "TemplateParseException", "{", "TemplateGenerator", "te", "=", "new", "TemplateGenerator", "(", "readerTemplate", ")", ";", "te", ".", "setDisableAlternative", "(", "strict", ")", ";", "te", ".", "execute", "(", "writerOut", ",", "symTable", ")", ";", "}" ]
Generates a template of any format having embedded Gosu. @param readerTemplate The source of the template. @param writerOut Where the output should go. @param symTable The symbol table to use. @param strict whether to allow althernative template @throws TemplateParseException on execution exception
[ "Generates", "a", "template", "of", "any", "format", "having", "embedded", "Gosu", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/template/TemplateGenerator.java#L178-L183
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/TSDBEntity.java
TSDBEntity.setTags
public void setTags(Map<String, String> tags) { TSDBEntity.validateTags(tags); _tags.clear(); if (tags != null) { _tags.putAll(tags); } }
java
public void setTags(Map<String, String> tags) { TSDBEntity.validateTags(tags); _tags.clear(); if (tags != null) { _tags.putAll(tags); } }
[ "public", "void", "setTags", "(", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "TSDBEntity", ".", "validateTags", "(", "tags", ")", ";", "_tags", ".", "clear", "(", ")", ";", "if", "(", "tags", "!=", "null", ")", "{", "_tags", ".", "putAll", "(", "tags", ")", ";", "}", "}" ]
Replaces the tags for a metric. Tags cannot use any of the reserved tag names. @param tags The new tags for the metric.
[ "Replaces", "the", "tags", "for", "a", "metric", ".", "Tags", "cannot", "use", "any", "of", "the", "reserved", "tag", "names", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/TSDBEntity.java#L155-L162
landawn/AbacusUtil
src/com/landawn/abacus/util/stream/Collectors.java
Collectors.distinctBy
public static <T> Collector<T, ?, List<T>> distinctBy(final Function<? super T, ?> mapper) { @SuppressWarnings("rawtypes") final Supplier<Map<Object, T>> supplier = (Supplier) Suppliers.<Object, T> ofLinkedHashMap(); final BiConsumer<Map<Object, T>, T> accumulator = new BiConsumer<Map<Object, T>, T>() { @Override public void accept(Map<Object, T> map, T t) { final Object key = mapper.apply(t); if (map.containsKey(key) == false) { map.put(key, t); } } }; final BinaryOperator<Map<Object, T>> combiner = new BinaryOperator<Map<Object, T>>() { @Override public Map<Object, T> apply(Map<Object, T> a, Map<Object, T> b) { for (Map.Entry<Object, T> entry : b.entrySet()) { if (a.containsKey(entry.getKey()) == false) { a.put(entry.getKey(), entry.getValue()); } } return a; } }; final Function<Map<Object, T>, List<T>> finisher = new Function<Map<Object, T>, List<T>>() { @Override public List<T> apply(Map<Object, T> map) { return new ArrayList<>(map.values()); } }; return new CollectorImpl<>(supplier, accumulator, combiner, finisher, CH_UNORDERED_NOID); }
java
public static <T> Collector<T, ?, List<T>> distinctBy(final Function<? super T, ?> mapper) { @SuppressWarnings("rawtypes") final Supplier<Map<Object, T>> supplier = (Supplier) Suppliers.<Object, T> ofLinkedHashMap(); final BiConsumer<Map<Object, T>, T> accumulator = new BiConsumer<Map<Object, T>, T>() { @Override public void accept(Map<Object, T> map, T t) { final Object key = mapper.apply(t); if (map.containsKey(key) == false) { map.put(key, t); } } }; final BinaryOperator<Map<Object, T>> combiner = new BinaryOperator<Map<Object, T>>() { @Override public Map<Object, T> apply(Map<Object, T> a, Map<Object, T> b) { for (Map.Entry<Object, T> entry : b.entrySet()) { if (a.containsKey(entry.getKey()) == false) { a.put(entry.getKey(), entry.getValue()); } } return a; } }; final Function<Map<Object, T>, List<T>> finisher = new Function<Map<Object, T>, List<T>>() { @Override public List<T> apply(Map<Object, T> map) { return new ArrayList<>(map.values()); } }; return new CollectorImpl<>(supplier, accumulator, combiner, finisher, CH_UNORDERED_NOID); }
[ "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "List", "<", "T", ">", ">", "distinctBy", "(", "final", "Function", "<", "?", "super", "T", ",", "?", ">", "mapper", ")", "{", "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "final", "Supplier", "<", "Map", "<", "Object", ",", "T", ">", ">", "supplier", "=", "(", "Supplier", ")", "Suppliers", ".", "<", "Object", ",", "T", ">", "ofLinkedHashMap", "(", ")", ";", "final", "BiConsumer", "<", "Map", "<", "Object", ",", "T", ">", ",", "T", ">", "accumulator", "=", "new", "BiConsumer", "<", "Map", "<", "Object", ",", "T", ">", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "Map", "<", "Object", ",", "T", ">", "map", ",", "T", "t", ")", "{", "final", "Object", "key", "=", "mapper", ".", "apply", "(", "t", ")", ";", "if", "(", "map", ".", "containsKey", "(", "key", ")", "==", "false", ")", "{", "map", ".", "put", "(", "key", ",", "t", ")", ";", "}", "}", "}", ";", "final", "BinaryOperator", "<", "Map", "<", "Object", ",", "T", ">", ">", "combiner", "=", "new", "BinaryOperator", "<", "Map", "<", "Object", ",", "T", ">", ">", "(", ")", "{", "@", "Override", "public", "Map", "<", "Object", ",", "T", ">", "apply", "(", "Map", "<", "Object", ",", "T", ">", "a", ",", "Map", "<", "Object", ",", "T", ">", "b", ")", "{", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "T", ">", "entry", ":", "b", ".", "entrySet", "(", ")", ")", "{", "if", "(", "a", ".", "containsKey", "(", "entry", ".", "getKey", "(", ")", ")", "==", "false", ")", "{", "a", ".", "put", "(", "entry", ".", "getKey", "(", ")", ",", "entry", ".", "getValue", "(", ")", ")", ";", "}", "}", "return", "a", ";", "}", "}", ";", "final", "Function", "<", "Map", "<", "Object", ",", "T", ">", ",", "List", "<", "T", ">", ">", "finisher", "=", "new", "Function", "<", "Map", "<", "Object", ",", "T", ">", ",", "List", "<", "T", ">", ">", "(", ")", "{", "@", "Override", "public", "List", "<", "T", ">", "apply", "(", "Map", "<", "Object", ",", "T", ">", "map", ")", "{", "return", "new", "ArrayList", "<>", "(", "map", ".", "values", "(", ")", ")", ";", "}", "}", ";", "return", "new", "CollectorImpl", "<>", "(", "supplier", ",", "accumulator", ",", "combiner", ",", "finisher", ",", "CH_UNORDERED_NOID", ")", ";", "}" ]
It's copied from StreamEx: https://github.com/amaembo/streamex under Apache License v2 and may be modified. <br /> Returns a {@code Collector} which collects into the {@link List} the input elements for which given mapper function returns distinct results. <p> For ordered source the order of collected elements is preserved. If the same result is returned by mapper function for several elements, only the first element is included into the resulting list. <p> There are no guarantees on the type, mutability, serializability, or thread-safety of the {@code List} returned. <p> The operation performed by the returned collector is equivalent to {@code stream.distinct(mapper).toList()}, but may work faster. @param <T> the type of the input elements @param mapper a function which classifies input elements. @return a collector which collects distinct elements to the {@code List}. @since 0.3.8
[ "It", "s", "copied", "from", "StreamEx", ":", "https", ":", "//", "github", ".", "com", "/", "amaembo", "/", "streamex", "under", "Apache", "License", "v2", "and", "may", "be", "modified", ".", "<br", "/", ">" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/stream/Collectors.java#L1826-L1862
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.splitPreserveAllTokens
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { return splitWorker(str, separatorChars, max, true); }
java
public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { return splitWorker(str, separatorChars, max, true); }
[ "public", "static", "String", "[", "]", "splitPreserveAllTokens", "(", "final", "String", "str", ",", "final", "String", "separatorChars", ",", "final", "int", "max", ")", "{", "return", "splitWorker", "(", "str", ",", "separatorChars", ",", "max", ",", "true", ")", ";", "}" ]
<p>Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.</p> <p>The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. Adjacent separators are treated as one separator.</p> <p>A {@code null} input String returns {@code null}. A {@code null} separatorChars splits on whitespace.</p> <p>If more than {@code max} delimited substrings are found, the last returned string includes all characters after the first {@code max - 1} returned strings (including separator characters).</p> <pre> StringUtils.splitPreserveAllTokens(null, *, *) = null StringUtils.splitPreserveAllTokens("", *, *) = [] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"] </pre> @param str the String to parse, may be {@code null} @param separatorChars the characters used as the delimiters, {@code null} splits on whitespace @param max the maximum number of elements to include in the array. A zero or negative value implies no limit @return an array of parsed Strings, {@code null} if null String input @since 2.1
[ "<p", ">", "Splits", "the", "provided", "text", "into", "an", "array", "with", "a", "maximum", "length", "separators", "specified", "preserving", "all", "tokens", "including", "empty", "tokens", "created", "by", "adjacent", "separators", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L3627-L3629
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java
ControlBeanContext.getBeanAnnotationMap
protected PropertyMap getBeanAnnotationMap(ControlBean bean, AnnotatedElement annotElem) { PropertyMap map = new AnnotatedElementMap(annotElem); // REVIEW: is this the right place to handle the general control client case? if ( bean != null ) setDelegateMap( map, bean, annotElem ); return map; }
java
protected PropertyMap getBeanAnnotationMap(ControlBean bean, AnnotatedElement annotElem) { PropertyMap map = new AnnotatedElementMap(annotElem); // REVIEW: is this the right place to handle the general control client case? if ( bean != null ) setDelegateMap( map, bean, annotElem ); return map; }
[ "protected", "PropertyMap", "getBeanAnnotationMap", "(", "ControlBean", "bean", ",", "AnnotatedElement", "annotElem", ")", "{", "PropertyMap", "map", "=", "new", "AnnotatedElementMap", "(", "annotElem", ")", ";", "// REVIEW: is this the right place to handle the general control client case?", "if", "(", "bean", "!=", "null", ")", "setDelegateMap", "(", "map", ",", "bean", ",", "annotElem", ")", ";", "return", "map", ";", "}" ]
The default implementation of getBeanAnnotationMap. This returns a map based purely upon annotation reflection
[ "The", "default", "implementation", "of", "getBeanAnnotationMap", ".", "This", "returns", "a", "map", "based", "purely", "upon", "annotation", "reflection" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ControlBeanContext.java#L391-L400
jenkinsci/jenkins
core/src/main/java/hudson/search/Search.java
Search.find
public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext); if(r.isEmpty()){ return null; } else if(1==r.size()){ return r.get(0); } else { // we have more than one suggested item, so return the item who's url // contains the query as this is probably the job's name return findClosestSuggestedItem(r, query); } }
java
public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) { List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext); if(r.isEmpty()){ return null; } else if(1==r.size()){ return r.get(0); } else { // we have more than one suggested item, so return the item who's url // contains the query as this is probably the job's name return findClosestSuggestedItem(r, query); } }
[ "public", "static", "SuggestedItem", "find", "(", "SearchIndex", "index", ",", "String", "query", ",", "SearchableModelObject", "searchContext", ")", "{", "List", "<", "SuggestedItem", ">", "r", "=", "find", "(", "Mode", ".", "FIND", ",", "index", ",", "query", ",", "searchContext", ")", ";", "if", "(", "r", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "}", "else", "if", "(", "1", "==", "r", ".", "size", "(", ")", ")", "{", "return", "r", ".", "get", "(", "0", ")", ";", "}", "else", "{", "// we have more than one suggested item, so return the item who's url", "// contains the query as this is probably the job's name", "return", "findClosestSuggestedItem", "(", "r", ",", "query", ")", ";", "}", "}" ]
Performs a search and returns the match, or null if no match was found or more than one match was found. @since 1.527
[ "Performs", "a", "search", "and", "returns", "the", "match", "or", "null", "if", "no", "match", "was", "found", "or", "more", "than", "one", "match", "was", "found", "." ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/search/Search.java#L265-L279
ModeShape/modeshape
modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java
CheckArg.isPowerOfTwo
public static void isPowerOfTwo( int argument, String name ) { if (Integer.bitCount(argument) != 1) { throw new IllegalArgumentException(CommonI18n.argumentMustBePowerOfTwo.text(name, argument)); } }
java
public static void isPowerOfTwo( int argument, String name ) { if (Integer.bitCount(argument) != 1) { throw new IllegalArgumentException(CommonI18n.argumentMustBePowerOfTwo.text(name, argument)); } }
[ "public", "static", "void", "isPowerOfTwo", "(", "int", "argument", ",", "String", "name", ")", "{", "if", "(", "Integer", ".", "bitCount", "(", "argument", ")", "!=", "1", ")", "{", "throw", "new", "IllegalArgumentException", "(", "CommonI18n", ".", "argumentMustBePowerOfTwo", ".", "text", "(", "name", ",", "argument", ")", ")", ";", "}", "}" ]
Check that the argument is a power of 2. @param argument The argument @param name The name of the argument @throws IllegalArgumentException If argument is not a power of 2
[ "Check", "that", "the", "argument", "is", "a", "power", "of", "2", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/CheckArg.java#L210-L215
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/util/Util.java
Util.throwIfNull
public static void throwIfNull(Object obj1, Object obj2) { if(obj1 == null){ throw new IllegalArgumentException(); } if(obj2 == null){ throw new IllegalArgumentException(); } }
java
public static void throwIfNull(Object obj1, Object obj2) { if(obj1 == null){ throw new IllegalArgumentException(); } if(obj2 == null){ throw new IllegalArgumentException(); } }
[ "public", "static", "void", "throwIfNull", "(", "Object", "obj1", ",", "Object", "obj2", ")", "{", "if", "(", "obj1", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "if", "(", "obj2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", ")", ";", "}", "}" ]
faster util method that avoids creation of array for two-arg cases
[ "faster", "util", "method", "that", "avoids", "creation", "of", "array", "for", "two", "-", "arg", "cases" ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/util/Util.java#L36-L43
gallandarakhneorg/afc
advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/RectangularPrism3ifx.java
RectangularPrism3ifx.depthProperty
@Pure public IntegerProperty depthProperty() { if (this.depth == null) { this.depth = new ReadOnlyIntegerWrapper(this, MathFXAttributeNames.DEPTH); this.depth.bind(Bindings.subtract(maxZProperty(), minZProperty())); } return this.depth; }
java
@Pure public IntegerProperty depthProperty() { if (this.depth == null) { this.depth = new ReadOnlyIntegerWrapper(this, MathFXAttributeNames.DEPTH); this.depth.bind(Bindings.subtract(maxZProperty(), minZProperty())); } return this.depth; }
[ "@", "Pure", "public", "IntegerProperty", "depthProperty", "(", ")", "{", "if", "(", "this", ".", "depth", "==", "null", ")", "{", "this", ".", "depth", "=", "new", "ReadOnlyIntegerWrapper", "(", "this", ",", "MathFXAttributeNames", ".", "DEPTH", ")", ";", "this", ".", "depth", ".", "bind", "(", "Bindings", ".", "subtract", "(", "maxZProperty", "(", ")", ",", "minZProperty", "(", ")", ")", ")", ";", "}", "return", "this", ".", "depth", ";", "}" ]
Replies the property that is the depth of the box. @return the depth property.
[ "Replies", "the", "property", "that", "is", "the", "depth", "of", "the", "box", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/mathfx/src/main/java/org/arakhne/afc/math/geometry/d3/ifx/RectangularPrism3ifx.java#L397-L404
jwtk/jjwt
impl/src/main/java/io/jsonwebtoken/impl/crypto/EllipticCurveProvider.java
EllipticCurveProvider.generateKeyPair
public static KeyPair generateKeyPair(SignatureAlgorithm alg, SecureRandom random) { return generateKeyPair("EC", null, alg, random); }
java
public static KeyPair generateKeyPair(SignatureAlgorithm alg, SecureRandom random) { return generateKeyPair("EC", null, alg, random); }
[ "public", "static", "KeyPair", "generateKeyPair", "(", "SignatureAlgorithm", "alg", ",", "SecureRandom", "random", ")", "{", "return", "generateKeyPair", "(", "\"EC\"", ",", "null", ",", "alg", ",", "random", ")", ";", "}" ]
Generates a new secure-random key pair of sufficient strength for the specified Elliptic Curve {@link SignatureAlgorithm} (must be one of {@code ES256}, {@code ES384} or {@code ES512}) using the specified {@link SecureRandom} random number generator. This is a convenience method that immediately delegates to {@link #generateKeyPair(String, String, SignatureAlgorithm, SecureRandom)} using {@code "EC"} as the {@code jcaAlgorithmName}. @param alg alg the algorithm indicating strength, must be one of {@code ES256}, {@code ES384} or {@code ES512} @param random the SecureRandom generator to use during key generation. @return a new secure-randomly generated key pair of sufficient strength for the specified {@link SignatureAlgorithm} (must be one of {@code ES256}, {@code ES384} or {@code ES512}) using the specified {@link SecureRandom} random number generator. @see #generateKeyPair() @see #generateKeyPair(SignatureAlgorithm) @see #generateKeyPair(String, String, SignatureAlgorithm, SecureRandom)
[ "Generates", "a", "new", "secure", "-", "random", "key", "pair", "of", "sufficient", "strength", "for", "the", "specified", "Elliptic", "Curve", "{", "@link", "SignatureAlgorithm", "}", "(", "must", "be", "one", "of", "{", "@code", "ES256", "}", "{", "@code", "ES384", "}", "or", "{", "@code", "ES512", "}", ")", "using", "the", "specified", "{", "@link", "SecureRandom", "}", "random", "number", "generator", ".", "This", "is", "a", "convenience", "method", "that", "immediately", "delegates", "to", "{", "@link", "#generateKeyPair", "(", "String", "String", "SignatureAlgorithm", "SecureRandom", ")", "}", "using", "{", "@code", "EC", "}", "as", "the", "{", "@code", "jcaAlgorithmName", "}", "." ]
train
https://github.com/jwtk/jjwt/blob/86b6096946752cffcfbc9b0a5503f1ea195cc140/impl/src/main/java/io/jsonwebtoken/impl/crypto/EllipticCurveProvider.java#L103-L105
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeFormatter.java
DateTimeFormatter.parseInto
public int parseInto(ReadWritableInstant instant, String text, int position) { InternalParser parser = requireParser(); if (instant == null) { throw new IllegalArgumentException("Instant must not be null"); } long instantMillis = instant.getMillis(); Chronology chrono = instant.getChronology(); int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, defaultYear); int newPos = parser.parseInto(bucket, text, position); instant.setMillis(bucket.computeMillis(false, text)); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } instant.setChronology(chrono); if (iZone != null) { instant.setZone(iZone); } return newPos; }
java
public int parseInto(ReadWritableInstant instant, String text, int position) { InternalParser parser = requireParser(); if (instant == null) { throw new IllegalArgumentException("Instant must not be null"); } long instantMillis = instant.getMillis(); Chronology chrono = instant.getChronology(); int defaultYear = DateTimeUtils.getChronology(chrono).year().get(instantMillis); long instantLocal = instantMillis + chrono.getZone().getOffset(instantMillis); chrono = selectChronology(chrono); DateTimeParserBucket bucket = new DateTimeParserBucket( instantLocal, chrono, iLocale, iPivotYear, defaultYear); int newPos = parser.parseInto(bucket, text, position); instant.setMillis(bucket.computeMillis(false, text)); if (iOffsetParsed && bucket.getOffsetInteger() != null) { int parsedOffset = bucket.getOffsetInteger(); DateTimeZone parsedZone = DateTimeZone.forOffsetMillis(parsedOffset); chrono = chrono.withZone(parsedZone); } else if (bucket.getZone() != null) { chrono = chrono.withZone(bucket.getZone()); } instant.setChronology(chrono); if (iZone != null) { instant.setZone(iZone); } return newPos; }
[ "public", "int", "parseInto", "(", "ReadWritableInstant", "instant", ",", "String", "text", ",", "int", "position", ")", "{", "InternalParser", "parser", "=", "requireParser", "(", ")", ";", "if", "(", "instant", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Instant must not be null\"", ")", ";", "}", "long", "instantMillis", "=", "instant", ".", "getMillis", "(", ")", ";", "Chronology", "chrono", "=", "instant", ".", "getChronology", "(", ")", ";", "int", "defaultYear", "=", "DateTimeUtils", ".", "getChronology", "(", "chrono", ")", ".", "year", "(", ")", ".", "get", "(", "instantMillis", ")", ";", "long", "instantLocal", "=", "instantMillis", "+", "chrono", ".", "getZone", "(", ")", ".", "getOffset", "(", "instantMillis", ")", ";", "chrono", "=", "selectChronology", "(", "chrono", ")", ";", "DateTimeParserBucket", "bucket", "=", "new", "DateTimeParserBucket", "(", "instantLocal", ",", "chrono", ",", "iLocale", ",", "iPivotYear", ",", "defaultYear", ")", ";", "int", "newPos", "=", "parser", ".", "parseInto", "(", "bucket", ",", "text", ",", "position", ")", ";", "instant", ".", "setMillis", "(", "bucket", ".", "computeMillis", "(", "false", ",", "text", ")", ")", ";", "if", "(", "iOffsetParsed", "&&", "bucket", ".", "getOffsetInteger", "(", ")", "!=", "null", ")", "{", "int", "parsedOffset", "=", "bucket", ".", "getOffsetInteger", "(", ")", ";", "DateTimeZone", "parsedZone", "=", "DateTimeZone", ".", "forOffsetMillis", "(", "parsedOffset", ")", ";", "chrono", "=", "chrono", ".", "withZone", "(", "parsedZone", ")", ";", "}", "else", "if", "(", "bucket", ".", "getZone", "(", ")", "!=", "null", ")", "{", "chrono", "=", "chrono", ".", "withZone", "(", "bucket", ".", "getZone", "(", ")", ")", ";", "}", "instant", ".", "setChronology", "(", "chrono", ")", ";", "if", "(", "iZone", "!=", "null", ")", "{", "instant", ".", "setZone", "(", "iZone", ")", ";", "}", "return", "newPos", ";", "}" ]
Parses a datetime from the given text, at the given position, saving the result into the fields of the given ReadWritableInstant. If the parse succeeds, the return value is the new text position. Note that the parse may succeed without fully reading the text and in this case those fields that were read will be set. <p> Only those fields present in the string will be changed in the specified instant. All other fields will remain unaltered. Thus if the string only contains a year and a month, then the day and time will be retained from the input instant. If this is not the behaviour you want, then reset the fields before calling this method, or use {@link #parseDateTime(String)} or {@link #parseMutableDateTime(String)}. <p> If it fails, the return value is negative, but the instant may still be modified. To determine the position where the parse failed, apply the one's complement operator (~) on the return value. <p> This parse method ignores the {@link #getDefaultYear() default year} and parses using the year from the supplied instant based on the chronology and time-zone of the supplied instant. <p> The parse will use the chronology of the instant. @param instant an instant that will be modified, not null @param text the text to parse @param position position to start parsing from @return new position, negative value means parse failed - apply complement operator (~) to get position of failure @throws UnsupportedOperationException if parsing is not supported @throws IllegalArgumentException if the instant is null @throws IllegalArgumentException if any field is out of range
[ "Parses", "a", "datetime", "from", "the", "given", "text", "at", "the", "given", "position", "saving", "the", "result", "into", "the", "fields", "of", "the", "given", "ReadWritableInstant", ".", "If", "the", "parse", "succeeds", "the", "return", "value", "is", "the", "new", "text", "position", ".", "Note", "that", "the", "parse", "may", "succeed", "without", "fully", "reading", "the", "text", "and", "in", "this", "case", "those", "fields", "that", "were", "read", "will", "be", "set", ".", "<p", ">", "Only", "those", "fields", "present", "in", "the", "string", "will", "be", "changed", "in", "the", "specified", "instant", ".", "All", "other", "fields", "will", "remain", "unaltered", ".", "Thus", "if", "the", "string", "only", "contains", "a", "year", "and", "a", "month", "then", "the", "day", "and", "time", "will", "be", "retained", "from", "the", "input", "instant", ".", "If", "this", "is", "not", "the", "behaviour", "you", "want", "then", "reset", "the", "fields", "before", "calling", "this", "method", "or", "use", "{", "@link", "#parseDateTime", "(", "String", ")", "}", "or", "{", "@link", "#parseMutableDateTime", "(", "String", ")", "}", ".", "<p", ">", "If", "it", "fails", "the", "return", "value", "is", "negative", "but", "the", "instant", "may", "still", "be", "modified", ".", "To", "determine", "the", "position", "where", "the", "parse", "failed", "apply", "the", "one", "s", "complement", "operator", "(", "~", ")", "on", "the", "return", "value", ".", "<p", ">", "This", "parse", "method", "ignores", "the", "{", "@link", "#getDefaultYear", "()", "default", "year", "}", "and", "parses", "using", "the", "year", "from", "the", "supplied", "instant", "based", "on", "the", "chronology", "and", "time", "-", "zone", "of", "the", "supplied", "instant", ".", "<p", ">", "The", "parse", "will", "use", "the", "chronology", "of", "the", "instant", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatter.java#L780-L808
Bedework/bw-util
bw-util-http/src/main/java/org/bedework/util/http/BasicHttpClient.java
BasicHttpClient.setCredentials
public void setCredentials(final String user, final String pw) { if (user == null) { credentials = null; } else { credentials = new UsernamePasswordCredentials(user, pw); } }
java
public void setCredentials(final String user, final String pw) { if (user == null) { credentials = null; } else { credentials = new UsernamePasswordCredentials(user, pw); } }
[ "public", "void", "setCredentials", "(", "final", "String", "user", ",", "final", "String", "pw", ")", "{", "if", "(", "user", "==", "null", ")", "{", "credentials", "=", "null", ";", "}", "else", "{", "credentials", "=", "new", "UsernamePasswordCredentials", "(", "user", ",", "pw", ")", ";", "}", "}" ]
Set the credentials. user == null for unauthenticated. @param user @param pw
[ "Set", "the", "credentials", ".", "user", "==", "null", "for", "unauthenticated", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-http/src/main/java/org/bedework/util/http/BasicHttpClient.java#L420-L426
osmdroid/osmdroid
osmdroid-mapsforge/src/main/java/org/osmdroid/mapsforge/MapsForgeTileSource.java
MapsForgeTileSource.createFromFiles
public static MapsForgeTileSource createFromFiles(File[] file, XmlRenderTheme theme, String themeName) { //these settings are ignored and are set based on .map file info int minZoomLevel = MIN_ZOOM; int maxZoomLevel = MAX_ZOOM; int tileSizePixels = TILE_SIZE_PIXELS; return new MapsForgeTileSource(themeName, minZoomLevel, maxZoomLevel, tileSizePixels, file, theme, MultiMapDataStore.DataPolicy.RETURN_ALL, null); }
java
public static MapsForgeTileSource createFromFiles(File[] file, XmlRenderTheme theme, String themeName) { //these settings are ignored and are set based on .map file info int minZoomLevel = MIN_ZOOM; int maxZoomLevel = MAX_ZOOM; int tileSizePixels = TILE_SIZE_PIXELS; return new MapsForgeTileSource(themeName, minZoomLevel, maxZoomLevel, tileSizePixels, file, theme, MultiMapDataStore.DataPolicy.RETURN_ALL, null); }
[ "public", "static", "MapsForgeTileSource", "createFromFiles", "(", "File", "[", "]", "file", ",", "XmlRenderTheme", "theme", ",", "String", "themeName", ")", "{", "//these settings are ignored and are set based on .map file info", "int", "minZoomLevel", "=", "MIN_ZOOM", ";", "int", "maxZoomLevel", "=", "MAX_ZOOM", ";", "int", "tileSizePixels", "=", "TILE_SIZE_PIXELS", ";", "return", "new", "MapsForgeTileSource", "(", "themeName", ",", "minZoomLevel", ",", "maxZoomLevel", ",", "tileSizePixels", ",", "file", ",", "theme", ",", "MultiMapDataStore", ".", "DataPolicy", ".", "RETURN_ALL", ",", "null", ")", ";", "}" ]
Creates a new MapsForgeTileSource from file[]. <p></p> Parameters minZoom and maxZoom are obtained from the database. If they cannot be obtained from the DB, the default values as defined by this class are used, which is zoom = 3-20 @param file @param theme this can be null, in which case the default them will be used @param themeName when using a custom theme, this sets up the osmdroid caching correctly @return
[ "Creates", "a", "new", "MapsForgeTileSource", "from", "file", "[]", ".", "<p", ">", "<", "/", "p", ">", "Parameters", "minZoom", "and", "maxZoom", "are", "obtained", "from", "the", "database", ".", "If", "they", "cannot", "be", "obtained", "from", "the", "DB", "the", "default", "values", "as", "defined", "by", "this", "class", "are", "used", "which", "is", "zoom", "=", "3", "-", "20" ]
train
https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-mapsforge/src/main/java/org/osmdroid/mapsforge/MapsForgeTileSource.java#L145-L152
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java
CassandraSchemaManager.createIndexUsingThrift
private void createIndexUsingThrift(TableInfo tableInfo, CfDef cfDef) throws Exception { for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed()) { for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (new String(columnDef.getName(), Constants.ENCODING).equals(indexInfo.getColumnName())) { columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // columnDef.setIndex_name(indexInfo.getIndexName()); } } } cassandra_client.system_update_column_family(cfDef); }
java
private void createIndexUsingThrift(TableInfo tableInfo, CfDef cfDef) throws Exception { for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed()) { for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (new String(columnDef.getName(), Constants.ENCODING).equals(indexInfo.getColumnName())) { columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // columnDef.setIndex_name(indexInfo.getIndexName()); } } } cassandra_client.system_update_column_family(cfDef); }
[ "private", "void", "createIndexUsingThrift", "(", "TableInfo", "tableInfo", ",", "CfDef", "cfDef", ")", "throws", "Exception", "{", "for", "(", "IndexInfo", "indexInfo", ":", "tableInfo", ".", "getColumnsToBeIndexed", "(", ")", ")", "{", "for", "(", "ColumnDef", "columnDef", ":", "cfDef", ".", "getColumn_metadata", "(", ")", ")", "{", "if", "(", "new", "String", "(", "columnDef", ".", "getName", "(", ")", ",", "Constants", ".", "ENCODING", ")", ".", "equals", "(", "indexInfo", ".", "getColumnName", "(", ")", ")", ")", "{", "columnDef", ".", "setIndex_type", "(", "CassandraIndexHelper", ".", "getIndexType", "(", "indexInfo", ".", "getIndexType", "(", ")", ")", ")", ";", "// columnDef.setIndex_name(indexInfo.getIndexName());", "}", "}", "}", "cassandra_client", ".", "system_update_column_family", "(", "cfDef", ")", ";", "}" ]
Creates the index using thrift. @param tableInfo the table info @param cfDef the cf def @throws Exception the exception
[ "Creates", "the", "index", "using", "thrift", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/schemamanager/CassandraSchemaManager.java#L1368-L1382
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java
ContentSpecProcessor.getTopicForTopicNode
protected TopicWrapper getTopicForTopicNode(final DataProviderFactory providerFactory, final ITopicNode topicNode) { TopicWrapper topic = null; if (topicNode.isTopicANewTopic()) { topic = getTopicForNewTopicNode(providerFactory, topicNode); } else if (topicNode.isTopicAClonedTopic()) { topic = ProcessorUtilities.cloneTopic(providerFactory, topicNode, serverEntities); } else if (topicNode.isTopicAnExistingTopic()) { topic = getTopicForExistingTopicNode(providerFactory, topicNode); } return topic; }
java
protected TopicWrapper getTopicForTopicNode(final DataProviderFactory providerFactory, final ITopicNode topicNode) { TopicWrapper topic = null; if (topicNode.isTopicANewTopic()) { topic = getTopicForNewTopicNode(providerFactory, topicNode); } else if (topicNode.isTopicAClonedTopic()) { topic = ProcessorUtilities.cloneTopic(providerFactory, topicNode, serverEntities); } else if (topicNode.isTopicAnExistingTopic()) { topic = getTopicForExistingTopicNode(providerFactory, topicNode); } return topic; }
[ "protected", "TopicWrapper", "getTopicForTopicNode", "(", "final", "DataProviderFactory", "providerFactory", ",", "final", "ITopicNode", "topicNode", ")", "{", "TopicWrapper", "topic", "=", "null", ";", "if", "(", "topicNode", ".", "isTopicANewTopic", "(", ")", ")", "{", "topic", "=", "getTopicForNewTopicNode", "(", "providerFactory", ",", "topicNode", ")", ";", "}", "else", "if", "(", "topicNode", ".", "isTopicAClonedTopic", "(", ")", ")", "{", "topic", "=", "ProcessorUtilities", ".", "cloneTopic", "(", "providerFactory", ",", "topicNode", ",", "serverEntities", ")", ";", "}", "else", "if", "(", "topicNode", ".", "isTopicAnExistingTopic", "(", ")", ")", "{", "topic", "=", "getTopicForExistingTopicNode", "(", "providerFactory", ",", "topicNode", ")", ";", "}", "return", "topic", ";", "}" ]
Gets or creates the underlying Topic Entity for a spec topic. @param providerFactory @param topicNode The spec topic to get the topic entity for. @return The topic entity if one could be found, otherwise null.
[ "Gets", "or", "creates", "the", "underlying", "Topic", "Entity", "for", "a", "spec", "topic", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecProcessor.java#L628-L640
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ValidationUtils.java
ValidationUtils.validate2x2NonNegative
public static int[][] validate2x2NonNegative(int[][] data, String paramName){ for(int[] part : data) validateNonNegative(part, paramName); return validate2x2(data, paramName); } /** * Reformats the input array to a 2x2 array. * * If the array is 2x1 ([[a], [b]]), returns [[a, a], [b, b]] * If the array is 1x2 ([[a, b]]), returns [[a, b], [a, b]] * If the array is 2x2, returns the array * * @param data An array * @param paramName The param name, for error reporting * @return An int array of length 2 that represents the input */ public static int[][] validate2x2(int[][] data, String paramName){ if(data == null) { return null; } Preconditions.checkArgument( (data.length == 1 && data[0].length == 2) || (data.length == 2 && (data[0].length == 1 || data[0].length == 2) && (data[1].length == 1 || data[1].length == 2) && data[0].length == data[1].length ), "Value for %s must have shape 2x1, 1x2, or 2x2, got %sx%s shaped array: %s", paramName, data.length, data[0].length, data); if(data.length == 1) { return new int[][]{ data[0], data[0] }; } else if(data[0].length == 1){ return new int[][]{ new int[]{data[0][0], data[0][0]}, new int[]{data[1][0], data[1][0]} }; } else { return data; } }
java
public static int[][] validate2x2NonNegative(int[][] data, String paramName){ for(int[] part : data) validateNonNegative(part, paramName); return validate2x2(data, paramName); } /** * Reformats the input array to a 2x2 array. * * If the array is 2x1 ([[a], [b]]), returns [[a, a], [b, b]] * If the array is 1x2 ([[a, b]]), returns [[a, b], [a, b]] * If the array is 2x2, returns the array * * @param data An array * @param paramName The param name, for error reporting * @return An int array of length 2 that represents the input */ public static int[][] validate2x2(int[][] data, String paramName){ if(data == null) { return null; } Preconditions.checkArgument( (data.length == 1 && data[0].length == 2) || (data.length == 2 && (data[0].length == 1 || data[0].length == 2) && (data[1].length == 1 || data[1].length == 2) && data[0].length == data[1].length ), "Value for %s must have shape 2x1, 1x2, or 2x2, got %sx%s shaped array: %s", paramName, data.length, data[0].length, data); if(data.length == 1) { return new int[][]{ data[0], data[0] }; } else if(data[0].length == 1){ return new int[][]{ new int[]{data[0][0], data[0][0]}, new int[]{data[1][0], data[1][0]} }; } else { return data; } }
[ "public", "static", "int", "[", "]", "[", "]", "validate2x2NonNegative", "(", "int", "[", "]", "[", "]", "data", ",", "String", "paramName", ")", "{", "for", "(", "int", "[", "]", "part", ":", "data", ")", "validateNonNegative", "(", "part", ",", "paramName", ")", ";", "return", "validate2x2", "(", "data", ",", "paramName", ")", ";", "}", "/**\n * Reformats the input array to a 2x2 array.\n *\n * If the array is 2x1 ([[a], [b]]), returns [[a, a], [b, b]]\n * If the array is 1x2 ([[a, b]]), returns [[a, b], [a, b]]\n * If the array is 2x2, returns the array\n *\n * @param data An array\n * @param paramName The param name, for error reporting\n * @return An int array of length 2 that represents the input\n */", "public", "static", "int", "[", "]", "[", "]", "validate2x2", "(", "int", "[", "]", "[", "]", "data", ",", "String", "paramName", ")", "{", "if", "(", "data", "==", "null", ")", "{", "return", "null", ";", "}", "Preconditions", ".", "checkArgument", "(", "(", "data", ".", "length", "==", "1", "&&", "data", "[", "0", "]", ".", "length", "==", "2", ")", "||", "(", "data", ".", "length", "==", "2", "&&", "(", "data", "[", "0", "]", ".", "length", "==", "1", "||", "data", "[", "0", "]", ".", "length", "==", "2", ")", "&&", "(", "data", "[", "1", "]", ".", "length", "==", "1", "||", "data", "[", "1", "]", ".", "length", "==", "2", ")", "&&", "data", "[", "0", "]", ".", "length", "==", "data", "[", "1", "]", ".", "length", ")", ",", "\"Value for %s must have shape 2x1, 1x2, or 2x2, got %sx%s shaped array: %s\"", ",", "paramName", ",", "data", ".", "length", ",", "data", "[", "0", "]", ".", "length", ",", "data", ")", ";", "if", "(", "data", ".", "length", "==", "1", ")", "{", "return", "new", "int", "[", "]", "[", "]", "{", "data", "[", "0", "]", ",", "data", "[", "0", "]", "}", ";", "}", "else", "if", "(", "data", "[", "0", "]", ".", "length", "==", "1", ")", "{", "return", "new", "int", "[", "]", "[", "]", "{", "new", "int", "[", "]", "{", "data", "[", "0", "]", "[", "0", "]", ",", "data", "[", "0", "]", "[", "0", "]", "}", ",", "new", "int", "[", "]", "{", "data", "[", "1", "]", "[", "0", "]", ",", "data", "[", "1", "]", "[", "0", "]", "}", "}", ";", "}", "else", "{", "return", "data", ";", "}", "}" ]
Reformats the input array to a 2x2 array and checks that all values are >= 0. If the array is 2x1 ([[a], [b]]), returns [[a, a], [b, b]] If the array is 1x2 ([[a, b]]), returns [[a, b], [a, b]] If the array is 2x2, returns the array @param data An array @param paramName The param name, for error reporting @return An int array of length 2 that represents the input
[ "Reformats", "the", "input", "array", "to", "a", "2x2", "array", "and", "checks", "that", "all", "values", "are", ">", "=", "0", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/util/ValidationUtils.java#L172-L218
foundation-runtime/service-directory
1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java
LookupManagerImpl.removeNotificationHandler
@Override public void removeNotificationHandler(String serviceName, NotificationHandler handler) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (handler == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "NotificationHandler"); } getLookupService().removeNotificationHandler(serviceName, handler); }
java
@Override public void removeNotificationHandler(String serviceName, NotificationHandler handler) throws ServiceException { ServiceInstanceUtils.validateManagerIsStarted(isStarted.get()); ServiceInstanceUtils.validateServiceName(serviceName); if (handler == null) { throw new ServiceException(ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR, ErrorCode.SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR.getMessageTemplate(), "NotificationHandler"); } getLookupService().removeNotificationHandler(serviceName, handler); }
[ "@", "Override", "public", "void", "removeNotificationHandler", "(", "String", "serviceName", ",", "NotificationHandler", "handler", ")", "throws", "ServiceException", "{", "ServiceInstanceUtils", ".", "validateManagerIsStarted", "(", "isStarted", ".", "get", "(", ")", ")", ";", "ServiceInstanceUtils", ".", "validateServiceName", "(", "serviceName", ")", ";", "if", "(", "handler", "==", "null", ")", "{", "throw", "new", "ServiceException", "(", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ",", "ErrorCode", ".", "SERVICE_DIRECTORY_NULL_ARGUMENT_ERROR", ".", "getMessageTemplate", "(", ")", ",", "\"NotificationHandler\"", ")", ";", "}", "getLookupService", "(", ")", ".", "removeNotificationHandler", "(", "serviceName", ",", "handler", ")", ";", "}" ]
Remove the NotificationHandler from the Service. @param serviceName the service name. @param handler the NotificationHandler for the service. @deprecated
[ "Remove", "the", "NotificationHandler", "from", "the", "Service", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/1.2/sd-api/src/main/java/com/cisco/oss/foundation/directory/lookup/LookupManagerImpl.java#L385-L397
m-m-m/util
exception/src/main/java/net/sf/mmm/util/exception/api/ThrowableHelper.java
ThrowableHelper.removeDetails
static void removeDetails(Throwable throwable, ExceptionTruncation truncation) { if (truncation.isRemoveStacktrace()) { throwable.setStackTrace(ExceptionUtil.NO_STACKTRACE); } if (truncation.isRemoveCause()) { getHelper().setCause(throwable, null); } if (truncation.isRemoveSuppressed()) { getHelper().setSuppressed(throwable, null); } }
java
static void removeDetails(Throwable throwable, ExceptionTruncation truncation) { if (truncation.isRemoveStacktrace()) { throwable.setStackTrace(ExceptionUtil.NO_STACKTRACE); } if (truncation.isRemoveCause()) { getHelper().setCause(throwable, null); } if (truncation.isRemoveSuppressed()) { getHelper().setSuppressed(throwable, null); } }
[ "static", "void", "removeDetails", "(", "Throwable", "throwable", ",", "ExceptionTruncation", "truncation", ")", "{", "if", "(", "truncation", ".", "isRemoveStacktrace", "(", ")", ")", "{", "throwable", ".", "setStackTrace", "(", "ExceptionUtil", ".", "NO_STACKTRACE", ")", ";", "}", "if", "(", "truncation", ".", "isRemoveCause", "(", ")", ")", "{", "getHelper", "(", ")", ".", "setCause", "(", "throwable", ",", "null", ")", ";", "}", "if", "(", "truncation", ".", "isRemoveSuppressed", "(", ")", ")", "{", "getHelper", "(", ")", ".", "setSuppressed", "(", "throwable", ",", "null", ")", ";", "}", "}" ]
@see NlsThrowable#createCopy(ExceptionTruncation) @param throwable is the {@link Throwable} to truncate. @param truncation the {@link ExceptionTruncation} settings.
[ "@see", "NlsThrowable#createCopy", "(", "ExceptionTruncation", ")" ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/exception/src/main/java/net/sf/mmm/util/exception/api/ThrowableHelper.java#L48-L59
minio/minio-java
api/src/main/java/io/minio/MinioClient.java
MinioClient.listObjects
public Iterable<Result<Item>> listObjects(final String bucketName) throws XmlPullParserException { return listObjects(bucketName, null); }
java
public Iterable<Result<Item>> listObjects(final String bucketName) throws XmlPullParserException { return listObjects(bucketName, null); }
[ "public", "Iterable", "<", "Result", "<", "Item", ">", ">", "listObjects", "(", "final", "String", "bucketName", ")", "throws", "XmlPullParserException", "{", "return", "listObjects", "(", "bucketName", ",", "null", ")", ";", "}" ]
Lists object information in given bucket. @param bucketName Bucket name. @return an iterator of Result Items. * @throws XmlPullParserException upon parsing response xml
[ "Lists", "object", "information", "in", "given", "bucket", "." ]
train
https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L2797-L2799
intive-FDV/DynamicJasper
src/main/java/ar/com/fdvs/dj/core/layout/Dj2JrCrosstabBuilder.java
Dj2JrCrosstabBuilder.registerRows
private void registerRows() { for (int i = 0; i < rows.length; i++) { DJCrosstabRow crosstabRow = rows[i]; JRDesignCrosstabRowGroup ctRowGroup = new JRDesignCrosstabRowGroup(); ctRowGroup.setWidth(crosstabRow.getHeaderWidth()); ctRowGroup.setName(crosstabRow.getProperty().getProperty()); JRDesignCrosstabBucket rowBucket = new JRDesignCrosstabBucket(); //New in JR 4.1+ rowBucket.setValueClassName(crosstabRow.getProperty().getValueClassName()); ctRowGroup.setBucket(rowBucket); JRDesignExpression bucketExp = ExpressionUtils.createExpression("$F{"+crosstabRow.getProperty().getProperty()+"}", crosstabRow.getProperty().getValueClassName()); rowBucket.setExpression(bucketExp); JRDesignCellContents rowHeaderContents = new JRDesignCellContents(); JRDesignTextField rowTitle = new JRDesignTextField(); JRDesignExpression rowTitExp = new JRDesignExpression(); rowTitExp.setValueClassName(crosstabRow.getProperty().getValueClassName()); rowTitExp.setText("$V{"+crosstabRow.getProperty().getProperty()+"}"); rowTitle.setExpression(rowTitExp); rowTitle.setWidth(crosstabRow.getHeaderWidth()); //The width can be the sum of the with of all the rows starting from the current one, up to the inner most one. int auxHeight = getRowHeaderMaxHeight(crosstabRow); // int auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't rowTitle.setHeight(auxHeight); Style headerstyle = crosstabRow.getHeaderStyle() == null ? this.djcross.getRowHeaderStyle(): crosstabRow.getHeaderStyle(); if (headerstyle != null){ layoutManager.applyStyleToElement(headerstyle, rowTitle); rowHeaderContents.setBackcolor(headerstyle.getBackgroundColor()); } rowHeaderContents.addElement(rowTitle); rowHeaderContents.setMode( ModeEnum.OPAQUE ); boolean fullBorder = i <= 0; //Only outer most will have full border applyCellBorder(rowHeaderContents, false, fullBorder); ctRowGroup.setHeader(rowHeaderContents ); if (crosstabRow.isShowTotals()) createRowTotalHeader(ctRowGroup,crosstabRow,fullBorder); try { jrcross.addRowGroup(ctRowGroup); } catch (JRException e) { log.error(e.getMessage(),e); } } }
java
private void registerRows() { for (int i = 0; i < rows.length; i++) { DJCrosstabRow crosstabRow = rows[i]; JRDesignCrosstabRowGroup ctRowGroup = new JRDesignCrosstabRowGroup(); ctRowGroup.setWidth(crosstabRow.getHeaderWidth()); ctRowGroup.setName(crosstabRow.getProperty().getProperty()); JRDesignCrosstabBucket rowBucket = new JRDesignCrosstabBucket(); //New in JR 4.1+ rowBucket.setValueClassName(crosstabRow.getProperty().getValueClassName()); ctRowGroup.setBucket(rowBucket); JRDesignExpression bucketExp = ExpressionUtils.createExpression("$F{"+crosstabRow.getProperty().getProperty()+"}", crosstabRow.getProperty().getValueClassName()); rowBucket.setExpression(bucketExp); JRDesignCellContents rowHeaderContents = new JRDesignCellContents(); JRDesignTextField rowTitle = new JRDesignTextField(); JRDesignExpression rowTitExp = new JRDesignExpression(); rowTitExp.setValueClassName(crosstabRow.getProperty().getValueClassName()); rowTitExp.setText("$V{"+crosstabRow.getProperty().getProperty()+"}"); rowTitle.setExpression(rowTitExp); rowTitle.setWidth(crosstabRow.getHeaderWidth()); //The width can be the sum of the with of all the rows starting from the current one, up to the inner most one. int auxHeight = getRowHeaderMaxHeight(crosstabRow); // int auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't rowTitle.setHeight(auxHeight); Style headerstyle = crosstabRow.getHeaderStyle() == null ? this.djcross.getRowHeaderStyle(): crosstabRow.getHeaderStyle(); if (headerstyle != null){ layoutManager.applyStyleToElement(headerstyle, rowTitle); rowHeaderContents.setBackcolor(headerstyle.getBackgroundColor()); } rowHeaderContents.addElement(rowTitle); rowHeaderContents.setMode( ModeEnum.OPAQUE ); boolean fullBorder = i <= 0; //Only outer most will have full border applyCellBorder(rowHeaderContents, false, fullBorder); ctRowGroup.setHeader(rowHeaderContents ); if (crosstabRow.isShowTotals()) createRowTotalHeader(ctRowGroup,crosstabRow,fullBorder); try { jrcross.addRowGroup(ctRowGroup); } catch (JRException e) { log.error(e.getMessage(),e); } } }
[ "private", "void", "registerRows", "(", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "rows", ".", "length", ";", "i", "++", ")", "{", "DJCrosstabRow", "crosstabRow", "=", "rows", "[", "i", "]", ";", "JRDesignCrosstabRowGroup", "ctRowGroup", "=", "new", "JRDesignCrosstabRowGroup", "(", ")", ";", "ctRowGroup", ".", "setWidth", "(", "crosstabRow", ".", "getHeaderWidth", "(", ")", ")", ";", "ctRowGroup", ".", "setName", "(", "crosstabRow", ".", "getProperty", "(", ")", ".", "getProperty", "(", ")", ")", ";", "JRDesignCrosstabBucket", "rowBucket", "=", "new", "JRDesignCrosstabBucket", "(", ")", ";", "//New in JR 4.1+", "rowBucket", ".", "setValueClassName", "(", "crosstabRow", ".", "getProperty", "(", ")", ".", "getValueClassName", "(", ")", ")", ";", "ctRowGroup", ".", "setBucket", "(", "rowBucket", ")", ";", "JRDesignExpression", "bucketExp", "=", "ExpressionUtils", ".", "createExpression", "(", "\"$F{\"", "+", "crosstabRow", ".", "getProperty", "(", ")", ".", "getProperty", "(", ")", "+", "\"}\"", ",", "crosstabRow", ".", "getProperty", "(", ")", ".", "getValueClassName", "(", ")", ")", ";", "rowBucket", ".", "setExpression", "(", "bucketExp", ")", ";", "JRDesignCellContents", "rowHeaderContents", "=", "new", "JRDesignCellContents", "(", ")", ";", "JRDesignTextField", "rowTitle", "=", "new", "JRDesignTextField", "(", ")", ";", "JRDesignExpression", "rowTitExp", "=", "new", "JRDesignExpression", "(", ")", ";", "rowTitExp", ".", "setValueClassName", "(", "crosstabRow", ".", "getProperty", "(", ")", ".", "getValueClassName", "(", ")", ")", ";", "rowTitExp", ".", "setText", "(", "\"$V{\"", "+", "crosstabRow", ".", "getProperty", "(", ")", ".", "getProperty", "(", ")", "+", "\"}\"", ")", ";", "rowTitle", ".", "setExpression", "(", "rowTitExp", ")", ";", "rowTitle", ".", "setWidth", "(", "crosstabRow", ".", "getHeaderWidth", "(", ")", ")", ";", "//The width can be the sum of the with of all the rows starting from the current one, up to the inner most one.", "int", "auxHeight", "=", "getRowHeaderMaxHeight", "(", "crosstabRow", ")", ";", "//\t\t\tint auxHeight = crosstabRow.getHeight(); //FIXME getRowHeaderMaxHeight() must be FIXED because it breaks when 1rs row shows total and 2nd doesn't", "rowTitle", ".", "setHeight", "(", "auxHeight", ")", ";", "Style", "headerstyle", "=", "crosstabRow", ".", "getHeaderStyle", "(", ")", "==", "null", "?", "this", ".", "djcross", ".", "getRowHeaderStyle", "(", ")", ":", "crosstabRow", ".", "getHeaderStyle", "(", ")", ";", "if", "(", "headerstyle", "!=", "null", ")", "{", "layoutManager", ".", "applyStyleToElement", "(", "headerstyle", ",", "rowTitle", ")", ";", "rowHeaderContents", ".", "setBackcolor", "(", "headerstyle", ".", "getBackgroundColor", "(", ")", ")", ";", "}", "rowHeaderContents", ".", "addElement", "(", "rowTitle", ")", ";", "rowHeaderContents", ".", "setMode", "(", "ModeEnum", ".", "OPAQUE", ")", ";", "boolean", "fullBorder", "=", "i", "<=", "0", ";", "//Only outer most will have full border", "applyCellBorder", "(", "rowHeaderContents", ",", "false", ",", "fullBorder", ")", ";", "ctRowGroup", ".", "setHeader", "(", "rowHeaderContents", ")", ";", "if", "(", "crosstabRow", ".", "isShowTotals", "(", ")", ")", "createRowTotalHeader", "(", "ctRowGroup", ",", "crosstabRow", ",", "fullBorder", ")", ";", "try", "{", "jrcross", ".", "addRowGroup", "(", "ctRowGroup", ")", ";", "}", "catch", "(", "JRException", "e", ")", "{", "log", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}", "}" ]
Register the Rowgroup buckets and places the header cells for the rows
[ "Register", "the", "Rowgroup", "buckets", "and", "places", "the", "header", "cells", "for", "the", "rows" ]
train
https://github.com/intive-FDV/DynamicJasper/blob/63919574cc401ae40574d13129f628e66d1682a3/src/main/java/ar/com/fdvs/dj/core/layout/Dj2JrCrosstabBuilder.java#L773-L835
apache/flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/AvroUtils.java
AvroUtils.getAvroUtils
public static AvroUtils getAvroUtils() { // try and load the special AvroUtils from the flink-avro package try { Class<?> clazz = Class.forName(AVRO_KRYO_UTILS, false, Thread.currentThread().getContextClassLoader()); return clazz.asSubclass(AvroUtils.class).getConstructor().newInstance(); } catch (ClassNotFoundException e) { // cannot find the utils, return the default implementation return new DefaultAvroUtils(); } catch (Exception e) { throw new RuntimeException("Could not instantiate " + AVRO_KRYO_UTILS + ".", e); } }
java
public static AvroUtils getAvroUtils() { // try and load the special AvroUtils from the flink-avro package try { Class<?> clazz = Class.forName(AVRO_KRYO_UTILS, false, Thread.currentThread().getContextClassLoader()); return clazz.asSubclass(AvroUtils.class).getConstructor().newInstance(); } catch (ClassNotFoundException e) { // cannot find the utils, return the default implementation return new DefaultAvroUtils(); } catch (Exception e) { throw new RuntimeException("Could not instantiate " + AVRO_KRYO_UTILS + ".", e); } }
[ "public", "static", "AvroUtils", "getAvroUtils", "(", ")", "{", "// try and load the special AvroUtils from the flink-avro package", "try", "{", "Class", "<", "?", ">", "clazz", "=", "Class", ".", "forName", "(", "AVRO_KRYO_UTILS", ",", "false", ",", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ")", ";", "return", "clazz", ".", "asSubclass", "(", "AvroUtils", ".", "class", ")", ".", "getConstructor", "(", ")", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "ClassNotFoundException", "e", ")", "{", "// cannot find the utils, return the default implementation", "return", "new", "DefaultAvroUtils", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not instantiate \"", "+", "AVRO_KRYO_UTILS", "+", "\".\"", ",", "e", ")", ";", "}", "}" ]
Returns either the default {@link AvroUtils} which throw an exception in cases where Avro would be needed or loads the specific utils for Avro from flink-avro.
[ "Returns", "either", "the", "default", "{" ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/java/typeutils/AvroUtils.java#L44-L55
dustin/java-memcached-client
src/main/java/net/spy/memcached/MemcachedConnection.java
MemcachedConnection.addOperations
public void addOperations(final Map<MemcachedNode, Operation> ops) { for (Map.Entry<MemcachedNode, Operation> me : ops.entrySet()) { addOperation(me.getKey(), me.getValue()); } }
java
public void addOperations(final Map<MemcachedNode, Operation> ops) { for (Map.Entry<MemcachedNode, Operation> me : ops.entrySet()) { addOperation(me.getKey(), me.getValue()); } }
[ "public", "void", "addOperations", "(", "final", "Map", "<", "MemcachedNode", ",", "Operation", ">", "ops", ")", "{", "for", "(", "Map", ".", "Entry", "<", "MemcachedNode", ",", "Operation", ">", "me", ":", "ops", ".", "entrySet", "(", ")", ")", "{", "addOperation", "(", "me", ".", "getKey", "(", ")", ",", "me", ".", "getValue", "(", ")", ")", ";", "}", "}" ]
Enqueue the given list of operations on each handling node. @param ops the operations for each node.
[ "Enqueue", "the", "given", "list", "of", "operations", "on", "each", "handling", "node", "." ]
train
https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/MemcachedConnection.java#L1295-L1299
OpenLiberty/open-liberty
dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/JPAEMPool.java
JPAEMPool.getEntityManager
public EntityManager getEntityManager(boolean jtaTxExists, boolean unsynchronized) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getEntityManager : [" + ivPoolSize + "] tx = " + jtaTxExists + " unsynchronized = " + unsynchronized); EntityManager em = ivPool.poll(); if (em != null) { synchronized (this) { --ivPoolSize; } if (jtaTxExists && !unsynchronized) { em.joinTransaction(); } } else { // createEntityManager will join transaction if present and is SYNCHRONIZED. em = ivAbstractJpaComponent.getJPARuntime().createEntityManagerInstance(ivFactory, ivProperties, unsynchronized); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "getEntityManager : [" + ivPoolSize + "] " + em); return em; }
java
public EntityManager getEntityManager(boolean jtaTxExists, boolean unsynchronized) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.entry(tc, "getEntityManager : [" + ivPoolSize + "] tx = " + jtaTxExists + " unsynchronized = " + unsynchronized); EntityManager em = ivPool.poll(); if (em != null) { synchronized (this) { --ivPoolSize; } if (jtaTxExists && !unsynchronized) { em.joinTransaction(); } } else { // createEntityManager will join transaction if present and is SYNCHRONIZED. em = ivAbstractJpaComponent.getJPARuntime().createEntityManagerInstance(ivFactory, ivProperties, unsynchronized); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) Tr.exit(tc, "getEntityManager : [" + ivPoolSize + "] " + em); return em; }
[ "public", "EntityManager", "getEntityManager", "(", "boolean", "jtaTxExists", ",", "boolean", "unsynchronized", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"getEntityManager : [\"", "+", "ivPoolSize", "+", "\"] tx = \"", "+", "jtaTxExists", "+", "\" unsynchronized = \"", "+", "unsynchronized", ")", ";", "EntityManager", "em", "=", "ivPool", ".", "poll", "(", ")", ";", "if", "(", "em", "!=", "null", ")", "{", "synchronized", "(", "this", ")", "{", "--", "ivPoolSize", ";", "}", "if", "(", "jtaTxExists", "&&", "!", "unsynchronized", ")", "{", "em", ".", "joinTransaction", "(", ")", ";", "}", "}", "else", "{", "// createEntityManager will join transaction if present and is SYNCHRONIZED.", "em", "=", "ivAbstractJpaComponent", ".", "getJPARuntime", "(", ")", ".", "createEntityManagerInstance", "(", "ivFactory", ",", "ivProperties", ",", "unsynchronized", ")", ";", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "exit", "(", "tc", ",", "\"getEntityManager : [\"", "+", "ivPoolSize", "+", "\"] \"", "+", "em", ")", ";", "return", "em", ";", "}" ]
Returns an EntityManager instance from the pool, or a newly created instance if the pool is empty. <p> If a global JTA transaction is present, the EntityManager will have joined that transaction. <p> @param jtaTxExists true if a global jta transaction exists; otherwise false. @param unsynchronized true if SynchronizationType.UNSYNCHRONIZED is requested, false if not.
[ "Returns", "an", "EntityManager", "instance", "from", "the", "pool", "or", "a", "newly", "created", "instance", "if", "the", "pool", "is", "empty", ".", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/JPAEMPool.java#L133-L162
aws/aws-sdk-java
aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetRouteResponseResult.java
GetRouteResponseResult.withResponseModels
public GetRouteResponseResult withResponseModels(java.util.Map<String, String> responseModels) { setResponseModels(responseModels); return this; }
java
public GetRouteResponseResult withResponseModels(java.util.Map<String, String> responseModels) { setResponseModels(responseModels); return this; }
[ "public", "GetRouteResponseResult", "withResponseModels", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseModels", ")", "{", "setResponseModels", "(", "responseModels", ")", ";", "return", "this", ";", "}" ]
<p> Represents the response models of a route response. </p> @param responseModels Represents the response models of a route response. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Represents", "the", "response", "models", "of", "a", "route", "response", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-apigatewayv2/src/main/java/com/amazonaws/services/apigatewayv2/model/GetRouteResponseResult.java#L127-L130
pressgang-ccms/PressGangCCMSContentSpecProcessor
src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java
ContentSpecParser.changeCurrentLevel
protected void changeCurrentLevel(ParserData parserData, final Level newLevel, int newIndentationLevel) { parserData.setIndentationLevel(newIndentationLevel); parserData.setCurrentLevel(newLevel); }
java
protected void changeCurrentLevel(ParserData parserData, final Level newLevel, int newIndentationLevel) { parserData.setIndentationLevel(newIndentationLevel); parserData.setCurrentLevel(newLevel); }
[ "protected", "void", "changeCurrentLevel", "(", "ParserData", "parserData", ",", "final", "Level", "newLevel", ",", "int", "newIndentationLevel", ")", "{", "parserData", ".", "setIndentationLevel", "(", "newIndentationLevel", ")", ";", "parserData", ".", "setCurrentLevel", "(", "newLevel", ")", ";", "}" ]
Changes the current level that content is being processed for to a new level. @param parserData @param newLevel The new level to process for, @param newIndentationLevel The new indentation level of the level in the Content Specification.
[ "Changes", "the", "current", "level", "that", "content", "is", "being", "processed", "for", "to", "a", "new", "level", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpecProcessor/blob/85ffac047c4ede0f972364ab1f03f7d61a4de5f1/src/main/java/org/jboss/pressgang/ccms/contentspec/processor/ContentSpecParser.java#L946-L949
rhuss/jolokia
agent/core/src/main/java/org/jolokia/util/JmxUtil.java
JmxUtil.newObjectName
public static ObjectName newObjectName(String pName) { try { return new ObjectName(pName); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("Invalid object name " + pName,e); } }
java
public static ObjectName newObjectName(String pName) { try { return new ObjectName(pName); } catch (MalformedObjectNameException e) { throw new IllegalArgumentException("Invalid object name " + pName,e); } }
[ "public", "static", "ObjectName", "newObjectName", "(", "String", "pName", ")", "{", "try", "{", "return", "new", "ObjectName", "(", "pName", ")", ";", "}", "catch", "(", "MalformedObjectNameException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid object name \"", "+", "pName", ",", "e", ")", ";", "}", "}" ]
Factory method for creating a new object name, mapping any checked {@link MalformedObjectNameException} to a runtime exception ({@link IllegalArgumentException}) @param pName name to convert @return the created object name
[ "Factory", "method", "for", "creating", "a", "new", "object", "name", "mapping", "any", "checked", "{" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/core/src/main/java/org/jolokia/util/JmxUtil.java#L25-L31
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/model/BuildWithDetails.java
BuildWithDetails.updateDisplayNameAndDescription
public BuildWithDetails updateDisplayNameAndDescription(String displayName, String description, boolean crumbFlag) throws IOException { Objects.requireNonNull(displayName, "displayName is not allowed to be null."); Objects.requireNonNull(description, "description is not allowed to be null."); //TODO:JDK9+ Map.of()... Map<String, String> params = new HashMap<>(); params.put("displayName", displayName); params.put("description", description); // TODO: Check what the "core:apply" means? params.put("core:apply", ""); params.put("Submit", "Save"); client.post_form(this.getUrl() + "/configSubmit?", params, crumbFlag); return this; }
java
public BuildWithDetails updateDisplayNameAndDescription(String displayName, String description, boolean crumbFlag) throws IOException { Objects.requireNonNull(displayName, "displayName is not allowed to be null."); Objects.requireNonNull(description, "description is not allowed to be null."); //TODO:JDK9+ Map.of()... Map<String, String> params = new HashMap<>(); params.put("displayName", displayName); params.put("description", description); // TODO: Check what the "core:apply" means? params.put("core:apply", ""); params.put("Submit", "Save"); client.post_form(this.getUrl() + "/configSubmit?", params, crumbFlag); return this; }
[ "public", "BuildWithDetails", "updateDisplayNameAndDescription", "(", "String", "displayName", ",", "String", "description", ",", "boolean", "crumbFlag", ")", "throws", "IOException", "{", "Objects", ".", "requireNonNull", "(", "displayName", ",", "\"displayName is not allowed to be null.\"", ")", ";", "Objects", ".", "requireNonNull", "(", "description", ",", "\"description is not allowed to be null.\"", ")", ";", "//TODO:JDK9+ Map.of()...", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "HashMap", "<>", "(", ")", ";", "params", ".", "put", "(", "\"displayName\"", ",", "displayName", ")", ";", "params", ".", "put", "(", "\"description\"", ",", "description", ")", ";", "// TODO: Check what the \"core:apply\" means?", "params", ".", "put", "(", "\"core:apply\"", ",", "\"\"", ")", ";", "params", ".", "put", "(", "\"Submit\"", ",", "\"Save\"", ")", ";", "client", ".", "post_form", "(", "this", ".", "getUrl", "(", ")", "+", "\"/configSubmit?\"", ",", "params", ",", "crumbFlag", ")", ";", "return", "this", ";", "}" ]
Update <code>displayName</code> and the <code>description</code> of a build. @param displayName The new displayName which should be set. @param description The description which should be set. @param crumbFlag <code>true</code> or <code>false</code>. @throws IOException in case of errors.
[ "Update", "<code", ">", "displayName<", "/", "code", ">", "and", "the", "<code", ">", "description<", "/", "code", ">", "of", "a", "build", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/model/BuildWithDetails.java#L181-L194
Stratio/bdt
src/main/java/com/stratio/qa/specs/CommonG.java
CommonG.asYaml
public String asYaml(String jsonStringFile) throws JsonProcessingException, IOException, FileNotFoundException { InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonStringFile); Writer writer = new StringWriter(); char[] buffer = new char[1024]; Reader reader; if (stream == null) { this.getLogger().error("File does not exist: {}", jsonStringFile); throw new FileNotFoundException("ERR! File not found: " + jsonStringFile); } try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (Exception readerexception) { this.getLogger().error(readerexception.getMessage()); } finally { try { stream.close(); } catch (Exception closeException) { this.getLogger().error(closeException.getMessage()); } } String text = writer.toString(); String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input // parse JSON JsonNode jsonNodeTree = new ObjectMapper().readTree(std); // save it as YAML String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree); return jsonAsYaml; }
java
public String asYaml(String jsonStringFile) throws JsonProcessingException, IOException, FileNotFoundException { InputStream stream = getClass().getClassLoader().getResourceAsStream(jsonStringFile); Writer writer = new StringWriter(); char[] buffer = new char[1024]; Reader reader; if (stream == null) { this.getLogger().error("File does not exist: {}", jsonStringFile); throw new FileNotFoundException("ERR! File not found: " + jsonStringFile); } try { reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); int n; while ((n = reader.read(buffer)) != -1) { writer.write(buffer, 0, n); } } catch (Exception readerexception) { this.getLogger().error(readerexception.getMessage()); } finally { try { stream.close(); } catch (Exception closeException) { this.getLogger().error(closeException.getMessage()); } } String text = writer.toString(); String std = text.replace("\r", "").replace("\n", ""); // make sure we have unix style text regardless of the input // parse JSON JsonNode jsonNodeTree = new ObjectMapper().readTree(std); // save it as YAML String jsonAsYaml = new YAMLMapper().writeValueAsString(jsonNodeTree); return jsonAsYaml; }
[ "public", "String", "asYaml", "(", "String", "jsonStringFile", ")", "throws", "JsonProcessingException", ",", "IOException", ",", "FileNotFoundException", "{", "InputStream", "stream", "=", "getClass", "(", ")", ".", "getClassLoader", "(", ")", ".", "getResourceAsStream", "(", "jsonStringFile", ")", ";", "Writer", "writer", "=", "new", "StringWriter", "(", ")", ";", "char", "[", "]", "buffer", "=", "new", "char", "[", "1024", "]", ";", "Reader", "reader", ";", "if", "(", "stream", "==", "null", ")", "{", "this", ".", "getLogger", "(", ")", ".", "error", "(", "\"File does not exist: {}\"", ",", "jsonStringFile", ")", ";", "throw", "new", "FileNotFoundException", "(", "\"ERR! File not found: \"", "+", "jsonStringFile", ")", ";", "}", "try", "{", "reader", "=", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "stream", ",", "\"UTF-8\"", ")", ")", ";", "int", "n", ";", "while", "(", "(", "n", "=", "reader", ".", "read", "(", "buffer", ")", ")", "!=", "-", "1", ")", "{", "writer", ".", "write", "(", "buffer", ",", "0", ",", "n", ")", ";", "}", "}", "catch", "(", "Exception", "readerexception", ")", "{", "this", ".", "getLogger", "(", ")", ".", "error", "(", "readerexception", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "try", "{", "stream", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "closeException", ")", "{", "this", ".", "getLogger", "(", ")", ".", "error", "(", "closeException", ".", "getMessage", "(", ")", ")", ";", "}", "}", "String", "text", "=", "writer", ".", "toString", "(", ")", ";", "String", "std", "=", "text", ".", "replace", "(", "\"\\r\"", ",", "\"\"", ")", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", ";", "// make sure we have unix style text regardless of the input", "// parse JSON", "JsonNode", "jsonNodeTree", "=", "new", "ObjectMapper", "(", ")", ".", "readTree", "(", "std", ")", ";", "// save it as YAML", "String", "jsonAsYaml", "=", "new", "YAMLMapper", "(", ")", ".", "writeValueAsString", "(", "jsonNodeTree", ")", ";", "return", "jsonAsYaml", ";", "}" ]
Method to convert one json to yaml file - backup&restore functionality <p> File will be placed on path /target/test-classes
[ "Method", "to", "convert", "one", "json", "to", "yaml", "file", "-", "backup&restore", "functionality", "<p", ">", "File", "will", "be", "placed", "on", "path", "/", "target", "/", "test", "-", "classes" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L2068-L2105
Swagger2Markup/swagger2markup
src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java
PathsDocument.buildOperation
private void buildOperation(MarkupDocBuilder markupDocBuilder, PathOperation operation, Swagger2MarkupConfig config) { if (config.isSeparatedOperationsEnabled()) { MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder); applyPathOperationComponent(pathDocBuilder, operation); java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation)); pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8); if (logger.isDebugEnabled()) { logger.debug("Separate operation file produced : '{}'", operationFile); } buildOperationRef(markupDocBuilder, operation); } else { applyPathOperationComponent(markupDocBuilder, operation); } if (logger.isDebugEnabled()) { logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId())); } }
java
private void buildOperation(MarkupDocBuilder markupDocBuilder, PathOperation operation, Swagger2MarkupConfig config) { if (config.isSeparatedOperationsEnabled()) { MarkupDocBuilder pathDocBuilder = copyMarkupDocBuilder(markupDocBuilder); applyPathOperationComponent(pathDocBuilder, operation); java.nio.file.Path operationFile = context.getOutputPath().resolve(operationDocumentNameResolver.apply(operation)); pathDocBuilder.writeToFileWithoutExtension(operationFile, StandardCharsets.UTF_8); if (logger.isDebugEnabled()) { logger.debug("Separate operation file produced : '{}'", operationFile); } buildOperationRef(markupDocBuilder, operation); } else { applyPathOperationComponent(markupDocBuilder, operation); } if (logger.isDebugEnabled()) { logger.debug("Operation processed : '{}' (normalized id = '{}')", operation, normalizeName(operation.getId())); } }
[ "private", "void", "buildOperation", "(", "MarkupDocBuilder", "markupDocBuilder", ",", "PathOperation", "operation", ",", "Swagger2MarkupConfig", "config", ")", "{", "if", "(", "config", ".", "isSeparatedOperationsEnabled", "(", ")", ")", "{", "MarkupDocBuilder", "pathDocBuilder", "=", "copyMarkupDocBuilder", "(", "markupDocBuilder", ")", ";", "applyPathOperationComponent", "(", "pathDocBuilder", ",", "operation", ")", ";", "java", ".", "nio", ".", "file", ".", "Path", "operationFile", "=", "context", ".", "getOutputPath", "(", ")", ".", "resolve", "(", "operationDocumentNameResolver", ".", "apply", "(", "operation", ")", ")", ";", "pathDocBuilder", ".", "writeToFileWithoutExtension", "(", "operationFile", ",", "StandardCharsets", ".", "UTF_8", ")", ";", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Separate operation file produced : '{}'\"", ",", "operationFile", ")", ";", "}", "buildOperationRef", "(", "markupDocBuilder", ",", "operation", ")", ";", "}", "else", "{", "applyPathOperationComponent", "(", "markupDocBuilder", ",", "operation", ")", ";", "}", "if", "(", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "logger", ".", "debug", "(", "\"Operation processed : '{}' (normalized id = '{}')\"", ",", "operation", ",", "normalizeName", "(", "operation", ".", "getId", "(", ")", ")", ")", ";", "}", "}" ]
Builds a path operation depending on generation mode. @param operation operation
[ "Builds", "a", "path", "operation", "depending", "on", "generation", "mode", "." ]
train
https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/PathsDocument.java#L207-L225
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java
PoolsImpl.deleteAsync
public Observable<Void> deleteAsync(String poolId) { return deleteWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolDeleteHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, PoolDeleteHeaders> response) { return response.body(); } }); }
java
public Observable<Void> deleteAsync(String poolId) { return deleteWithServiceResponseAsync(poolId).map(new Func1<ServiceResponseWithHeaders<Void, PoolDeleteHeaders>, Void>() { @Override public Void call(ServiceResponseWithHeaders<Void, PoolDeleteHeaders> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "deleteAsync", "(", "String", "poolId", ")", "{", "return", "deleteWithServiceResponseAsync", "(", "poolId", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponseWithHeaders", "<", "Void", ",", "PoolDeleteHeaders", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponseWithHeaders", "<", "Void", ",", "PoolDeleteHeaders", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Deletes a pool from the specified account. When you request that a pool be deleted, the following actions occur: the pool state is set to deleting; any ongoing resize operation on the pool are stopped; the Batch service starts resizing the pool to zero nodes; any tasks running on existing nodes are terminated and requeued (as if a resize pool operation had been requested with the default requeue option); finally, the pool is removed from the system. Because running tasks are requeued, the user can rerun these tasks by updating their job to target a different pool. The tasks can then run on the new pool. If you want to override the requeue behavior, then you should call resize pool explicitly to shrink the pool to zero size before deleting the pool. If you call an Update, Patch or Delete API on a pool in the deleting state, it will fail with HTTP status code 409 with error code PoolBeingDeleted. @param poolId The ID of the pool to delete. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponseWithHeaders} object if successful.
[ "Deletes", "a", "pool", "from", "the", "specified", "account", ".", "When", "you", "request", "that", "a", "pool", "be", "deleted", "the", "following", "actions", "occur", ":", "the", "pool", "state", "is", "set", "to", "deleting", ";", "any", "ongoing", "resize", "operation", "on", "the", "pool", "are", "stopped", ";", "the", "Batch", "service", "starts", "resizing", "the", "pool", "to", "zero", "nodes", ";", "any", "tasks", "running", "on", "existing", "nodes", "are", "terminated", "and", "requeued", "(", "as", "if", "a", "resize", "pool", "operation", "had", "been", "requested", "with", "the", "default", "requeue", "option", ")", ";", "finally", "the", "pool", "is", "removed", "from", "the", "system", ".", "Because", "running", "tasks", "are", "requeued", "the", "user", "can", "rerun", "these", "tasks", "by", "updating", "their", "job", "to", "target", "a", "different", "pool", ".", "The", "tasks", "can", "then", "run", "on", "the", "new", "pool", ".", "If", "you", "want", "to", "override", "the", "requeue", "behavior", "then", "you", "should", "call", "resize", "pool", "explicitly", "to", "shrink", "the", "pool", "to", "zero", "size", "before", "deleting", "the", "pool", ".", "If", "you", "call", "an", "Update", "Patch", "or", "Delete", "API", "on", "a", "pool", "in", "the", "deleting", "state", "it", "will", "fail", "with", "HTTP", "status", "code", "409", "with", "error", "code", "PoolBeingDeleted", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L1171-L1178
Drivemode/TypefaceHelper
TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java
TypefaceHelper.setTypeface
public View setTypeface(Context context, @LayoutRes int layoutRes, ViewGroup parent, String typefaceName, int style) { ViewGroup view = (ViewGroup) LayoutInflater.from(context).inflate(layoutRes, parent); setTypeface(view, typefaceName, style); return view; }
java
public View setTypeface(Context context, @LayoutRes int layoutRes, ViewGroup parent, String typefaceName, int style) { ViewGroup view = (ViewGroup) LayoutInflater.from(context).inflate(layoutRes, parent); setTypeface(view, typefaceName, style); return view; }
[ "public", "View", "setTypeface", "(", "Context", "context", ",", "@", "LayoutRes", "int", "layoutRes", ",", "ViewGroup", "parent", ",", "String", "typefaceName", ",", "int", "style", ")", "{", "ViewGroup", "view", "=", "(", "ViewGroup", ")", "LayoutInflater", ".", "from", "(", "context", ")", ".", "inflate", "(", "layoutRes", ",", "parent", ")", ";", "setTypeface", "(", "view", ",", "typefaceName", ",", "style", ")", ";", "return", "view", ";", "}" ]
Set the typeface to the all text views belong to the view group. @param context the context. @param layoutRes the layout resource id. @param parent the parent view group to attach the layout. @param typefaceName typeface name. @param style the typeface style. @return the view.
[ "Set", "the", "typeface", "to", "the", "all", "text", "views", "belong", "to", "the", "view", "group", "." ]
train
https://github.com/Drivemode/TypefaceHelper/blob/86bef9ce16b9626b7076559e846db1b9f043c008/TypefaceHelper/src/main/java/com/drivemode/android/typeface/TypefaceHelper.java#L290-L294
arquillian/arquillian-algeron
common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java
GitOperations.createTag
public Ref createTag(Git git, String name) { try { return git.tag() .setName(name) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
java
public Ref createTag(Git git, String name) { try { return git.tag() .setName(name) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } }
[ "public", "Ref", "createTag", "(", "Git", "git", ",", "String", "name", ")", "{", "try", "{", "return", "git", ".", "tag", "(", ")", ".", "setName", "(", "name", ")", ".", "call", "(", ")", ";", "}", "catch", "(", "GitAPIException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "}" ]
Creates a tag. @param git instance. @param name of the tag. @return Ref created to tag.
[ "Creates", "a", "tag", "." ]
train
https://github.com/arquillian/arquillian-algeron/blob/ec79372defdafe99ab2f7bb696f1c1eabdbbacb6/common/git/src/main/java/org/arquillian/algeron/git/GitOperations.java#L329-L337
Netflix/netflix-graph
src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java
NFBuildGraph.addConnection
public void addConnection(NFBuildGraphNode fromNode, NFPropertySpec propertySpec, int connectionModelIndex, NFBuildGraphNode toNode) { fromNode.addConnection(connectionModelIndex, propertySpec, toNode.getOrdinal()); toNode.incrementNumIncomingConnections(); }
java
public void addConnection(NFBuildGraphNode fromNode, NFPropertySpec propertySpec, int connectionModelIndex, NFBuildGraphNode toNode) { fromNode.addConnection(connectionModelIndex, propertySpec, toNode.getOrdinal()); toNode.incrementNumIncomingConnections(); }
[ "public", "void", "addConnection", "(", "NFBuildGraphNode", "fromNode", ",", "NFPropertySpec", "propertySpec", ",", "int", "connectionModelIndex", ",", "NFBuildGraphNode", "toNode", ")", "{", "fromNode", ".", "addConnection", "(", "connectionModelIndex", ",", "propertySpec", ",", "toNode", ".", "getOrdinal", "(", ")", ")", ";", "toNode", ".", "incrementNumIncomingConnections", "(", ")", ";", "}" ]
Add a connection to this graph. This method is exposed for efficiency purposes. It is more efficient than {@code addConnection(String connectionModel, String nodeType, int fromOrdinal, String viaPropertyName, int toOrdinal)} as it avoids multiple lookups for <code>fromNode</code>, <code>propertySpec</code>, <code>connectionModelIndex</code> and <code>toNode</code>.
[ "Add", "a", "connection", "to", "this", "graph", ".", "This", "method", "is", "exposed", "for", "efficiency", "purposes", ".", "It", "is", "more", "efficient", "than", "{" ]
train
https://github.com/Netflix/netflix-graph/blob/ee129252a08a9f51dd296d6fca2f0b28b7be284e/src/main/java/com/netflix/nfgraph/build/NFBuildGraph.java#L119-L122
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/server/reactive/WebFluxLinkBuilder.java
WebFluxLinkBuilder.linkTo
public static WebFluxBuilder linkTo(Object invocation, ServerWebExchange exchange) { return new WebFluxBuilder(linkToInternal(invocation, Mono.just(getBuilder(exchange)))); }
java
public static WebFluxBuilder linkTo(Object invocation, ServerWebExchange exchange) { return new WebFluxBuilder(linkToInternal(invocation, Mono.just(getBuilder(exchange)))); }
[ "public", "static", "WebFluxBuilder", "linkTo", "(", "Object", "invocation", ",", "ServerWebExchange", "exchange", ")", "{", "return", "new", "WebFluxBuilder", "(", "linkToInternal", "(", "invocation", ",", "Mono", ".", "just", "(", "getBuilder", "(", "exchange", ")", ")", ")", ")", ";", "}" ]
Create a {@link WebFluxLinkBuilder} using an explicitly defined {@link ServerWebExchange}. This is possible if your WebFlux method includes the exchange and you want to pass it straight in. @param invocation must not be {@literal null}. @param exchange must not be {@literal null}.
[ "Create", "a", "{", "@link", "WebFluxLinkBuilder", "}", "using", "an", "explicitly", "defined", "{", "@link", "ServerWebExchange", "}", ".", "This", "is", "possible", "if", "your", "WebFlux", "method", "includes", "the", "exchange", "and", "you", "want", "to", "pass", "it", "straight", "in", "." ]
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/reactive/WebFluxLinkBuilder.java#L79-L81
protobufel/protobuf-el
protobufel/src/main/java/com/github/protobufel/DynamicMessage.java
DynamicMessage.parseFrom
public static DynamicMessage parseFrom(final Descriptor type, final InputStream input) throws IOException { return wrap(com.google.protobuf.DynamicMessage.parseFrom(type, input)); }
java
public static DynamicMessage parseFrom(final Descriptor type, final InputStream input) throws IOException { return wrap(com.google.protobuf.DynamicMessage.parseFrom(type, input)); }
[ "public", "static", "DynamicMessage", "parseFrom", "(", "final", "Descriptor", "type", ",", "final", "InputStream", "input", ")", "throws", "IOException", "{", "return", "wrap", "(", "com", ".", "google", ".", "protobuf", ".", "DynamicMessage", ".", "parseFrom", "(", "type", ",", "input", ")", ")", ";", "}" ]
Parse a message of the given type from {@code input} and return it.
[ "Parse", "a", "message", "of", "the", "given", "type", "from", "{" ]
train
https://github.com/protobufel/protobuf-el/blob/3a600e2f7a8e74b637f44eee0331ef6e57e7441c/protobufel/src/main/java/com/github/protobufel/DynamicMessage.java#L165-L168
allengeorge/libraft
libraft-agent/src/main/java/io/libraft/agent/rpc/Handshakers.java
Handshakers.getServerIdFromHandshake
static String getServerIdFromHandshake(ChannelBuffer handshakeBuffer, ObjectMapper mapper) throws IOException { Handshake handshake = getHandshakeFromBuffer(handshakeBuffer, mapper); return handshake.getServerId(); }
java
static String getServerIdFromHandshake(ChannelBuffer handshakeBuffer, ObjectMapper mapper) throws IOException { Handshake handshake = getHandshakeFromBuffer(handshakeBuffer, mapper); return handshake.getServerId(); }
[ "static", "String", "getServerIdFromHandshake", "(", "ChannelBuffer", "handshakeBuffer", ",", "ObjectMapper", "mapper", ")", "throws", "IOException", "{", "Handshake", "handshake", "=", "getHandshakeFromBuffer", "(", "handshakeBuffer", ",", "mapper", ")", ";", "return", "handshake", ".", "getServerId", "(", ")", ";", "}" ]
Extract the unique id of the Raft server that sent a handshake message from its wire representation. @param handshakeBuffer instance of {@code ChannelBuffer} that contains the encoded handshake message @param mapper instance of {@code ObjectMapper} used to map handshake fields in the encoded message to their corresponding Java representation @return unique id of the Raft server that sent the handshake message @throws IOException if a valid handshake cannot be read from the {@code handshakeBuffer}
[ "Extract", "the", "unique", "id", "of", "the", "Raft", "server", "that", "sent", "a", "handshake", "message", "from", "its", "wire", "representation", "." ]
train
https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-agent/src/main/java/io/libraft/agent/rpc/Handshakers.java#L121-L124
threerings/playn
java/src/playn/java/JavaGLContext.java
JavaGLContext.convertImage
static BufferedImage convertImage (BufferedImage image) { switch (image.getType()) { case BufferedImage.TYPE_INT_ARGB_PRE: return image; // Already good to go case BufferedImage.TYPE_4BYTE_ABGR: image.coerceData(true); // Just premultiply the alpha and it's fine return image; } // Didn't know an easy thing to do, so create a whole new image in our preferred format BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics g = convertedImage.getGraphics(); g.setColor(new Color(0f, 0f, 0f, 0f)); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.drawImage(image, 0, 0, null); return convertedImage; }
java
static BufferedImage convertImage (BufferedImage image) { switch (image.getType()) { case BufferedImage.TYPE_INT_ARGB_PRE: return image; // Already good to go case BufferedImage.TYPE_4BYTE_ABGR: image.coerceData(true); // Just premultiply the alpha and it's fine return image; } // Didn't know an easy thing to do, so create a whole new image in our preferred format BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE); Graphics g = convertedImage.getGraphics(); g.setColor(new Color(0f, 0f, 0f, 0f)); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.drawImage(image, 0, 0, null); return convertedImage; }
[ "static", "BufferedImage", "convertImage", "(", "BufferedImage", "image", ")", "{", "switch", "(", "image", ".", "getType", "(", ")", ")", "{", "case", "BufferedImage", ".", "TYPE_INT_ARGB_PRE", ":", "return", "image", ";", "// Already good to go", "case", "BufferedImage", ".", "TYPE_4BYTE_ABGR", ":", "image", ".", "coerceData", "(", "true", ")", ";", "// Just premultiply the alpha and it's fine", "return", "image", ";", "}", "// Didn't know an easy thing to do, so create a whole new image in our preferred format", "BufferedImage", "convertedImage", "=", "new", "BufferedImage", "(", "image", ".", "getWidth", "(", ")", ",", "image", ".", "getHeight", "(", ")", ",", "BufferedImage", ".", "TYPE_INT_ARGB_PRE", ")", ";", "Graphics", "g", "=", "convertedImage", ".", "getGraphics", "(", ")", ";", "g", ".", "setColor", "(", "new", "Color", "(", "0f", ",", "0f", ",", "0f", ",", "0f", ")", ")", ";", "g", ".", "fillRect", "(", "0", ",", "0", ",", "image", ".", "getWidth", "(", ")", ",", "image", ".", "getHeight", "(", ")", ")", ";", "g", ".", "drawImage", "(", "image", ",", "0", ",", "0", ",", "null", ")", ";", "return", "convertedImage", ";", "}" ]
Converts the given image into a format for quick upload to the GPU.
[ "Converts", "the", "given", "image", "into", "a", "format", "for", "quick", "upload", "to", "the", "GPU", "." ]
train
https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/java/src/playn/java/JavaGLContext.java#L37-L55
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/FrameworkManager.java
FrameworkManager.introspectFramework
public void introspectFramework(String timestamp, Set<JavaDumpAction> javaDumpActions) { Tr.audit(tc, "info.introspect.request.received"); File dumpDir = config.getOutputFile(BootstrapConstants.SERVER_DUMP_FOLDER_PREFIX + timestamp + "/"); if (!dumpDir.exists()) { throw new IllegalStateException("dump directory does not exist."); } // generate java dumps if needed, and move them to the dump directory. if (javaDumpActions != null) { File javaDumpLocations = new File(dumpDir, BootstrapConstants.SERVER_DUMPED_FILE_LOCATIONS); dumpJava(javaDumpActions, javaDumpLocations); } IntrospectionContext introspectionCtx = new IntrospectionContext(systemBundleCtx, dumpDir); introspectionCtx.introspectAll(); // create dumped flag file File dumpedFlag = new File(dumpDir, BootstrapConstants.SERVER_DUMPED_FLAG_FILE_NAME); try { dumpedFlag.createNewFile(); } catch (IOException e) { Tr.warning(tc, "warn.unableWriteFile", dumpedFlag, e.getMessage()); } }
java
public void introspectFramework(String timestamp, Set<JavaDumpAction> javaDumpActions) { Tr.audit(tc, "info.introspect.request.received"); File dumpDir = config.getOutputFile(BootstrapConstants.SERVER_DUMP_FOLDER_PREFIX + timestamp + "/"); if (!dumpDir.exists()) { throw new IllegalStateException("dump directory does not exist."); } // generate java dumps if needed, and move them to the dump directory. if (javaDumpActions != null) { File javaDumpLocations = new File(dumpDir, BootstrapConstants.SERVER_DUMPED_FILE_LOCATIONS); dumpJava(javaDumpActions, javaDumpLocations); } IntrospectionContext introspectionCtx = new IntrospectionContext(systemBundleCtx, dumpDir); introspectionCtx.introspectAll(); // create dumped flag file File dumpedFlag = new File(dumpDir, BootstrapConstants.SERVER_DUMPED_FLAG_FILE_NAME); try { dumpedFlag.createNewFile(); } catch (IOException e) { Tr.warning(tc, "warn.unableWriteFile", dumpedFlag, e.getMessage()); } }
[ "public", "void", "introspectFramework", "(", "String", "timestamp", ",", "Set", "<", "JavaDumpAction", ">", "javaDumpActions", ")", "{", "Tr", ".", "audit", "(", "tc", ",", "\"info.introspect.request.received\"", ")", ";", "File", "dumpDir", "=", "config", ".", "getOutputFile", "(", "BootstrapConstants", ".", "SERVER_DUMP_FOLDER_PREFIX", "+", "timestamp", "+", "\"/\"", ")", ";", "if", "(", "!", "dumpDir", ".", "exists", "(", ")", ")", "{", "throw", "new", "IllegalStateException", "(", "\"dump directory does not exist.\"", ")", ";", "}", "// generate java dumps if needed, and move them to the dump directory.", "if", "(", "javaDumpActions", "!=", "null", ")", "{", "File", "javaDumpLocations", "=", "new", "File", "(", "dumpDir", ",", "BootstrapConstants", ".", "SERVER_DUMPED_FILE_LOCATIONS", ")", ";", "dumpJava", "(", "javaDumpActions", ",", "javaDumpLocations", ")", ";", "}", "IntrospectionContext", "introspectionCtx", "=", "new", "IntrospectionContext", "(", "systemBundleCtx", ",", "dumpDir", ")", ";", "introspectionCtx", ".", "introspectAll", "(", ")", ";", "// create dumped flag file", "File", "dumpedFlag", "=", "new", "File", "(", "dumpDir", ",", "BootstrapConstants", ".", "SERVER_DUMPED_FLAG_FILE_NAME", ")", ";", "try", "{", "dumpedFlag", ".", "createNewFile", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "Tr", ".", "warning", "(", "tc", ",", "\"warn.unableWriteFile\"", ",", "dumpedFlag", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
Introspect the framework Get all IntrospectableService from OSGi bundle context, and dump a running server status from them. @param timestamp Create a unique dump folder based on the time stamp string. @param javaDumpActions The java dumps to create, or null for the default set.
[ "Introspect", "the", "framework", "Get", "all", "IntrospectableService", "from", "OSGi", "bundle", "context", "and", "dump", "a", "running", "server", "status", "from", "them", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.nested/src/com/ibm/ws/kernel/launch/internal/FrameworkManager.java#L1061-L1085
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/MatrixFeatures_DSCC.java
MatrixFeatures_DSCC.isSameStructure
public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) { if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) { for (int i = 0; i <= a.numCols; i++) { if( a.col_idx[i] != b.col_idx[i] ) return false; } for (int i = 0; i < a.nz_length; i++) { if( a.nz_rows[i] != b.nz_rows[i] ) return false; } return true; } return false; }
java
public static boolean isSameStructure(DMatrixSparseCSC a , DMatrixSparseCSC b) { if( a.numRows == b.numRows && a.numCols == b.numCols && a.nz_length == b.nz_length) { for (int i = 0; i <= a.numCols; i++) { if( a.col_idx[i] != b.col_idx[i] ) return false; } for (int i = 0; i < a.nz_length; i++) { if( a.nz_rows[i] != b.nz_rows[i] ) return false; } return true; } return false; }
[ "public", "static", "boolean", "isSameStructure", "(", "DMatrixSparseCSC", "a", ",", "DMatrixSparseCSC", "b", ")", "{", "if", "(", "a", ".", "numRows", "==", "b", ".", "numRows", "&&", "a", ".", "numCols", "==", "b", ".", "numCols", "&&", "a", ".", "nz_length", "==", "b", ".", "nz_length", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<=", "a", ".", "numCols", ";", "i", "++", ")", "{", "if", "(", "a", ".", "col_idx", "[", "i", "]", "!=", "b", ".", "col_idx", "[", "i", "]", ")", "return", "false", ";", "}", "for", "(", "int", "i", "=", "0", ";", "i", "<", "a", ".", "nz_length", ";", "i", "++", ")", "{", "if", "(", "a", ".", "nz_rows", "[", "i", "]", "!=", "b", ".", "nz_rows", "[", "i", "]", ")", "return", "false", ";", "}", "return", "true", ";", "}", "return", "false", ";", "}" ]
Checks to see if the two matrices have the same shape and same pattern of non-zero elements @param a Matrix @param b Matrix @return true if the structure is the same
[ "Checks", "to", "see", "if", "the", "two", "matrices", "have", "the", "same", "shape", "and", "same", "pattern", "of", "non", "-", "zero", "elements" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/MatrixFeatures_DSCC.java#L97-L110
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_spla_id_PUT
public void serviceName_spla_id_PUT(String serviceName, Long id, OvhSpla body) throws IOException { String qPath = "/dedicated/server/{serviceName}/spla/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
java
public void serviceName_spla_id_PUT(String serviceName, Long id, OvhSpla body) throws IOException { String qPath = "/dedicated/server/{serviceName}/spla/{id}"; StringBuilder sb = path(qPath, serviceName, id); exec(qPath, "PUT", sb.toString(), body); }
[ "public", "void", "serviceName_spla_id_PUT", "(", "String", "serviceName", ",", "Long", "id", ",", "OvhSpla", "body", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/server/{serviceName}/spla/{id}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "id", ")", ";", "exec", "(", "qPath", ",", "\"PUT\"", ",", "sb", ".", "toString", "(", ")", ",", "body", ")", ";", "}" ]
Alter this object properties REST: PUT /dedicated/server/{serviceName}/spla/{id} @param body [required] New object properties @param serviceName [required] The internal name of your dedicated server @param id [required] License id
[ "Alter", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L679-L683
Ordinastie/MalisisCore
src/main/java/net/malisis/core/inventory/message/OpenInventoryMessage.java
OpenInventoryMessage.process
@Override public void process(Packet message, MessageContext ctx) { EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer(); if (message.type == ContainerType.TYPE_TILEENTITY) { IDirectInventoryProvider inventoryProvider = TileEntityUtils.getTileEntity( IDirectInventoryProvider.class, Utils.getClientWorld(), message.pos); if (inventoryProvider != null) MalisisInventory.open(player, inventoryProvider, message.windowId); } else if (message.type == ContainerType.TYPE_ITEM) { //TODO: send and use slot number instead of limited to equipped ItemStack itemStack = player.getHeldItemMainhand(); if (itemStack == null || !(itemStack.getItem() instanceof IDeferredInventoryProvider<?>)) return; @SuppressWarnings("unchecked") IDeferredInventoryProvider<ItemStack> inventoryProvider = (IDeferredInventoryProvider<ItemStack>) itemStack.getItem(); MalisisInventory.open(player, inventoryProvider, itemStack, message.windowId); } }
java
@Override public void process(Packet message, MessageContext ctx) { EntityPlayerSP player = (EntityPlayerSP) Utils.getClientPlayer(); if (message.type == ContainerType.TYPE_TILEENTITY) { IDirectInventoryProvider inventoryProvider = TileEntityUtils.getTileEntity( IDirectInventoryProvider.class, Utils.getClientWorld(), message.pos); if (inventoryProvider != null) MalisisInventory.open(player, inventoryProvider, message.windowId); } else if (message.type == ContainerType.TYPE_ITEM) { //TODO: send and use slot number instead of limited to equipped ItemStack itemStack = player.getHeldItemMainhand(); if (itemStack == null || !(itemStack.getItem() instanceof IDeferredInventoryProvider<?>)) return; @SuppressWarnings("unchecked") IDeferredInventoryProvider<ItemStack> inventoryProvider = (IDeferredInventoryProvider<ItemStack>) itemStack.getItem(); MalisisInventory.open(player, inventoryProvider, itemStack, message.windowId); } }
[ "@", "Override", "public", "void", "process", "(", "Packet", "message", ",", "MessageContext", "ctx", ")", "{", "EntityPlayerSP", "player", "=", "(", "EntityPlayerSP", ")", "Utils", ".", "getClientPlayer", "(", ")", ";", "if", "(", "message", ".", "type", "==", "ContainerType", ".", "TYPE_TILEENTITY", ")", "{", "IDirectInventoryProvider", "inventoryProvider", "=", "TileEntityUtils", ".", "getTileEntity", "(", "IDirectInventoryProvider", ".", "class", ",", "Utils", ".", "getClientWorld", "(", ")", ",", "message", ".", "pos", ")", ";", "if", "(", "inventoryProvider", "!=", "null", ")", "MalisisInventory", ".", "open", "(", "player", ",", "inventoryProvider", ",", "message", ".", "windowId", ")", ";", "}", "else", "if", "(", "message", ".", "type", "==", "ContainerType", ".", "TYPE_ITEM", ")", "{", "//TODO: send and use slot number instead of limited to equipped", "ItemStack", "itemStack", "=", "player", ".", "getHeldItemMainhand", "(", ")", ";", "if", "(", "itemStack", "==", "null", "||", "!", "(", "itemStack", ".", "getItem", "(", ")", "instanceof", "IDeferredInventoryProvider", "<", "?", ">", ")", ")", "return", ";", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "IDeferredInventoryProvider", "<", "ItemStack", ">", "inventoryProvider", "=", "(", "IDeferredInventoryProvider", "<", "ItemStack", ">", ")", "itemStack", ".", "getItem", "(", ")", ";", "MalisisInventory", ".", "open", "(", "player", ",", "inventoryProvider", ",", "itemStack", ",", "message", ".", "windowId", ")", ";", "}", "}" ]
Handles the received {@link Packet} on the client.<br> Opens the GUI for the {@link MalisisInventory} @param message the message @param ctx the ctx
[ "Handles", "the", "received", "{", "@link", "Packet", "}", "on", "the", "client", ".", "<br", ">", "Opens", "the", "GUI", "for", "the", "{", "@link", "MalisisInventory", "}" ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/inventory/message/OpenInventoryMessage.java#L74-L98
ops4j/org.ops4j.pax.swissbox
pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java
BndUtils.createBundle
public static InputStream createBundle( final InputStream jarInputStream, final Properties instructions, final String jarInfo, final OverwriteMode overwriteMode ) throws IOException { NullArgumentException.validateNotNull( jarInputStream, "Jar URL" ); NullArgumentException.validateNotNull( instructions, "Instructions" ); NullArgumentException.validateNotEmpty( jarInfo, "Jar info" ); LOG.debug( "Creating bundle for [" + jarInfo + "]" ); LOG.debug( "Overwrite mode: " + overwriteMode ); LOG.trace( "Using instructions " + instructions ); final Jar jar = new Jar( "dot", jarInputStream ); Manifest manifest = null; try { manifest = jar.getManifest(); } catch ( Exception e ) { jar.close(); throw new Ops4jException( e ); } // Make the jar a bundle if it is not already a bundle if( manifest == null || OverwriteMode.KEEP != overwriteMode || ( manifest.getMainAttributes().getValue( Analyzer.EXPORT_PACKAGE ) == null && manifest.getMainAttributes().getValue( Analyzer.IMPORT_PACKAGE ) == null ) ) { // Do not use instructions as default for properties because it looks like BND uses the props // via some other means then getProperty() and so the instructions will not be used at all // So, just copy instructions to properties final Properties properties = new Properties(); properties.putAll( instructions ); properties.put( "Generated-By-Ops4j-Pax-From", jarInfo ); final Analyzer analyzer = new Analyzer(); analyzer.setJar( jar ); analyzer.setProperties( properties ); if( manifest != null && OverwriteMode.MERGE == overwriteMode ) { analyzer.mergeManifest( manifest ); } checkMandatoryProperties( analyzer, jar, jarInfo ); try { Manifest newManifest = analyzer.calcManifest(); jar.setManifest( newManifest ); } catch ( Exception e ) { jar.close(); throw new Ops4jException( e ); } } return createInputStream( jar ); }
java
public static InputStream createBundle( final InputStream jarInputStream, final Properties instructions, final String jarInfo, final OverwriteMode overwriteMode ) throws IOException { NullArgumentException.validateNotNull( jarInputStream, "Jar URL" ); NullArgumentException.validateNotNull( instructions, "Instructions" ); NullArgumentException.validateNotEmpty( jarInfo, "Jar info" ); LOG.debug( "Creating bundle for [" + jarInfo + "]" ); LOG.debug( "Overwrite mode: " + overwriteMode ); LOG.trace( "Using instructions " + instructions ); final Jar jar = new Jar( "dot", jarInputStream ); Manifest manifest = null; try { manifest = jar.getManifest(); } catch ( Exception e ) { jar.close(); throw new Ops4jException( e ); } // Make the jar a bundle if it is not already a bundle if( manifest == null || OverwriteMode.KEEP != overwriteMode || ( manifest.getMainAttributes().getValue( Analyzer.EXPORT_PACKAGE ) == null && manifest.getMainAttributes().getValue( Analyzer.IMPORT_PACKAGE ) == null ) ) { // Do not use instructions as default for properties because it looks like BND uses the props // via some other means then getProperty() and so the instructions will not be used at all // So, just copy instructions to properties final Properties properties = new Properties(); properties.putAll( instructions ); properties.put( "Generated-By-Ops4j-Pax-From", jarInfo ); final Analyzer analyzer = new Analyzer(); analyzer.setJar( jar ); analyzer.setProperties( properties ); if( manifest != null && OverwriteMode.MERGE == overwriteMode ) { analyzer.mergeManifest( manifest ); } checkMandatoryProperties( analyzer, jar, jarInfo ); try { Manifest newManifest = analyzer.calcManifest(); jar.setManifest( newManifest ); } catch ( Exception e ) { jar.close(); throw new Ops4jException( e ); } } return createInputStream( jar ); }
[ "public", "static", "InputStream", "createBundle", "(", "final", "InputStream", "jarInputStream", ",", "final", "Properties", "instructions", ",", "final", "String", "jarInfo", ",", "final", "OverwriteMode", "overwriteMode", ")", "throws", "IOException", "{", "NullArgumentException", ".", "validateNotNull", "(", "jarInputStream", ",", "\"Jar URL\"", ")", ";", "NullArgumentException", ".", "validateNotNull", "(", "instructions", ",", "\"Instructions\"", ")", ";", "NullArgumentException", ".", "validateNotEmpty", "(", "jarInfo", ",", "\"Jar info\"", ")", ";", "LOG", ".", "debug", "(", "\"Creating bundle for [\"", "+", "jarInfo", "+", "\"]\"", ")", ";", "LOG", ".", "debug", "(", "\"Overwrite mode: \"", "+", "overwriteMode", ")", ";", "LOG", ".", "trace", "(", "\"Using instructions \"", "+", "instructions", ")", ";", "final", "Jar", "jar", "=", "new", "Jar", "(", "\"dot\"", ",", "jarInputStream", ")", ";", "Manifest", "manifest", "=", "null", ";", "try", "{", "manifest", "=", "jar", ".", "getManifest", "(", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "jar", ".", "close", "(", ")", ";", "throw", "new", "Ops4jException", "(", "e", ")", ";", "}", "// Make the jar a bundle if it is not already a bundle", "if", "(", "manifest", "==", "null", "||", "OverwriteMode", ".", "KEEP", "!=", "overwriteMode", "||", "(", "manifest", ".", "getMainAttributes", "(", ")", ".", "getValue", "(", "Analyzer", ".", "EXPORT_PACKAGE", ")", "==", "null", "&&", "manifest", ".", "getMainAttributes", "(", ")", ".", "getValue", "(", "Analyzer", ".", "IMPORT_PACKAGE", ")", "==", "null", ")", ")", "{", "// Do not use instructions as default for properties because it looks like BND uses the props", "// via some other means then getProperty() and so the instructions will not be used at all", "// So, just copy instructions to properties", "final", "Properties", "properties", "=", "new", "Properties", "(", ")", ";", "properties", ".", "putAll", "(", "instructions", ")", ";", "properties", ".", "put", "(", "\"Generated-By-Ops4j-Pax-From\"", ",", "jarInfo", ")", ";", "final", "Analyzer", "analyzer", "=", "new", "Analyzer", "(", ")", ";", "analyzer", ".", "setJar", "(", "jar", ")", ";", "analyzer", ".", "setProperties", "(", "properties", ")", ";", "if", "(", "manifest", "!=", "null", "&&", "OverwriteMode", ".", "MERGE", "==", "overwriteMode", ")", "{", "analyzer", ".", "mergeManifest", "(", "manifest", ")", ";", "}", "checkMandatoryProperties", "(", "analyzer", ",", "jar", ",", "jarInfo", ")", ";", "try", "{", "Manifest", "newManifest", "=", "analyzer", ".", "calcManifest", "(", ")", ";", "jar", ".", "setManifest", "(", "newManifest", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "jar", ".", "close", "(", ")", ";", "throw", "new", "Ops4jException", "(", "e", ")", ";", "}", "}", "return", "createInputStream", "(", "jar", ")", ";", "}" ]
Processes the input jar and generates the necessary OSGi headers using specified instructions. @param jarInputStream input stream for the jar to be processed. Cannot be null. @param instructions bnd specific processing instructions. Cannot be null. @param jarInfo information about the jar to be processed. Usually the jar url. Cannot be null or empty. @param overwriteMode manifets overwrite mode @return an input stream for the generated bundle @throws NullArgumentException if any of the parameters is null @throws IOException re-thron during jar processing
[ "Processes", "the", "input", "jar", "and", "generates", "the", "necessary", "OSGi", "headers", "using", "specified", "instructions", "." ]
train
https://github.com/ops4j/org.ops4j.pax.swissbox/blob/00b0ee16cdbe8017984a4d7ba808b10d985c5b5c/pax-swissbox-bnd/src/main/java/org/ops4j/pax/swissbox/bnd/BndUtils.java#L109-L172
meertensinstituut/mtas
src/main/java/mtas/codec/tree/IntervalTree.java
IntervalTree.printBalance
final private String printBalance(Integer p, N n) { StringBuilder text = new StringBuilder(); if (n != null) { text.append(printBalance((p + 1), n.leftChild)); String format = "%" + (3 * p) + "s"; text.append(String.format(format, "")); if (n.left == n.right) { text.append("[" + n.left + "] (" + n.max + ") : " + n.lists.size() + " lists\n"); } else { text.append("[" + n.left + "-" + n.right + "] (" + n.max + ") : " + n.lists.size() + " lists\n"); } text.append(printBalance((p + 1), n.rightChild)); } return text.toString(); }
java
final private String printBalance(Integer p, N n) { StringBuilder text = new StringBuilder(); if (n != null) { text.append(printBalance((p + 1), n.leftChild)); String format = "%" + (3 * p) + "s"; text.append(String.format(format, "")); if (n.left == n.right) { text.append("[" + n.left + "] (" + n.max + ") : " + n.lists.size() + " lists\n"); } else { text.append("[" + n.left + "-" + n.right + "] (" + n.max + ") : " + n.lists.size() + " lists\n"); } text.append(printBalance((p + 1), n.rightChild)); } return text.toString(); }
[ "final", "private", "String", "printBalance", "(", "Integer", "p", ",", "N", "n", ")", "{", "StringBuilder", "text", "=", "new", "StringBuilder", "(", ")", ";", "if", "(", "n", "!=", "null", ")", "{", "text", ".", "append", "(", "printBalance", "(", "(", "p", "+", "1", ")", ",", "n", ".", "leftChild", ")", ")", ";", "String", "format", "=", "\"%\"", "+", "(", "3", "*", "p", ")", "+", "\"s\"", ";", "text", ".", "append", "(", "String", ".", "format", "(", "format", ",", "\"\"", ")", ")", ";", "if", "(", "n", ".", "left", "==", "n", ".", "right", ")", "{", "text", ".", "append", "(", "\"[\"", "+", "n", ".", "left", "+", "\"] (\"", "+", "n", ".", "max", "+", "\") : \"", "+", "n", ".", "lists", ".", "size", "(", ")", "+", "\" lists\\n\"", ")", ";", "}", "else", "{", "text", ".", "append", "(", "\"[\"", "+", "n", ".", "left", "+", "\"-\"", "+", "n", ".", "right", "+", "\"] (\"", "+", "n", ".", "max", "+", "\") : \"", "+", "n", ".", "lists", ".", "size", "(", ")", "+", "\" lists\\n\"", ")", ";", "}", "text", ".", "append", "(", "printBalance", "(", "(", "p", "+", "1", ")", ",", "n", ".", "rightChild", ")", ")", ";", "}", "return", "text", ".", "toString", "(", ")", ";", "}" ]
Prints the balance. @param p the p @param n the n @return the string
[ "Prints", "the", "balance", "." ]
train
https://github.com/meertensinstituut/mtas/blob/f02ae730848616bd88b553efa7f9eddc32818e64/src/main/java/mtas/codec/tree/IntervalTree.java#L83-L99
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java
AttachmentManager.generateFilenameForKey
static String generateFilenameForKey(SQLDatabase db, String keyString) throws NameGenerationException { String filename = null; long result = -1; // -1 is error for insert call int tries = 0; while (result == -1 && tries < 200) { byte[] randomBytes = new byte[20]; filenameRandom.nextBytes(randomBytes); String candidate = keyToString(randomBytes); ContentValues contentValues = new ContentValues(); contentValues.put("key", keyString); contentValues.put("filename", candidate); result = db.insert(ATTACHMENTS_KEY_FILENAME, contentValues); if (result != -1) { // i.e., insert worked, filename unique filename = candidate; } tries++; } if (filename != null) { return filename; } else { throw new NameGenerationException(String.format( "Couldn't generate unique filename for attachment with key %s", keyString)); } }
java
static String generateFilenameForKey(SQLDatabase db, String keyString) throws NameGenerationException { String filename = null; long result = -1; // -1 is error for insert call int tries = 0; while (result == -1 && tries < 200) { byte[] randomBytes = new byte[20]; filenameRandom.nextBytes(randomBytes); String candidate = keyToString(randomBytes); ContentValues contentValues = new ContentValues(); contentValues.put("key", keyString); contentValues.put("filename", candidate); result = db.insert(ATTACHMENTS_KEY_FILENAME, contentValues); if (result != -1) { // i.e., insert worked, filename unique filename = candidate; } tries++; } if (filename != null) { return filename; } else { throw new NameGenerationException(String.format( "Couldn't generate unique filename for attachment with key %s", keyString)); } }
[ "static", "String", "generateFilenameForKey", "(", "SQLDatabase", "db", ",", "String", "keyString", ")", "throws", "NameGenerationException", "{", "String", "filename", "=", "null", ";", "long", "result", "=", "-", "1", ";", "// -1 is error for insert call", "int", "tries", "=", "0", ";", "while", "(", "result", "==", "-", "1", "&&", "tries", "<", "200", ")", "{", "byte", "[", "]", "randomBytes", "=", "new", "byte", "[", "20", "]", ";", "filenameRandom", ".", "nextBytes", "(", "randomBytes", ")", ";", "String", "candidate", "=", "keyToString", "(", "randomBytes", ")", ";", "ContentValues", "contentValues", "=", "new", "ContentValues", "(", ")", ";", "contentValues", ".", "put", "(", "\"key\"", ",", "keyString", ")", ";", "contentValues", ".", "put", "(", "\"filename\"", ",", "candidate", ")", ";", "result", "=", "db", ".", "insert", "(", "ATTACHMENTS_KEY_FILENAME", ",", "contentValues", ")", ";", "if", "(", "result", "!=", "-", "1", ")", "{", "// i.e., insert worked, filename unique", "filename", "=", "candidate", ";", "}", "tries", "++", ";", "}", "if", "(", "filename", "!=", "null", ")", "{", "return", "filename", ";", "}", "else", "{", "throw", "new", "NameGenerationException", "(", "String", ".", "format", "(", "\"Couldn't generate unique filename for attachment with key %s\"", ",", "keyString", ")", ")", ";", "}", "}" ]
Iterate candidate filenames generated from the filenameRandom generator until we find one which doesn't already exist. We try inserting the new record into attachments_key_filename to find a unique filename rather than checking on disk filenames. This is because we can make use of the fact that this method is called on a serial database queue to make sure our name is unique, whereas we don't have that guarantee for on-disk filenames. This works because filename is declared UNIQUE in the attachments_key_filename table. We allow up to 200 random name generations, which should give us many millions of files before a name fails to be generated and makes sure this method doesn't loop forever. @param db database to use @param keyString blob's key
[ "Iterate", "candidate", "filenames", "generated", "from", "the", "filenameRandom", "generator", "until", "we", "find", "one", "which", "doesn", "t", "already", "exist", "." ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/documentstore/AttachmentManager.java#L552-L582
ModeShape/modeshape
modeshape-jcr-api/src/main/java/org/modeshape/jcr/api/sequencer/Sequencer.java
Sequencer.registerNamespace
protected boolean registerNamespace( String namespacePrefix, String namespaceUri, NamespaceRegistry namespaceRegistry ) throws RepositoryException { if (namespacePrefix == null || namespaceUri == null) { throw new IllegalArgumentException("Neither the namespace prefix, nor the uri should be null"); } try { // if the call succeeds, means it was previously registered namespaceRegistry.getPrefix(namespaceUri); return false; } catch (NamespaceException e) { // namespace not registered yet namespaceRegistry.registerNamespace(namespacePrefix, namespaceUri); return true; } }
java
protected boolean registerNamespace( String namespacePrefix, String namespaceUri, NamespaceRegistry namespaceRegistry ) throws RepositoryException { if (namespacePrefix == null || namespaceUri == null) { throw new IllegalArgumentException("Neither the namespace prefix, nor the uri should be null"); } try { // if the call succeeds, means it was previously registered namespaceRegistry.getPrefix(namespaceUri); return false; } catch (NamespaceException e) { // namespace not registered yet namespaceRegistry.registerNamespace(namespacePrefix, namespaceUri); return true; } }
[ "protected", "boolean", "registerNamespace", "(", "String", "namespacePrefix", ",", "String", "namespaceUri", ",", "NamespaceRegistry", "namespaceRegistry", ")", "throws", "RepositoryException", "{", "if", "(", "namespacePrefix", "==", "null", "||", "namespaceUri", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Neither the namespace prefix, nor the uri should be null\"", ")", ";", "}", "try", "{", "// if the call succeeds, means it was previously registered", "namespaceRegistry", ".", "getPrefix", "(", "namespaceUri", ")", ";", "return", "false", ";", "}", "catch", "(", "NamespaceException", "e", ")", "{", "// namespace not registered yet", "namespaceRegistry", ".", "registerNamespace", "(", "namespacePrefix", ",", "namespaceUri", ")", ";", "return", "true", ";", "}", "}" ]
Registers a namespace using the given {@link NamespaceRegistry}, if the namespace has not been previously registered. @param namespacePrefix a non-null {@code String} @param namespaceUri a non-null {@code String} @param namespaceRegistry a {@code NamespaceRegistry} instance. @return true if the namespace has been registered, or false if it was already registered @throws RepositoryException if anything fails during the registration process
[ "Registers", "a", "namespace", "using", "the", "given", "{", "@link", "NamespaceRegistry", "}", "if", "the", "namespace", "has", "not", "been", "previously", "registered", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr-api/src/main/java/org/modeshape/jcr/api/sequencer/Sequencer.java#L239-L254
GoogleCloudPlatform/bigdata-interop
gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageItemInfo.java
GoogleCloudStorageItemInfo.metadataEquals
public boolean metadataEquals(Map<String, byte[]> otherMetadata) { if (metadata == otherMetadata) { // Fast-path for common cases where the same actual default metadata instance may be used in // multiple different item infos. return true; } // No need to check if other `metadata` is not null, // because previous `if` checks if both of them are null. if (metadata == null || otherMetadata == null) { return false; } if (!metadata.keySet().equals(otherMetadata.keySet())) { return false; } // Compare each byte[] with Arrays.equals. for (Map.Entry<String, byte[]> metadataEntry : metadata.entrySet()) { if (!Arrays.equals(metadataEntry.getValue(), otherMetadata.get(metadataEntry.getKey()))) { return false; } } return true; }
java
public boolean metadataEquals(Map<String, byte[]> otherMetadata) { if (metadata == otherMetadata) { // Fast-path for common cases where the same actual default metadata instance may be used in // multiple different item infos. return true; } // No need to check if other `metadata` is not null, // because previous `if` checks if both of them are null. if (metadata == null || otherMetadata == null) { return false; } if (!metadata.keySet().equals(otherMetadata.keySet())) { return false; } // Compare each byte[] with Arrays.equals. for (Map.Entry<String, byte[]> metadataEntry : metadata.entrySet()) { if (!Arrays.equals(metadataEntry.getValue(), otherMetadata.get(metadataEntry.getKey()))) { return false; } } return true; }
[ "public", "boolean", "metadataEquals", "(", "Map", "<", "String", ",", "byte", "[", "]", ">", "otherMetadata", ")", "{", "if", "(", "metadata", "==", "otherMetadata", ")", "{", "// Fast-path for common cases where the same actual default metadata instance may be used in", "// multiple different item infos.", "return", "true", ";", "}", "// No need to check if other `metadata` is not null,", "// because previous `if` checks if both of them are null.", "if", "(", "metadata", "==", "null", "||", "otherMetadata", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "metadata", ".", "keySet", "(", ")", ".", "equals", "(", "otherMetadata", ".", "keySet", "(", ")", ")", ")", "{", "return", "false", ";", "}", "// Compare each byte[] with Arrays.equals.", "for", "(", "Map", ".", "Entry", "<", "String", ",", "byte", "[", "]", ">", "metadataEntry", ":", "metadata", ".", "entrySet", "(", ")", ")", "{", "if", "(", "!", "Arrays", ".", "equals", "(", "metadataEntry", ".", "getValue", "(", ")", ",", "otherMetadata", ".", "get", "(", "metadataEntry", ".", "getKey", "(", ")", ")", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Helper for checking logical equality of metadata maps, checking equality of keySet() between this.metadata and otherMetadata, and then using Arrays.equals to compare contents of corresponding byte arrays.
[ "Helper", "for", "checking", "logical", "equality", "of", "metadata", "maps", "checking", "equality", "of", "keySet", "()", "between", "this", ".", "metadata", "and", "otherMetadata", "and", "then", "using", "Arrays", ".", "equals", "to", "compare", "contents", "of", "corresponding", "byte", "arrays", "." ]
train
https://github.com/GoogleCloudPlatform/bigdata-interop/blob/918d91c80a63e36046edb28972a5c65d3326a858/gcsio/src/main/java/com/google/cloud/hadoop/gcsio/GoogleCloudStorageItemInfo.java#L317-L339
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/javac/comp/Infer.java
Infer.instantiatePolymorphicSignatureInstance
Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env, MethodSymbol spMethod, // sig. poly. method or null if none Resolve.MethodResolutionContext resolveContext, List<Type> argtypes) { final Type restype; //The return type for a polymorphic signature call is computed from //the enclosing tree E, as follows: if E is a cast, then use the //target type of the cast expression as a return type; if E is an //expression statement, the return type is 'void' - otherwise the //return type is simply 'Object'. A correctness check ensures that //env.next refers to the lexically enclosing environment in which //the polymorphic signature call environment is nested. switch (env.next.tree.getTag()) { case TYPECAST: JCTypeCast castTree = (JCTypeCast)env.next.tree; restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ? castTree.clazz.type : syms.objectType; break; case EXEC: JCTree.JCExpressionStatement execTree = (JCTree.JCExpressionStatement)env.next.tree; restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ? syms.voidType : syms.objectType; break; default: restype = syms.objectType; } List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step)); List<Type> exType = spMethod != null ? spMethod.getThrownTypes() : List.of(syms.throwableType); // make it throw all exceptions MethodType mtype = new MethodType(paramtypes, restype, exType, syms.methodClass); return mtype; }
java
Type instantiatePolymorphicSignatureInstance(Env<AttrContext> env, MethodSymbol spMethod, // sig. poly. method or null if none Resolve.MethodResolutionContext resolveContext, List<Type> argtypes) { final Type restype; //The return type for a polymorphic signature call is computed from //the enclosing tree E, as follows: if E is a cast, then use the //target type of the cast expression as a return type; if E is an //expression statement, the return type is 'void' - otherwise the //return type is simply 'Object'. A correctness check ensures that //env.next refers to the lexically enclosing environment in which //the polymorphic signature call environment is nested. switch (env.next.tree.getTag()) { case TYPECAST: JCTypeCast castTree = (JCTypeCast)env.next.tree; restype = (TreeInfo.skipParens(castTree.expr) == env.tree) ? castTree.clazz.type : syms.objectType; break; case EXEC: JCTree.JCExpressionStatement execTree = (JCTree.JCExpressionStatement)env.next.tree; restype = (TreeInfo.skipParens(execTree.expr) == env.tree) ? syms.voidType : syms.objectType; break; default: restype = syms.objectType; } List<Type> paramtypes = Type.map(argtypes, new ImplicitArgType(spMethod, resolveContext.step)); List<Type> exType = spMethod != null ? spMethod.getThrownTypes() : List.of(syms.throwableType); // make it throw all exceptions MethodType mtype = new MethodType(paramtypes, restype, exType, syms.methodClass); return mtype; }
[ "Type", "instantiatePolymorphicSignatureInstance", "(", "Env", "<", "AttrContext", ">", "env", ",", "MethodSymbol", "spMethod", ",", "// sig. poly. method or null if none", "Resolve", ".", "MethodResolutionContext", "resolveContext", ",", "List", "<", "Type", ">", "argtypes", ")", "{", "final", "Type", "restype", ";", "//The return type for a polymorphic signature call is computed from", "//the enclosing tree E, as follows: if E is a cast, then use the", "//target type of the cast expression as a return type; if E is an", "//expression statement, the return type is 'void' - otherwise the", "//return type is simply 'Object'. A correctness check ensures that", "//env.next refers to the lexically enclosing environment in which", "//the polymorphic signature call environment is nested.", "switch", "(", "env", ".", "next", ".", "tree", ".", "getTag", "(", ")", ")", "{", "case", "TYPECAST", ":", "JCTypeCast", "castTree", "=", "(", "JCTypeCast", ")", "env", ".", "next", ".", "tree", ";", "restype", "=", "(", "TreeInfo", ".", "skipParens", "(", "castTree", ".", "expr", ")", "==", "env", ".", "tree", ")", "?", "castTree", ".", "clazz", ".", "type", ":", "syms", ".", "objectType", ";", "break", ";", "case", "EXEC", ":", "JCTree", ".", "JCExpressionStatement", "execTree", "=", "(", "JCTree", ".", "JCExpressionStatement", ")", "env", ".", "next", ".", "tree", ";", "restype", "=", "(", "TreeInfo", ".", "skipParens", "(", "execTree", ".", "expr", ")", "==", "env", ".", "tree", ")", "?", "syms", ".", "voidType", ":", "syms", ".", "objectType", ";", "break", ";", "default", ":", "restype", "=", "syms", ".", "objectType", ";", "}", "List", "<", "Type", ">", "paramtypes", "=", "Type", ".", "map", "(", "argtypes", ",", "new", "ImplicitArgType", "(", "spMethod", ",", "resolveContext", ".", "step", ")", ")", ";", "List", "<", "Type", ">", "exType", "=", "spMethod", "!=", "null", "?", "spMethod", ".", "getThrownTypes", "(", ")", ":", "List", ".", "of", "(", "syms", ".", "throwableType", ")", ";", "// make it throw all exceptions", "MethodType", "mtype", "=", "new", "MethodType", "(", "paramtypes", ",", "restype", ",", "exType", ",", "syms", ".", "methodClass", ")", ";", "return", "mtype", ";", "}" ]
Compute a synthetic method type corresponding to the requested polymorphic method signature. The target return type is computed from the immediately enclosing scope surrounding the polymorphic-signature call.
[ "Compute", "a", "synthetic", "method", "type", "corresponding", "to", "the", "requested", "polymorphic", "method", "signature", ".", "The", "target", "return", "type", "is", "computed", "from", "the", "immediately", "enclosing", "scope", "surrounding", "the", "polymorphic", "-", "signature", "call", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/comp/Infer.java#L404-L446
chrisjenx/Calligraphy
calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java
CalligraphyFactory.matchesResourceIdName
protected static boolean matchesResourceIdName(View view, String matches) { if (view.getId() == View.NO_ID) return false; final String resourceEntryName = view.getResources().getResourceEntryName(view.getId()); return resourceEntryName.equalsIgnoreCase(matches); }
java
protected static boolean matchesResourceIdName(View view, String matches) { if (view.getId() == View.NO_ID) return false; final String resourceEntryName = view.getResources().getResourceEntryName(view.getId()); return resourceEntryName.equalsIgnoreCase(matches); }
[ "protected", "static", "boolean", "matchesResourceIdName", "(", "View", "view", ",", "String", "matches", ")", "{", "if", "(", "view", ".", "getId", "(", ")", "==", "View", ".", "NO_ID", ")", "return", "false", ";", "final", "String", "resourceEntryName", "=", "view", ".", "getResources", "(", ")", ".", "getResourceEntryName", "(", "view", ".", "getId", "(", ")", ")", ";", "return", "resourceEntryName", ".", "equalsIgnoreCase", "(", "matches", ")", ";", "}" ]
Use to match a view against a potential view id. Such as ActionBar title etc. @param view not null view you want to see has resource matching name. @param matches not null resource name to match against. Its not case sensitive. @return true if matches false otherwise.
[ "Use", "to", "match", "a", "view", "against", "a", "potential", "view", "id", ".", "Such", "as", "ActionBar", "title", "etc", "." ]
train
https://github.com/chrisjenx/Calligraphy/blob/085e441954d787bd4ef31f245afe5f2f2a311ea5/calligraphy/src/main/java/uk/co/chrisjenx/calligraphy/CalligraphyFactory.java#L87-L91
cache2k/cache2k
cache2k-core/src/main/java/org/cache2k/core/InternalCache2kBuilder.java
InternalCache2kBuilder.constructEviction
private Eviction constructEviction(HeapCache hc, HeapCacheListener l, Cache2kConfiguration config) { final boolean _strictEviction = config.isStrictEviction(); final int _availableProcessors = Runtime.getRuntime().availableProcessors(); final boolean _boostConcurrency = config.isBoostConcurrency(); final long _maximumWeight = config.getMaximumWeight(); long _entryCapacity = config.getEntryCapacity(); if (_entryCapacity < 0 && _maximumWeight < 0) { _entryCapacity = 2000; } final int _segmentCountOverride = HeapCache.TUNABLE.segmentCountOverride; int _segmentCount = determineSegmentCount(_strictEviction, _availableProcessors, _boostConcurrency, _entryCapacity, _segmentCountOverride); Eviction[] _segments = new Eviction[_segmentCount]; long _maxSize = determineMaxSize(_entryCapacity, _segmentCount); long _maxWeight = determineMaxWeight(_maximumWeight, _segmentCount); final Weigher _weigher = (Weigher) hc.createCustomization(config.getWeigher()); for (int i = 0; i < _segments.length; i++) { Eviction ev = new ClockProPlusEviction(hc, l, _maxSize, _weigher, _maxWeight); _segments[i] = ev; } if (_segmentCount == 1) { return _segments[0]; } return new SegmentedEviction(_segments); }
java
private Eviction constructEviction(HeapCache hc, HeapCacheListener l, Cache2kConfiguration config) { final boolean _strictEviction = config.isStrictEviction(); final int _availableProcessors = Runtime.getRuntime().availableProcessors(); final boolean _boostConcurrency = config.isBoostConcurrency(); final long _maximumWeight = config.getMaximumWeight(); long _entryCapacity = config.getEntryCapacity(); if (_entryCapacity < 0 && _maximumWeight < 0) { _entryCapacity = 2000; } final int _segmentCountOverride = HeapCache.TUNABLE.segmentCountOverride; int _segmentCount = determineSegmentCount(_strictEviction, _availableProcessors, _boostConcurrency, _entryCapacity, _segmentCountOverride); Eviction[] _segments = new Eviction[_segmentCount]; long _maxSize = determineMaxSize(_entryCapacity, _segmentCount); long _maxWeight = determineMaxWeight(_maximumWeight, _segmentCount); final Weigher _weigher = (Weigher) hc.createCustomization(config.getWeigher()); for (int i = 0; i < _segments.length; i++) { Eviction ev = new ClockProPlusEviction(hc, l, _maxSize, _weigher, _maxWeight); _segments[i] = ev; } if (_segmentCount == 1) { return _segments[0]; } return new SegmentedEviction(_segments); }
[ "private", "Eviction", "constructEviction", "(", "HeapCache", "hc", ",", "HeapCacheListener", "l", ",", "Cache2kConfiguration", "config", ")", "{", "final", "boolean", "_strictEviction", "=", "config", ".", "isStrictEviction", "(", ")", ";", "final", "int", "_availableProcessors", "=", "Runtime", ".", "getRuntime", "(", ")", ".", "availableProcessors", "(", ")", ";", "final", "boolean", "_boostConcurrency", "=", "config", ".", "isBoostConcurrency", "(", ")", ";", "final", "long", "_maximumWeight", "=", "config", ".", "getMaximumWeight", "(", ")", ";", "long", "_entryCapacity", "=", "config", ".", "getEntryCapacity", "(", ")", ";", "if", "(", "_entryCapacity", "<", "0", "&&", "_maximumWeight", "<", "0", ")", "{", "_entryCapacity", "=", "2000", ";", "}", "final", "int", "_segmentCountOverride", "=", "HeapCache", ".", "TUNABLE", ".", "segmentCountOverride", ";", "int", "_segmentCount", "=", "determineSegmentCount", "(", "_strictEviction", ",", "_availableProcessors", ",", "_boostConcurrency", ",", "_entryCapacity", ",", "_segmentCountOverride", ")", ";", "Eviction", "[", "]", "_segments", "=", "new", "Eviction", "[", "_segmentCount", "]", ";", "long", "_maxSize", "=", "determineMaxSize", "(", "_entryCapacity", ",", "_segmentCount", ")", ";", "long", "_maxWeight", "=", "determineMaxWeight", "(", "_maximumWeight", ",", "_segmentCount", ")", ";", "final", "Weigher", "_weigher", "=", "(", "Weigher", ")", "hc", ".", "createCustomization", "(", "config", ".", "getWeigher", "(", ")", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "_segments", ".", "length", ";", "i", "++", ")", "{", "Eviction", "ev", "=", "new", "ClockProPlusEviction", "(", "hc", ",", "l", ",", "_maxSize", ",", "_weigher", ",", "_maxWeight", ")", ";", "_segments", "[", "i", "]", "=", "ev", ";", "}", "if", "(", "_segmentCount", "==", "1", ")", "{", "return", "_segments", "[", "0", "]", ";", "}", "return", "new", "SegmentedEviction", "(", "_segments", ")", ";", "}" ]
Construct segmented or queued eviction. For the moment hard coded. If capacity is at least 1000 we use 2 segments if 2 or more CPUs are available. Segmenting the eviction only improves for lots of concurrent inserts or evictions, there is no effect on read performance.
[ "Construct", "segmented", "or", "queued", "eviction", ".", "For", "the", "moment", "hard", "coded", ".", "If", "capacity", "is", "at", "least", "1000", "we", "use", "2", "segments", "if", "2", "or", "more", "CPUs", "are", "available", ".", "Segmenting", "the", "eviction", "only", "improves", "for", "lots", "of", "concurrent", "inserts", "or", "evictions", "there", "is", "no", "effect", "on", "read", "performance", "." ]
train
https://github.com/cache2k/cache2k/blob/3c9ccff12608c598c387ec50957089784cc4b618/cache2k-core/src/main/java/org/cache2k/core/InternalCache2kBuilder.java#L366-L389
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SDVariable.java
SDVariable.gt
public SDVariable gt(String name, SDVariable other){ return sameDiff.gt(name, this, other); }
java
public SDVariable gt(String name, SDVariable other){ return sameDiff.gt(name, this, other); }
[ "public", "SDVariable", "gt", "(", "String", "name", ",", "SDVariable", "other", ")", "{", "return", "sameDiff", ".", "gt", "(", "name", ",", "this", ",", "other", ")", ";", "}" ]
Greater than operation: elementwise {@code this > y}<br> If x and y arrays have equal shape, the output shape is the same as the inputs.<br> Supports broadcasting: if x and y have different shapes and are broadcastable, the output shape is broadcast.<br> Returns an array with values 1 where condition is satisfied, or value 0 otherwise. @param name Name of the output variable @param other Variable to compare values against @return Output SDVariable with values 0 (not satisfied) and 1 (where the condition is satisfied)
[ "Greater", "than", "operation", ":", "elementwise", "{", "@code", "this", ">", "y", "}", "<br", ">", "If", "x", "and", "y", "arrays", "have", "equal", "shape", "the", "output", "shape", "is", "the", "same", "as", "the", "inputs", ".", "<br", ">", "Supports", "broadcasting", ":", "if", "x", "and", "y", "have", "different", "shapes", "and", "are", "broadcastable", "the", "output", "shape", "is", "broadcast", ".", "<br", ">", "Returns", "an", "array", "with", "values", "1", "where", "condition", "is", "satisfied", "or", "value", "0", "otherwise", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SDVariable.java#L546-L548
micrometer-metrics/micrometer
micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java
DatabaseTableMetrics.monitor
public static void monitor(MeterRegistry registry, String tableName, String dataSourceName, DataSource dataSource, String... tags) { monitor(registry, dataSource, dataSourceName, tableName, Tags.of(tags)); }
java
public static void monitor(MeterRegistry registry, String tableName, String dataSourceName, DataSource dataSource, String... tags) { monitor(registry, dataSource, dataSourceName, tableName, Tags.of(tags)); }
[ "public", "static", "void", "monitor", "(", "MeterRegistry", "registry", ",", "String", "tableName", ",", "String", "dataSourceName", ",", "DataSource", "dataSource", ",", "String", "...", "tags", ")", "{", "monitor", "(", "registry", ",", "dataSource", ",", "dataSourceName", ",", "tableName", ",", "Tags", ".", "of", "(", "tags", ")", ")", ";", "}" ]
Record the row count for an individual database table. @param registry The registry to bind metrics to. @param tableName The name of the table to report table size for. @param dataSourceName Will be used to tag metrics with "db". @param dataSource The data source to use to run the row count query. @param tags Tags to apply to all recorded metrics. Must be an even number of arguments representing key/value pairs of tags.
[ "Record", "the", "row", "count", "for", "an", "individual", "database", "table", "." ]
train
https://github.com/micrometer-metrics/micrometer/blob/127fa3265325cc894f368312ed8890b76a055d88/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/db/DatabaseTableMetrics.java#L84-L86
telly/groundy
library/src/main/java/com/telly/groundy/TaskResult.java
TaskResult.addParcelableArrayList
public TaskResult addParcelableArrayList(String key, ArrayList<? extends Parcelable> value) { mBundle.putParcelableArrayList(key, value); return this; }
java
public TaskResult addParcelableArrayList(String key, ArrayList<? extends Parcelable> value) { mBundle.putParcelableArrayList(key, value); return this; }
[ "public", "TaskResult", "addParcelableArrayList", "(", "String", "key", ",", "ArrayList", "<", "?", "extends", "Parcelable", ">", "value", ")", "{", "mBundle", ".", "putParcelableArrayList", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a List of Parcelable values into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList of Parcelable objects, or null
[ "Inserts", "a", "List", "of", "Parcelable", "values", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/TaskResult.java#L203-L206
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NamespaceDataPersister.java
NamespaceDataPersister.addNamespace
public void addNamespace(String prefix, String uri) throws RepositoryException { if (!started) { if (log.isDebugEnabled()) log.debug("Unable save namespace " + uri + "=" + prefix + " in to the storage. Storage not initialized"); return; } PlainChangesLog changesLog = new PlainChangesLogImpl(); internallAdd(changesLog, prefix, uri); dataManager.save(new TransactionChangesLog(changesLog)); }
java
public void addNamespace(String prefix, String uri) throws RepositoryException { if (!started) { if (log.isDebugEnabled()) log.debug("Unable save namespace " + uri + "=" + prefix + " in to the storage. Storage not initialized"); return; } PlainChangesLog changesLog = new PlainChangesLogImpl(); internallAdd(changesLog, prefix, uri); dataManager.save(new TransactionChangesLog(changesLog)); }
[ "public", "void", "addNamespace", "(", "String", "prefix", ",", "String", "uri", ")", "throws", "RepositoryException", "{", "if", "(", "!", "started", ")", "{", "if", "(", "log", ".", "isDebugEnabled", "(", ")", ")", "log", ".", "debug", "(", "\"Unable save namespace \"", "+", "uri", "+", "\"=\"", "+", "prefix", "+", "\" in to the storage. Storage not initialized\"", ")", ";", "return", ";", "}", "PlainChangesLog", "changesLog", "=", "new", "PlainChangesLogImpl", "(", ")", ";", "internallAdd", "(", "changesLog", ",", "prefix", ",", "uri", ")", ";", "dataManager", ".", "save", "(", "new", "TransactionChangesLog", "(", "changesLog", ")", ")", ";", "}" ]
Add new namespace. @param prefix NS prefix @param uri NS URI @throws RepositoryException Repository error
[ "Add", "new", "namespace", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/NamespaceDataPersister.java#L94-L107
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/util/Sort.java
Sort.mergeSort
private static <T extends Comparable<? super T>> void mergeSort( T[] arr, T[] tmpArr, int left, int right ) { //recursive way if ( left < right ) { int center = ( left + right ) / 2; mergeSort(arr, tmpArr, left, center); mergeSort(arr, tmpArr, center + 1, right); merge(arr, tmpArr, left, center + 1, right); } //loop instead /* int len = 2, pos; int rpos, offset, cut; while ( len <= right ) { pos = 0; offset = len / 2; while ( pos + len <= right ) { rpos = pos + offset; merge( arr, tmpArr, pos, rpos, rpos + offset - 1 ); pos += len; } //merge the rest cut = pos + offset; if ( cut <= right ) merge( arr, tmpArr, pos, cut, right ); len *= 2; } merge( arr, tmpArr, 0, len / 2, right );*/ }
java
private static <T extends Comparable<? super T>> void mergeSort( T[] arr, T[] tmpArr, int left, int right ) { //recursive way if ( left < right ) { int center = ( left + right ) / 2; mergeSort(arr, tmpArr, left, center); mergeSort(arr, tmpArr, center + 1, right); merge(arr, tmpArr, left, center + 1, right); } //loop instead /* int len = 2, pos; int rpos, offset, cut; while ( len <= right ) { pos = 0; offset = len / 2; while ( pos + len <= right ) { rpos = pos + offset; merge( arr, tmpArr, pos, rpos, rpos + offset - 1 ); pos += len; } //merge the rest cut = pos + offset; if ( cut <= right ) merge( arr, tmpArr, pos, cut, right ); len *= 2; } merge( arr, tmpArr, 0, len / 2, right );*/ }
[ "private", "static", "<", "T", "extends", "Comparable", "<", "?", "super", "T", ">", ">", "void", "mergeSort", "(", "T", "[", "]", "arr", ",", "T", "[", "]", "tmpArr", ",", "int", "left", ",", "int", "right", ")", "{", "//recursive way", "if", "(", "left", "<", "right", ")", "{", "int", "center", "=", "(", "left", "+", "right", ")", "/", "2", ";", "mergeSort", "(", "arr", ",", "tmpArr", ",", "left", ",", "center", ")", ";", "mergeSort", "(", "arr", ",", "tmpArr", ",", "center", "+", "1", ",", "right", ")", ";", "merge", "(", "arr", ",", "tmpArr", ",", "left", ",", "center", "+", "1", ",", "right", ")", ";", "}", "//loop instead", "/* int len = 2, pos;\n int rpos, offset, cut;\n while ( len <= right ) {\n pos = 0;\n offset = len / 2;\n while ( pos + len <= right ) {\n rpos = pos + offset;\n merge( arr, tmpArr, pos, rpos, rpos + offset - 1 );\n pos += len;\n }\n \n //merge the rest\n cut = pos + offset;\n if ( cut <= right ) \n merge( arr, tmpArr, pos, cut, right );\n \n len *= 2;\n }\n merge( arr, tmpArr, 0, len / 2, right );*/", "}" ]
internal method to make a recursive call @param arr an array of Comparable items @param tmpArr temp array to placed the merged result @param left left-most index of the subarray @param right right-most index of the subarray
[ "internal", "method", "to", "make", "a", "recursive", "call" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/Sort.java#L111-L142
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/Config.java
Config.setSetConfigs
public Config setSetConfigs(Map<String, SetConfig> setConfigs) { this.setConfigs.clear(); this.setConfigs.putAll(setConfigs); for (Entry<String, SetConfig> entry : setConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
java
public Config setSetConfigs(Map<String, SetConfig> setConfigs) { this.setConfigs.clear(); this.setConfigs.putAll(setConfigs); for (Entry<String, SetConfig> entry : setConfigs.entrySet()) { entry.getValue().setName(entry.getKey()); } return this; }
[ "public", "Config", "setSetConfigs", "(", "Map", "<", "String", ",", "SetConfig", ">", "setConfigs", ")", "{", "this", ".", "setConfigs", ".", "clear", "(", ")", ";", "this", ".", "setConfigs", ".", "putAll", "(", "setConfigs", ")", ";", "for", "(", "Entry", "<", "String", ",", "SetConfig", ">", "entry", ":", "setConfigs", ".", "entrySet", "(", ")", ")", "{", "entry", ".", "getValue", "(", ")", ".", "setName", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "return", "this", ";", "}" ]
Sets the map of {@link com.hazelcast.core.ISet} configurations, mapped by config name. The config name may be a pattern with which the configuration will be obtained in the future. @param setConfigs the set configuration map to set @return this config instance
[ "Sets", "the", "map", "of", "{", "@link", "com", ".", "hazelcast", ".", "core", ".", "ISet", "}", "configurations", "mapped", "by", "config", "name", ".", "The", "config", "name", "may", "be", "a", "pattern", "with", "which", "the", "configuration", "will", "be", "obtained", "in", "the", "future", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/Config.java#L1000-L1007
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/OptionsApi.java
OptionsApi.optionsPutAsync
public com.squareup.okhttp.Call optionsPutAsync(OptionsPut body, final ApiCallback<OptionsPutResponseStatusSuccess> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = optionsPutValidateBeforeCall(body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<OptionsPutResponseStatusSuccess>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
java
public com.squareup.okhttp.Call optionsPutAsync(OptionsPut body, final ApiCallback<OptionsPutResponseStatusSuccess> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = optionsPutValidateBeforeCall(body, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<OptionsPutResponseStatusSuccess>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "optionsPutAsync", "(", "OptionsPut", "body", ",", "final", "ApiCallback", "<", "OptionsPutResponseStatusSuccess", ">", "callback", ")", "throws", "ApiException", "{", "ProgressResponseBody", ".", "ProgressListener", "progressListener", "=", "null", ";", "ProgressRequestBody", ".", "ProgressRequestListener", "progressRequestListener", "=", "null", ";", "if", "(", "callback", "!=", "null", ")", "{", "progressListener", "=", "new", "ProgressResponseBody", ".", "ProgressListener", "(", ")", "{", "@", "Override", "public", "void", "update", "(", "long", "bytesRead", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onDownloadProgress", "(", "bytesRead", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "progressRequestListener", "=", "new", "ProgressRequestBody", ".", "ProgressRequestListener", "(", ")", "{", "@", "Override", "public", "void", "onRequestProgress", "(", "long", "bytesWritten", ",", "long", "contentLength", ",", "boolean", "done", ")", "{", "callback", ".", "onUploadProgress", "(", "bytesWritten", ",", "contentLength", ",", "done", ")", ";", "}", "}", ";", "}", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "optionsPutValidateBeforeCall", "(", "body", ",", "progressListener", ",", "progressRequestListener", ")", ";", "Type", "localVarReturnType", "=", "new", "TypeToken", "<", "OptionsPutResponseStatusSuccess", ">", "(", ")", "{", "}", ".", "getType", "(", ")", ";", "apiClient", ".", "executeAsync", "(", "call", ",", "localVarReturnType", ",", "callback", ")", ";", "return", "call", ";", "}" ]
Add/Change/Delete options. (asynchronously) The PUT operation will add, change or delete values in CloudCluster/Options. @param body Body Data (required) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "Add", "/", "Change", "/", "Delete", "options", ".", "(", "asynchronously", ")", "The", "PUT", "operation", "will", "add", "change", "or", "delete", "values", "in", "CloudCluster", "/", "Options", "." ]
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/OptionsApi.java#L407-L432
JoeKerouac/utils
src/main/java/com/joe/utils/poi/ExcelExecutor.java
ExcelExecutor.writeToExcel
public Workbook writeToExcel(List<? extends Object> datas, boolean hasTitle, Workbook workbook) { return writeToExcel(datas, hasTitle, workbook, false); }
java
public Workbook writeToExcel(List<? extends Object> datas, boolean hasTitle, Workbook workbook) { return writeToExcel(datas, hasTitle, workbook, false); }
[ "public", "Workbook", "writeToExcel", "(", "List", "<", "?", "extends", "Object", ">", "datas", ",", "boolean", "hasTitle", ",", "Workbook", "workbook", ")", "{", "return", "writeToExcel", "(", "datas", ",", "hasTitle", ",", "workbook", ",", "false", ")", ";", "}" ]
将pojo集合写入excel @param datas pojo集合,空元素将被忽略 @param hasTitle 是否需要title @param workbook 工作簿 @return 写入后的工作簿
[ "将pojo集合写入excel" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/poi/ExcelExecutor.java#L262-L265