repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java
SparkComputationGraph.evaluateROCMultiClass
public <T extends ROCMultiClass> T evaluateROCMultiClass(JavaRDD<DataSet> data, int thresholdSteps, int evaluationMinibatchSize) { return (T)doEvaluation(data, new org.deeplearning4j.eval.ROCMultiClass(thresholdSteps), evaluationMinibatchSize); }
java
public <T extends ROCMultiClass> T evaluateROCMultiClass(JavaRDD<DataSet> data, int thresholdSteps, int evaluationMinibatchSize) { return (T)doEvaluation(data, new org.deeplearning4j.eval.ROCMultiClass(thresholdSteps), evaluationMinibatchSize); }
[ "public", "<", "T", "extends", "ROCMultiClass", ">", "T", "evaluateROCMultiClass", "(", "JavaRDD", "<", "DataSet", ">", "data", ",", "int", "thresholdSteps", ",", "int", "evaluationMinibatchSize", ")", "{", "return", "(", "T", ")", "doEvaluation", "(", "data",...
Perform ROC analysis/evaluation (for the multi-class case, using {@link ROCMultiClass} on the given DataSet in a distributed manner @param data Test set data (to evaluate on) @param thresholdSteps Number of threshold steps for ROC - see {@link ROC} @param evaluationMinibatchSize Minibatch size to use when performing ROC evaluation @return ROCMultiClass for the entire data set
[ "Perform", "ROC", "analysis", "/", "evaluation", "(", "for", "the", "multi", "-", "class", "case", "using", "{", "@link", "ROCMultiClass", "}", "on", "the", "given", "DataSet", "in", "a", "distributed", "manner" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-scaleout/spark/dl4j-spark/src/main/java/org/deeplearning4j/spark/impl/graph/SparkComputationGraph.java#L697-L699
apereo/cas
support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/DelegatedClientNavigationController.java
DelegatedClientNavigationController.getResultingView
@SneakyThrows protected View getResultingView(final IndirectClient<Credentials, CommonProfile> client, final J2EContext webContext, final Ticket ticket) { val action = client.getRedirectAction(webContext); if (RedirectAction.RedirectType.SUCCESS.equals(action.getType())) { return new DynamicHtmlView(action.getContent()); } val builder = new URIBuilder(action.getLocation()); val url = builder.toString(); LOGGER.debug("Redirecting client [{}] to [{}] based on identifier [{}]", client.getName(), url, ticket.getId()); return new RedirectView(url); }
java
@SneakyThrows protected View getResultingView(final IndirectClient<Credentials, CommonProfile> client, final J2EContext webContext, final Ticket ticket) { val action = client.getRedirectAction(webContext); if (RedirectAction.RedirectType.SUCCESS.equals(action.getType())) { return new DynamicHtmlView(action.getContent()); } val builder = new URIBuilder(action.getLocation()); val url = builder.toString(); LOGGER.debug("Redirecting client [{}] to [{}] based on identifier [{}]", client.getName(), url, ticket.getId()); return new RedirectView(url); }
[ "@", "SneakyThrows", "protected", "View", "getResultingView", "(", "final", "IndirectClient", "<", "Credentials", ",", "CommonProfile", ">", "client", ",", "final", "J2EContext", "webContext", ",", "final", "Ticket", "ticket", ")", "{", "val", "action", "=", "cl...
Gets resulting view. @param client the client @param webContext the web context @param ticket the ticket @return the resulting view
[ "Gets", "resulting", "view", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pac4j-webflow/src/main/java/org/apereo/cas/web/DelegatedClientNavigationController.java#L144-L154
JadiraOrg/jadira
bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java
BasicBinder.findUnmarshaller
public <S, T> FromUnmarshaller<S, T> findUnmarshaller(Class<S> source, Class<T> target, Class<? extends Annotation> qualifier) { return findUnmarshaller(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier)); }
java
public <S, T> FromUnmarshaller<S, T> findUnmarshaller(Class<S> source, Class<T> target, Class<? extends Annotation> qualifier) { return findUnmarshaller(new ConverterKey<S,T>(source, target, qualifier == null ? DefaultBinding.class : qualifier)); }
[ "public", "<", "S", ",", "T", ">", "FromUnmarshaller", "<", "S", ",", "T", ">", "findUnmarshaller", "(", "Class", "<", "S", ">", "source", ",", "Class", "<", "T", ">", "target", ",", "Class", "<", "?", "extends", "Annotation", ">", "qualifier", ")", ...
Resolve an UnMarshaller with the given source and target class. The unmarshaller is used as follows: Instances of the source can be marshalled into the target class. @param source The source (input) class @param target The target (output) class @param qualifier The qualifier for which the unmarshaller must be registered
[ "Resolve", "an", "UnMarshaller", "with", "the", "given", "source", "and", "target", "class", ".", "The", "unmarshaller", "is", "used", "as", "follows", ":", "Instances", "of", "the", "source", "can", "be", "marshalled", "into", "the", "target", "class", "." ...
train
https://github.com/JadiraOrg/jadira/blob/d55d0238395f0cb900531f1f08b4b2d87fa9a4f6/bindings/src/main/java/org/jadira/bindings/core/binder/BasicBinder.java#L1017-L1019
CodeNarc/CodeNarc
src/main/java/org/codenarc/util/AstUtil.java
AstUtil.respondsTo
public static boolean respondsTo(Object object, String methodName) { MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object); if (!metaClass.respondsTo(object, methodName).isEmpty()) { return true; } Map properties = DefaultGroovyMethods.getProperties(object); return properties.containsKey(methodName); }
java
public static boolean respondsTo(Object object, String methodName) { MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object); if (!metaClass.respondsTo(object, methodName).isEmpty()) { return true; } Map properties = DefaultGroovyMethods.getProperties(object); return properties.containsKey(methodName); }
[ "public", "static", "boolean", "respondsTo", "(", "Object", "object", ",", "String", "methodName", ")", "{", "MetaClass", "metaClass", "=", "DefaultGroovyMethods", ".", "getMetaClass", "(", "object", ")", ";", "if", "(", "!", "metaClass", ".", "respondsTo", "(...
Return true only if the specified object responds to the named method @param object - the object to check @param methodName - the name of the method @return true if the object responds to the named method
[ "Return", "true", "only", "if", "the", "specified", "object", "responds", "to", "the", "named", "method" ]
train
https://github.com/CodeNarc/CodeNarc/blob/9a7cec02cb8cbaf845030f2434309e8968f5d7a7/src/main/java/org/codenarc/util/AstUtil.java#L638-L645
voldemort/voldemort
src/java/voldemort/tools/admin/AdminToolUtils.java
AdminToolUtils.assertServerNotInRebalancingState
public static void assertServerNotInRebalancingState(AdminClient adminClient, Integer nodeId) { assertServerNotInRebalancingState(adminClient, Lists.newArrayList(new Integer[]{nodeId})); }
java
public static void assertServerNotInRebalancingState(AdminClient adminClient, Integer nodeId) { assertServerNotInRebalancingState(adminClient, Lists.newArrayList(new Integer[]{nodeId})); }
[ "public", "static", "void", "assertServerNotInRebalancingState", "(", "AdminClient", "adminClient", ",", "Integer", "nodeId", ")", "{", "assertServerNotInRebalancingState", "(", "adminClient", ",", "Lists", ".", "newArrayList", "(", "new", "Integer", "[", "]", "{", ...
Utility function that checks the execution state of the server by checking the state of {@link VoldemortState} <br> This function checks if the nodes are not in rebalancing state ( {@link VoldemortState#REBALANCING_MASTER_SERVER}). @param adminClient An instance of AdminClient points to given cluster @param nodeId Node id to be checked @throws VoldemortException if any node is in rebalancing state
[ "Utility", "function", "that", "checks", "the", "execution", "state", "of", "the", "server", "by", "checking", "the", "state", "of", "{", "@link", "VoldemortState", "}", "<br", ">" ]
train
https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/tools/admin/AdminToolUtils.java#L416-L418
ThreeTen/threetenbp
src/main/java/org/threeten/bp/LocalDateTime.java
LocalDateTime.plusWithOverflow
private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, long nanos, int sign) { // 9223372036854775808 long, 2147483648 int if ((hours | minutes | seconds | nanos) == 0) { return with(newDate, time); } long totDays = nanos / NANOS_PER_DAY + // max/24*60*60*1B seconds / SECONDS_PER_DAY + // max/24*60*60 minutes / MINUTES_PER_DAY + // max/24*60 hours / HOURS_PER_DAY; // max/24 totDays *= sign; // total max*0.4237... long totNanos = nanos % NANOS_PER_DAY + // max 86400000000000 (seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND + // max 86400000000000 (minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE + // max 86400000000000 (hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 86400000000000 long curNoD = time.toNanoOfDay(); // max 86400000000000 totNanos = totNanos * sign + curNoD; // total 432000000000000 totDays += Jdk8Methods.floorDiv(totNanos, NANOS_PER_DAY); long newNoD = Jdk8Methods.floorMod(totNanos, NANOS_PER_DAY); LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD)); return with(newDate.plusDays(totDays), newTime); }
java
private LocalDateTime plusWithOverflow(LocalDate newDate, long hours, long minutes, long seconds, long nanos, int sign) { // 9223372036854775808 long, 2147483648 int if ((hours | minutes | seconds | nanos) == 0) { return with(newDate, time); } long totDays = nanos / NANOS_PER_DAY + // max/24*60*60*1B seconds / SECONDS_PER_DAY + // max/24*60*60 minutes / MINUTES_PER_DAY + // max/24*60 hours / HOURS_PER_DAY; // max/24 totDays *= sign; // total max*0.4237... long totNanos = nanos % NANOS_PER_DAY + // max 86400000000000 (seconds % SECONDS_PER_DAY) * NANOS_PER_SECOND + // max 86400000000000 (minutes % MINUTES_PER_DAY) * NANOS_PER_MINUTE + // max 86400000000000 (hours % HOURS_PER_DAY) * NANOS_PER_HOUR; // max 86400000000000 long curNoD = time.toNanoOfDay(); // max 86400000000000 totNanos = totNanos * sign + curNoD; // total 432000000000000 totDays += Jdk8Methods.floorDiv(totNanos, NANOS_PER_DAY); long newNoD = Jdk8Methods.floorMod(totNanos, NANOS_PER_DAY); LocalTime newTime = (newNoD == curNoD ? time : LocalTime.ofNanoOfDay(newNoD)); return with(newDate.plusDays(totDays), newTime); }
[ "private", "LocalDateTime", "plusWithOverflow", "(", "LocalDate", "newDate", ",", "long", "hours", ",", "long", "minutes", ",", "long", "seconds", ",", "long", "nanos", ",", "int", "sign", ")", "{", "// 9223372036854775808 long, 2147483648 int", "if", "(", "(", ...
Returns a copy of this {@code LocalDateTime} with the specified period added. <p> This instance is immutable and unaffected by this method call. @param newDate the new date to base the calculation on, not null @param hours the hours to add, may be negative @param minutes the minutes to add, may be negative @param seconds the seconds to add, may be negative @param nanos the nanos to add, may be negative @param sign the sign to determine add or subtract @return the combined result, not null
[ "Returns", "a", "copy", "of", "this", "{", "@code", "LocalDateTime", "}", "with", "the", "specified", "period", "added", ".", "<p", ">", "This", "instance", "is", "immutable", "and", "unaffected", "by", "this", "method", "call", "." ]
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/LocalDateTime.java#L1392-L1412
forge/javaee-descriptors
impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/connector16/ConnectorDescriptorImpl.java
ConnectorDescriptorImpl.addNamespace
public ConnectorDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
java
public ConnectorDescriptor addNamespace(String name, String value) { model.attribute(name, value); return this; }
[ "public", "ConnectorDescriptor", "addNamespace", "(", "String", "name", ",", "String", "value", ")", "{", "model", ".", "attribute", "(", "name", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds a new namespace @return the current instance of <code>ConnectorDescriptor</code>
[ "Adds", "a", "new", "namespace" ]
train
https://github.com/forge/javaee-descriptors/blob/cb914330a1a0b04bfc1d0f199bd9cde3bbf0b3ed/impl/src/main/java/org/jboss/shrinkwrap/descriptor/impl/connector16/ConnectorDescriptorImpl.java#L87-L91
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/gradientcheck/GradientCheckUtil.java
GradientCheckUtil.checkGradients
public static boolean checkGradients(MultiLayerNetwork mln, double epsilon, double maxRelError, double minAbsoluteError, boolean print, boolean exitOnFirstError, INDArray input, INDArray labels) { return checkGradients(mln, epsilon, maxRelError, minAbsoluteError, print, exitOnFirstError, input, labels, null, null); }
java
public static boolean checkGradients(MultiLayerNetwork mln, double epsilon, double maxRelError, double minAbsoluteError, boolean print, boolean exitOnFirstError, INDArray input, INDArray labels) { return checkGradients(mln, epsilon, maxRelError, minAbsoluteError, print, exitOnFirstError, input, labels, null, null); }
[ "public", "static", "boolean", "checkGradients", "(", "MultiLayerNetwork", "mln", ",", "double", "epsilon", ",", "double", "maxRelError", ",", "double", "minAbsoluteError", ",", "boolean", "print", ",", "boolean", "exitOnFirstError", ",", "INDArray", "input", ",", ...
Check backprop gradients for a MultiLayerNetwork. @param mln MultiLayerNetwork to test. This must be initialized. @param epsilon Usually on the order/ of 1e-4 or so. @param maxRelError Maximum relative error. Usually < 1e-5 or so, though maybe more for deep networks or those with nonlinear activation @param minAbsoluteError Minimum absolute error to cause a failure. Numerical gradients can be non-zero due to precision issues. For example, 0.0 vs. 1e-18: relative error is 1.0, but not really a failure @param print Whether to print full pass/failure details for each parameter gradient @param exitOnFirstError If true: return upon first failure. If false: continue checking even if one parameter gradient has failed. Typically use false for debugging, true for unit tests. @param input Input array to use for forward pass. May be mini-batch data. @param labels Labels/targets to use to calculate backprop gradient. May be mini-batch data. @return true if gradients are passed, false otherwise.
[ "Check", "backprop", "gradients", "for", "a", "MultiLayerNetwork", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/gradientcheck/GradientCheckUtil.java#L129-L132
phax/ph-oton
ph-oton-exchange/src/main/java/com/helger/photon/exchange/bulkexport/format/ExporterCSV.java
ExporterCSV.createCSVWriter
@SuppressWarnings ("resource") @Nonnull @OverrideOnDemand @WillCloseWhenClosed protected CSVWriter createCSVWriter (@Nonnull final OutputStream aOS) { return new CSVWriter (new OutputStreamWriter (aOS, m_aCharset)).setSeparatorChar (m_cSeparatorChar) .setQuoteChar (m_cQuoteChar) .setEscapeChar (m_cEscapeChar) .setLineEnd (m_sLineEnd) .setAvoidFinalLineEnd (m_bAvoidFinalLineEnd); }
java
@SuppressWarnings ("resource") @Nonnull @OverrideOnDemand @WillCloseWhenClosed protected CSVWriter createCSVWriter (@Nonnull final OutputStream aOS) { return new CSVWriter (new OutputStreamWriter (aOS, m_aCharset)).setSeparatorChar (m_cSeparatorChar) .setQuoteChar (m_cQuoteChar) .setEscapeChar (m_cEscapeChar) .setLineEnd (m_sLineEnd) .setAvoidFinalLineEnd (m_bAvoidFinalLineEnd); }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "@", "Nonnull", "@", "OverrideOnDemand", "@", "WillCloseWhenClosed", "protected", "CSVWriter", "createCSVWriter", "(", "@", "Nonnull", "final", "OutputStream", "aOS", ")", "{", "return", "new", "CSVWriter", "(", "...
Create a new CSV writer. @param aOS The output stream to write to. May not be <code>null</code>. @return The {@link CSVWriter} to used. Never <code>null</code>.
[ "Create", "a", "new", "CSV", "writer", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-exchange/src/main/java/com/helger/photon/exchange/bulkexport/format/ExporterCSV.java#L239-L250
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.setRotationXYZ
public Matrix4f setRotationXYZ(float angleX, float angleY, float angleZ) { float sinX = (float) Math.sin(angleX); float cosX = (float) Math.cosFromSin(sinX, angleX); float sinY = (float) Math.sin(angleY); float cosY = (float) Math.cosFromSin(sinY, angleY); float sinZ = (float) Math.sin(angleZ); float cosZ = (float) Math.cosFromSin(sinZ, angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; this._m20(sinY); this._m21(nm21 * cosY); this._m22(nm22 * cosY); // rotateZ this._m00(nm00 * cosZ); this._m01(nm01 * cosZ + nm11 * sinZ); this._m02(nm02 * cosZ + nm12 * sinZ); this._m10(nm00 * m_sinZ); this._m11(nm01 * m_sinZ + nm11 * cosZ); this._m12(nm02 * m_sinZ + nm12 * cosZ); properties = properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return this; }
java
public Matrix4f setRotationXYZ(float angleX, float angleY, float angleZ) { float sinX = (float) Math.sin(angleX); float cosX = (float) Math.cosFromSin(sinX, angleX); float sinY = (float) Math.sin(angleY); float cosY = (float) Math.cosFromSin(sinY, angleY); float sinZ = (float) Math.sin(angleZ); float cosZ = (float) Math.cosFromSin(sinZ, angleZ); float m_sinX = -sinX; float m_sinY = -sinY; float m_sinZ = -sinZ; // rotateX float nm11 = cosX; float nm12 = sinX; float nm21 = m_sinX; float nm22 = cosX; // rotateY float nm00 = cosY; float nm01 = nm21 * m_sinY; float nm02 = nm22 * m_sinY; this._m20(sinY); this._m21(nm21 * cosY); this._m22(nm22 * cosY); // rotateZ this._m00(nm00 * cosZ); this._m01(nm01 * cosZ + nm11 * sinZ); this._m02(nm02 * cosZ + nm12 * sinZ); this._m10(nm00 * m_sinZ); this._m11(nm01 * m_sinZ + nm11 * cosZ); this._m12(nm02 * m_sinZ + nm12 * cosZ); properties = properties & ~(PROPERTY_PERSPECTIVE | PROPERTY_IDENTITY | PROPERTY_TRANSLATION); return this; }
[ "public", "Matrix4f", "setRotationXYZ", "(", "float", "angleX", ",", "float", "angleY", ",", "float", "angleZ", ")", "{", "float", "sinX", "=", "(", "float", ")", "Math", ".", "sin", "(", "angleX", ")", ";", "float", "cosX", "=", "(", "float", ")", "...
Set only the upper left 3x3 submatrix of this matrix to a rotation of <code>angleX</code> radians about the X axis, followed by a rotation of <code>angleY</code> radians about the Y axis and followed by a rotation of <code>angleZ</code> radians about the Z axis. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. @param angleX the angle to rotate about X @param angleY the angle to rotate about Y @param angleZ the angle to rotate about Z @return this
[ "Set", "only", "the", "upper", "left", "3x3", "submatrix", "of", "this", "matrix", "to", "a", "rotation", "of", "<code", ">", "angleX<", "/", "code", ">", "radians", "about", "the", "X", "axis", "followed", "by", "a", "rotation", "of", "<code", ">", "a...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L3782-L3814
hibernate/hibernate-ogm
mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java
MongoDBDialect.objectForInsert
private static Document objectForInsert(Tuple tuple, Document dbObject) { MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot(); for ( TupleOperation operation : tuple.getOperations() ) { String column = operation.getColumn(); if ( notInIdField( snapshot, column ) ) { switch ( operation.getType() ) { case PUT: MongoHelpers.setValue( dbObject, column, operation.getValue() ); break; case PUT_NULL: case REMOVE: MongoHelpers.resetValue( dbObject, column ); break; } } } return dbObject; }
java
private static Document objectForInsert(Tuple tuple, Document dbObject) { MongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot(); for ( TupleOperation operation : tuple.getOperations() ) { String column = operation.getColumn(); if ( notInIdField( snapshot, column ) ) { switch ( operation.getType() ) { case PUT: MongoHelpers.setValue( dbObject, column, operation.getValue() ); break; case PUT_NULL: case REMOVE: MongoHelpers.resetValue( dbObject, column ); break; } } } return dbObject; }
[ "private", "static", "Document", "objectForInsert", "(", "Tuple", "tuple", ",", "Document", "dbObject", ")", "{", "MongoDBTupleSnapshot", "snapshot", "=", "(", "MongoDBTupleSnapshot", ")", "tuple", ".", "getSnapshot", "(", ")", ";", "for", "(", "TupleOperation", ...
Creates a Document that can be passed to the MongoDB batch insert function
[ "Creates", "a", "Document", "that", "can", "be", "passed", "to", "the", "MongoDB", "batch", "insert", "function" ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/mongodb/src/main/java/org/hibernate/ogm/datastore/mongodb/MongoDBDialect.java#L554-L571
Karumi/HeaderRecyclerView
library/src/main/java/com/karumi/headerrecyclerview/HeaderRecyclerViewAdapter.java
HeaderRecyclerViewAdapter.onBindViewHolder
@Override public final void onBindViewHolder(VH holder, int position) { if (isHeaderPosition(position)) { onBindHeaderViewHolder(holder, position); } else if (isFooterPosition(position)) { onBindFooterViewHolder(holder, position); } else { onBindItemViewHolder(holder, position); } }
java
@Override public final void onBindViewHolder(VH holder, int position) { if (isHeaderPosition(position)) { onBindHeaderViewHolder(holder, position); } else if (isFooterPosition(position)) { onBindFooterViewHolder(holder, position); } else { onBindItemViewHolder(holder, position); } }
[ "@", "Override", "public", "final", "void", "onBindViewHolder", "(", "VH", "holder", ",", "int", "position", ")", "{", "if", "(", "isHeaderPosition", "(", "position", ")", ")", "{", "onBindHeaderViewHolder", "(", "holder", ",", "position", ")", ";", "}", "...
Invokes onBindHeaderViewHolder, onBindItemViewHolder or onBindFooterViewHOlder methods based on the position param.
[ "Invokes", "onBindHeaderViewHolder", "onBindItemViewHolder", "or", "onBindFooterViewHOlder", "methods", "based", "on", "the", "position", "param", "." ]
train
https://github.com/Karumi/HeaderRecyclerView/blob/c018472a1b15de661d8aec153bd5f555ef1e9a37/library/src/main/java/com/karumi/headerrecyclerview/HeaderRecyclerViewAdapter.java#L81-L89
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java
ComputeNodeOperations.addComputeNodeUser
public void addComputeNodeUser(String poolId, String nodeId, ComputeNodeUser user, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { ComputeNodeAddUserOptions options = new ComputeNodeAddUserOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().computeNodes().addUser(poolId, nodeId, user, options); }
java
public void addComputeNodeUser(String poolId, String nodeId, ComputeNodeUser user, Iterable<BatchClientBehavior> additionalBehaviors) throws BatchErrorException, IOException { ComputeNodeAddUserOptions options = new ComputeNodeAddUserOptions(); BehaviorManager bhMgr = new BehaviorManager(this.customBehaviors(), additionalBehaviors); bhMgr.applyRequestBehaviors(options); this.parentBatchClient.protocolLayer().computeNodes().addUser(poolId, nodeId, user, options); }
[ "public", "void", "addComputeNodeUser", "(", "String", "poolId", ",", "String", "nodeId", ",", "ComputeNodeUser", "user", ",", "Iterable", "<", "BatchClientBehavior", ">", "additionalBehaviors", ")", "throws", "BatchErrorException", ",", "IOException", "{", "ComputeNo...
Adds a user account to the specified compute node. @param poolId The ID of the pool that contains the compute node. @param nodeId The ID of the compute node where the user account will be created. @param user The user account to be created. @param additionalBehaviors A collection of {@link BatchClientBehavior} instances that are applied to the Batch service request. @throws BatchErrorException Exception thrown when an error response is received from the Batch service. @throws IOException Exception thrown when there is an error in serialization/deserialization of data sent to/received from the Batch service.
[ "Adds", "a", "user", "account", "to", "the", "specified", "compute", "node", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/ComputeNodeOperations.java#L96-L102
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/DevicesManagementApi.java
DevicesManagementApi.updateTaskForDevice
public DeviceTaskUpdateResponse updateTaskForDevice(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { ApiResponse<DeviceTaskUpdateResponse> resp = updateTaskForDeviceWithHttpInfo(tid, did, deviceTaskUpdateRequest); return resp.getData(); }
java
public DeviceTaskUpdateResponse updateTaskForDevice(String tid, String did, DeviceTaskUpdateRequest deviceTaskUpdateRequest) throws ApiException { ApiResponse<DeviceTaskUpdateResponse> resp = updateTaskForDeviceWithHttpInfo(tid, did, deviceTaskUpdateRequest); return resp.getData(); }
[ "public", "DeviceTaskUpdateResponse", "updateTaskForDevice", "(", "String", "tid", ",", "String", "did", ",", "DeviceTaskUpdateRequest", "deviceTaskUpdateRequest", ")", "throws", "ApiException", "{", "ApiResponse", "<", "DeviceTaskUpdateResponse", ">", "resp", "=", "updat...
Updates a task for a specific device - For now just allows changing the state to cancelled. Updates a task for a specific device - For now just allows changing the state to cancelled. @param tid Task ID. (required) @param did Device ID. (required) @param deviceTaskUpdateRequest Device task update request (required) @return DeviceTaskUpdateResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Updates", "a", "task", "for", "a", "specific", "device", "-", "For", "now", "just", "allows", "changing", "the", "state", "to", "cancelled", ".", "Updates", "a", "task", "for", "a", "specific", "device", "-", "For", "now", "just", "allows", "changing", ...
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/DevicesManagementApi.java#L1942-L1945
dropbox/dropbox-sdk-java
src/main/java/com/dropbox/core/v1/DbxClientV1.java
DbxClientV1.getDeltaCWithPathPrefix
public <C> DbxDeltaC<C> getDeltaCWithPathPrefix(Collector<DbxDeltaC.Entry<DbxEntry>, C> collector, /*@Nullable*/String cursor, String pathPrefix) throws DbxException { return getDeltaCWithPathPrefix(collector, cursor, pathPrefix, false); }
java
public <C> DbxDeltaC<C> getDeltaCWithPathPrefix(Collector<DbxDeltaC.Entry<DbxEntry>, C> collector, /*@Nullable*/String cursor, String pathPrefix) throws DbxException { return getDeltaCWithPathPrefix(collector, cursor, pathPrefix, false); }
[ "public", "<", "C", ">", "DbxDeltaC", "<", "C", ">", "getDeltaCWithPathPrefix", "(", "Collector", "<", "DbxDeltaC", ".", "Entry", "<", "DbxEntry", ">", ",", "C", ">", "collector", ",", "/*@Nullable*/", "String", "cursor", ",", "String", "pathPrefix", ")", ...
Same as {@link #getDeltaCWithPathPrefix(Collector, String, String, boolean)} with {@code includeMediaInfo} set to {@code false}.
[ "Same", "as", "{" ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L1563-L1568
alkacon/opencms-core
src/org/opencms/ui/apps/user/CmsUserEditDialog.java
CmsUserEditDialog.setUserPasswordStatus
private void setUserPasswordStatus(CmsUser user, boolean reset) { if (reset) { user.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET, "true"); } else { user.deleteAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET); } CmsUserTable.USER_PASSWORD_STATUS.put(user.getId(), new Boolean(reset)); }
java
private void setUserPasswordStatus(CmsUser user, boolean reset) { if (reset) { user.setAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET, "true"); } else { user.deleteAdditionalInfo(CmsUserSettings.ADDITIONAL_INFO_PASSWORD_RESET); } CmsUserTable.USER_PASSWORD_STATUS.put(user.getId(), new Boolean(reset)); }
[ "private", "void", "setUserPasswordStatus", "(", "CmsUser", "user", ",", "boolean", "reset", ")", "{", "if", "(", "reset", ")", "{", "user", ".", "setAdditionalInfo", "(", "CmsUserSettings", ".", "ADDITIONAL_INFO_PASSWORD_RESET", ",", "\"true\"", ")", ";", "}", ...
Sets the password status for the user.<p> @param user CmsUser @param reset true or false
[ "Sets", "the", "password", "status", "for", "the", "user", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/user/CmsUserEditDialog.java#L1406-L1414
google/closure-compiler
src/com/google/javascript/jscomp/PolymerPassStaticUtils.java
PolymerPassStaticUtils.getTypeFromProperty
static JSTypeExpression getTypeFromProperty( MemberDefinition property, AbstractCompiler compiler) { if (property.info != null && property.info.hasType()) { return property.info.getType(); } String typeString; if (property.value.isObjectLit()) { Node typeValue = NodeUtil.getFirstPropMatchingKey(property.value, "type"); if (typeValue == null || !typeValue.isName()) { compiler.report(JSError.make(property.name, PolymerPassErrors.POLYMER_INVALID_PROPERTY)); return null; } typeString = typeValue.getString(); } else if (property.value.isName()) { typeString = property.value.getString(); } else { typeString = ""; } Node typeNode; switch (typeString) { case "Boolean": case "String": case "Number": typeNode = IR.string(typeString.toLowerCase()); break; case "Array": case "Function": case "Object": case "Date": typeNode = new Node(Token.BANG, IR.string(typeString)); break; default: compiler.report(JSError.make(property.name, PolymerPassErrors.POLYMER_INVALID_PROPERTY)); return null; } return new JSTypeExpression(typeNode, VIRTUAL_FILE); }
java
static JSTypeExpression getTypeFromProperty( MemberDefinition property, AbstractCompiler compiler) { if (property.info != null && property.info.hasType()) { return property.info.getType(); } String typeString; if (property.value.isObjectLit()) { Node typeValue = NodeUtil.getFirstPropMatchingKey(property.value, "type"); if (typeValue == null || !typeValue.isName()) { compiler.report(JSError.make(property.name, PolymerPassErrors.POLYMER_INVALID_PROPERTY)); return null; } typeString = typeValue.getString(); } else if (property.value.isName()) { typeString = property.value.getString(); } else { typeString = ""; } Node typeNode; switch (typeString) { case "Boolean": case "String": case "Number": typeNode = IR.string(typeString.toLowerCase()); break; case "Array": case "Function": case "Object": case "Date": typeNode = new Node(Token.BANG, IR.string(typeString)); break; default: compiler.report(JSError.make(property.name, PolymerPassErrors.POLYMER_INVALID_PROPERTY)); return null; } return new JSTypeExpression(typeNode, VIRTUAL_FILE); }
[ "static", "JSTypeExpression", "getTypeFromProperty", "(", "MemberDefinition", "property", ",", "AbstractCompiler", "compiler", ")", "{", "if", "(", "property", ".", "info", "!=", "null", "&&", "property", ".", "info", ".", "hasType", "(", ")", ")", "{", "retur...
Gets the JSTypeExpression for a given property using its "type" key. @see https://github.com/Polymer/polymer/blob/0.8-preview/PRIMER.md#configuring-properties
[ "Gets", "the", "JSTypeExpression", "for", "a", "given", "property", "using", "its", "type", "key", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/PolymerPassStaticUtils.java#L207-L246
alkacon/opencms-core
src-modules/org/opencms/workplace/CmsWidgetDialog.java
CmsWidgetDialog.actionToggleElement
public void actionToggleElement() { // get the necessary parameters to add/remove the element int index = 0; try { index = Integer.parseInt(getParamElementIndex()); } catch (Exception e) { // ignore, should not happen } String name = getParamElementName(); // get the base parameter definition CmsWidgetDialogParameter base = getParameterDefinition(name); if (base != null) { // the requested parameter is valid for this dialog List<CmsWidgetDialogParameter> params = getParameters().get(name); if (getAction() == ACTION_ELEMENT_REMOVE) { // remove the value params.remove(index); } else { List<CmsWidgetDialogParameter> sequence = getParameters().get(base.getName()); if (sequence.size() > 0) { // add the new value after the clicked element index = index + 1; } CmsWidgetDialogParameter newParam = new CmsWidgetDialogParameter(base, index); params.add(index, newParam); } // reset all index value in the parameter list for (int i = 0; i < params.size(); i++) { CmsWidgetDialogParameter param = params.get(i); param.setindex(i); } } }
java
public void actionToggleElement() { // get the necessary parameters to add/remove the element int index = 0; try { index = Integer.parseInt(getParamElementIndex()); } catch (Exception e) { // ignore, should not happen } String name = getParamElementName(); // get the base parameter definition CmsWidgetDialogParameter base = getParameterDefinition(name); if (base != null) { // the requested parameter is valid for this dialog List<CmsWidgetDialogParameter> params = getParameters().get(name); if (getAction() == ACTION_ELEMENT_REMOVE) { // remove the value params.remove(index); } else { List<CmsWidgetDialogParameter> sequence = getParameters().get(base.getName()); if (sequence.size() > 0) { // add the new value after the clicked element index = index + 1; } CmsWidgetDialogParameter newParam = new CmsWidgetDialogParameter(base, index); params.add(index, newParam); } // reset all index value in the parameter list for (int i = 0; i < params.size(); i++) { CmsWidgetDialogParameter param = params.get(i); param.setindex(i); } } }
[ "public", "void", "actionToggleElement", "(", ")", "{", "// get the necessary parameters to add/remove the element", "int", "index", "=", "0", ";", "try", "{", "index", "=", "Integer", ".", "parseInt", "(", "getParamElementIndex", "(", ")", ")", ";", "}", "catch",...
Adds or removes an optional element.<p> Depends on the value stored in the <code>{@link CmsDialog#getAction()}</code> method.<p>
[ "Adds", "or", "removes", "an", "optional", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/CmsWidgetDialog.java#L182-L215
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java
Partitioner.getSnapshotLowWatermark
private long getSnapshotLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) { LOG.debug("Getting snapshot low water mark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE); if (isPreviousWatermarkExists(previousWatermark)) { if (isSimpleWatermark(watermarkType)) { return previousWatermark + deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0); } DateTime wm = Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds( (deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0))); return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone)); } // If previous watermark is not found, override with the start value // (irrespective of source.is.watermark.override flag) long startValue = Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone); LOG.info("Overriding low water mark with the given start value: " + startValue); return startValue; }
java
private long getSnapshotLowWatermark(WatermarkType watermarkType, long previousWatermark, int deltaForNextWatermark) { LOG.debug("Getting snapshot low water mark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE, ConfigurationKeys.DEFAULT_SOURCE_TIMEZONE); if (isPreviousWatermarkExists(previousWatermark)) { if (isSimpleWatermark(watermarkType)) { return previousWatermark + deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0); } DateTime wm = Utils.toDateTime(previousWatermark, WATERMARKTIMEFORMAT, timeZone).plusSeconds( (deltaForNextWatermark - this.state .getPropAsInt(ConfigurationKeys.SOURCE_QUERYBASED_LOW_WATERMARK_BACKUP_SECS, 0))); return Long.parseLong(Utils.dateTimeToString(wm, WATERMARKTIMEFORMAT, timeZone)); } // If previous watermark is not found, override with the start value // (irrespective of source.is.watermark.override flag) long startValue = Utils.getLongWithCurrentDate(this.state.getProp(ConfigurationKeys.SOURCE_QUERYBASED_START_VALUE), timeZone); LOG.info("Overriding low water mark with the given start value: " + startValue); return startValue; }
[ "private", "long", "getSnapshotLowWatermark", "(", "WatermarkType", "watermarkType", ",", "long", "previousWatermark", ",", "int", "deltaForNextWatermark", ")", "{", "LOG", ".", "debug", "(", "\"Getting snapshot low water mark\"", ")", ";", "String", "timeZone", "=", ...
Get low water mark @param watermarkType Watermark type @param previousWatermark Previous water mark @param deltaForNextWatermark delta number for next water mark @return Previous watermark (fallback to {@link ConfigurationKeys#SOURCE_QUERYBASED_START_VALUE} iff previous watermark is unavailable)
[ "Get", "low", "water", "mark" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java#L369-L390
Azure/azure-sdk-for-java
network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java
VirtualNetworksInner.getByResourceGroupAsync
public Observable<VirtualNetworkInner> getByResourceGroupAsync(String resourceGroupName, String virtualNetworkName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkName).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
java
public Observable<VirtualNetworkInner> getByResourceGroupAsync(String resourceGroupName, String virtualNetworkName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, virtualNetworkName).map(new Func1<ServiceResponse<VirtualNetworkInner>, VirtualNetworkInner>() { @Override public VirtualNetworkInner call(ServiceResponse<VirtualNetworkInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualNetworkInner", ">", "getByResourceGroupAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkName", ...
Gets the specified virtual network by resource group. @param resourceGroupName The name of the resource group. @param virtualNetworkName The name of the virtual network. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualNetworkInner object
[ "Gets", "the", "specified", "virtual", "network", "by", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/network/v2017_10_01/implementation/VirtualNetworksInner.java#L314-L321
knowm/XChange
xchange-anx/src/main/java/org/knowm/xchange/anx/v2/ANXAdapters.java
ANXAdapters.adaptOrder
public static LimitOrder adaptOrder( BigDecimal originalAmount, BigDecimal price, String tradedCurrency, String transactionCurrency, String orderTypeString, String id, Date timestamp) { // place a limit order OrderType orderType = adaptSide(orderTypeString); CurrencyPair currencyPair = adaptCurrencyPair(tradedCurrency, transactionCurrency); LimitOrder limitOrder = new LimitOrder(orderType, originalAmount, currencyPair, id, timestamp, price); return limitOrder; }
java
public static LimitOrder adaptOrder( BigDecimal originalAmount, BigDecimal price, String tradedCurrency, String transactionCurrency, String orderTypeString, String id, Date timestamp) { // place a limit order OrderType orderType = adaptSide(orderTypeString); CurrencyPair currencyPair = adaptCurrencyPair(tradedCurrency, transactionCurrency); LimitOrder limitOrder = new LimitOrder(orderType, originalAmount, currencyPair, id, timestamp, price); return limitOrder; }
[ "public", "static", "LimitOrder", "adaptOrder", "(", "BigDecimal", "originalAmount", ",", "BigDecimal", "price", ",", "String", "tradedCurrency", ",", "String", "transactionCurrency", ",", "String", "orderTypeString", ",", "String", "id", ",", "Date", "timestamp", "...
Adapts a ANXOrder to a LimitOrder @param price @param orderTypeString @return
[ "Adapts", "a", "ANXOrder", "to", "a", "LimitOrder" ]
train
https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-anx/src/main/java/org/knowm/xchange/anx/v2/ANXAdapters.java#L70-L87
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.createPrebuiltEntityRoleAsync
public Observable<UUID> createPrebuiltEntityRoleAsync(UUID appId, String versionId, UUID entityId, CreatePrebuiltEntityRoleOptionalParameter createPrebuiltEntityRoleOptionalParameter) { return createPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createPrebuiltEntityRoleOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
java
public Observable<UUID> createPrebuiltEntityRoleAsync(UUID appId, String versionId, UUID entityId, CreatePrebuiltEntityRoleOptionalParameter createPrebuiltEntityRoleOptionalParameter) { return createPrebuiltEntityRoleWithServiceResponseAsync(appId, versionId, entityId, createPrebuiltEntityRoleOptionalParameter).map(new Func1<ServiceResponse<UUID>, UUID>() { @Override public UUID call(ServiceResponse<UUID> response) { return response.body(); } }); }
[ "public", "Observable", "<", "UUID", ">", "createPrebuiltEntityRoleAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "CreatePrebuiltEntityRoleOptionalParameter", "createPrebuiltEntityRoleOptionalParameter", ")", "{", "return", "createPr...
Create an entity role for an entity in the application. @param appId The application ID. @param versionId The version ID. @param entityId The entity model ID. @param createPrebuiltEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the UUID object
[ "Create", "an", "entity", "role", "for", "an", "entity", "in", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L8061-L8068
aws/aws-sdk-java
aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/SigningProfile.java
SigningProfile.withSigningParameters
public SigningProfile withSigningParameters(java.util.Map<String, String> signingParameters) { setSigningParameters(signingParameters); return this; }
java
public SigningProfile withSigningParameters(java.util.Map<String, String> signingParameters) { setSigningParameters(signingParameters); return this; }
[ "public", "SigningProfile", "withSigningParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "signingParameters", ")", "{", "setSigningParameters", "(", "signingParameters", ")", ";", "return", "this", ";", "}" ]
<p> The parameters that are available for use by an AWS Signer user. </p> @param signingParameters The parameters that are available for use by an AWS Signer user. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "parameters", "that", "are", "available", "for", "use", "by", "an", "AWS", "Signer", "user", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/SigningProfile.java#L218-L221
apache/incubator-heron
heron/spi/src/java/org/apache/heron/spi/utils/UploaderUtils.java
UploaderUtils.generateFilename
public static String generateFilename( String topologyName, String role) { // By default, we have empty tag info and version 0 return generateFilename(topologyName, role, "tag", 0, DEFAULT_FILENAME_EXTENSION); }
java
public static String generateFilename( String topologyName, String role) { // By default, we have empty tag info and version 0 return generateFilename(topologyName, role, "tag", 0, DEFAULT_FILENAME_EXTENSION); }
[ "public", "static", "String", "generateFilename", "(", "String", "topologyName", ",", "String", "role", ")", "{", "// By default, we have empty tag info and version 0", "return", "generateFilename", "(", "topologyName", ",", "role", ",", "\"tag\"", ",", "0", ",", "DEF...
Generate a unique filename to upload in the storage service @param topologyName topology name @param role role owns the topology @return a unique filename
[ "Generate", "a", "unique", "filename", "to", "upload", "in", "the", "storage", "service" ]
train
https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/spi/src/java/org/apache/heron/spi/utils/UploaderUtils.java#L45-L50
apache/incubator-druid
extensions-core/druid-bloom-filter/src/main/java/org/apache/druid/query/filter/BloomKFilter.java
BloomKFilter.addHash
public static void addHash(ByteBuffer buffer, long hash64) { final int hash1 = (int) hash64; final int hash2 = (int) (hash64 >>> 32); int firstHash = hash1 + hash2; // hashcode should be positive, flip all the bits if it's negative if (firstHash < 0) { firstHash = ~firstHash; } ByteBuffer view = buffer.duplicate().order(ByteOrder.BIG_ENDIAN); int startPosition = view.position(); int numHashFuncs = view.get(startPosition); int totalBlockCount = view.getInt(startPosition + 1) / DEFAULT_BLOCK_SIZE; // first hash is used to locate start of the block (blockBaseOffset) // subsequent K hashes are used to generate K bits within a block of words final int blockIdx = firstHash % totalBlockCount; final int blockBaseOffset = blockIdx << DEFAULT_BLOCK_SIZE_BITS; for (int i = 1; i <= numHashFuncs; i++) { int combinedHash = hash1 + ((i + 1) * hash2); // hashcode should be positive, flip all the bits if it's negative if (combinedHash < 0) { combinedHash = ~combinedHash; } // LSB 3 bits is used to locate offset within the block final int absOffset = blockBaseOffset + (combinedHash & DEFAULT_BLOCK_OFFSET_MASK); // Next 6 bits are used to locate offset within a long/word final int bitPos = (combinedHash >>> DEFAULT_BLOCK_SIZE_BITS) & DEFAULT_BIT_OFFSET_MASK; final int bufPos = startPosition + START_OF_SERIALIZED_LONGS + (absOffset * Long.BYTES); view.putLong(bufPos, view.getLong(bufPos) | (1L << bitPos)); } }
java
public static void addHash(ByteBuffer buffer, long hash64) { final int hash1 = (int) hash64; final int hash2 = (int) (hash64 >>> 32); int firstHash = hash1 + hash2; // hashcode should be positive, flip all the bits if it's negative if (firstHash < 0) { firstHash = ~firstHash; } ByteBuffer view = buffer.duplicate().order(ByteOrder.BIG_ENDIAN); int startPosition = view.position(); int numHashFuncs = view.get(startPosition); int totalBlockCount = view.getInt(startPosition + 1) / DEFAULT_BLOCK_SIZE; // first hash is used to locate start of the block (blockBaseOffset) // subsequent K hashes are used to generate K bits within a block of words final int blockIdx = firstHash % totalBlockCount; final int blockBaseOffset = blockIdx << DEFAULT_BLOCK_SIZE_BITS; for (int i = 1; i <= numHashFuncs; i++) { int combinedHash = hash1 + ((i + 1) * hash2); // hashcode should be positive, flip all the bits if it's negative if (combinedHash < 0) { combinedHash = ~combinedHash; } // LSB 3 bits is used to locate offset within the block final int absOffset = blockBaseOffset + (combinedHash & DEFAULT_BLOCK_OFFSET_MASK); // Next 6 bits are used to locate offset within a long/word final int bitPos = (combinedHash >>> DEFAULT_BLOCK_SIZE_BITS) & DEFAULT_BIT_OFFSET_MASK; final int bufPos = startPosition + START_OF_SERIALIZED_LONGS + (absOffset * Long.BYTES); view.putLong(bufPos, view.getLong(bufPos) | (1L << bitPos)); } }
[ "public", "static", "void", "addHash", "(", "ByteBuffer", "buffer", ",", "long", "hash64", ")", "{", "final", "int", "hash1", "=", "(", "int", ")", "hash64", ";", "final", "int", "hash2", "=", "(", "int", ")", "(", "hash64", ">>>", "32", ")", ";", ...
ByteBuffer based copy of {@link BloomKFilter#addHash(long)} that adds a value to the ByteBuffer in place.
[ "ByteBuffer", "based", "copy", "of", "{" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/druid-bloom-filter/src/main/java/org/apache/druid/query/filter/BloomKFilter.java#L392-L425
JavaMoney/jsr354-api
src/main/java/javax/money/AbstractQueryBuilder.java
AbstractQueryBuilder.setProviderNames
public B setProviderNames(List<String> providers) { Objects.requireNonNull(providers); return set(AbstractQuery.KEY_QUERY_PROVIDERS, providers); }
java
public B setProviderNames(List<String> providers) { Objects.requireNonNull(providers); return set(AbstractQuery.KEY_QUERY_PROVIDERS, providers); }
[ "public", "B", "setProviderNames", "(", "List", "<", "String", ">", "providers", ")", "{", "Objects", ".", "requireNonNull", "(", "providers", ")", ";", "return", "set", "(", "AbstractQuery", ".", "KEY_QUERY_PROVIDERS", ",", "providers", ")", ";", "}" ]
Set the providers to be considered. If not set explicitly the <i>default</i> ISO currencies as returned by {@link java.util.Currency} is used. @param providers the providers to use, not null. @return the query builder for chaining.
[ "Set", "the", "providers", "to", "be", "considered", ".", "If", "not", "set", "explicitly", "the", "<i", ">", "default<", "/", "i", ">", "ISO", "currencies", "as", "returned", "by", "{", "@link", "java", ".", "util", ".", "Currency", "}", "is", "used",...
train
https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/AbstractQueryBuilder.java#L61-L64
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java
AppServicePlansInner.listWebAppsWithServiceResponseAsync
public Observable<ServiceResponse<Page<SiteInner>>> listWebAppsWithServiceResponseAsync(final String resourceGroupName, final String name, final String skipToken, final String filter, final String top) { return listWebAppsSinglePageAsync(resourceGroupName, name, skipToken, filter, top) .concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() { @Override public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listWebAppsNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<SiteInner>>> listWebAppsWithServiceResponseAsync(final String resourceGroupName, final String name, final String skipToken, final String filter, final String top) { return listWebAppsSinglePageAsync(resourceGroupName, name, skipToken, filter, top) .concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() { @Override public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listWebAppsNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", ">", "listWebAppsWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ",", "final", "String", "skipToken", ",", "final", "St...
Get all apps associated with an App Service plan. Get all apps associated with an App Service plan. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service plan. @param skipToken Skip to a web app in the list of webapps associated with app service plan. If specified, the resulting list will contain web apps starting from (including) the skipToken. Otherwise, the resulting list contains web apps from the start of the list @param filter Supported filter: $filter=state eq running. Returns only web apps that are currently running @param top List page size. If specified, results are paged. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SiteInner&gt; object
[ "Get", "all", "apps", "associated", "with", "an", "App", "Service", "plan", ".", "Get", "all", "apps", "associated", "with", "an", "App", "Service", "plan", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServicePlansInner.java#L2568-L2580
OpenLiberty/open-liberty
dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/LdapConnection.java
LdapConnection.toKey
@Trivial private static String toKey(String name, String filterExpr, Object[] filterArgs, SearchControls cons) { int length = name.length() + filterExpr.length() + filterArgs.length + 200; StringBuffer key = new StringBuffer(length); key.append(name); key.append("|"); key.append(filterExpr); String[] attrIds = cons.getReturningAttributes(); for (int i = 0; i < filterArgs.length; i++) { key.append("|"); key.append(filterArgs[i]); } if (attrIds != null) { for (int i = 0; i < attrIds.length; i++) { key.append("|"); key.append(attrIds[i]); } } return key.toString(); }
java
@Trivial private static String toKey(String name, String filterExpr, Object[] filterArgs, SearchControls cons) { int length = name.length() + filterExpr.length() + filterArgs.length + 200; StringBuffer key = new StringBuffer(length); key.append(name); key.append("|"); key.append(filterExpr); String[] attrIds = cons.getReturningAttributes(); for (int i = 0; i < filterArgs.length; i++) { key.append("|"); key.append(filterArgs[i]); } if (attrIds != null) { for (int i = 0; i < attrIds.length; i++) { key.append("|"); key.append(attrIds[i]); } } return key.toString(); }
[ "@", "Trivial", "private", "static", "String", "toKey", "(", "String", "name", ",", "String", "filterExpr", ",", "Object", "[", "]", "filterArgs", ",", "SearchControls", "cons", ")", "{", "int", "length", "=", "name", ".", "length", "(", ")", "+", "filte...
Returns a hash key for the name|filterExpr|filterArgs|cons tuple used in the search query-results cache. @param name The name of the context or object to search @param filterExpr the filter expression used in the search. @param filterArgs the filter arguments used in the search. @param cons The search controls used in the search. @throws NamingException If a naming exception is encountered.
[ "Returns", "a", "hash", "key", "for", "the", "name|filterExpr|filterArgs|cons", "tuple", "used", "in", "the", "search", "query", "-", "results", "cache", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.wim.adapter.ldap/src/com/ibm/ws/security/wim/adapter/ldap/LdapConnection.java#L243-L262
apache/flink
flink-connectors/flink-connector-filesystem/src/main/java/org/apache/flink/streaming/connectors/fs/RollingSink.java
RollingSink.openNewPartFile
private void openNewPartFile() throws Exception { closeCurrentPartFile(); Path newBucketDirectory = bucketer.getNextBucketPath(new Path(basePath)); if (!newBucketDirectory.equals(currentBucketDirectory)) { currentBucketDirectory = newBucketDirectory; try { if (fs.mkdirs(currentBucketDirectory)) { LOG.debug("Created new bucket directory: {}", currentBucketDirectory); } } catch (IOException e) { throw new RuntimeException("Could not create base path for new rolling file.", e); } } int subtaskIndex = getRuntimeContext().getIndexOfThisSubtask(); currentPartPath = new Path(currentBucketDirectory, partPrefix + "-" + subtaskIndex + "-" + partCounter); // This should work since there is only one parallel subtask that tries names with // our subtask id. Otherwise we would run into concurrency issues here. while (fs.exists(currentPartPath) || fs.exists(getPendingPathFor(currentPartPath)) || fs.exists(getInProgressPathFor(currentPartPath))) { partCounter++; currentPartPath = new Path(currentBucketDirectory, partPrefix + "-" + subtaskIndex + "-" + partCounter); } // increase, so we don't have to check for this name next time partCounter++; LOG.debug("Next part path is {}", currentPartPath.toString()); Path inProgressPath = getInProgressPathFor(currentPartPath); writer.open(fs, inProgressPath); isWriterOpen = true; }
java
private void openNewPartFile() throws Exception { closeCurrentPartFile(); Path newBucketDirectory = bucketer.getNextBucketPath(new Path(basePath)); if (!newBucketDirectory.equals(currentBucketDirectory)) { currentBucketDirectory = newBucketDirectory; try { if (fs.mkdirs(currentBucketDirectory)) { LOG.debug("Created new bucket directory: {}", currentBucketDirectory); } } catch (IOException e) { throw new RuntimeException("Could not create base path for new rolling file.", e); } } int subtaskIndex = getRuntimeContext().getIndexOfThisSubtask(); currentPartPath = new Path(currentBucketDirectory, partPrefix + "-" + subtaskIndex + "-" + partCounter); // This should work since there is only one parallel subtask that tries names with // our subtask id. Otherwise we would run into concurrency issues here. while (fs.exists(currentPartPath) || fs.exists(getPendingPathFor(currentPartPath)) || fs.exists(getInProgressPathFor(currentPartPath))) { partCounter++; currentPartPath = new Path(currentBucketDirectory, partPrefix + "-" + subtaskIndex + "-" + partCounter); } // increase, so we don't have to check for this name next time partCounter++; LOG.debug("Next part path is {}", currentPartPath.toString()); Path inProgressPath = getInProgressPathFor(currentPartPath); writer.open(fs, inProgressPath); isWriterOpen = true; }
[ "private", "void", "openNewPartFile", "(", ")", "throws", "Exception", "{", "closeCurrentPartFile", "(", ")", ";", "Path", "newBucketDirectory", "=", "bucketer", ".", "getNextBucketPath", "(", "new", "Path", "(", "basePath", ")", ")", ";", "if", "(", "!", "n...
Opens a new part file. <p>This closes the old bucket file and retrieves a new bucket path from the {@code Bucketer}.
[ "Opens", "a", "new", "part", "file", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-filesystem/src/main/java/org/apache/flink/streaming/connectors/fs/RollingSink.java#L446-L482
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java
Task.executeAsyncCallRunnable
private void executeAsyncCallRunnable(Runnable runnable, String callName, boolean blocking) { // make sure the executor is initialized. lock against concurrent calls to this function synchronized (this) { if (executionState != ExecutionState.RUNNING) { return; } // get ourselves a reference on the stack that cannot be concurrently modified BlockingCallMonitoringThreadPool executor = this.asyncCallDispatcher; if (executor == null) { // first time use, initialize checkState(userCodeClassLoader != null, "userCodeClassLoader must not be null"); // Under normal execution, we expect that one thread will suffice, this is why we // keep the core threads to 1. In the case of a synchronous savepoint, we will block // the checkpointing thread, so we need an additional thread to execute the // notifyCheckpointComplete() callback. Finally, we aggressively purge (potentially) // idle thread so that we do not risk to have many idle thread on machines with multiple // tasks on them. Either way, only one of them can execute at a time due to the // checkpoint lock. executor = new BlockingCallMonitoringThreadPool( new DispatcherThreadFactory( TASK_THREADS_GROUP, "Async calls on " + taskNameWithSubtask, userCodeClassLoader)); this.asyncCallDispatcher = executor; // double-check for execution state, and make sure we clean up after ourselves // if we created the dispatcher while the task was concurrently canceled if (executionState != ExecutionState.RUNNING) { executor.shutdown(); asyncCallDispatcher = null; return; } } LOG.debug("Invoking async call {} on task {}", callName, taskNameWithSubtask); try { executor.submit(runnable, blocking); } catch (RejectedExecutionException e) { // may be that we are concurrently finished or canceled. // if not, report that something is fishy if (executionState == ExecutionState.RUNNING) { throw new RuntimeException("Async call with a " + (blocking ? "" : "non-") + "blocking call was rejected, even though the task is running.", e); } } } }
java
private void executeAsyncCallRunnable(Runnable runnable, String callName, boolean blocking) { // make sure the executor is initialized. lock against concurrent calls to this function synchronized (this) { if (executionState != ExecutionState.RUNNING) { return; } // get ourselves a reference on the stack that cannot be concurrently modified BlockingCallMonitoringThreadPool executor = this.asyncCallDispatcher; if (executor == null) { // first time use, initialize checkState(userCodeClassLoader != null, "userCodeClassLoader must not be null"); // Under normal execution, we expect that one thread will suffice, this is why we // keep the core threads to 1. In the case of a synchronous savepoint, we will block // the checkpointing thread, so we need an additional thread to execute the // notifyCheckpointComplete() callback. Finally, we aggressively purge (potentially) // idle thread so that we do not risk to have many idle thread on machines with multiple // tasks on them. Either way, only one of them can execute at a time due to the // checkpoint lock. executor = new BlockingCallMonitoringThreadPool( new DispatcherThreadFactory( TASK_THREADS_GROUP, "Async calls on " + taskNameWithSubtask, userCodeClassLoader)); this.asyncCallDispatcher = executor; // double-check for execution state, and make sure we clean up after ourselves // if we created the dispatcher while the task was concurrently canceled if (executionState != ExecutionState.RUNNING) { executor.shutdown(); asyncCallDispatcher = null; return; } } LOG.debug("Invoking async call {} on task {}", callName, taskNameWithSubtask); try { executor.submit(runnable, blocking); } catch (RejectedExecutionException e) { // may be that we are concurrently finished or canceled. // if not, report that something is fishy if (executionState == ExecutionState.RUNNING) { throw new RuntimeException("Async call with a " + (blocking ? "" : "non-") + "blocking call was rejected, even though the task is running.", e); } } } }
[ "private", "void", "executeAsyncCallRunnable", "(", "Runnable", "runnable", ",", "String", "callName", ",", "boolean", "blocking", ")", "{", "// make sure the executor is initialized. lock against concurrent calls to this function", "synchronized", "(", "this", ")", "{", "if"...
Utility method to dispatch an asynchronous call on the invokable. @param runnable The async call runnable. @param callName The name of the call, for logging purposes.
[ "Utility", "method", "to", "dispatch", "an", "asynchronous", "call", "on", "the", "invokable", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/Task.java#L1319-L1369
spring-projects/spring-data-solr
src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java
EmbeddedSolrServerFactory.createCoreContainerViaConstructor
private CoreContainer createCoreContainerViaConstructor(String solrHomeDirectory, File solrXmlFile) { Constructor<CoreContainer> constructor = ClassUtils.getConstructorIfAvailable(CoreContainer.class, String.class, File.class); return BeanUtils.instantiateClass(constructor, solrHomeDirectory, solrXmlFile); }
java
private CoreContainer createCoreContainerViaConstructor(String solrHomeDirectory, File solrXmlFile) { Constructor<CoreContainer> constructor = ClassUtils.getConstructorIfAvailable(CoreContainer.class, String.class, File.class); return BeanUtils.instantiateClass(constructor, solrHomeDirectory, solrXmlFile); }
[ "private", "CoreContainer", "createCoreContainerViaConstructor", "(", "String", "solrHomeDirectory", ",", "File", "solrXmlFile", ")", "{", "Constructor", "<", "CoreContainer", ">", "constructor", "=", "ClassUtils", ".", "getConstructorIfAvailable", "(", "CoreContainer", "...
Create {@link CoreContainer} via its constructor (Solr 3.6.0 - 4.3.1) @param solrHomeDirectory @param solrXmlFile @return
[ "Create", "{", "@link", "CoreContainer", "}", "via", "its", "constructor", "(", "Solr", "3", ".", "6", ".", "0", "-", "4", ".", "3", ".", "1", ")" ]
train
https://github.com/spring-projects/spring-data-solr/blob/20be5cb82498b70134dfda6c1a91ad21f8e657e0/src/main/java/org/springframework/data/solr/server/support/EmbeddedSolrServerFactory.java#L127-L131
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/util/WindowUtils.java
WindowUtils.setWindowShape
public static void setWindowShape(Window window, Shape s) { if (PlatformUtils.isJava6()) { setWindowShapeJava6(window, s); } else { setWindowShapeJava7(window, s); } }
java
public static void setWindowShape(Window window, Shape s) { if (PlatformUtils.isJava6()) { setWindowShapeJava6(window, s); } else { setWindowShapeJava7(window, s); } }
[ "public", "static", "void", "setWindowShape", "(", "Window", "window", ",", "Shape", "s", ")", "{", "if", "(", "PlatformUtils", ".", "isJava6", "(", ")", ")", "{", "setWindowShapeJava6", "(", "window", ",", "s", ")", ";", "}", "else", "{", "setWindowShap...
Sets the shape of a window. This will be done via a com.sun API and may be not available on all platforms. @param window to change the shape for @param s the new shape for the window.
[ "Sets", "the", "shape", "of", "a", "window", ".", "This", "will", "be", "done", "via", "a", "com", ".", "sun", "API", "and", "may", "be", "not", "available", "on", "all", "platforms", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/util/WindowUtils.java#L75-L81
GwtMaterialDesign/gwt-material-table
src/main/java/gwt/material/design/client/ui/table/CellBasedWidgetImpl.java
CellBasedWidgetImpl.sinkEvents
public final void sinkEvents(Widget widget, Set<String> typeNames) { if (typeNames == null) { return; } int eventsToSink = 0; for (String typeName : typeNames) { int typeInt = Event.getTypeInt(typeName); if (typeInt < 0) { widget.sinkBitlessEvent(typeName); } else { typeInt = sinkEvent(widget, typeName); if (typeInt > 0) { eventsToSink |= typeInt; } } } if (eventsToSink > 0) { widget.sinkEvents(eventsToSink); } }
java
public final void sinkEvents(Widget widget, Set<String> typeNames) { if (typeNames == null) { return; } int eventsToSink = 0; for (String typeName : typeNames) { int typeInt = Event.getTypeInt(typeName); if (typeInt < 0) { widget.sinkBitlessEvent(typeName); } else { typeInt = sinkEvent(widget, typeName); if (typeInt > 0) { eventsToSink |= typeInt; } } } if (eventsToSink > 0) { widget.sinkEvents(eventsToSink); } }
[ "public", "final", "void", "sinkEvents", "(", "Widget", "widget", ",", "Set", "<", "String", ">", "typeNames", ")", "{", "if", "(", "typeNames", "==", "null", ")", "{", "return", ";", "}", "int", "eventsToSink", "=", "0", ";", "for", "(", "String", "...
Sink events on the widget. @param widget the {@link Widget} that will handle the events @param typeNames the names of the events to sink
[ "Sink", "events", "on", "the", "widget", "." ]
train
https://github.com/GwtMaterialDesign/gwt-material-table/blob/1352cafdcbff747bc1f302e709ed376df6642ef5/src/main/java/gwt/material/design/client/ui/table/CellBasedWidgetImpl.java#L133-L153
quattor/pan
panc/src/main/java/org/quattor/pan/ttemplate/IteratorMap.java
IteratorMap.put
public void put(Resource resource, Resource.Iterator iterator) { assert (resource != null); Integer key = Integer.valueOf(System.identityHashCode(resource)); if (iterator != null) { map.put(key, iterator); } else { map.remove(key); } }
java
public void put(Resource resource, Resource.Iterator iterator) { assert (resource != null); Integer key = Integer.valueOf(System.identityHashCode(resource)); if (iterator != null) { map.put(key, iterator); } else { map.remove(key); } }
[ "public", "void", "put", "(", "Resource", "resource", ",", "Resource", ".", "Iterator", "iterator", ")", "{", "assert", "(", "resource", "!=", "null", ")", ";", "Integer", "key", "=", "Integer", ".", "valueOf", "(", "System", ".", "identityHashCode", "(", ...
Associate the iterator to the given resource. If the iterator is null, then the mapping is removed. @param resource resource to associate the iterator to @param iterator iterator to associate to the resource; if null mapping is removed
[ "Associate", "the", "iterator", "to", "the", "given", "resource", ".", "If", "the", "iterator", "is", "null", "then", "the", "mapping", "is", "removed", "." ]
train
https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/ttemplate/IteratorMap.java#L52-L62
nabedge/mixer2
src/main/java/org/mixer2/xhtml/AbstractJaxb.java
AbstractJaxb.insertAfterId
public <T extends AbstractJaxb> boolean insertAfterId(String id, T insObject) throws TagTypeUnmatchException { return InsertByIdUtil.insertAfterId(id, insObject, this); }
java
public <T extends AbstractJaxb> boolean insertAfterId(String id, T insObject) throws TagTypeUnmatchException { return InsertByIdUtil.insertAfterId(id, insObject, this); }
[ "public", "<", "T", "extends", "AbstractJaxb", ">", "boolean", "insertAfterId", "(", "String", "id", ",", "T", "insObject", ")", "throws", "TagTypeUnmatchException", "{", "return", "InsertByIdUtil", ".", "insertAfterId", "(", "id", ",", "insObject", ",", "this",...
<p> insert element after the element having specified id attribute. This method use deep copy of "insObject" </p> @param id id attribute @param insObject @return true if success to insert. if no hit, return false. @throws TagTypeUnmatchException
[ "<p", ">", "insert", "element", "after", "the", "element", "having", "specified", "id", "attribute", ".", "This", "method", "use", "deep", "copy", "of", "insObject", "<", "/", "p", ">" ]
train
https://github.com/nabedge/mixer2/blob/8c2db27cfcd65bf0b1e0242ef9362ebd8033777c/src/main/java/org/mixer2/xhtml/AbstractJaxb.java#L489-L492
TheHolyWaffle/League-of-Legends-XMPP-Chat-Library
src/main/java/com/github/theholywaffle/lolchatapi/LolChat.java
LolChat.getFriendGroupByName
public FriendGroup getFriendGroupByName(String name) { final RosterGroup g = connection.getRoster().getGroup(name); if (g != null) { return new FriendGroup(this, connection, g); } return addFriendGroup(name); }
java
public FriendGroup getFriendGroupByName(String name) { final RosterGroup g = connection.getRoster().getGroup(name); if (g != null) { return new FriendGroup(this, connection, g); } return addFriendGroup(name); }
[ "public", "FriendGroup", "getFriendGroupByName", "(", "String", "name", ")", "{", "final", "RosterGroup", "g", "=", "connection", ".", "getRoster", "(", ")", ".", "getGroup", "(", "name", ")", ";", "if", "(", "g", "!=", "null", ")", "{", "return", "new",...
Gets a FriendGroup by name, for example "Duo Partners". The name is case sensitive! The FriendGroup will be created if it didn't exist yet. @param name The name of your group (case-sensitive) @return The corresponding FriendGroup
[ "Gets", "a", "FriendGroup", "by", "name", "for", "example", "Duo", "Partners", ".", "The", "name", "is", "case", "sensitive!", "The", "FriendGroup", "will", "be", "created", "if", "it", "didn", "t", "exist", "yet", "." ]
train
https://github.com/TheHolyWaffle/League-of-Legends-XMPP-Chat-Library/blob/5e4d87d0c054ff2f6510545b0e9f838338695c70/src/main/java/com/github/theholywaffle/lolchatapi/LolChat.java#L493-L499
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.setBaselineFixedCostAccrual
public void setBaselineFixedCostAccrual(int baselineNumber, AccrueType value) { set(selectField(TaskFieldLists.BASELINE_FIXED_COST_ACCRUALS, baselineNumber), value); }
java
public void setBaselineFixedCostAccrual(int baselineNumber, AccrueType value) { set(selectField(TaskFieldLists.BASELINE_FIXED_COST_ACCRUALS, baselineNumber), value); }
[ "public", "void", "setBaselineFixedCostAccrual", "(", "int", "baselineNumber", ",", "AccrueType", "value", ")", "{", "set", "(", "selectField", "(", "TaskFieldLists", ".", "BASELINE_FIXED_COST_ACCRUALS", ",", "baselineNumber", ")", ",", "value", ")", ";", "}" ]
Set a baseline value. @param baselineNumber baseline index (1-10) @param value baseline value
[ "Set", "a", "baseline", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L4546-L4549
OpenLiberty/open-liberty
dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java
ThreadPoolController.manageIdlePool
boolean manageIdlePool(ThreadPoolExecutor threadPool, long intervalCompleted) { // Manage the intervalCompleted count if (intervalCompleted == 0 && threadPool.getActiveCount() == 0) { consecutiveIdleCount++; } else { consecutiveIdleCount = 0; } if (consecutiveIdleCount >= IDLE_INTERVALS_BEFORE_PAUSE) { pause(); lastAction = LastAction.PAUSE; return true; } return false; }
java
boolean manageIdlePool(ThreadPoolExecutor threadPool, long intervalCompleted) { // Manage the intervalCompleted count if (intervalCompleted == 0 && threadPool.getActiveCount() == 0) { consecutiveIdleCount++; } else { consecutiveIdleCount = 0; } if (consecutiveIdleCount >= IDLE_INTERVALS_BEFORE_PAUSE) { pause(); lastAction = LastAction.PAUSE; return true; } return false; }
[ "boolean", "manageIdlePool", "(", "ThreadPoolExecutor", "threadPool", ",", "long", "intervalCompleted", ")", "{", "// Manage the intervalCompleted count", "if", "(", "intervalCompleted", "==", "0", "&&", "threadPool", ".", "getActiveCount", "(", ")", "==", "0", ")", ...
Determine whether or not the thread pool has been idle long enough to pause the monitoring task. @param threadPool a reference to the thread pool @param intervalCompleted the tasks completed this interval @return true if the controller has been paused
[ "Determine", "whether", "or", "not", "the", "thread", "pool", "has", "been", "idle", "long", "enough", "to", "pause", "the", "monitoring", "task", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.threading/src/com/ibm/ws/threading/internal/ThreadPoolController.java#L774-L790
zaproxy/zaproxy
src/org/zaproxy/zap/view/StandardFieldsDialog.java
StandardFieldsDialog.addComboField
public <E> void addComboField(int tabIndex, String fieldLabel, ComboBoxModel<E> comboBoxModel) { addComboField(tabIndex, fieldLabel, comboBoxModel, false); }
java
public <E> void addComboField(int tabIndex, String fieldLabel, ComboBoxModel<E> comboBoxModel) { addComboField(tabIndex, fieldLabel, comboBoxModel, false); }
[ "public", "<", "E", ">", "void", "addComboField", "(", "int", "tabIndex", ",", "String", "fieldLabel", ",", "ComboBoxModel", "<", "E", ">", "comboBoxModel", ")", "{", "addComboField", "(", "tabIndex", ",", "fieldLabel", ",", "comboBoxModel", ",", "false", ")...
Adds a combo box field with the given label and model, to the tab with the given index. <p> Control of selection state (i.e. set/get selected item) is done through the combo box model. @param <E> the type of the elements of the combo box model. @param tabIndex the index of the tab where the combo box should be added. @param fieldLabel the name of the label of the combo box field. @param comboBoxModel the model to set into the combo box. @since 2.6.0 @throws IllegalArgumentException if any of the following conditions is true: <ul> <li>the dialogue does not have tabs;</li> <li>the dialogue has tabs but the given tab index is not valid;</li> <li>a field with the given label already exists.</li> </ul> @see #addComboField(String, ComboBoxModel) @see #addComboField(int, String, ComboBoxModel, boolean) @see #setComboBoxModel(String, ComboBoxModel)
[ "Adds", "a", "combo", "box", "field", "with", "the", "given", "label", "and", "model", "to", "the", "tab", "with", "the", "given", "index", ".", "<p", ">", "Control", "of", "selection", "state", "(", "i", ".", "e", ".", "set", "/", "get", "selected",...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/view/StandardFieldsDialog.java#L805-L807
microfocus-idol/java-configuration-impl
src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java
ConfigurationUtils.mergeComponent
public static <F extends ConfigurationComponent<F>> F mergeComponent(final F localValue, final F defaultValue) { return Optional.ofNullable(localValue).map(v -> v.merge(defaultValue)).orElse(defaultValue); }
java
public static <F extends ConfigurationComponent<F>> F mergeComponent(final F localValue, final F defaultValue) { return Optional.ofNullable(localValue).map(v -> v.merge(defaultValue)).orElse(defaultValue); }
[ "public", "static", "<", "F", "extends", "ConfigurationComponent", "<", "F", ">", ">", "F", "mergeComponent", "(", "final", "F", "localValue", ",", "final", "F", "defaultValue", ")", "{", "return", "Optional", ".", "ofNullable", "(", "localValue", ")", ".", ...
Merges a (nullable) object field on the local config object with a default (nullable) value in the default config object @param localValue local field value @param defaultValue default field value @param <F> the configuration object type @return the merged field value
[ "Merges", "a", "(", "nullable", ")", "object", "field", "on", "the", "local", "config", "object", "with", "a", "default", "(", "nullable", ")", "value", "in", "the", "default", "config", "object" ]
train
https://github.com/microfocus-idol/java-configuration-impl/blob/cd9d744cacfaaae3c76cacc211e65742bbc7b00a/src/main/java/com/hp/autonomy/frontend/configuration/ConfigurationUtils.java#L54-L56
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.telephony_billingAccount_numberNogeographic_GET
public OvhOrder telephony_billingAccount_numberNogeographic_GET(String billingAccount, String ape, String city, OvhNumberCountryEnum country, Boolean displayUniversalDirectory, String email, String firstname, OvhLegalFormEnum legalform, String name, OvhNumberOffer offer, String organisation, String phone, OvhNumberPoolEnum pool, Boolean retractation, String siret, String socialNomination, String specificNumber, String streetName, String streetNumber, String zip) throws IOException { String qPath = "/order/telephony/{billingAccount}/numberNogeographic"; StringBuilder sb = path(qPath, billingAccount); query(sb, "ape", ape); query(sb, "city", city); query(sb, "country", country); query(sb, "displayUniversalDirectory", displayUniversalDirectory); query(sb, "email", email); query(sb, "firstname", firstname); query(sb, "legalform", legalform); query(sb, "name", name); query(sb, "offer", offer); query(sb, "organisation", organisation); query(sb, "phone", phone); query(sb, "pool", pool); query(sb, "retractation", retractation); query(sb, "siret", siret); query(sb, "socialNomination", socialNomination); query(sb, "specificNumber", specificNumber); query(sb, "streetName", streetName); query(sb, "streetNumber", streetNumber); query(sb, "zip", zip); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder telephony_billingAccount_numberNogeographic_GET(String billingAccount, String ape, String city, OvhNumberCountryEnum country, Boolean displayUniversalDirectory, String email, String firstname, OvhLegalFormEnum legalform, String name, OvhNumberOffer offer, String organisation, String phone, OvhNumberPoolEnum pool, Boolean retractation, String siret, String socialNomination, String specificNumber, String streetName, String streetNumber, String zip) throws IOException { String qPath = "/order/telephony/{billingAccount}/numberNogeographic"; StringBuilder sb = path(qPath, billingAccount); query(sb, "ape", ape); query(sb, "city", city); query(sb, "country", country); query(sb, "displayUniversalDirectory", displayUniversalDirectory); query(sb, "email", email); query(sb, "firstname", firstname); query(sb, "legalform", legalform); query(sb, "name", name); query(sb, "offer", offer); query(sb, "organisation", organisation); query(sb, "phone", phone); query(sb, "pool", pool); query(sb, "retractation", retractation); query(sb, "siret", siret); query(sb, "socialNomination", socialNomination); query(sb, "specificNumber", specificNumber); query(sb, "streetName", streetName); query(sb, "streetNumber", streetNumber); query(sb, "zip", zip); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "telephony_billingAccount_numberNogeographic_GET", "(", "String", "billingAccount", ",", "String", "ape", ",", "String", "city", ",", "OvhNumberCountryEnum", "country", ",", "Boolean", "displayUniversalDirectory", ",", "String", "email", ",", "String...
Get prices and contracts information REST: GET /order/telephony/{billingAccount}/numberNogeographic @param firstname [required] Contact firstname @param streetName [required] Street name @param email [required] @param organisation [required] Contact organisation @param pool [required] Number of alias in case of pool @param socialNomination [required] Company social nomination @param zip [required] Contact zip @param name [required] Contact name @param country [required] Number country @param retractation [required] Retractation rights if set @param displayUniversalDirectory [required] Publish contact informations on universal directories @param siret [required] Companu siret @param phone [required] Contact phone @param specificNumber [required] Preselected standard number @param streetNumber [required] Street number @param legalform [required] Legal form @param offer [required] Number offer @param city [required] Contact city @param ape [required] Company ape @param billingAccount [required] The name of your billingAccount
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L6240-L6264
eclipse/xtext-core
org.eclipse.xtext/src/org/eclipse/xtext/resource/SaveOptions.java
SaveOptions.getOptions
@SuppressWarnings("deprecation") public static SaveOptions getOptions(Map<?, ?> saveOptions) { if (saveOptions == null || saveOptions.isEmpty()) return defaultOptions(); if (saveOptions.containsKey(KEY)) return (SaveOptions) saveOptions.get(KEY); if (saveOptions.containsKey(XtextResource.OPTION_SERIALIZATION_OPTIONS)) return ((org.eclipse.xtext.parsetree.reconstr.SerializerOptions) saveOptions.get(XtextResource.OPTION_SERIALIZATION_OPTIONS)).toSaveOptions(); if (Boolean.TRUE.equals(saveOptions.get(XtextResource.OPTION_FORMAT))) { return newBuilder().format().getOptions(); } return defaultOptions(); }
java
@SuppressWarnings("deprecation") public static SaveOptions getOptions(Map<?, ?> saveOptions) { if (saveOptions == null || saveOptions.isEmpty()) return defaultOptions(); if (saveOptions.containsKey(KEY)) return (SaveOptions) saveOptions.get(KEY); if (saveOptions.containsKey(XtextResource.OPTION_SERIALIZATION_OPTIONS)) return ((org.eclipse.xtext.parsetree.reconstr.SerializerOptions) saveOptions.get(XtextResource.OPTION_SERIALIZATION_OPTIONS)).toSaveOptions(); if (Boolean.TRUE.equals(saveOptions.get(XtextResource.OPTION_FORMAT))) { return newBuilder().format().getOptions(); } return defaultOptions(); }
[ "@", "SuppressWarnings", "(", "\"deprecation\"", ")", "public", "static", "SaveOptions", "getOptions", "(", "Map", "<", "?", ",", "?", ">", "saveOptions", ")", "{", "if", "(", "saveOptions", "==", "null", "||", "saveOptions", ".", "isEmpty", "(", ")", ")",...
Transparently handles the deprecated options that could be passed as map-entries to {@link org.eclipse.emf.ecore.resource.Resource#save(Map)} and converts them to semantically equal {@link SaveOptions}. @param saveOptions the options-map or <code>null</code> if none. @return the options to use. Will never return <code>null</code>.
[ "Transparently", "handles", "the", "deprecated", "options", "that", "could", "be", "passed", "as", "map", "-", "entries", "to", "{", "@link", "org", ".", "eclipse", ".", "emf", ".", "ecore", ".", "resource", ".", "Resource#save", "(", "Map", ")", "}", "a...
train
https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/resource/SaveOptions.java#L47-L60
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java
JobExecutionsInner.listByAgentAsync
public Observable<Page<JobExecutionInner>> listByAgentAsync(final String resourceGroupName, final String serverName, final String jobAgentName) { return listByAgentWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName) .map(new Func1<ServiceResponse<Page<JobExecutionInner>>, Page<JobExecutionInner>>() { @Override public Page<JobExecutionInner> call(ServiceResponse<Page<JobExecutionInner>> response) { return response.body(); } }); }
java
public Observable<Page<JobExecutionInner>> listByAgentAsync(final String resourceGroupName, final String serverName, final String jobAgentName) { return listByAgentWithServiceResponseAsync(resourceGroupName, serverName, jobAgentName) .map(new Func1<ServiceResponse<Page<JobExecutionInner>>, Page<JobExecutionInner>>() { @Override public Page<JobExecutionInner> call(ServiceResponse<Page<JobExecutionInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "JobExecutionInner", ">", ">", "listByAgentAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "serverName", ",", "final", "String", "jobAgentName", ")", "{", "return", "listByAgentWithServiceResponseA...
Lists all executions in a job agent. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobExecutionInner&gt; object
[ "Lists", "all", "executions", "in", "a", "job", "agent", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobExecutionsInner.java#L158-L166
cdk/cdk
base/standard/src/main/java/org/openscience/cdk/stereo/StereoElementFactory.java
StereoElementFactory.using3DCoordinates
public static StereoElementFactory using3DCoordinates(IAtomContainer container) { EdgeToBondMap bondMap = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bondMap); return new StereoElementFactory3D(container, graph, bondMap).checkSymmetry(true); }
java
public static StereoElementFactory using3DCoordinates(IAtomContainer container) { EdgeToBondMap bondMap = EdgeToBondMap.withSpaceFor(container); int[][] graph = GraphUtil.toAdjList(container, bondMap); return new StereoElementFactory3D(container, graph, bondMap).checkSymmetry(true); }
[ "public", "static", "StereoElementFactory", "using3DCoordinates", "(", "IAtomContainer", "container", ")", "{", "EdgeToBondMap", "bondMap", "=", "EdgeToBondMap", ".", "withSpaceFor", "(", "container", ")", ";", "int", "[", "]", "[", "]", "graph", "=", "GraphUtil",...
Create a stereo element factory for creating stereo elements using 3D coordinates and depiction labels (up/down, wedge/hatch). @param container the structure to create the factory for @return the factory instance
[ "Create", "a", "stereo", "element", "factory", "for", "creating", "stereo", "elements", "using", "3D", "coordinates", "and", "depiction", "labels", "(", "up", "/", "down", "wedge", "/", "hatch", ")", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/stereo/StereoElementFactory.java#L496-L500
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/misc/Pattern.java
Pattern.selection
public static Pattern selection(Pattern pattern1, Pattern pattern2) { if (pattern1 == null || pattern2 == null) { throw new IllegalArgumentException("Neither pattern can be null"); } return new SelectPattern(pattern1, pattern2); }
java
public static Pattern selection(Pattern pattern1, Pattern pattern2) { if (pattern1 == null || pattern2 == null) { throw new IllegalArgumentException("Neither pattern can be null"); } return new SelectPattern(pattern1, pattern2); }
[ "public", "static", "Pattern", "selection", "(", "Pattern", "pattern1", ",", "Pattern", "pattern2", ")", "{", "if", "(", "pattern1", "==", "null", "||", "pattern2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Neither pattern can b...
A pattern which matches <code>pattern1</code> followed by <code>pattern2</code> and returns the longer of the two matches. @param pattern1 @param pattern2 @return @throws IllegalArgumentException if either argument is <code>null</code>
[ "A", "pattern", "which", "matches", "<code", ">", "pattern1<", "/", "code", ">", "followed", "by", "<code", ">", "pattern2<", "/", "code", ">", "and", "returns", "the", "longer", "of", "the", "two", "matches", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/misc/Pattern.java#L163-L170
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/titlepaneforegound/TitlePaneButtonForegroundPainter.java
TitlePaneButtonForegroundPainter.paintHover
public void paintHover(Graphics2D g, JComponent c, int width, int height) { paint(g, c, width, height, hoverBorder, hoverCorner, hoverInterior); }
java
public void paintHover(Graphics2D g, JComponent c, int width, int height) { paint(g, c, width, height, hoverBorder, hoverCorner, hoverInterior); }
[ "public", "void", "paintHover", "(", "Graphics2D", "g", ",", "JComponent", "c", ",", "int", "width", ",", "int", "height", ")", "{", "paint", "(", "g", ",", "c", ",", "width", ",", "height", ",", "hoverBorder", ",", "hoverCorner", ",", "hoverInterior", ...
Paint the mouse-over state of the button foreground. @param g the Graphics2D context to paint with. @param c the button to paint. @param width the width to paint. @param height the height to paint.
[ "Paint", "the", "mouse", "-", "over", "state", "of", "the", "button", "foreground", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/titlepaneforegound/TitlePaneButtonForegroundPainter.java#L46-L48
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.createGroup
public GitlabGroup createGroup(String name, String path, String ldapCn, GitlabAccessLevel ldapAccess, GitlabUser sudoUser) throws IOException { return createGroup(name, path, ldapCn, ldapAccess, sudoUser, null); }
java
public GitlabGroup createGroup(String name, String path, String ldapCn, GitlabAccessLevel ldapAccess, GitlabUser sudoUser) throws IOException { return createGroup(name, path, ldapCn, ldapAccess, sudoUser, null); }
[ "public", "GitlabGroup", "createGroup", "(", "String", "name", ",", "String", "path", ",", "String", "ldapCn", ",", "GitlabAccessLevel", "ldapAccess", ",", "GitlabUser", "sudoUser", ")", "throws", "IOException", "{", "return", "createGroup", "(", "name", ",", "p...
Creates a Group @param name The name of the group @param path The path for the group @param ldapCn LDAP Group Name to sync with, null otherwise @param ldapAccess Access level for LDAP group members, null otherwise @param sudoUser The user to create the group on behalf of @return The GitLab Group @throws IOException on gitlab api call error
[ "Creates", "a", "Group" ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L620-L622
magro/memcached-session-manager
core/src/main/java/de/javakaffee/web/msm/MemcachedNodesManager.java
MemcachedNodesManager.setNodeAvailableForSessionId
public String setNodeAvailableForSessionId(final String sessionId, final boolean available) { if ( _nodeIdService != null && isEncodeNodeIdInSessionId() ) { final String nodeId = _sessionIdFormat.extractMemcachedId(sessionId); if ( nodeId != null ) { _nodeIdService.setNodeAvailable(nodeId, available); return nodeId; } else { LOG.warn("Got sessionId without nodeId: " + sessionId); } } return null; }
java
public String setNodeAvailableForSessionId(final String sessionId, final boolean available) { if ( _nodeIdService != null && isEncodeNodeIdInSessionId() ) { final String nodeId = _sessionIdFormat.extractMemcachedId(sessionId); if ( nodeId != null ) { _nodeIdService.setNodeAvailable(nodeId, available); return nodeId; } else { LOG.warn("Got sessionId without nodeId: " + sessionId); } } return null; }
[ "public", "String", "setNodeAvailableForSessionId", "(", "final", "String", "sessionId", ",", "final", "boolean", "available", ")", "{", "if", "(", "_nodeIdService", "!=", "null", "&&", "isEncodeNodeIdInSessionId", "(", ")", ")", "{", "final", "String", "nodeId", ...
Mark the memcached node encoded in the given sessionId as available or not. If nodeIds shall not be encoded in the sessionId or if the given sessionId does not contain a nodeId no action will be taken. @param sessionId the sessionId that may contain a node id. @param available specifies if the possibly referenced node is available or not. @return the extracted nodeId or <code>null</code>. @see #isEncodeNodeIdInSessionId()
[ "Mark", "the", "memcached", "node", "encoded", "in", "the", "given", "sessionId", "as", "available", "or", "not", ".", "If", "nodeIds", "shall", "not", "be", "encoded", "in", "the", "sessionId", "or", "if", "the", "given", "sessionId", "does", "not", "cont...
train
https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/MemcachedNodesManager.java#L482-L494
Axway/Grapes
utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java
GrapesClient.promoteModule
public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version)); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "promote module", name, version); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
java
public void promoteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{ final Client client = getClient(user, password); final WebResource resource = client.resource(serverURL).path(RequestUtils.promoteModulePath(name, version)); final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class); client.destroy(); if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){ final String message = String.format(FAILED_TO_GET_MODULE, "promote module", name, version); if(LOG.isErrorEnabled()) { LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus())); } throw new GrapesCommunicationException(message, response.getStatus()); } }
[ "public", "void", "promoteModule", "(", "final", "String", "name", ",", "final", "String", "version", ",", "final", "String", "user", ",", "final", "String", "password", ")", "throws", "GrapesCommunicationException", ",", "AuthenticationException", "{", "final", "...
Promote a module in the Grapes server @param name @param version @throws GrapesCommunicationException @throws javax.naming.AuthenticationException
[ "Promote", "a", "module", "in", "the", "Grapes", "server" ]
train
https://github.com/Axway/Grapes/blob/ce9cc73d85f83eaa5fbc991abb593915a8c8374e/utils/src/main/java/org/axway/grapes/utils/client/GrapesClient.java#L328-L341
vvakame/JsonPullParser
jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java
JsonUtil.putByteList
public static void putByteList(Writer writer, List<Byte> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
java
public static void putByteList(Writer writer, List<Byte> values) throws IOException { if (values == null) { writer.write("null"); } else { startArray(writer); for (int i = 0; i < values.size(); i++) { put(writer, values.get(i)); if (i != values.size() - 1) { addSeparator(writer); } } endArray(writer); } }
[ "public", "static", "void", "putByteList", "(", "Writer", "writer", ",", "List", "<", "Byte", ">", "values", ")", "throws", "IOException", "{", "if", "(", "values", "==", "null", ")", "{", "writer", ".", "write", "(", "\"null\"", ")", ";", "}", "else",...
Writes the given value with the given writer. @param writer @param values @throws IOException @author vvakame
[ "Writes", "the", "given", "value", "with", "the", "given", "writer", "." ]
train
https://github.com/vvakame/JsonPullParser/blob/fce183ca66354723323a77f2ae8cb5222b5836bc/jsonpullparser-core/src/main/java/net/vvakame/util/jsonpullparser/util/JsonUtil.java#L260-L273
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/ProjectApi.java
ProjectApi.forkProject
public Project forkProject(Object projectIdOrPath, String namespace) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm().withParam("namespace", namespace, true); Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.CREATED); Response response = post(expectedStatus, formData, "projects", getProjectIdOrPath(projectIdOrPath), "fork"); return (response.readEntity(Project.class)); }
java
public Project forkProject(Object projectIdOrPath, String namespace) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm().withParam("namespace", namespace, true); Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.CREATED); Response response = post(expectedStatus, formData, "projects", getProjectIdOrPath(projectIdOrPath), "fork"); return (response.readEntity(Project.class)); }
[ "public", "Project", "forkProject", "(", "Object", "projectIdOrPath", ",", "String", "namespace", ")", "throws", "GitLabApiException", "{", "GitLabApiForm", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "\"namespace\"", ",", "namespace", ...
Forks a project into the user namespace of the authenticated user or the one provided. The forking operation for a project is asynchronous and is completed in a background job. The request will return immediately. <pre><code>POST /projects/:id/fork</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param namespace path of the namespace that the project will be forked to @return the newly forked Project instance @throws GitLabApiException if any exception occurs
[ "Forks", "a", "project", "into", "the", "user", "namespace", "of", "the", "authenticated", "user", "or", "the", "one", "provided", ".", "The", "forking", "operation", "for", "a", "project", "is", "asynchronous", "and", "is", "completed", "in", "a", "backgrou...
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProjectApi.java#L1104-L1109
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updateHierarchicalEntityChildAsync
public Observable<OperationStatus> updateHierarchicalEntityChildAsync(UUID appId, String versionId, UUID hEntityId, UUID hChildId, UpdateHierarchicalEntityChildOptionalParameter updateHierarchicalEntityChildOptionalParameter) { return updateHierarchicalEntityChildWithServiceResponseAsync(appId, versionId, hEntityId, hChildId, updateHierarchicalEntityChildOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
java
public Observable<OperationStatus> updateHierarchicalEntityChildAsync(UUID appId, String versionId, UUID hEntityId, UUID hChildId, UpdateHierarchicalEntityChildOptionalParameter updateHierarchicalEntityChildOptionalParameter) { return updateHierarchicalEntityChildWithServiceResponseAsync(appId, versionId, hEntityId, hChildId, updateHierarchicalEntityChildOptionalParameter).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() { @Override public OperationStatus call(ServiceResponse<OperationStatus> response) { return response.body(); } }); }
[ "public", "Observable", "<", "OperationStatus", ">", "updateHierarchicalEntityChildAsync", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "hEntityId", ",", "UUID", "hChildId", ",", "UpdateHierarchicalEntityChildOptionalParameter", "updateHierarchicalEntityChil...
Renames a single child in an existing hierarchical entity model. @param appId The application ID. @param versionId The version ID. @param hEntityId The hierarchical entity extractor ID. @param hChildId The hierarchical entity extractor child ID. @param updateHierarchicalEntityChildOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the OperationStatus object
[ "Renames", "a", "single", "child", "in", "an", "existing", "hierarchical", "entity", "model", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L6372-L6379
eFaps/eFaps-Kernel
src/main/java/org/efaps/admin/common/SystemConfiguration.java
SystemConfiguration.getAttributeValueAsEncryptedProperties
public Properties getAttributeValueAsEncryptedProperties(final String _key, final boolean _concatenate) throws EFapsException { final Properties properties = getAttributeValueAsProperties(_key, _concatenate); final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setConfig(SystemConfiguration.getPBEConfig()); final Properties props = new EncryptableProperties(properties, encryptor); return props; }
java
public Properties getAttributeValueAsEncryptedProperties(final String _key, final boolean _concatenate) throws EFapsException { final Properties properties = getAttributeValueAsProperties(_key, _concatenate); final StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setConfig(SystemConfiguration.getPBEConfig()); final Properties props = new EncryptableProperties(properties, encryptor); return props; }
[ "public", "Properties", "getAttributeValueAsEncryptedProperties", "(", "final", "String", "_key", ",", "final", "boolean", "_concatenate", ")", "throws", "EFapsException", "{", "final", "Properties", "properties", "=", "getAttributeValueAsProperties", "(", "_key", ",", ...
Returns for given <code>_key</code> the related value as Properties. If no attribute is found an empty Properties is returned. @param _key key of searched attribute @param _concatenate is concatenate or not @return Properties @throws EFapsException on error @see #attributes
[ "Returns", "for", "given", "<code", ">", "_key<", "/", "code", ">", "the", "related", "value", "as", "Properties", ".", "If", "no", "attribute", "is", "found", "an", "empty", "Properties", "is", "returned", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/common/SystemConfiguration.java#L453-L462
protostuff/protostuff
protostuff-msgpack/src/main/java/io/protostuff/MsgpackOutput.java
MsgpackOutput.use
public MsgpackOutput use(MsgpackGenerator generator, Schema<?> schema) { this.schema = schema; this.generator = generator; return this; }
java
public MsgpackOutput use(MsgpackGenerator generator, Schema<?> schema) { this.schema = schema; this.generator = generator; return this; }
[ "public", "MsgpackOutput", "use", "(", "MsgpackGenerator", "generator", ",", "Schema", "<", "?", ">", "schema", ")", "{", "this", ".", "schema", "=", "schema", ";", "this", ".", "generator", "=", "generator", ";", "return", "this", ";", "}" ]
Before serializing a message/object tied to a schema, this should be called. This also resets the internal state of this output.
[ "Before", "serializing", "a", "message", "/", "object", "tied", "to", "a", "schema", "this", "should", "be", "called", ".", "This", "also", "resets", "the", "internal", "state", "of", "this", "output", "." ]
train
https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-msgpack/src/main/java/io/protostuff/MsgpackOutput.java#L61-L66
Wikidata/Wikidata-Toolkit
wdtk-examples/src/main/java/org/wikidata/wdtk/examples/GenderRatioProcessor.java
GenderRatioProcessor.containsValue
private boolean containsValue(StatementGroup statementGroup, Value value) { for (Statement s : statementGroup) { if (value.equals(s.getValue())) { return true; } } return false; }
java
private boolean containsValue(StatementGroup statementGroup, Value value) { for (Statement s : statementGroup) { if (value.equals(s.getValue())) { return true; } } return false; }
[ "private", "boolean", "containsValue", "(", "StatementGroup", "statementGroup", ",", "Value", "value", ")", "{", "for", "(", "Statement", "s", ":", "statementGroup", ")", "{", "if", "(", "value", ".", "equals", "(", "s", ".", "getValue", "(", ")", ")", "...
Checks if the given group of statements contains the given value as the value of a main snak of some statement. @param statementGroup the statement group to scan @param value the value to scan for @return true if value was found
[ "Checks", "if", "the", "given", "group", "of", "statements", "contains", "the", "given", "value", "as", "the", "value", "of", "a", "main", "snak", "of", "some", "statement", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-examples/src/main/java/org/wikidata/wdtk/examples/GenderRatioProcessor.java#L397-L405
bushidowallet/bushido-java-service
bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java
V2Wallet.newTransactionHandler
public void newTransactionHandler(PersistedTransaction tx, PersistedV2Key key) throws Exception { listenForUpdates(tx); tx.keyId = key.getId(); tx.walletId = this.descriptor.getKey(); tx.account = key.account; System.out.println("Incoming transaction captured in API service: " + tx.toString()); transactionDAO.create(tx); WalletChange change = new WalletChange(tx.value, getBalance(), createKey(key.account).address, tx); WalletChangeMessage out = new WalletChangeMessage(); out.setCommand(Command.BALANCE_CHANGE_RECEIVED); out.setKey(this.descriptor.key); out.setPayload(change); router.sendUpdate(this.descriptor.key, out); }
java
public void newTransactionHandler(PersistedTransaction tx, PersistedV2Key key) throws Exception { listenForUpdates(tx); tx.keyId = key.getId(); tx.walletId = this.descriptor.getKey(); tx.account = key.account; System.out.println("Incoming transaction captured in API service: " + tx.toString()); transactionDAO.create(tx); WalletChange change = new WalletChange(tx.value, getBalance(), createKey(key.account).address, tx); WalletChangeMessage out = new WalletChangeMessage(); out.setCommand(Command.BALANCE_CHANGE_RECEIVED); out.setKey(this.descriptor.key); out.setPayload(change); router.sendUpdate(this.descriptor.key, out); }
[ "public", "void", "newTransactionHandler", "(", "PersistedTransaction", "tx", ",", "PersistedV2Key", "key", ")", "throws", "Exception", "{", "listenForUpdates", "(", "tx", ")", ";", "tx", ".", "keyId", "=", "key", ".", "getId", "(", ")", ";", "tx", ".", "w...
New transaction handler, incoming funds only based on BIP32 derived key @param tx - incoming funds transaction @param key - related V2Key @throws Exception
[ "New", "transaction", "handler", "incoming", "funds", "only", "based", "on", "BIP32", "derived", "key" ]
train
https://github.com/bushidowallet/bushido-java-service/blob/e1a0157527e57459b509718044d2df44084876a2/bushido-wallet-service/src/main/java/com/bitcoin/blockchain/api/service/v2wallet/V2Wallet.java#L206-L219
hankcs/HanLP
src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java
TfIdf.tfIdf
public static <TERM> Map<TERM, Double> tfIdf(Map<TERM, Double> tf, Map<TERM, Double> idf) { return tfIdf(tf, idf, Normalization.NONE); }
java
public static <TERM> Map<TERM, Double> tfIdf(Map<TERM, Double> tf, Map<TERM, Double> idf) { return tfIdf(tf, idf, Normalization.NONE); }
[ "public", "static", "<", "TERM", ">", "Map", "<", "TERM", ",", "Double", ">", "tfIdf", "(", "Map", "<", "TERM", ",", "Double", ">", "tf", ",", "Map", "<", "TERM", ",", "Double", ">", "idf", ")", "{", "return", "tfIdf", "(", "tf", ",", "idf", ",...
计算文档的tf-idf(不正规化) @param tf 词频 @param idf 倒排频率 @param <TERM> 词语类型 @return 一个词语->tf-idf的Map
[ "计算文档的tf", "-", "idf(不正规化)" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/mining/word/TfIdf.java#L217-L220
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java
JsonStringToJsonIntermediateConverter.parseEnumType
private JsonElement parseEnumType(JsonSchema schema, JsonElement value) throws DataConversionException { if (schema.getSymbols().contains(value)) { return value; } throw new DataConversionException( "Invalid symbol: " + value.getAsString() + " allowed values: " + schema.getSymbols().toString()); }
java
private JsonElement parseEnumType(JsonSchema schema, JsonElement value) throws DataConversionException { if (schema.getSymbols().contains(value)) { return value; } throw new DataConversionException( "Invalid symbol: " + value.getAsString() + " allowed values: " + schema.getSymbols().toString()); }
[ "private", "JsonElement", "parseEnumType", "(", "JsonSchema", "schema", ",", "JsonElement", "value", ")", "throws", "DataConversionException", "{", "if", "(", "schema", ".", "getSymbols", "(", ")", ".", "contains", "(", "value", ")", ")", "{", "return", "value...
Parses Enum type values @param schema @param value @return @throws DataConversionException
[ "Parses", "Enum", "type", "values" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonStringToJsonIntermediateConverter.java#L167-L174
julianhyde/sqlline
src/main/java/sqlline/Commands.java
Commands.record
public void record(String line, DispatchCallback callback) { if (sqlLine.getRecordOutputFile() == null) { startRecording(line, callback); } else { stopRecording(line, callback); } }
java
public void record(String line, DispatchCallback callback) { if (sqlLine.getRecordOutputFile() == null) { startRecording(line, callback); } else { stopRecording(line, callback); } }
[ "public", "void", "record", "(", "String", "line", ",", "DispatchCallback", "callback", ")", "{", "if", "(", "sqlLine", ".", "getRecordOutputFile", "(", ")", "==", "null", ")", "{", "startRecording", "(", "line", ",", "callback", ")", ";", "}", "else", "...
Starts or stops saving all output to a file. @param line Command line @param callback Callback for command status
[ "Starts", "or", "stops", "saving", "all", "output", "to", "a", "file", "." ]
train
https://github.com/julianhyde/sqlline/blob/7577f3ebaca0897a9ff01d1553d4576487e1d2c3/src/main/java/sqlline/Commands.java#L1555-L1561
actframework/actframework
src/main/java/act/ws/WebSocketConnectionManager.java
WebSocketConnectionManager.sendToTagged
public void sendToTagged(String message, String ... labels) { for (String label : labels) { sendToTagged(message, label); } }
java
public void sendToTagged(String message, String ... labels) { for (String label : labels) { sendToTagged(message, label); } }
[ "public", "void", "sendToTagged", "(", "String", "message", ",", "String", "...", "labels", ")", "{", "for", "(", "String", "label", ":", "labels", ")", "{", "sendToTagged", "(", "message", ",", "label", ")", ";", "}", "}" ]
Send message to all connections tagged with all given tags @param message the message @param labels the tag labels
[ "Send", "message", "to", "all", "connections", "tagged", "with", "all", "given", "tags" ]
train
https://github.com/actframework/actframework/blob/55a8f8b45e71159a79ec6e157c02f71700f8cd54/src/main/java/act/ws/WebSocketConnectionManager.java#L147-L151
osglworks/java-mvc
src/main/java/org/osgl/mvc/result/NotImplemented.java
NotImplemented.of
public static NotImplemented of(Throwable cause) { if (_localizedErrorMsg()) { return of(cause, defaultMessage(NOT_IMPLEMENTED)); } else { touchPayload().cause(cause); return _INSTANCE; } }
java
public static NotImplemented of(Throwable cause) { if (_localizedErrorMsg()) { return of(cause, defaultMessage(NOT_IMPLEMENTED)); } else { touchPayload().cause(cause); return _INSTANCE; } }
[ "public", "static", "NotImplemented", "of", "(", "Throwable", "cause", ")", "{", "if", "(", "_localizedErrorMsg", "(", ")", ")", "{", "return", "of", "(", "cause", ",", "defaultMessage", "(", "NOT_IMPLEMENTED", ")", ")", ";", "}", "else", "{", "touchPayloa...
Returns a static NotImplemented instance and set the {@link #payload} thread local with cause specified. When calling the instance on {@link #getMessage()} method, it will return whatever stored in the {@link #payload} thread local @param cause the cause @return a static NotImplemented instance as described above
[ "Returns", "a", "static", "NotImplemented", "instance", "and", "set", "the", "{", "@link", "#payload", "}", "thread", "local", "with", "cause", "specified", "." ]
train
https://github.com/osglworks/java-mvc/blob/4d2b2ec40498ac6ee7040c0424377cbeacab124b/src/main/java/org/osgl/mvc/result/NotImplemented.java#L128-L135
unbescape/unbescape
src/main/java/org/unbescape/html/HtmlEscape.java
HtmlEscape.escapeHtml
public static void escapeHtml(final String text, final Writer writer, final HtmlEscapeType type, final HtmlEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (type == null) { throw new IllegalArgumentException("The 'type' argument cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } HtmlEscapeUtil.escape(new InternalStringReader(text), writer, type, level); }
java
public static void escapeHtml(final String text, final Writer writer, final HtmlEscapeType type, final HtmlEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (type == null) { throw new IllegalArgumentException("The 'type' argument cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } HtmlEscapeUtil.escape(new InternalStringReader(text), writer, type, level); }
[ "public", "static", "void", "escapeHtml", "(", "final", "String", "text", ",", "final", "Writer", "writer", ",", "final", "HtmlEscapeType", "type", ",", "final", "HtmlEscapeLevel", "level", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ...
<p> Perform a (configurable) HTML <strong>escape</strong> operation on a <tt>String</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.html.HtmlEscapeType} and {@link org.unbescape.html.HtmlEscapeLevel} argument values. </p> <p> All other <tt>String</tt>/<tt>Writer</tt>-based <tt>escapeHtml*(...)</tt> methods call this one with preconfigured <tt>type</tt> and <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @param type the type of escape operation to be performed, see {@link org.unbescape.html.HtmlEscapeType}. @param level the escape level to be applied, see {@link org.unbescape.html.HtmlEscapeLevel}. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "HTML", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">"...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/html/HtmlEscape.java#L573-L590
samskivert/pythagoras
src/main/java/pythagoras/f/Box.java
Box.intersectionY
protected float intersectionY (IRay3 ray, float y) { IVector3 origin = ray.origin(), dir = ray.direction(); float t = (y - origin.y()) / dir.y(); if (t < 0f) { return Float.MAX_VALUE; } float ix = origin.x() + t*dir.x(), iz = origin.z() + t*dir.z(); return (ix >= _minExtent.x && ix <= _maxExtent.x && iz >= _minExtent.z && iz <= _maxExtent.z) ? t : Float.MAX_VALUE; }
java
protected float intersectionY (IRay3 ray, float y) { IVector3 origin = ray.origin(), dir = ray.direction(); float t = (y - origin.y()) / dir.y(); if (t < 0f) { return Float.MAX_VALUE; } float ix = origin.x() + t*dir.x(), iz = origin.z() + t*dir.z(); return (ix >= _minExtent.x && ix <= _maxExtent.x && iz >= _minExtent.z && iz <= _maxExtent.z) ? t : Float.MAX_VALUE; }
[ "protected", "float", "intersectionY", "(", "IRay3", "ray", ",", "float", "y", ")", "{", "IVector3", "origin", "=", "ray", ".", "origin", "(", ")", ",", "dir", "=", "ray", ".", "direction", "(", ")", ";", "float", "t", "=", "(", "y", "-", "origin",...
Helper method for {@link #intersection}. Finds the <code>t</code> value where the ray intersects the box at the plane where y equals the value specified, or returns {@link Float#MAX_VALUE} if there is no such intersection.
[ "Helper", "method", "for", "{" ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/Box.java#L496-L505
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java
PersonGroupPersonsImpl.getFace
public PersistedFace getFace(String personGroupId, UUID personId, UUID persistedFaceId) { return getFaceWithServiceResponseAsync(personGroupId, personId, persistedFaceId).toBlocking().single().body(); }
java
public PersistedFace getFace(String personGroupId, UUID personId, UUID persistedFaceId) { return getFaceWithServiceResponseAsync(personGroupId, personId, persistedFaceId).toBlocking().single().body(); }
[ "public", "PersistedFace", "getFace", "(", "String", "personGroupId", ",", "UUID", "personId", ",", "UUID", "persistedFaceId", ")", "{", "return", "getFaceWithServiceResponseAsync", "(", "personGroupId", ",", "personId", ",", "persistedFaceId", ")", ".", "toBlocking",...
Retrieve information about a persisted face (specified by persistedFaceId, personId and its belonging personGroupId). @param personGroupId Id referencing a particular person group. @param personId Id referencing a particular person. @param persistedFaceId Id referencing a particular persistedFaceId of an existing face. @throws IllegalArgumentException thrown if parameters fail the validation @throws APIErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the PersistedFace object if successful.
[ "Retrieve", "information", "about", "a", "persisted", "face", "(", "specified", "by", "persistedFaceId", "personId", "and", "its", "belonging", "personGroupId", ")", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/faceapi/src/main/java/com/microsoft/azure/cognitiveservices/vision/faceapi/implementation/PersonGroupPersonsImpl.java#L890-L892
aws/aws-sdk-java
aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/DevEndpoint.java
DevEndpoint.withArguments
public DevEndpoint withArguments(java.util.Map<String, String> arguments) { setArguments(arguments); return this; }
java
public DevEndpoint withArguments(java.util.Map<String, String> arguments) { setArguments(arguments); return this; }
[ "public", "DevEndpoint", "withArguments", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "arguments", ")", "{", "setArguments", "(", "arguments", ")", ";", "return", "this", ";", "}" ]
<p> A map of arguments used to configure the DevEndpoint. </p> <p> Note that currently, we only support "--enable-glue-datacatalog": "" as a valid argument. </p> @param arguments A map of arguments used to configure the DevEndpoint.</p> <p> Note that currently, we only support "--enable-glue-datacatalog": "" as a valid argument. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "arguments", "used", "to", "configure", "the", "DevEndpoint", ".", "<", "/", "p", ">", "<p", ">", "Note", "that", "currently", "we", "only", "support", "--", "enable", "-", "glue", "-", "datacatalog", ":", "as", "a", "val...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/DevEndpoint.java#L1270-L1273
spring-projects/spring-ldap
core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java
TransactionAwareDirContextInvocationHandler.doCloseConnection
void doCloseConnection(DirContext context, ContextSource contextSource) throws javax.naming.NamingException { DirContextHolder transactionContextHolder = (DirContextHolder) TransactionSynchronizationManager .getResource(contextSource); if (transactionContextHolder == null || transactionContextHolder.getCtx() != context) { log.debug("Closing context"); // This is not the transactional context or the transaction is // no longer active - we should close it. context.close(); } else { log.debug("Leaving transactional context open"); } }
java
void doCloseConnection(DirContext context, ContextSource contextSource) throws javax.naming.NamingException { DirContextHolder transactionContextHolder = (DirContextHolder) TransactionSynchronizationManager .getResource(contextSource); if (transactionContextHolder == null || transactionContextHolder.getCtx() != context) { log.debug("Closing context"); // This is not the transactional context or the transaction is // no longer active - we should close it. context.close(); } else { log.debug("Leaving transactional context open"); } }
[ "void", "doCloseConnection", "(", "DirContext", "context", ",", "ContextSource", "contextSource", ")", "throws", "javax", ".", "naming", ".", "NamingException", "{", "DirContextHolder", "transactionContextHolder", "=", "(", "DirContextHolder", ")", "TransactionSynchroniza...
Close the supplied context, but only if it is not associated with the current transaction. @param context the DirContext to close. @param contextSource the ContextSource bound to the transaction. @throws NamingException
[ "Close", "the", "supplied", "context", "but", "only", "if", "it", "is", "not", "associated", "with", "the", "current", "transaction", "." ]
train
https://github.com/spring-projects/spring-ldap/blob/15142d4ae18a9dc6b363a1ebf085e2bda9d9a4c0/core/src/main/java/org/springframework/ldap/transaction/compensating/manager/TransactionAwareDirContextInvocationHandler.java#L107-L120
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java
ValueRange.checkValidValue
public long checkValidValue(long value, TemporalField field) { if (isValidValue(value) == false) { throw new DateTimeException(genInvalidFieldMessage(field, value)); } return value; }
java
public long checkValidValue(long value, TemporalField field) { if (isValidValue(value) == false) { throw new DateTimeException(genInvalidFieldMessage(field, value)); } return value; }
[ "public", "long", "checkValidValue", "(", "long", "value", ",", "TemporalField", "field", ")", "{", "if", "(", "isValidValue", "(", "value", ")", "==", "false", ")", "{", "throw", "new", "DateTimeException", "(", "genInvalidFieldMessage", "(", "field", ",", ...
Checks that the specified value is valid. <p> This validates that the value is within the valid range of values. The field is only used to improve the error message. @param value the value to check @param field the field being checked, may be null @return the value that was passed in @see #isValidValue(long)
[ "Checks", "that", "the", "specified", "value", "is", "valid", ".", "<p", ">", "This", "validates", "that", "the", "value", "is", "within", "the", "valid", "range", "of", "values", ".", "The", "field", "is", "only", "used", "to", "improve", "the", "error"...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/time/temporal/ValueRange.java#L309-L314
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java
FieldUtils.writeStaticField
public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value, final boolean forceAccess) throws IllegalAccessException { final Field field = getField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls); // already forced access above, don't repeat it here: writeStaticField(field, value, false); }
java
public static void writeStaticField(final Class<?> cls, final String fieldName, final Object value, final boolean forceAccess) throws IllegalAccessException { final Field field = getField(cls, fieldName, forceAccess); Validate.isTrue(field != null, "Cannot locate field %s on %s", fieldName, cls); // already forced access above, don't repeat it here: writeStaticField(field, value, false); }
[ "public", "static", "void", "writeStaticField", "(", "final", "Class", "<", "?", ">", "cls", ",", "final", "String", "fieldName", ",", "final", "Object", "value", ",", "final", "boolean", "forceAccess", ")", "throws", "IllegalAccessException", "{", "final", "F...
Writes a named {@code static} {@link Field}. Superclasses will be considered. @param cls {@link Class} on which the field is to be found @param fieldName to write @param value to set @param forceAccess whether to break scope restrictions using the {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will only match {@code public} fields. @throws IllegalArgumentException if {@code cls} is {@code null}, the field name is blank or empty, the field cannot be located or is not {@code static}, or {@code value} is not assignable @throws IllegalAccessException if the field is not made accessible or is {@code final}
[ "Writes", "a", "named", "{", "@code", "static", "}", "{", "@link", "Field", "}", ".", "Superclasses", "will", "be", "considered", "." ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/reflect/FieldUtils.java#L595-L601
roboconf/roboconf-platform
core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java
Utils.copyStream
public static void copyStream( File inputFile, File outputFile ) throws IOException { InputStream is = new FileInputStream( inputFile ); try { copyStream( is, outputFile ); } finally { is.close(); } }
java
public static void copyStream( File inputFile, File outputFile ) throws IOException { InputStream is = new FileInputStream( inputFile ); try { copyStream( is, outputFile ); } finally { is.close(); } }
[ "public", "static", "void", "copyStream", "(", "File", "inputFile", ",", "File", "outputFile", ")", "throws", "IOException", "{", "InputStream", "is", "=", "new", "FileInputStream", "(", "inputFile", ")", ";", "try", "{", "copyStream", "(", "is", ",", "outpu...
Copies the content from inputFile into outputFile. @param inputFile an input file (must be a file and exist) @param outputFile will be created if it does not exist @throws IOException if something went wrong
[ "Copies", "the", "content", "from", "inputFile", "into", "outputFile", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-core/src/main/java/net/roboconf/core/utils/Utils.java#L371-L378
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/collection/LazyList.java
LazyList.toArray
public static Object toArray(Object list, Class<?> clazz) { if (list == null) return Array.newInstance(clazz, 0); if (list instanceof List) { List<?> l = (List<?>) list; if (clazz.isPrimitive()) { Object a = Array.newInstance(clazz, l.size()); for (int i = 0; i < l.size(); i++) Array.set(a, i, l.get(i)); return a; } return l.toArray((Object[]) Array.newInstance(clazz, l.size())); } Object a = Array.newInstance(clazz, 1); Array.set(a, 0, list); return a; }
java
public static Object toArray(Object list, Class<?> clazz) { if (list == null) return Array.newInstance(clazz, 0); if (list instanceof List) { List<?> l = (List<?>) list; if (clazz.isPrimitive()) { Object a = Array.newInstance(clazz, l.size()); for (int i = 0; i < l.size(); i++) Array.set(a, i, l.get(i)); return a; } return l.toArray((Object[]) Array.newInstance(clazz, l.size())); } Object a = Array.newInstance(clazz, 1); Array.set(a, 0, list); return a; }
[ "public", "static", "Object", "toArray", "(", "Object", "list", ",", "Class", "<", "?", ">", "clazz", ")", "{", "if", "(", "list", "==", "null", ")", "return", "Array", ".", "newInstance", "(", "clazz", ",", "0", ")", ";", "if", "(", "list", "insta...
Convert a lazylist to an array @param list The list to convert @param clazz The class of the array, which may be a primitive type @return array of the lazylist entries passed in
[ "Convert", "a", "lazylist", "to", "an", "array" ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/collection/LazyList.java#L276-L295
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Searches.java
Searches.findFirst
public static <E> E findFirst(Iterable<E> iterable, Predicate<E> predicate) { dbc.precondition(iterable != null, "cannot findFirst with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), predicate); return new FirstElement<E>().apply(filtered); }
java
public static <E> E findFirst(Iterable<E> iterable, Predicate<E> predicate) { dbc.precondition(iterable != null, "cannot findFirst with a null iterable"); final Iterator<E> filtered = new FilteringIterator<E>(iterable.iterator(), predicate); return new FirstElement<E>().apply(filtered); }
[ "public", "static", "<", "E", ">", "E", "findFirst", "(", "Iterable", "<", "E", ">", "iterable", ",", "Predicate", "<", "E", ">", "predicate", ")", "{", "dbc", ".", "precondition", "(", "iterable", "!=", "null", ",", "\"cannot findFirst with a null iterable\...
Searches the first matching element returning it. @param <E> the element type parameter @param iterable the iterable to be searched @param predicate the predicate to be applied to each element @throws IllegalArgumentException if no element matches @return the found element
[ "Searches", "the", "first", "matching", "element", "returning", "it", "." ]
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Searches.java#L434-L438
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/SelectBuilder.java
SelectBuilder.orderBy
public SelectBuilder orderBy(String name, boolean ascending) { if (ascending) { orderBys.add(name + " asc"); } else { orderBys.add(name + " desc"); } return this; }
java
public SelectBuilder orderBy(String name, boolean ascending) { if (ascending) { orderBys.add(name + " asc"); } else { orderBys.add(name + " desc"); } return this; }
[ "public", "SelectBuilder", "orderBy", "(", "String", "name", ",", "boolean", "ascending", ")", "{", "if", "(", "ascending", ")", "{", "orderBys", ".", "add", "(", "name", "+", "\" asc\"", ")", ";", "}", "else", "{", "orderBys", ".", "add", "(", "name",...
Adds an ORDER BY item with a direction indicator. @param name Name of the column by which to sort. @param ascending If true, specifies the direction "asc", otherwise, specifies the direction "desc".
[ "Adds", "an", "ORDER", "BY", "item", "with", "a", "direction", "indicator", "." ]
train
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/SelectBuilder.java#L248-L255
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java
DateUtil.formatBetween
public static String formatBetween(Date beginDate, Date endDate, BetweenFormater.Level level) { return formatBetween(between(beginDate, endDate, DateUnit.MS), level); }
java
public static String formatBetween(Date beginDate, Date endDate, BetweenFormater.Level level) { return formatBetween(between(beginDate, endDate, DateUnit.MS), level); }
[ "public", "static", "String", "formatBetween", "(", "Date", "beginDate", ",", "Date", "endDate", ",", "BetweenFormater", ".", "Level", "level", ")", "{", "return", "formatBetween", "(", "between", "(", "beginDate", ",", "endDate", ",", "DateUnit", ".", "MS", ...
格式化日期间隔输出 @param beginDate 起始日期 @param endDate 结束日期 @param level 级别,按照天、小时、分、秒、毫秒分为5个等级 @return XX天XX小时XX分XX秒
[ "格式化日期间隔输出" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1318-L1320
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PacketCapturesInner.java
PacketCapturesInner.createAsync
public Observable<PacketCaptureResultInner> createAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) { return createWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).map(new Func1<ServiceResponse<PacketCaptureResultInner>, PacketCaptureResultInner>() { @Override public PacketCaptureResultInner call(ServiceResponse<PacketCaptureResultInner> response) { return response.body(); } }); }
java
public Observable<PacketCaptureResultInner> createAsync(String resourceGroupName, String networkWatcherName, String packetCaptureName, PacketCaptureInner parameters) { return createWithServiceResponseAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).map(new Func1<ServiceResponse<PacketCaptureResultInner>, PacketCaptureResultInner>() { @Override public PacketCaptureResultInner call(ServiceResponse<PacketCaptureResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "PacketCaptureResultInner", ">", "createAsync", "(", "String", "resourceGroupName", ",", "String", "networkWatcherName", ",", "String", "packetCaptureName", ",", "PacketCaptureInner", "parameters", ")", "{", "return", "createWithServiceResponseA...
Create and start a packet capture on the specified VM. @param resourceGroupName The name of the resource group. @param networkWatcherName The name of the network watcher. @param packetCaptureName The name of the packet capture session. @param parameters Parameters that define the create packet capture operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "and", "start", "a", "packet", "capture", "on", "the", "specified", "VM", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PacketCapturesInner.java#L147-L154
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/appfw/appfwsignatures.java
appfwsignatures.get
public static appfwsignatures get(nitro_service service, String name) throws Exception{ appfwsignatures obj = new appfwsignatures(); obj.set_name(name); appfwsignatures response = (appfwsignatures) obj.get_resource(service); return response; }
java
public static appfwsignatures get(nitro_service service, String name) throws Exception{ appfwsignatures obj = new appfwsignatures(); obj.set_name(name); appfwsignatures response = (appfwsignatures) obj.get_resource(service); return response; }
[ "public", "static", "appfwsignatures", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "appfwsignatures", "obj", "=", "new", "appfwsignatures", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "app...
Use this API to fetch appfwsignatures resource of given name .
[ "Use", "this", "API", "to", "fetch", "appfwsignatures", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/appfw/appfwsignatures.java#L330-L335
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/ModifyBeanHelper.java
ModifyBeanHelper.buildReturnCode
public void buildReturnCode(MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) { if (returnType == TypeName.VOID) { } else if (isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) { methodBuilder.addJavadoc("\n"); if (updateMode) methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise"); else methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise"); methodBuilder.addJavadoc("\n"); methodBuilder.addCode("return result!=0;\n"); } else if (isTypeIncludedIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) { methodBuilder.addJavadoc("\n"); if (updateMode) { methodBuilder.addJavadoc("@return number of updated records"); } else { methodBuilder.addJavadoc("@return number of deleted records"); } methodBuilder.addJavadoc("\n"); methodBuilder.addCode("return result;\n"); } else { // more than one listener found throw (new InvalidMethodSignException(method, "invalid return type")); } }
java
public void buildReturnCode(MethodSpec.Builder methodBuilder, boolean updateMode, SQLiteModelMethod method, TypeName returnType) { if (returnType == TypeName.VOID) { } else if (isTypeIncludedIn(returnType, Boolean.TYPE, Boolean.class)) { methodBuilder.addJavadoc("\n"); if (updateMode) methodBuilder.addJavadoc("@return <code>true</code> if record is updated, <code>false</code> otherwise"); else methodBuilder.addJavadoc("@return <code>true</code> if record is deleted, <code>false</code> otherwise"); methodBuilder.addJavadoc("\n"); methodBuilder.addCode("return result!=0;\n"); } else if (isTypeIncludedIn(returnType, Long.TYPE, Long.class, Integer.TYPE, Integer.class, Short.TYPE, Short.class)) { methodBuilder.addJavadoc("\n"); if (updateMode) { methodBuilder.addJavadoc("@return number of updated records"); } else { methodBuilder.addJavadoc("@return number of deleted records"); } methodBuilder.addJavadoc("\n"); methodBuilder.addCode("return result;\n"); } else { // more than one listener found throw (new InvalidMethodSignException(method, "invalid return type")); } }
[ "public", "void", "buildReturnCode", "(", "MethodSpec", ".", "Builder", "methodBuilder", ",", "boolean", "updateMode", ",", "SQLiteModelMethod", "method", ",", "TypeName", "returnType", ")", "{", "if", "(", "returnType", "==", "TypeName", ".", "VOID", ")", "{", ...
Builds the return code. @param methodBuilder the method builder @param updateMode the update mode @param method the method @param returnType the return type
[ "Builds", "the", "return", "code", "." ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/ModifyBeanHelper.java#L256-L282
hibernate/hibernate-metamodelgen
src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java
TypeUtils.getAccessTypeInCaseElementIsRoot
private static AccessType getAccessTypeInCaseElementIsRoot(TypeElement searchedElement, Context context) { List<? extends Element> myMembers = searchedElement.getEnclosedElements(); for ( Element subElement : myMembers ) { List<? extends AnnotationMirror> entityAnnotations = context.getElementUtils().getAllAnnotationMirrors( subElement ); for ( Object entityAnnotation : entityAnnotations ) { AnnotationMirror annotationMirror = (AnnotationMirror) entityAnnotation; if ( isIdAnnotation( annotationMirror ) ) { return getAccessTypeOfIdAnnotation( subElement ); } } } return null; }
java
private static AccessType getAccessTypeInCaseElementIsRoot(TypeElement searchedElement, Context context) { List<? extends Element> myMembers = searchedElement.getEnclosedElements(); for ( Element subElement : myMembers ) { List<? extends AnnotationMirror> entityAnnotations = context.getElementUtils().getAllAnnotationMirrors( subElement ); for ( Object entityAnnotation : entityAnnotations ) { AnnotationMirror annotationMirror = (AnnotationMirror) entityAnnotation; if ( isIdAnnotation( annotationMirror ) ) { return getAccessTypeOfIdAnnotation( subElement ); } } } return null; }
[ "private", "static", "AccessType", "getAccessTypeInCaseElementIsRoot", "(", "TypeElement", "searchedElement", ",", "Context", "context", ")", "{", "List", "<", "?", "extends", "Element", ">", "myMembers", "=", "searchedElement", ".", "getEnclosedElements", "(", ")", ...
Iterates all elements of a type to check whether they contain the id annotation. If so the placement of this annotation determines the access type @param searchedElement the type to be searched @param context The global execution context @return returns the access type of the element annotated with the id annotation. If no element is annotated {@code null} is returned.
[ "Iterates", "all", "elements", "of", "a", "type", "to", "check", "whether", "they", "contain", "the", "id", "annotation", ".", "If", "so", "the", "placement", "of", "this", "annotation", "determines", "the", "access", "type" ]
train
https://github.com/hibernate/hibernate-metamodelgen/blob/2c87b262bc03b1a5a541789fc00c54e0531a36b2/src/main/java/org/hibernate/jpamodelgen/util/TypeUtils.java#L340-L353
Jasig/uPortal
uPortal-portlets/src/main/java/org/apereo/portal/portlets/account/selfedit/AccountPasswordFormValidator.java
AccountPasswordFormValidator.validateEnterPassword
public void validateEnterPassword(AccountPasswordForm form, MessageContext context) { // ensure that a current account password was entered if (StringUtils.isBlank(form.getCurrentPassword())) { context.addMessage( new MessageBuilder() .error() .source("currentPassword") .code("please.enter.current.password") .defaultText("Please enter your current password") .build()); } // check to see if the provided password matches the current account // password else { ILocalAccountPerson account = accountDao.getPerson(form.getUserId()); if (!passwordService.validatePassword( form.getCurrentPassword(), account.getPassword())) { context.addMessage( new MessageBuilder() .error() .source("currentPassword") .code("current.password.doesnt.match") .defaultText( "Provided password does not match the current account password") .build()); } } // ensure a new account password was entered if (StringUtils.isBlank(form.getNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("newPassword") .code("please.enter.new.password") .defaultText("Please enter a new password") .build()); } // ensure a new account password confirmation was entered if (StringUtils.isBlank(form.getConfirmNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("confirmNewPassword") .code("please.enter.confirm.password") .defaultText("Please confirm your new password") .build()); } // ensure the new password and new password confirmation match if (StringUtils.isNotBlank(form.getNewPassword()) && StringUtils.isNotBlank(form.getConfirmNewPassword()) && !form.getNewPassword().equals(form.getConfirmNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("confirmPassword") .code("passwords.must.match") .defaultText("Passwords must match") .build()); } }
java
public void validateEnterPassword(AccountPasswordForm form, MessageContext context) { // ensure that a current account password was entered if (StringUtils.isBlank(form.getCurrentPassword())) { context.addMessage( new MessageBuilder() .error() .source("currentPassword") .code("please.enter.current.password") .defaultText("Please enter your current password") .build()); } // check to see if the provided password matches the current account // password else { ILocalAccountPerson account = accountDao.getPerson(form.getUserId()); if (!passwordService.validatePassword( form.getCurrentPassword(), account.getPassword())) { context.addMessage( new MessageBuilder() .error() .source("currentPassword") .code("current.password.doesnt.match") .defaultText( "Provided password does not match the current account password") .build()); } } // ensure a new account password was entered if (StringUtils.isBlank(form.getNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("newPassword") .code("please.enter.new.password") .defaultText("Please enter a new password") .build()); } // ensure a new account password confirmation was entered if (StringUtils.isBlank(form.getConfirmNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("confirmNewPassword") .code("please.enter.confirm.password") .defaultText("Please confirm your new password") .build()); } // ensure the new password and new password confirmation match if (StringUtils.isNotBlank(form.getNewPassword()) && StringUtils.isNotBlank(form.getConfirmNewPassword()) && !form.getNewPassword().equals(form.getConfirmNewPassword())) { context.addMessage( new MessageBuilder() .error() .source("confirmPassword") .code("passwords.must.match") .defaultText("Passwords must match") .build()); } }
[ "public", "void", "validateEnterPassword", "(", "AccountPasswordForm", "form", ",", "MessageContext", "context", ")", "{", "// ensure that a current account password was entered", "if", "(", "StringUtils", ".", "isBlank", "(", "form", ".", "getCurrentPassword", "(", ")", ...
/* NB: This validation method correctly matches a state defined in the edit-account flow, but there doesn't appear currently to be a way to enter it.
[ "/", "*", "NB", ":", "This", "validation", "method", "correctly", "matches", "a", "state", "defined", "in", "the", "edit", "-", "account", "flow", "but", "there", "doesn", "t", "appear", "currently", "to", "be", "a", "way", "to", "enter", "it", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-portlets/src/main/java/org/apereo/portal/portlets/account/selfedit/AccountPasswordFormValidator.java#L52-L118
phax/ph-oton
ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java
MarkdownHelper.readRawUntil
public static int readRawUntil (final StringBuilder out, final String in, final int start, final char end) { int pos = start; while (pos < in.length ()) { final char ch = in.charAt (pos); if (ch == end) break; out.append (ch); pos++; } return (pos == in.length ()) ? -1 : pos; }
java
public static int readRawUntil (final StringBuilder out, final String in, final int start, final char end) { int pos = start; while (pos < in.length ()) { final char ch = in.charAt (pos); if (ch == end) break; out.append (ch); pos++; } return (pos == in.length ()) ? -1 : pos; }
[ "public", "static", "int", "readRawUntil", "(", "final", "StringBuilder", "out", ",", "final", "String", "in", ",", "final", "int", "start", ",", "final", "char", "end", ")", "{", "int", "pos", "=", "start", ";", "while", "(", "pos", "<", "in", ".", ...
Reads characters until the end character is encountered, ignoring escape sequences. @param out The StringBuilder to write to. @param in The Input String. @param start Starting position. @param end End characters. @return The new position or -1 if no 'end' char was found.
[ "Reads", "characters", "until", "the", "end", "character", "is", "encountered", "ignoring", "escape", "sequences", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-html/src/main/java/com/helger/html/markdown/MarkdownHelper.java#L337-L350
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java
UCharacter.getStringPropertyValue
@Deprecated ///CLOVER:OFF public static String getStringPropertyValue(int propertyEnum, int codepoint, int nameChoice) { if ((propertyEnum >= UProperty.BINARY_START && propertyEnum < UProperty.BINARY_LIMIT) || (propertyEnum >= UProperty.INT_START && propertyEnum < UProperty.INT_LIMIT)) { return getPropertyValueName(propertyEnum, getIntPropertyValue(codepoint, propertyEnum), nameChoice); } if (propertyEnum == UProperty.NUMERIC_VALUE) { return String.valueOf(getUnicodeNumericValue(codepoint)); } // otherwise must be string property switch (propertyEnum) { case UProperty.AGE: return getAge(codepoint).toString(); case UProperty.ISO_COMMENT: return getISOComment(codepoint); case UProperty.BIDI_MIRRORING_GLYPH: return toString(getMirror(codepoint)); case UProperty.CASE_FOLDING: return toString(foldCase(codepoint, true)); case UProperty.LOWERCASE_MAPPING: return toString(toLowerCase(codepoint)); case UProperty.NAME: return getName(codepoint); case UProperty.SIMPLE_CASE_FOLDING: return toString(foldCase(codepoint, true)); case UProperty.SIMPLE_LOWERCASE_MAPPING: return toString(toLowerCase(codepoint)); case UProperty.SIMPLE_TITLECASE_MAPPING: return toString(toTitleCase(codepoint)); case UProperty.SIMPLE_UPPERCASE_MAPPING: return toString(toUpperCase(codepoint)); case UProperty.TITLECASE_MAPPING: return toString(toTitleCase(codepoint)); case UProperty.UNICODE_1_NAME: return getName1_0(codepoint); case UProperty.UPPERCASE_MAPPING: return toString(toUpperCase(codepoint)); } throw new IllegalArgumentException("Illegal Property Enum"); }
java
@Deprecated ///CLOVER:OFF public static String getStringPropertyValue(int propertyEnum, int codepoint, int nameChoice) { if ((propertyEnum >= UProperty.BINARY_START && propertyEnum < UProperty.BINARY_LIMIT) || (propertyEnum >= UProperty.INT_START && propertyEnum < UProperty.INT_LIMIT)) { return getPropertyValueName(propertyEnum, getIntPropertyValue(codepoint, propertyEnum), nameChoice); } if (propertyEnum == UProperty.NUMERIC_VALUE) { return String.valueOf(getUnicodeNumericValue(codepoint)); } // otherwise must be string property switch (propertyEnum) { case UProperty.AGE: return getAge(codepoint).toString(); case UProperty.ISO_COMMENT: return getISOComment(codepoint); case UProperty.BIDI_MIRRORING_GLYPH: return toString(getMirror(codepoint)); case UProperty.CASE_FOLDING: return toString(foldCase(codepoint, true)); case UProperty.LOWERCASE_MAPPING: return toString(toLowerCase(codepoint)); case UProperty.NAME: return getName(codepoint); case UProperty.SIMPLE_CASE_FOLDING: return toString(foldCase(codepoint, true)); case UProperty.SIMPLE_LOWERCASE_MAPPING: return toString(toLowerCase(codepoint)); case UProperty.SIMPLE_TITLECASE_MAPPING: return toString(toTitleCase(codepoint)); case UProperty.SIMPLE_UPPERCASE_MAPPING: return toString(toUpperCase(codepoint)); case UProperty.TITLECASE_MAPPING: return toString(toTitleCase(codepoint)); case UProperty.UNICODE_1_NAME: return getName1_0(codepoint); case UProperty.UPPERCASE_MAPPING: return toString(toUpperCase(codepoint)); } throw new IllegalArgumentException("Illegal Property Enum"); }
[ "@", "Deprecated", "///CLOVER:OFF", "public", "static", "String", "getStringPropertyValue", "(", "int", "propertyEnum", ",", "int", "codepoint", ",", "int", "nameChoice", ")", "{", "if", "(", "(", "propertyEnum", ">=", "UProperty", ".", "BINARY_START", "&&", "pr...
<strong>[icu]</strong> Returns a string version of the property value. @param propertyEnum The property enum value. @param codepoint The codepoint value. @param nameChoice The choice of the name. @return value as string @deprecated This API is ICU internal only. @hide original deprecated declaration @hide draft / provisional / internal are hidden on Android
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Returns", "a", "string", "version", "of", "the", "property", "value", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/lang/UCharacter.java#L5100-L5128
googleapis/google-cloud-java
google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CloudSnippets.java
CloudSnippets.runQueryPermanentTable
public void runQueryPermanentTable(String destinationDataset, String destinationTable) throws InterruptedException { // [START bigquery_query_destination_table] // BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); // String destinationDataset = 'my_destination_dataset'; // String destinationTable = 'my_destination_table'; String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; QueryJobConfiguration queryConfig = // Note that setUseLegacySql is set to false by default QueryJobConfiguration.newBuilder(query) // Save the results of the query to a permanent table. .setDestinationTable(TableId.of(destinationDataset, destinationTable)) .build(); // Print the results. for (FieldValueList row : bigquery.query(queryConfig).iterateAll()) { for (FieldValue val : row) { System.out.printf("%s,", val.toString()); } System.out.printf("\n"); } // [END bigquery_query_destination_table] }
java
public void runQueryPermanentTable(String destinationDataset, String destinationTable) throws InterruptedException { // [START bigquery_query_destination_table] // BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); // String destinationDataset = 'my_destination_dataset'; // String destinationTable = 'my_destination_table'; String query = "SELECT corpus FROM `bigquery-public-data.samples.shakespeare` GROUP BY corpus;"; QueryJobConfiguration queryConfig = // Note that setUseLegacySql is set to false by default QueryJobConfiguration.newBuilder(query) // Save the results of the query to a permanent table. .setDestinationTable(TableId.of(destinationDataset, destinationTable)) .build(); // Print the results. for (FieldValueList row : bigquery.query(queryConfig).iterateAll()) { for (FieldValue val : row) { System.out.printf("%s,", val.toString()); } System.out.printf("\n"); } // [END bigquery_query_destination_table] }
[ "public", "void", "runQueryPermanentTable", "(", "String", "destinationDataset", ",", "String", "destinationTable", ")", "throws", "InterruptedException", "{", "// [START bigquery_query_destination_table]", "// BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();", "/...
Example of running a query and saving the results to a table.
[ "Example", "of", "running", "a", "query", "and", "saving", "the", "results", "to", "a", "table", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CloudSnippets.java#L69-L91
codeprimate-software/cp-elements
src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java
ElementsExceptionsFactory.newMappingException
public static MappingException newMappingException(Throwable cause, String message, Object... args) { return new MappingException(format(message, args), cause); }
java
public static MappingException newMappingException(Throwable cause, String message, Object... args) { return new MappingException(format(message, args), cause); }
[ "public", "static", "MappingException", "newMappingException", "(", "Throwable", "cause", ",", "String", "message", ",", "Object", "...", "args", ")", "{", "return", "new", "MappingException", "(", "format", "(", "message", ",", "args", ")", ",", "cause", ")",...
Constructs and initializes a new {@link MappingException} with the given {@link Throwable cause} and {@link String message} formatted with the given {@link Object[] arguments}. @param cause {@link Throwable} identified as the reason this {@link MappingException} was thrown. @param message {@link String} describing the {@link MappingException exception}. @param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}. @return a new {@link MappingException} with the given {@link Throwable cause} and {@link String message}. @see org.cp.elements.data.mapping.MappingException
[ "Constructs", "and", "initializes", "a", "new", "{", "@link", "MappingException", "}", "with", "the", "given", "{", "@link", "Throwable", "cause", "}", "and", "{", "@link", "String", "message", "}", "formatted", "with", "the", "given", "{", "@link", "Object"...
train
https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L197-L199
nohana/Amalgam
amalgam/src/main/java/com/amalgam/os/BundleUtils.java
BundleUtils.optSize
@Nullable @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static Size optSize(@Nullable Bundle bundle, @Nullable String key, @Nullable Size fallback) { if (bundle == null) { return fallback; } return bundle.getSize(key); }
java
@Nullable @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static Size optSize(@Nullable Bundle bundle, @Nullable String key, @Nullable Size fallback) { if (bundle == null) { return fallback; } return bundle.getSize(key); }
[ "@", "Nullable", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "LOLLIPOP", ")", "public", "static", "Size", "optSize", "(", "@", "Nullable", "Bundle", "bundle", ",", "@", "Nullable", "String", "key", ",", "@", "Nullable", "Size", "fallback", "...
Returns a optional {@link android.util.Size} value. In other words, returns the value mapped by key if it exists and is a {@link android.util.Size}. The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns null. @param bundle a bundle. If the bundle is null, this method will return null. @param key a key for the value. @param fallback fallback value. @return a {@link android.util.Size} value if exists, null otherwise. @see android.os.Bundle#getSize(String)
[ "Returns", "a", "optional", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L886-L893
jkrasnay/sqlbuilder
src/main/java/ca/krasnay/sqlbuilder/InsertBuilder.java
InsertBuilder.set
public InsertBuilder set(String column, String value) { columns.add(column); values.add(value); return this; }
java
public InsertBuilder set(String column, String value) { columns.add(column); values.add(value); return this; }
[ "public", "InsertBuilder", "set", "(", "String", "column", ",", "String", "value", ")", "{", "columns", ".", "add", "(", "column", ")", ";", "values", ".", "add", "(", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a column name, value pair into the SQL. @param column Name of the table column. @param value Value to substitute in. InsertBuilder does *no* interpretation of this. If you want a string constant inserted, you must provide the single quotes and escape the internal quotes. It is more common to use a question mark or a token in the style of {@link ParameterizedPreparedStatementCreator}, e.g. ":foo".
[ "Inserts", "a", "column", "name", "value", "pair", "into", "the", "SQL", "." ]
train
https://github.com/jkrasnay/sqlbuilder/blob/8e6acedc51cfad0527263376af51e1ef052f7147/src/main/java/ca/krasnay/sqlbuilder/InsertBuilder.java#L44-L48
google/truth
core/src/main/java/com/google/common/truth/IterableSubject.java
IterableSubject.containsAtLeastElementsIn
@CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn(Iterable<?> expectedIterable) { List<?> actual = Lists.newLinkedList(actual()); final Collection<?> expected = iterableToCollection(expectedIterable); List<Object> missing = newArrayList(); List<Object> actualNotInOrder = newArrayList(); boolean ordered = true; // step through the expected elements... for (Object e : expected) { int index = actual.indexOf(e); if (index != -1) { // if we find the element in the actual list... // drain all the elements that come before that element into actualNotInOrder moveElements(actual, actualNotInOrder, index); // and remove the element from the actual list actual.remove(0); } else { // otherwise try removing it from actualNotInOrder... if (actualNotInOrder.remove(e)) { // if it was in actualNotInOrder, we're not in order ordered = false; } else { // if it's not in actualNotInOrder, we're missing an expected element missing.add(e); } } } // if we have any missing expected elements, fail if (!missing.isEmpty()) { return failAtLeast(expected, missing); } /* * TODO(cpovirk): In the NotInOrder case, also include a Fact that shows _only_ the required * elements (that is, without any extras) but in the order they were actually found. That should * make it easier for users to compare the actual order of the required elements to the expected * order. Or, if that's too much trouble, at least try to find a better title for the full * actual iterable than the default of "but was," which may _sound_ like it should show only the * required elements, rather than the full actual iterable. */ return ordered ? IN_ORDER : new Ordered() { @Override public void inOrder() { failWithActual( simpleFact("required elements were all found, but order was wrong"), fact("expected order for required elements", expected)); } }; }
java
@CanIgnoreReturnValue public final Ordered containsAtLeastElementsIn(Iterable<?> expectedIterable) { List<?> actual = Lists.newLinkedList(actual()); final Collection<?> expected = iterableToCollection(expectedIterable); List<Object> missing = newArrayList(); List<Object> actualNotInOrder = newArrayList(); boolean ordered = true; // step through the expected elements... for (Object e : expected) { int index = actual.indexOf(e); if (index != -1) { // if we find the element in the actual list... // drain all the elements that come before that element into actualNotInOrder moveElements(actual, actualNotInOrder, index); // and remove the element from the actual list actual.remove(0); } else { // otherwise try removing it from actualNotInOrder... if (actualNotInOrder.remove(e)) { // if it was in actualNotInOrder, we're not in order ordered = false; } else { // if it's not in actualNotInOrder, we're missing an expected element missing.add(e); } } } // if we have any missing expected elements, fail if (!missing.isEmpty()) { return failAtLeast(expected, missing); } /* * TODO(cpovirk): In the NotInOrder case, also include a Fact that shows _only_ the required * elements (that is, without any extras) but in the order they were actually found. That should * make it easier for users to compare the actual order of the required elements to the expected * order. Or, if that's too much trouble, at least try to find a better title for the full * actual iterable than the default of "but was," which may _sound_ like it should show only the * required elements, rather than the full actual iterable. */ return ordered ? IN_ORDER : new Ordered() { @Override public void inOrder() { failWithActual( simpleFact("required elements were all found, but order was wrong"), fact("expected order for required elements", expected)); } }; }
[ "@", "CanIgnoreReturnValue", "public", "final", "Ordered", "containsAtLeastElementsIn", "(", "Iterable", "<", "?", ">", "expectedIterable", ")", "{", "List", "<", "?", ">", "actual", "=", "Lists", ".", "newLinkedList", "(", "actual", "(", ")", ")", ";", "fin...
Checks that the actual iterable contains at least all of the expected elements or fails. If an element appears more than once in the expected elements then it must appear at least that number of times in the actual elements. <p>To also test that the contents appear in the given order, make a call to {@code inOrder()} on the object returned by this method. The expected elements must appear in the given order within the actual elements, but they are not required to be consecutive.
[ "Checks", "that", "the", "actual", "iterable", "contains", "at", "least", "all", "of", "the", "expected", "elements", "or", "fails", ".", "If", "an", "element", "appears", "more", "than", "once", "in", "the", "expected", "elements", "then", "it", "must", "...
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/IterableSubject.java#L299-L347
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java
RetireJSDataSource.initializeRetireJsRepo
private void initializeRetireJsRepo(Settings settings, URL repoUrl) throws UpdateException { try { final File dataDir = settings.getDataDirectory(); final File tmpDir = settings.getTempDirectory(); boolean useProxy = false; if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) { useProxy = true; LOGGER.debug("Using proxy"); } LOGGER.debug("RetireJS Repo URL: {}", repoUrl.toExternalForm()); final URLConnectionFactory factory = new URLConnectionFactory(settings); final HttpURLConnection conn = factory.createHttpURLConnection(repoUrl, useProxy); final String filename = repoUrl.getFile().substring(repoUrl.getFile().lastIndexOf("/") + 1, repoUrl.getFile().length()); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { final File tmpFile = new File(tmpDir, filename); final File repoFile = new File(dataDir, filename); try (InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(tmpFile)) { IOUtils.copy(inputStream, outputStream); } //using move fails if target and destination are on different disks which does happen (see #1394 and #1404) Files.copy(tmpFile.toPath(), repoFile.toPath(), StandardCopyOption.REPLACE_EXISTING); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } } catch (IOException e) { throw new UpdateException("Failed to initialize the RetireJS repo", e); } }
java
private void initializeRetireJsRepo(Settings settings, URL repoUrl) throws UpdateException { try { final File dataDir = settings.getDataDirectory(); final File tmpDir = settings.getTempDirectory(); boolean useProxy = false; if (null != settings.getString(Settings.KEYS.PROXY_SERVER)) { useProxy = true; LOGGER.debug("Using proxy"); } LOGGER.debug("RetireJS Repo URL: {}", repoUrl.toExternalForm()); final URLConnectionFactory factory = new URLConnectionFactory(settings); final HttpURLConnection conn = factory.createHttpURLConnection(repoUrl, useProxy); final String filename = repoUrl.getFile().substring(repoUrl.getFile().lastIndexOf("/") + 1, repoUrl.getFile().length()); if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) { final File tmpFile = new File(tmpDir, filename); final File repoFile = new File(dataDir, filename); try (InputStream inputStream = conn.getInputStream(); FileOutputStream outputStream = new FileOutputStream(tmpFile)) { IOUtils.copy(inputStream, outputStream); } //using move fails if target and destination are on different disks which does happen (see #1394 and #1404) Files.copy(tmpFile.toPath(), repoFile.toPath(), StandardCopyOption.REPLACE_EXISTING); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } } catch (IOException e) { throw new UpdateException("Failed to initialize the RetireJS repo", e); } }
[ "private", "void", "initializeRetireJsRepo", "(", "Settings", "settings", ",", "URL", "repoUrl", ")", "throws", "UpdateException", "{", "try", "{", "final", "File", "dataDir", "=", "settings", ".", "getDataDirectory", "(", ")", ";", "final", "File", "tmpDir", ...
Initializes the local RetireJS repository @param settings a reference to the dependency-check settings @param repoUrl the URL to the RetireJS repo to use @throws UpdateException thrown if there is an exception during initialization
[ "Initializes", "the", "local", "RetireJS", "repository" ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/update/RetireJSDataSource.java#L147-L176
io7m/jproperties
com.io7m.jproperties.core/src/main/java/com/io7m/jproperties/JProperties.java
JProperties.getBooleanOptional
public static boolean getBooleanOptional( final Properties properties, final String key, final boolean other) throws JPropertyIncorrectType { Objects.requireNonNull(properties, "Properties"); Objects.requireNonNull(key, "Key"); final String text = properties.getProperty(key); if (text == null) { return other; } return parseBoolean(key, text); }
java
public static boolean getBooleanOptional( final Properties properties, final String key, final boolean other) throws JPropertyIncorrectType { Objects.requireNonNull(properties, "Properties"); Objects.requireNonNull(key, "Key"); final String text = properties.getProperty(key); if (text == null) { return other; } return parseBoolean(key, text); }
[ "public", "static", "boolean", "getBooleanOptional", "(", "final", "Properties", "properties", ",", "final", "String", "key", ",", "final", "boolean", "other", ")", "throws", "JPropertyIncorrectType", "{", "Objects", ".", "requireNonNull", "(", "properties", ",", ...
<p> Returns the boolean value associated with {@code key} in the properties referenced by {@code properties} if it exists, otherwise returns {@code other}. </p> <p> A boolean value is syntactically the strings "true" or "false", case insensitive. </p> @param other The default value @param properties The loaded properties. @param key The requested key. @return The value associated with the key, parsed as a boolean. @throws JPropertyIncorrectType If the value associated with the key cannot be parsed as a boolean.
[ "<p", ">", "Returns", "the", "boolean", "value", "associated", "with", "{", "@code", "key", "}", "in", "the", "properties", "referenced", "by", "{", "@code", "properties", "}", "if", "it", "exists", "otherwise", "returns", "{", "@code", "other", "}", ".", ...
train
https://github.com/io7m/jproperties/blob/b188b8fd87b3b078f1e2b564a9ed5996db0becfd/com.io7m.jproperties.core/src/main/java/com/io7m/jproperties/JProperties.java#L231-L246
JoeKerouac/utils
src/main/java/com/joe/utils/reflect/asm/AsmInvokeDistributeFactory.java
AsmInvokeDistributeFactory.buildMethod
private static void buildMethod(ClassWriter cw, String className, Class<?> parentClass) { /* Build method */ MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, // public method DISTRIBUTE_METHOD_NAME, // name DISTRIBUTE_METHOD_DESC, // descriptor null, // signature (null means not generic) CollectionUtil.array(convert(NoSuchMethodException.class))); // exceptions (array of strings) // 开始方法区 mv.visitCode(); // 判断要调用那个方法,然后将动态调用转化为对应的本地调用 { List<Method> allMethod = ReflectUtil.getAllMethod(parentClass); Label next = new Label(); Label start = new Label(); for (Method method : allMethod) { // 只处理非静态的public方法和protected方法 if (Modifier.isStatic(method.getModifiers()) || (!AccessorUtil.isPublic(method) && !AccessorUtil.isProtected(method))) { continue; } createIf(mv, method, next, start, className, parentClass); start = next; next = new Label(); } // 结束位置标记 mv.visitLabel(start); mv.visitFrame(F_SAME, 0, null, 0, null); } // throw new NoSuchMethodException(String.format("method [%s:%s:%s] not found", owner, methodName, desc)); { // 默认抛出Error,不应该有这种情况 mv.visitTypeInsn(NEW, convert(NoSuchMethodException.class)); mv.visitInsn(DUP); mv.visitLdcInsn("method [%s:%s:%s] not found"); mv.visitInsn(ICONST_3); mv.visitTypeInsn(ANEWARRAY, convert(Object.class)); mv.visitInsn(DUP); mv.visitInsn(ICONST_0); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(AASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_1); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(AASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_2); mv.visitVarInsn(ALOAD, 3); mv.visitInsn(AASTORE); mv.visitMethodInsn(INVOKESTATIC, convert(String.class), MethodConst.FORMAT_METHOD.getName(), getMethodDesc(MethodConst.FORMAT_METHOD), false); mv.visitMethodInsn(INVOKESPECIAL, convert(NoSuchMethodException.class), INIT, getConstructorDesc(ERROR_CONSTRUCTOR), false); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); } mv.visitEnd(); }
java
private static void buildMethod(ClassWriter cw, String className, Class<?> parentClass) { /* Build method */ MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, // public method DISTRIBUTE_METHOD_NAME, // name DISTRIBUTE_METHOD_DESC, // descriptor null, // signature (null means not generic) CollectionUtil.array(convert(NoSuchMethodException.class))); // exceptions (array of strings) // 开始方法区 mv.visitCode(); // 判断要调用那个方法,然后将动态调用转化为对应的本地调用 { List<Method> allMethod = ReflectUtil.getAllMethod(parentClass); Label next = new Label(); Label start = new Label(); for (Method method : allMethod) { // 只处理非静态的public方法和protected方法 if (Modifier.isStatic(method.getModifiers()) || (!AccessorUtil.isPublic(method) && !AccessorUtil.isProtected(method))) { continue; } createIf(mv, method, next, start, className, parentClass); start = next; next = new Label(); } // 结束位置标记 mv.visitLabel(start); mv.visitFrame(F_SAME, 0, null, 0, null); } // throw new NoSuchMethodException(String.format("method [%s:%s:%s] not found", owner, methodName, desc)); { // 默认抛出Error,不应该有这种情况 mv.visitTypeInsn(NEW, convert(NoSuchMethodException.class)); mv.visitInsn(DUP); mv.visitLdcInsn("method [%s:%s:%s] not found"); mv.visitInsn(ICONST_3); mv.visitTypeInsn(ANEWARRAY, convert(Object.class)); mv.visitInsn(DUP); mv.visitInsn(ICONST_0); mv.visitVarInsn(ALOAD, 1); mv.visitInsn(AASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_1); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(AASTORE); mv.visitInsn(DUP); mv.visitInsn(ICONST_2); mv.visitVarInsn(ALOAD, 3); mv.visitInsn(AASTORE); mv.visitMethodInsn(INVOKESTATIC, convert(String.class), MethodConst.FORMAT_METHOD.getName(), getMethodDesc(MethodConst.FORMAT_METHOD), false); mv.visitMethodInsn(INVOKESPECIAL, convert(NoSuchMethodException.class), INIT, getConstructorDesc(ERROR_CONSTRUCTOR), false); mv.visitInsn(ATHROW); mv.visitMaxs(0, 0); } mv.visitEnd(); }
[ "private", "static", "void", "buildMethod", "(", "ClassWriter", "cw", ",", "String", "className", ",", "Class", "<", "?", ">", "parentClass", ")", "{", "/* Build method */", "MethodVisitor", "mv", "=", "cw", ".", "visitMethod", "(", "ACC_PUBLIC", ",", "// publ...
构建{@link InvokeDistribute#invoke(String, String, String, Object[]) invoke}方法 @param cw ClassWriter @param className 生成的类名 @param parentClass 父类
[ "构建", "{" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/reflect/asm/AsmInvokeDistributeFactory.java#L160-L227
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Jdt2Ecore.java
Jdt2Ecore.getJvmConstructor
public JvmConstructor getJvmConstructor(IMethod constructor, XtendTypeDeclaration context) throws JavaModelException { if (constructor.isConstructor()) { final JvmType type = this.typeReferences.findDeclaredType( constructor.getDeclaringType().getFullyQualifiedName(), context); if (type instanceof JvmDeclaredType) { final JvmDeclaredType declaredType = (JvmDeclaredType) type; final ActionParameterTypes jdtSignature = this.actionPrototypeProvider.createParameterTypes( Flags.isVarargs(constructor.getFlags()), getFormalParameterProvider(constructor)); for (final JvmConstructor jvmConstructor : declaredType.getDeclaredConstructors()) { final ActionParameterTypes jvmSignature = this.actionPrototypeProvider.createParameterTypesFromJvmModel( jvmConstructor.isVarArgs(), jvmConstructor.getParameters()); if (jvmSignature.equals(jdtSignature)) { return jvmConstructor; } } } } return null; }
java
public JvmConstructor getJvmConstructor(IMethod constructor, XtendTypeDeclaration context) throws JavaModelException { if (constructor.isConstructor()) { final JvmType type = this.typeReferences.findDeclaredType( constructor.getDeclaringType().getFullyQualifiedName(), context); if (type instanceof JvmDeclaredType) { final JvmDeclaredType declaredType = (JvmDeclaredType) type; final ActionParameterTypes jdtSignature = this.actionPrototypeProvider.createParameterTypes( Flags.isVarargs(constructor.getFlags()), getFormalParameterProvider(constructor)); for (final JvmConstructor jvmConstructor : declaredType.getDeclaredConstructors()) { final ActionParameterTypes jvmSignature = this.actionPrototypeProvider.createParameterTypesFromJvmModel( jvmConstructor.isVarArgs(), jvmConstructor.getParameters()); if (jvmSignature.equals(jdtSignature)) { return jvmConstructor; } } } } return null; }
[ "public", "JvmConstructor", "getJvmConstructor", "(", "IMethod", "constructor", ",", "XtendTypeDeclaration", "context", ")", "throws", "JavaModelException", "{", "if", "(", "constructor", ".", "isConstructor", "(", ")", ")", "{", "final", "JvmType", "type", "=", "...
Create the JvmConstructor for the given JDT constructor. @param constructor the JDT constructor. @param context the context of the constructor. @return the JvmConstructor @throws JavaModelException if the Java model is invalid.
[ "Create", "the", "JvmConstructor", "for", "the", "given", "JDT", "constructor", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/util/Jdt2Ecore.java#L365-L387
JOML-CI/JOML
src/org/joml/Quaternionf.java
Quaternionf.nlerpIterative
public Quaternionf nlerpIterative(Quaternionfc q, float alpha, float dotThreshold) { return nlerpIterative(q, alpha, dotThreshold, this); }
java
public Quaternionf nlerpIterative(Quaternionfc q, float alpha, float dotThreshold) { return nlerpIterative(q, alpha, dotThreshold, this); }
[ "public", "Quaternionf", "nlerpIterative", "(", "Quaternionfc", "q", ",", "float", "alpha", ",", "float", "dotThreshold", ")", "{", "return", "nlerpIterative", "(", "q", ",", "alpha", ",", "dotThreshold", ",", "this", ")", ";", "}" ]
Compute linear (non-spherical) interpolations of <code>this</code> and the given quaternion <code>q</code> iteratively and store the result in <code>this</code>. <p> This method performs a series of small-step nlerp interpolations to avoid doing a costly spherical linear interpolation, like {@link #slerp(Quaternionfc, float, Quaternionf) slerp}, by subdividing the rotation arc between <code>this</code> and <code>q</code> via non-spherical linear interpolations as long as the absolute dot product of <code>this</code> and <code>q</code> is greater than the given <code>dotThreshold</code> parameter. <p> Thanks to <code>@theagentd</code> at <a href="http://www.java-gaming.org/">http://www.java-gaming.org/</a> for providing the code. @param q the other quaternion @param alpha the interpolation factor, between 0.0 and 1.0 @param dotThreshold the threshold for the dot product of <code>this</code> and <code>q</code> above which this method performs another iteration of a small-step linear interpolation @return this
[ "Compute", "linear", "(", "non", "-", "spherical", ")", "interpolations", "of", "<code", ">", "this<", "/", "code", ">", "and", "the", "given", "quaternion", "<code", ">", "q<", "/", "code", ">", "iteratively", "and", "store", "the", "result", "in", "<co...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaternionf.java#L2032-L2034
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/lib/ArrayUtil.java
ArrayUtil.countCommonElements
public static int countCommonElements(int[] arra, int[] arrb) { int k = 0; for (int i = 0; i < arra.length; i++) { for (int j = 0; j < arrb.length; j++) { if (arra[i] == arrb[j]) { k++; } } } return k; }
java
public static int countCommonElements(int[] arra, int[] arrb) { int k = 0; for (int i = 0; i < arra.length; i++) { for (int j = 0; j < arrb.length; j++) { if (arra[i] == arrb[j]) { k++; } } } return k; }
[ "public", "static", "int", "countCommonElements", "(", "int", "[", "]", "arra", ",", "int", "[", "]", "arrb", ")", "{", "int", "k", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "arra", ".", "length", ";", "i", "++", ")", "{...
Returns the number of elements shared between the two arrays containing sets.<p> Return the number of elements shared by two column index arrays. This method assumes that each of these arrays contains a set (each element index is listed only once in each index array). Otherwise the returned number will NOT represent the number of unique column indexes shared by both index array. @param arra int[]; first array of column indexes. @param arrb int[]; second array of column indexes @return int; number of elements shared by <code>a</code> and <code>b</code>
[ "Returns", "the", "number", "of", "elements", "shared", "between", "the", "two", "arrays", "containing", "sets", ".", "<p", ">" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/ArrayUtil.java#L499-L512
Nexmo/nexmo-java
src/main/java/com/nexmo/client/conversion/ConversionClient.java
ConversionClient.submitConversion
public void submitConversion(ConversionRequest.Type type, String messageId, boolean delivered, Date timestamp) throws IOException, NexmoClientException { this.conversionEndpoint.submitConversion(new ConversionRequest(type, messageId, delivered, timestamp)); }
java
public void submitConversion(ConversionRequest.Type type, String messageId, boolean delivered, Date timestamp) throws IOException, NexmoClientException { this.conversionEndpoint.submitConversion(new ConversionRequest(type, messageId, delivered, timestamp)); }
[ "public", "void", "submitConversion", "(", "ConversionRequest", ".", "Type", "type", ",", "String", "messageId", ",", "boolean", "delivered", ",", "Date", "timestamp", ")", "throws", "IOException", ",", "NexmoClientException", "{", "this", ".", "conversionEndpoint",...
Submit a request to the Conversion API indicating whether or not a message was delivered. @param type The {@link ConversionRequest.Type} type of com.nexmo.client.conversion. @param messageId The id of the message that was sent. @param delivered A boolean indicating whether or not it was delivered. @param timestamp A timestamp of when it was known to be delivered. @throws IOException if a network error occurred contacting the Nexmo Conversion API. @throws NexmoClientException if there was a problem with the Nexmo request or response objects.
[ "Submit", "a", "request", "to", "the", "Conversion", "API", "indicating", "whether", "or", "not", "a", "message", "was", "delivered", "." ]
train
https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/conversion/ConversionClient.java#L60-L65
marvinlabs/android-intents
library/src/main/java/com/marvinlabs/intents/PhoneIntents.java
PhoneIntents.newDialNumberIntent
public static Intent newDialNumberIntent(String phoneNumber) { final Intent intent; if (phoneNumber == null || phoneNumber.trim().length() <= 0) { intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:")); } else { intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber.replace(" ", ""))); } return intent; }
java
public static Intent newDialNumberIntent(String phoneNumber) { final Intent intent; if (phoneNumber == null || phoneNumber.trim().length() <= 0) { intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:")); } else { intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber.replace(" ", ""))); } return intent; }
[ "public", "static", "Intent", "newDialNumberIntent", "(", "String", "phoneNumber", ")", "{", "final", "Intent", "intent", ";", "if", "(", "phoneNumber", "==", "null", "||", "phoneNumber", ".", "trim", "(", ")", ".", "length", "(", ")", "<=", "0", ")", "{...
Creates an intent that will open the phone app and enter the given number. Unlike {@link #newCallNumberIntent(String)}, this does not actually dispatch the call, so it gives the user a chance to review and edit the number. @param phoneNumber the number to dial @return the intent
[ "Creates", "an", "intent", "that", "will", "open", "the", "phone", "app", "and", "enter", "the", "given", "number", ".", "Unlike", "{", "@link", "#newCallNumberIntent", "(", "String", ")", "}", "this", "does", "not", "actually", "dispatch", "the", "call", ...
train
https://github.com/marvinlabs/android-intents/blob/33e79c825188b6a97601869522533cc825801f6e/library/src/main/java/com/marvinlabs/intents/PhoneIntents.java#L125-L133
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/EditUtilities.java
EditUtilities.getVertexToSnap
public static GeometryLocation getVertexToSnap(Geometry g, Point p, double tolerance) { DistanceOp distanceOp = new DistanceOp(g, p); GeometryLocation snapedPoint = distanceOp.nearestLocations()[0]; if (tolerance == 0 || snapedPoint.getCoordinate().distance(p.getCoordinate()) <= tolerance) { return snapedPoint; } return null; }
java
public static GeometryLocation getVertexToSnap(Geometry g, Point p, double tolerance) { DistanceOp distanceOp = new DistanceOp(g, p); GeometryLocation snapedPoint = distanceOp.nearestLocations()[0]; if (tolerance == 0 || snapedPoint.getCoordinate().distance(p.getCoordinate()) <= tolerance) { return snapedPoint; } return null; }
[ "public", "static", "GeometryLocation", "getVertexToSnap", "(", "Geometry", "g", ",", "Point", "p", ",", "double", "tolerance", ")", "{", "DistanceOp", "distanceOp", "=", "new", "DistanceOp", "(", "g", ",", "p", ")", ";", "GeometryLocation", "snapedPoint", "="...
Gets the coordinate of a Geometry that is the nearest of a given Point, with a distance tolerance. @param g @param p @param tolerance @return
[ "Gets", "the", "coordinate", "of", "a", "Geometry", "that", "is", "the", "nearest", "of", "a", "given", "Point", "with", "a", "distance", "tolerance", "." ]
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/spatial/edit/EditUtilities.java#L44-L52
podio/podio-java
src/main/java/com/podio/app/AppAPI.java
AppAPI.addField
public int addField(int appId, ApplicationFieldCreate field) { return getResourceFactory().getApiResource("/app/" + appId + "/field/") .entity(field, MediaType.APPLICATION_JSON_TYPE) .post(ApplicationFieldCreateResponse.class).getId(); }
java
public int addField(int appId, ApplicationFieldCreate field) { return getResourceFactory().getApiResource("/app/" + appId + "/field/") .entity(field, MediaType.APPLICATION_JSON_TYPE) .post(ApplicationFieldCreateResponse.class).getId(); }
[ "public", "int", "addField", "(", "int", "appId", ",", "ApplicationFieldCreate", "field", ")", "{", "return", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/app/\"", "+", "appId", "+", "\"/field/\"", ")", ".", "entity", "(", "field", ",", "M...
Adds a new field to an app @param appId The id of the the field should be added to @param field The definition of the new field @return The id of the newly created field
[ "Adds", "a", "new", "field", "to", "an", "app" ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/app/AppAPI.java#L111-L115
OpenVidu/openvidu
openvidu-server/src/main/java/io/openvidu/server/recording/service/RecordingService.java
RecordingService.updateRecordingManagerCollections
protected void updateRecordingManagerCollections(Session session, Recording recording) { this.recordingManager.sessionHandler.setRecordingStarted(session.getSessionId(), recording); this.recordingManager.sessionsRecordings.put(session.getSessionId(), recording); this.recordingManager.startingRecordings.remove(recording.getId()); this.recordingManager.startedRecordings.put(recording.getId(), recording); }
java
protected void updateRecordingManagerCollections(Session session, Recording recording) { this.recordingManager.sessionHandler.setRecordingStarted(session.getSessionId(), recording); this.recordingManager.sessionsRecordings.put(session.getSessionId(), recording); this.recordingManager.startingRecordings.remove(recording.getId()); this.recordingManager.startedRecordings.put(recording.getId(), recording); }
[ "protected", "void", "updateRecordingManagerCollections", "(", "Session", "session", ",", "Recording", "recording", ")", "{", "this", ".", "recordingManager", ".", "sessionHandler", ".", "setRecordingStarted", "(", "session", ".", "getSessionId", "(", ")", ",", "rec...
Changes recording from starting to started, updates global recording collections and sends RPC response to clients
[ "Changes", "recording", "from", "starting", "to", "started", "updates", "global", "recording", "collections", "and", "sends", "RPC", "response", "to", "clients" ]
train
https://github.com/OpenVidu/openvidu/blob/89db47dd37949ceab29e5228371a8fcab04d8d55/openvidu-server/src/main/java/io/openvidu/server/recording/service/RecordingService.java#L101-L106
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java
ConnectionFactory.getConnection
public synchronized Connection getConnection() throws DatabaseException { initialize(); Connection conn = null; try { conn = DriverManager.getConnection(connectionString, userName, password); } catch (SQLException ex) { LOGGER.debug("", ex); throw new DatabaseException("Unable to connect to the database", ex); } return conn; }
java
public synchronized Connection getConnection() throws DatabaseException { initialize(); Connection conn = null; try { conn = DriverManager.getConnection(connectionString, userName, password); } catch (SQLException ex) { LOGGER.debug("", ex); throw new DatabaseException("Unable to connect to the database", ex); } return conn; }
[ "public", "synchronized", "Connection", "getConnection", "(", ")", "throws", "DatabaseException", "{", "initialize", "(", ")", ";", "Connection", "conn", "=", "null", ";", "try", "{", "conn", "=", "DriverManager", ".", "getConnection", "(", "connectionString", "...
Constructs a new database connection object per the database configuration. @return a database connection object @throws DatabaseException thrown if there is an exception loading the database connection
[ "Constructs", "a", "new", "database", "connection", "object", "per", "the", "database", "configuration", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/data/nvdcve/ConnectionFactory.java#L230-L240
fcrepo3/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multifile/JournalInputFile.java
JournalInputFile.closeAndRename
public void closeAndRename(File archiveDirectory) throws JournalException { try { xmlReader.close(); fileReader.close(); File archiveFile = new File(archiveDirectory, file.getName()); /* * java.io.File.renameTo() has a known bug when working across * file-systems, see: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756 So * instead of this call: file.renameTo(archiveFile); We use the * following line, and check for exception... */ try { FileMovingUtil.move(file, archiveFile); } catch (IOException e) { throw new JournalException("Failed to rename file from '" + file.getPath() + "' to '" + archiveFile.getPath() + "'", e); } } catch (XMLStreamException e) { throw new JournalException(e); } catch (IOException e) { throw new JournalException(e); } }
java
public void closeAndRename(File archiveDirectory) throws JournalException { try { xmlReader.close(); fileReader.close(); File archiveFile = new File(archiveDirectory, file.getName()); /* * java.io.File.renameTo() has a known bug when working across * file-systems, see: * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756 So * instead of this call: file.renameTo(archiveFile); We use the * following line, and check for exception... */ try { FileMovingUtil.move(file, archiveFile); } catch (IOException e) { throw new JournalException("Failed to rename file from '" + file.getPath() + "' to '" + archiveFile.getPath() + "'", e); } } catch (XMLStreamException e) { throw new JournalException(e); } catch (IOException e) { throw new JournalException(e); } }
[ "public", "void", "closeAndRename", "(", "File", "archiveDirectory", ")", "throws", "JournalException", "{", "try", "{", "xmlReader", ".", "close", "(", ")", ";", "fileReader", ".", "close", "(", ")", ";", "File", "archiveFile", "=", "new", "File", "(", "a...
When we have processed the file, move it to the archive directory.
[ "When", "we", "have", "processed", "the", "file", "move", "it", "to", "the", "archive", "directory", "." ]
train
https://github.com/fcrepo3/fcrepo/blob/37df51b9b857fd12c6ab8269820d406c3c4ad774/fcrepo-server/src/main/java/org/fcrepo/server/journal/readerwriter/multifile/JournalInputFile.java#L63-L88
zaproxy/zaproxy
src/org/zaproxy/zap/extension/dynssl/SslCertificateUtils.java
SslCertificateUtils.createRootCA
public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime()+ DEFAULT_VALIDITY_IN_MS); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Security.addProvider(new BouncyCastleProvider()); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder ( namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey ); KeyStore ks = null; try { certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[]{cert}); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
java
public static final KeyStore createRootCA() throws NoSuchAlgorithmException { final Date startDate = Calendar.getInstance().getTime(); final Date expireDate = new Date(startDate.getTime()+ DEFAULT_VALIDITY_IN_MS); final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA"); g.initialize(2048, SecureRandom.getInstance("SHA1PRNG")); final KeyPair keypair = g.genKeyPair(); final PrivateKey privKey = keypair.getPrivate(); final PublicKey pubKey = keypair.getPublic(); Security.addProvider(new BouncyCastleProvider()); Random rnd = new Random(); // using the hash code of the user's name and home path, keeps anonymity // but also gives user a chance to distinguish between each other X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE); namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA"); namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode()) + Integer.toHexString(System.getProperty("user.home").hashCode())); namebld.addRDN(BCStyle.O, "OWASP Root CA"); namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA"); namebld.addRDN(BCStyle.C, "xx"); X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder ( namebld.build(), BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey ); KeyStore ks = null; try { certGen.addExtension(Extension.subjectKeyIdentifier, false, new SubjectKeyIdentifier(pubKey.getEncoded())); certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); certGen.addExtension(Extension.keyUsage, false, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.dataEncipherment | KeyUsage.cRLSign)); KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth, KeyPurposeId.anyExtendedKeyUsage }; certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku)); final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC").build(privKey); final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certGen.build(sigGen)); ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE, new Certificate[]{cert}); } catch (final Exception e) { throw new IllegalStateException("Errors during assembling root CA.", e); } return ks; }
[ "public", "static", "final", "KeyStore", "createRootCA", "(", ")", "throws", "NoSuchAlgorithmException", "{", "final", "Date", "startDate", "=", "Calendar", ".", "getInstance", "(", ")", ".", "getTime", "(", ")", ";", "final", "Date", "expireDate", "=", "new",...
Creates a new Root CA certificate and returns private and public key as {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used. @return @throws NoSuchAlgorithmException If no providers are found for 'RSA' key pair generator or 'SHA1PRNG' Secure random number generator @throws IllegalStateException in case of errors during assembling {@link KeyStore}
[ "Creates", "a", "new", "Root", "CA", "certificate", "and", "returns", "private", "and", "public", "key", "as", "{", "@link", "KeyStore", "}", ".", "The", "{", "@link", "KeyStore#getDefaultType", "()", "}", "is", "used", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/dynssl/SslCertificateUtils.java#L113-L167
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/PerQueryCache.java
PerQueryCache.get
Object get(Class<?> type, Object key) { return map.get(new Key(type, key)); }
java
Object get(Class<?> type, Object key) { return map.get(new Key(type, key)); }
[ "Object", "get", "(", "Class", "<", "?", ">", "type", ",", "Object", "key", ")", "{", "return", "map", ".", "get", "(", "new", "Key", "(", "type", ",", "key", ")", ")", ";", "}" ]
Returns the value from the cache with the given <code>type</code> and <code>key</code>. @param type the query type. @param key the key object. @return the value assigned to <code>type</code> and <code>key</code> or <code>null</code> if it does not exist in the cache.
[ "Returns", "the", "value", "from", "the", "cache", "with", "the", "given", "<code", ">", "type<", "/", "code", ">", "and", "<code", ">", "key<", "/", "code", ">", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/PerQueryCache.java#L67-L69