repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
geomajas/geomajas-project-client-gwt | client/src/main/java/org/geomajas/gwt/client/map/MapView.java | MapView.getWorldToPanTranslation | public Matrix getWorldToPanTranslation() {
if (viewState.getScale() > 0) {
double dX = -(viewState.getPanX() * viewState.getScale());
double dY = viewState.getPanY() * viewState.getScale();
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
} | java | public Matrix getWorldToPanTranslation() {
if (viewState.getScale() > 0) {
double dX = -(viewState.getPanX() * viewState.getScale());
double dY = viewState.getPanY() * viewState.getScale();
return new Matrix(1, 0, 0, 1, dX, dY);
}
return new Matrix(1, 0, 0, 1, 0, 0);
} | [
"public",
"Matrix",
"getWorldToPanTranslation",
"(",
")",
"{",
"if",
"(",
"viewState",
".",
"getScale",
"(",
")",
">",
"0",
")",
"{",
"double",
"dX",
"=",
"-",
"(",
"viewState",
".",
"getPanX",
"(",
")",
"*",
"viewState",
".",
"getScale",
"(",
")",
"... | Return the translation of scaled world coordinates to coordinates relative to the pan origin.
@return transformation matrix | [
"Return",
"the",
"translation",
"of",
"scaled",
"world",
"coordinates",
"to",
"coordinates",
"relative",
"to",
"the",
"pan",
"origin",
"."
] | train | https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/MapView.java#L197-L204 |
Azure/azure-sdk-for-java | containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/RunsInner.java | RunsInner.update | public RunInner update(String resourceGroupName, String registryName, String runId, Boolean isArchiveEnabled) {
return updateWithServiceResponseAsync(resourceGroupName, registryName, runId, isArchiveEnabled).toBlocking().last().body();
} | java | public RunInner update(String resourceGroupName, String registryName, String runId, Boolean isArchiveEnabled) {
return updateWithServiceResponseAsync(resourceGroupName, registryName, runId, isArchiveEnabled).toBlocking().last().body();
} | [
"public",
"RunInner",
"update",
"(",
"String",
"resourceGroupName",
",",
"String",
"registryName",
",",
"String",
"runId",
",",
"Boolean",
"isArchiveEnabled",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"registryName",
",",
"ru... | Patch the run properties.
@param resourceGroupName The name of the resource group to which the container registry belongs.
@param registryName The name of the container registry.
@param runId The run ID.
@param isArchiveEnabled The value that indicates whether archiving is enabled or not.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RunInner object if successful. | [
"Patch",
"the",
"run",
"properties",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/containerregistry/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/containerregistry/v2018_09_01/implementation/RunsInner.java#L524-L526 |
etnetera/seb | src/main/java/cz/etnetera/seb/element/SebElement.java | SebElement.blur | public void blur() {
if (getDriver() instanceof JavascriptExecutor)
getSeb().getJavascriptLibrary().callEmbeddedSelenium(getDriver(), "triggerEvent", this, "blur");
else
throw new SebException("Triggering blur event is supported with JavascriptExecutor driver only, this is " + getDriver().getClass());
} | java | public void blur() {
if (getDriver() instanceof JavascriptExecutor)
getSeb().getJavascriptLibrary().callEmbeddedSelenium(getDriver(), "triggerEvent", this, "blur");
else
throw new SebException("Triggering blur event is supported with JavascriptExecutor driver only, this is " + getDriver().getClass());
} | [
"public",
"void",
"blur",
"(",
")",
"{",
"if",
"(",
"getDriver",
"(",
")",
"instanceof",
"JavascriptExecutor",
")",
"getSeb",
"(",
")",
".",
"getJavascriptLibrary",
"(",
")",
".",
"callEmbeddedSelenium",
"(",
"getDriver",
"(",
")",
",",
"\"triggerEvent\"",
"... | Loose focus from element.
It works only for {@link JavascriptExecutor} drivers.
It throws {@link SebException} if driver is not
implementing {@link JavascriptExecutor}. | [
"Loose",
"focus",
"from",
"element",
".",
"It",
"works",
"only",
"for",
"{"
] | train | https://github.com/etnetera/seb/blob/6aed29c7726db12f440c60cfd253de229064ed04/src/main/java/cz/etnetera/seb/element/SebElement.java#L267-L272 |
minio/minio-java | api/src/main/java/io/minio/MinioClient.java | MinioClient.removeObject | public void removeObject(String bucketName, String objectName)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException, InvalidArgumentException {
if ((bucketName == null) || (bucketName.isEmpty())) {
throw new InvalidArgumentException("bucket name cannot be empty");
}
if ((objectName == null) || (objectName.isEmpty())) {
throw new InvalidArgumentException("object name cannot be empty");
}
executeDelete(bucketName, objectName, null);
} | java | public void removeObject(String bucketName, String objectName)
throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException,
InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException,
InternalException, InvalidArgumentException {
if ((bucketName == null) || (bucketName.isEmpty())) {
throw new InvalidArgumentException("bucket name cannot be empty");
}
if ((objectName == null) || (objectName.isEmpty())) {
throw new InvalidArgumentException("object name cannot be empty");
}
executeDelete(bucketName, objectName, null);
} | [
"public",
"void",
"removeObject",
"(",
"String",
"bucketName",
",",
"String",
"objectName",
")",
"throws",
"InvalidBucketNameException",
",",
"NoSuchAlgorithmException",
",",
"InsufficientDataException",
",",
"IOException",
",",
"InvalidKeyException",
",",
"NoResponseExcept... | Removes an object from a bucket.
</p><b>Example:</b><br>
<pre>{@code minioClient.removeObject("my-bucketname", "my-objectname"); }</pre>
@param bucketName Bucket name.
@param objectName Object name in the bucket.
@throws InvalidBucketNameException upon invalid bucket name is given
@throws NoSuchAlgorithmException
upon requested algorithm was not found during signature calculation
@throws InsufficientDataException upon getting EOFException while reading given
InputStream even before reading given length
@throws IOException upon connection error
@throws InvalidKeyException
upon an invalid access key or secret key
@throws NoResponseException upon no response from server
@throws XmlPullParserException upon parsing response xml
@throws ErrorResponseException upon unsuccessful execution
@throws InternalException upon internal library error
@throws InvalidArgumentException upon invalid value is passed to a method. | [
"Removes",
"an",
"object",
"from",
"a",
"bucket",
"."
] | train | https://github.com/minio/minio-java/blob/b2028f56403c89ce2d5900ae813bc1314c87bc7f/api/src/main/java/io/minio/MinioClient.java#L2615-L2628 |
spockframework/spock | spock-core/src/main/java/org/spockframework/runtime/GroovyRuntimeUtil.java | GroovyRuntimeUtil.isVoidMethod | public static boolean isVoidMethod(@Nullable Object target, String method, Object... args) {
if (target == null) return false; // no way to tell
Class[] argTypes = ReflectionUtil.getTypes(args);
// the way we choose metaClass, we won't find methods on java.lang.Class
// but since java.lang.Class has no void methods other than the ones inherited
// from java.lang.Object, and since we operate on a best effort basis, that's OK
// also we will choose a static method like Foo.getName() over the equally
// named method on java.lang.Class, but this is consistent with current Groovy semantics
// (see http://jira.codehaus.org/browse/GROOVY-3548)
// in the end it's probably best to rely on NullAwareInvokeMethodSpec to tell us if
// everything is OK
MetaClass metaClass = target instanceof Class ?
InvokerHelper.getMetaClass((Class) target) : InvokerHelper.getMetaClass(target);
// seems to find more methods than getMetaMethod()
MetaMethod metaMethod = metaClass.pickMethod(method, argTypes);
if (metaMethod == null) return false; // we were unable to figure out which method was called
Class returnType = metaMethod.getReturnType();
// although Void.class will occur rarely, it makes sense to handle
// it in the same way as void.class
return returnType == void.class || returnType == Void.class;
} | java | public static boolean isVoidMethod(@Nullable Object target, String method, Object... args) {
if (target == null) return false; // no way to tell
Class[] argTypes = ReflectionUtil.getTypes(args);
// the way we choose metaClass, we won't find methods on java.lang.Class
// but since java.lang.Class has no void methods other than the ones inherited
// from java.lang.Object, and since we operate on a best effort basis, that's OK
// also we will choose a static method like Foo.getName() over the equally
// named method on java.lang.Class, but this is consistent with current Groovy semantics
// (see http://jira.codehaus.org/browse/GROOVY-3548)
// in the end it's probably best to rely on NullAwareInvokeMethodSpec to tell us if
// everything is OK
MetaClass metaClass = target instanceof Class ?
InvokerHelper.getMetaClass((Class) target) : InvokerHelper.getMetaClass(target);
// seems to find more methods than getMetaMethod()
MetaMethod metaMethod = metaClass.pickMethod(method, argTypes);
if (metaMethod == null) return false; // we were unable to figure out which method was called
Class returnType = metaMethod.getReturnType();
// although Void.class will occur rarely, it makes sense to handle
// it in the same way as void.class
return returnType == void.class || returnType == Void.class;
} | [
"public",
"static",
"boolean",
"isVoidMethod",
"(",
"@",
"Nullable",
"Object",
"target",
",",
"String",
"method",
",",
"Object",
"...",
"args",
")",
"{",
"if",
"(",
"target",
"==",
"null",
")",
"return",
"false",
";",
"// no way to tell",
"Class",
"[",
"]"... | InvokerHelper.invokeMethod, even if the same method is chosen (see Spec GroovyMopExploration) | [
"InvokerHelper",
".",
"invokeMethod",
"even",
"if",
"the",
"same",
"method",
"is",
"chosen",
"(",
"see",
"Spec",
"GroovyMopExploration",
")"
] | train | https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/runtime/GroovyRuntimeUtil.java#L261-L285 |
mojohaus/aspectj-maven-plugin | src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java | AjcHelper.createClassPath | @SuppressWarnings( "unchecked" )
public static String createClassPath( MavenProject project, List<Artifact> pluginArtifacts, List<String> outDirs )
{
String cp = new String();
Set<Artifact> classPathElements = Collections.synchronizedSet( new LinkedHashSet<Artifact>() );
Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
classPathElements.addAll( dependencyArtifacts == null ? Collections.<Artifact>emptySet() : dependencyArtifacts );
classPathElements.addAll( project.getArtifacts() );
classPathElements.addAll( pluginArtifacts == null ? Collections.<Artifact>emptySet() : pluginArtifacts );
for ( Artifact classPathElement : classPathElements )
{
File artifact = classPathElement.getFile();
if ( null != artifact )
{
String type = classPathElement.getType();
if (!type.equals("pom")){
cp += classPathElement.getFile().getAbsolutePath();
cp += File.pathSeparatorChar;
}
}
}
Iterator<String> outIter = outDirs.iterator();
while ( outIter.hasNext() )
{
cp += outIter.next();
cp += File.pathSeparatorChar;
}
if ( cp.endsWith( "" + File.pathSeparatorChar ) )
{
cp = cp.substring( 0, cp.length() - 1 );
}
cp = StringUtils.replace( cp, "//", "/" );
return cp;
} | java | @SuppressWarnings( "unchecked" )
public static String createClassPath( MavenProject project, List<Artifact> pluginArtifacts, List<String> outDirs )
{
String cp = new String();
Set<Artifact> classPathElements = Collections.synchronizedSet( new LinkedHashSet<Artifact>() );
Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
classPathElements.addAll( dependencyArtifacts == null ? Collections.<Artifact>emptySet() : dependencyArtifacts );
classPathElements.addAll( project.getArtifacts() );
classPathElements.addAll( pluginArtifacts == null ? Collections.<Artifact>emptySet() : pluginArtifacts );
for ( Artifact classPathElement : classPathElements )
{
File artifact = classPathElement.getFile();
if ( null != artifact )
{
String type = classPathElement.getType();
if (!type.equals("pom")){
cp += classPathElement.getFile().getAbsolutePath();
cp += File.pathSeparatorChar;
}
}
}
Iterator<String> outIter = outDirs.iterator();
while ( outIter.hasNext() )
{
cp += outIter.next();
cp += File.pathSeparatorChar;
}
if ( cp.endsWith( "" + File.pathSeparatorChar ) )
{
cp = cp.substring( 0, cp.length() - 1 );
}
cp = StringUtils.replace( cp, "//", "/" );
return cp;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"String",
"createClassPath",
"(",
"MavenProject",
"project",
",",
"List",
"<",
"Artifact",
">",
"pluginArtifacts",
",",
"List",
"<",
"String",
">",
"outDirs",
")",
"{",
"String",
"cp",
"="... | Constructs AspectJ compiler classpath string
@param project the Maven Project
@param pluginArtifacts the plugin Artifacts
@param outDirs the outputDirectories
@return a os spesific classpath string | [
"Constructs",
"AspectJ",
"compiler",
"classpath",
"string"
] | train | https://github.com/mojohaus/aspectj-maven-plugin/blob/120ee1ce08b93873931035ed98cd70e3ccceeefb/src/main/java/org/codehaus/mojo/aspectj/AjcHelper.java#L89-L124 |
qiujuer/Genius-Android | caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/AbsSeekBar.java | AbsSeekBar.setThumbColor | public void setThumbColor(int startColor, int endColor) {
mSeekBarDrawable.setThumbColor(ColorStateList.valueOf(startColor));
if (mIndicator != null)
mIndicator.setColors(startColor, endColor);
} | java | public void setThumbColor(int startColor, int endColor) {
mSeekBarDrawable.setThumbColor(ColorStateList.valueOf(startColor));
if (mIndicator != null)
mIndicator.setColors(startColor, endColor);
} | [
"public",
"void",
"setThumbColor",
"(",
"int",
"startColor",
",",
"int",
"endColor",
")",
"{",
"mSeekBarDrawable",
".",
"setThumbColor",
"(",
"ColorStateList",
".",
"valueOf",
"(",
"startColor",
")",
")",
";",
"if",
"(",
"mIndicator",
"!=",
"null",
")",
"mIn... | Sets the color of the seek thumb, as well as the color of the popup indicator.
@param startColor The color the seek thumb will be changed to
@param endColor The color the popup indicator will be changed to | [
"Sets",
"the",
"color",
"of",
"the",
"seek",
"thumb",
"as",
"well",
"as",
"the",
"color",
"of",
"the",
"popup",
"indicator",
"."
] | train | https://github.com/qiujuer/Genius-Android/blob/babefaf1321f5883a21cada582b6fa5104adc648/caprice/ui/src/main/java/net/qiujuer/genius/ui/widget/AbsSeekBar.java#L502-L506 |
firebase/geofire-java | common/src/main/java/com/firebase/geofire/GeoFire.java | GeoFire.setLocation | public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) {
if (key == null) {
throw new NullPointerException();
}
DatabaseReference keyRef = this.getDatabaseRefForKey(key);
GeoHash geoHash = new GeoHash(location);
Map<String, Object> updates = new HashMap<>();
updates.put("g", geoHash.getGeoHashString());
updates.put("l", Arrays.asList(location.latitude, location.longitude));
if (completionListener != null) {
keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
completionListener.onComplete(key, databaseError);
}
});
} else {
keyRef.setValue(updates, geoHash.getGeoHashString());
}
} | java | public void setLocation(final String key, final GeoLocation location, final CompletionListener completionListener) {
if (key == null) {
throw new NullPointerException();
}
DatabaseReference keyRef = this.getDatabaseRefForKey(key);
GeoHash geoHash = new GeoHash(location);
Map<String, Object> updates = new HashMap<>();
updates.put("g", geoHash.getGeoHashString());
updates.put("l", Arrays.asList(location.latitude, location.longitude));
if (completionListener != null) {
keyRef.setValue(updates, geoHash.getGeoHashString(), new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
completionListener.onComplete(key, databaseError);
}
});
} else {
keyRef.setValue(updates, geoHash.getGeoHashString());
}
} | [
"public",
"void",
"setLocation",
"(",
"final",
"String",
"key",
",",
"final",
"GeoLocation",
"location",
",",
"final",
"CompletionListener",
"completionListener",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
... | Sets the location for a given key.
@param key The key to save the location for
@param location The location of this key
@param completionListener A listener that is called once the location was successfully saved on the server or an
error occurred | [
"Sets",
"the",
"location",
"for",
"a",
"given",
"key",
"."
] | train | https://github.com/firebase/geofire-java/blob/c46ff339060d150741a8d0d40c8e73b78edca6c3/common/src/main/java/com/firebase/geofire/GeoFire.java#L165-L184 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/classimbalance/BaseUnderSamplingPreProcessor.java | BaseUnderSamplingPreProcessor.calculateBernoulli | private INDArray calculateBernoulli(INDArray minorityLabels, INDArray labelMask, double targetMinorityDist) {
INDArray minorityClass = minorityLabels.castTo(Nd4j.defaultFloatingPointType()).muli(labelMask);
INDArray majorityClass = minorityLabels.rsub(1.0).muli(labelMask); //rsub(1.0) is equivalent to swapping 0s and 1s
//all minorityLabel class, keep masks as is
//presence of minoriy class and donotmask minority windows set to true return label as is
if (majorityClass.sumNumber().intValue() == 0
|| (minorityClass.sumNumber().intValue() > 0 && donotMaskMinorityWindows))
return labelMask;
//all majority class and set to not mask all majority windows sample majority class by 1-targetMinorityDist
if (minorityClass.sumNumber().intValue() == 0 && !maskAllMajorityWindows)
return labelMask.muli(1 - targetMinorityDist);
//Probabilities to be used for bernoulli sampling
INDArray minoritymajorityRatio = minorityClass.sum(1).div(majorityClass.sum(1));
INDArray majorityBernoulliP = minoritymajorityRatio.muli(1 - targetMinorityDist).divi(targetMinorityDist);
BooleanIndexing.replaceWhere(majorityBernoulliP, 1.0, Conditions.greaterThan(1.0)); //if minority ratio is already met round down to 1.0
return majorityClass.muliColumnVector(majorityBernoulliP).addi(minorityClass);
} | java | private INDArray calculateBernoulli(INDArray minorityLabels, INDArray labelMask, double targetMinorityDist) {
INDArray minorityClass = minorityLabels.castTo(Nd4j.defaultFloatingPointType()).muli(labelMask);
INDArray majorityClass = minorityLabels.rsub(1.0).muli(labelMask); //rsub(1.0) is equivalent to swapping 0s and 1s
//all minorityLabel class, keep masks as is
//presence of minoriy class and donotmask minority windows set to true return label as is
if (majorityClass.sumNumber().intValue() == 0
|| (minorityClass.sumNumber().intValue() > 0 && donotMaskMinorityWindows))
return labelMask;
//all majority class and set to not mask all majority windows sample majority class by 1-targetMinorityDist
if (minorityClass.sumNumber().intValue() == 0 && !maskAllMajorityWindows)
return labelMask.muli(1 - targetMinorityDist);
//Probabilities to be used for bernoulli sampling
INDArray minoritymajorityRatio = minorityClass.sum(1).div(majorityClass.sum(1));
INDArray majorityBernoulliP = minoritymajorityRatio.muli(1 - targetMinorityDist).divi(targetMinorityDist);
BooleanIndexing.replaceWhere(majorityBernoulliP, 1.0, Conditions.greaterThan(1.0)); //if minority ratio is already met round down to 1.0
return majorityClass.muliColumnVector(majorityBernoulliP).addi(minorityClass);
} | [
"private",
"INDArray",
"calculateBernoulli",
"(",
"INDArray",
"minorityLabels",
",",
"INDArray",
"labelMask",
",",
"double",
"targetMinorityDist",
")",
"{",
"INDArray",
"minorityClass",
"=",
"minorityLabels",
".",
"castTo",
"(",
"Nd4j",
".",
"defaultFloatingPointType",
... | /*
Given a list of labels return the bernoulli prob that the masks
will be sampled at to meet the target minority label distribution
Masks at time steps where label is the minority class will always be one
i.e a bernoulli with p = 1
Masks at time steps where label is the majority class will be sampled from
a bernoulli dist with p
= (minorityCount/majorityCount) * ((1-targetDist)/targetDist) | [
"/",
"*",
"Given",
"a",
"list",
"of",
"labels",
"return",
"the",
"bernoulli",
"prob",
"that",
"the",
"masks",
"will",
"be",
"sampled",
"at",
"to",
"meet",
"the",
"target",
"minority",
"label",
"distribution"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/dataset/api/preprocessor/classimbalance/BaseUnderSamplingPreProcessor.java#L102-L121 |
googleapis/google-http-java-client | google-http-client/src/main/java/com/google/api/client/http/HttpMediaType.java | HttpMediaType.setParameter | public HttpMediaType setParameter(String name, String value) {
if (value == null) {
removeParameter(name);
return this;
}
Preconditions.checkArgument(
TOKEN_REGEX.matcher(name).matches(), "Name contains reserved characters");
cachedBuildResult = null;
parameters.put(name.toLowerCase(Locale.US), value);
return this;
} | java | public HttpMediaType setParameter(String name, String value) {
if (value == null) {
removeParameter(name);
return this;
}
Preconditions.checkArgument(
TOKEN_REGEX.matcher(name).matches(), "Name contains reserved characters");
cachedBuildResult = null;
parameters.put(name.toLowerCase(Locale.US), value);
return this;
} | [
"public",
"HttpMediaType",
"setParameter",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"removeParameter",
"(",
"name",
")",
";",
"return",
"this",
";",
"}",
"Preconditions",
".",
"checkArgument",
"("... | Sets the media parameter to the specified value.
@param name case-insensitive name of the parameter
@param value value of the parameter or {@code null} to remove | [
"Sets",
"the",
"media",
"parameter",
"to",
"the",
"specified",
"value",
"."
] | train | https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/http/HttpMediaType.java#L203-L214 |
glyptodon/guacamole-client | guacamole-ext/src/main/java/org/apache/guacamole/net/auth/simple/SimpleObjectPermissionSet.java | SimpleObjectPermissionSet.createPermissions | private static Set<ObjectPermission> createPermissions(Collection<String> identifiers,
Collection<ObjectPermission.Type> types) {
// Add a permission of each type to the set for each identifier given
Set<ObjectPermission> permissions = new HashSet<>(identifiers.size());
types.forEach(type -> {
identifiers.forEach(identifier -> permissions.add(new ObjectPermission(type, identifier)));
});
return permissions;
} | java | private static Set<ObjectPermission> createPermissions(Collection<String> identifiers,
Collection<ObjectPermission.Type> types) {
// Add a permission of each type to the set for each identifier given
Set<ObjectPermission> permissions = new HashSet<>(identifiers.size());
types.forEach(type -> {
identifiers.forEach(identifier -> permissions.add(new ObjectPermission(type, identifier)));
});
return permissions;
} | [
"private",
"static",
"Set",
"<",
"ObjectPermission",
">",
"createPermissions",
"(",
"Collection",
"<",
"String",
">",
"identifiers",
",",
"Collection",
"<",
"ObjectPermission",
".",
"Type",
">",
"types",
")",
"{",
"// Add a permission of each type to the set for each id... | Creates a new set of ObjectPermissions for each possible combination of
the given identifiers and permission types.
@param identifiers
The identifiers which should have one ObjectPermission for each of
the given permission types.
@param types
The permissions which should be granted for each of the given
identifiers.
@return
A new set of ObjectPermissions containing one ObjectPermission for
each possible combination of the given identifiers and permission
types. | [
"Creates",
"a",
"new",
"set",
"of",
"ObjectPermissions",
"for",
"each",
"possible",
"combination",
"of",
"the",
"given",
"identifiers",
"and",
"permission",
"types",
"."
] | train | https://github.com/glyptodon/guacamole-client/blob/ea1b10e9d1e3f1fa640dff2ca64d61b44bf1ace9/guacamole-ext/src/main/java/org/apache/guacamole/net/auth/simple/SimpleObjectPermissionSet.java#L69-L80 |
jimmoores/quandl4j | core/src/main/java/com/jimmoores/quandl/QuandlCodeRequest.java | QuandlCodeRequest.allColumns | public static QuandlCodeRequest allColumns(final String quandlCode) {
ArgumentChecker.notNull(quandlCode, "quandlCode");
return new QuandlCodeRequest(quandlCode, null);
} | java | public static QuandlCodeRequest allColumns(final String quandlCode) {
ArgumentChecker.notNull(quandlCode, "quandlCode");
return new QuandlCodeRequest(quandlCode, null);
} | [
"public",
"static",
"QuandlCodeRequest",
"allColumns",
"(",
"final",
"String",
"quandlCode",
")",
"{",
"ArgumentChecker",
".",
"notNull",
"(",
"quandlCode",
",",
"\"quandlCode\"",
")",
";",
"return",
"new",
"QuandlCodeRequest",
"(",
"quandlCode",
",",
"null",
")",... | Request all columns for a given quandlCode.
@param quandlCode the Quandl code you're interested in, not null
@return an request instance, not null | [
"Request",
"all",
"columns",
"for",
"a",
"given",
"quandlCode",
"."
] | train | https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/QuandlCodeRequest.java#L36-L39 |
eclipse/xtext-extras | org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java | JvmTypesBuilder.addAnnotation | public void addAnnotation(/* @Nullable */ JvmAnnotationTarget target, /* @Nullable */ XAnnotation annotation) {
if(annotation == null || target == null)
return;
JvmAnnotationReference annotationReference = getJvmAnnotationReference(annotation);
if(annotationReference != null) {
target.getAnnotations().add(annotationReference);
}
} | java | public void addAnnotation(/* @Nullable */ JvmAnnotationTarget target, /* @Nullable */ XAnnotation annotation) {
if(annotation == null || target == null)
return;
JvmAnnotationReference annotationReference = getJvmAnnotationReference(annotation);
if(annotationReference != null) {
target.getAnnotations().add(annotationReference);
}
} | [
"public",
"void",
"addAnnotation",
"(",
"/* @Nullable */",
"JvmAnnotationTarget",
"target",
",",
"/* @Nullable */",
"XAnnotation",
"annotation",
")",
"{",
"if",
"(",
"annotation",
"==",
"null",
"||",
"target",
"==",
"null",
")",
"return",
";",
"JvmAnnotationReferenc... | Translates an {@link XAnnotation} to a {@link JvmAnnotationReference}
and adds them to the given {@link JvmAnnotationTarget}.
@param target the annotation target. If <code>null</code> this method does nothing.
@param annotation the annotation. If <code>null</code> this method does nothing. | [
"Translates",
"an",
"{",
"@link",
"XAnnotation",
"}",
"to",
"a",
"{",
"@link",
"JvmAnnotationReference",
"}",
"and",
"adds",
"them",
"to",
"the",
"given",
"{",
"@link",
"JvmAnnotationTarget",
"}",
"."
] | train | https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/jvmmodel/JvmTypesBuilder.java#L1369-L1376 |
google/closure-compiler | src/com/google/javascript/jscomp/RewriteJsonToModule.java | RewriteJsonToModule.processBrowserFieldAdvancedUsage | private void processBrowserFieldAdvancedUsage(String dirName, Node entry) {
for (Node child : entry.children()) {
Node value = child.getFirstChild();
checkState(child.isStringKey() && (value.isString() || value.isFalse()));
String path = child.getString();
if (path.startsWith(ModuleLoader.DEFAULT_FILENAME_PREFIX)) {
path = path.substring(ModuleLoader.DEFAULT_FILENAME_PREFIX.length());
}
String replacement =
value.isString()
? dirName + value.getString()
: ModuleLoader.JSC_BROWSER_BLACKLISTED_MARKER;
packageJsonMainEntries.put(dirName + path, replacement);
}
} | java | private void processBrowserFieldAdvancedUsage(String dirName, Node entry) {
for (Node child : entry.children()) {
Node value = child.getFirstChild();
checkState(child.isStringKey() && (value.isString() || value.isFalse()));
String path = child.getString();
if (path.startsWith(ModuleLoader.DEFAULT_FILENAME_PREFIX)) {
path = path.substring(ModuleLoader.DEFAULT_FILENAME_PREFIX.length());
}
String replacement =
value.isString()
? dirName + value.getString()
: ModuleLoader.JSC_BROWSER_BLACKLISTED_MARKER;
packageJsonMainEntries.put(dirName + path, replacement);
}
} | [
"private",
"void",
"processBrowserFieldAdvancedUsage",
"(",
"String",
"dirName",
",",
"Node",
"entry",
")",
"{",
"for",
"(",
"Node",
"child",
":",
"entry",
".",
"children",
"(",
")",
")",
"{",
"Node",
"value",
"=",
"child",
".",
"getFirstChild",
"(",
")",
... | For browser field entries in package.json files that are used in an advanced manner
(https://github.com/defunctzombie/package-browser-field-spec/#replace-specific-files---advanced),
track the entries in that object literal as module file replacements. | [
"For",
"browser",
"field",
"entries",
"in",
"package",
".",
"json",
"files",
"that",
"are",
"used",
"in",
"an",
"advanced",
"manner",
"(",
"https",
":",
"//",
"github",
".",
"com",
"/",
"defunctzombie",
"/",
"package",
"-",
"browser",
"-",
"field",
"-",
... | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RewriteJsonToModule.java#L173-L192 |
looly/hutool | hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java | ServletUtil.fillBean | public static <T> T fillBean(final ServletRequest request, T bean, CopyOptions copyOptions) {
final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName());
return BeanUtil.fillBean(bean, new ValueProvider<String>() {
@Override
public Object value(String key, Type valueType) {
String value = request.getParameter(key);
if (StrUtil.isEmpty(value)) {
// 使用类名前缀尝试查找值
value = request.getParameter(beanName + StrUtil.DOT + key);
if (StrUtil.isEmpty(value)) {
// 此处取得的值为空时跳过,包括null和""
value = null;
}
}
return value;
}
@Override
public boolean containsKey(String key) {
// 对于Servlet来说,返回值null意味着无此参数
return (null != request.getParameter(key)) || (null != request.getParameter(beanName + StrUtil.DOT + key));
}
}, copyOptions);
} | java | public static <T> T fillBean(final ServletRequest request, T bean, CopyOptions copyOptions) {
final String beanName = StrUtil.lowerFirst(bean.getClass().getSimpleName());
return BeanUtil.fillBean(bean, new ValueProvider<String>() {
@Override
public Object value(String key, Type valueType) {
String value = request.getParameter(key);
if (StrUtil.isEmpty(value)) {
// 使用类名前缀尝试查找值
value = request.getParameter(beanName + StrUtil.DOT + key);
if (StrUtil.isEmpty(value)) {
// 此处取得的值为空时跳过,包括null和""
value = null;
}
}
return value;
}
@Override
public boolean containsKey(String key) {
// 对于Servlet来说,返回值null意味着无此参数
return (null != request.getParameter(key)) || (null != request.getParameter(beanName + StrUtil.DOT + key));
}
}, copyOptions);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"fillBean",
"(",
"final",
"ServletRequest",
"request",
",",
"T",
"bean",
",",
"CopyOptions",
"copyOptions",
")",
"{",
"final",
"String",
"beanName",
"=",
"StrUtil",
".",
"lowerFirst",
"(",
"bean",
".",
"getClass",
"(... | ServletRequest 参数转Bean
@param <T> Bean类型
@param request ServletRequest
@param bean Bean
@param copyOptions 注入时的设置
@return Bean
@since 3.0.4 | [
"ServletRequest",
"参数转Bean"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L125-L148 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/report/AnalysisScreen.java | AnalysisScreen.addSummary | public void addSummary(Record recSummary, BaseField[][] mxKeyFields, BaseField[][] mxDataFields)
{
try {
recSummary.addNew();
// First move the key to see if a record exists
this.setupSummaryKey(mxKeyFields);
boolean bSuccess = recSummary.seek("=");
if (bSuccess)
recSummary.edit();
else
{
recSummary.addNew();
this.setupSummaryKey(mxKeyFields);
}
this.addSummaryData(mxDataFields);
if (bSuccess)
recSummary.set();
else
recSummary.add();
} catch (DBException ex) {
ex.printStackTrace();
}
} | java | public void addSummary(Record recSummary, BaseField[][] mxKeyFields, BaseField[][] mxDataFields)
{
try {
recSummary.addNew();
// First move the key to see if a record exists
this.setupSummaryKey(mxKeyFields);
boolean bSuccess = recSummary.seek("=");
if (bSuccess)
recSummary.edit();
else
{
recSummary.addNew();
this.setupSummaryKey(mxKeyFields);
}
this.addSummaryData(mxDataFields);
if (bSuccess)
recSummary.set();
else
recSummary.add();
} catch (DBException ex) {
ex.printStackTrace();
}
} | [
"public",
"void",
"addSummary",
"(",
"Record",
"recSummary",
",",
"BaseField",
"[",
"]",
"[",
"]",
"mxKeyFields",
",",
"BaseField",
"[",
"]",
"[",
"]",
"mxDataFields",
")",
"{",
"try",
"{",
"recSummary",
".",
"addNew",
"(",
")",
";",
"// First move the key... | Add/update this summary record.
@param recSummary The destination summary record.
@param mxKeyFields The key fields map.
@param mxDataFields The data fields map. | [
"Add",
"/",
"update",
"this",
"summary",
"record",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/report/AnalysisScreen.java#L113-L135 |
jqno/equalsverifier | src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java | ConfiguredEqualsVerifier.withPrefabValues | public <S> ConfiguredEqualsVerifier withPrefabValues(Class<S> otherType, S red, S black) {
PrefabValuesApi.addPrefabValues(factoryCache, otherType, red, black);
return this;
} | java | public <S> ConfiguredEqualsVerifier withPrefabValues(Class<S> otherType, S red, S black) {
PrefabValuesApi.addPrefabValues(factoryCache, otherType, red, black);
return this;
} | [
"public",
"<",
"S",
">",
"ConfiguredEqualsVerifier",
"withPrefabValues",
"(",
"Class",
"<",
"S",
">",
"otherType",
",",
"S",
"red",
",",
"S",
"black",
")",
"{",
"PrefabValuesApi",
".",
"addPrefabValues",
"(",
"factoryCache",
",",
"otherType",
",",
"red",
","... | Adds prefabricated values for instance fields of classes that
EqualsVerifier cannot instantiate by itself.
@param <S> The class of the prefabricated values.
@param otherType The class of the prefabricated values.
@param red An instance of {@code S}.
@param black Another instance of {@code S}, not equal to {@code red}.
@return {@code this}, for easy method chaining.
@throws NullPointerException If either {@code otherType}, {@code red},
or {@code black} is null.
@throws IllegalArgumentException If {@code red} equals {@code black}. | [
"Adds",
"prefabricated",
"values",
"for",
"instance",
"fields",
"of",
"classes",
"that",
"EqualsVerifier",
"cannot",
"instantiate",
"by",
"itself",
"."
] | train | https://github.com/jqno/equalsverifier/blob/25d73c9cb801c8b20b257d1d1283ac6e0585ef1d/src/main/java/nl/jqno/equalsverifier/ConfiguredEqualsVerifier.java#L42-L45 |
OpenTSDB/opentsdb | src/core/Internal.java | Internal.decodeHistogramDataPoint | public static HistogramDataPoint decodeHistogramDataPoint(final TSDB tsdb,
final long base_time,
final byte[] qualifier,
final byte[] value) {
final HistogramDataPointCodec decoder =
tsdb.histogramManager().getCodec((int) value[0]);
long timestamp = getTimeStampFromNonDP(base_time, qualifier);
final Histogram histogram = decoder.decode(value, true);
return new SimpleHistogramDataPointAdapter(histogram, timestamp);
} | java | public static HistogramDataPoint decodeHistogramDataPoint(final TSDB tsdb,
final long base_time,
final byte[] qualifier,
final byte[] value) {
final HistogramDataPointCodec decoder =
tsdb.histogramManager().getCodec((int) value[0]);
long timestamp = getTimeStampFromNonDP(base_time, qualifier);
final Histogram histogram = decoder.decode(value, true);
return new SimpleHistogramDataPointAdapter(histogram, timestamp);
} | [
"public",
"static",
"HistogramDataPoint",
"decodeHistogramDataPoint",
"(",
"final",
"TSDB",
"tsdb",
",",
"final",
"long",
"base_time",
",",
"final",
"byte",
"[",
"]",
"qualifier",
",",
"final",
"byte",
"[",
"]",
"value",
")",
"{",
"final",
"HistogramDataPointCod... | Decode the histogram point from the given key and values
@param tsdb The TSDB to use when fetching the decoder manager.
@param base_time the base time of the histogram
@param qualifier the qualifier used to store the histogram
@param value the encoded value of the histogram
@return the decoded {@code HistogramDataPoint} | [
"Decode",
"the",
"histogram",
"point",
"from",
"the",
"given",
"key",
"and",
"values"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/Internal.java#L1074-L1083 |
Metatavu/edelphi | edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/util/QueryFieldDataStatistics.java | QueryFieldDataStatistics.getQuantile | public Double getQuantile(int quantile, int base) {
if (getCount() == 0)
return null;
if ((quantile > base) || (quantile <= 0) || (base <= 0))
throw new IllegalArgumentException("Incorrect quantile/base specified.");
double quantileFraq = (double) quantile / base;
int index = (int) Math.round(quantileFraq * (getCount() - 1));
return (double) data.get(index) + shift;
} | java | public Double getQuantile(int quantile, int base) {
if (getCount() == 0)
return null;
if ((quantile > base) || (quantile <= 0) || (base <= 0))
throw new IllegalArgumentException("Incorrect quantile/base specified.");
double quantileFraq = (double) quantile / base;
int index = (int) Math.round(quantileFraq * (getCount() - 1));
return (double) data.get(index) + shift;
} | [
"public",
"Double",
"getQuantile",
"(",
"int",
"quantile",
",",
"int",
"base",
")",
"{",
"if",
"(",
"getCount",
"(",
")",
"==",
"0",
")",
"return",
"null",
";",
"if",
"(",
"(",
"quantile",
">",
"base",
")",
"||",
"(",
"quantile",
"<=",
"0",
")",
... | Returns quantile over base value.
@param quantile quantile index
@param base quantile base
@return quantile over base value. | [
"Returns",
"quantile",
"over",
"base",
"value",
"."
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/pages/panel/admin/report/util/QueryFieldDataStatistics.java#L110-L122 |
js-lib-com/commons | src/main/java/js/util/Classes.java | Classes.newRegisteredInstance | @SuppressWarnings("unchecked")
private static <T> T newRegisteredInstance(Map<Class<?>, Class<?>> implementationsRegistry, Type interfaceType) throws BugError
{
Class<?> implementation = getImplementation(implementationsRegistry, interfaceType);
try {
return (T)implementation.newInstance();
}
catch(IllegalAccessException e) {
// illegal access exception is thrown if the class or its no-arguments constructor is not accessible
// since we use well known JRE classes this condition may never meet
throw new BugError(e);
}
catch(InstantiationException e) {
// instantiation exception is thrown if class is abstract, interface, array, primitive or void
// since we use well known JRE classes this condition may never meet
throw new BugError(e);
}
} | java | @SuppressWarnings("unchecked")
private static <T> T newRegisteredInstance(Map<Class<?>, Class<?>> implementationsRegistry, Type interfaceType) throws BugError
{
Class<?> implementation = getImplementation(implementationsRegistry, interfaceType);
try {
return (T)implementation.newInstance();
}
catch(IllegalAccessException e) {
// illegal access exception is thrown if the class or its no-arguments constructor is not accessible
// since we use well known JRE classes this condition may never meet
throw new BugError(e);
}
catch(InstantiationException e) {
// instantiation exception is thrown if class is abstract, interface, array, primitive or void
// since we use well known JRE classes this condition may never meet
throw new BugError(e);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"static",
"<",
"T",
">",
"T",
"newRegisteredInstance",
"(",
"Map",
"<",
"Class",
"<",
"?",
">",
",",
"Class",
"<",
"?",
">",
">",
"implementationsRegistry",
",",
"Type",
"interfaceType",
")",
"... | Lookup implementation for requested interface into given registry and return a new instance of it.
@param implementationsRegistry implementations registry,
@param interfaceType interface to lookup into registry.
@param <T> instance type.
@return implementation instance.
@throws BugError if implementation is not found into registry. | [
"Lookup",
"implementation",
"for",
"requested",
"interface",
"into",
"given",
"registry",
"and",
"return",
"a",
"new",
"instance",
"of",
"it",
"."
] | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/util/Classes.java#L1505-L1522 |
williamwebb/alogger | BillingHelper/src/main/java/com/jug6ernaut/billing/IabHelper.java | IabHelper.queryInventoryAsync | public void queryInventoryAsync(final boolean querySkuDetails,
final List<String> moreSkus,
final QueryInventoryFinishedListener listener) {
final Handler handler = new Handler();
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
}
})).start();
} | java | public void queryInventoryAsync(final boolean querySkuDetails,
final List<String> moreSkus,
final QueryInventoryFinishedListener listener) {
final Handler handler = new Handler();
checkNotDisposed();
checkSetupDone("queryInventory");
flagStartAsync("refresh inventory");
(new Thread(new Runnable() {
public void run() {
IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful.");
Inventory inv = null;
try {
inv = queryInventory(querySkuDetails, moreSkus);
}
catch (IabException ex) {
result = ex.getResult();
}
flagEndAsync();
final IabResult result_f = result;
final Inventory inv_f = inv;
if (!mDisposed && listener != null) {
handler.post(new Runnable() {
public void run() {
listener.onQueryInventoryFinished(result_f, inv_f);
}
});
}
}
})).start();
} | [
"public",
"void",
"queryInventoryAsync",
"(",
"final",
"boolean",
"querySkuDetails",
",",
"final",
"List",
"<",
"String",
">",
"moreSkus",
",",
"final",
"QueryInventoryFinishedListener",
"listener",
")",
"{",
"final",
"Handler",
"handler",
"=",
"new",
"Handler",
"... | Asynchronous wrapper for inventory query. This will perform an inventory
query as described in {@link #queryInventory}, but will do so asynchronously
and call back the specified listener upon completion. This method is safe to
call from a UI thread.
@param querySkuDetails as in {@link #queryInventory}
@param moreSkus as in {@link #queryInventory}
@param listener The listener to notify when the refresh operation completes. | [
"Asynchronous",
"wrapper",
"for",
"inventory",
"query",
".",
"This",
"will",
"perform",
"an",
"inventory",
"query",
"as",
"described",
"in",
"{",
"@link",
"#queryInventory",
"}",
"but",
"will",
"do",
"so",
"asynchronously",
"and",
"call",
"back",
"the",
"speci... | train | https://github.com/williamwebb/alogger/blob/61fca49e0b8d9c3a76c40da8883ac354b240351e/BillingHelper/src/main/java/com/jug6ernaut/billing/IabHelper.java#L615-L646 |
Berico-Technologies/CLAVIN | src/main/java/com/bericotech/clavin/gazetteer/FeatureCodeBuilder.java | FeatureCodeBuilder.main | public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream codeStream = FeatureCodeBuilder.class.getClassLoader().getResourceAsStream("featureCodes_en.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(codeStream, Charset.forName("UTF-8")));
// generate dummy feature code for top-level territories
Set<Code> featureCodes = new TreeSet<Code>();
featureCodes.add(new Code("TERRI", "A", "independent territory", "a territory that acts as an independent political entity",
"manually added to identify territories that can contain other administrative divisions"));
String line;
while ((line = in.readLine()) != null) {
String[] tokens = line.split("\t");
if (!tokens[0].equals("null")) {
String[] codes = tokens[0].split("\\.");
featureCodes.add(new Code(codes[1], codes[0], tokens[1], tokens.length == 3 ? tokens[2] : ""));
}
}
in.close();
for (Code code : featureCodes) {
System.out.println(code);
}
System.out.println("// manually added for locations not assigned to a feature code");
System.out.println("NULL(FeatureClass.NULL, \"not available\", \"\", false);");
} | java | public static void main(String[] args) throws FileNotFoundException, IOException {
InputStream codeStream = FeatureCodeBuilder.class.getClassLoader().getResourceAsStream("featureCodes_en.txt");
BufferedReader in = new BufferedReader(new InputStreamReader(codeStream, Charset.forName("UTF-8")));
// generate dummy feature code for top-level territories
Set<Code> featureCodes = new TreeSet<Code>();
featureCodes.add(new Code("TERRI", "A", "independent territory", "a territory that acts as an independent political entity",
"manually added to identify territories that can contain other administrative divisions"));
String line;
while ((line = in.readLine()) != null) {
String[] tokens = line.split("\t");
if (!tokens[0].equals("null")) {
String[] codes = tokens[0].split("\\.");
featureCodes.add(new Code(codes[1], codes[0], tokens[1], tokens.length == 3 ? tokens[2] : ""));
}
}
in.close();
for (Code code : featureCodes) {
System.out.println(code);
}
System.out.println("// manually added for locations not assigned to a feature code");
System.out.println("NULL(FeatureClass.NULL, \"not available\", \"\", false);");
} | [
"public",
"static",
"void",
"main",
"(",
"String",
"[",
"]",
"args",
")",
"throws",
"FileNotFoundException",
",",
"IOException",
"{",
"InputStream",
"codeStream",
"=",
"FeatureCodeBuilder",
".",
"class",
".",
"getClassLoader",
"(",
")",
".",
"getResourceAsStream",... | Reads-in featureCodes_en.txt file, spits-out
{@link FeatureClass} enum definitions.
@param args the command line arguments
@throws FileNotFoundException if featureCodes_en.txt is not found on the classpath
@throws IOException if an error occurs reading the featureCodes file | [
"Reads",
"-",
"in",
"featureCodes_en",
".",
"txt",
"file",
"spits",
"-",
"out",
"{",
"@link",
"FeatureClass",
"}",
"enum",
"definitions",
".",
"@param",
"args",
"the",
"command",
"line",
"arguments"
] | train | https://github.com/Berico-Technologies/CLAVIN/blob/f73c741f33a01b91aa5b06e71860bc354ef3010d/src/main/java/com/bericotech/clavin/gazetteer/FeatureCodeBuilder.java#L56-L77 |
carewebframework/carewebframework-vista | org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Security.java | Security.changePassword | public static String changePassword(BrokerSession session, String oldPassword, String newPassword) {
String cipherKey = session.getServerCaps().getCipherKey();
String result = session.callRPC("RGNETBRP CVC", encrypt(oldPassword, cipherKey), encrypt(newPassword, cipherKey));
return result.startsWith("0") ? null : StrUtil.piece(result, StrUtil.U, 2);
} | java | public static String changePassword(BrokerSession session, String oldPassword, String newPassword) {
String cipherKey = session.getServerCaps().getCipherKey();
String result = session.callRPC("RGNETBRP CVC", encrypt(oldPassword, cipherKey), encrypt(newPassword, cipherKey));
return result.startsWith("0") ? null : StrUtil.piece(result, StrUtil.U, 2);
} | [
"public",
"static",
"String",
"changePassword",
"(",
"BrokerSession",
"session",
",",
"String",
"oldPassword",
",",
"String",
"newPassword",
")",
"{",
"String",
"cipherKey",
"=",
"session",
".",
"getServerCaps",
"(",
")",
".",
"getCipherKey",
"(",
")",
";",
"S... | Change a password.
@param session Broker session.
@param oldPassword Old password.
@param newPassword New password.
@return Status message from server. | [
"Change",
"a",
"password",
"."
] | train | https://github.com/carewebframework/carewebframework-vista/blob/883b2cbe395d9e8a21cd19db820f0876bda6b1c6/org.carewebframework.vista.mbroker/src/main/java/org/carewebframework/vista/mbroker/Security.java#L82-L86 |
square/wire | wire-schema/src/main/java/com/squareup/wire/schema/ProtoFile.java | ProtoFile.retainAll | ProtoFile retainAll(Schema schema, MarkSet markSet) {
ImmutableList.Builder<Type> retainedTypes = ImmutableList.builder();
for (Type type : types) {
Type retainedType = type.retainAll(schema, markSet);
if (retainedType != null) {
retainedTypes.add(retainedType);
}
}
ImmutableList.Builder<Service> retainedServices = ImmutableList.builder();
for (Service service : services) {
Service retainedService = service.retainAll(schema, markSet);
if (retainedService != null) {
retainedServices.add(retainedService);
}
}
ProtoFile result = new ProtoFile(location, imports, publicImports, packageName,
retainedTypes.build(), retainedServices.build(), extendList,
options.retainAll(schema, markSet), syntax);
result.javaPackage = javaPackage;
return result;
} | java | ProtoFile retainAll(Schema schema, MarkSet markSet) {
ImmutableList.Builder<Type> retainedTypes = ImmutableList.builder();
for (Type type : types) {
Type retainedType = type.retainAll(schema, markSet);
if (retainedType != null) {
retainedTypes.add(retainedType);
}
}
ImmutableList.Builder<Service> retainedServices = ImmutableList.builder();
for (Service service : services) {
Service retainedService = service.retainAll(schema, markSet);
if (retainedService != null) {
retainedServices.add(retainedService);
}
}
ProtoFile result = new ProtoFile(location, imports, publicImports, packageName,
retainedTypes.build(), retainedServices.build(), extendList,
options.retainAll(schema, markSet), syntax);
result.javaPackage = javaPackage;
return result;
} | [
"ProtoFile",
"retainAll",
"(",
"Schema",
"schema",
",",
"MarkSet",
"markSet",
")",
"{",
"ImmutableList",
".",
"Builder",
"<",
"Type",
">",
"retainedTypes",
"=",
"ImmutableList",
".",
"builder",
"(",
")",
";",
"for",
"(",
"Type",
"type",
":",
"types",
")",
... | Returns a new proto file that omits types and services not in {@code identifiers}. | [
"Returns",
"a",
"new",
"proto",
"file",
"that",
"omits",
"types",
"and",
"services",
"not",
"in",
"{"
] | train | https://github.com/square/wire/blob/4a9a00dfadfc14d6a0780b85810418f9cbc78a49/wire-schema/src/main/java/com/squareup/wire/schema/ProtoFile.java#L141-L163 |
apereo/cas | core/cas-server-core-web-api/src/main/java/org/apereo/cas/services/web/view/AbstractCasView.java | AbstractCasView.getProxyGrantingTicketIou | protected String getProxyGrantingTicketIou(final Map<String, Object> model) {
return (String) model.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU);
} | java | protected String getProxyGrantingTicketIou(final Map<String, Object> model) {
return (String) model.get(CasViewConstants.MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU);
} | [
"protected",
"String",
"getProxyGrantingTicketIou",
"(",
"final",
"Map",
"<",
"String",
",",
"Object",
">",
"model",
")",
"{",
"return",
"(",
"String",
")",
"model",
".",
"get",
"(",
"CasViewConstants",
".",
"MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU",
")",
"... | Gets the PGT-IOU from the model.
@param model the model
@return the pgt-iou id | [
"Gets",
"the",
"PGT",
"-",
"IOU",
"from",
"the",
"model",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-web-api/src/main/java/org/apereo/cas/services/web/view/AbstractCasView.java#L107-L109 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/Analyze.java | Analyze.deepInstanceOf | public static double deepInstanceOf(@DottedClassName String x, @DottedClassName String y) throws ClassNotFoundException {
return deepInstanceOf(AnalysisContext.currentAnalysisContext().lookupClass(x), AnalysisContext.currentAnalysisContext()
.lookupClass(y));
} | java | public static double deepInstanceOf(@DottedClassName String x, @DottedClassName String y) throws ClassNotFoundException {
return deepInstanceOf(AnalysisContext.currentAnalysisContext().lookupClass(x), AnalysisContext.currentAnalysisContext()
.lookupClass(y));
} | [
"public",
"static",
"double",
"deepInstanceOf",
"(",
"@",
"DottedClassName",
"String",
"x",
",",
"@",
"DottedClassName",
"String",
"y",
")",
"throws",
"ClassNotFoundException",
"{",
"return",
"deepInstanceOf",
"(",
"AnalysisContext",
".",
"currentAnalysisContext",
"("... | Given two JavaClasses, try to estimate the probability that an reference
of type x is also an instance of type y. Will return 0 only if it is
impossible and 1 only if it is guaranteed.
@param x
Known type of object
@param y
Type queried about
@return 0 - 1 value indicating probablility | [
"Given",
"two",
"JavaClasses",
"try",
"to",
"estimate",
"the",
"probability",
"that",
"an",
"reference",
"of",
"type",
"x",
"is",
"also",
"an",
"instance",
"of",
"type",
"y",
".",
"Will",
"return",
"0",
"only",
"if",
"it",
"is",
"impossible",
"and",
"1",... | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/Analyze.java#L160-L163 |
apache/incubator-shardingsphere | sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/filler/sharding/dml/ShardingOrPredicateFiller.java | ShardingOrPredicateFiller.buildCondition | public OrCondition buildCondition(final OrPredicateSegment sqlSegment, final SQLStatement sqlStatement) {
OrCondition result = createOrCondition(sqlSegment, sqlStatement);
createEncryptOrPredicateFiller().fill(sqlSegment, sqlStatement);
return result;
} | java | public OrCondition buildCondition(final OrPredicateSegment sqlSegment, final SQLStatement sqlStatement) {
OrCondition result = createOrCondition(sqlSegment, sqlStatement);
createEncryptOrPredicateFiller().fill(sqlSegment, sqlStatement);
return result;
} | [
"public",
"OrCondition",
"buildCondition",
"(",
"final",
"OrPredicateSegment",
"sqlSegment",
",",
"final",
"SQLStatement",
"sqlStatement",
")",
"{",
"OrCondition",
"result",
"=",
"createOrCondition",
"(",
"sqlSegment",
",",
"sqlStatement",
")",
";",
"createEncryptOrPred... | Build condition.
@param sqlSegment SQL segment
@param sqlStatement SQL statement
@return or condition | [
"Build",
"condition",
"."
] | train | https://github.com/apache/incubator-shardingsphere/blob/f88fd29fc345dfb31fdce12e9e96cbfa0fd2402d/sharding-core/sharding-core-parse/sharding-core-parse-common/src/main/java/org/apache/shardingsphere/core/parse/antlr/filler/sharding/dml/ShardingOrPredicateFiller.java#L66-L70 |
alrocar/POIProxy | es.alrocar.poiproxy/src/main/java/es/alrocar/poiproxy/proxy/POIProxy.java | POIProxy.getPOIs | public String getPOIs(String id, double minX, double minY, double maxX, double maxY, List<Param> optionalParams)
throws Exception {
DescribeService describeService = getDescribeServiceByID(id);
POIProxyEvent beforeEvent = new POIProxyEvent(POIProxyEventEnum.BeforeBrowseExtent, describeService,
new Extent(minX, minY, maxX, maxY), null, null, null, null, null, null, null, null, null);
notifyListenersBeforeRequest(beforeEvent);
String geoJSON = this.getCacheData(beforeEvent);
boolean fromCache = true;
if (geoJSON == null) {
fromCache = false;
geoJSON = getResponseAsGeoJSON(id, optionalParams, describeService, minX, minY, maxX, maxY, 0, 0,
beforeEvent);
}
POIProxyEvent afterEvent = new POIProxyEvent(POIProxyEventEnum.AfterBrowseExtent, describeService,
new Extent(minX, minY, maxX, maxY), null, null, null, null, null, null, null, geoJSON, null);
if (!fromCache) {
storeData(afterEvent);
}
notifyListenersAfterParse(afterEvent);
return geoJSON;
} | java | public String getPOIs(String id, double minX, double minY, double maxX, double maxY, List<Param> optionalParams)
throws Exception {
DescribeService describeService = getDescribeServiceByID(id);
POIProxyEvent beforeEvent = new POIProxyEvent(POIProxyEventEnum.BeforeBrowseExtent, describeService,
new Extent(minX, minY, maxX, maxY), null, null, null, null, null, null, null, null, null);
notifyListenersBeforeRequest(beforeEvent);
String geoJSON = this.getCacheData(beforeEvent);
boolean fromCache = true;
if (geoJSON == null) {
fromCache = false;
geoJSON = getResponseAsGeoJSON(id, optionalParams, describeService, minX, minY, maxX, maxY, 0, 0,
beforeEvent);
}
POIProxyEvent afterEvent = new POIProxyEvent(POIProxyEventEnum.AfterBrowseExtent, describeService,
new Extent(minX, minY, maxX, maxY), null, null, null, null, null, null, null, geoJSON, null);
if (!fromCache) {
storeData(afterEvent);
}
notifyListenersAfterParse(afterEvent);
return geoJSON;
} | [
"public",
"String",
"getPOIs",
"(",
"String",
"id",
",",
"double",
"minX",
",",
"double",
"minY",
",",
"double",
"maxX",
",",
"double",
"maxY",
",",
"List",
"<",
"Param",
">",
"optionalParams",
")",
"throws",
"Exception",
"{",
"DescribeService",
"describeSer... | This method is used to get the pois from a service and return a GeoJSON
document with the data retrieved given a bounding box corners
@param id
The id of the service
@param minX
@param minY
@param maxX
@param maxY
@return The GeoJSON response from the original service response | [
"This",
"method",
"is",
"used",
"to",
"get",
"the",
"pois",
"from",
"a",
"service",
"and",
"return",
"a",
"GeoJSON",
"document",
"with",
"the",
"data",
"retrieved",
"given",
"a",
"bounding",
"box",
"corners"
] | train | https://github.com/alrocar/POIProxy/blob/e1dabe738a862478b2580e90d5fc4209a2997868/es.alrocar.poiproxy/src/main/java/es/alrocar/poiproxy/proxy/POIProxy.java#L430-L458 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/FeaturesImpl.java | FeaturesImpl.listPhraseLists | public List<PhraseListFeatureInfo> listPhraseLists(UUID appId, String versionId, ListPhraseListsOptionalParameter listPhraseListsOptionalParameter) {
return listPhraseListsWithServiceResponseAsync(appId, versionId, listPhraseListsOptionalParameter).toBlocking().single().body();
} | java | public List<PhraseListFeatureInfo> listPhraseLists(UUID appId, String versionId, ListPhraseListsOptionalParameter listPhraseListsOptionalParameter) {
return listPhraseListsWithServiceResponseAsync(appId, versionId, listPhraseListsOptionalParameter).toBlocking().single().body();
} | [
"public",
"List",
"<",
"PhraseListFeatureInfo",
">",
"listPhraseLists",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"ListPhraseListsOptionalParameter",
"listPhraseListsOptionalParameter",
")",
"{",
"return",
"listPhraseListsWithServiceResponseAsync",
"(",
"appId",
... | Gets all the phraselist features.
@param appId The application ID.
@param versionId The version ID.
@param listPhraseListsOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<PhraseListFeatureInfo> object if successful. | [
"Gets",
"all",
"the",
"phraselist",
"features",
"."
] | 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/FeaturesImpl.java#L201-L203 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpp/MPPAbstractTimephasedWorkNormaliser.java | MPPAbstractTimephasedWorkNormaliser.normalise | @Override public void normalise(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
{
if (!list.isEmpty())
{
//dumpList(list);
splitDays(calendar, list);
//dumpList(list);
mergeSameDay(calendar, list);
//dumpList(list);
mergeSameWork(list);
//dumpList(list);
convertToHours(list);
//dumpList(list);
}
} | java | @Override public void normalise(ProjectCalendar calendar, LinkedList<TimephasedWork> list)
{
if (!list.isEmpty())
{
//dumpList(list);
splitDays(calendar, list);
//dumpList(list);
mergeSameDay(calendar, list);
//dumpList(list);
mergeSameWork(list);
//dumpList(list);
convertToHours(list);
//dumpList(list);
}
} | [
"@",
"Override",
"public",
"void",
"normalise",
"(",
"ProjectCalendar",
"calendar",
",",
"LinkedList",
"<",
"TimephasedWork",
">",
"list",
")",
"{",
"if",
"(",
"!",
"list",
".",
"isEmpty",
"(",
")",
")",
"{",
"//dumpList(list);",
"splitDays",
"(",
"calendar"... | This method converts the internal representation of timephased
resource assignment data used by MS Project into a standardised
format to make it easy to work with.
@param calendar current calendar
@param list list of assignment data | [
"This",
"method",
"converts",
"the",
"internal",
"representation",
"of",
"timephased",
"resource",
"assignment",
"data",
"used",
"by",
"MS",
"Project",
"into",
"a",
"standardised",
"format",
"to",
"make",
"it",
"easy",
"to",
"work",
"with",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/MPPAbstractTimephasedWorkNormaliser.java#L50-L64 |
foundation-runtime/logging | logging-log4j/src/main/java/com/cisco/oss/foundation/logging/appender/AbstractRoller.java | AbstractRoller.doFileRoll | private void doFileRoll(final File from, final File to) {
final FileHelper fileHelper = FileHelper.getInstance();
if (!fileHelper.deleteExisting(to)) {
this.getAppender().getErrorHandler()
.error("Unable to delete existing " + to + " for rename");
}
final String original = from.toString();
if (fileHelper.rename(from, to)) {
LogLog.debug("Renamed " + original + " to " + to);
} else {
this.getAppender().getErrorHandler()
.error("Unable to rename " + original + " to " + to);
}
} | java | private void doFileRoll(final File from, final File to) {
final FileHelper fileHelper = FileHelper.getInstance();
if (!fileHelper.deleteExisting(to)) {
this.getAppender().getErrorHandler()
.error("Unable to delete existing " + to + " for rename");
}
final String original = from.toString();
if (fileHelper.rename(from, to)) {
LogLog.debug("Renamed " + original + " to " + to);
} else {
this.getAppender().getErrorHandler()
.error("Unable to rename " + original + " to " + to);
}
} | [
"private",
"void",
"doFileRoll",
"(",
"final",
"File",
"from",
",",
"final",
"File",
"to",
")",
"{",
"final",
"FileHelper",
"fileHelper",
"=",
"FileHelper",
".",
"getInstance",
"(",
")",
";",
"if",
"(",
"!",
"fileHelper",
".",
"deleteExisting",
"(",
"to",
... | Renames the current base log file to the roll file name.
@param from
The current base log file.
@param to
The backup file. | [
"Renames",
"the",
"current",
"base",
"log",
"file",
"to",
"the",
"roll",
"file",
"name",
"."
] | train | https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-log4j/src/main/java/com/cisco/oss/foundation/logging/appender/AbstractRoller.java#L210-L223 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/parser/util/InlineModelResolver.java | InlineModelResolver.copyVendorExtensions | public void copyVendorExtensions(Schema source, Schema target) {
if (source.getExtensions() != null) {
Map<String, Object> vendorExtensions = source.getExtensions();
for (String extName : vendorExtensions.keySet()) {
((SchemaImpl) target).addExtension_compat(extName, vendorExtensions.get(extName));
}
}
} | java | public void copyVendorExtensions(Schema source, Schema target) {
if (source.getExtensions() != null) {
Map<String, Object> vendorExtensions = source.getExtensions();
for (String extName : vendorExtensions.keySet()) {
((SchemaImpl) target).addExtension_compat(extName, vendorExtensions.get(extName));
}
}
} | [
"public",
"void",
"copyVendorExtensions",
"(",
"Schema",
"source",
",",
"Schema",
"target",
")",
"{",
"if",
"(",
"source",
".",
"getExtensions",
"(",
")",
"!=",
"null",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"vendorExtensions",
"=",
"source",
... | Copy vendor extensions from Property to another Property
@param source source property
@param target target property | [
"Copy",
"vendor",
"extensions",
"from",
"Property",
"to",
"another",
"Property"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.openapi/src/com/ibm/ws/microprofile/openapi/impl/parser/util/InlineModelResolver.java#L499-L506 |
apache/incubator-heron | heron/simulator/src/java/org/apache/heron/simulator/Simulator.java | Simulator.submitTopology | public void submitTopology(String name, Config heronConfig, HeronTopology heronTopology) {
TopologyAPI.Topology topologyToRun =
heronTopology.
setConfig(heronConfig).
setName(name).
setState(TopologyAPI.TopologyState.RUNNING).
getTopology();
if (!TopologyUtils.verifyTopology(topologyToRun)) {
throw new RuntimeException("Topology object is Malformed");
}
// TODO (nlu): add simulator support stateful processing
if (isTopologyStateful(heronConfig)) {
throw new RuntimeException("Stateful topology is not supported");
}
TopologyManager topologyManager = new TopologyManager(topologyToRun);
LOG.info("Physical Plan: \n" + topologyManager.getPhysicalPlan());
// Create the stream executor
streamExecutor = new StreamExecutor(topologyManager);
// Create the metrics executor
metricsExecutor = new MetricsExecutor(systemConfig);
// Create instance Executor
for (PhysicalPlans.Instance instance : topologyManager.getPhysicalPlan().getInstancesList()) {
InstanceExecutor instanceExecutor = new InstanceExecutor(
topologyManager.getPhysicalPlan(),
instance.getInstanceId()
);
streamExecutor.addInstanceExecutor(instanceExecutor);
metricsExecutor.addInstanceExecutor(instanceExecutor);
instanceExecutors.add(instanceExecutor);
}
// Start - run executors
// Add exception handler for any uncaught exception here.
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
threadsPool.execute(metricsExecutor);
threadsPool.execute(streamExecutor);
for (InstanceExecutor instanceExecutor : instanceExecutors) {
threadsPool.execute(instanceExecutor);
}
} | java | public void submitTopology(String name, Config heronConfig, HeronTopology heronTopology) {
TopologyAPI.Topology topologyToRun =
heronTopology.
setConfig(heronConfig).
setName(name).
setState(TopologyAPI.TopologyState.RUNNING).
getTopology();
if (!TopologyUtils.verifyTopology(topologyToRun)) {
throw new RuntimeException("Topology object is Malformed");
}
// TODO (nlu): add simulator support stateful processing
if (isTopologyStateful(heronConfig)) {
throw new RuntimeException("Stateful topology is not supported");
}
TopologyManager topologyManager = new TopologyManager(topologyToRun);
LOG.info("Physical Plan: \n" + topologyManager.getPhysicalPlan());
// Create the stream executor
streamExecutor = new StreamExecutor(topologyManager);
// Create the metrics executor
metricsExecutor = new MetricsExecutor(systemConfig);
// Create instance Executor
for (PhysicalPlans.Instance instance : topologyManager.getPhysicalPlan().getInstancesList()) {
InstanceExecutor instanceExecutor = new InstanceExecutor(
topologyManager.getPhysicalPlan(),
instance.getInstanceId()
);
streamExecutor.addInstanceExecutor(instanceExecutor);
metricsExecutor.addInstanceExecutor(instanceExecutor);
instanceExecutors.add(instanceExecutor);
}
// Start - run executors
// Add exception handler for any uncaught exception here.
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
threadsPool.execute(metricsExecutor);
threadsPool.execute(streamExecutor);
for (InstanceExecutor instanceExecutor : instanceExecutors) {
threadsPool.execute(instanceExecutor);
}
} | [
"public",
"void",
"submitTopology",
"(",
"String",
"name",
",",
"Config",
"heronConfig",
",",
"HeronTopology",
"heronTopology",
")",
"{",
"TopologyAPI",
".",
"Topology",
"topologyToRun",
"=",
"heronTopology",
".",
"setConfig",
"(",
"heronConfig",
")",
".",
"setNam... | Submit and run topology in simulator
@param name topology name
@param heronConfig topology config
@param heronTopology topology built from topology builder | [
"Submit",
"and",
"run",
"topology",
"in",
"simulator"
] | train | https://github.com/apache/incubator-heron/blob/776abe2b5a45b93a0eb957fd65cbc149d901a92a/heron/simulator/src/java/org/apache/heron/simulator/Simulator.java#L110-L158 |
lightblue-platform/lightblue-client | http/src/main/java/com/redhat/lightblue/client/http/servlet/AbstractLightblueProxyServlet.java | AbstractLightblueProxyServlet.proxyRequest | private HttpUriRequest proxyRequest(HttpServletRequest request) throws ServletException,
IOException {
String newUri = serviceUriForRequest(request);
BasicHttpEntityEnclosingRequest httpRequest
= new BasicHttpEntityEnclosingRequest(request.getMethod(), newUri);
HttpEntity entity = new InputStreamEntity(request.getInputStream(),
request.getContentLength());
httpRequest.setEntity(entity);
try {
// Sadly have to do this to set the URI; it is not derived from the original httpRequest
HttpRequestWrapper wrappedRequest = HttpRequestWrapper.wrap(httpRequest);
wrappedRequest.setURI(new URI(newUri));
// Somehow, content type header does not come in the original request either
wrappedRequest.setHeader("Content-Type", "application/json");
return wrappedRequest;
} catch (URISyntaxException e) {
LOGGER.error("Syntax exception in service URI, " + newUri, e);
throw new LightblueServletException("Syntax exception in service URI, " + newUri, e);
}
} | java | private HttpUriRequest proxyRequest(HttpServletRequest request) throws ServletException,
IOException {
String newUri = serviceUriForRequest(request);
BasicHttpEntityEnclosingRequest httpRequest
= new BasicHttpEntityEnclosingRequest(request.getMethod(), newUri);
HttpEntity entity = new InputStreamEntity(request.getInputStream(),
request.getContentLength());
httpRequest.setEntity(entity);
try {
// Sadly have to do this to set the URI; it is not derived from the original httpRequest
HttpRequestWrapper wrappedRequest = HttpRequestWrapper.wrap(httpRequest);
wrappedRequest.setURI(new URI(newUri));
// Somehow, content type header does not come in the original request either
wrappedRequest.setHeader("Content-Type", "application/json");
return wrappedRequest;
} catch (URISyntaxException e) {
LOGGER.error("Syntax exception in service URI, " + newUri, e);
throw new LightblueServletException("Syntax exception in service URI, " + newUri, e);
}
} | [
"private",
"HttpUriRequest",
"proxyRequest",
"(",
"HttpServletRequest",
"request",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"String",
"newUri",
"=",
"serviceUriForRequest",
"(",
"request",
")",
";",
"BasicHttpEntityEnclosingRequest",
"httpRequest",
"=",... | For the given servlet request, return a new request object (for use with
Apache HttpClient), that may be executed in place of the original request
to make the real service call.
@throws javax.servlet.ServletException | [
"For",
"the",
"given",
"servlet",
"request",
"return",
"a",
"new",
"request",
"object",
"(",
"for",
"use",
"with",
"Apache",
"HttpClient",
")",
"that",
"may",
"be",
"executed",
"in",
"place",
"of",
"the",
"original",
"request",
"to",
"make",
"the",
"real",... | train | https://github.com/lightblue-platform/lightblue-client/blob/03790aff34e90d3889f60fd6c603c21a21dc1a40/http/src/main/java/com/redhat/lightblue/client/http/servlet/AbstractLightblueProxyServlet.java#L192-L215 |
Jasig/uPortal | uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/StylesheetUserPreferencesServiceImpl.java | StylesheetUserPreferencesServiceImpl.getStyleSheetName | protected String getStyleSheetName(final HttpServletRequest request, PreferencesScope scope) {
final String stylesheetNameFromRequest;
if (scope.equals(PreferencesScope.STRUCTURE)) {
stylesheetNameFromRequest =
(String) request.getAttribute(STYLESHEET_STRUCTURE_OVERRIDE_REQUEST_ATTRIBUTE);
} else {
stylesheetNameFromRequest =
(String) request.getAttribute(STYLESHEET_THEME_OVERRIDE_REQUEST_ATTRIBUTE_NAME);
}
return stylesheetNameFromRequest;
} | java | protected String getStyleSheetName(final HttpServletRequest request, PreferencesScope scope) {
final String stylesheetNameFromRequest;
if (scope.equals(PreferencesScope.STRUCTURE)) {
stylesheetNameFromRequest =
(String) request.getAttribute(STYLESHEET_STRUCTURE_OVERRIDE_REQUEST_ATTRIBUTE);
} else {
stylesheetNameFromRequest =
(String) request.getAttribute(STYLESHEET_THEME_OVERRIDE_REQUEST_ATTRIBUTE_NAME);
}
return stylesheetNameFromRequest;
} | [
"protected",
"String",
"getStyleSheetName",
"(",
"final",
"HttpServletRequest",
"request",
",",
"PreferencesScope",
"scope",
")",
"{",
"final",
"String",
"stylesheetNameFromRequest",
";",
"if",
"(",
"scope",
".",
"equals",
"(",
"PreferencesScope",
".",
"STRUCTURE",
... | Returns the stylesheet name if overridden in the request object.
@param request HttpRequest
@param scope Scope (Structure or Theme)
@return Stylesheet name if set as an override in the request, else null if it was not. | [
"Returns",
"the",
"stylesheet",
"name",
"if",
"overridden",
"in",
"the",
"request",
"object",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/StylesheetUserPreferencesServiceImpl.java#L1254-L1266 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/expressions/Expressions.java | Expressions.isLessThan | public static StringIsLessThan isLessThan(StringExpression left, Object constant) {
if (!(constant instanceof String))
throw new IllegalArgumentException("constant is not a String");
return new StringIsLessThan(left, constant((String)constant));
} | java | public static StringIsLessThan isLessThan(StringExpression left, Object constant) {
if (!(constant instanceof String))
throw new IllegalArgumentException("constant is not a String");
return new StringIsLessThan(left, constant((String)constant));
} | [
"public",
"static",
"StringIsLessThan",
"isLessThan",
"(",
"StringExpression",
"left",
",",
"Object",
"constant",
")",
"{",
"if",
"(",
"!",
"(",
"constant",
"instanceof",
"String",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"constant is not a Strin... | Creates an StringIsLessThan expression from the given expression and constant.
@param left The left expression.
@param constant The constant to compare to (must be a String).
@throws IllegalArgumentException If the constant is not a String
@return A new is less than binary expression. | [
"Creates",
"an",
"StringIsLessThan",
"expression",
"from",
"the",
"given",
"expression",
"and",
"constant",
"."
] | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/expressions/Expressions.java#L389-L395 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/PackagesApi.java | PackagesApi.deletePackage | public void deletePackage(Object projectIdOrPath, Integer packageId) throws GitLabApiException {
if (packageId == null) {
throw new RuntimeException("packageId cannot be null");
}
delete(Response.Status.NO_CONTENT, null,"projects", getProjectIdOrPath(projectIdOrPath), "packages", packageId);
} | java | public void deletePackage(Object projectIdOrPath, Integer packageId) throws GitLabApiException {
if (packageId == null) {
throw new RuntimeException("packageId cannot be null");
}
delete(Response.Status.NO_CONTENT, null,"projects", getProjectIdOrPath(projectIdOrPath), "packages", packageId);
} | [
"public",
"void",
"deletePackage",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"packageId",
")",
"throws",
"GitLabApiException",
"{",
"if",
"(",
"packageId",
"==",
"null",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"packageId cannot be null\"",
")",
... | Deletes a project package.
<pre><code>GitLab Endpoint: DELETE /projects/:id/packages/:package_id</code></pre>
@param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
@param packageId the ID of the package to delete
@throws GitLabApiException if any exception occurs | [
"Deletes",
"a",
"project",
"package",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/PackagesApi.java#L196-L203 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDAvailabilityEstimatePersistenceImpl.java | CPDAvailabilityEstimatePersistenceImpl.findAll | @Override
public List<CPDAvailabilityEstimate> findAll(int start, int end) {
return findAll(start, end, null);
} | java | @Override
public List<CPDAvailabilityEstimate> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CPDAvailabilityEstimate",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the cpd availability estimates.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CPDAvailabilityEstimateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of cpd availability estimates
@param end the upper bound of the range of cpd availability estimates (not inclusive)
@return the range of cpd availability estimates | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"cpd",
"availability",
"estimates",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDAvailabilityEstimatePersistenceImpl.java#L2921-L2924 |
autermann/yaml | src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java | YamlMappingNode.put | public T put(YamlNode key, Byte[] value) {
return put(key, getNodeFactory().binaryNode(value));
} | java | public T put(YamlNode key, Byte[] value) {
return put(key, getNodeFactory().binaryNode(value));
} | [
"public",
"T",
"put",
"(",
"YamlNode",
"key",
",",
"Byte",
"[",
"]",
"value",
")",
"{",
"return",
"put",
"(",
"key",
",",
"getNodeFactory",
"(",
")",
".",
"binaryNode",
"(",
"value",
")",
")",
";",
"}"
] | Adds the specified {@code key}/{@code value} pair to this mapping.
@param key the key
@param value the value
@return {@code this} | [
"Adds",
"the",
"specified",
"{",
"@code",
"key",
"}",
"/",
"{",
"@code",
"value",
"}",
"pair",
"to",
"this",
"mapping",
"."
] | train | https://github.com/autermann/yaml/blob/5f8ab03e4fec3a2abe72c03561cdaa3a3936634d/src/main/java/com/github/autermann/yaml/nodes/YamlMappingNode.java#L348-L350 |
netplex/json-smart-v2 | json-smart/src/main/java/net/minidev/json/parser/JSONParser.java | JSONParser.parse | public <T> T parse(Reader in, Class<T> mapTo) throws ParseException {
return getPStream().parse(in, JSONValue.defaultReader.getMapper(mapTo));
} | java | public <T> T parse(Reader in, Class<T> mapTo) throws ParseException {
return getPStream().parse(in, JSONValue.defaultReader.getMapper(mapTo));
} | [
"public",
"<",
"T",
">",
"T",
"parse",
"(",
"Reader",
"in",
",",
"Class",
"<",
"T",
">",
"mapTo",
")",
"throws",
"ParseException",
"{",
"return",
"getPStream",
"(",
")",
".",
"parse",
"(",
"in",
",",
"JSONValue",
".",
"defaultReader",
".",
"getMapper",... | use to return Primitive Type, or String, Or JsonObject or JsonArray
generated by a ContainerFactory | [
"use",
"to",
"return",
"Primitive",
"Type",
"or",
"String",
"Or",
"JsonObject",
"or",
"JsonArray",
"generated",
"by",
"a",
"ContainerFactory"
] | train | https://github.com/netplex/json-smart-v2/blob/bfb3daef039e22a7bbff5f76bf14ea23330cd70e/json-smart/src/main/java/net/minidev/json/parser/JSONParser.java#L254-L256 |
JodaOrg/joda-time | src/main/java/org/joda/time/convert/StringConverter.java | StringConverter.getInstantMillis | public long getInstantMillis(Object object, Chronology chrono) {
String str = (String) object;
DateTimeFormatter p = ISODateTimeFormat.dateTimeParser();
return p.withChronology(chrono).parseMillis(str);
} | java | public long getInstantMillis(Object object, Chronology chrono) {
String str = (String) object;
DateTimeFormatter p = ISODateTimeFormat.dateTimeParser();
return p.withChronology(chrono).parseMillis(str);
} | [
"public",
"long",
"getInstantMillis",
"(",
"Object",
"object",
",",
"Chronology",
"chrono",
")",
"{",
"String",
"str",
"=",
"(",
"String",
")",
"object",
";",
"DateTimeFormatter",
"p",
"=",
"ISODateTimeFormat",
".",
"dateTimeParser",
"(",
")",
";",
"return",
... | Gets the millis, which is the ISO parsed string value.
@param object the String to convert, must not be null
@param chrono the chronology to use, non-null result of getChronology
@return the millisecond value
@throws IllegalArgumentException if the value if invalid | [
"Gets",
"the",
"millis",
"which",
"is",
"the",
"ISO",
"parsed",
"string",
"value",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/convert/StringConverter.java#L62-L66 |
js-lib-com/dom | src/main/java/js/dom/w3c/DocumentBuilderImpl.java | DocumentBuilderImpl.loadXML | private static Document loadXML(InputSource source, boolean useNamespace) {
try {
org.w3c.dom.Document doc = getDocumentBuilder(null, useNamespace).parse(source);
return new DocumentImpl(doc);
} catch (Exception e) {
throw new DomException(e);
} finally {
close(source);
}
} | java | private static Document loadXML(InputSource source, boolean useNamespace) {
try {
org.w3c.dom.Document doc = getDocumentBuilder(null, useNamespace).parse(source);
return new DocumentImpl(doc);
} catch (Exception e) {
throw new DomException(e);
} finally {
close(source);
}
} | [
"private",
"static",
"Document",
"loadXML",
"(",
"InputSource",
"source",
",",
"boolean",
"useNamespace",
")",
"{",
"try",
"{",
"org",
".",
"w3c",
".",
"dom",
".",
"Document",
"doc",
"=",
"getDocumentBuilder",
"(",
"null",
",",
"useNamespace",
")",
".",
"p... | Helper method to load XML document from input source.
@param source input source,
@param useNamespace flag to control name space awareness.
@return newly created XML document. | [
"Helper",
"method",
"to",
"load",
"XML",
"document",
"from",
"input",
"source",
"."
] | train | https://github.com/js-lib-com/dom/blob/8c7cd7c802977f210674dec7c2a8f61e8de05b63/src/main/java/js/dom/w3c/DocumentBuilderImpl.java#L164-L173 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/JPAScopeInfo.java | JPAScopeInfo.processPersistenceUnit | void processPersistenceUnit(JPAPXml pxml, JPAApplInfo applInfo) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "processPersistenceUnit" + pxml);
synchronized (pxmlsInfo) {
URL pxmlRootURL = pxml.getRootURL();
String pxmlInfoKey = scope == JPAPuScope.EAR_Scope ? pxml.getArchiveName() : pxmlRootURL.toString();
JPAPxmlInfo pxmlInfo = pxmlsInfo.get(pxmlInfoKey);
// if root URL is defined for this persistence.xml, it has been processed before,
// i.e. deployed web module processing will find persistence.xml in the ejb module
// since the ejb module is in the web module classpath.
if (pxmlInfo == null) {
pxmlInfo = new JPAPxmlInfo(this, pxmlRootURL); // F743-23167
pxmlsInfo.put(pxmlInfoKey, pxmlInfo);
JPAIntrospection.beginPXmlInfoVisit(pxmlInfo);
try {
// read in all the persistence unit define in this persistence.xml
pxmlInfo.extractPersistenceUnits(pxml); //PK62950
} finally {
JPAIntrospection.endPXmlInfoVisit();
}
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processPersistenceUnit", getPUList());
} | java | void processPersistenceUnit(JPAPXml pxml, JPAApplInfo applInfo) {
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "processPersistenceUnit" + pxml);
synchronized (pxmlsInfo) {
URL pxmlRootURL = pxml.getRootURL();
String pxmlInfoKey = scope == JPAPuScope.EAR_Scope ? pxml.getArchiveName() : pxmlRootURL.toString();
JPAPxmlInfo pxmlInfo = pxmlsInfo.get(pxmlInfoKey);
// if root URL is defined for this persistence.xml, it has been processed before,
// i.e. deployed web module processing will find persistence.xml in the ejb module
// since the ejb module is in the web module classpath.
if (pxmlInfo == null) {
pxmlInfo = new JPAPxmlInfo(this, pxmlRootURL); // F743-23167
pxmlsInfo.put(pxmlInfoKey, pxmlInfo);
JPAIntrospection.beginPXmlInfoVisit(pxmlInfo);
try {
// read in all the persistence unit define in this persistence.xml
pxmlInfo.extractPersistenceUnits(pxml); //PK62950
} finally {
JPAIntrospection.endPXmlInfoVisit();
}
}
}
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "processPersistenceUnit", getPUList());
} | [
"void",
"processPersistenceUnit",
"(",
"JPAPXml",
"pxml",
",",
"JPAApplInfo",
"applInfo",
")",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
";",
"if",
"(",
"isTraceOn",
"&&",
"tc",
".",
"isEntryEnabled",
"(",... | Process each persistence.xml found in an application. Discover all the persistence unit(s)
defined in the module.
@param pxml
@param looseConfig | [
"Process",
"each",
"persistence",
".",
"xml",
"found",
"in",
"an",
"application",
".",
"Discover",
"all",
"the",
"persistence",
"unit",
"(",
"s",
")",
"defined",
"in",
"the",
"module",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/management/JPAScopeInfo.java#L69-L99 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SecurityPolicyClient.java | SecurityPolicyClient.removeRuleSecurityPolicy | @BetaApi
public final Operation removeRuleSecurityPolicy(Integer priority, String securityPolicy) {
RemoveRuleSecurityPolicyHttpRequest request =
RemoveRuleSecurityPolicyHttpRequest.newBuilder()
.setPriority(priority)
.setSecurityPolicy(securityPolicy)
.build();
return removeRuleSecurityPolicy(request);
} | java | @BetaApi
public final Operation removeRuleSecurityPolicy(Integer priority, String securityPolicy) {
RemoveRuleSecurityPolicyHttpRequest request =
RemoveRuleSecurityPolicyHttpRequest.newBuilder()
.setPriority(priority)
.setSecurityPolicy(securityPolicy)
.build();
return removeRuleSecurityPolicy(request);
} | [
"@",
"BetaApi",
"public",
"final",
"Operation",
"removeRuleSecurityPolicy",
"(",
"Integer",
"priority",
",",
"String",
"securityPolicy",
")",
"{",
"RemoveRuleSecurityPolicyHttpRequest",
"request",
"=",
"RemoveRuleSecurityPolicyHttpRequest",
".",
"newBuilder",
"(",
")",
".... | Deletes a rule at the specified priority.
<p>Sample code:
<pre><code>
try (SecurityPolicyClient securityPolicyClient = SecurityPolicyClient.create()) {
Integer priority = 0;
ProjectGlobalSecurityPolicyName securityPolicy = ProjectGlobalSecurityPolicyName.of("[PROJECT]", "[SECURITY_POLICY]");
Operation response = securityPolicyClient.removeRuleSecurityPolicy(priority, securityPolicy.toString());
}
</code></pre>
@param priority The priority of the rule to remove from the security policy.
@param securityPolicy Name of the security policy to update.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Deletes",
"a",
"rule",
"at",
"the",
"specified",
"priority",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/v1/SecurityPolicyClient.java#L1141-L1150 |
jayantk/jklol | src/com/jayantkrish/jklol/ccg/HeadedSyntacticCategory.java | HeadedSyntacticCategory.parseFrom | public static HeadedSyntacticCategory parseFrom(String typeString) {
// Strip variable numbers and features, without using
// regular expressions for GWT compatibility.
String syntacticString = stripBracketedExpression(typeString, "{", "}");
SyntacticCategory syntax = SyntacticCategory.parseFrom(syntacticString);
int[] semanticVariables = new int[syntax.getNumSubcategories()];
parseSemanticVariables(syntax, typeString, semanticVariables, 0);
int rootIndex = syntax.getNumReturnSubcategories();
return new HeadedSyntacticCategory(syntax, semanticVariables, rootIndex);
} | java | public static HeadedSyntacticCategory parseFrom(String typeString) {
// Strip variable numbers and features, without using
// regular expressions for GWT compatibility.
String syntacticString = stripBracketedExpression(typeString, "{", "}");
SyntacticCategory syntax = SyntacticCategory.parseFrom(syntacticString);
int[] semanticVariables = new int[syntax.getNumSubcategories()];
parseSemanticVariables(syntax, typeString, semanticVariables, 0);
int rootIndex = syntax.getNumReturnSubcategories();
return new HeadedSyntacticCategory(syntax, semanticVariables, rootIndex);
} | [
"public",
"static",
"HeadedSyntacticCategory",
"parseFrom",
"(",
"String",
"typeString",
")",
"{",
"// Strip variable numbers and features, without using ",
"// regular expressions for GWT compatibility.",
"String",
"syntacticString",
"=",
"stripBracketedExpression",
"(",
"typeString... | Parses a syntactic category with augmented semantic variable
information from a category string. The expected format is
identical to that for {@link SyntacticCategory}, except that each
parenthesized or atomic element may be followed by a semantic
variable number in curly braces ({}). All elements with the same
number will be semantically unified during parsing. Unnumbered
elements will be assigned to semantic variable 0, which typically
denotes the head of the syntactic category.
<p>
Furthermore, components of the category string may be annotated
with syntactic subcategorization features in square braces ([]).
These features may be passed to other syntactic variables via
unification during parsing, in the same fashion as semantic
variables. If included, these features must be placed before
the semantic variable number, e.g., N[athlete]{1}.
<p>
Examples:<br>
that := ((N{1}\N{1}){0}/(S\N{1})){0} <br>
very := ((N{1}/N{1}){2}/(N{1}/N{1}){2}){0}
going := ((S[ing]{0}\N{1}){0}/N{2}){0}
@param typeString
@return | [
"Parses",
"a",
"syntactic",
"category",
"with",
"augmented",
"semantic",
"variable",
"information",
"from",
"a",
"category",
"string",
".",
"The",
"expected",
"format",
"is",
"identical",
"to",
"that",
"for",
"{",
"@link",
"SyntacticCategory",
"}",
"except",
"th... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/ccg/HeadedSyntacticCategory.java#L70-L81 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/Unjitable.java | Unjitable.visitCode | @Override
public void visitCode(Code obj) {
Method m = getMethod();
if ((!m.isStatic() || !Values.STATIC_INITIALIZER.equals(m.getName())) && (!m.getName().contains("enum constant"))) { // a findbugs thing!!
byte[] code = obj.getCode();
if (code.length >= UNJITABLE_CODE_LENGTH) {
bugReporter.reportBug(new BugInstance(this, BugType.UJM_UNJITABLE_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addString("Code Bytes: " + code.length));
}
}
} | java | @Override
public void visitCode(Code obj) {
Method m = getMethod();
if ((!m.isStatic() || !Values.STATIC_INITIALIZER.equals(m.getName())) && (!m.getName().contains("enum constant"))) { // a findbugs thing!!
byte[] code = obj.getCode();
if (code.length >= UNJITABLE_CODE_LENGTH) {
bugReporter.reportBug(new BugInstance(this, BugType.UJM_UNJITABLE_METHOD.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addString("Code Bytes: " + code.length));
}
}
} | [
"@",
"Override",
"public",
"void",
"visitCode",
"(",
"Code",
"obj",
")",
"{",
"Method",
"m",
"=",
"getMethod",
"(",
")",
";",
"if",
"(",
"(",
"!",
"m",
".",
"isStatic",
"(",
")",
"||",
"!",
"Values",
".",
"STATIC_INITIALIZER",
".",
"equals",
"(",
"... | implements the visitor to look at the size of the method. static initializer are ignored as these will only be executed once anyway.
@param obj
the context object of the currently parsed method | [
"implements",
"the",
"visitor",
"to",
"look",
"at",
"the",
"size",
"of",
"the",
"method",
".",
"static",
"initializer",
"are",
"ignored",
"as",
"these",
"will",
"only",
"be",
"executed",
"once",
"anyway",
"."
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/Unjitable.java#L65-L76 |
JoeKerouac/utils | src/main/java/com/joe/utils/secure/impl/SignatureUtilImpl.java | SignatureUtilImpl.buildSignatureHolder | private static SignatureHolder buildSignatureHolder(String privateKey, String publicKey,
Algorithms algorithms) {
log.debug("构建SignatureHolder");
try {
log.debug("构建公钥以及验签器");
RSAPublicKey pubKey = (RSAPublicKey) KeyTools.getPublicKeyFromX509("RSA",
new ByteArrayInputStream(publicKey.getBytes()));
Signature verify = Signature.getInstance(algorithms.toString());
verify.initVerify(pubKey);
log.debug("构建私钥以及签名器");
RSAPrivateKey priKey = (RSAPrivateKey) KeyTools.getPrivateKeyFromPKCS8("RSA",
new ByteArrayInputStream(privateKey.getBytes()));
Signature sign = Signature.getInstance(algorithms.toString());
sign.initSign(priKey);
log.debug("SignatureHolder构建成功");
return new SignatureHolder(sign, verify, priKey, pubKey);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new SecureException("创建验签器[" + algorithms + "]失败", e);
}
} | java | private static SignatureHolder buildSignatureHolder(String privateKey, String publicKey,
Algorithms algorithms) {
log.debug("构建SignatureHolder");
try {
log.debug("构建公钥以及验签器");
RSAPublicKey pubKey = (RSAPublicKey) KeyTools.getPublicKeyFromX509("RSA",
new ByteArrayInputStream(publicKey.getBytes()));
Signature verify = Signature.getInstance(algorithms.toString());
verify.initVerify(pubKey);
log.debug("构建私钥以及签名器");
RSAPrivateKey priKey = (RSAPrivateKey) KeyTools.getPrivateKeyFromPKCS8("RSA",
new ByteArrayInputStream(privateKey.getBytes()));
Signature sign = Signature.getInstance(algorithms.toString());
sign.initSign(priKey);
log.debug("SignatureHolder构建成功");
return new SignatureHolder(sign, verify, priKey, pubKey);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
throw new SecureException("创建验签器[" + algorithms + "]失败", e);
}
} | [
"private",
"static",
"SignatureHolder",
"buildSignatureHolder",
"(",
"String",
"privateKey",
",",
"String",
"publicKey",
",",
"Algorithms",
"algorithms",
")",
"{",
"log",
".",
"debug",
"(",
"\"构建SignatureHolder\");",
"",
"",
"try",
"{",
"log",
".",
"debug",
"(",... | 使用指定公钥和RSA加密类型获取RSA验证器
@param privateKey PKCS8文件格式的私钥
@param publicKey X509格式的公钥
@param algorithms RSA加密类型
@return RSA验证器 | [
"使用指定公钥和RSA加密类型获取RSA验证器"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/secure/impl/SignatureUtilImpl.java#L138-L159 |
tvesalainen/util | util/src/main/java/org/vesalainen/lang/Primitives.java | Primitives.parseBoolean | public static final boolean parseBoolean(CharSequence cs, int radix, int beginIndex, int endIndex)
{
if (radix != 2)
{
throw new IllegalArgumentException("radix must be 2");
}
if (Character.codePointCount(cs, beginIndex, endIndex) != 1)
{
throw new IllegalArgumentException("input length must be 1");
}
int digit = Character.digit(Character.codePointAt(cs, beginIndex), 2);
switch (digit)
{
case 1:
return true;
case 0:
return false;
default:
throw new IllegalArgumentException("input must be 0/1");
}
} | java | public static final boolean parseBoolean(CharSequence cs, int radix, int beginIndex, int endIndex)
{
if (radix != 2)
{
throw new IllegalArgumentException("radix must be 2");
}
if (Character.codePointCount(cs, beginIndex, endIndex) != 1)
{
throw new IllegalArgumentException("input length must be 1");
}
int digit = Character.digit(Character.codePointAt(cs, beginIndex), 2);
switch (digit)
{
case 1:
return true;
case 0:
return false;
default:
throw new IllegalArgumentException("input must be 0/1");
}
} | [
"public",
"static",
"final",
"boolean",
"parseBoolean",
"(",
"CharSequence",
"cs",
",",
"int",
"radix",
",",
"int",
"beginIndex",
",",
"int",
"endIndex",
")",
"{",
"if",
"(",
"radix",
"!=",
"2",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\... | Parses the char sequence argument as a boolean. The boolean returned represents
the value true if the char sequence argument is not null and it's digit value
is 1.
@param cs
@param radix Must be 2.
@param beginIndex the index to the first char of the text range.
@param endIndex the index after the last char of the text range.
@return
@throws IllegalArgumentException radix != 2 or if code point count != 1
or if input digit is not 0/1.
@see java.lang.Character#digit(int, int)
@see java.lang.Character#codePointCount(java.lang.CharSequence, int, int) | [
"Parses",
"the",
"char",
"sequence",
"argument",
"as",
"a",
"boolean",
".",
"The",
"boolean",
"returned",
"represents",
"the",
"value",
"true",
"if",
"the",
"char",
"sequence",
"argument",
"is",
"not",
"null",
"and",
"it",
"s",
"digit",
"value",
"is",
"1",... | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/lang/Primitives.java#L543-L563 |
dhanji/sitebricks | stat/src/main/java/com/google/sitebricks/stat/StatCollector.java | StatCollector.apply | @Override public List<MemberAnnotatedWithAtStat> apply(Class<?> clazz) {
List<MemberAnnotatedWithAtStat> annotatedMembers = Lists.newArrayList();
for (Class<?> currentClass = clazz;
currentClass != Object.class;
currentClass = currentClass.getSuperclass()) {
for (Method method : currentClass.getDeclaredMethods()) {
Stat stat = method.getAnnotation(Stat.class);
if (stat != null && staticMemberPolicy.shouldAccept(method)) {
annotatedMembers.add(new MemberAnnotatedWithAtStat(stat, method));
}
}
for (Field field : currentClass.getDeclaredFields()) {
Stat stat = field.getAnnotation(Stat.class);
if (stat != null && staticMemberPolicy.shouldAccept(field)) {
annotatedMembers.add(new MemberAnnotatedWithAtStat(stat, field));
}
}
}
return annotatedMembers;
} | java | @Override public List<MemberAnnotatedWithAtStat> apply(Class<?> clazz) {
List<MemberAnnotatedWithAtStat> annotatedMembers = Lists.newArrayList();
for (Class<?> currentClass = clazz;
currentClass != Object.class;
currentClass = currentClass.getSuperclass()) {
for (Method method : currentClass.getDeclaredMethods()) {
Stat stat = method.getAnnotation(Stat.class);
if (stat != null && staticMemberPolicy.shouldAccept(method)) {
annotatedMembers.add(new MemberAnnotatedWithAtStat(stat, method));
}
}
for (Field field : currentClass.getDeclaredFields()) {
Stat stat = field.getAnnotation(Stat.class);
if (stat != null && staticMemberPolicy.shouldAccept(field)) {
annotatedMembers.add(new MemberAnnotatedWithAtStat(stat, field));
}
}
}
return annotatedMembers;
} | [
"@",
"Override",
"public",
"List",
"<",
"MemberAnnotatedWithAtStat",
">",
"apply",
"(",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"List",
"<",
"MemberAnnotatedWithAtStat",
">",
"annotatedMembers",
"=",
"Lists",
".",
"newArrayList",
"(",
")",
";",
"for",
"("... | {@inheritDoc}
<p>Climbs the class hierarchy finding all annotated members. | [
"{",
"@inheritDoc",
"}"
] | train | https://github.com/dhanji/sitebricks/blob/8682029a78bd48fb8566173d970800499e9e5d97/stat/src/main/java/com/google/sitebricks/stat/StatCollector.java#L68-L89 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/bucket/api/Utils.java | Utils.formatTimeout | static String formatTimeout(final CouchbaseRequest request, final long timeout) {
Map<String, Object> fieldMap = new HashMap<String, Object>();
fieldMap.put("t", timeout);
if (request != null) {
fieldMap.put("s", formatServiceType(request));
putIfNotNull(fieldMap, "i", request.operationId());
putIfNotNull(fieldMap, "b", request.bucket());
putIfNotNull(fieldMap, "c", request.lastLocalId());
putIfNotNull(fieldMap, "l", request.lastLocalSocket());
putIfNotNull(fieldMap, "r", request.lastRemoteSocket());
}
try {
return DefaultObjectMapper.writeValueAsString(fieldMap);
} catch (JsonProcessingException e) {
LOGGER.warn("Could not format timeout information for request " + request, e);
return null;
}
} | java | static String formatTimeout(final CouchbaseRequest request, final long timeout) {
Map<String, Object> fieldMap = new HashMap<String, Object>();
fieldMap.put("t", timeout);
if (request != null) {
fieldMap.put("s", formatServiceType(request));
putIfNotNull(fieldMap, "i", request.operationId());
putIfNotNull(fieldMap, "b", request.bucket());
putIfNotNull(fieldMap, "c", request.lastLocalId());
putIfNotNull(fieldMap, "l", request.lastLocalSocket());
putIfNotNull(fieldMap, "r", request.lastRemoteSocket());
}
try {
return DefaultObjectMapper.writeValueAsString(fieldMap);
} catch (JsonProcessingException e) {
LOGGER.warn("Could not format timeout information for request " + request, e);
return null;
}
} | [
"static",
"String",
"formatTimeout",
"(",
"final",
"CouchbaseRequest",
"request",
",",
"final",
"long",
"timeout",
")",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"fieldMap",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"f... | This method take the given request and produces the correct additional timeout
information according to the RFC. | [
"This",
"method",
"take",
"the",
"given",
"request",
"and",
"produces",
"the",
"correct",
"additional",
"timeout",
"information",
"according",
"to",
"the",
"RFC",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/bucket/api/Utils.java#L70-L89 |
lastaflute/lastaflute | src/main/java/org/lastaflute/core/message/UserMessages.java | UserMessages.hasMessageOf | public boolean hasMessageOf(String property, String messageKey) {
assertArgumentNotNull("property", property);
assertArgumentNotNull("messageKey", messageKey);
final UserMessageItem item = getPropertyItem(property);
return item != null && item.getMessageList().stream().anyMatch(message -> {
final String myKey = resolveMessageKey(messageKey);
if (message.isResource()) {
if (myKey.equals(resolveMessageKey(message.getMessageKey()))) {
return true;
}
} else { // direct message
if (message.getValidatorMessageKey().filter(vlkey -> resolveMessageKey(vlkey).equals(myKey)).isPresent()) {
return true;
}
}
return false;
});
} | java | public boolean hasMessageOf(String property, String messageKey) {
assertArgumentNotNull("property", property);
assertArgumentNotNull("messageKey", messageKey);
final UserMessageItem item = getPropertyItem(property);
return item != null && item.getMessageList().stream().anyMatch(message -> {
final String myKey = resolveMessageKey(messageKey);
if (message.isResource()) {
if (myKey.equals(resolveMessageKey(message.getMessageKey()))) {
return true;
}
} else { // direct message
if (message.getValidatorMessageKey().filter(vlkey -> resolveMessageKey(vlkey).equals(myKey)).isPresent()) {
return true;
}
}
return false;
});
} | [
"public",
"boolean",
"hasMessageOf",
"(",
"String",
"property",
",",
"String",
"messageKey",
")",
"{",
"assertArgumentNotNull",
"(",
"\"property\"",
",",
"property",
")",
";",
"assertArgumentNotNull",
"(",
"\"messageKey\"",
",",
"messageKey",
")",
";",
"final",
"U... | Does the property has user message for the message key?
@param property the name of property, which may have user messages. (NotNull)
@param messageKey The message key to find message. (NotNull)
@return The determination, true or false. | [
"Does",
"the",
"property",
"has",
"user",
"message",
"for",
"the",
"message",
"key?"
] | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/core/message/UserMessages.java#L194-L211 |
facebook/fresco | imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java | PlatformBitmapFactory.createBitmap | public CloseableReference<Bitmap> createBitmap(
DisplayMetrics display,
int width,
int height,
Bitmap.Config config) {
return createBitmap(display, width, height, config, null);
} | java | public CloseableReference<Bitmap> createBitmap(
DisplayMetrics display,
int width,
int height,
Bitmap.Config config) {
return createBitmap(display, width, height, config, null);
} | [
"public",
"CloseableReference",
"<",
"Bitmap",
">",
"createBitmap",
"(",
"DisplayMetrics",
"display",
",",
"int",
"width",
",",
"int",
"height",
",",
"Bitmap",
".",
"Config",
"config",
")",
"{",
"return",
"createBitmap",
"(",
"display",
",",
"width",
",",
"h... | Creates a bitmap with the specified width and height. Its
initial density is determined from the given DisplayMetrics.
@param display Display metrics for the display this bitmap will be
drawn on.
@param width The width of the bitmap
@param height The height of the bitmap
@param config The bitmap config to create.
@return a reference to the bitmap
@throws IllegalArgumentException if the width or height are <= 0
@throws TooManyBitmapsException if the pool is full
@throws java.lang.OutOfMemoryError if the Bitmap cannot be allocated | [
"Creates",
"a",
"bitmap",
"with",
"the",
"specified",
"width",
"and",
"height",
".",
"Its",
"initial",
"density",
"is",
"determined",
"from",
"the",
"given",
"DisplayMetrics",
"."
] | train | https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/imagepipeline/bitmaps/PlatformBitmapFactory.java#L373-L379 |
finmath/finmath-lib | src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java | DiscountCurveInterpolation.createDiscountFactorsFromForwardRates | public static DiscountCurveInterface createDiscountFactorsFromForwardRates(String name, TimeDiscretization tenor, RandomVariable [] forwardRates) {
DiscountCurveInterpolation discountFactors = new DiscountCurveInterpolation(name);
RandomVariable df = forwardRates[0].mult(tenor.getTimeStep(0)).add(1.0).invert();
discountFactors.addDiscountFactor(tenor.getTime(1), df, tenor.getTime(1) > 0);
for(int timeIndex=1; timeIndex<tenor.getNumberOfTimeSteps();timeIndex++) {
df = df.div(forwardRates[timeIndex].mult(tenor.getTimeStep(timeIndex)).add(1.0));
discountFactors.addDiscountFactor(tenor.getTime(timeIndex+1), df, tenor.getTime(timeIndex+1) > 0);
}
return discountFactors;
} | java | public static DiscountCurveInterface createDiscountFactorsFromForwardRates(String name, TimeDiscretization tenor, RandomVariable [] forwardRates) {
DiscountCurveInterpolation discountFactors = new DiscountCurveInterpolation(name);
RandomVariable df = forwardRates[0].mult(tenor.getTimeStep(0)).add(1.0).invert();
discountFactors.addDiscountFactor(tenor.getTime(1), df, tenor.getTime(1) > 0);
for(int timeIndex=1; timeIndex<tenor.getNumberOfTimeSteps();timeIndex++) {
df = df.div(forwardRates[timeIndex].mult(tenor.getTimeStep(timeIndex)).add(1.0));
discountFactors.addDiscountFactor(tenor.getTime(timeIndex+1), df, tenor.getTime(timeIndex+1) > 0);
}
return discountFactors;
} | [
"public",
"static",
"DiscountCurveInterface",
"createDiscountFactorsFromForwardRates",
"(",
"String",
"name",
",",
"TimeDiscretization",
"tenor",
",",
"RandomVariable",
"[",
"]",
"forwardRates",
")",
"{",
"DiscountCurveInterpolation",
"discountFactors",
"=",
"new",
"Discoun... | Create a discount curve from given time discretization and forward rates.
This function is provided for "single interest rate curve" frameworks.
@param name The name of this discount curve.
@param tenor Time discretization for the forward rates
@param forwardRates Array of forward rates.
@return A new discount factor object. | [
"Create",
"a",
"discount",
"curve",
"from",
"given",
"time",
"discretization",
"and",
"forward",
"rates",
".",
"This",
"function",
"is",
"provided",
"for",
"single",
"interest",
"rate",
"curve",
"frameworks",
"."
] | train | https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/marketdata2/model/curves/DiscountCurveInterpolation.java#L380-L390 |
GoogleCloudPlatform/appengine-plugins-core | src/main/java/com/google/cloud/tools/appengine/AppEngineDescriptor.java | AppEngineDescriptor.getServiceId | @Nullable
public String getServiceId() throws AppEngineException {
String serviceId = getText(getNode(document, "appengine-web-app", "service"));
if (serviceId != null) {
return serviceId;
}
return getText(getNode(document, "appengine-web-app", "module"));
} | java | @Nullable
public String getServiceId() throws AppEngineException {
String serviceId = getText(getNode(document, "appengine-web-app", "service"));
if (serviceId != null) {
return serviceId;
}
return getText(getNode(document, "appengine-web-app", "module"));
} | [
"@",
"Nullable",
"public",
"String",
"getServiceId",
"(",
")",
"throws",
"AppEngineException",
"{",
"String",
"serviceId",
"=",
"getText",
"(",
"getNode",
"(",
"document",
",",
"\"appengine-web-app\"",
",",
"\"service\"",
")",
")",
";",
"if",
"(",
"serviceId",
... | Returns service ID from the <service> element of the appengine-web.xml, or null if it is
missing. Will also look at module ID. | [
"Returns",
"service",
"ID",
"from",
"the",
"<",
";",
"service>",
";",
"element",
"of",
"the",
"appengine",
"-",
"web",
".",
"xml",
"or",
"null",
"if",
"it",
"is",
"missing",
".",
"Will",
"also",
"look",
"at",
"module",
"ID",
"."
] | train | https://github.com/GoogleCloudPlatform/appengine-plugins-core/blob/d22e9fa1103522409ab6fdfbf68c4a5a0bc5b97d/src/main/java/com/google/cloud/tools/appengine/AppEngineDescriptor.java#L98-L105 |
SeleniumJT/seleniumjt-core | src/main/java/com/jt/selenium/SeleniumJT.java | SeleniumJT.typeTinyMceEditor | @LogExecTime
public void typeTinyMceEditor(String locator, String value)
{
jtTinyMce.typeTinyMceEditor(locator, value);
} | java | @LogExecTime
public void typeTinyMceEditor(String locator, String value)
{
jtTinyMce.typeTinyMceEditor(locator, value);
} | [
"@",
"LogExecTime",
"public",
"void",
"typeTinyMceEditor",
"(",
"String",
"locator",
",",
"String",
"value",
")",
"{",
"jtTinyMce",
".",
"typeTinyMceEditor",
"(",
"locator",
",",
"value",
")",
";",
"}"
] | Custom method for typing text into a tinyMce which is formed of an embedded iframe html page which we need to target and type into. After we have typed
our value we then need to exit the selected iFrame and return to the main page.
@param locator
@param value | [
"Custom",
"method",
"for",
"typing",
"text",
"into",
"a",
"tinyMce",
"which",
"is",
"formed",
"of",
"an",
"embedded",
"iframe",
"html",
"page",
"which",
"we",
"need",
"to",
"target",
"and",
"type",
"into",
".",
"After",
"we",
"have",
"typed",
"our",
"val... | train | https://github.com/SeleniumJT/seleniumjt-core/blob/8e972f69adc4846a3f1d7b8ca9c3f8d953a2d0f3/src/main/java/com/jt/selenium/SeleniumJT.java#L342-L346 |
RestComm/sip-servlets | sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java | FacebookRestClient.photos_getAlbums | public T photos_getAlbums(Integer userId, Collection<Long> albumIds)
throws FacebookException, IOException {
boolean hasUserId = null != userId && userId != 0;
boolean hasAlbumIds = null != albumIds && !albumIds.isEmpty();
assert (hasUserId || hasAlbumIds); // one of the two must be provided
if (hasUserId)
return (hasAlbumIds) ?
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS, new Pair<String, CharSequence>("uid",
Integer.toString(userId)),
new Pair<String, CharSequence>("aids", delimit(albumIds))) :
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("uid", Integer.toString(userId)));
else
return this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("aids", delimit(albumIds)));
} | java | public T photos_getAlbums(Integer userId, Collection<Long> albumIds)
throws FacebookException, IOException {
boolean hasUserId = null != userId && userId != 0;
boolean hasAlbumIds = null != albumIds && !albumIds.isEmpty();
assert (hasUserId || hasAlbumIds); // one of the two must be provided
if (hasUserId)
return (hasAlbumIds) ?
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS, new Pair<String, CharSequence>("uid",
Integer.toString(userId)),
new Pair<String, CharSequence>("aids", delimit(albumIds))) :
this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("uid", Integer.toString(userId)));
else
return this.callMethod(FacebookMethod.PHOTOS_GET_ALBUMS,
new Pair<String, CharSequence>("aids", delimit(albumIds)));
} | [
"public",
"T",
"photos_getAlbums",
"(",
"Integer",
"userId",
",",
"Collection",
"<",
"Long",
">",
"albumIds",
")",
"throws",
"FacebookException",
",",
"IOException",
"{",
"boolean",
"hasUserId",
"=",
"null",
"!=",
"userId",
"&&",
"userId",
"!=",
"0",
";",
"b... | Retrieves album metadata. Pass a user id and/or a list of album ids to specify the albums
to be retrieved (at least one must be provided)
@param userId (optional) the id of the albums' owner (optional)
@param albumIds (optional) the ids of albums whose metadata is to be retrieved
@return album objects
@see <a href="http://wiki.developers.facebook.com/index.php/Photos.getAlbums">
Developers Wiki: Photos.getAlbums</a> | [
"Retrieves",
"album",
"metadata",
".",
"Pass",
"a",
"user",
"id",
"and",
"/",
"or",
"a",
"list",
"of",
"album",
"ids",
"to",
"specify",
"the",
"albums",
"to",
"be",
"retrieved",
"(",
"at",
"least",
"one",
"must",
"be",
"provided",
")"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-examples/facebook-c2c/src/main/java/com/facebook/api/FacebookRestClient.java#L1801-L1817 |
grails/grails-core | grails-core/src/main/groovy/grails/util/GrailsClassUtils.java | GrailsClassUtils.isVisible | public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
} | java | public static boolean isVisible(Class<?> clazz, ClassLoader classLoader) {
if (classLoader == null) {
return true;
}
try {
Class<?> actualClass = classLoader.loadClass(clazz.getName());
return (clazz == actualClass);
// Else: different interface class found...
}
catch (ClassNotFoundException ex) {
// No interface class found...
return false;
}
} | [
"public",
"static",
"boolean",
"isVisible",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"ClassLoader",
"classLoader",
")",
"{",
"if",
"(",
"classLoader",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"try",
"{",
"Class",
"<",
"?",
">",
"actualClas... | Check whether the given class is visible in the given ClassLoader.
@param clazz the class to check (typically an interface)
@param classLoader the ClassLoader to check against (may be {@code null},
in which case this method will always return {@code true}) | [
"Check",
"whether",
"the",
"given",
"class",
"is",
"visible",
"in",
"the",
"given",
"ClassLoader",
"."
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsClassUtils.java#L177-L190 |
infinispan/infinispan | commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java | UnsignedNumeric.writeUnsignedInt | public static void writeUnsignedInt(ObjectOutput out, int i) throws IOException {
while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.writeByte((byte) i);
} | java | public static void writeUnsignedInt(ObjectOutput out, int i) throws IOException {
while ((i & ~0x7F) != 0) {
out.writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
out.writeByte((byte) i);
} | [
"public",
"static",
"void",
"writeUnsignedInt",
"(",
"ObjectOutput",
"out",
",",
"int",
"i",
")",
"throws",
"IOException",
"{",
"while",
"(",
"(",
"i",
"&",
"~",
"0x7F",
")",
"!=",
"0",
")",
"{",
"out",
".",
"writeByte",
"(",
"(",
"byte",
")",
"(",
... | Writes an int in a variable-length format. Writes between one and five bytes. Smaller values take fewer bytes.
Negative numbers are not supported.
@param i int to write | [
"Writes",
"an",
"int",
"in",
"a",
"variable",
"-",
"length",
"format",
".",
"Writes",
"between",
"one",
"and",
"five",
"bytes",
".",
"Smaller",
"values",
"take",
"fewer",
"bytes",
".",
"Negative",
"numbers",
"are",
"not",
"supported",
"."
] | train | https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/commons/src/main/java/org/infinispan/commons/io/UnsignedNumeric.java#L56-L62 |
UrielCh/ovh-java-sdk | ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java | ApiOvhCloud.project_serviceName_storage_containerId_DELETE | public void project_serviceName_storage_containerId_DELETE(String serviceName, String containerId) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage/{containerId}";
StringBuilder sb = path(qPath, serviceName, containerId);
exec(qPath, "DELETE", sb.toString(), null);
} | java | public void project_serviceName_storage_containerId_DELETE(String serviceName, String containerId) throws IOException {
String qPath = "/cloud/project/{serviceName}/storage/{containerId}";
StringBuilder sb = path(qPath, serviceName, containerId);
exec(qPath, "DELETE", sb.toString(), null);
} | [
"public",
"void",
"project_serviceName_storage_containerId_DELETE",
"(",
"String",
"serviceName",
",",
"String",
"containerId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/cloud/project/{serviceName}/storage/{containerId}\"",
";",
"StringBuilder",
"sb",
"="... | Delete container
REST: DELETE /cloud/project/{serviceName}/storage/{containerId}
@param containerId [required] Container id
@param serviceName [required] Service name | [
"Delete",
"container"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L606-L610 |
googleads/googleads-java-lib | extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ApiServicesRetryStrategy.java | ApiServicesRetryStrategy.updateAccountWaitTime | private void updateAccountWaitTime(long clientCustomerId, long waitForMillis) {
final long minWaitTime = millisFromNow(waitForMillis);
// Here we are assuming that the AtomicLong reference isn't changed once inserted. Therefore,
// the content of this map grows with the number of account rate limits encountered. Future work
// may address the problem of flushing this to reduce overall memory pressure.
//
// Overhead of AtomicLong is ~ size(long) 64 bytes,
// if managing 100k customers this implies a total memory pressure of ~ 100000 * 64 = 6MB.
//
// Overhead of managing the map is 2 * 100k * (size(key) + size(reference)) = 24MB,
// multiplying by factor of 2 to compensate for a map with 50% max load.
//
// An additional 36MB of RAM is a reasonable trade-off to simplify this implementation.
AtomicLong recordedWaitTime =
accountWaitUntil.computeIfAbsent(clientCustomerId, k -> new AtomicLong(minWaitTime));
// This update algorithm will eventually terminate, but possibly not on the first iteration due
// to concurrent updates. A better solution would be to use
// AtomicLongMap.accumulateAndGet(K, long, LongBinaryOperator) from Guava 21.0, however this
// would require bumping the Guava version for all Google Ads Java libraries and their
// dependents.
long snapshotTime = recordedWaitTime.get();
while (snapshotTime < minWaitTime) {
if (recordedWaitTime.compareAndSet(snapshotTime, minWaitTime)) {
break;
} else {
snapshotTime = recordedWaitTime.get();
}
}
} | java | private void updateAccountWaitTime(long clientCustomerId, long waitForMillis) {
final long minWaitTime = millisFromNow(waitForMillis);
// Here we are assuming that the AtomicLong reference isn't changed once inserted. Therefore,
// the content of this map grows with the number of account rate limits encountered. Future work
// may address the problem of flushing this to reduce overall memory pressure.
//
// Overhead of AtomicLong is ~ size(long) 64 bytes,
// if managing 100k customers this implies a total memory pressure of ~ 100000 * 64 = 6MB.
//
// Overhead of managing the map is 2 * 100k * (size(key) + size(reference)) = 24MB,
// multiplying by factor of 2 to compensate for a map with 50% max load.
//
// An additional 36MB of RAM is a reasonable trade-off to simplify this implementation.
AtomicLong recordedWaitTime =
accountWaitUntil.computeIfAbsent(clientCustomerId, k -> new AtomicLong(minWaitTime));
// This update algorithm will eventually terminate, but possibly not on the first iteration due
// to concurrent updates. A better solution would be to use
// AtomicLongMap.accumulateAndGet(K, long, LongBinaryOperator) from Guava 21.0, however this
// would require bumping the Guava version for all Google Ads Java libraries and their
// dependents.
long snapshotTime = recordedWaitTime.get();
while (snapshotTime < minWaitTime) {
if (recordedWaitTime.compareAndSet(snapshotTime, minWaitTime)) {
break;
} else {
snapshotTime = recordedWaitTime.get();
}
}
} | [
"private",
"void",
"updateAccountWaitTime",
"(",
"long",
"clientCustomerId",
",",
"long",
"waitForMillis",
")",
"{",
"final",
"long",
"minWaitTime",
"=",
"millisFromNow",
"(",
"waitForMillis",
")",
";",
"// Here we are assuming that the AtomicLong reference isn't changed once... | Update the wait time for ACCOUNT scope.
@param clientCustomerId the client customer ID
@param waitForMillis the wait time in milliseconds | [
"Update",
"the",
"wait",
"time",
"for",
"ACCOUNT",
"scope",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/extensions/adwords_rate_limiter/src/main/java/com/google/api/ads/adwords/extension/ratelimiter/ApiServicesRetryStrategy.java#L143-L174 |
auth0/Lock.Android | lib/src/main/java/com/auth0/android/lock/WebProvider.java | WebProvider.resume | public boolean resume(int requestCode, int resultCode, Intent intent) {
return WebAuthProvider.resume(requestCode, resultCode, intent);
} | java | public boolean resume(int requestCode, int resultCode, Intent intent) {
return WebAuthProvider.resume(requestCode, resultCode, intent);
} | [
"public",
"boolean",
"resume",
"(",
"int",
"requestCode",
",",
"int",
"resultCode",
",",
"Intent",
"intent",
")",
"{",
"return",
"WebAuthProvider",
".",
"resume",
"(",
"requestCode",
",",
"resultCode",
",",
"intent",
")",
";",
"}"
] | Finishes the authentication flow in the WebAuthProvider
@param requestCode the request code received on the onActivityResult method
@param resultCode the result code received on the onActivityResult method
@param intent the intent received in the onActivityResult method.
@return true if a result was expected and has a valid format, or false if not | [
"Finishes",
"the",
"authentication",
"flow",
"in",
"the",
"WebAuthProvider"
] | train | https://github.com/auth0/Lock.Android/blob/8eb2a979048d2eb6cf0ec631e82e6c3fe6e7d220/lib/src/main/java/com/auth0/android/lock/WebProvider.java#L92-L94 |
apache/flink | flink-filesystems/flink-s3-fs-base/src/main/java/org/apache/flink/fs/s3/common/utils/RefCountedFile.java | RefCountedFile.newFile | public static RefCountedFile newFile(
final File file,
final OutputStream currentOut) throws IOException {
return new RefCountedFile(file, currentOut, 0L);
} | java | public static RefCountedFile newFile(
final File file,
final OutputStream currentOut) throws IOException {
return new RefCountedFile(file, currentOut, 0L);
} | [
"public",
"static",
"RefCountedFile",
"newFile",
"(",
"final",
"File",
"file",
",",
"final",
"OutputStream",
"currentOut",
")",
"throws",
"IOException",
"{",
"return",
"new",
"RefCountedFile",
"(",
"file",
",",
"currentOut",
",",
"0L",
")",
";",
"}"
] | ------------------------------ Factory methods for initializing a temporary file ------------------------------ | [
"------------------------------",
"Factory",
"methods",
"for",
"initializing",
"a",
"temporary",
"file",
"------------------------------"
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-filesystems/flink-s3-fs-base/src/main/java/org/apache/flink/fs/s3/common/utils/RefCountedFile.java#L128-L132 |
QSFT/Doradus | doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java | CQLTransaction.addColumnDelete | private BoundStatement addColumnDelete(String tableName, String key, String colName) {
PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_COLUMN, tableName);
BoundStatement boundState = prepState.bind();
boundState.setString(0, key);
boundState.setString(1, colName);
return boundState;
} | java | private BoundStatement addColumnDelete(String tableName, String key, String colName) {
PreparedStatement prepState = m_dbservice.getPreparedUpdate(Update.DELETE_COLUMN, tableName);
BoundStatement boundState = prepState.bind();
boundState.setString(0, key);
boundState.setString(1, colName);
return boundState;
} | [
"private",
"BoundStatement",
"addColumnDelete",
"(",
"String",
"tableName",
",",
"String",
"key",
",",
"String",
"colName",
")",
"{",
"PreparedStatement",
"prepState",
"=",
"m_dbservice",
".",
"getPreparedUpdate",
"(",
"Update",
".",
"DELETE_COLUMN",
",",
"tableName... | Create and return a BoundStatement that deletes the given column. | [
"Create",
"and",
"return",
"a",
"BoundStatement",
"that",
"deletes",
"the",
"given",
"column",
"."
] | train | https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/db/cql/CQLTransaction.java#L130-L136 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplDouble_CustomFieldSerializer.java | OWLLiteralImplDouble_CustomFieldSerializer.deserializeInstance | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLLiteralImplDouble instance) throws SerializationException {
deserialize(streamReader, instance);
} | java | @Override
public void deserializeInstance(SerializationStreamReader streamReader, OWLLiteralImplDouble instance) throws SerializationException {
deserialize(streamReader, instance);
} | [
"@",
"Override",
"public",
"void",
"deserializeInstance",
"(",
"SerializationStreamReader",
"streamReader",
",",
"OWLLiteralImplDouble",
"instance",
")",
"throws",
"SerializationException",
"{",
"deserialize",
"(",
"streamReader",
",",
"instance",
")",
";",
"}"
] | Deserializes the content of the object from the
{@link com.google.gwt.user.client.rpc.SerializationStreamReader}.
@param streamReader the {@link com.google.gwt.user.client.rpc.SerializationStreamReader} to read the
object's content from
@param instance the object instance to deserialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the deserialization operation is not
successful | [
"Deserializes",
"the",
"content",
"of",
"the",
"object",
"from",
"the",
"{"
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplDouble_CustomFieldSerializer.java#L87-L90 |
MGunlogson/CuckooFilter4J | src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java | FilterTable.swapRandomTagInBucket | long swapRandomTagInBucket(long curIndex, long tag) {
int randomBucketPosition = ThreadLocalRandom.current().nextInt(CuckooFilter.BUCKET_SIZE);
return readTagAndSet(curIndex, randomBucketPosition, tag);
} | java | long swapRandomTagInBucket(long curIndex, long tag) {
int randomBucketPosition = ThreadLocalRandom.current().nextInt(CuckooFilter.BUCKET_SIZE);
return readTagAndSet(curIndex, randomBucketPosition, tag);
} | [
"long",
"swapRandomTagInBucket",
"(",
"long",
"curIndex",
",",
"long",
"tag",
")",
"{",
"int",
"randomBucketPosition",
"=",
"ThreadLocalRandom",
".",
"current",
"(",
")",
".",
"nextInt",
"(",
"CuckooFilter",
".",
"BUCKET_SIZE",
")",
";",
"return",
"readTagAndSet... | Replaces a tag in a random position in the given bucket and returns the
tag that was replaced.
@param curIndex
bucket index
@param tag
tag
@return the replaced tag | [
"Replaces",
"a",
"tag",
"in",
"a",
"random",
"position",
"in",
"the",
"given",
"bucket",
"and",
"returns",
"the",
"tag",
"that",
"was",
"replaced",
"."
] | train | https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L114-L117 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/base64/Base64.java | Base64.encodeFromFile | @Nonnull
public static String encodeFromFile (@Nonnull final String filename) throws IOException
{
// Setup some useful variables
final File file = new File (filename);
// Open a stream
try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), ENCODE))
{
// Need max() for math on small files (v2.2.1);
// Need +1 for a few corner cases (v2.3.5)
final byte [] aBuffer = new byte [Math.max ((int) (file.length () * 1.4 + 1), 40)];
int nLength = 0;
int nBytes;
// Read until done
while ((nBytes = bis.read (aBuffer, nLength, 4096)) >= 0)
{
nLength += nBytes;
}
// Save in a variable to return
return new String (aBuffer, 0, nLength, PREFERRED_ENCODING);
}
} | java | @Nonnull
public static String encodeFromFile (@Nonnull final String filename) throws IOException
{
// Setup some useful variables
final File file = new File (filename);
// Open a stream
try (final Base64InputStream bis = new Base64InputStream (FileHelper.getBufferedInputStream (file), ENCODE))
{
// Need max() for math on small files (v2.2.1);
// Need +1 for a few corner cases (v2.3.5)
final byte [] aBuffer = new byte [Math.max ((int) (file.length () * 1.4 + 1), 40)];
int nLength = 0;
int nBytes;
// Read until done
while ((nBytes = bis.read (aBuffer, nLength, 4096)) >= 0)
{
nLength += nBytes;
}
// Save in a variable to return
return new String (aBuffer, 0, nLength, PREFERRED_ENCODING);
}
} | [
"@",
"Nonnull",
"public",
"static",
"String",
"encodeFromFile",
"(",
"@",
"Nonnull",
"final",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"// Setup some useful variables",
"final",
"File",
"file",
"=",
"new",
"File",
"(",
"filename",
")",
";",
"// O... | Convenience method for reading a binary file and base64-encoding it.
<p>
As of v 2.3, if there is a error, the method will throw an IOException.
<b>This is new to v2.3!</b> In earlier versions, it just returned false,
but in retrospect that's a pretty poor way to handle it.
</p>
@param filename
Filename for reading binary data
@return base64-encoded string
@throws IOException
if there is an error
@since 2.1 | [
"Convenience",
"method",
"for",
"reading",
"a",
"binary",
"file",
"and",
"base64",
"-",
"encoding",
"it",
".",
"<p",
">",
"As",
"of",
"v",
"2",
".",
"3",
"if",
"there",
"is",
"a",
"error",
"the",
"method",
"will",
"throw",
"an",
"IOException",
".",
"... | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/base64/Base64.java#L2460-L2485 |
LMAX-Exchange/disruptor | src/main/java/com/lmax/disruptor/dsl/Disruptor.java | Disruptor.handleEventsWith | @SafeVarargs
public final EventHandlerGroup<T> handleEventsWith(final EventProcessorFactory<T>... eventProcessorFactories)
{
final Sequence[] barrierSequences = new Sequence[0];
return createEventProcessors(barrierSequences, eventProcessorFactories);
} | java | @SafeVarargs
public final EventHandlerGroup<T> handleEventsWith(final EventProcessorFactory<T>... eventProcessorFactories)
{
final Sequence[] barrierSequences = new Sequence[0];
return createEventProcessors(barrierSequences, eventProcessorFactories);
} | [
"@",
"SafeVarargs",
"public",
"final",
"EventHandlerGroup",
"<",
"T",
">",
"handleEventsWith",
"(",
"final",
"EventProcessorFactory",
"<",
"T",
">",
"...",
"eventProcessorFactories",
")",
"{",
"final",
"Sequence",
"[",
"]",
"barrierSequences",
"=",
"new",
"Sequenc... | <p>Set up custom event processors to handle events from the ring buffer. The Disruptor will
automatically start these processors when {@link #start()} is called.</p>
<p>This method can be used as the start of a chain. For example if the handler <code>A</code> must
process events before handler <code>B</code>:</p>
<pre><code>dw.handleEventsWith(A).then(B);</code></pre>
<p>Since this is the start of the chain, the processor factories will always be passed an empty <code>Sequence</code>
array, so the factory isn't necessary in this case. This method is provided for consistency with
{@link EventHandlerGroup#handleEventsWith(EventProcessorFactory...)} and {@link EventHandlerGroup#then(EventProcessorFactory...)}
which do have barrier sequences to provide.</p>
<p>This call is additive, but generally should only be called once when setting up the Disruptor instance</p>
@param eventProcessorFactories the event processor factories to use to create the event processors that will process events.
@return a {@link EventHandlerGroup} that can be used to chain dependencies. | [
"<p",
">",
"Set",
"up",
"custom",
"event",
"processors",
"to",
"handle",
"events",
"from",
"the",
"ring",
"buffer",
".",
"The",
"Disruptor",
"will",
"automatically",
"start",
"these",
"processors",
"when",
"{",
"@link",
"#start",
"()",
"}",
"is",
"called",
... | train | https://github.com/LMAX-Exchange/disruptor/blob/4266d00c5250190313446fdd7c8aa7a4edb5c818/src/main/java/com/lmax/disruptor/dsl/Disruptor.java#L188-L193 |
kuujo/vertigo | util/src/main/java/net/kuujo/vertigo/io/FileSender.java | FileSender.sendFile | public FileSender sendFile(final AsyncFile file, final Handler<AsyncResult<Void>> doneHandler) {
output.group("file", "file", new Handler<OutputGroup>() {
@Override
public void handle(OutputGroup group) {
doSendFile(file, group, doneHandler);
}
});
return this;
} | java | public FileSender sendFile(final AsyncFile file, final Handler<AsyncResult<Void>> doneHandler) {
output.group("file", "file", new Handler<OutputGroup>() {
@Override
public void handle(OutputGroup group) {
doSendFile(file, group, doneHandler);
}
});
return this;
} | [
"public",
"FileSender",
"sendFile",
"(",
"final",
"AsyncFile",
"file",
",",
"final",
"Handler",
"<",
"AsyncResult",
"<",
"Void",
">",
">",
"doneHandler",
")",
"{",
"output",
".",
"group",
"(",
"\"file\"",
",",
"\"file\"",
",",
"new",
"Handler",
"<",
"Outpu... | Sends a file on the output port.
@param file The file to send.
@param doneHandler An asynchronous handler to be called once the file has been sent.
@return The file sender. | [
"Sends",
"a",
"file",
"on",
"the",
"output",
"port",
"."
] | train | https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/util/src/main/java/net/kuujo/vertigo/io/FileSender.java#L65-L73 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.findResult | public static <T, U> T findResult(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
while (self.hasNext()) {
U next = self.next();
T result = condition.call(next);
if (result != null) {
return result;
}
}
return null;
} | java | public static <T, U> T findResult(Iterator<U> self, @ClosureParams(FirstParam.FirstGenericType.class) Closure<T> condition) {
while (self.hasNext()) {
U next = self.next();
T result = condition.call(next);
if (result != null) {
return result;
}
}
return null;
} | [
"public",
"static",
"<",
"T",
",",
"U",
">",
"T",
"findResult",
"(",
"Iterator",
"<",
"U",
">",
"self",
",",
"@",
"ClosureParams",
"(",
"FirstParam",
".",
"FirstGenericType",
".",
"class",
")",
"Closure",
"<",
"T",
">",
"condition",
")",
"{",
"while",
... | Iterates through the Iterator calling the given closure condition for each item but stopping once the first non-null
result is found and returning that result. If all results are null, null is returned.
@param self an Iterator
@param condition a closure that returns a non-null value to indicate that processing should stop and the value should be returned
@return the first non-null result from calling the closure, or null
@since 2.5.0 | [
"Iterates",
"through",
"the",
"Iterator",
"calling",
"the",
"given",
"closure",
"condition",
"for",
"each",
"item",
"but",
"stopping",
"once",
"the",
"first",
"non",
"-",
"null",
"result",
"is",
"found",
"and",
"returning",
"that",
"result",
".",
"If",
"all"... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4504-L4513 |
xfcjscn/sudoor-server-lib | src/main/java/net/gplatform/sudoor/server/security/model/auth/SSAuth.java | SSAuth.authenticateAndSignin | public void authenticateAndSignin(String username, String password) {
logger.debug("authenticateAndSignin:" + username);
Authentication request = new UsernamePasswordAuthenticationToken(username, password);
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
} | java | public void authenticateAndSignin(String username, String password) {
logger.debug("authenticateAndSignin:" + username);
Authentication request = new UsernamePasswordAuthenticationToken(username, password);
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
} | [
"public",
"void",
"authenticateAndSignin",
"(",
"String",
"username",
",",
"String",
"password",
")",
"{",
"logger",
".",
"debug",
"(",
"\"authenticateAndSignin:\"",
"+",
"username",
")",
";",
"Authentication",
"request",
"=",
"new",
"UsernamePasswordAuthenticationTok... | WARNING: Normally this is used by non-web interface. For web interface,
pls use Spring Security config to auto authenticate
@param username
@param password | [
"WARNING",
":",
"Normally",
"this",
"is",
"used",
"by",
"non",
"-",
"web",
"interface",
".",
"For",
"web",
"interface",
"pls",
"use",
"Spring",
"Security",
"config",
"to",
"auto",
"authenticate"
] | train | https://github.com/xfcjscn/sudoor-server-lib/blob/37dc1996eaa9cad25c82abd1de315ba565e32097/src/main/java/net/gplatform/sudoor/server/security/model/auth/SSAuth.java#L141-L147 |
Netflix/zeno | src/main/java/com/netflix/zeno/genericobject/GenericObjectFrameworkSerializer.java | GenericObjectFrameworkSerializer.serializeObject | @Deprecated
@Override
@SuppressWarnings("unchecked")
public void serializeObject(GenericObject rec, String fieldName, String typeName, Object obj) {
if( obj == null ){
rec.add(fieldName, null);
} else if (isPrimitive(obj.getClass())){
serializePrimitive(rec, fieldName, obj);
return;
} else {
GenericObject subObject = new GenericObject(typeName, obj);
getSerializer(typeName).serialize(obj, subObject);
rec.add(fieldName, subObject);
}
} | java | @Deprecated
@Override
@SuppressWarnings("unchecked")
public void serializeObject(GenericObject rec, String fieldName, String typeName, Object obj) {
if( obj == null ){
rec.add(fieldName, null);
} else if (isPrimitive(obj.getClass())){
serializePrimitive(rec, fieldName, obj);
return;
} else {
GenericObject subObject = new GenericObject(typeName, obj);
getSerializer(typeName).serialize(obj, subObject);
rec.add(fieldName, subObject);
}
} | [
"@",
"Deprecated",
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"void",
"serializeObject",
"(",
"GenericObject",
"rec",
",",
"String",
"fieldName",
",",
"String",
"typeName",
",",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
... | /*
@Deprecated instead use serializeObject(GenericObject rec, String fieldName, Object obj) | [
"/",
"*",
"@Deprecated",
"instead",
"use",
"serializeObject",
"(",
"GenericObject",
"rec",
"String",
"fieldName",
"Object",
"obj",
")"
] | train | https://github.com/Netflix/zeno/blob/e571a3f1e304942724d454408fe6417fe18c20fd/src/main/java/com/netflix/zeno/genericobject/GenericObjectFrameworkSerializer.java#L80-L94 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_phonebook_bookKey_PUT | public void billingAccount_phonebook_bookKey_PUT(String billingAccount, String bookKey, OvhPhonebookMaster body) throws IOException {
String qPath = "/telephony/{billingAccount}/phonebook/{bookKey}";
StringBuilder sb = path(qPath, billingAccount, bookKey);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void billingAccount_phonebook_bookKey_PUT(String billingAccount, String bookKey, OvhPhonebookMaster body) throws IOException {
String qPath = "/telephony/{billingAccount}/phonebook/{bookKey}";
StringBuilder sb = path(qPath, billingAccount, bookKey);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"billingAccount_phonebook_bookKey_PUT",
"(",
"String",
"billingAccount",
",",
"String",
"bookKey",
",",
"OvhPhonebookMaster",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/phonebook/{bookKey}\"",
";",
"St... | Alter this object properties
REST: PUT /telephony/{billingAccount}/phonebook/{bookKey}
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param bookKey [required] Identifier of the phonebook | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L5583-L5587 |
Azure/azure-sdk-for-java | redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java | RedisInner.exportDataAsync | public Observable<Void> exportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters) {
return exportDataWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> exportDataAsync(String resourceGroupName, String name, ExportRDBParameters parameters) {
return exportDataWithServiceResponseAsync(resourceGroupName, name, parameters).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"exportDataAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"name",
",",
"ExportRDBParameters",
"parameters",
")",
"{",
"return",
"exportDataWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"name",
",",
"par... | Export data from the redis cache to blobs in a container.
@param resourceGroupName The name of the resource group.
@param name The name of the Redis cache.
@param parameters Parameters for Redis export operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Export",
"data",
"from",
"the",
"redis",
"cache",
"to",
"blobs",
"in",
"a",
"container",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/redis/resource-manager/v2017_10_01/src/main/java/com/microsoft/azure/management/redis/v2017_10_01/implementation/RedisInner.java#L1535-L1542 |
Mozu/mozu-java | mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/couponsets/CouponUrl.java | CouponUrl.deleteCouponUrl | public static MozuUrl deleteCouponUrl(String couponCode, String couponSetCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/couponsets/{couponSetCode}/couponcodes/{couponCode}");
formatter.formatUrl("couponCode", couponCode);
formatter.formatUrl("couponSetCode", couponSetCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | java | public static MozuUrl deleteCouponUrl(String couponCode, String couponSetCode)
{
UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/couponsets/{couponSetCode}/couponcodes/{couponCode}");
formatter.formatUrl("couponCode", couponCode);
formatter.formatUrl("couponSetCode", couponSetCode);
return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ;
} | [
"public",
"static",
"MozuUrl",
"deleteCouponUrl",
"(",
"String",
"couponCode",
",",
"String",
"couponSetCode",
")",
"{",
"UrlFormatter",
"formatter",
"=",
"new",
"UrlFormatter",
"(",
"\"/api/commerce/catalog/admin/couponsets/{couponSetCode}/couponcodes/{couponCode}\"",
")",
"... | Get Resource Url for DeleteCoupon
@param couponCode Code associated with the coupon to remove from the cart.
@param couponSetCode The unique identifier of the coupon set that the coupon belongs to.
@return String Resource Url | [
"Get",
"Resource",
"Url",
"for",
"DeleteCoupon"
] | train | https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/couponsets/CouponUrl.java#L88-L94 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/MariaDbStatement.java | MariaDbStatement.executeUpdate | public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException {
if (executeInternal(sql, fetchSize, autoGeneratedKeys)) {
return 0;
}
return getUpdateCount();
} | java | public int executeUpdate(final String sql, final int autoGeneratedKeys) throws SQLException {
if (executeInternal(sql, fetchSize, autoGeneratedKeys)) {
return 0;
}
return getUpdateCount();
} | [
"public",
"int",
"executeUpdate",
"(",
"final",
"String",
"sql",
",",
"final",
"int",
"autoGeneratedKeys",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"executeInternal",
"(",
"sql",
",",
"fetchSize",
",",
"autoGeneratedKeys",
")",
")",
"{",
"return",
"0",
... | Executes the given SQL statement and signals the driver with the given flag about whether the
auto-generated keys produced by this <code>Statement</code> object should be made available for
retrieval. The driver will ignore the flag if the SQL statement is not an
<code>INSERT</code> statement, or an SQL statement able to return auto-generated keys (the
list of such statements is vendor-specific).
@param sql an SQL Data Manipulation Language (DML) statement, such as
<code>INSERT</code>,
<code>UPDATE</code> or <code>DELETE</code>; or an
SQL statement that returns nothing, such as a DDL statement.
@param autoGeneratedKeys a flag indicating whether auto-generated keys should be made available
for retrieval; one of the following constants:
<code>Statement.RETURN_GENERATED_KEYS</code> <code>Statement.NO_GENERATED_KEYS</code>
@return either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0
for SQL statements that return nothing
@throws SQLException if a database access error occurs, this method is
called on a closed
<code>Statement</code>, the given SQL
statement returns a <code>ResultSet</code> object, or
the given constant is not one of those allowed | [
"Executes",
"the",
"given",
"SQL",
"statement",
"and",
"signals",
"the",
"driver",
"with",
"the",
"given",
"flag",
"about",
"whether",
"the",
"auto",
"-",
"generated",
"keys",
"produced",
"by",
"this",
"<code",
">",
"Statement<",
"/",
"code",
">",
"object",
... | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/MariaDbStatement.java#L545-L550 |
BioPAX/Paxtools | pattern/src/main/java/org/biopax/paxtools/pattern/Searcher.java | Searcher.addControlsRecursive | private static void addControlsRecursive(Interaction inter, Set<Interaction> set)
{
for (Control ctrl : inter.getControlledOf())
{
set.add(ctrl);
addControlsRecursive(ctrl, set);
}
} | java | private static void addControlsRecursive(Interaction inter, Set<Interaction> set)
{
for (Control ctrl : inter.getControlledOf())
{
set.add(ctrl);
addControlsRecursive(ctrl, set);
}
} | [
"private",
"static",
"void",
"addControlsRecursive",
"(",
"Interaction",
"inter",
",",
"Set",
"<",
"Interaction",
">",
"set",
")",
"{",
"for",
"(",
"Control",
"ctrl",
":",
"inter",
".",
"getControlledOf",
"(",
")",
")",
"{",
"set",
".",
"add",
"(",
"ctrl... | Adds controls of the given interactions recursively to the given set.
@param inter interaction to add its controls
@param set set to add to | [
"Adds",
"controls",
"of",
"the",
"given",
"interactions",
"recursively",
"to",
"the",
"given",
"set",
"."
] | train | https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/pattern/src/main/java/org/biopax/paxtools/pattern/Searcher.java#L491-L498 |
foundation-runtime/logging | logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java | LoggingHelper.fatal | public static void fatal(final Logger logger, final String format, final Object... params) {
fatal(logger, format, null, params);
} | java | public static void fatal(final Logger logger, final String format, final Object... params) {
fatal(logger, format, null, params);
} | [
"public",
"static",
"void",
"fatal",
"(",
"final",
"Logger",
"logger",
",",
"final",
"String",
"format",
",",
"final",
"Object",
"...",
"params",
")",
"{",
"fatal",
"(",
"logger",
",",
"format",
",",
"null",
",",
"params",
")",
";",
"}"
] | log message using the String.format API.
@param logger
the logger that will be used to log the message
@param format
the format string (the template string)
@param params
the parameters to be formatted into it the string format | [
"log",
"message",
"using",
"the",
"String",
".",
"format",
"API",
"."
] | train | https://github.com/foundation-runtime/logging/blob/cd0a07b3c5b458ecf90ab92a1e0c72a067f5cbd6/logging-log4j/src/main/java/com/cisco/oss/foundation/logging/LoggingHelper.java#L324-L326 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.dedicatedCloud_serviceName_ip_GET | public ArrayList<String> dedicatedCloud_serviceName_ip_GET(String serviceName, OvhIpCountriesEnum country, String description, Long estimatedClientsNumber, String networkName, OvhOrderableIpBlockRangeEnum size, String usage) throws IOException {
String qPath = "/order/dedicatedCloud/{serviceName}/ip";
StringBuilder sb = path(qPath, serviceName);
query(sb, "country", country);
query(sb, "description", description);
query(sb, "estimatedClientsNumber", estimatedClientsNumber);
query(sb, "networkName", networkName);
query(sb, "size", size);
query(sb, "usage", usage);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> dedicatedCloud_serviceName_ip_GET(String serviceName, OvhIpCountriesEnum country, String description, Long estimatedClientsNumber, String networkName, OvhOrderableIpBlockRangeEnum size, String usage) throws IOException {
String qPath = "/order/dedicatedCloud/{serviceName}/ip";
StringBuilder sb = path(qPath, serviceName);
query(sb, "country", country);
query(sb, "description", description);
query(sb, "estimatedClientsNumber", estimatedClientsNumber);
query(sb, "networkName", networkName);
query(sb, "size", size);
query(sb, "usage", usage);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"dedicatedCloud_serviceName_ip_GET",
"(",
"String",
"serviceName",
",",
"OvhIpCountriesEnum",
"country",
",",
"String",
"description",
",",
"Long",
"estimatedClientsNumber",
",",
"String",
"networkName",
",",
"OvhOrderableIpBlock... | Get allowed durations for 'ip' option
REST: GET /order/dedicatedCloud/{serviceName}/ip
@param size [required] The network ranges orderable
@param usage [required] Basic information of how will this bloc be used (as "web","ssl","cloud" or other things)
@param description [required] Information visible on whois (minimum 3 and maximum 250 alphanumeric characters)
@param country [required] This Ip block country
@param estimatedClientsNumber [required] How much clients would be hosted on those ips ?
@param networkName [required] Information visible on whois (between 2 and maximum 20 alphanumeric characters)
@param serviceName [required] | [
"Get",
"allowed",
"durations",
"for",
"ip",
"option"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5798-L5809 |
ist-dresden/composum | sling/core/commons/src/main/java/com/composum/sling/clientlibs/processor/RendererContext.java | RendererContext.registerClientlibLink | public void registerClientlibLink(ClientlibLink link, ClientlibResourceFolder parent) {
if (renderedClientlibs.contains(link)) {
LOG.error("Bug: duplicate clientlib link {} being included from {} ", link, parent);
} else {
renderedClientlibs.add(link);
LOG.debug("registered {} referenced from {}", link, parent);
}
} | java | public void registerClientlibLink(ClientlibLink link, ClientlibResourceFolder parent) {
if (renderedClientlibs.contains(link)) {
LOG.error("Bug: duplicate clientlib link {} being included from {} ", link, parent);
} else {
renderedClientlibs.add(link);
LOG.debug("registered {} referenced from {}", link, parent);
}
} | [
"public",
"void",
"registerClientlibLink",
"(",
"ClientlibLink",
"link",
",",
"ClientlibResourceFolder",
"parent",
")",
"{",
"if",
"(",
"renderedClientlibs",
".",
"contains",
"(",
"link",
")",
")",
"{",
"LOG",
".",
"error",
"(",
"\"Bug: duplicate clientlib link {} b... | Registers rendered resources / client libraries that have already been rendered for the current request, that is,
over all clientlib tag calls of a request
@param link the element to be registered
@param parent the element referencing it, for logging purposes | [
"Registers",
"rendered",
"resources",
"/",
"client",
"libraries",
"that",
"have",
"already",
"been",
"rendered",
"for",
"the",
"current",
"request",
"that",
"is",
"over",
"all",
"clientlib",
"tag",
"calls",
"of",
"a",
"request"
] | train | https://github.com/ist-dresden/composum/blob/ebc79f559f6022c935240c19102539bdfb1bd1e2/sling/core/commons/src/main/java/com/composum/sling/clientlibs/processor/RendererContext.java#L66-L73 |
fozziethebeat/S-Space | src/main/java/org/tartarus/snowball/SnowballProgram.java | SnowballProgram.replace_s | protected int replace_s(int c_bra, int c_ket, String s)
{
int adjustment = s.length() - (c_ket - c_bra);
current.replace(c_bra, c_ket, s);
limit += adjustment;
if (cursor >= c_ket) cursor += adjustment;
else if (cursor > c_bra) cursor = c_bra;
return adjustment;
} | java | protected int replace_s(int c_bra, int c_ket, String s)
{
int adjustment = s.length() - (c_ket - c_bra);
current.replace(c_bra, c_ket, s);
limit += adjustment;
if (cursor >= c_ket) cursor += adjustment;
else if (cursor > c_bra) cursor = c_bra;
return adjustment;
} | [
"protected",
"int",
"replace_s",
"(",
"int",
"c_bra",
",",
"int",
"c_ket",
",",
"String",
"s",
")",
"{",
"int",
"adjustment",
"=",
"s",
".",
"length",
"(",
")",
"-",
"(",
"c_ket",
"-",
"c_bra",
")",
";",
"current",
".",
"replace",
"(",
"c_bra",
","... | /* to replace chars between c_bra and c_ket in current by the
chars in s. | [
"/",
"*",
"to",
"replace",
"chars",
"between",
"c_bra",
"and",
"c_ket",
"in",
"current",
"by",
"the",
"chars",
"in",
"s",
"."
] | train | https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/org/tartarus/snowball/SnowballProgram.java#L325-L333 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/AttributeCollector.java | AttributeCollector.writeAttribute | public void writeAttribute(int index, XmlWriter xw, XMLValidator validator)
throws IOException, XMLStreamException
{
// Note: here we assume index checks have been done by caller
Attribute attr = mAttributes[index];
String ln = attr.mLocalName;
String prefix = attr.mPrefix;
final String value = getValue(index);
if (prefix == null || prefix.length() == 0) {
xw.writeAttribute(ln, value);
} else {
xw.writeAttribute(prefix, ln, value);
}
if (validator != null) {
validator.validateAttribute(ln, attr.mNamespaceURI, prefix, value);
}
} | java | public void writeAttribute(int index, XmlWriter xw, XMLValidator validator)
throws IOException, XMLStreamException
{
// Note: here we assume index checks have been done by caller
Attribute attr = mAttributes[index];
String ln = attr.mLocalName;
String prefix = attr.mPrefix;
final String value = getValue(index);
if (prefix == null || prefix.length() == 0) {
xw.writeAttribute(ln, value);
} else {
xw.writeAttribute(prefix, ln, value);
}
if (validator != null) {
validator.validateAttribute(ln, attr.mNamespaceURI, prefix, value);
}
} | [
"public",
"void",
"writeAttribute",
"(",
"int",
"index",
",",
"XmlWriter",
"xw",
",",
"XMLValidator",
"validator",
")",
"throws",
"IOException",
",",
"XMLStreamException",
"{",
"// Note: here we assume index checks have been done by caller",
"Attribute",
"attr",
"=",
"mAt... | Method that basically serializes the specified (read-in) attribute
using Writers provided. Serialization is done by
writing out (fully-qualified) name
of the attribute, followed by the equals sign and quoted value. | [
"Method",
"that",
"basically",
"serializes",
"the",
"specified",
"(",
"read",
"-",
"in",
")",
"attribute",
"using",
"Writers",
"provided",
".",
"Serialization",
"is",
"done",
"by",
"writing",
"out",
"(",
"fully",
"-",
"qualified",
")",
"name",
"of",
"the",
... | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/AttributeCollector.java#L1091-L1107 |
alexcojocaru/elasticsearch-maven-plugin | src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/ProcessUtil.java | ProcessUtil.executeScript | public static List<String> executeScript(InstanceConfiguration config,
CommandLine command,
Map<String, String> environment,
ProcessDestroyer processDestroyer)
{
return executeScript(config, command, environment, processDestroyer, false);
} | java | public static List<String> executeScript(InstanceConfiguration config,
CommandLine command,
Map<String, String> environment,
ProcessDestroyer processDestroyer)
{
return executeScript(config, command, environment, processDestroyer, false);
} | [
"public",
"static",
"List",
"<",
"String",
">",
"executeScript",
"(",
"InstanceConfiguration",
"config",
",",
"CommandLine",
"command",
",",
"Map",
"<",
"String",
",",
"String",
">",
"environment",
",",
"ProcessDestroyer",
"processDestroyer",
")",
"{",
"return",
... | Run the given command as a process within the supplied instance config context
and wait until it finalizes. An ElasticsearchSetupException is thrown if the exit code
is not 0.
@param config - the instance config
@param command - the command to execute
@param environment - a map of environment variables; can be null
@param processDestroyer - a destroyer handler for the spawned process; can be null
@return the output (not trimmed of whitespaces) of the given command, as separate lines | [
"Run",
"the",
"given",
"command",
"as",
"a",
"process",
"within",
"the",
"supplied",
"instance",
"config",
"context",
"and",
"wait",
"until",
"it",
"finalizes",
".",
"An",
"ElasticsearchSetupException",
"is",
"thrown",
"if",
"the",
"exit",
"code",
"is",
"not",... | train | https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/util/ProcessUtil.java#L174-L180 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_appcvpx_image.java | xen_appcvpx_image.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_appcvpx_image_responses result = (xen_appcvpx_image_responses) service.get_payload_formatter().string_to_resource(xen_appcvpx_image_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_appcvpx_image_response_array);
}
xen_appcvpx_image[] result_xen_appcvpx_image = new xen_appcvpx_image[result.xen_appcvpx_image_response_array.length];
for(int i = 0; i < result.xen_appcvpx_image_response_array.length; i++)
{
result_xen_appcvpx_image[i] = result.xen_appcvpx_image_response_array[i].xen_appcvpx_image[0];
}
return result_xen_appcvpx_image;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_appcvpx_image_responses result = (xen_appcvpx_image_responses) service.get_payload_formatter().string_to_resource(xen_appcvpx_image_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_appcvpx_image_response_array);
}
xen_appcvpx_image[] result_xen_appcvpx_image = new xen_appcvpx_image[result.xen_appcvpx_image_response_array.length];
for(int i = 0; i < result.xen_appcvpx_image_response_array.length; i++)
{
result_xen_appcvpx_image[i] = result.xen_appcvpx_image_response_array[i].xen_appcvpx_image[0];
}
return result_xen_appcvpx_image;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_appcvpx_image_responses",
"result",
"=",
"(",
"xen_appcvpx_image_responses",
")",
"service",
".",
"get_pa... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_appcvpx_image.java#L264-L281 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java | MetadataFinder.requestMetadataFrom | @SuppressWarnings("WeakerAccess")
public TrackMetadata requestMetadataFrom(final CdjStatus status) {
if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {
return null;
}
final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),
status.getRekordboxId());
return requestMetadataFrom(track, status.getTrackType());
} | java | @SuppressWarnings("WeakerAccess")
public TrackMetadata requestMetadataFrom(final CdjStatus status) {
if (status.getTrackSourceSlot() == CdjStatus.TrackSourceSlot.NO_TRACK || status.getRekordboxId() == 0) {
return null;
}
final DataReference track = new DataReference(status.getTrackSourcePlayer(), status.getTrackSourceSlot(),
status.getRekordboxId());
return requestMetadataFrom(track, status.getTrackType());
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"TrackMetadata",
"requestMetadataFrom",
"(",
"final",
"CdjStatus",
"status",
")",
"{",
"if",
"(",
"status",
".",
"getTrackSourceSlot",
"(",
")",
"==",
"CdjStatus",
".",
"TrackSourceSlot",
".",
"NO_TR... | Given a status update from a CDJ, find the metadata for the track that it has loaded, if any. If there is
an appropriate metadata cache, will use that, otherwise makes a query to the players dbserver.
@param status the CDJ status update that will be used to determine the loaded track and ask the appropriate
player for metadata about it
@return the metadata that was obtained, if any | [
"Given",
"a",
"status",
"update",
"from",
"a",
"CDJ",
"find",
"the",
"metadata",
"for",
"the",
"track",
"that",
"it",
"has",
"loaded",
"if",
"any",
".",
"If",
"there",
"is",
"an",
"appropriate",
"metadata",
"cache",
"will",
"use",
"that",
"otherwise",
"m... | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L52-L60 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsAreaSelectPanel.java | CmsAreaSelectPanel.setSelectPositionX | private void setSelectPositionX(int posX, int width) {
m_markerStyle.setLeft(posX, Unit.PX);
m_markerStyle.setWidth(width, Unit.PX);
m_overlayLeftStyle.setWidth(posX, Unit.PX);
m_overlayTopStyle.setLeft(posX, Unit.PX);
m_overlayTopStyle.setWidth(width, Unit.PX);
m_overlayBottomStyle.setLeft(posX, Unit.PX);
m_overlayBottomStyle.setWidth(width, Unit.PX);
m_overlayRightStyle.setWidth(m_elementWidth - posX - width, Unit.PX);
m_currentSelection.setLeft(posX);
m_currentSelection.setWidth(width);
} | java | private void setSelectPositionX(int posX, int width) {
m_markerStyle.setLeft(posX, Unit.PX);
m_markerStyle.setWidth(width, Unit.PX);
m_overlayLeftStyle.setWidth(posX, Unit.PX);
m_overlayTopStyle.setLeft(posX, Unit.PX);
m_overlayTopStyle.setWidth(width, Unit.PX);
m_overlayBottomStyle.setLeft(posX, Unit.PX);
m_overlayBottomStyle.setWidth(width, Unit.PX);
m_overlayRightStyle.setWidth(m_elementWidth - posX - width, Unit.PX);
m_currentSelection.setLeft(posX);
m_currentSelection.setWidth(width);
} | [
"private",
"void",
"setSelectPositionX",
"(",
"int",
"posX",
",",
"int",
"width",
")",
"{",
"m_markerStyle",
".",
"setLeft",
"(",
"posX",
",",
"Unit",
".",
"PX",
")",
";",
"m_markerStyle",
".",
"setWidth",
"(",
"width",
",",
"Unit",
".",
"PX",
")",
";"... | Sets X position and width of the select area.<p>
@param posX the new X position
@param width the new width | [
"Sets",
"X",
"position",
"and",
"width",
"of",
"the",
"select",
"area",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsAreaSelectPanel.java#L791-L805 |
TimeAndSpaceIO/SmoothieMap | src/main/java/net/openhft/smoothie/SmoothieMap.java | SmoothieMap.replaceAll | @Override
public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
int mc = this.modCount;
Segment<K, V> segment;
for (long segmentIndex = 0; segmentIndex >= 0;
segmentIndex = nextSegmentIndex(segmentIndex, segment)) {
(segment = segment(segmentIndex)).replaceAll(function);
}
if (mc != modCount)
throw new ConcurrentModificationException();
} | java | @Override
public final void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
Objects.requireNonNull(function);
int mc = this.modCount;
Segment<K, V> segment;
for (long segmentIndex = 0; segmentIndex >= 0;
segmentIndex = nextSegmentIndex(segmentIndex, segment)) {
(segment = segment(segmentIndex)).replaceAll(function);
}
if (mc != modCount)
throw new ConcurrentModificationException();
} | [
"@",
"Override",
"public",
"final",
"void",
"replaceAll",
"(",
"BiFunction",
"<",
"?",
"super",
"K",
",",
"?",
"super",
"V",
",",
"?",
"extends",
"V",
">",
"function",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"function",
")",
";",
"int",
"mc",
... | Replaces each entry's value with the result of invoking the given function on that entry
until all entries have been processed or the function throws an exception. Exceptions thrown
by the function are relayed to the caller.
@param function the function to apply to each entry
@throws NullPointerException if the specified function is null
@throws ConcurrentModificationException if any structural modification of the map (new entry
insertion or an entry removal) is detected during iteration | [
"Replaces",
"each",
"entry",
"s",
"value",
"with",
"the",
"result",
"of",
"invoking",
"the",
"given",
"function",
"on",
"that",
"entry",
"until",
"all",
"entries",
"have",
"been",
"processed",
"or",
"the",
"function",
"throws",
"an",
"exception",
".",
"Excep... | train | https://github.com/TimeAndSpaceIO/SmoothieMap/blob/c798f6cae1d377f6913e8821a1fcf5bf45ee0412/src/main/java/net/openhft/smoothie/SmoothieMap.java#L1107-L1118 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java | SDNN.biasAdd | public SDVariable biasAdd(String name, SDVariable input, SDVariable bias) {
validateFloatingPoint("biasAdd", "input", input);
validateFloatingPoint("biasAdd", "bias", bias);
SDVariable ret = f().biasAdd(input, bias);
return updateVariableNameAndReference(ret, name);
} | java | public SDVariable biasAdd(String name, SDVariable input, SDVariable bias) {
validateFloatingPoint("biasAdd", "input", input);
validateFloatingPoint("biasAdd", "bias", bias);
SDVariable ret = f().biasAdd(input, bias);
return updateVariableNameAndReference(ret, name);
} | [
"public",
"SDVariable",
"biasAdd",
"(",
"String",
"name",
",",
"SDVariable",
"input",
",",
"SDVariable",
"bias",
")",
"{",
"validateFloatingPoint",
"(",
"\"biasAdd\"",
",",
"\"input\"",
",",
"input",
")",
";",
"validateFloatingPoint",
"(",
"\"biasAdd\"",
",",
"\... | Bias addition operation: a special case of addition, typically used with CNN 4D activations and a 1D bias vector
@param name Name of the output variable
@param input 4d input variable
@param bias 1d bias
@return Output variable | [
"Bias",
"addition",
"operation",
":",
"a",
"special",
"case",
"of",
"addition",
"typically",
"used",
"with",
"CNN",
"4D",
"activations",
"and",
"a",
"1D",
"bias",
"vector"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDNN.java#L90-L95 |
alipay/sofa-rpc | extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/netty/NettyHelper.java | NettyHelper.getServerBizEventLoopGroup | public static EventLoopGroup getServerBizEventLoopGroup(ServerTransportConfig config, Executor executor) {
int bizThreads = config.getBizMaxThreads();
return config.isUseEpoll() ?
new EpollEventLoopGroup(config.getBizMaxThreads(), executor) :
new NioEventLoopGroup(bizThreads, executor);
} | java | public static EventLoopGroup getServerBizEventLoopGroup(ServerTransportConfig config, Executor executor) {
int bizThreads = config.getBizMaxThreads();
return config.isUseEpoll() ?
new EpollEventLoopGroup(config.getBizMaxThreads(), executor) :
new NioEventLoopGroup(bizThreads, executor);
} | [
"public",
"static",
"EventLoopGroup",
"getServerBizEventLoopGroup",
"(",
"ServerTransportConfig",
"config",
",",
"Executor",
"executor",
")",
"{",
"int",
"bizThreads",
"=",
"config",
".",
"getBizMaxThreads",
"(",
")",
";",
"return",
"config",
".",
"isUseEpoll",
"(",... | 得到服务端业务线程池
@param config 服务端配置
@param executor 业务线程池
@return 服务端业务线程池 | [
"得到服务端业务线程池"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/remoting-http/src/main/java/com/alipay/sofa/rpc/transport/netty/NettyHelper.java#L231-L236 |
calrissian/mango | mango-core/src/main/java/org/calrissian/mango/collect/FluentCloseableIterable.java | FluentCloseableIterable.firstMatch | public final Optional<T> firstMatch(Predicate<? super T> predicate) {
return ofNullable(Iterables.tryFind(this, predicate::test).orNull());
} | java | public final Optional<T> firstMatch(Predicate<? super T> predicate) {
return ofNullable(Iterables.tryFind(this, predicate::test).orNull());
} | [
"public",
"final",
"Optional",
"<",
"T",
">",
"firstMatch",
"(",
"Predicate",
"<",
"?",
"super",
"T",
">",
"predicate",
")",
"{",
"return",
"ofNullable",
"(",
"Iterables",
".",
"tryFind",
"(",
"this",
",",
"predicate",
"::",
"test",
")",
".",
"orNull",
... | Returns an {@link Optional} containing the first element in this fluent iterable that
satisfies the given predicate, if such an element exists.
<p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null}
is matched in this fluent iterable, a {@link NullPointerException} will be thrown. | [
"Returns",
"an",
"{",
"@link",
"Optional",
"}",
"containing",
"the",
"first",
"element",
"in",
"this",
"fluent",
"iterable",
"that",
"satisfies",
"the",
"given",
"predicate",
"if",
"such",
"an",
"element",
"exists",
"."
] | train | https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/collect/FluentCloseableIterable.java#L176-L178 |
grails/grails-core | grails-core/src/main/groovy/grails/util/GrailsClassUtils.java | GrailsClassUtils.registerPrimitiveClassPair | private static final void registerPrimitiveClassPair(Class<?> left, Class<?> right) {
PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put(left, right);
PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put(right, left);
} | java | private static final void registerPrimitiveClassPair(Class<?> left, Class<?> right) {
PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put(left, right);
PRIMITIVE_TYPE_COMPATIBLE_CLASSES.put(right, left);
} | [
"private",
"static",
"final",
"void",
"registerPrimitiveClassPair",
"(",
"Class",
"<",
"?",
">",
"left",
",",
"Class",
"<",
"?",
">",
"right",
")",
"{",
"PRIMITIVE_TYPE_COMPATIBLE_CLASSES",
".",
"put",
"(",
"left",
",",
"right",
")",
";",
"PRIMITIVE_TYPE_COMPA... | Just add two entries to the class compatibility map
@param left
@param right | [
"Just",
"add",
"two",
"entries",
"to",
"the",
"class",
"compatibility",
"map"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/grails/util/GrailsClassUtils.java#L73-L76 |
arquillian/arquillian-cube | kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java | KubernetesAssistant.deployAll | public void deployAll(String applicationName, Path directory) throws IOException {
this.applicationName = applicationName;
if (Files.isDirectory(directory)) {
Files.list(directory)
.filter(ResourceFilter::filterKubernetesResource)
.map(p -> {
try {
return Files.newInputStream(p);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
})
.forEach(is -> {
try {
deploy(is);
is.close();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
});
} else {
throw new IllegalArgumentException(String.format("%s should be a directory", directory));
}
} | java | public void deployAll(String applicationName, Path directory) throws IOException {
this.applicationName = applicationName;
if (Files.isDirectory(directory)) {
Files.list(directory)
.filter(ResourceFilter::filterKubernetesResource)
.map(p -> {
try {
return Files.newInputStream(p);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
})
.forEach(is -> {
try {
deploy(is);
is.close();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
});
} else {
throw new IllegalArgumentException(String.format("%s should be a directory", directory));
}
} | [
"public",
"void",
"deployAll",
"(",
"String",
"applicationName",
",",
"Path",
"directory",
")",
"throws",
"IOException",
"{",
"this",
".",
"applicationName",
"=",
"applicationName",
";",
"if",
"(",
"Files",
".",
"isDirectory",
"(",
"directory",
")",
")",
"{",
... | Deploys all y(a)ml and json files located at given directory.
@param applicationName to configure in cluster
@param directory where resources files are stored
@throws IOException | [
"Deploys",
"all",
"y",
"(",
"a",
")",
"ml",
"and",
"json",
"files",
"located",
"at",
"given",
"directory",
"."
] | train | https://github.com/arquillian/arquillian-cube/blob/ce6b08062cc6ba2a68ecc29606bbae9acda5be13/kubernetes/kubernetes/src/main/java/org/arquillian/cube/kubernetes/impl/KubernetesAssistant.java#L199-L223 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/SnsAPI.java | SnsAPI.oauth2ComponentRefreshToken | public static SnsToken oauth2ComponentRefreshToken(String appid,String refresh_token,String component_appid,String component_access_token){
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/component/refresh_token")
.addParameter("appid", appid)
.addParameter("refresh_token", refresh_token)
.addParameter("grant_type", "refresh_token")
.addParameter("component_appid", component_appid)
.addParameter("component_access_token", component_access_token)
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | java | public static SnsToken oauth2ComponentRefreshToken(String appid,String refresh_token,String component_appid,String component_access_token){
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setUri(BASE_URI + "/sns/oauth2/component/refresh_token")
.addParameter("appid", appid)
.addParameter("refresh_token", refresh_token)
.addParameter("grant_type", "refresh_token")
.addParameter("component_appid", component_appid)
.addParameter("component_access_token", component_access_token)
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest,SnsToken.class);
} | [
"public",
"static",
"SnsToken",
"oauth2ComponentRefreshToken",
"(",
"String",
"appid",
",",
"String",
"refresh_token",
",",
"String",
"component_appid",
",",
"String",
"component_access_token",
")",
"{",
"HttpUriRequest",
"httpUriRequest",
"=",
"RequestBuilder",
".",
"p... | 刷新access_token (第三方平台开发)
@param appid appid
@param refresh_token refresh_token
@param component_appid 服务开发商的appid
@param component_access_token 服务开发方的access_token
@return SnsToken | [
"刷新access_token",
"(",
"第三方平台开发",
")"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/SnsAPI.java#L90-L100 |
Waikato/moa | moa/src/main/java/weka/core/MOAUtils.java | MOAUtils.fromCommandLine | public static MOAObject fromCommandLine(ClassOption option, String commandline) {
return fromCommandLine(option.getRequiredType(), commandline);
} | java | public static MOAObject fromCommandLine(ClassOption option, String commandline) {
return fromCommandLine(option.getRequiredType(), commandline);
} | [
"public",
"static",
"MOAObject",
"fromCommandLine",
"(",
"ClassOption",
"option",
",",
"String",
"commandline",
")",
"{",
"return",
"fromCommandLine",
"(",
"option",
".",
"getRequiredType",
"(",
")",
",",
"commandline",
")",
";",
"}"
] | Turns a commandline into an object (classname + optional options).
@param option the corresponding class option
@param commandline the commandline to turn into an object
@return the generated oblect | [
"Turns",
"a",
"commandline",
"into",
"an",
"object",
"(",
"classname",
"+",
"optional",
"options",
")",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/weka/core/MOAUtils.java#L43-L45 |
alkacon/opencms-core | src/org/opencms/security/CmsOrgUnitManager.java | CmsOrgUnitManager.countUsers | public long countUsers(CmsObject cms, CmsUserSearchParameters params) throws CmsException {
return m_securityManager.countUsers(cms.getRequestContext(), params);
} | java | public long countUsers(CmsObject cms, CmsUserSearchParameters params) throws CmsException {
return m_securityManager.countUsers(cms.getRequestContext(), params);
} | [
"public",
"long",
"countUsers",
"(",
"CmsObject",
"cms",
",",
"CmsUserSearchParameters",
"params",
")",
"throws",
"CmsException",
"{",
"return",
"m_securityManager",
".",
"countUsers",
"(",
"cms",
".",
"getRequestContext",
"(",
")",
",",
"params",
")",
";",
"}"
... | Counts the users which fit the given search criteria.<p>
@param cms the current CMS context
@param params the user search parameters
@return the total number of users which fit the given search parameters
@throws CmsException if something goes wrong | [
"Counts",
"the",
"users",
"which",
"fit",
"the",
"given",
"search",
"criteria",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/security/CmsOrgUnitManager.java#L95-L98 |
Stratio/stratio-cassandra | src/java/com/stratio/cassandra/index/service/RowService.java | RowService.accepted | private boolean accepted(Columns columns, IndexExpression expression) {
ByteBuffer expectedValue = expression.value;
ColumnDefinition def = metadata.getColumnDefinition(expression.column);
String name = def.name.toString();
Column column = columns.getColumn(name);
if (column == null) {
return false;
}
ByteBuffer actualValue = column.getDecomposedValue();
if (actualValue == null) {
return false;
}
AbstractType<?> validator = def.type;
int comparison = validator.compare(actualValue, expectedValue);
switch (expression.operator) {
case EQ:
return comparison == 0;
case GTE:
return comparison >= 0;
case GT:
return comparison > 0;
case LTE:
return comparison <= 0;
case LT:
return comparison < 0;
default:
throw new IllegalStateException();
}
} | java | private boolean accepted(Columns columns, IndexExpression expression) {
ByteBuffer expectedValue = expression.value;
ColumnDefinition def = metadata.getColumnDefinition(expression.column);
String name = def.name.toString();
Column column = columns.getColumn(name);
if (column == null) {
return false;
}
ByteBuffer actualValue = column.getDecomposedValue();
if (actualValue == null) {
return false;
}
AbstractType<?> validator = def.type;
int comparison = validator.compare(actualValue, expectedValue);
switch (expression.operator) {
case EQ:
return comparison == 0;
case GTE:
return comparison >= 0;
case GT:
return comparison > 0;
case LTE:
return comparison <= 0;
case LT:
return comparison < 0;
default:
throw new IllegalStateException();
}
} | [
"private",
"boolean",
"accepted",
"(",
"Columns",
"columns",
",",
"IndexExpression",
"expression",
")",
"{",
"ByteBuffer",
"expectedValue",
"=",
"expression",
".",
"value",
";",
"ColumnDefinition",
"def",
"=",
"metadata",
".",
"getColumnDefinition",
"(",
"expression... | Returns {@code true} if the specified {@link Columns} satisfies the the specified {@link IndexExpression}, {@code
false} otherwise.
@param columns A {@link Columns}
@param expression A {@link IndexExpression}s to be satisfied by {@code columns}.
@return {@code true} if the specified {@link Columns} satisfies the the specified {@link IndexExpression}, {@code
false} otherwise. | [
"Returns",
"{",
"@code",
"true",
"}",
"if",
"the",
"specified",
"{",
"@link",
"Columns",
"}",
"satisfies",
"the",
"the",
"specified",
"{",
"@link",
"IndexExpression",
"}",
"{",
"@code",
"false",
"}",
"otherwise",
"."
] | train | https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/com/stratio/cassandra/index/service/RowService.java#L326-L359 |
allure-framework/allure1 | allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java | AllureResultsUtils.writeAttachmentSafely | public static Attachment writeAttachmentSafely(byte[] attachment, String title, String type) {
try {
return type == null || type.isEmpty()
? writeAttachment(attachment, title)
: writeAttachment(attachment, title, type);
} catch (Exception e) {
LOGGER.trace("Error while saving attachment " + title + ":" + type, e);
return writeAttachmentWithErrorMessage(e, title);
}
} | java | public static Attachment writeAttachmentSafely(byte[] attachment, String title, String type) {
try {
return type == null || type.isEmpty()
? writeAttachment(attachment, title)
: writeAttachment(attachment, title, type);
} catch (Exception e) {
LOGGER.trace("Error while saving attachment " + title + ":" + type, e);
return writeAttachmentWithErrorMessage(e, title);
}
} | [
"public",
"static",
"Attachment",
"writeAttachmentSafely",
"(",
"byte",
"[",
"]",
"attachment",
",",
"String",
"title",
",",
"String",
"type",
")",
"{",
"try",
"{",
"return",
"type",
"==",
"null",
"||",
"type",
".",
"isEmpty",
"(",
")",
"?",
"writeAttachme... | Write attachment uses {@link #writeAttachment(byte[], String, String)} (if
specified attachment type not empty) or {@link #writeAttachment(byte[], String)}
otherwise. If something went wrong uses
{@link #writeAttachmentWithErrorMessage(Throwable, String)}
@param attachment which will write
@param title attachment title
@param type attachment type (should be valid mime-type, empty string or null)
@return Created {@link ru.yandex.qatools.allure.model.Attachment} | [
"Write",
"attachment",
"uses",
"{",
"@link",
"#writeAttachment",
"(",
"byte",
"[]",
"String",
"String",
")",
"}",
"(",
"if",
"specified",
"attachment",
"type",
"not",
"empty",
")",
"or",
"{",
"@link",
"#writeAttachment",
"(",
"byte",
"[]",
"String",
")",
"... | train | https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java#L224-L234 |
FDMediagroep/hamcrest-jsoup | src/main/java/nl/fd/hamcrest/jsoup/ElementWithAttribute.java | ElementWithAttribute.hasHref | @Factory
public static Matcher<Element> hasHref(final String expectedValue) {
return hasAttribute("href", Matchers.is(expectedValue));
} | java | @Factory
public static Matcher<Element> hasHref(final String expectedValue) {
return hasAttribute("href", Matchers.is(expectedValue));
} | [
"@",
"Factory",
"public",
"static",
"Matcher",
"<",
"Element",
">",
"hasHref",
"(",
"final",
"String",
"expectedValue",
")",
"{",
"return",
"hasAttribute",
"(",
"\"href\"",
",",
"Matchers",
".",
"is",
"(",
"expectedValue",
")",
")",
";",
"}"
] | Creates a {@link org.hamcrest.Matcher} for a JSoup {@link org.jsoup.nodes.Element} with the given {@code expectedValue} for the "href"
attribute. See {@link #hasAttribute(String, org.hamcrest.Matcher)} for use with Matchers.
@param expectedValue The attribute value that is expected
@return a {@link org.hamcrest.Matcher} for a JSoup {@link org.jsoup.nodes.Element} with the given {@code expectedValue} for the "href"
@deprecated Use {@link #hasAttribute instead} | [
"Creates",
"a",
"{",
"@link",
"org",
".",
"hamcrest",
".",
"Matcher",
"}",
"for",
"a",
"JSoup",
"{",
"@link",
"org",
".",
"jsoup",
".",
"nodes",
".",
"Element",
"}",
"with",
"the",
"given",
"{",
"@code",
"expectedValue",
"}",
"for",
"the",
"href",
"a... | train | https://github.com/FDMediagroep/hamcrest-jsoup/blob/b7152dac6f834e40117fb7cfdd3149a268d95f7b/src/main/java/nl/fd/hamcrest/jsoup/ElementWithAttribute.java#L83-L86 |
Azure/azure-sdk-for-java | compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java | LogAnalyticsInner.exportRequestRateByInterval | public LogAnalyticsOperationResultInner exportRequestRateByInterval(String location, RequestRateByIntervalInput parameters) {
return exportRequestRateByIntervalWithServiceResponseAsync(location, parameters).toBlocking().last().body();
} | java | public LogAnalyticsOperationResultInner exportRequestRateByInterval(String location, RequestRateByIntervalInput parameters) {
return exportRequestRateByIntervalWithServiceResponseAsync(location, parameters).toBlocking().last().body();
} | [
"public",
"LogAnalyticsOperationResultInner",
"exportRequestRateByInterval",
"(",
"String",
"location",
",",
"RequestRateByIntervalInput",
"parameters",
")",
"{",
"return",
"exportRequestRateByIntervalWithServiceResponseAsync",
"(",
"location",
",",
"parameters",
")",
".",
"toB... | Export logs that show Api requests made by this subscription in the given time window to show throttling activities.
@param location The location upon which virtual-machine-sizes is queried.
@param parameters Parameters supplied to the LogAnalytics getRequestRateByInterval Api.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the LogAnalyticsOperationResultInner object if successful. | [
"Export",
"logs",
"that",
"show",
"Api",
"requests",
"made",
"by",
"this",
"subscription",
"in",
"the",
"given",
"time",
"window",
"to",
"show",
"throttling",
"activities",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/LogAnalyticsInner.java#L86-L88 |
Netflix/conductor | es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearchRestDAOV5.java | ElasticSearchRestDAOV5.indexWithRetry | private void indexWithRetry(final IndexRequest request, final String operationDescription) {
try {
new RetryUtil<IndexResponse>().retryOnException(() -> {
try {
return elasticSearchClient.index(request);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, null, null, RETRY_COUNT, operationDescription, "indexWithRetry");
} catch (Exception e) {
Monitors.error(className, "index");
logger.error("Failed to index {} for request type: {}", request.id(), request.type(), e);
}
} | java | private void indexWithRetry(final IndexRequest request, final String operationDescription) {
try {
new RetryUtil<IndexResponse>().retryOnException(() -> {
try {
return elasticSearchClient.index(request);
} catch (IOException e) {
throw new RuntimeException(e);
}
}, null, null, RETRY_COUNT, operationDescription, "indexWithRetry");
} catch (Exception e) {
Monitors.error(className, "index");
logger.error("Failed to index {} for request type: {}", request.id(), request.type(), e);
}
} | [
"private",
"void",
"indexWithRetry",
"(",
"final",
"IndexRequest",
"request",
",",
"final",
"String",
"operationDescription",
")",
"{",
"try",
"{",
"new",
"RetryUtil",
"<",
"IndexResponse",
">",
"(",
")",
".",
"retryOnException",
"(",
"(",
")",
"->",
"{",
"t... | Performs an index operation with a retry.
@param request The index request that we want to perform.
@param operationDescription The type of operation that we are performing. | [
"Performs",
"an",
"index",
"operation",
"with",
"a",
"retry",
"."
] | train | https://github.com/Netflix/conductor/blob/78fae0ed9ddea22891f9eebb96a2ec0b2783dca0/es5-persistence/src/main/java/com/netflix/conductor/dao/es5/index/ElasticSearchRestDAOV5.java#L661-L675 |
lessthanoptimal/BoofCV | main/boofcv-io/src/main/java/boofcv/io/image/UtilImageIO.java | UtilImageIO.loadPPM | public static BufferedImage loadPPM( String fileName , BufferedImage storage ) throws IOException {
return loadPPM(new FileInputStream(fileName),storage);
} | java | public static BufferedImage loadPPM( String fileName , BufferedImage storage ) throws IOException {
return loadPPM(new FileInputStream(fileName),storage);
} | [
"public",
"static",
"BufferedImage",
"loadPPM",
"(",
"String",
"fileName",
",",
"BufferedImage",
"storage",
")",
"throws",
"IOException",
"{",
"return",
"loadPPM",
"(",
"new",
"FileInputStream",
"(",
"fileName",
")",
",",
"storage",
")",
";",
"}"
] | Loads a PPM image from a file.
@param fileName Location of PPM image
@param storage (Optional) Storage for output image. Must be the width and height of the image being read.
Better performance of type BufferedImage.TYPE_INT_RGB. If null or width/height incorrect a new image
will be declared.
@return The read in image
@throws IOException Thrown if there is a problem reading the image | [
"Loads",
"a",
"PPM",
"image",
"from",
"a",
"file",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/UtilImageIO.java#L203-L205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.