repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 194 | func_name stringlengths 6 111 | whole_func_string stringlengths 80 3.8k | language stringclasses 1
value | func_code_string stringlengths 80 3.8k | func_code_tokens listlengths 20 697 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 434 | split_name stringclasses 1
value | func_code_url stringlengths 111 308 |
|---|---|---|---|---|---|---|---|---|---|---|
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/PropertiesAdapter.java | PropertiesAdapter.getAsType | public <T> T getAsType(String propertyName, Class<T> type) {
return getAsType(propertyName, type, null);
} | java | public <T> T getAsType(String propertyName, Class<T> type) {
return getAsType(propertyName, type, null);
} | [
"public",
"<",
"T",
">",
"T",
"getAsType",
"(",
"String",
"propertyName",
",",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"getAsType",
"(",
"propertyName",
",",
"type",
",",
"null",
")",
";",
"}"
] | Gets the assigned value of the named property as an instance of the specified {@link Class} type.
@param <T> {@link Class} type of the return value.
@param propertyName the name of the property to get.
@param type Class type of the value to return for the specified property.
@return the assigned value of the named property as an instance of the specified {@link Class} type.
@see #getAsType(String, Class, Object) | [
"Gets",
"the",
"assigned",
"value",
"of",
"the",
"named",
"property",
"as",
"an",
"instance",
"of",
"the",
"specified",
"{",
"@link",
"Class",
"}",
"type",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/PropertiesAdapter.java#L243-L245 |
CenturyLinkCloud/mdw | mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java | VariableTranslator.isDocumentReferenceVariable | public static boolean isDocumentReferenceVariable(Package pkg, String type) {
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
return (trans instanceof DocumentReferenceTranslator);
} | java | public static boolean isDocumentReferenceVariable(Package pkg, String type) {
com.centurylink.mdw.variable.VariableTranslator trans = getTranslator(pkg, type);
return (trans instanceof DocumentReferenceTranslator);
} | [
"public",
"static",
"boolean",
"isDocumentReferenceVariable",
"(",
"Package",
"pkg",
",",
"String",
"type",
")",
"{",
"com",
".",
"centurylink",
".",
"mdw",
".",
"variable",
".",
"VariableTranslator",
"trans",
"=",
"getTranslator",
"(",
"pkg",
",",
"type",
")"... | If pkg is null then will use any available bundle to provide the translator. | [
"If",
"pkg",
"is",
"null",
"then",
"will",
"use",
"any",
"available",
"bundle",
"to",
"provide",
"the",
"translator",
"."
] | train | https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/translator/VariableTranslator.java#L170-L173 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstantsSummaryBuilder.java | ConstantsSummaryBuilder.buildPackageHeader | public void buildPackageHeader(XMLNode node, Content summariesTree) {
String parsedPackageName = parsePackageName(currentPackage.name());
if (! printedPackageHeaders.contains(parsedPackageName)) {
writer.addPackageName(currentPackage,
parsePackageName(currentPackage.name()), summariesTree);
printedPackageHeaders.add(parsedPackageName);
}
} | java | public void buildPackageHeader(XMLNode node, Content summariesTree) {
String parsedPackageName = parsePackageName(currentPackage.name());
if (! printedPackageHeaders.contains(parsedPackageName)) {
writer.addPackageName(currentPackage,
parsePackageName(currentPackage.name()), summariesTree);
printedPackageHeaders.add(parsedPackageName);
}
} | [
"public",
"void",
"buildPackageHeader",
"(",
"XMLNode",
"node",
",",
"Content",
"summariesTree",
")",
"{",
"String",
"parsedPackageName",
"=",
"parsePackageName",
"(",
"currentPackage",
".",
"name",
"(",
")",
")",
";",
"if",
"(",
"!",
"printedPackageHeaders",
".... | Build the header for the given package.
@param node the XML element that specifies which components to document
@param summariesTree the tree to which the package header will be added | [
"Build",
"the",
"header",
"for",
"the",
"given",
"package",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ConstantsSummaryBuilder.java#L192-L199 |
TNG/JGiven | jgiven-core/src/main/java/com/tngtech/jgiven/report/config/ConfigOptionParser.java | ConfigOptionParser.printSuggestion | private void printSuggestion( String arg, List<ConfigOption> co ) {
List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );
Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );
System.err.println( "Parse error for argument \"" + arg + "\", did you mean " + sortedList.get( 0 ).getCommandLineOption()
.showFlagInfo() + "? Ignoring for now." );
} | java | private void printSuggestion( String arg, List<ConfigOption> co ) {
List<ConfigOption> sortedList = new ArrayList<ConfigOption>( co );
Collections.sort( sortedList, new ConfigOptionLevenshteinDistance( arg ) );
System.err.println( "Parse error for argument \"" + arg + "\", did you mean " + sortedList.get( 0 ).getCommandLineOption()
.showFlagInfo() + "? Ignoring for now." );
} | [
"private",
"void",
"printSuggestion",
"(",
"String",
"arg",
",",
"List",
"<",
"ConfigOption",
">",
"co",
")",
"{",
"List",
"<",
"ConfigOption",
">",
"sortedList",
"=",
"new",
"ArrayList",
"<",
"ConfigOption",
">",
"(",
"co",
")",
";",
"Collections",
".",
... | Prints a suggestion to stderr for the argument based on the levenshtein distance metric
@param arg the argument which could not be assigned to a flag
@param co the {@link ConfigOption} List where every flag is stored | [
"Prints",
"a",
"suggestion",
"to",
"stderr",
"for",
"the",
"argument",
"based",
"on",
"the",
"levenshtein",
"distance",
"metric"
] | train | https://github.com/TNG/JGiven/blob/1a69248fc6d7eb380cdc4542e3be273842889748/jgiven-core/src/main/java/com/tngtech/jgiven/report/config/ConfigOptionParser.java#L149-L155 |
apiman/apiman | gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultPluginRegistry.java | DefaultPluginRegistry.downloadArtifactTo | protected void downloadArtifactTo(URL artifactUrl, File pluginFile, IAsyncResultHandler<File> handler) {
InputStream istream = null;
OutputStream ostream = null;
try {
URLConnection connection = artifactUrl.openConnection();
connection.connect();
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
if (httpConnection.getResponseCode() != 200) {
handler.handle(AsyncResultImpl.create(null));
return;
}
}
istream = connection.getInputStream();
ostream = new FileOutputStream(pluginFile);
IOUtils.copy(istream, ostream);
ostream.flush();
handler.handle(AsyncResultImpl.create(pluginFile));
} catch (Exception e) {
handler.handle(AsyncResultImpl.<File>create(e));
} finally {
IOUtils.closeQuietly(istream);
IOUtils.closeQuietly(ostream);
}
} | java | protected void downloadArtifactTo(URL artifactUrl, File pluginFile, IAsyncResultHandler<File> handler) {
InputStream istream = null;
OutputStream ostream = null;
try {
URLConnection connection = artifactUrl.openConnection();
connection.connect();
if (connection instanceof HttpURLConnection) {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
if (httpConnection.getResponseCode() != 200) {
handler.handle(AsyncResultImpl.create(null));
return;
}
}
istream = connection.getInputStream();
ostream = new FileOutputStream(pluginFile);
IOUtils.copy(istream, ostream);
ostream.flush();
handler.handle(AsyncResultImpl.create(pluginFile));
} catch (Exception e) {
handler.handle(AsyncResultImpl.<File>create(e));
} finally {
IOUtils.closeQuietly(istream);
IOUtils.closeQuietly(ostream);
}
} | [
"protected",
"void",
"downloadArtifactTo",
"(",
"URL",
"artifactUrl",
",",
"File",
"pluginFile",
",",
"IAsyncResultHandler",
"<",
"File",
">",
"handler",
")",
"{",
"InputStream",
"istream",
"=",
"null",
";",
"OutputStream",
"ostream",
"=",
"null",
";",
"try",
... | Download the artifact at the given URL and store it locally into the given
plugin file path. | [
"Download",
"the",
"artifact",
"at",
"the",
"given",
"URL",
"and",
"store",
"it",
"locally",
"into",
"the",
"given",
"plugin",
"file",
"path",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/gateway/engine/core/src/main/java/io/apiman/gateway/engine/impl/DefaultPluginRegistry.java#L375-L399 |
mapbox/mapbox-navigation-android | libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/route/RouteFetcher.java | RouteFetcher.findRouteFromRouteProgress | public void findRouteFromRouteProgress(Location location, RouteProgress routeProgress) {
this.routeProgress = routeProgress;
NavigationRoute.Builder builder = buildRequestFrom(location, routeProgress);
findRouteWith(builder);
} | java | public void findRouteFromRouteProgress(Location location, RouteProgress routeProgress) {
this.routeProgress = routeProgress;
NavigationRoute.Builder builder = buildRequestFrom(location, routeProgress);
findRouteWith(builder);
} | [
"public",
"void",
"findRouteFromRouteProgress",
"(",
"Location",
"location",
",",
"RouteProgress",
"routeProgress",
")",
"{",
"this",
".",
"routeProgress",
"=",
"routeProgress",
";",
"NavigationRoute",
".",
"Builder",
"builder",
"=",
"buildRequestFrom",
"(",
"location... | Calculates a new {@link com.mapbox.api.directions.v5.models.DirectionsRoute} given
the current {@link Location} and {@link RouteProgress} along the route.
<p>
Uses {@link RouteOptions#coordinates()} and {@link RouteProgress#remainingWaypoints()}
to determine the amount of remaining waypoints there are along the given route.
@param location current location of the device
@param routeProgress for remaining waypoints along the route
@since 0.13.0 | [
"Calculates",
"a",
"new",
"{",
"@link",
"com",
".",
"mapbox",
".",
"api",
".",
"directions",
".",
"v5",
".",
"models",
".",
"DirectionsRoute",
"}",
"given",
"the",
"current",
"{",
"@link",
"Location",
"}",
"and",
"{",
"@link",
"RouteProgress",
"}",
"alon... | train | https://github.com/mapbox/mapbox-navigation-android/blob/375a89c017d360b9defc2c90d0c03468165162ec/libandroid-navigation/src/main/java/com/mapbox/services/android/navigation/v5/route/RouteFetcher.java#L98-L102 |
Waikato/moa | moa/src/main/java/moa/clusterers/dstream/CharacteristicVector.java | CharacteristicVector.densityWithNew | public void densityWithNew(int currTime, double decayFactor)
{
// Update the density grid's density
double densityOfG = this.getGridDensity();
//System.out.print("["+decayFactor+"^("+currTime+" - "+this.getDensityTimeStamp()+") * "+densityOfG+"] + 1.0 = ");
densityOfG = (Math.pow(decayFactor, (currTime-this.getUpdateTime())) * densityOfG)+1.0;
//System.out.println(densityOfG);
this.setGridDensity(densityOfG, currTime);
} | java | public void densityWithNew(int currTime, double decayFactor)
{
// Update the density grid's density
double densityOfG = this.getGridDensity();
//System.out.print("["+decayFactor+"^("+currTime+" - "+this.getDensityTimeStamp()+") * "+densityOfG+"] + 1.0 = ");
densityOfG = (Math.pow(decayFactor, (currTime-this.getUpdateTime())) * densityOfG)+1.0;
//System.out.println(densityOfG);
this.setGridDensity(densityOfG, currTime);
} | [
"public",
"void",
"densityWithNew",
"(",
"int",
"currTime",
",",
"double",
"decayFactor",
")",
"{",
"// Update the density grid's density",
"double",
"densityOfG",
"=",
"this",
".",
"getGridDensity",
"(",
")",
";",
"//System.out.print(\"[\"+decayFactor+\"^(\"+currTime+\" - ... | Implements the density update function given in
eq 5 (Proposition 3.1) of Chen and Tu 2007.
@param currTime the data stream's current internal time
@param decayFactor the value of lambda | [
"Implements",
"the",
"density",
"update",
"function",
"given",
"in",
"eq",
"5",
"(",
"Proposition",
"3",
".",
"1",
")",
"of",
"Chen",
"and",
"Tu",
"2007",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/dstream/CharacteristicVector.java#L213-L223 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/constraints/ModelConstraints.java | ModelConstraints.usedByReference | private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)
{
String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();
ClassDescriptorDef classDef;
ReferenceDescriptorDef refDef;
String targetClassName;
// only relevant for primarykey fields
if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))
{
for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)
{
classDef = (ClassDescriptorDef)classIt.next();
for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)
{
refDef = (ReferenceDescriptorDef)refIt.next();
targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');
if (ownerClassName.equals(targetClassName))
{
// the field is a primary key of the class referenced by this reference descriptor
return refDef;
}
}
}
}
return null;
} | java | private ReferenceDescriptorDef usedByReference(ModelDef modelDef, FieldDescriptorDef fieldDef)
{
String ownerClassName = ((ClassDescriptorDef)fieldDef.getOwner()).getQualifiedName();
ClassDescriptorDef classDef;
ReferenceDescriptorDef refDef;
String targetClassName;
// only relevant for primarykey fields
if (PropertyHelper.toBoolean(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY), false))
{
for (Iterator classIt = modelDef.getClasses(); classIt.hasNext();)
{
classDef = (ClassDescriptorDef)classIt.next();
for (Iterator refIt = classDef.getReferences(); refIt.hasNext();)
{
refDef = (ReferenceDescriptorDef)refIt.next();
targetClassName = refDef.getProperty(PropertyHelper.OJB_PROPERTY_CLASS_REF).replace('$', '.');
if (ownerClassName.equals(targetClassName))
{
// the field is a primary key of the class referenced by this reference descriptor
return refDef;
}
}
}
}
return null;
} | [
"private",
"ReferenceDescriptorDef",
"usedByReference",
"(",
"ModelDef",
"modelDef",
",",
"FieldDescriptorDef",
"fieldDef",
")",
"{",
"String",
"ownerClassName",
"=",
"(",
"(",
"ClassDescriptorDef",
")",
"fieldDef",
".",
"getOwner",
"(",
")",
")",
".",
"getQualified... | Checks whether the given field definition is used as the primary key of a class referenced by
a reference.
@param modelDef The model
@param fieldDef The current field descriptor def
@return The reference that uses the field or <code>null</code> if the field is not used in this way | [
"Checks",
"whether",
"the",
"given",
"field",
"definition",
"is",
"used",
"as",
"the",
"primary",
"key",
"of",
"a",
"class",
"referenced",
"by",
"a",
"reference",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/constraints/ModelConstraints.java#L877-L903 |
grycap/coreutils | coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/net/UrlBuilder.java | UrlBuilder.buildRelativeUrl | public String buildRelativeUrl(final @Nullable String fragment, final @Nullable Map<String, String> params) {
String url = null;
final Optional<String> fragment2 = ofNullable(trimToNull(fragment));
try {
final Optional<URL> fragmentUrl = ofNullable(fragment2.isPresent() ? new URL("http://example.com/" + fragment2.get()) : null);
final URIBuilder uriBuilder = new URIBuilder();
// add path
uriBuilder.setPath(new StringBuilder(ofNullable(trimToNull(baseUrl.getPath())).orElse("/"))
.append(fragmentUrl.isPresent() ? "/" + stripEnd(fragmentUrl.get().getPath(), "/") : "")
.toString().replaceAll("[/]{2,}", "/"));
// add query parameters
if (isNotBlank(baseUrl.getQuery())) {
uriBuilder.setParameters(URLEncodedUtils.parse(baseUrl.getQuery(), defaultCharset()));
}
if (fragmentUrl.isPresent() && isNotBlank(fragmentUrl.get().getQuery())) {
URLEncodedUtils.parse(fragmentUrl.get().getQuery(), defaultCharset()).stream().forEach(p -> {
uriBuilder.addParameter(p.getName(), p.getValue());
});
}
ofNullable(params).orElse(emptyMap()).entrySet().stream().forEach(p -> {
uriBuilder.addParameter(p.getKey(), p.getValue());
});
// add internal reference
uriBuilder.setFragment(baseUrl.getRef());
// build relative URL
url = uriBuilder.build().normalize().toString();
} catch (MalformedURLException | URISyntaxException e) {
throw new IllegalStateException(new StringBuilder("Failed to create relative URL from provided parameters: fragment=")
.append(fragment2.orElse("null")).append(", params=").append(params != null ? params.toString() : "null").toString(), e);
}
return url;
} | java | public String buildRelativeUrl(final @Nullable String fragment, final @Nullable Map<String, String> params) {
String url = null;
final Optional<String> fragment2 = ofNullable(trimToNull(fragment));
try {
final Optional<URL> fragmentUrl = ofNullable(fragment2.isPresent() ? new URL("http://example.com/" + fragment2.get()) : null);
final URIBuilder uriBuilder = new URIBuilder();
// add path
uriBuilder.setPath(new StringBuilder(ofNullable(trimToNull(baseUrl.getPath())).orElse("/"))
.append(fragmentUrl.isPresent() ? "/" + stripEnd(fragmentUrl.get().getPath(), "/") : "")
.toString().replaceAll("[/]{2,}", "/"));
// add query parameters
if (isNotBlank(baseUrl.getQuery())) {
uriBuilder.setParameters(URLEncodedUtils.parse(baseUrl.getQuery(), defaultCharset()));
}
if (fragmentUrl.isPresent() && isNotBlank(fragmentUrl.get().getQuery())) {
URLEncodedUtils.parse(fragmentUrl.get().getQuery(), defaultCharset()).stream().forEach(p -> {
uriBuilder.addParameter(p.getName(), p.getValue());
});
}
ofNullable(params).orElse(emptyMap()).entrySet().stream().forEach(p -> {
uriBuilder.addParameter(p.getKey(), p.getValue());
});
// add internal reference
uriBuilder.setFragment(baseUrl.getRef());
// build relative URL
url = uriBuilder.build().normalize().toString();
} catch (MalformedURLException | URISyntaxException e) {
throw new IllegalStateException(new StringBuilder("Failed to create relative URL from provided parameters: fragment=")
.append(fragment2.orElse("null")).append(", params=").append(params != null ? params.toString() : "null").toString(), e);
}
return url;
} | [
"public",
"String",
"buildRelativeUrl",
"(",
"final",
"@",
"Nullable",
"String",
"fragment",
",",
"final",
"@",
"Nullable",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"{",
"String",
"url",
"=",
"null",
";",
"final",
"Optional",
"<",
"String",... | Creates a new URL relative to the base URL provided in the constructor of this class. The new relative URL
includes the path, query parameters and the internal reference of the {@link UrlBuilder#baseUrl base URL}
provided with this class. An additional fragment, as well as additional query parameters can be optionally
added to the new URL. In addition to the parameters passed to the method as an argument, the supplied
fragment can also include parameters that will be added to the created URL. The created URL is normalized
and unencoded before returning it to the caller. The current implementation has the following limitations:
<ul>
<li>Arrays are not supported: <tt>q=foo&q=bar</tt> will produce an error.</li>
<li>Internal references are only supported in the base URL. Any additional reference provided with the
fragment will be silently ignored: the fragment <tt>/rd#ref</tt> will be appended to the base URL as
<tt>/rd</tt>, ignoring the internal reference.</li>
</ul>
@param fragment - optional URL fragment (may include parameters, but not references) that will be added
to the base URL
@param params - optional query parameters that will be added to the base URL
@return A relative URL created from the base URL provided in the constructor of this class and adding the
fragment and parameters passed as arguments to this method. | [
"Creates",
"a",
"new",
"URL",
"relative",
"to",
"the",
"base",
"URL",
"provided",
"in",
"the",
"constructor",
"of",
"this",
"class",
".",
"The",
"new",
"relative",
"URL",
"includes",
"the",
"path",
"query",
"parameters",
"and",
"the",
"internal",
"reference"... | train | https://github.com/grycap/coreutils/blob/e6db61dc50b49ea7276c0c29c7401204681a10c2/coreutils-fiber/src/main/java/es/upv/grycap/coreutils/fiber/net/UrlBuilder.java#L99-L130 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java | UserSearch.sendSimpleSearchForm | public ReportedData sendSimpleSearchForm(XMPPConnection con, Form searchForm, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
SimpleUserSearch search = new SimpleUserSearch();
search.setForm(searchForm);
search.setType(IQ.Type.set);
search.setTo(searchService);
SimpleUserSearch response = con.createStanzaCollectorAndSend(search).nextResultOrThrow();
return response.getReportedData();
} | java | public ReportedData sendSimpleSearchForm(XMPPConnection con, Form searchForm, DomainBareJid searchService) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
SimpleUserSearch search = new SimpleUserSearch();
search.setForm(searchForm);
search.setType(IQ.Type.set);
search.setTo(searchService);
SimpleUserSearch response = con.createStanzaCollectorAndSend(search).nextResultOrThrow();
return response.getReportedData();
} | [
"public",
"ReportedData",
"sendSimpleSearchForm",
"(",
"XMPPConnection",
"con",
",",
"Form",
"searchForm",
",",
"DomainBareJid",
"searchService",
")",
"throws",
"NoResponseException",
",",
"XMPPErrorException",
",",
"NotConnectedException",
",",
"InterruptedException",
"{",... | Sends the filled out answer form to be sent and queried by the search service.
@param con the current XMPPConnection.
@param searchForm the <code>Form</code> to send for querying.
@param searchService the search service to use. (ex. search.jivesoftware.com)
@return ReportedData the data found from the query.
@throws XMPPErrorException
@throws NoResponseException
@throws NotConnectedException
@throws InterruptedException | [
"Sends",
"the",
"filled",
"out",
"answer",
"form",
"to",
"be",
"sent",
"and",
"queried",
"by",
"the",
"search",
"service",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/search/UserSearch.java#L116-L124 |
Azure/azure-sdk-for-java | privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java | PrivateZonesInner.getByResourceGroupAsync | public Observable<PrivateZoneInner> getByResourceGroupAsync(String resourceGroupName, String privateZoneName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, privateZoneName).map(new Func1<ServiceResponse<PrivateZoneInner>, PrivateZoneInner>() {
@Override
public PrivateZoneInner call(ServiceResponse<PrivateZoneInner> response) {
return response.body();
}
});
} | java | public Observable<PrivateZoneInner> getByResourceGroupAsync(String resourceGroupName, String privateZoneName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, privateZoneName).map(new Func1<ServiceResponse<PrivateZoneInner>, PrivateZoneInner>() {
@Override
public PrivateZoneInner call(ServiceResponse<PrivateZoneInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"PrivateZoneInner",
">",
"getByResourceGroupAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"privateZoneName",
")",
"{",
"return",
"getByResourceGroupWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"privateZoneName",
")",
".... | Gets a Private DNS zone. Retrieves the zone properties, but not the virtual networks links or the record sets within the zone.
@param resourceGroupName The name of the resource group.
@param privateZoneName The name of the Private DNS zone (without a terminating dot).
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PrivateZoneInner object | [
"Gets",
"a",
"Private",
"DNS",
"zone",
".",
"Retrieves",
"the",
"zone",
"properties",
"but",
"not",
"the",
"virtual",
"networks",
"links",
"or",
"the",
"record",
"sets",
"within",
"the",
"zone",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/privatedns/resource-manager/v2018_09_01/src/main/java/com/microsoft/azure/management/privatedns/v2018_09_01/implementation/PrivateZonesInner.java#L1160-L1167 |
OpenLiberty/open-liberty | dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java | HttpChannelConfig.parseMaxPersist | private void parseMaxPersist(Map<Object, Object> props) {
// -1 means unlimited
// 0..1 means 1
// X means X
Object value = props.get(HttpConfigConstants.PROPNAME_MAX_PERSIST);
if (null != value) {
try {
this.maxPersistRequest = minLimit(convertInteger(value), HttpConfigConstants.MIN_PERSIST_REQ);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Max persistent requests is " + getMaximumPersistentRequests());
}
} catch (NumberFormatException nfe) {
FFDCFilter.processException(nfe, getClass().getName() + ".parseMaxPersist", "1");
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Invalid max persistent requests; " + value);
}
}
}
} | java | private void parseMaxPersist(Map<Object, Object> props) {
// -1 means unlimited
// 0..1 means 1
// X means X
Object value = props.get(HttpConfigConstants.PROPNAME_MAX_PERSIST);
if (null != value) {
try {
this.maxPersistRequest = minLimit(convertInteger(value), HttpConfigConstants.MIN_PERSIST_REQ);
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Max persistent requests is " + getMaximumPersistentRequests());
}
} catch (NumberFormatException nfe) {
FFDCFilter.processException(nfe, getClass().getName() + ".parseMaxPersist", "1");
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Config: Invalid max persistent requests; " + value);
}
}
}
} | [
"private",
"void",
"parseMaxPersist",
"(",
"Map",
"<",
"Object",
",",
"Object",
">",
"props",
")",
"{",
"// -1 means unlimited",
"// 0..1 means 1",
"// X means X",
"Object",
"value",
"=",
"props",
".",
"get",
"(",
"HttpConfigConstants",
".",
"PROPNAME_MAX_PERSIST",
... | Check the input configuration for the maximum allowed requests per socket
setting.
@param props | [
"Check",
"the",
"input",
"configuration",
"for",
"the",
"maximum",
"allowed",
"requests",
"per",
"socket",
"setting",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transport.http/src/com/ibm/ws/http/channel/internal/HttpChannelConfig.java#L508-L526 |
redbox-mint/redbox | plugins/transaction/curation/src/main/java/com/googlecode/fascinator/redbox/plugins/curation/redbox/FormDataParser.java | FormDataParser.getArray | private static JSONArray getArray(JsonObject object, String key)
throws IOException {
// Get the existing one
if (object.containsKey(key)) {
Object existing = object.get(key);
if (!(existing instanceof JSONArray)) {
throw new IOException("Invalid field structure, '" + key +
"' expected to be an array, but incompatible "
+ "data type already present.");
}
return (JSONArray) existing;
// Or add a new one
} else {
JSONArray newObject = new JSONArray();
object.put(key, newObject);
return newObject;
}
} | java | private static JSONArray getArray(JsonObject object, String key)
throws IOException {
// Get the existing one
if (object.containsKey(key)) {
Object existing = object.get(key);
if (!(existing instanceof JSONArray)) {
throw new IOException("Invalid field structure, '" + key +
"' expected to be an array, but incompatible "
+ "data type already present.");
}
return (JSONArray) existing;
// Or add a new one
} else {
JSONArray newObject = new JSONArray();
object.put(key, newObject);
return newObject;
}
} | [
"private",
"static",
"JSONArray",
"getArray",
"(",
"JsonObject",
"object",
",",
"String",
"key",
")",
"throws",
"IOException",
"{",
"// Get the existing one",
"if",
"(",
"object",
".",
"containsKey",
"(",
"key",
")",
")",
"{",
"Object",
"existing",
"=",
"objec... | Get a child JSON Array from an incoming JSON object. If the child does
not exist it will be created.
@param object The incoming object we are to look inside
@param key The child node we are looking for
@return JSONArray The child we found or created
@throws IOException if there is a type mismatch on existing data | [
"Get",
"a",
"child",
"JSON",
"Array",
"from",
"an",
"incoming",
"JSON",
"object",
".",
"If",
"the",
"child",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
"."
] | train | https://github.com/redbox-mint/redbox/blob/1db230f218031b85c48c8603cbb04fce7ac6de0c/plugins/transaction/curation/src/main/java/com/googlecode/fascinator/redbox/plugins/curation/redbox/FormDataParser.java#L271-L289 |
betfair/cougar | cougar-framework/cougar-marshalling-impl/src/main/java/com/betfair/cougar/marshalling/impl/databinding/json/JSONBindingFactory.java | JSONBindingFactory.applyNumericRangeBugfixes | private static void applyNumericRangeBugfixes(ObjectMapper mapper) {
// Create a custom module
SimpleModule customModule = new SimpleModule("CustomModule", new Version(1, 0, 0, null, null, null));
// Register a deserializer for Integer that overrides default buggy version
customModule.addDeserializer(Integer.class, new IntegerDeserializer());
customModule.addDeserializer(int.class, new IntegerDeserializer());
// Register a deserializer for Long that overrides default buggy version
customModule.addDeserializer(Long.class, new LongDeserializer());
customModule.addDeserializer(long.class, new LongDeserializer());
// Register a deserializer for Byte that overrides default buggy version
customModule.addDeserializer(Byte.class, new ByteDeserializer());
customModule.addDeserializer(byte.class, new ByteDeserializer());
// Add the module to the mapper
mapper.registerModule(customModule);
} | java | private static void applyNumericRangeBugfixes(ObjectMapper mapper) {
// Create a custom module
SimpleModule customModule = new SimpleModule("CustomModule", new Version(1, 0, 0, null, null, null));
// Register a deserializer for Integer that overrides default buggy version
customModule.addDeserializer(Integer.class, new IntegerDeserializer());
customModule.addDeserializer(int.class, new IntegerDeserializer());
// Register a deserializer for Long that overrides default buggy version
customModule.addDeserializer(Long.class, new LongDeserializer());
customModule.addDeserializer(long.class, new LongDeserializer());
// Register a deserializer for Byte that overrides default buggy version
customModule.addDeserializer(Byte.class, new ByteDeserializer());
customModule.addDeserializer(byte.class, new ByteDeserializer());
// Add the module to the mapper
mapper.registerModule(customModule);
} | [
"private",
"static",
"void",
"applyNumericRangeBugfixes",
"(",
"ObjectMapper",
"mapper",
")",
"{",
"// Create a custom module",
"SimpleModule",
"customModule",
"=",
"new",
"SimpleModule",
"(",
"\"CustomModule\"",
",",
"new",
"Version",
"(",
"1",
",",
"0",
",",
"0",
... | Fixes problem in Jackson's StdDeserializer. with _parseInteger and _parseLong.
The provided implementation allowed out-of-range numbers to be shoe-horned into types, ignoring under/overflow.
E.g. 21474836470 would be deserialized into an Integer as -10.
E.g. 92233720368547758080 would be deserialized into a Long as 0. | [
"Fixes",
"problem",
"in",
"Jackson",
"s",
"StdDeserializer",
".",
"with",
"_parseInteger",
"and",
"_parseLong",
".",
"The",
"provided",
"implementation",
"allowed",
"out",
"-",
"of",
"-",
"range",
"numbers",
"to",
"be",
"shoe",
"-",
"horned",
"into",
"types",
... | train | https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/cougar-marshalling-impl/src/main/java/com/betfair/cougar/marshalling/impl/databinding/json/JSONBindingFactory.java#L77-L91 |
elki-project/elki | elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/utilities/scaling/outlier/MixtureModelOutlierScaling.java | MixtureModelOutlierScaling.calcP_i | protected static double calcP_i(double f, double mu, double sigma) {
final double fmu = f - mu;
return ONEBYSQRT2PI / sigma * FastMath.exp(fmu * fmu / (-2 * sigma * sigma));
} | java | protected static double calcP_i(double f, double mu, double sigma) {
final double fmu = f - mu;
return ONEBYSQRT2PI / sigma * FastMath.exp(fmu * fmu / (-2 * sigma * sigma));
} | [
"protected",
"static",
"double",
"calcP_i",
"(",
"double",
"f",
",",
"double",
"mu",
",",
"double",
"sigma",
")",
"{",
"final",
"double",
"fmu",
"=",
"f",
"-",
"mu",
";",
"return",
"ONEBYSQRT2PI",
"/",
"sigma",
"*",
"FastMath",
".",
"exp",
"(",
"fmu",
... | Compute p_i (Gaussian distribution, outliers)
@param f value
@param mu Mu parameter
@param sigma Sigma parameter
@return probability | [
"Compute",
"p_i",
"(",
"Gaussian",
"distribution",
"outliers",
")"
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-outlier/src/main/java/de/lmu/ifi/dbs/elki/utilities/scaling/outlier/MixtureModelOutlierScaling.java#L103-L106 |
molgenis/molgenis | molgenis-data/src/main/java/org/molgenis/data/util/EntityUtils.java | EntityUtils.getTypedValue | public static Object getTypedValue(String valueStr, Attribute attr, EntityManager entityManager) {
if (valueStr == null) return null;
switch (attr.getDataType()) {
case BOOL:
return Boolean.valueOf(valueStr);
case CATEGORICAL:
case FILE:
case XREF:
EntityType xrefEntity = attr.getRefEntity();
Object xrefIdValue = getTypedValue(valueStr, xrefEntity.getIdAttribute(), entityManager);
return entityManager.getReference(xrefEntity, xrefIdValue);
case CATEGORICAL_MREF:
case MREF:
case ONE_TO_MANY:
EntityType mrefEntity = attr.getRefEntity();
List<String> mrefIdStrValues = ListEscapeUtils.toList(valueStr);
return mrefIdStrValues
.stream()
.map(
mrefIdStrValue ->
getTypedValue(mrefIdStrValue, mrefEntity.getIdAttribute(), entityManager))
.map(mrefIdValue -> entityManager.getReference(mrefEntity, mrefIdValue))
.collect(toList());
case COMPOUND:
throw new IllegalArgumentException("Compound attribute has no value");
case DATE:
try {
return parseLocalDate(valueStr);
} catch (DateTimeParseException e) {
throw new MolgenisDataException(
format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATE_MESSAGE, attr.getName(), valueStr), e);
}
case DATE_TIME:
try {
return parseInstant(valueStr);
} catch (DateTimeParseException e) {
throw new MolgenisDataException(
format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATETIME_MESSAGE, attr.getName(), valueStr), e);
}
case DECIMAL:
return Double.valueOf(valueStr);
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case SCRIPT:
case STRING:
case TEXT:
return valueStr;
case INT:
return Integer.valueOf(valueStr);
case LONG:
return Long.valueOf(valueStr);
default:
throw new UnexpectedEnumException(attr.getDataType());
}
} | java | public static Object getTypedValue(String valueStr, Attribute attr, EntityManager entityManager) {
if (valueStr == null) return null;
switch (attr.getDataType()) {
case BOOL:
return Boolean.valueOf(valueStr);
case CATEGORICAL:
case FILE:
case XREF:
EntityType xrefEntity = attr.getRefEntity();
Object xrefIdValue = getTypedValue(valueStr, xrefEntity.getIdAttribute(), entityManager);
return entityManager.getReference(xrefEntity, xrefIdValue);
case CATEGORICAL_MREF:
case MREF:
case ONE_TO_MANY:
EntityType mrefEntity = attr.getRefEntity();
List<String> mrefIdStrValues = ListEscapeUtils.toList(valueStr);
return mrefIdStrValues
.stream()
.map(
mrefIdStrValue ->
getTypedValue(mrefIdStrValue, mrefEntity.getIdAttribute(), entityManager))
.map(mrefIdValue -> entityManager.getReference(mrefEntity, mrefIdValue))
.collect(toList());
case COMPOUND:
throw new IllegalArgumentException("Compound attribute has no value");
case DATE:
try {
return parseLocalDate(valueStr);
} catch (DateTimeParseException e) {
throw new MolgenisDataException(
format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATE_MESSAGE, attr.getName(), valueStr), e);
}
case DATE_TIME:
try {
return parseInstant(valueStr);
} catch (DateTimeParseException e) {
throw new MolgenisDataException(
format(FAILED_TO_PARSE_ATTRIBUTE_AS_DATETIME_MESSAGE, attr.getName(), valueStr), e);
}
case DECIMAL:
return Double.valueOf(valueStr);
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case SCRIPT:
case STRING:
case TEXT:
return valueStr;
case INT:
return Integer.valueOf(valueStr);
case LONG:
return Long.valueOf(valueStr);
default:
throw new UnexpectedEnumException(attr.getDataType());
}
} | [
"public",
"static",
"Object",
"getTypedValue",
"(",
"String",
"valueStr",
",",
"Attribute",
"attr",
",",
"EntityManager",
"entityManager",
")",
"{",
"if",
"(",
"valueStr",
"==",
"null",
")",
"return",
"null",
";",
"switch",
"(",
"attr",
".",
"getDataType",
"... | Convert a string value to a typed value based on the attribute data type.
@param valueStr string value
@param attr attribute
@param entityManager entity manager used to convert referenced entity values
@return typed value | [
"Convert",
"a",
"string",
"value",
"to",
"a",
"typed",
"value",
"based",
"on",
"the",
"attribute",
"data",
"type",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-data/src/main/java/org/molgenis/data/util/EntityUtils.java#L55-L111 |
samskivert/samskivert | src/main/java/com/samskivert/velocity/FormTool.java | FormTool.fixedText | public String fixedText (String name, String extra, Object value)
{
return fixedInput("text", name, value, extra);
} | java | public String fixedText (String name, String extra, Object value)
{
return fixedInput("text", name, value, extra);
} | [
"public",
"String",
"fixedText",
"(",
"String",
"name",
",",
"String",
"extra",
",",
"Object",
"value",
")",
"{",
"return",
"fixedInput",
"(",
"\"text\"",
",",
"name",
",",
"value",
",",
"extra",
")",
";",
"}"
] | Creates a text input field with the specified name and the
specified extra arguments and the specified value. | [
"Creates",
"a",
"text",
"input",
"field",
"with",
"the",
"specified",
"name",
"and",
"the",
"specified",
"extra",
"arguments",
"and",
"the",
"specified",
"value",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/FormTool.java#L90-L93 |
navnorth/LRJavaLib | src/com/navnorth/learningregistry/LRImporter.java | LRImporter.getObtainJSONData | private LRResult getObtainJSONData(String requestID, Boolean byResourceID, Boolean byDocID, Boolean idsOnly, String resumptionToken) throws LRException
{
String path = getObtainRequestPath(requestID, byResourceID, byDocID, idsOnly, resumptionToken);
JSONObject json = getJSONFromPath(path);
return new LRResult(json);
} | java | private LRResult getObtainJSONData(String requestID, Boolean byResourceID, Boolean byDocID, Boolean idsOnly, String resumptionToken) throws LRException
{
String path = getObtainRequestPath(requestID, byResourceID, byDocID, idsOnly, resumptionToken);
JSONObject json = getJSONFromPath(path);
return new LRResult(json);
} | [
"private",
"LRResult",
"getObtainJSONData",
"(",
"String",
"requestID",
",",
"Boolean",
"byResourceID",
",",
"Boolean",
"byDocID",
",",
"Boolean",
"idsOnly",
",",
"String",
"resumptionToken",
")",
"throws",
"LRException",
"{",
"String",
"path",
"=",
"getObtainReques... | Get a result from an obtain request
If the resumption token is not null, it will override the other parameters for ths request
@param requestID the "request_id" value to use for this request
@param byResourceID the "by_resource_id" value to use for this request
@param byDocID the "by_doc_id" value to use for this request
@param idsOnly the "ids_only" value to use for this request
@param resumptionToken the "resumption_token" value to use for this request
@return the result from this request | [
"Get",
"a",
"result",
"from",
"an",
"obtain",
"request",
"If",
"the",
"resumption",
"token",
"is",
"not",
"null",
"it",
"will",
"override",
"the",
"other",
"parameters",
"for",
"ths",
"request"
] | train | https://github.com/navnorth/LRJavaLib/blob/27af28b9f80d772273592414e7d0dccffaac09e1/src/com/navnorth/learningregistry/LRImporter.java#L247-L254 |
apptik/jus | jus-java/src/main/java/io/apptik/comm/jus/NetworkDispatcher.java | NetworkDispatcher.hasResponseBody | public static boolean hasResponseBody(String requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(100 <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
&& responseCode != HttpURLConnection.HTTP_NO_CONTENT
&& responseCode != HttpURLConnection.HTTP_RESET
&& responseCode != HttpURLConnection.HTTP_NOT_MODIFIED;
} | java | public static boolean hasResponseBody(String requestMethod, int responseCode) {
return requestMethod != Request.Method.HEAD
&& !(100 <= responseCode && responseCode < HttpURLConnection.HTTP_OK)
&& responseCode != HttpURLConnection.HTTP_NO_CONTENT
&& responseCode != HttpURLConnection.HTTP_RESET
&& responseCode != HttpURLConnection.HTTP_NOT_MODIFIED;
} | [
"public",
"static",
"boolean",
"hasResponseBody",
"(",
"String",
"requestMethod",
",",
"int",
"responseCode",
")",
"{",
"return",
"requestMethod",
"!=",
"Request",
".",
"Method",
".",
"HEAD",
"&&",
"!",
"(",
"100",
"<=",
"responseCode",
"&&",
"responseCode",
"... | Checks if a response message contains a body.
@param requestMethod request method
@param responseCode response status code
@return whether the response has a body
@see <a href="https://tools.ietf.org/html/rfc7230#section-3.3">RFC 7230 section 3.3</a> | [
"Checks",
"if",
"a",
"response",
"message",
"contains",
"a",
"body",
"."
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/jus-java/src/main/java/io/apptik/comm/jus/NetworkDispatcher.java#L83-L89 |
Netflix/Hystrix | hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java | HystrixCommandExecutionHook.onError | @Deprecated
public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) {
// pass-thru by default
return e;
} | java | @Deprecated
public <T> Exception onError(HystrixCommand<T> commandInstance, FailureType failureType, Exception e) {
// pass-thru by default
return e;
} | [
"@",
"Deprecated",
"public",
"<",
"T",
">",
"Exception",
"onError",
"(",
"HystrixCommand",
"<",
"T",
">",
"commandInstance",
",",
"FailureType",
"failureType",
",",
"Exception",
"e",
")",
"{",
"// pass-thru by default",
"return",
"e",
";",
"}"
] | DEPRECATED: Change usages of this to {@link #onError}.
Invoked after failed completion of {@link HystrixCommand} execution.
@param commandInstance
The executing HystrixCommand instance.
@param failureType
{@link FailureType} representing the type of failure that occurred.
<p>
See {@link HystrixRuntimeException} for more information.
@param e
Exception thrown by {@link HystrixCommand}
@return Exception that can be decorated, replaced or just returned as a pass-thru.
@since 1.2 | [
"DEPRECATED",
":",
"Change",
"usages",
"of",
"this",
"to",
"{",
"@link",
"#onError",
"}",
"."
] | train | https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-core/src/main/java/com/netflix/hystrix/strategy/executionhook/HystrixCommandExecutionHook.java#L492-L496 |
Jasig/uPortal | uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java | RDBMEntityLockStore.primSelect | private IEntityLock[] primSelect(String sql) throws LockingException {
Connection conn = null;
Statement stmnt = null;
ResultSet rs = null;
List locks = new ArrayList();
if (log.isDebugEnabled()) log.debug("RDBMEntityLockStore.primSelect(): " + sql);
try {
conn = RDBMServices.getConnection();
stmnt = conn.createStatement();
try {
rs = stmnt.executeQuery(sql);
try {
while (rs.next()) {
locks.add(instanceFromResultSet(rs));
}
} finally {
rs.close();
}
} finally {
stmnt.close();
}
} catch (SQLException sqle) {
log.error(sqle, sqle);
throw new LockingException("Problem retrieving EntityLocks", sqle);
} finally {
RDBMServices.releaseConnection(conn);
}
return ((IEntityLock[]) locks.toArray(new IEntityLock[locks.size()]));
} | java | private IEntityLock[] primSelect(String sql) throws LockingException {
Connection conn = null;
Statement stmnt = null;
ResultSet rs = null;
List locks = new ArrayList();
if (log.isDebugEnabled()) log.debug("RDBMEntityLockStore.primSelect(): " + sql);
try {
conn = RDBMServices.getConnection();
stmnt = conn.createStatement();
try {
rs = stmnt.executeQuery(sql);
try {
while (rs.next()) {
locks.add(instanceFromResultSet(rs));
}
} finally {
rs.close();
}
} finally {
stmnt.close();
}
} catch (SQLException sqle) {
log.error(sqle, sqle);
throw new LockingException("Problem retrieving EntityLocks", sqle);
} finally {
RDBMServices.releaseConnection(conn);
}
return ((IEntityLock[]) locks.toArray(new IEntityLock[locks.size()]));
} | [
"private",
"IEntityLock",
"[",
"]",
"primSelect",
"(",
"String",
"sql",
")",
"throws",
"LockingException",
"{",
"Connection",
"conn",
"=",
"null",
";",
"Statement",
"stmnt",
"=",
"null",
";",
"ResultSet",
"rs",
"=",
"null",
";",
"List",
"locks",
"=",
"new"... | Retrieve IEntityLocks from the underlying store.
@param sql String - the sql string used to select the entity lock rows.
@exception LockingException - wraps an Exception specific to the store. | [
"Retrieve",
"IEntityLocks",
"from",
"the",
"underlying",
"store",
"."
] | train | https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-utils/uPortal-utils-core/src/main/java/org/apereo/portal/concurrency/locking/RDBMEntityLockStore.java#L471-L502 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java | ApiOvhDedicatedserver.serviceName_install_templateCapabilities_GET | public OvhTemplateCaps serviceName_install_templateCapabilities_GET(String serviceName, String templateName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/install/templateCapabilities";
StringBuilder sb = path(qPath, serviceName);
query(sb, "templateName", templateName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTemplateCaps.class);
} | java | public OvhTemplateCaps serviceName_install_templateCapabilities_GET(String serviceName, String templateName) throws IOException {
String qPath = "/dedicated/server/{serviceName}/install/templateCapabilities";
StringBuilder sb = path(qPath, serviceName);
query(sb, "templateName", templateName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhTemplateCaps.class);
} | [
"public",
"OvhTemplateCaps",
"serviceName_install_templateCapabilities_GET",
"(",
"String",
"serviceName",
",",
"String",
"templateName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/server/{serviceName}/install/templateCapabilities\"",
";",
"StringBui... | Gives some capabilities regarding the template for the current dedicated server.
REST: GET /dedicated/server/{serviceName}/install/templateCapabilities
@param templateName [required]
@param serviceName [required] The internal name of your dedicated server | [
"Gives",
"some",
"capabilities",
"regarding",
"the",
"template",
"for",
"the",
"current",
"dedicated",
"server",
"."
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L1624-L1630 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelUtils.java | KerasModelUtils.determineKerasMajorVersion | public static int determineKerasMajorVersion(Map<String, Object> modelConfig, KerasModelConfiguration config)
throws InvalidKerasConfigurationException {
int kerasMajorVersion;
if (!modelConfig.containsKey(config.getFieldKerasVersion())) {
log.warn("Could not read keras version used (no "
+ config.getFieldKerasVersion() + " field found) \n"
+ "assuming keras version is 1.0.7 or earlier."
);
kerasMajorVersion = 1;
} else {
String kerasVersionString = (String) modelConfig.get(config.getFieldKerasVersion());
if (Character.isDigit(kerasVersionString.charAt(0))) {
kerasMajorVersion = Character.getNumericValue(kerasVersionString.charAt(0));
} else {
throw new InvalidKerasConfigurationException(
"Keras version was not readable (" + config.getFieldKerasVersion() + " provided)"
);
}
}
return kerasMajorVersion;
} | java | public static int determineKerasMajorVersion(Map<String, Object> modelConfig, KerasModelConfiguration config)
throws InvalidKerasConfigurationException {
int kerasMajorVersion;
if (!modelConfig.containsKey(config.getFieldKerasVersion())) {
log.warn("Could not read keras version used (no "
+ config.getFieldKerasVersion() + " field found) \n"
+ "assuming keras version is 1.0.7 or earlier."
);
kerasMajorVersion = 1;
} else {
String kerasVersionString = (String) modelConfig.get(config.getFieldKerasVersion());
if (Character.isDigit(kerasVersionString.charAt(0))) {
kerasMajorVersion = Character.getNumericValue(kerasVersionString.charAt(0));
} else {
throw new InvalidKerasConfigurationException(
"Keras version was not readable (" + config.getFieldKerasVersion() + " provided)"
);
}
}
return kerasMajorVersion;
} | [
"public",
"static",
"int",
"determineKerasMajorVersion",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"modelConfig",
",",
"KerasModelConfiguration",
"config",
")",
"throws",
"InvalidKerasConfigurationException",
"{",
"int",
"kerasMajorVersion",
";",
"if",
"(",
"!",
... | Determine Keras major version
@param modelConfig parsed model configuration for keras model
@param config basic model configuration (KerasModelConfiguration)
@return Major Keras version (1 or 2)
@throws InvalidKerasConfigurationException Invalid Keras config | [
"Determine",
"Keras",
"major",
"version"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-modelimport/src/main/java/org/deeplearning4j/nn/modelimport/keras/utils/KerasModelUtils.java#L96-L116 |
maxirosson/jdroid-android | jdroid-android-core/src/main/java/com/jdroid/android/utils/SharedPreferencesHelper.java | SharedPreferencesHelper.loadPreferenceAsInteger | public Integer loadPreferenceAsInteger(String key, Integer defaultValue) {
Integer value = defaultValue;
if (hasPreference(key)) {
value = getSharedPreferences().getInt(key, 0);
}
logLoad(key, value);
return value;
} | java | public Integer loadPreferenceAsInteger(String key, Integer defaultValue) {
Integer value = defaultValue;
if (hasPreference(key)) {
value = getSharedPreferences().getInt(key, 0);
}
logLoad(key, value);
return value;
} | [
"public",
"Integer",
"loadPreferenceAsInteger",
"(",
"String",
"key",
",",
"Integer",
"defaultValue",
")",
"{",
"Integer",
"value",
"=",
"defaultValue",
";",
"if",
"(",
"hasPreference",
"(",
"key",
")",
")",
"{",
"value",
"=",
"getSharedPreferences",
"(",
")",... | Retrieve an Integer value from the preferences.
@param key The name of the preference to retrieve
@param defaultValue Value to return if this preference does not exist
@return the preference value if it exists, or defaultValue. | [
"Retrieve",
"an",
"Integer",
"value",
"from",
"the",
"preferences",
"."
] | train | https://github.com/maxirosson/jdroid-android/blob/1ba9cae56a16fa36bdb2c9c04379853f0300707f/jdroid-android-core/src/main/java/com/jdroid/android/utils/SharedPreferencesHelper.java#L255-L262 |
defei/codelogger-utils | src/main/java/org/codelogger/utils/HttpUtils.java | HttpUtils.doGet | public static String doGet(final String url, final int retryTimes) {
try {
return doGetByLoop(url, retryTimes);
} catch (HttpException e) {
throw new HttpException(format("Failed to download content for url: '%s'. Tried '%s' times",
url, Math.max(retryTimes + 1, 1)));
}
} | java | public static String doGet(final String url, final int retryTimes) {
try {
return doGetByLoop(url, retryTimes);
} catch (HttpException e) {
throw new HttpException(format("Failed to download content for url: '%s'. Tried '%s' times",
url, Math.max(retryTimes + 1, 1)));
}
} | [
"public",
"static",
"String",
"doGet",
"(",
"final",
"String",
"url",
",",
"final",
"int",
"retryTimes",
")",
"{",
"try",
"{",
"return",
"doGetByLoop",
"(",
"url",
",",
"retryTimes",
")",
";",
"}",
"catch",
"(",
"HttpException",
"e",
")",
"{",
"throw",
... | access given url by get request, if get exception, will retry by given
retryTimes.
@param url url to access
@param retryTimes retry times when get exception.
@return response content of target url. | [
"access",
"given",
"url",
"by",
"get",
"request",
"if",
"get",
"exception",
"will",
"retry",
"by",
"given",
"retryTimes",
"."
] | train | https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/HttpUtils.java#L66-L74 |
HiddenStage/divide | Client/android-client/src/main/java/com/google/android/gcm/GCMRegistrar.java | GCMRegistrar.setRegistrationId | static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
} | java | static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
Log.v(TAG, "Saving regId on app version " + appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
} | [
"static",
"String",
"setRegistrationId",
"(",
"Context",
"context",
",",
"String",
"regId",
")",
"{",
"final",
"SharedPreferences",
"prefs",
"=",
"getGCMPreferences",
"(",
"context",
")",
";",
"String",
"oldRegistrationId",
"=",
"prefs",
".",
"getString",
"(",
"... | Sets the registration id in the persistence store.
@param context application's context.
@param regId registration id | [
"Sets",
"the",
"registration",
"id",
"in",
"the",
"persistence",
"store",
"."
] | train | https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Client/android-client/src/main/java/com/google/android/gcm/GCMRegistrar.java#L364-L374 |
EdwardRaff/JSAT | JSAT/src/jsat/math/ExponentialMovingStatistics.java | ExponentialMovingStatistics.setSmoothing | public void setSmoothing(double smoothing)
{
if (smoothing <= 0 || smoothing > 1 || Double.isNaN(smoothing))
throw new IllegalArgumentException("Smoothing must be in (0, 1], not " + smoothing);
this.smoothing = smoothing;
} | java | public void setSmoothing(double smoothing)
{
if (smoothing <= 0 || smoothing > 1 || Double.isNaN(smoothing))
throw new IllegalArgumentException("Smoothing must be in (0, 1], not " + smoothing);
this.smoothing = smoothing;
} | [
"public",
"void",
"setSmoothing",
"(",
"double",
"smoothing",
")",
"{",
"if",
"(",
"smoothing",
"<=",
"0",
"||",
"smoothing",
">",
"1",
"||",
"Double",
".",
"isNaN",
"(",
"smoothing",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Smoothing mu... | Sets the smoothing parameter value to use. Must be in the range (0, 1].
Changing this value will impact how quickly the statistics adapt to
changes, with larger values increasing rate of change and smaller values
decreasing it.
@param smoothing the smoothing value to use | [
"Sets",
"the",
"smoothing",
"parameter",
"value",
"to",
"use",
".",
"Must",
"be",
"in",
"the",
"range",
"(",
"0",
"1",
"]",
".",
"Changing",
"this",
"value",
"will",
"impact",
"how",
"quickly",
"the",
"statistics",
"adapt",
"to",
"changes",
"with",
"larg... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/math/ExponentialMovingStatistics.java#L86-L91 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getPatternAnyEntityRoles | public List<EntityRole> getPatternAnyEntityRoles(UUID appId, String versionId, UUID entityId) {
return getPatternAnyEntityRolesWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | java | public List<EntityRole> getPatternAnyEntityRoles(UUID appId, String versionId, UUID entityId) {
return getPatternAnyEntityRolesWithServiceResponseAsync(appId, versionId, entityId).toBlocking().single().body();
} | [
"public",
"List",
"<",
"EntityRole",
">",
"getPatternAnyEntityRoles",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"entityId",
")",
"{",
"return",
"getPatternAnyEntityRolesWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"entityId",
... | Get All Entity Roles for a given entity.
@param appId The application ID.
@param versionId The version ID.
@param entityId entity Id
@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<EntityRole> object if successful. | [
"Get",
"All",
"Entity",
"Roles",
"for",
"a",
"given",
"entity",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L9059-L9061 |
Waikato/jclasslocator | src/main/java/nz/ac/waikato/cms/locator/LoggingHelper.java | LoggingHelper.getLevel | public static Level getLevel(Class cls, Level defLevel) {
Level result;
String levelStr;
result = defLevel;
levelStr = System.getenv(cls.getName() + LOGLEVEL_SUFFIX);
if (levelStr != null) {
switch (levelStr) {
case "ALL":
return Level.ALL;
case "OFF":
return Level.OFF;
case "INFO":
return Level.INFO;
case "CONFIG":
return Level.CONFIG;
case "FINE":
return Level.FINE;
case "FINER":
return Level.FINER;
case "FINEST":
return Level.FINEST;
case "WARNING":
return Level.WARNING;
case "SEVERE":
return Level.SEVERE;
}
}
return result;
} | java | public static Level getLevel(Class cls, Level defLevel) {
Level result;
String levelStr;
result = defLevel;
levelStr = System.getenv(cls.getName() + LOGLEVEL_SUFFIX);
if (levelStr != null) {
switch (levelStr) {
case "ALL":
return Level.ALL;
case "OFF":
return Level.OFF;
case "INFO":
return Level.INFO;
case "CONFIG":
return Level.CONFIG;
case "FINE":
return Level.FINE;
case "FINER":
return Level.FINER;
case "FINEST":
return Level.FINEST;
case "WARNING":
return Level.WARNING;
case "SEVERE":
return Level.SEVERE;
}
}
return result;
} | [
"public",
"static",
"Level",
"getLevel",
"(",
"Class",
"cls",
",",
"Level",
"defLevel",
")",
"{",
"Level",
"result",
";",
"String",
"levelStr",
";",
"result",
"=",
"defLevel",
";",
"levelStr",
"=",
"System",
".",
"getenv",
"(",
"cls",
".",
"getName",
"("... | Returns the log level for the specified class. E.g., for the class
"hello.world.App" the environment variable "hello.world.App.LOGLEVEL"
is inspected and "{OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST}"
returned. Default is WARNING.
@param cls the class to return the debug level for
@param defLevel the default level to use
@return the logging level | [
"Returns",
"the",
"log",
"level",
"for",
"the",
"specified",
"class",
".",
"E",
".",
"g",
".",
"for",
"the",
"class",
"hello",
".",
"world",
".",
"App",
"the",
"environment",
"variable",
"hello",
".",
"world",
".",
"App",
".",
"LOGLEVEL",
"is",
"inspec... | train | https://github.com/Waikato/jclasslocator/blob/c899072fff607a56ee7f8c2d01fbeb15157ad144/src/main/java/nz/ac/waikato/cms/locator/LoggingHelper.java#L58-L89 |
jenkinsci/jenkins | core/src/main/java/jenkins/model/Jenkins.java | Jenkins.getXForwardedHeader | private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
} | java | private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
} | [
"private",
"static",
"String",
"getXForwardedHeader",
"(",
"StaplerRequest",
"req",
",",
"String",
"header",
",",
"String",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"req",
".",
"getHeader",
"(",
"header",
")",
";",
"if",
"(",
"value",
"!=",
"null",
... | Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
header is the first header. If the originating header contains a comma separated list, the originating entry
is the first one.
@param req the request
@param header the header name
@param defaultValue the value to return if the header is absent.
@return the originating entry of the header or the default value if the header was not present. | [
"Gets",
"the",
"originating",
"X",
"-",
"Forwarded",
"-",
"...",
"header",
"from",
"the",
"request",
".",
"If",
"there",
"are",
"multiple",
"headers",
"the",
"originating",
"header",
"is",
"the",
"first",
"header",
".",
"If",
"the",
"originating",
"header",
... | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/jenkins/model/Jenkins.java#L2367-L2374 |
JakeWharton/NineOldAndroids | library/src/com/nineoldandroids/util/ReflectiveProperty.java | ReflectiveProperty.typesMatch | private boolean typesMatch(Class<V> valueType, Class getterType) {
if (getterType != valueType) {
if (getterType.isPrimitive()) {
return (getterType == float.class && valueType == Float.class) ||
(getterType == int.class && valueType == Integer.class) ||
(getterType == boolean.class && valueType == Boolean.class) ||
(getterType == long.class && valueType == Long.class) ||
(getterType == double.class && valueType == Double.class) ||
(getterType == short.class && valueType == Short.class) ||
(getterType == byte.class && valueType == Byte.class) ||
(getterType == char.class && valueType == Character.class);
}
return false;
}
return true;
} | java | private boolean typesMatch(Class<V> valueType, Class getterType) {
if (getterType != valueType) {
if (getterType.isPrimitive()) {
return (getterType == float.class && valueType == Float.class) ||
(getterType == int.class && valueType == Integer.class) ||
(getterType == boolean.class && valueType == Boolean.class) ||
(getterType == long.class && valueType == Long.class) ||
(getterType == double.class && valueType == Double.class) ||
(getterType == short.class && valueType == Short.class) ||
(getterType == byte.class && valueType == Byte.class) ||
(getterType == char.class && valueType == Character.class);
}
return false;
}
return true;
} | [
"private",
"boolean",
"typesMatch",
"(",
"Class",
"<",
"V",
">",
"valueType",
",",
"Class",
"getterType",
")",
"{",
"if",
"(",
"getterType",
"!=",
"valueType",
")",
"{",
"if",
"(",
"getterType",
".",
"isPrimitive",
"(",
")",
")",
"{",
"return",
"(",
"g... | Utility method to check whether the type of the underlying field/method on the target
object matches the type of the Property. The extra checks for primitive types are because
generics will force the Property type to be a class, whereas the type of the underlying
method/field will probably be a primitive type instead. Accept float as matching Float,
etc. | [
"Utility",
"method",
"to",
"check",
"whether",
"the",
"type",
"of",
"the",
"underlying",
"field",
"/",
"method",
"on",
"the",
"target",
"object",
"matches",
"the",
"type",
"of",
"the",
"Property",
".",
"The",
"extra",
"checks",
"for",
"primitive",
"types",
... | train | https://github.com/JakeWharton/NineOldAndroids/blob/d582f0ec8e79013e9fa96c07986160b52e662e63/library/src/com/nineoldandroids/util/ReflectiveProperty.java#L116-L131 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/websphere/channelfw/ChannelUtils.java | ChannelUtils.defineEndPoint | private static EndPointInfo defineEndPoint(EndPointMgr epm, String name, String[] config) {
String host = null;
String port = null;
for (int i = 0; i < config.length; i++) {
String key = ChannelUtils.extractKey(config[i]);
if ("host".equalsIgnoreCase(key)) {
host = ChannelUtils.extractValue(config[i]);
} else if ("port".equalsIgnoreCase(key)) {
port = ChannelUtils.extractValue(config[i]);
}
}
return epm.defineEndPoint(name, host, Integer.parseInt(port));
} | java | private static EndPointInfo defineEndPoint(EndPointMgr epm, String name, String[] config) {
String host = null;
String port = null;
for (int i = 0; i < config.length; i++) {
String key = ChannelUtils.extractKey(config[i]);
if ("host".equalsIgnoreCase(key)) {
host = ChannelUtils.extractValue(config[i]);
} else if ("port".equalsIgnoreCase(key)) {
port = ChannelUtils.extractValue(config[i]);
}
}
return epm.defineEndPoint(name, host, Integer.parseInt(port));
} | [
"private",
"static",
"EndPointInfo",
"defineEndPoint",
"(",
"EndPointMgr",
"epm",
",",
"String",
"name",
",",
"String",
"[",
"]",
"config",
")",
"{",
"String",
"host",
"=",
"null",
";",
"String",
"port",
"=",
"null",
";",
"for",
"(",
"int",
"i",
"=",
"... | Define a new endpoint definition using the input name and list of
properties.
@param name
@param config
@return EndPointInfo
@throws IllegalArgumentException if input values are incorrect | [
"Define",
"a",
"new",
"endpoint",
"definition",
"using",
"the",
"input",
"name",
"and",
"list",
"of",
"properties",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/websphere/channelfw/ChannelUtils.java#L977-L989 |
netty/netty | handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java | ReferenceCountedOpenSslEngine.writePlaintextData | private int writePlaintextData(final ByteBuffer src, int len) {
final int pos = src.position();
final int limit = src.limit();
final int sslWrote;
if (src.isDirect()) {
sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
}
} else {
ByteBuf buf = alloc.directBuffer(len);
try {
src.limit(pos + len);
buf.setBytes(0, src);
src.limit(limit);
sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return sslWrote;
} | java | private int writePlaintextData(final ByteBuffer src, int len) {
final int pos = src.position();
final int limit = src.limit();
final int sslWrote;
if (src.isDirect()) {
sslWrote = SSL.writeToSSL(ssl, bufferAddress(src) + pos, len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
}
} else {
ByteBuf buf = alloc.directBuffer(len);
try {
src.limit(pos + len);
buf.setBytes(0, src);
src.limit(limit);
sslWrote = SSL.writeToSSL(ssl, memoryAddress(buf), len);
if (sslWrote > 0) {
src.position(pos + sslWrote);
} else {
src.position(pos);
}
} finally {
buf.release();
}
}
return sslWrote;
} | [
"private",
"int",
"writePlaintextData",
"(",
"final",
"ByteBuffer",
"src",
",",
"int",
"len",
")",
"{",
"final",
"int",
"pos",
"=",
"src",
".",
"position",
"(",
")",
";",
"final",
"int",
"limit",
"=",
"src",
".",
"limit",
"(",
")",
";",
"final",
"int... | Write plaintext data to the OpenSSL internal BIO
Calling this function with src.remaining == 0 is undefined. | [
"Write",
"plaintext",
"data",
"to",
"the",
"OpenSSL",
"internal",
"BIO"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java#L505-L534 |
notnoop/java-apns | src/main/java/com/notnoop/apns/ApnsServiceBuilder.java | ApnsServiceBuilder.build | public ApnsService build() {
checkInitialization();
ApnsService service;
SSLSocketFactory sslFactory = sslContext.getSocketFactory();
ApnsFeedbackConnection feedback = new ApnsFeedbackConnection(sslFactory, feedbackHost, feedbackPort, proxy, readTimeout, connectTimeout, proxyUsername, proxyPassword);
ApnsConnection conn = new ApnsConnectionImpl(sslFactory, gatewayHost,
gatewayPort, proxy, proxyUsername, proxyPassword, reconnectPolicy,
delegate, errorDetection, errorDetectionThreadFactory, cacheLength,
autoAdjustCacheLength, readTimeout, connectTimeout);
if (pooledMax != 1) {
conn = new ApnsPooledConnection(conn, pooledMax, executor);
}
service = new ApnsServiceImpl(conn, feedback);
if (isQueued) {
service = new QueuedApnsService(service, queueThreadFactory);
}
if (isBatched) {
service = new BatchApnsService(conn, feedback, batchWaitTimeInSec, batchMaxWaitTimeInSec, batchThreadPoolExecutor);
}
service.start();
return service;
} | java | public ApnsService build() {
checkInitialization();
ApnsService service;
SSLSocketFactory sslFactory = sslContext.getSocketFactory();
ApnsFeedbackConnection feedback = new ApnsFeedbackConnection(sslFactory, feedbackHost, feedbackPort, proxy, readTimeout, connectTimeout, proxyUsername, proxyPassword);
ApnsConnection conn = new ApnsConnectionImpl(sslFactory, gatewayHost,
gatewayPort, proxy, proxyUsername, proxyPassword, reconnectPolicy,
delegate, errorDetection, errorDetectionThreadFactory, cacheLength,
autoAdjustCacheLength, readTimeout, connectTimeout);
if (pooledMax != 1) {
conn = new ApnsPooledConnection(conn, pooledMax, executor);
}
service = new ApnsServiceImpl(conn, feedback);
if (isQueued) {
service = new QueuedApnsService(service, queueThreadFactory);
}
if (isBatched) {
service = new BatchApnsService(conn, feedback, batchWaitTimeInSec, batchMaxWaitTimeInSec, batchThreadPoolExecutor);
}
service.start();
return service;
} | [
"public",
"ApnsService",
"build",
"(",
")",
"{",
"checkInitialization",
"(",
")",
";",
"ApnsService",
"service",
";",
"SSLSocketFactory",
"sslFactory",
"=",
"sslContext",
".",
"getSocketFactory",
"(",
")",
";",
"ApnsFeedbackConnection",
"feedback",
"=",
"new",
"Ap... | Returns a fully initialized instance of {@link ApnsService},
according to the requested settings.
@return a new instance of ApnsService | [
"Returns",
"a",
"fully",
"initialized",
"instance",
"of",
"{",
"@link",
"ApnsService",
"}",
"according",
"to",
"the",
"requested",
"settings",
"."
] | train | https://github.com/notnoop/java-apns/blob/180a190d4cb49458441596ca7c69d50ec7f1dba5/src/main/java/com/notnoop/apns/ApnsServiceBuilder.java#L719-L747 |
m-m-m/util | io/src/main/java/net/sf/mmm/util/file/base/FileAccessPermissions.java | FileAccessPermissions.shiftMask | private int shiftMask(FileAccessClass fileModeClass, int bitMask) {
if (fileModeClass == FileAccessClass.USER) {
return bitMask << 6;
} else if (fileModeClass == FileAccessClass.GROUP) {
return bitMask << 3;
} else if (fileModeClass == FileAccessClass.OTHERS) {
return bitMask;
}
throw new IllegalArgumentException("Illegal FileModeClass: " + fileModeClass);
} | java | private int shiftMask(FileAccessClass fileModeClass, int bitMask) {
if (fileModeClass == FileAccessClass.USER) {
return bitMask << 6;
} else if (fileModeClass == FileAccessClass.GROUP) {
return bitMask << 3;
} else if (fileModeClass == FileAccessClass.OTHERS) {
return bitMask;
}
throw new IllegalArgumentException("Illegal FileModeClass: " + fileModeClass);
} | [
"private",
"int",
"shiftMask",
"(",
"FileAccessClass",
"fileModeClass",
",",
"int",
"bitMask",
")",
"{",
"if",
"(",
"fileModeClass",
"==",
"FileAccessClass",
".",
"USER",
")",
"{",
"return",
"bitMask",
"<<",
"6",
";",
"}",
"else",
"if",
"(",
"fileModeClass",... | This method shifts the given {@code bitMask} according to the given {@code fileModeClass}.
@param fileModeClass is the class of access ( {@link FileAccessClass#USER}, {@link FileAccessClass#GROUP}, or
{@link FileAccessClass#OTHERS}).
@param bitMask is the bit-mask to shift.
@return the shifted {@code bitMask}. | [
"This",
"method",
"shifts",
"the",
"given",
"{",
"@code",
"bitMask",
"}",
"according",
"to",
"the",
"given",
"{",
"@code",
"fileModeClass",
"}",
"."
] | train | https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/io/src/main/java/net/sf/mmm/util/file/base/FileAccessPermissions.java#L315-L325 |
kuali/ojb-1.0.4 | src/xdoclet/java/src/xdoclet/modules/ojb/constraints/FieldDescriptorConstraints.java | FieldDescriptorConstraints.ensureColumn | private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))
{
String javaname = fieldDef.getName();
if (fieldDef.isNested())
{
int pos = javaname.indexOf("::");
// we convert nested names ('_' for '::')
if (pos > 0)
{
StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));
int lastPos = pos + 2;
do
{
pos = javaname.indexOf("::", lastPos);
newJavaname.append("_");
if (pos > 0)
{
newJavaname.append(javaname.substring(lastPos, pos));
lastPos = pos + 2;
}
else
{
newJavaname.append(javaname.substring(lastPos));
}
}
while (pos > 0);
javaname = newJavaname.toString();
}
}
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);
}
} | java | private void ensureColumn(FieldDescriptorDef fieldDef, String checkLevel)
{
if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN))
{
String javaname = fieldDef.getName();
if (fieldDef.isNested())
{
int pos = javaname.indexOf("::");
// we convert nested names ('_' for '::')
if (pos > 0)
{
StringBuffer newJavaname = new StringBuffer(javaname.substring(0, pos));
int lastPos = pos + 2;
do
{
pos = javaname.indexOf("::", lastPos);
newJavaname.append("_");
if (pos > 0)
{
newJavaname.append(javaname.substring(lastPos, pos));
lastPos = pos + 2;
}
else
{
newJavaname.append(javaname.substring(lastPos));
}
}
while (pos > 0);
javaname = newJavaname.toString();
}
}
fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN, javaname);
}
} | [
"private",
"void",
"ensureColumn",
"(",
"FieldDescriptorDef",
"fieldDef",
",",
"String",
"checkLevel",
")",
"{",
"if",
"(",
"!",
"fieldDef",
".",
"hasProperty",
"(",
"PropertyHelper",
".",
"OJB_PROPERTY_COLUMN",
")",
")",
"{",
"String",
"javaname",
"=",
"fieldDe... | Constraint that ensures that the field has a column property. If none is specified, then
the name of the field is used.
@param fieldDef The field descriptor
@param checkLevel The current check level (this constraint is checked in all levels) | [
"Constraint",
"that",
"ensures",
"that",
"the",
"field",
"has",
"a",
"column",
"property",
".",
"If",
"none",
"is",
"specified",
"then",
"the",
"name",
"of",
"the",
"field",
"is",
"used",
"."
] | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/constraints/FieldDescriptorConstraints.java#L103-L139 |
KyoriPowered/text | api/src/main/java/net/kyori/text/TranslatableComponent.java | TranslatableComponent.make | public static TranslatableComponent make(final @NonNull String key, final @NonNull List<Component> args, final @NonNull Consumer<Builder> consumer) {
final Builder builder = builder(key).args(args);
consumer.accept(builder);
return builder.build();
} | java | public static TranslatableComponent make(final @NonNull String key, final @NonNull List<Component> args, final @NonNull Consumer<Builder> consumer) {
final Builder builder = builder(key).args(args);
consumer.accept(builder);
return builder.build();
} | [
"public",
"static",
"TranslatableComponent",
"make",
"(",
"final",
"@",
"NonNull",
"String",
"key",
",",
"final",
"@",
"NonNull",
"List",
"<",
"Component",
">",
"args",
",",
"final",
"@",
"NonNull",
"Consumer",
"<",
"Builder",
">",
"consumer",
")",
"{",
"f... | Creates a translatable component by applying configuration from {@code consumer}.
@param key the translation key
@param args the translation arguments
@param consumer the builder configurator
@return the translatable component | [
"Creates",
"a",
"translatable",
"component",
"by",
"applying",
"configuration",
"from",
"{",
"@code",
"consumer",
"}",
"."
] | train | https://github.com/KyoriPowered/text/blob/4496c593bf89e8fb036dd6efe26f8ac60f7655c9/api/src/main/java/net/kyori/text/TranslatableComponent.java#L224-L228 |
Whiley/WhileyCompiler | src/main/java/wyil/check/FlowTypeCheck.java | FlowTypeCheck.checkLVal | public Type checkLVal(LVal lval, Environment environment) {
Type type;
switch (lval.getOpcode()) {
case EXPR_variablecopy:
type = checkVariableLVal((Expr.VariableAccess) lval, environment);
break;
case EXPR_staticvariable:
type = checkStaticVariableLVal((Expr.StaticVariableAccess) lval, environment);
break;
case EXPR_arrayaccess:
case EXPR_arrayborrow:
type = checkArrayLVal((Expr.ArrayAccess) lval, environment);
break;
case EXPR_recordaccess:
case EXPR_recordborrow:
type = checkRecordLVal((Expr.RecordAccess) lval, environment);
break;
case EXPR_dereference:
type = checkDereferenceLVal((Expr.Dereference) lval, environment);
break;
default:
return internalFailure("unknown lval encountered (" + lval.getClass().getSimpleName() + ")", lval);
}
// Sanity check type. This can be non-sensical in the case of an upsteam type
// error
if (type != null) {
lval.setType(lval.getHeap().allocate(type));
}
return type;
} | java | public Type checkLVal(LVal lval, Environment environment) {
Type type;
switch (lval.getOpcode()) {
case EXPR_variablecopy:
type = checkVariableLVal((Expr.VariableAccess) lval, environment);
break;
case EXPR_staticvariable:
type = checkStaticVariableLVal((Expr.StaticVariableAccess) lval, environment);
break;
case EXPR_arrayaccess:
case EXPR_arrayborrow:
type = checkArrayLVal((Expr.ArrayAccess) lval, environment);
break;
case EXPR_recordaccess:
case EXPR_recordborrow:
type = checkRecordLVal((Expr.RecordAccess) lval, environment);
break;
case EXPR_dereference:
type = checkDereferenceLVal((Expr.Dereference) lval, environment);
break;
default:
return internalFailure("unknown lval encountered (" + lval.getClass().getSimpleName() + ")", lval);
}
// Sanity check type. This can be non-sensical in the case of an upsteam type
// error
if (type != null) {
lval.setType(lval.getHeap().allocate(type));
}
return type;
} | [
"public",
"Type",
"checkLVal",
"(",
"LVal",
"lval",
",",
"Environment",
"environment",
")",
"{",
"Type",
"type",
";",
"switch",
"(",
"lval",
".",
"getOpcode",
"(",
")",
")",
"{",
"case",
"EXPR_variablecopy",
":",
"type",
"=",
"checkVariableLVal",
"(",
"(",... | Type check a given lval assuming an initial environment. This returns the
largest type which can be safely assigned to the lval. Observe that this type
is determined by the declared type of the variable being assigned.
@param expression
@param environment
@return
@throws ResolutionError | [
"Type",
"check",
"a",
"given",
"lval",
"assuming",
"an",
"initial",
"environment",
".",
"This",
"returns",
"the",
"largest",
"type",
"which",
"can",
"be",
"safely",
"assigned",
"to",
"the",
"lval",
".",
"Observe",
"that",
"this",
"type",
"is",
"determined",
... | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/check/FlowTypeCheck.java#L1104-L1133 |
elki-project/elki | elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/result/ResultHierarchy.java | ResultHierarchy.fireResultAdded | private void fireResultAdded(Result child, Result parent) {
if(LOG.isDebugging()) {
LOG.debug("Result added: " + child + " <- " + parent);
}
for(int i = listenerList.size(); --i >= 0;) {
listenerList.get(i).resultAdded(child, parent);
}
} | java | private void fireResultAdded(Result child, Result parent) {
if(LOG.isDebugging()) {
LOG.debug("Result added: " + child + " <- " + parent);
}
for(int i = listenerList.size(); --i >= 0;) {
listenerList.get(i).resultAdded(child, parent);
}
} | [
"private",
"void",
"fireResultAdded",
"(",
"Result",
"child",
",",
"Result",
"parent",
")",
"{",
"if",
"(",
"LOG",
".",
"isDebugging",
"(",
")",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Result added: \"",
"+",
"child",
"+",
"\" <- \"",
"+",
"parent",
")",
... | Informs all registered {@link ResultListener} that a new result was added.
@param child New child result added
@param parent Parent result that was added to | [
"Informs",
"all",
"registered",
"{",
"@link",
"ResultListener",
"}",
"that",
"a",
"new",
"result",
"was",
"added",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-api/src/main/java/de/lmu/ifi/dbs/elki/result/ResultHierarchy.java#L116-L123 |
flow/commons | src/main/java/com/flowpowered/commons/ViewFrustum.java | ViewFrustum.intersectsCuboid | public boolean intersectsCuboid(Vector3f[] vertices, Vector3f position) {
return intersectsCuboid(vertices, position.getX(), position.getY(), position.getZ());
} | java | public boolean intersectsCuboid(Vector3f[] vertices, Vector3f position) {
return intersectsCuboid(vertices, position.getX(), position.getY(), position.getZ());
} | [
"public",
"boolean",
"intersectsCuboid",
"(",
"Vector3f",
"[",
"]",
"vertices",
",",
"Vector3f",
"position",
")",
"{",
"return",
"intersectsCuboid",
"(",
"vertices",
",",
"position",
".",
"getX",
"(",
")",
",",
"position",
".",
"getY",
"(",
")",
",",
"posi... | Checks if the frustum of this camera intersects the given cuboid vertices.
@param vertices The cuboid local vertices to check the frustum against
@param position The position of the cuboid
@return Whether or not the frustum intersects the cuboid | [
"Checks",
"if",
"the",
"frustum",
"of",
"this",
"camera",
"intersects",
"the",
"given",
"cuboid",
"vertices",
"."
] | train | https://github.com/flow/commons/blob/0690efdac06fd728fcd7e9cf10f2b1319379c45b/src/main/java/com/flowpowered/commons/ViewFrustum.java#L227-L229 |
paypal/SeLion | dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ReflectionUtils.java | ReflectionUtils.instantiateWrapperObject | public static Object instantiateWrapperObject(Class<?> type, Object objectToInvokeUpon, String valueToAssign) {
logger.entering(new Object[] { type, objectToInvokeUpon, valueToAssign });
validateParams(type, objectToInvokeUpon, valueToAssign);
checkArgument(ClassUtils.isPrimitiveWrapper(type), type.getName() + " is NOT a wrapper data type.");
try {
Object objectToReturn = type.getConstructor(new Class<?>[] { String.class }).newInstance(valueToAssign);
logger.exiting(objectToInvokeUpon);
return objectToReturn;
} catch (InstantiationException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new ReflectionException(e);
}
} | java | public static Object instantiateWrapperObject(Class<?> type, Object objectToInvokeUpon, String valueToAssign) {
logger.entering(new Object[] { type, objectToInvokeUpon, valueToAssign });
validateParams(type, objectToInvokeUpon, valueToAssign);
checkArgument(ClassUtils.isPrimitiveWrapper(type), type.getName() + " is NOT a wrapper data type.");
try {
Object objectToReturn = type.getConstructor(new Class<?>[] { String.class }).newInstance(valueToAssign);
logger.exiting(objectToInvokeUpon);
return objectToReturn;
} catch (InstantiationException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException e) {
throw new ReflectionException(e);
}
} | [
"public",
"static",
"Object",
"instantiateWrapperObject",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Object",
"objectToInvokeUpon",
",",
"String",
"valueToAssign",
")",
"{",
"logger",
".",
"entering",
"(",
"new",
"Object",
"[",
"]",
"{",
"type",
",",
"object... | This helper method facilitates creation of Wrapper data type object and initialize it with the provided value.
@param type
The type to instantiate. It has to be only a Wrapper data type [ such as Integer, Float, Boolean
etc.,]
@param objectToInvokeUpon
The object upon which the invocation is to be carried out.
@param valueToAssign
The value to initialize with.
@return An initialized object that represents the Wrapper data type. | [
"This",
"helper",
"method",
"facilitates",
"creation",
"of",
"Wrapper",
"data",
"type",
"object",
"and",
"initialize",
"it",
"with",
"the",
"provided",
"value",
"."
] | train | https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/dataproviders/src/main/java/com/paypal/selion/platform/dataprovider/impl/ReflectionUtils.java#L254-L268 |
dnsjava/dnsjava | org/xbill/DNS/Cache.java | Cache.findAnyRecords | public RRset []
findAnyRecords(Name name, int type) {
return findRecords(name, type, Credibility.GLUE);
} | java | public RRset []
findAnyRecords(Name name, int type) {
return findRecords(name, type, Credibility.GLUE);
} | [
"public",
"RRset",
"[",
"]",
"findAnyRecords",
"(",
"Name",
"name",
",",
"int",
"type",
")",
"{",
"return",
"findRecords",
"(",
"name",
",",
"type",
",",
"Credibility",
".",
"GLUE",
")",
";",
"}"
] | Looks up Records in the Cache (a wrapper around lookupRecords). Unlike
lookupRecords, this given no indication of why failure occurred.
@param name The name to look up
@param type The type to look up
@return An array of RRsets, or null
@see Credibility | [
"Looks",
"up",
"Records",
"in",
"the",
"Cache",
"(",
"a",
"wrapper",
"around",
"lookupRecords",
")",
".",
"Unlike",
"lookupRecords",
"this",
"given",
"no",
"indication",
"of",
"why",
"failure",
"occurred",
"."
] | train | https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/Cache.java#L546-L549 |
openengsb/openengsb | api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java | TransformationDescription.lengthField | public void lengthField(String sourceField, String targetField, String function) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceField);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.LENGTH_FUNCTION_PARAM, function);
step.setOperationName("length");
steps.add(step);
} | java | public void lengthField(String sourceField, String targetField, String function) {
TransformationStep step = new TransformationStep();
step.setSourceFields(sourceField);
step.setTargetField(targetField);
step.setOperationParameter(TransformationConstants.LENGTH_FUNCTION_PARAM, function);
step.setOperationName("length");
steps.add(step);
} | [
"public",
"void",
"lengthField",
"(",
"String",
"sourceField",
",",
"String",
"targetField",
",",
"String",
"function",
")",
"{",
"TransformationStep",
"step",
"=",
"new",
"TransformationStep",
"(",
")",
";",
"step",
".",
"setSourceFields",
"(",
"sourceField",
"... | Adds a length step to the transformation description. The step takes the object from the source field and
calculate the length through the given method function (which needs to be implemented by the object). The result
will be written in the target field. If the function is null, then "length" will be taken as standard function. | [
"Adds",
"a",
"length",
"step",
"to",
"the",
"transformation",
"description",
".",
"The",
"step",
"takes",
"the",
"object",
"from",
"the",
"source",
"field",
"and",
"calculate",
"the",
"length",
"through",
"the",
"given",
"method",
"function",
"(",
"which",
"... | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/api/ekb/src/main/java/org/openengsb/core/ekb/api/transformation/TransformationDescription.java#L165-L172 |
apache/predictionio-sdk-java | client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java | EventClient.deleteItem | public String deleteItem(String iid, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
return createEvent(deleteItemAsFuture(iid, eventTime));
} | java | public String deleteItem(String iid, DateTime eventTime)
throws ExecutionException, InterruptedException, IOException {
return createEvent(deleteItemAsFuture(iid, eventTime));
} | [
"public",
"String",
"deleteItem",
"(",
"String",
"iid",
",",
"DateTime",
"eventTime",
")",
"throws",
"ExecutionException",
",",
"InterruptedException",
",",
"IOException",
"{",
"return",
"createEvent",
"(",
"deleteItemAsFuture",
"(",
"iid",
",",
"eventTime",
")",
... | Deletes a item.
@param iid ID of the item
@param eventTime timestamp of the event
@return ID of this event | [
"Deletes",
"a",
"item",
"."
] | train | https://github.com/apache/predictionio-sdk-java/blob/16052c96b136340c175c3f9c2692e720850df219/client/src/main/java/org/apache/predictionio/sdk/java/EventClient.java#L588-L591 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/revisions/RevisionUtils.java | RevisionUtils.getDiscussionArchiveRevisionsForArticleRevision | public List<Revision> getDiscussionArchiveRevisionsForArticleRevision(int revisionId) throws WikiApiException, WikiPageNotFoundException{
List<Revision> result = new LinkedList<Revision>();
//get article revision
Revision rev = revApi.getRevision(revisionId);
Timestamp revTime = rev.getTimeStamp();
//get corresponding discussion archives
Iterable<Page> discArchives = wiki.getDiscussionArchives(rev.getArticleID());
/*
* for each discussion archive, find correct revision of discussion page
*/
for(Page discArchive:discArchives){
//get revision timestamps for the current discussion archive
List<Timestamp> discussionTs = revApi.getRevisionTimestamps(discArchive.getPageId());
// sort in reverse order - newest first
Collections.sort(discussionTs, new Comparator<Timestamp>()
{
public int compare(Timestamp ts1, Timestamp ts2)
{
return ts2.compareTo(ts1);
}
});
//find first timestamp equal to or before the article revision timestamp
for(Timestamp curDiscTime:discussionTs){
if(curDiscTime==revTime||curDiscTime.before(revTime)){
result.add(revApi.getRevision(discArchive.getPageId(), curDiscTime));
break;
}
}
}
return result;
} | java | public List<Revision> getDiscussionArchiveRevisionsForArticleRevision(int revisionId) throws WikiApiException, WikiPageNotFoundException{
List<Revision> result = new LinkedList<Revision>();
//get article revision
Revision rev = revApi.getRevision(revisionId);
Timestamp revTime = rev.getTimeStamp();
//get corresponding discussion archives
Iterable<Page> discArchives = wiki.getDiscussionArchives(rev.getArticleID());
/*
* for each discussion archive, find correct revision of discussion page
*/
for(Page discArchive:discArchives){
//get revision timestamps for the current discussion archive
List<Timestamp> discussionTs = revApi.getRevisionTimestamps(discArchive.getPageId());
// sort in reverse order - newest first
Collections.sort(discussionTs, new Comparator<Timestamp>()
{
public int compare(Timestamp ts1, Timestamp ts2)
{
return ts2.compareTo(ts1);
}
});
//find first timestamp equal to or before the article revision timestamp
for(Timestamp curDiscTime:discussionTs){
if(curDiscTime==revTime||curDiscTime.before(revTime)){
result.add(revApi.getRevision(discArchive.getPageId(), curDiscTime));
break;
}
}
}
return result;
} | [
"public",
"List",
"<",
"Revision",
">",
"getDiscussionArchiveRevisionsForArticleRevision",
"(",
"int",
"revisionId",
")",
"throws",
"WikiApiException",
",",
"WikiPageNotFoundException",
"{",
"List",
"<",
"Revision",
">",
"result",
"=",
"new",
"LinkedList",
"<",
"Revis... | For a given article revision, the method returns the revisions of the archived article discussion
pages which were available at the time of the article revision
@param revisionId revision of the article for which the talk page archive revisions should be retrieved
@return the revisions of the talk page archives that were available at the time of the article revision | [
"For",
"a",
"given",
"article",
"revision",
"the",
"method",
"returns",
"the",
"revisions",
"of",
"the",
"archived",
"article",
"discussion",
"pages",
"which",
"were",
"available",
"at",
"the",
"time",
"of",
"the",
"article",
"revision"
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.util/src/main/java/de/tudarmstadt/ukp/wikipedia/util/revisions/RevisionUtils.java#L104-L140 |
google/allocation-instrumenter | src/main/java/com/google/monitoring/runtime/instrumentation/AllocationMethodAdapter.java | AllocationMethodAdapter.visitIntInsn | @Override
public void visitIntInsn(int opcode, int operand) {
if (opcode == Opcodes.NEWARRAY) {
// instack: ... count
// outstack: ... aref
if (operand >= 4 && operand <= 11) {
super.visitInsn(Opcodes.DUP); // -> stack: ... count count
super.visitIntInsn(opcode, operand); // -> stack: ... count aref
invokeRecordAllocation(primitiveTypeNames[operand]);
// -> stack: ... aref
} else {
logger.severe(
"NEWARRAY called with an invalid operand "
+ operand
+ ". Not instrumenting this allocation!");
super.visitIntInsn(opcode, operand);
}
} else {
super.visitIntInsn(opcode, operand);
}
} | java | @Override
public void visitIntInsn(int opcode, int operand) {
if (opcode == Opcodes.NEWARRAY) {
// instack: ... count
// outstack: ... aref
if (operand >= 4 && operand <= 11) {
super.visitInsn(Opcodes.DUP); // -> stack: ... count count
super.visitIntInsn(opcode, operand); // -> stack: ... count aref
invokeRecordAllocation(primitiveTypeNames[operand]);
// -> stack: ... aref
} else {
logger.severe(
"NEWARRAY called with an invalid operand "
+ operand
+ ". Not instrumenting this allocation!");
super.visitIntInsn(opcode, operand);
}
} else {
super.visitIntInsn(opcode, operand);
}
} | [
"@",
"Override",
"public",
"void",
"visitIntInsn",
"(",
"int",
"opcode",
",",
"int",
"operand",
")",
"{",
"if",
"(",
"opcode",
"==",
"Opcodes",
".",
"NEWARRAY",
")",
"{",
"// instack: ... count",
"// outstack: ... aref",
"if",
"(",
"operand",
">=",
"4",
"&&"... | newarray shows up as an instruction taking an int operand (the primitive element type of the
array) so we hook it here. | [
"newarray",
"shows",
"up",
"as",
"an",
"instruction",
"taking",
"an",
"int",
"operand",
"(",
"the",
"primitive",
"element",
"type",
"of",
"the",
"array",
")",
"so",
"we",
"hook",
"it",
"here",
"."
] | train | https://github.com/google/allocation-instrumenter/blob/58d8473e8832e51f39ae7aa38328f61c4b747bff/src/main/java/com/google/monitoring/runtime/instrumentation/AllocationMethodAdapter.java#L122-L142 |
greatman/craftconomy3 | src/main/java/com/greatmancode/craftconomy3/Common.java | Common.sendConsoleMessage | public void sendConsoleMessage(Level level, String msg) {
if (!(getServerCaller() instanceof UnitTestServerCaller)) {
getLogger().log(level, msg);
}
} | java | public void sendConsoleMessage(Level level, String msg) {
if (!(getServerCaller() instanceof UnitTestServerCaller)) {
getLogger().log(level, msg);
}
} | [
"public",
"void",
"sendConsoleMessage",
"(",
"Level",
"level",
",",
"String",
"msg",
")",
"{",
"if",
"(",
"!",
"(",
"getServerCaller",
"(",
")",
"instanceof",
"UnitTestServerCaller",
")",
")",
"{",
"getLogger",
"(",
")",
".",
"log",
"(",
"level",
",",
"m... | Sends a message to the console through the Logge.r
@param level The log level to show.
@param msg The message to send. | [
"Sends",
"a",
"message",
"to",
"the",
"console",
"through",
"the",
"Logge",
".",
"r"
] | train | https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/Common.java#L245-L249 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/ReferenceField.java | ReferenceField.setReference | public int setReference(Record record, boolean bDisplayOption, int iMoveMode)
{
return this.moveFieldToThis((BaseField)record.getCounterField(), bDisplayOption, iMoveMode);
} | java | public int setReference(Record record, boolean bDisplayOption, int iMoveMode)
{
return this.moveFieldToThis((BaseField)record.getCounterField(), bDisplayOption, iMoveMode);
} | [
"public",
"int",
"setReference",
"(",
"Record",
"record",
",",
"boolean",
"bDisplayOption",
",",
"int",
"iMoveMode",
")",
"{",
"return",
"this",
".",
"moveFieldToThis",
"(",
"(",
"BaseField",
")",
"record",
".",
"getCounterField",
"(",
")",
",",
"bDisplayOptio... | Make this field a reference to the current object in this record info class.
@param record tour.db.Record The current record to set this field to reference.
@param bDisplayOption If true, display changes.
@param iMoveMode The move mode.
@return The error code (or NORMAL_RETURN). | [
"Make",
"this",
"field",
"a",
"reference",
"to",
"the",
"current",
"object",
"in",
"this",
"record",
"info",
"class",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/ReferenceField.java#L167-L170 |
cdapio/tephra | tephra-core/src/main/java/co/cask/tephra/visibility/VisibilityFence.java | VisibilityFence.prepareWait | public static FenceWait prepareWait(byte[] fenceId, TransactionSystemClient txClient)
throws TransactionFailureException, InterruptedException, TimeoutException {
return new DefaultFenceWait(new TransactionContext(txClient, new WriteFence(fenceId)));
} | java | public static FenceWait prepareWait(byte[] fenceId, TransactionSystemClient txClient)
throws TransactionFailureException, InterruptedException, TimeoutException {
return new DefaultFenceWait(new TransactionContext(txClient, new WriteFence(fenceId)));
} | [
"public",
"static",
"FenceWait",
"prepareWait",
"(",
"byte",
"[",
"]",
"fenceId",
",",
"TransactionSystemClient",
"txClient",
")",
"throws",
"TransactionFailureException",
",",
"InterruptedException",
",",
"TimeoutException",
"{",
"return",
"new",
"DefaultFenceWait",
"(... | Used by a writer to wait on a fence so that changes are visible to all readers with in-progress transactions.
@param fenceId uniquely identifies the data that this fence is used to synchronize.
If the data is a table cell then this id can be composed of the table name, row key
and column key for the data.
@return {@link FenceWait} object | [
"Used",
"by",
"a",
"writer",
"to",
"wait",
"on",
"a",
"fence",
"so",
"that",
"changes",
"are",
"visible",
"to",
"all",
"readers",
"with",
"in",
"-",
"progress",
"transactions",
"."
] | train | https://github.com/cdapio/tephra/blob/082c56c15c6ece15002631ff6f89206a00d8915c/tephra-core/src/main/java/co/cask/tephra/visibility/VisibilityFence.java#L134-L137 |
lagom/lagom | service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java | Descriptor.withPathParamSerializer | public <T> Descriptor withPathParamSerializer(Class<T> pathParamType, PathParamSerializer<T> pathParamSerializer) {
return withPathParamSerializer((Type) pathParamType, pathParamSerializer);
} | java | public <T> Descriptor withPathParamSerializer(Class<T> pathParamType, PathParamSerializer<T> pathParamSerializer) {
return withPathParamSerializer((Type) pathParamType, pathParamSerializer);
} | [
"public",
"<",
"T",
">",
"Descriptor",
"withPathParamSerializer",
"(",
"Class",
"<",
"T",
">",
"pathParamType",
",",
"PathParamSerializer",
"<",
"T",
">",
"pathParamSerializer",
")",
"{",
"return",
"withPathParamSerializer",
"(",
"(",
"Type",
")",
"pathParamType",... | Provide a custom path param serializer for the given path param type.
@param pathParamType The path param type.
@param pathParamSerializer The path param serializer.
@return A copy of this descriptor. | [
"Provide",
"a",
"custom",
"path",
"param",
"serializer",
"for",
"the",
"given",
"path",
"param",
"type",
"."
] | train | https://github.com/lagom/lagom/blob/3763055a9d1aace793a5d970f4e688aea61b1a5a/service/javadsl/api/src/main/java/com/lightbend/lagom/javadsl/api/Descriptor.java#L667-L669 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java | PathUtils.compareWithoutSchemeAndAuthority | public static boolean compareWithoutSchemeAndAuthority(Path path1, Path path2) {
return PathUtils.getPathWithoutSchemeAndAuthority(path1).equals(getPathWithoutSchemeAndAuthority(path2));
} | java | public static boolean compareWithoutSchemeAndAuthority(Path path1, Path path2) {
return PathUtils.getPathWithoutSchemeAndAuthority(path1).equals(getPathWithoutSchemeAndAuthority(path2));
} | [
"public",
"static",
"boolean",
"compareWithoutSchemeAndAuthority",
"(",
"Path",
"path1",
",",
"Path",
"path2",
")",
"{",
"return",
"PathUtils",
".",
"getPathWithoutSchemeAndAuthority",
"(",
"path1",
")",
".",
"equals",
"(",
"getPathWithoutSchemeAndAuthority",
"(",
"pa... | Compare two path without shedme and authority (the prefix)
@param path1
@param path2
@return | [
"Compare",
"two",
"path",
"without",
"shedme",
"and",
"authority",
"(",
"the",
"prefix",
")"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/PathUtils.java#L208-L210 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/v2/ConfigClient.java | ConfigClient.createSink | public final LogSink createSink(ParentName parent, LogSink sink) {
CreateSinkRequest request =
CreateSinkRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setSink(sink)
.build();
return createSink(request);
} | java | public final LogSink createSink(ParentName parent, LogSink sink) {
CreateSinkRequest request =
CreateSinkRequest.newBuilder()
.setParent(parent == null ? null : parent.toString())
.setSink(sink)
.build();
return createSink(request);
} | [
"public",
"final",
"LogSink",
"createSink",
"(",
"ParentName",
"parent",
",",
"LogSink",
"sink",
")",
"{",
"CreateSinkRequest",
"request",
"=",
"CreateSinkRequest",
".",
"newBuilder",
"(",
")",
".",
"setParent",
"(",
"parent",
"==",
"null",
"?",
"null",
":",
... | Creates a sink that exports specified log entries to a destination. The export of
newly-ingested log entries begins immediately, unless the sink's `writer_identity` is not
permitted to write to the destination. A sink can export log entries only from the resource
owning the sink.
<p>Sample code:
<pre><code>
try (ConfigClient configClient = ConfigClient.create()) {
ParentName parent = ProjectName.of("[PROJECT]");
LogSink sink = LogSink.newBuilder().build();
LogSink response = configClient.createSink(parent, sink);
}
</code></pre>
@param parent Required. The resource in which to create the sink:
<p>"projects/[PROJECT_ID]" "organizations/[ORGANIZATION_ID]"
"billingAccounts/[BILLING_ACCOUNT_ID]" "folders/[FOLDER_ID]"
<p>Examples: `"projects/my-logging-project"`, `"organizations/123456789"`.
@param sink Required. The new sink, whose `name` parameter is a sink identifier that is not
already in use.
@throws com.google.api.gax.rpc.ApiException if the remote call fails | [
"Creates",
"a",
"sink",
"that",
"exports",
"specified",
"log",
"entries",
"to",
"a",
"destination",
".",
"The",
"export",
"of",
"newly",
"-",
"ingested",
"log",
"entries",
"begins",
"immediately",
"unless",
"the",
"sink",
"s",
"writer_identity",
"is",
"not",
... | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-logging/src/main/java/com/google/cloud/logging/v2/ConfigClient.java#L431-L439 |
DDTH/ddth-commons | ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java | SerializationUtils.fromJson | public static <T> T fromJson(JsonNode json, Class<T> clazz, ClassLoader classLoader) {
if (json == null) {
return null;
}
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
Thread.currentThread().setContextClassLoader(classLoader);
}
try {
ObjectMapper mapper = poolMapper.borrowObject();
if (mapper != null) {
try {
return mapper.readValue(json.toString(), clazz);
} finally {
poolMapper.returnObject(mapper);
}
}
throw new DeserializationException("No ObjectMapper instance avaialble!");
} catch (Exception e) {
throw e instanceof DeserializationException ? (DeserializationException) e
: new DeserializationException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
} | java | public static <T> T fromJson(JsonNode json, Class<T> clazz, ClassLoader classLoader) {
if (json == null) {
return null;
}
ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
if (classLoader != null) {
Thread.currentThread().setContextClassLoader(classLoader);
}
try {
ObjectMapper mapper = poolMapper.borrowObject();
if (mapper != null) {
try {
return mapper.readValue(json.toString(), clazz);
} finally {
poolMapper.returnObject(mapper);
}
}
throw new DeserializationException("No ObjectMapper instance avaialble!");
} catch (Exception e) {
throw e instanceof DeserializationException ? (DeserializationException) e
: new DeserializationException(e);
} finally {
Thread.currentThread().setContextClassLoader(oldClassLoader);
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"fromJson",
"(",
"JsonNode",
"json",
",",
"Class",
"<",
"T",
">",
"clazz",
",",
"ClassLoader",
"classLoader",
")",
"{",
"if",
"(",
"json",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"ClassLoader",
"old... | Deserialize a {@link JsonNode}, with custom class loader.
@param json
@param clazz
@return
@since 0.6.2 | [
"Deserialize",
"a",
"{",
"@link",
"JsonNode",
"}",
"with",
"custom",
"class",
"loader",
"."
] | train | https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L726-L750 |
graknlabs/grakn | server/src/graql/executor/ComputeExecutor.java | ComputeExecutor.runComputeDegree | private Stream<ConceptSetMeasure> runComputeDegree(GraqlCompute.Centrality query) {
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
ComputerResult computerResult = compute(new DegreeVertexProgram(targetTypeLabelIDs),
new DegreeDistributionMapReduce(targetTypeLabelIDs, DegreeVertexProgram.DEGREE),
scopeTypeLabelIDs);
Map<Long, Set<ConceptId>> centralityMap = computerResult.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | java | private Stream<ConceptSetMeasure> runComputeDegree(GraqlCompute.Centrality query) {
Set<Label> targetTypeLabels;
// Check if ofType is valid before returning emptyMap
if (query.of().isEmpty()) {
targetTypeLabels = scopeTypeLabels(query);
} else {
targetTypeLabels = query.of().stream()
.flatMap(t -> {
Label typeLabel = Label.of(t);
Type type = tx.getSchemaConcept(typeLabel);
if (type == null) throw GraqlQueryException.labelNotFound(typeLabel);
return type.subs();
})
.map(SchemaConcept::label)
.collect(toSet());
}
Set<Label> scopeTypeLabels = Sets.union(scopeTypeLabels(query), targetTypeLabels);
if (!scopeContainsInstance(query)) {
return Stream.empty();
}
Set<LabelId> scopeTypeLabelIDs = convertLabelsToIds(scopeTypeLabels);
Set<LabelId> targetTypeLabelIDs = convertLabelsToIds(targetTypeLabels);
ComputerResult computerResult = compute(new DegreeVertexProgram(targetTypeLabelIDs),
new DegreeDistributionMapReduce(targetTypeLabelIDs, DegreeVertexProgram.DEGREE),
scopeTypeLabelIDs);
Map<Long, Set<ConceptId>> centralityMap = computerResult.memory().get(DegreeDistributionMapReduce.class.getName());
return centralityMap.entrySet().stream()
.map(centrality -> new ConceptSetMeasure(centrality.getValue(), centrality.getKey()));
} | [
"private",
"Stream",
"<",
"ConceptSetMeasure",
">",
"runComputeDegree",
"(",
"GraqlCompute",
".",
"Centrality",
"query",
")",
"{",
"Set",
"<",
"Label",
">",
"targetTypeLabels",
";",
"// Check if ofType is valid before returning emptyMap",
"if",
"(",
"query",
".",
"of"... | The Graql compute centrality using degree query run method
@return a Answer containing the centrality count map | [
"The",
"Graql",
"compute",
"centrality",
"using",
"degree",
"query",
"run",
"method"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/executor/ComputeExecutor.java#L381-L416 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/dateTimePicker/DateTimePickerRenderer.java | DateTimePickerRenderer.getDateAsString | public static String getDateAsString(FacesContext fc, DateTimePicker dtp, Object value, String javaFormatString, Locale locale) {
if (value == null) {
return null;
}
Converter converter = dtp.getConverter();
return converter == null ?
getInternalDateAsString(value, javaFormatString, locale)
:
converter.getAsString(fc, dtp, value);
} | java | public static String getDateAsString(FacesContext fc, DateTimePicker dtp, Object value, String javaFormatString, Locale locale) {
if (value == null) {
return null;
}
Converter converter = dtp.getConverter();
return converter == null ?
getInternalDateAsString(value, javaFormatString, locale)
:
converter.getAsString(fc, dtp, value);
} | [
"public",
"static",
"String",
"getDateAsString",
"(",
"FacesContext",
"fc",
",",
"DateTimePicker",
"dtp",
",",
"Object",
"value",
",",
"String",
"javaFormatString",
",",
"Locale",
"locale",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"nul... | Get date in string format
@param fc The FacesContext
@param dtp the DateTimePicker component
@param value The date to display
@param javaFormatString The format string as defined by the SimpleDateFormat syntax
@param locale The locale
@return null if the value is null. | [
"Get",
"date",
"in",
"string",
"format"
] | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/dateTimePicker/DateTimePickerRenderer.java#L106-L117 |
tvesalainen/util | util/src/main/java/org/vesalainen/ui/LineDrawer.java | LineDrawer.fillWidth | public static void fillWidth(double x0, double y0, double derivateX, double derivateY, double width, PlotOperator plot)
{
double halfWidth = width/2.0;
if (Math.abs(derivateY) <= Double.MIN_VALUE)
{
drawLine((int)(x0), (int)(y0+halfWidth), (int)(x0), (int)(y0-halfWidth), plot);
}
else
{
double s = derivateX/-derivateY;
double w2 = halfWidth*halfWidth;
double x1 = Math.sqrt(w2/(s*s+1));
double y1 = s*x1;
drawLine((int)(x0+x1), (int)(y0+y1), (int)(x0-x1), (int)(y0-y1), plot);
}
} | java | public static void fillWidth(double x0, double y0, double derivateX, double derivateY, double width, PlotOperator plot)
{
double halfWidth = width/2.0;
if (Math.abs(derivateY) <= Double.MIN_VALUE)
{
drawLine((int)(x0), (int)(y0+halfWidth), (int)(x0), (int)(y0-halfWidth), plot);
}
else
{
double s = derivateX/-derivateY;
double w2 = halfWidth*halfWidth;
double x1 = Math.sqrt(w2/(s*s+1));
double y1 = s*x1;
drawLine((int)(x0+x1), (int)(y0+y1), (int)(x0-x1), (int)(y0-y1), plot);
}
} | [
"public",
"static",
"void",
"fillWidth",
"(",
"double",
"x0",
",",
"double",
"y0",
",",
"double",
"derivateX",
",",
"double",
"derivateY",
",",
"double",
"width",
",",
"PlotOperator",
"plot",
")",
"{",
"double",
"halfWidth",
"=",
"width",
"/",
"2.0",
";",
... | Draws orthogonal to derivate width length line having center at (x0, y0).
@param x0
@param y0
@param derivateX
@param derivateY
@param width
@param plot | [
"Draws",
"orthogonal",
"to",
"derivate",
"width",
"length",
"line",
"having",
"center",
"at",
"(",
"x0",
"y0",
")",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/ui/LineDrawer.java#L48-L63 |
jMetal/jMetal | jmetal-core/src/main/java/org/uma/jmetal/solution/util/RepairDoubleSolutionAtBounds.java | RepairDoubleSolutionAtBounds.repairSolutionVariableValue | public double repairSolutionVariableValue(double value, double lowerBound, double upperBound) {
if (lowerBound > upperBound) {
throw new JMetalException("The lower bound (" + lowerBound + ") is greater than the "
+ "upper bound (" + upperBound+")") ;
}
double result = value ;
if (value < lowerBound) {
result = lowerBound ;
}
if (value > upperBound) {
result = upperBound ;
}
return result ;
} | java | public double repairSolutionVariableValue(double value, double lowerBound, double upperBound) {
if (lowerBound > upperBound) {
throw new JMetalException("The lower bound (" + lowerBound + ") is greater than the "
+ "upper bound (" + upperBound+")") ;
}
double result = value ;
if (value < lowerBound) {
result = lowerBound ;
}
if (value > upperBound) {
result = upperBound ;
}
return result ;
} | [
"public",
"double",
"repairSolutionVariableValue",
"(",
"double",
"value",
",",
"double",
"lowerBound",
",",
"double",
"upperBound",
")",
"{",
"if",
"(",
"lowerBound",
">",
"upperBound",
")",
"{",
"throw",
"new",
"JMetalException",
"(",
"\"The lower bound (\"",
"+... | Checks if the value is between its bounds; if not, the lower or upper bound is returned
@param value The value to be checked
@param lowerBound
@param upperBound
@return The same value if it is in the limits or a repaired value otherwise | [
"Checks",
"if",
"the",
"value",
"is",
"between",
"its",
"bounds",
";",
"if",
"not",
"the",
"lower",
"or",
"upper",
"bound",
"is",
"returned"
] | train | https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-core/src/main/java/org/uma/jmetal/solution/util/RepairDoubleSolutionAtBounds.java#L18-L33 |
knowm/XChart | xchart/src/main/java/org/knowm/xchart/OHLCChart.java | OHLCChart.addSeries | public OHLCSeries addSeries(
String seriesName,
List<? extends Number> openData,
List<? extends Number> highData,
List<? extends Number> lowData,
List<? extends Number> closeData) {
return addSeries(seriesName, null, openData, highData, lowData, closeData);
} | java | public OHLCSeries addSeries(
String seriesName,
List<? extends Number> openData,
List<? extends Number> highData,
List<? extends Number> lowData,
List<? extends Number> closeData) {
return addSeries(seriesName, null, openData, highData, lowData, closeData);
} | [
"public",
"OHLCSeries",
"addSeries",
"(",
"String",
"seriesName",
",",
"List",
"<",
"?",
"extends",
"Number",
">",
"openData",
",",
"List",
"<",
"?",
"extends",
"Number",
">",
"highData",
",",
"List",
"<",
"?",
"extends",
"Number",
">",
"lowData",
",",
"... | Add a series for a OHLC type chart using Lists
@param seriesName
@param openData the open data
@param highData the high data
@param lowData the low data
@param closeData the close data
@return A Series object that you can set properties on | [
"Add",
"a",
"series",
"for",
"a",
"OHLC",
"type",
"chart",
"using",
"Lists"
] | train | https://github.com/knowm/XChart/blob/677a105753a855edf24782fab1bf1f5aec3e642b/xchart/src/main/java/org/knowm/xchart/OHLCChart.java#L219-L227 |
ansell/restlet-utils | src/main/java/com/github/ansell/restletutils/RestletUtilSesameRealm.java | RestletUtilSesameRealm.buildRestletUserFromSparqlResult | protected RestletUtilUser buildRestletUserFromSparqlResult(final String userIdentifier, final BindingSet bindingSet)
{
// log.info("result={}", bindingSet);
String userEmail = bindingSet.getValue("userEmail").stringValue();
// TODO: When hashed, need to unhash here
char[] userSecret = null;
if(bindingSet.hasBinding("userSecret"))
{
userSecret = bindingSet.getValue("userSecret").stringValue().toCharArray();
}
String userFirstName = null;
if(bindingSet.hasBinding("userFirstName"))
{
userFirstName = bindingSet.getValue("userFirstName").stringValue();
}
String userLastName = null;
if(bindingSet.hasBinding("userLastName"))
{
userLastName = bindingSet.getValue("userLastName").stringValue();
}
return new RestletUtilUser(userIdentifier, userSecret, userFirstName, userLastName, userEmail);
} | java | protected RestletUtilUser buildRestletUserFromSparqlResult(final String userIdentifier, final BindingSet bindingSet)
{
// log.info("result={}", bindingSet);
String userEmail = bindingSet.getValue("userEmail").stringValue();
// TODO: When hashed, need to unhash here
char[] userSecret = null;
if(bindingSet.hasBinding("userSecret"))
{
userSecret = bindingSet.getValue("userSecret").stringValue().toCharArray();
}
String userFirstName = null;
if(bindingSet.hasBinding("userFirstName"))
{
userFirstName = bindingSet.getValue("userFirstName").stringValue();
}
String userLastName = null;
if(bindingSet.hasBinding("userLastName"))
{
userLastName = bindingSet.getValue("userLastName").stringValue();
}
return new RestletUtilUser(userIdentifier, userSecret, userFirstName, userLastName, userEmail);
} | [
"protected",
"RestletUtilUser",
"buildRestletUserFromSparqlResult",
"(",
"final",
"String",
"userIdentifier",
",",
"final",
"BindingSet",
"bindingSet",
")",
"{",
"// log.info(\"result={}\", bindingSet);",
"String",
"userEmail",
"=",
"bindingSet",
".",
"getValue",
"(",
"\"us... | Builds a RestletUtilUser from the data retrieved in a SPARQL result.
@param userIdentifier
The unique identifier of the User.
@param bindingSet
Results of a single user from SPARQL.
@return A RestletUtilUser account. | [
"Builds",
"a",
"RestletUtilUser",
"from",
"the",
"data",
"retrieved",
"in",
"a",
"SPARQL",
"result",
"."
] | train | https://github.com/ansell/restlet-utils/blob/6c39a3e91aa8295936af1dbfccd6ba27230c40a9/src/main/java/com/github/ansell/restletutils/RestletUtilSesameRealm.java#L596-L619 |
tango-controls/JTango | server/src/main/java/org/tango/server/servant/CommandGetter.java | CommandGetter.getCommand | public static CommandImpl getCommand(final String name, final List<CommandImpl> commandList) throws DevFailed {
CommandImpl result = null;
for (final CommandImpl command : commandList) {
if (command.getName().equalsIgnoreCase(name)) {
result = command;
break;
}
}
if (result == null) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.COMMAND_NOT_FOUND, "Command " + name + " not found");
}
return result;
} | java | public static CommandImpl getCommand(final String name, final List<CommandImpl> commandList) throws DevFailed {
CommandImpl result = null;
for (final CommandImpl command : commandList) {
if (command.getName().equalsIgnoreCase(name)) {
result = command;
break;
}
}
if (result == null) {
throw DevFailedUtils.newDevFailed(ExceptionMessages.COMMAND_NOT_FOUND, "Command " + name + " not found");
}
return result;
} | [
"public",
"static",
"CommandImpl",
"getCommand",
"(",
"final",
"String",
"name",
",",
"final",
"List",
"<",
"CommandImpl",
">",
"commandList",
")",
"throws",
"DevFailed",
"{",
"CommandImpl",
"result",
"=",
"null",
";",
"for",
"(",
"final",
"CommandImpl",
"comm... | Get a command
@param name
@return The command
@throws DevFailed | [
"Get",
"a",
"command"
] | train | https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/CommandGetter.java#L44-L56 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamUtils.java | StreamUtils.dirToTarArchiveOutputStreamRecursive | private static void dirToTarArchiveOutputStreamRecursive(FileStatus dirFileStatus, FileSystem fs,
Optional<Path> destDir, TarArchiveOutputStream tarArchiveOutputStream) throws IOException {
Preconditions.checkState(fs.isDirectory(dirFileStatus.getPath()));
Path dir = destDir.isPresent() ? new Path(destDir.get(), dirFileStatus.getPath().getName())
: new Path(dirFileStatus.getPath().getName());
dirToTarArchiveOutputStream(dir, tarArchiveOutputStream);
for (FileStatus childFileStatus : fs.listStatus(dirFileStatus.getPath())) {
Path childFile = new Path(dir, childFileStatus.getPath().getName());
if (fs.isDirectory(childFileStatus.getPath())) {
dirToTarArchiveOutputStreamRecursive(childFileStatus, fs, Optional.of(childFile), tarArchiveOutputStream);
} else {
try (FSDataInputStream fsDataInputStream = fs.open(childFileStatus.getPath())) {
fileToTarArchiveOutputStream(childFileStatus, fsDataInputStream, childFile, tarArchiveOutputStream);
}
}
}
} | java | private static void dirToTarArchiveOutputStreamRecursive(FileStatus dirFileStatus, FileSystem fs,
Optional<Path> destDir, TarArchiveOutputStream tarArchiveOutputStream) throws IOException {
Preconditions.checkState(fs.isDirectory(dirFileStatus.getPath()));
Path dir = destDir.isPresent() ? new Path(destDir.get(), dirFileStatus.getPath().getName())
: new Path(dirFileStatus.getPath().getName());
dirToTarArchiveOutputStream(dir, tarArchiveOutputStream);
for (FileStatus childFileStatus : fs.listStatus(dirFileStatus.getPath())) {
Path childFile = new Path(dir, childFileStatus.getPath().getName());
if (fs.isDirectory(childFileStatus.getPath())) {
dirToTarArchiveOutputStreamRecursive(childFileStatus, fs, Optional.of(childFile), tarArchiveOutputStream);
} else {
try (FSDataInputStream fsDataInputStream = fs.open(childFileStatus.getPath())) {
fileToTarArchiveOutputStream(childFileStatus, fsDataInputStream, childFile, tarArchiveOutputStream);
}
}
}
} | [
"private",
"static",
"void",
"dirToTarArchiveOutputStreamRecursive",
"(",
"FileStatus",
"dirFileStatus",
",",
"FileSystem",
"fs",
",",
"Optional",
"<",
"Path",
">",
"destDir",
",",
"TarArchiveOutputStream",
"tarArchiveOutputStream",
")",
"throws",
"IOException",
"{",
"P... | Helper method for {@link #tar(FileSystem, FileSystem, Path, Path)} that recursively adds a directory to a given
{@link TarArchiveOutputStream}. | [
"Helper",
"method",
"for",
"{"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/io/StreamUtils.java#L131-L151 |
Coveros/selenified | src/main/java/com/coveros/selenified/element/Element.java | Element.scrollTo | public void scrollTo() {
String action = "Scrolling screen to " + prettyOutput();
String expected = prettyOutputStart() + " is now within the current viewport";
try {
// wait for element to be present
if (isNotPresent(action, expected, CANT_SCROLL)) {
return;
}
// perform the move action
WebElement webElement = getWebElement();
Actions builder = new Actions(driver);
builder.moveToElement(webElement);
} catch (Exception e) {
cantScroll(e, action, expected);
return;
}
isScrolledTo(action, expected);
} | java | public void scrollTo() {
String action = "Scrolling screen to " + prettyOutput();
String expected = prettyOutputStart() + " is now within the current viewport";
try {
// wait for element to be present
if (isNotPresent(action, expected, CANT_SCROLL)) {
return;
}
// perform the move action
WebElement webElement = getWebElement();
Actions builder = new Actions(driver);
builder.moveToElement(webElement);
} catch (Exception e) {
cantScroll(e, action, expected);
return;
}
isScrolledTo(action, expected);
} | [
"public",
"void",
"scrollTo",
"(",
")",
"{",
"String",
"action",
"=",
"\"Scrolling screen to \"",
"+",
"prettyOutput",
"(",
")",
";",
"String",
"expected",
"=",
"prettyOutputStart",
"(",
")",
"+",
"\" is now within the current viewport\"",
";",
"try",
"{",
"// wai... | Scrolls the page to the element, making it displayed on the current
viewport, but only if the element is present. If that condition is not
met, the scroll action will be logged, but skipped and the test will
continue. | [
"Scrolls",
"the",
"page",
"to",
"the",
"element",
"making",
"it",
"displayed",
"on",
"the",
"current",
"viewport",
"but",
"only",
"if",
"the",
"element",
"is",
"present",
".",
"If",
"that",
"condition",
"is",
"not",
"met",
"the",
"scroll",
"action",
"will"... | train | https://github.com/Coveros/selenified/blob/396cc1f010dd69eed33cc5061c41253de246a4cd/src/main/java/com/coveros/selenified/element/Element.java#L1132-L1149 |
cwilper/fcrepo-misc | fcrepo-dto/fcrepo-dto-core/src/main/java/com/github/cwilper/fcrepo/dto/core/io/XMLUtil.java | XMLUtil.prettyPrint | public static byte[] prettyPrint(byte[] inBytes,
boolean omitXMLDeclaration)
throws IOException {
ByteArrayOutputStream sink = new ByteArrayOutputStream();
prettyPrint(new ByteArrayInputStream(inBytes),
new OutputStreamWriter(sink, "UTF-8"), omitXMLDeclaration);
return sink.toByteArray();
} | java | public static byte[] prettyPrint(byte[] inBytes,
boolean omitXMLDeclaration)
throws IOException {
ByteArrayOutputStream sink = new ByteArrayOutputStream();
prettyPrint(new ByteArrayInputStream(inBytes),
new OutputStreamWriter(sink, "UTF-8"), omitXMLDeclaration);
return sink.toByteArray();
} | [
"public",
"static",
"byte",
"[",
"]",
"prettyPrint",
"(",
"byte",
"[",
"]",
"inBytes",
",",
"boolean",
"omitXMLDeclaration",
")",
"throws",
"IOException",
"{",
"ByteArrayOutputStream",
"sink",
"=",
"new",
"ByteArrayOutputStream",
"(",
")",
";",
"prettyPrint",
"(... | Pretty-prints the given XML.
<p>
The input must be well-formed. The transformation has the following
effect:
<ul>
<li> Leading and trailing whitespace will be removed.</li>
<li> All processing instructions and doctype declarations will be
removed.</li>
<li> If Xalan is the currently active XML transformer (true by
default in Java 6), it will be reformatted to have two-space
indents. Otherwise, indenting behavior is undefined (it may or
may not be indented).</li>
<li> Attributes will use double-quotes around values.</li>
<li> All empty elements (e.g.
<code><element><element></code>) will be
collapsed (e.g. <code><element/></code></li>
</ul>
@param inBytes the xml to be pretty-printed.
@param omitXMLDeclaration whether to omit the xml declaration in the
output. If false, the output will not be directly embeddable in
other XML documents.
@return the pretty-printed XML as a UTF-8 encoded byte array.
@throws IOException | [
"Pretty",
"-",
"prints",
"the",
"given",
"XML",
".",
"<p",
">",
"The",
"input",
"must",
"be",
"well",
"-",
"formed",
".",
"The",
"transformation",
"has",
"the",
"following",
"effect",
":",
"<ul",
">",
"<li",
">",
"Leading",
"and",
"trailing",
"whitespace... | train | https://github.com/cwilper/fcrepo-misc/blob/3ed0e7025c5b1d4faaa373b699be229ed72465b6/fcrepo-dto/fcrepo-dto-core/src/main/java/com/github/cwilper/fcrepo/dto/core/io/XMLUtil.java#L98-L105 |
bramp/unsafe | unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java | UnsafeHelper.hexDump | public static void hexDump(PrintStream out, Object obj) {
// TODO Change this to use hexDumpAddress instead of toByteArray
byte[] bytes = toByteArray(obj);
hexDumpBytes(out, 0, bytes);
} | java | public static void hexDump(PrintStream out, Object obj) {
// TODO Change this to use hexDumpAddress instead of toByteArray
byte[] bytes = toByteArray(obj);
hexDumpBytes(out, 0, bytes);
} | [
"public",
"static",
"void",
"hexDump",
"(",
"PrintStream",
"out",
",",
"Object",
"obj",
")",
"{",
"// TODO Change this to use hexDumpAddress instead of toByteArray",
"byte",
"[",
"]",
"bytes",
"=",
"toByteArray",
"(",
"obj",
")",
";",
"hexDumpBytes",
"(",
"out",
"... | Prints out the object (including header, padding, and all fields) as hex.
<p>Some examples:
<p><pre>
/**
* Longs are always 8 byte aligned, so 4 bytes of padding
* 0x00000000: 01 00 00 00 00 00 00 00 9B 81 61 DF 00 00 00 00
* 0x00000010: EF CD AB 89 67 45 23 01
*/
static class Class8 {
long l = 0x0123456789ABCDEFL;
}
/**
* 0x00000000: 01 00 00 00 00 00 00 00 8A BF 62 DF 67 45 23 01
*/
static class Class4 {
int i = 0x01234567;
}
/**
* 0x00000000: 01 00 00 00 00 00 00 00 28 C0 62 DF 34 12 00 00
*/
static class Class2 {
short s = 0x01234;
}
/**
* 0x00000000: 01 00 00 00 00 00 00 00 E3 C0 62 DF 12 00 00 00
*/
static class Class1 {
byte b = 0x12;
}
/**
* 0x00000000: 01 00 00 00 00 00 00 00 96 C1 62 DF 12 00 00 00
* 0x00000010: EF CD AB 89 67 45 23 01
*/
static class ClassMixed18 {
byte b = 0x12;
long l = 0x0123456789ABCDEFL;
}
/**
* 0x00000000: 01 00 00 00 00 00 00 00 4C C2 62 DF 12 00 00 00
* 0x00000010: EF CD AB 89 67 45 23 01
*/
static class ClassMixed81 {
long l = 0x0123456789ABCDEFL;
byte b = 0x12;
}
public static void printMemoryLayout() {
UnsafeHelper.hexDump(System.out, new Class8());
UnsafeHelper.hexDump(System.out, new Class4());
UnsafeHelper.hexDump(System.out, new Class2());
UnsafeHelper.hexDump(System.out, new Class1());
UnsafeHelper.hexDump(System.out, new ClassMixed18());
UnsafeHelper.hexDump(System.out, new ClassMixed81());
}
</pre>
@param out PrintStream to print the hex to
@param obj The object to print | [
"Prints",
"out",
"the",
"object",
"(",
"including",
"header",
"padding",
"and",
"all",
"fields",
")",
"as",
"hex",
"."
] | train | https://github.com/bramp/unsafe/blob/805f54e2a8aee905003329556135b6c4059b4418/unsafe-helper/src/main/java/net/bramp/unsafe/UnsafeHelper.java#L354-L358 |
voostindie/sprox | src/main/java/nl/ulso/sprox/impl/ReflectionUtil.java | ReflectionUtil.resolveObjectClass | static Class resolveObjectClass(Type objectType) {
final Class type = PRIMITIVE_PARAMETER_TYPES.get(objectType);
if (type != null) {
return type;
}
if (isOptionalType(objectType)) {
return resolveObjectClass(extractTypeFromOptional(objectType));
}
try {
return (Class) objectType;
} catch (ClassCastException e) {
throw new IllegalStateException("Cannot resolve object class from type: " + objectType, e);
}
} | java | static Class resolveObjectClass(Type objectType) {
final Class type = PRIMITIVE_PARAMETER_TYPES.get(objectType);
if (type != null) {
return type;
}
if (isOptionalType(objectType)) {
return resolveObjectClass(extractTypeFromOptional(objectType));
}
try {
return (Class) objectType;
} catch (ClassCastException e) {
throw new IllegalStateException("Cannot resolve object class from type: " + objectType, e);
}
} | [
"static",
"Class",
"resolveObjectClass",
"(",
"Type",
"objectType",
")",
"{",
"final",
"Class",
"type",
"=",
"PRIMITIVE_PARAMETER_TYPES",
".",
"get",
"(",
"objectType",
")",
";",
"if",
"(",
"type",
"!=",
"null",
")",
"{",
"return",
"type",
";",
"}",
"if",
... | Resolves the {@link Class} that corresponds with a {@link Type}.
<p>
{@code Class} is an implementation of {@code Type} but, of course, not every {@code Type} is a {@code Class}.
Case in point here are primitive types. These can appear as method parameters.
@param objectType Type to resolve.
@return Corresponding class. | [
"Resolves",
"the",
"{",
"@link",
"Class",
"}",
"that",
"corresponds",
"with",
"a",
"{",
"@link",
"Type",
"}",
".",
"<p",
">",
"{",
"@code",
"Class",
"}",
"is",
"an",
"implementation",
"of",
"{",
"@code",
"Type",
"}",
"but",
"of",
"course",
"not",
"ev... | train | https://github.com/voostindie/sprox/blob/8cde722ac6712008c82830fd2ef130e219232b8c/src/main/java/nl/ulso/sprox/impl/ReflectionUtil.java#L35-L48 |
httl/httl | httl/src/main/java/httl/Context.java | Context.pushContext | public static Context pushContext(Map<String, Object> current) {
Context context = new Context(getContext(), current);
LOCAL.set(context);
return context;
} | java | public static Context pushContext(Map<String, Object> current) {
Context context = new Context(getContext(), current);
LOCAL.set(context);
return context;
} | [
"public",
"static",
"Context",
"pushContext",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"current",
")",
"{",
"Context",
"context",
"=",
"new",
"Context",
"(",
"getContext",
"(",
")",
",",
"current",
")",
";",
"LOCAL",
".",
"set",
"(",
"context",
"... | Push the current context to thread local.
@param current - current variables | [
"Push",
"the",
"current",
"context",
"to",
"thread",
"local",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/Context.java#L104-L108 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java | Vector.insertElementAt | public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
} | java | public synchronized void insertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
throw new ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
} | [
"public",
"synchronized",
"void",
"insertElementAt",
"(",
"E",
"obj",
",",
"int",
"index",
")",
"{",
"modCount",
"++",
";",
"if",
"(",
"index",
">",
"elementCount",
")",
"{",
"throw",
"new",
"ArrayIndexOutOfBoundsException",
"(",
"index",
"+",
"\" > \"",
"+"... | Inserts the specified object as a component in this vector at the
specified {@code index}. Each component in this vector with
an index greater or equal to the specified {@code index} is
shifted upward to have an index one greater than the value it had
previously.
<p>The index must be a value greater than or equal to {@code 0}
and less than or equal to the current size of the vector. (If the
index is equal to the current size of the vector, the new element
is appended to the Vector.)
<p>This method is identical in functionality to the
{@link #add(int, Object) add(int, E)}
method (which is part of the {@link List} interface). Note that the
{@code add} method reverses the order of the parameters, to more closely
match array usage.
@param obj the component to insert
@param index where to insert the new component
@throws ArrayIndexOutOfBoundsException if the index is out of range
({@code index < 0 || index > size()}) | [
"Inserts",
"the",
"specified",
"object",
"as",
"a",
"component",
"in",
"this",
"vector",
"at",
"the",
"specified",
"{",
"@code",
"index",
"}",
".",
"Each",
"component",
"in",
"this",
"vector",
"with",
"an",
"index",
"greater",
"or",
"equal",
"to",
"the",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Vector.java#L595-L605 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLLiteralImplDouble_CustomFieldSerializer.java | OWLLiteralImplDouble_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplDouble instance) throws SerializationException {
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, OWLLiteralImplDouble instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"OWLLiteralImplDouble",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"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#L67-L70 |
alkacon/opencms-core | src/org/opencms/file/CmsObject.java | CmsObject.getDetailName | public String getDetailName(CmsResource res, Locale locale, List<Locale> defaultLocales) throws CmsException {
String urlName = readBestUrlName(res.getStructureId(), locale, defaultLocales);
if (urlName == null) {
urlName = res.getStructureId().toString();
}
return urlName;
} | java | public String getDetailName(CmsResource res, Locale locale, List<Locale> defaultLocales) throws CmsException {
String urlName = readBestUrlName(res.getStructureId(), locale, defaultLocales);
if (urlName == null) {
urlName = res.getStructureId().toString();
}
return urlName;
} | [
"public",
"String",
"getDetailName",
"(",
"CmsResource",
"res",
",",
"Locale",
"locale",
",",
"List",
"<",
"Locale",
">",
"defaultLocales",
")",
"throws",
"CmsException",
"{",
"String",
"urlName",
"=",
"readBestUrlName",
"(",
"res",
".",
"getStructureId",
"(",
... | Returns the detail name of a resource.<p>
The detail view URI of a content element consists of its detail page URI and the detail name returned by this
method.<p>
@param res the resource for which the detail name should be retrieved
@param locale the locale for the detail name
@param defaultLocales the default locales for the detail name
@return the detail name
@throws CmsException if something goes wrong | [
"Returns",
"the",
"detail",
"name",
"of",
"a",
"resource",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L1397-L1404 |
JOML-CI/JOML | src/org/joml/Matrix3x2f.java | Matrix3x2f.transformDirection | public Vector2f transformDirection(float x, float y, Vector2f dest) {
return dest.set(m00 * x + m10 * y, m01 * x + m11 * y);
} | java | public Vector2f transformDirection(float x, float y, Vector2f dest) {
return dest.set(m00 * x + m10 * y, m01 * x + m11 * y);
} | [
"public",
"Vector2f",
"transformDirection",
"(",
"float",
"x",
",",
"float",
"y",
",",
"Vector2f",
"dest",
")",
"{",
"return",
"dest",
".",
"set",
"(",
"m00",
"*",
"x",
"+",
"m10",
"*",
"y",
",",
"m01",
"*",
"x",
"+",
"m11",
"*",
"y",
")",
";",
... | Transform/multiply the given 2D-vector <code>(x, y)</code>, as if it was a 3D-vector with z=0, by
this matrix and store the result in <code>dest</code>.
<p>
The given 2D-vector is treated as a 3D-vector with its z-component being <code>0.0</code>, so it
will represent a direction in 2D-space rather than a position. This method will therefore
not take the translation part of the matrix into account.
<p>
In order to store the result in the same vector, use {@link #transformDirection(Vector2f)}.
@see #transformDirection(Vector2f)
@param x
the x component of the vector to transform
@param y
the y component of the vector to transform
@param dest
will hold the result
@return dest | [
"Transform",
"/",
"multiply",
"the",
"given",
"2D",
"-",
"vector",
"<code",
">",
"(",
"x",
"y",
")",
"<",
"/",
"code",
">",
"as",
"if",
"it",
"was",
"a",
"3D",
"-",
"vector",
"with",
"z",
"=",
"0",
"by",
"this",
"matrix",
"and",
"store",
"the",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix3x2f.java#L1803-L1805 |
alkacon/opencms-core | src/org/opencms/i18n/CmsListResourceBundle.java | CmsListResourceBundle.addMessage | public void addMessage(String key, String value) {
if (m_bundleMap != null) {
m_bundleMap.put(key, value);
}
} | java | public void addMessage(String key, String value) {
if (m_bundleMap != null) {
m_bundleMap.put(key, value);
}
} | [
"public",
"void",
"addMessage",
"(",
"String",
"key",
",",
"String",
"value",
")",
"{",
"if",
"(",
"m_bundleMap",
"!=",
"null",
")",
"{",
"m_bundleMap",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}",
"}"
] | Adds a message to this list bundle.<p>
Please note:
All additions after the initial call to {@link #getContents()} are ignored.<p>
@param key the message key
@param value the message itself | [
"Adds",
"a",
"message",
"to",
"this",
"list",
"bundle",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsListResourceBundle.java#L57-L62 |
pedrovgs/Renderers | renderers/src/main/java/com/pedrogomez/renderers/Renderer.java | Renderer.onCreate | public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {
this.content = content;
this.rootView = inflate(layoutInflater, parent);
if (rootView == null) {
throw new NotInflateViewException(
"Renderer instances have to return a not null view in inflateView method");
}
this.rootView.setTag(this);
setUpView(rootView);
hookListeners(rootView);
} | java | public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {
this.content = content;
this.rootView = inflate(layoutInflater, parent);
if (rootView == null) {
throw new NotInflateViewException(
"Renderer instances have to return a not null view in inflateView method");
}
this.rootView.setTag(this);
setUpView(rootView);
hookListeners(rootView);
} | [
"public",
"void",
"onCreate",
"(",
"T",
"content",
",",
"LayoutInflater",
"layoutInflater",
",",
"ViewGroup",
"parent",
")",
"{",
"this",
".",
"content",
"=",
"content",
";",
"this",
".",
"rootView",
"=",
"inflate",
"(",
"layoutInflater",
",",
"parent",
")",... | Method called when the renderer is going to be created. This method has the responsibility of
inflate the xml layout using the layoutInflater and the parent ViewGroup, set itself to the
tag and call setUpView and hookListeners methods.
@param content to render. If you are using Renderers with RecyclerView widget the content will
be null in this method.
@param layoutInflater used to inflate the view.
@param parent used to inflate the view. | [
"Method",
"called",
"when",
"the",
"renderer",
"is",
"going",
"to",
"be",
"created",
".",
"This",
"method",
"has",
"the",
"responsibility",
"of",
"inflate",
"the",
"xml",
"layout",
"using",
"the",
"layoutInflater",
"and",
"the",
"parent",
"ViewGroup",
"set",
... | train | https://github.com/pedrovgs/Renderers/blob/7477fb6e3984468b32b59c8520b66afb765081ea/renderers/src/main/java/com/pedrogomez/renderers/Renderer.java#L54-L64 |
Metatavu/edelphi | rest/src/main/java/fi/metatavu/edelphi/comments/QueryQuestionCommentController.java | QueryQuestionCommentController.updateQueryQuestionComment | public QueryQuestionComment updateQueryQuestionComment(QueryQuestionComment queryQuestionComment, String comment, Boolean hidden, User modifier, Date modified) {
queryQuestionCommentDAO.updateHidden(queryQuestionComment, hidden, modifier);
return queryQuestionCommentDAO.updateComment(queryQuestionComment, comment, modifier, modified);
} | java | public QueryQuestionComment updateQueryQuestionComment(QueryQuestionComment queryQuestionComment, String comment, Boolean hidden, User modifier, Date modified) {
queryQuestionCommentDAO.updateHidden(queryQuestionComment, hidden, modifier);
return queryQuestionCommentDAO.updateComment(queryQuestionComment, comment, modifier, modified);
} | [
"public",
"QueryQuestionComment",
"updateQueryQuestionComment",
"(",
"QueryQuestionComment",
"queryQuestionComment",
",",
"String",
"comment",
",",
"Boolean",
"hidden",
",",
"User",
"modifier",
",",
"Date",
"modified",
")",
"{",
"queryQuestionCommentDAO",
".",
"updateHidd... | Updates query question comment
@param queryQuestionComment comment to be updated
@param comment comment contents
@param hidden whether comment should be hidden
@param modifier modifier
@param modified modification time
@return | [
"Updates",
"query",
"question",
"comment"
] | train | https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/rest/src/main/java/fi/metatavu/edelphi/comments/QueryQuestionCommentController.java#L93-L96 |
netty/netty-tcnative | openssl-dynamic/src/main/java/io/netty/internal/tcnative/SSLContext.java | SSLContext.setSessionTicketKeys | public static void setSessionTicketKeys(long ctx, SessionTicketKey[] keys) {
if (keys == null || keys.length == 0) {
throw new IllegalArgumentException("Length of the keys should be longer than 0.");
}
byte[] binaryKeys = new byte[keys.length * SessionTicketKey.TICKET_KEY_SIZE];
for (int i = 0; i < keys.length; i++) {
SessionTicketKey key = keys[i];
int dstCurPos = SessionTicketKey.TICKET_KEY_SIZE * i;
System.arraycopy(key.name, 0, binaryKeys, dstCurPos, SessionTicketKey.NAME_SIZE);
dstCurPos += SessionTicketKey.NAME_SIZE;
System.arraycopy(key.hmacKey, 0, binaryKeys, dstCurPos, SessionTicketKey.HMAC_KEY_SIZE);
dstCurPos += SessionTicketKey.HMAC_KEY_SIZE;
System.arraycopy(key.aesKey, 0, binaryKeys, dstCurPos, SessionTicketKey.AES_KEY_SIZE);
}
setSessionTicketKeys0(ctx, binaryKeys);
} | java | public static void setSessionTicketKeys(long ctx, SessionTicketKey[] keys) {
if (keys == null || keys.length == 0) {
throw new IllegalArgumentException("Length of the keys should be longer than 0.");
}
byte[] binaryKeys = new byte[keys.length * SessionTicketKey.TICKET_KEY_SIZE];
for (int i = 0; i < keys.length; i++) {
SessionTicketKey key = keys[i];
int dstCurPos = SessionTicketKey.TICKET_KEY_SIZE * i;
System.arraycopy(key.name, 0, binaryKeys, dstCurPos, SessionTicketKey.NAME_SIZE);
dstCurPos += SessionTicketKey.NAME_SIZE;
System.arraycopy(key.hmacKey, 0, binaryKeys, dstCurPos, SessionTicketKey.HMAC_KEY_SIZE);
dstCurPos += SessionTicketKey.HMAC_KEY_SIZE;
System.arraycopy(key.aesKey, 0, binaryKeys, dstCurPos, SessionTicketKey.AES_KEY_SIZE);
}
setSessionTicketKeys0(ctx, binaryKeys);
} | [
"public",
"static",
"void",
"setSessionTicketKeys",
"(",
"long",
"ctx",
",",
"SessionTicketKey",
"[",
"]",
"keys",
")",
"{",
"if",
"(",
"keys",
"==",
"null",
"||",
"keys",
".",
"length",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",... | Set TLS session ticket keys.
<p> The first key in the list is the primary key. Tickets dervied from the other keys
in the list will be accepted but updated to a new ticket using the primary key. This
is useful for implementing ticket key rotation.
See <a href="https://tools.ietf.org/html/rfc5077">RFC 5077</a>
@param ctx Server or Client context to use
@param keys the {@link SessionTicketKey}s | [
"Set",
"TLS",
"session",
"ticket",
"keys",
"."
] | train | https://github.com/netty/netty-tcnative/blob/4a5d7330c6c36cff2bebbb465571cab1cf7a4063/openssl-dynamic/src/main/java/io/netty/internal/tcnative/SSLContext.java#L423-L438 |
trustathsh/ironcommon | src/main/java/de/hshannover/f4/trust/ironcommon/yaml/YamlWriter.java | YamlWriter.persist | public static synchronized void persist(String fileName, Object object)
throws IOException {
ObjectChecks.checkForNullReference(fileName, "fileName is null");
ObjectChecks.checkForNullReference(object, "object is null");
FileWriter fileWriter = null;
File f = null;
try {
fileWriter = new FileWriter(fileName);
} catch (IOException e) {
f = new File(fileName);
if (f.isDirectory()) {
throw new IOException(fileName + " is a directory");
} else {
throw new IOException("Could not create " + fileName + ": "
+ e.getMessage());
}
}
Yaml yaml = new Yaml(mOptions);
yaml.dump(object, fileWriter);
fileWriter.close();
} | java | public static synchronized void persist(String fileName, Object object)
throws IOException {
ObjectChecks.checkForNullReference(fileName, "fileName is null");
ObjectChecks.checkForNullReference(object, "object is null");
FileWriter fileWriter = null;
File f = null;
try {
fileWriter = new FileWriter(fileName);
} catch (IOException e) {
f = new File(fileName);
if (f.isDirectory()) {
throw new IOException(fileName + " is a directory");
} else {
throw new IOException("Could not create " + fileName + ": "
+ e.getMessage());
}
}
Yaml yaml = new Yaml(mOptions);
yaml.dump(object, fileWriter);
fileWriter.close();
} | [
"public",
"static",
"synchronized",
"void",
"persist",
"(",
"String",
"fileName",
",",
"Object",
"object",
")",
"throws",
"IOException",
"{",
"ObjectChecks",
".",
"checkForNullReference",
"(",
"fileName",
",",
"\"fileName is null\"",
")",
";",
"ObjectChecks",
".",
... | Save a given {@link Object} to the yml-file.
@param fileName
The file name of the yml-file.
@param object
The {@link Object} to be stored.
@throws IOException
If the file could not be opened, created (when it doesn't
exist) or the given filename is a directory. | [
"Save",
"a",
"given",
"{",
"@link",
"Object",
"}",
"to",
"the",
"yml",
"-",
"file",
"."
] | train | https://github.com/trustathsh/ironcommon/blob/fee589a9300ab16744ca12fafae4357dd18c9fcb/src/main/java/de/hshannover/f4/trust/ironcommon/yaml/YamlWriter.java#L80-L103 |
MGunlogson/CuckooFilter4J | src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java | SegmentedBucketLocker.unlockBucketsRead | void unlockBucketsRead(long i1, long i2) {
int bucket1LockIdx = getBucketLock(i1);
int bucket2LockIdx = getBucketLock(i2);
// always unlock segments in same order to avoid deadlocks
if (bucket1LockIdx == bucket2LockIdx) {
lockAry[bucket1LockIdx].tryUnlockRead();
return;
}
lockAry[bucket1LockIdx].tryUnlockRead();
lockAry[bucket2LockIdx].tryUnlockRead();
} | java | void unlockBucketsRead(long i1, long i2) {
int bucket1LockIdx = getBucketLock(i1);
int bucket2LockIdx = getBucketLock(i2);
// always unlock segments in same order to avoid deadlocks
if (bucket1LockIdx == bucket2LockIdx) {
lockAry[bucket1LockIdx].tryUnlockRead();
return;
}
lockAry[bucket1LockIdx].tryUnlockRead();
lockAry[bucket2LockIdx].tryUnlockRead();
} | [
"void",
"unlockBucketsRead",
"(",
"long",
"i1",
",",
"long",
"i2",
")",
"{",
"int",
"bucket1LockIdx",
"=",
"getBucketLock",
"(",
"i1",
")",
";",
"int",
"bucket2LockIdx",
"=",
"getBucketLock",
"(",
"i2",
")",
";",
"// always unlock segments in same order to avoid d... | Unlocks segments corresponding to bucket indexes in specific order to prevent deadlocks | [
"Unlocks",
"segments",
"corresponding",
"to",
"bucket",
"indexes",
"in",
"specific",
"order",
"to",
"prevent",
"deadlocks"
] | train | https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java#L117-L127 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/xml/RaXmlGen.java | RaXmlGen.writeInbound | private void writeInbound(Definition def, Writer out, int indent) throws IOException
{
writeIndent(out, indent);
out.write("<inbound-resourceadapter>");
writeEol(out);
writeIndent(out, indent + 1);
out.write("<messageadapter>");
writeEol(out);
writeIndent(out, indent + 2);
out.write("<messagelistener>");
writeEol(out);
writeIndent(out, indent + 3);
if (!def.isDefaultPackageInbound())
{
out.write("<messagelistener-type>" + def.getMlClass() + "</messagelistener-type>");
}
else
{
out.write("<messagelistener-type>" + def.getRaPackage() +
".inflow." + def.getMlClass() + "</messagelistener-type>");
}
writeEol(out);
writeIndent(out, indent + 3);
out.write("<activationspec>");
writeEol(out);
writeIndent(out, indent + 4);
out.write("<activationspec-class>" + def.getRaPackage() +
".inflow." + def.getAsClass() + "</activationspec-class>");
writeEol(out);
writeAsConfigPropsXml(def.getAsConfigProps(), out, indent + 4);
writeIndent(out, indent + 3);
out.write("</activationspec>");
writeEol(out);
writeIndent(out, indent + 2);
out.write("</messagelistener>");
writeEol(out);
writeIndent(out, indent + 1);
out.write("</messageadapter>");
writeEol(out);
writeIndent(out, indent);
out.write("</inbound-resourceadapter>");
writeEol(out);
} | java | private void writeInbound(Definition def, Writer out, int indent) throws IOException
{
writeIndent(out, indent);
out.write("<inbound-resourceadapter>");
writeEol(out);
writeIndent(out, indent + 1);
out.write("<messageadapter>");
writeEol(out);
writeIndent(out, indent + 2);
out.write("<messagelistener>");
writeEol(out);
writeIndent(out, indent + 3);
if (!def.isDefaultPackageInbound())
{
out.write("<messagelistener-type>" + def.getMlClass() + "</messagelistener-type>");
}
else
{
out.write("<messagelistener-type>" + def.getRaPackage() +
".inflow." + def.getMlClass() + "</messagelistener-type>");
}
writeEol(out);
writeIndent(out, indent + 3);
out.write("<activationspec>");
writeEol(out);
writeIndent(out, indent + 4);
out.write("<activationspec-class>" + def.getRaPackage() +
".inflow." + def.getAsClass() + "</activationspec-class>");
writeEol(out);
writeAsConfigPropsXml(def.getAsConfigProps(), out, indent + 4);
writeIndent(out, indent + 3);
out.write("</activationspec>");
writeEol(out);
writeIndent(out, indent + 2);
out.write("</messagelistener>");
writeEol(out);
writeIndent(out, indent + 1);
out.write("</messageadapter>");
writeEol(out);
writeIndent(out, indent);
out.write("</inbound-resourceadapter>");
writeEol(out);
} | [
"private",
"void",
"writeInbound",
"(",
"Definition",
"def",
",",
"Writer",
"out",
",",
"int",
"indent",
")",
"throws",
"IOException",
"{",
"writeIndent",
"(",
"out",
",",
"indent",
")",
";",
"out",
".",
"write",
"(",
"\"<inbound-resourceadapter>\"",
")",
";... | Output inbound xml part
@param def definition
@param out Writer
@param indent space number
@throws IOException ioException | [
"Output",
"inbound",
"xml",
"part"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/xml/RaXmlGen.java#L243-L286 |
jenkinsci/jenkins | core/src/main/java/hudson/PluginManager.java | PluginManager.containsHpiJpi | private boolean containsHpiJpi(Collection<String> bundledPlugins, String name) {
return bundledPlugins.contains(name.replaceAll("\\.hpi",".jpi"))
|| bundledPlugins.contains(name.replaceAll("\\.jpi",".hpi"));
} | java | private boolean containsHpiJpi(Collection<String> bundledPlugins, String name) {
return bundledPlugins.contains(name.replaceAll("\\.hpi",".jpi"))
|| bundledPlugins.contains(name.replaceAll("\\.jpi",".hpi"));
} | [
"private",
"boolean",
"containsHpiJpi",
"(",
"Collection",
"<",
"String",
">",
"bundledPlugins",
",",
"String",
"name",
")",
"{",
"return",
"bundledPlugins",
".",
"contains",
"(",
"name",
".",
"replaceAll",
"(",
"\"\\\\.hpi\"",
",",
"\".jpi\"",
")",
")",
"||",... | /*
contains operation that considers xxx.hpi and xxx.jpi as equal
this is necessary since the bundled plugins are still called *.hpi | [
"/",
"*",
"contains",
"operation",
"that",
"considers",
"xxx",
".",
"hpi",
"and",
"xxx",
".",
"jpi",
"as",
"equal",
"this",
"is",
"necessary",
"since",
"the",
"bundled",
"plugins",
"are",
"still",
"called",
"*",
".",
"hpi"
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/PluginManager.java#L835-L838 |
NessComputing/syslog4j | src/main/java/com/nesscomputing/syslog4j/util/Base64.java | Base64.decode4to3 | private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
{
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else
{
try{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}catch( Exception e){
LOG.info(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
LOG.info(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
LOG.info(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
LOG.info(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
return -1;
} // end catch
}
} | java | private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options )
{
byte[] DECODABET = getDecodabet( options );
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else
{
try{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}catch( Exception e){
LOG.info(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
LOG.info(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
LOG.info(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
LOG.info(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
return -1;
} // end catch
}
} | [
"private",
"static",
"int",
"decode4to3",
"(",
"byte",
"[",
"]",
"source",
",",
"int",
"srcOffset",
",",
"byte",
"[",
"]",
"destination",
",",
"int",
"destOffset",
",",
"int",
"options",
")",
"{",
"byte",
"[",
"]",
"DECODABET",
"=",
"getDecodabet",
"(",
... | Decodes four bytes from array <var>source</var>
and writes the resulting bytes (up to three of them)
to <var>destination</var>.
The source and destination arrays can be manipulated
anywhere along their length by specifying
<var>srcOffset</var> and <var>destOffset</var>.
This method does not check to make sure your arrays
are large enough to accomodate <var>srcOffset</var> + 4 for
the <var>source</var> array or <var>destOffset</var> + 3 for
the <var>destination</var> array.
This method returns the actual number of bytes that
were converted from the Base64 encoding.
<p>This is the lowest level of the decoding methods with
all possible parameters.</p>
@param source the array to convert
@param srcOffset the index where conversion begins
@param destination the array to hold the conversion
@param destOffset the index where output will be put
@param options alphabet type is pulled from this (standard, url-safe, ordered)
@return the number of decoded bytes converted
@since 1.3 | [
"Decodes",
"four",
"bytes",
"from",
"array",
"<var",
">",
"source<",
"/",
"var",
">",
"and",
"writes",
"the",
"resulting",
"bytes",
"(",
"up",
"to",
"three",
"of",
"them",
")",
"to",
"<var",
">",
"destination<",
"/",
"var",
">",
".",
"The",
"source",
... | train | https://github.com/NessComputing/syslog4j/blob/698fe4ce926cfc46524329d089052507cdb8cba4/src/main/java/com/nesscomputing/syslog4j/util/Base64.java#L776-L837 |
ykrasik/jaci | jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/directory/CliDirectory.java | CliDirectory.autoCompleteDirectory | public AutoComplete autoCompleteDirectory(String prefix) {
final Trie<CliValueType> possibilities = childDirectories.subTrie(prefix).mapValues(CliValueType.DIRECTORY.<CliDirectory>getMapper());
return new AutoComplete(prefix, possibilities);
} | java | public AutoComplete autoCompleteDirectory(String prefix) {
final Trie<CliValueType> possibilities = childDirectories.subTrie(prefix).mapValues(CliValueType.DIRECTORY.<CliDirectory>getMapper());
return new AutoComplete(prefix, possibilities);
} | [
"public",
"AutoComplete",
"autoCompleteDirectory",
"(",
"String",
"prefix",
")",
"{",
"final",
"Trie",
"<",
"CliValueType",
">",
"possibilities",
"=",
"childDirectories",
".",
"subTrie",
"(",
"prefix",
")",
".",
"mapValues",
"(",
"CliValueType",
".",
"DIRECTORY",
... | Auto complete the given prefix with child directory possibilities.
@param prefix Prefix to offer auto complete for.
@return Auto complete for child {@link CliDirectory}s that starts with the given prefix. Case insensitive. | [
"Auto",
"complete",
"the",
"given",
"prefix",
"with",
"child",
"directory",
"possibilities",
"."
] | train | https://github.com/ykrasik/jaci/blob/4615edef7c76288ad5ea8d678132b161645ca1e3/jaci-cli-core/src/main/java/com/github/ykrasik/jaci/cli/directory/CliDirectory.java#L122-L125 |
apigee/usergrid-java-sdk | src/main/java/org/usergrid/java/client/Client.java | Client.addUserToGroup | public ApiResponse addUserToGroup(String userId, String groupId) {
return apiRequest(HttpMethod.POST, null, null, organizationId, applicationId, "groups",
groupId, "users", userId);
} | java | public ApiResponse addUserToGroup(String userId, String groupId) {
return apiRequest(HttpMethod.POST, null, null, organizationId, applicationId, "groups",
groupId, "users", userId);
} | [
"public",
"ApiResponse",
"addUserToGroup",
"(",
"String",
"userId",
",",
"String",
"groupId",
")",
"{",
"return",
"apiRequest",
"(",
"HttpMethod",
".",
"POST",
",",
"null",
",",
"null",
",",
"organizationId",
",",
"applicationId",
",",
"\"groups\"",
",",
"grou... | Adds a user to the specified groups.
@param userId
@param groupId
@return | [
"Adds",
"a",
"user",
"to",
"the",
"specified",
"groups",
"."
] | train | https://github.com/apigee/usergrid-java-sdk/blob/6202745f184754defff13962dfc3d830bc7d8c63/src/main/java/org/usergrid/java/client/Client.java#L876-L879 |
landawn/AbacusUtil | src/com/landawn/abacus/util/JdbcUtil.java | JdbcUtil.importData | @SuppressWarnings("rawtypes")
public static int importData(final DataSet dataset, final Connection conn, final String insertSQL, final Map<String, ? extends Type> columnTypeMap)
throws UncheckedSQLException {
return importData(dataset, 0, dataset.size(), conn, insertSQL, columnTypeMap);
} | java | @SuppressWarnings("rawtypes")
public static int importData(final DataSet dataset, final Connection conn, final String insertSQL, final Map<String, ? extends Type> columnTypeMap)
throws UncheckedSQLException {
return importData(dataset, 0, dataset.size(), conn, insertSQL, columnTypeMap);
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"static",
"int",
"importData",
"(",
"final",
"DataSet",
"dataset",
",",
"final",
"Connection",
"conn",
",",
"final",
"String",
"insertSQL",
",",
"final",
"Map",
"<",
"String",
",",
"?",
"extends",
... | Imports the data from <code>DataSet</code> to database.
@param dataset
@param conn
@param insertSQL the column order in the sql must be consistent with the column order in the DataSet. Here is sample about how to create the sql:
<pre><code>
List<String> columnNameList = new ArrayList<>(dataset.columnNameList());
columnNameList.retainAll(yourSelectColumnNames);
String sql = RE.insert(columnNameList).into(tableName).sql();
</code></pre>
@param columnTypeMap
@return
@throws UncheckedSQLException | [
"Imports",
"the",
"data",
"from",
"<code",
">",
"DataSet<",
"/",
"code",
">",
"to",
"database",
"."
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/JdbcUtil.java#L1975-L1979 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/content/CmsElementRename.java | CmsElementRename.isValidElement | private boolean isValidElement(CmsXmlPage page, String element) {
CmsFile file = page.getFile();
String template;
try {
template = getCms().readPropertyObject(
getCms().getSitePath(file),
CmsPropertyDefinition.PROPERTY_TEMPLATE,
true).getValue(null);
} catch (CmsException e) {
return false;
}
return isValidTemplateElement(template, element);
} | java | private boolean isValidElement(CmsXmlPage page, String element) {
CmsFile file = page.getFile();
String template;
try {
template = getCms().readPropertyObject(
getCms().getSitePath(file),
CmsPropertyDefinition.PROPERTY_TEMPLATE,
true).getValue(null);
} catch (CmsException e) {
return false;
}
return isValidTemplateElement(template, element);
} | [
"private",
"boolean",
"isValidElement",
"(",
"CmsXmlPage",
"page",
",",
"String",
"element",
")",
"{",
"CmsFile",
"file",
"=",
"page",
".",
"getFile",
"(",
")",
";",
"String",
"template",
";",
"try",
"{",
"template",
"=",
"getCms",
"(",
")",
".",
"readPr... | Checks if the selected new element is valid for the selected template.<p>
@param page the xml page
@param element the element name
@return true if ALL_TEMPLATES selected or the element is valid for the selected template; otherwise false | [
"Checks",
"if",
"the",
"selected",
"new",
"element",
"is",
"valid",
"for",
"the",
"selected",
"template",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/content/CmsElementRename.java#L742-L756 |
canoo/dolphin-platform | platform/dolphin-platform-remoting-client-javafx/src/main/java/com/canoo/platform/remoting/client/javafx/DolphinPlatformApplication.java | DolphinPlatformApplication.init | @Override
public final void init() throws Exception {
FxToolkit.init();
applicationInit();
PlatformClient.getClientConfiguration().setUncaughtExceptionHandler((Thread thread, Throwable exception) -> {
PlatformClient.getClientConfiguration().getUiExecutor().execute(() -> {
Assert.requireNonNull(thread, "thread");
Assert.requireNonNull(exception, "exception");
if (connectInProgress.get()) {
runtimeExceptionsAtInitialization.add(new DolphinRuntimeException(thread, "Unhandled error in Dolphin Platform background thread", exception));
} else {
onRuntimeError(primaryStage, new DolphinRuntimeException(thread, "Unhandled error in Dolphin Platform background thread", exception));
}
});
});
try {
clientContext = createClientContext();
Assert.requireNonNull(clientContext, "clientContext");
connectInProgress.set(true);
clientContext.connect().get(30_000, TimeUnit.MILLISECONDS);
} catch (ClientInitializationException e) {
initializationException = e;
} catch (Exception e) {
initializationException = new ClientInitializationException("Can not initialize Dolphin Platform Context", e);
} finally {
connectInProgress.set(false);
}
} | java | @Override
public final void init() throws Exception {
FxToolkit.init();
applicationInit();
PlatformClient.getClientConfiguration().setUncaughtExceptionHandler((Thread thread, Throwable exception) -> {
PlatformClient.getClientConfiguration().getUiExecutor().execute(() -> {
Assert.requireNonNull(thread, "thread");
Assert.requireNonNull(exception, "exception");
if (connectInProgress.get()) {
runtimeExceptionsAtInitialization.add(new DolphinRuntimeException(thread, "Unhandled error in Dolphin Platform background thread", exception));
} else {
onRuntimeError(primaryStage, new DolphinRuntimeException(thread, "Unhandled error in Dolphin Platform background thread", exception));
}
});
});
try {
clientContext = createClientContext();
Assert.requireNonNull(clientContext, "clientContext");
connectInProgress.set(true);
clientContext.connect().get(30_000, TimeUnit.MILLISECONDS);
} catch (ClientInitializationException e) {
initializationException = e;
} catch (Exception e) {
initializationException = new ClientInitializationException("Can not initialize Dolphin Platform Context", e);
} finally {
connectInProgress.set(false);
}
} | [
"@",
"Override",
"public",
"final",
"void",
"init",
"(",
")",
"throws",
"Exception",
"{",
"FxToolkit",
".",
"init",
"(",
")",
";",
"applicationInit",
"(",
")",
";",
"PlatformClient",
".",
"getClientConfiguration",
"(",
")",
".",
"setUncaughtExceptionHandler",
... | Creates the connection to the Dolphin Platform server. If this method will be overridden always call the super method.
@throws Exception a exception if the connection can't be created | [
"Creates",
"the",
"connection",
"to",
"the",
"Dolphin",
"Platform",
"server",
".",
"If",
"this",
"method",
"will",
"be",
"overridden",
"always",
"call",
"the",
"super",
"method",
"."
] | train | https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-remoting-client-javafx/src/main/java/com/canoo/platform/remoting/client/javafx/DolphinPlatformApplication.java#L100-L132 |
overview/mime-types | src/main/java/org/overviewproject/mime_types/MimeTypeDetector.java | MimeTypeDetector.subArraysEqualWithMask | private boolean subArraysEqualWithMask(byte[] a, int aStart, byte[] b, int bStart, byte[] mask, int maskStart, int len) {
for (int i = aStart, j = bStart, k = maskStart; len > 0; i++, j++, k++, len--) {
if ((a[i] & mask[k]) != (b[j] & mask[k])) {
return false;
}
}
return true;
} | java | private boolean subArraysEqualWithMask(byte[] a, int aStart, byte[] b, int bStart, byte[] mask, int maskStart, int len) {
for (int i = aStart, j = bStart, k = maskStart; len > 0; i++, j++, k++, len--) {
if ((a[i] & mask[k]) != (b[j] & mask[k])) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"subArraysEqualWithMask",
"(",
"byte",
"[",
"]",
"a",
",",
"int",
"aStart",
",",
"byte",
"[",
"]",
"b",
",",
"int",
"bStart",
",",
"byte",
"[",
"]",
"mask",
",",
"int",
"maskStart",
",",
"int",
"len",
")",
"{",
"for",
"(",
"in... | Returns true if subarrays are equal, with the given mask.
<p>
The mask must have length <tt>len</tt>.
</p> | [
"Returns",
"true",
"if",
"subarrays",
"are",
"equal",
"with",
"the",
"given",
"mask",
"."
] | train | https://github.com/overview/mime-types/blob/d5c45302049c0cd5e634a50954304d8ddeb9abb4/src/main/java/org/overviewproject/mime_types/MimeTypeDetector.java#L421-L429 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java | AbstractService.updateMessage | public void updateMessage(final Wave wave, final String message) {
// Update the current task message
JRebirth.runIntoJAT("Service Task Mesage => " + message,
() -> wave.get(JRebirthWaves.SERVICE_TASK).updateMessage(message));
} | java | public void updateMessage(final Wave wave, final String message) {
// Update the current task message
JRebirth.runIntoJAT("Service Task Mesage => " + message,
() -> wave.get(JRebirthWaves.SERVICE_TASK).updateMessage(message));
} | [
"public",
"void",
"updateMessage",
"(",
"final",
"Wave",
"wave",
",",
"final",
"String",
"message",
")",
"{",
"// Update the current task message",
"JRebirth",
".",
"runIntoJAT",
"(",
"\"Service Task Mesage => \"",
"+",
"message",
",",
"(",
")",
"->",
"wave",
".",... | Update the current message of the service task related to the given wave.
@param wave the wave that trigger the service task call
@param message the current message of the service task processed | [
"Update",
"the",
"current",
"message",
"of",
"the",
"service",
"task",
"related",
"to",
"the",
"given",
"wave",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/AbstractService.java#L346-L351 |
lessthanoptimal/BoofCV | main/boofcv-types/src/main/java/boofcv/struct/image/InterleavedS32.java | InterleavedS32.setBand | @Override
public void setBand(int x, int y, int band, int value) {
if (!isInBounds(x, y))
throw new ImageAccessException("Requested pixel is out of bounds.");
if (band < 0 || band >= numBands)
throw new ImageAccessException("Invalid band requested.");
data[getIndex(x, y, band)] = value;
} | java | @Override
public void setBand(int x, int y, int band, int value) {
if (!isInBounds(x, y))
throw new ImageAccessException("Requested pixel is out of bounds.");
if (band < 0 || band >= numBands)
throw new ImageAccessException("Invalid band requested.");
data[getIndex(x, y, band)] = value;
} | [
"@",
"Override",
"public",
"void",
"setBand",
"(",
"int",
"x",
",",
"int",
"y",
",",
"int",
"band",
",",
"int",
"value",
")",
"{",
"if",
"(",
"!",
"isInBounds",
"(",
"x",
",",
"y",
")",
")",
"throw",
"new",
"ImageAccessException",
"(",
"\"Requested p... | Returns the value of the specified band in the specified pixel.
@param x pixel coordinate.
@param y pixel coordinate.
@param band which color band in the pixel
@param value The new value of the element. | [
"Returns",
"the",
"value",
"of",
"the",
"specified",
"band",
"in",
"the",
"specified",
"pixel",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-types/src/main/java/boofcv/struct/image/InterleavedS32.java#L106-L114 |
lucee/Lucee | core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java | CFMLExpressionInterpreter.impOp | private Ref impOp() throws PageException {
Ref ref = eqvOp();
while (cfml.forwardIfCurrentAndNoWordAfter("imp")) {
cfml.removeSpace();
ref = new Imp(ref, eqvOp(), limited);
}
return ref;
} | java | private Ref impOp() throws PageException {
Ref ref = eqvOp();
while (cfml.forwardIfCurrentAndNoWordAfter("imp")) {
cfml.removeSpace();
ref = new Imp(ref, eqvOp(), limited);
}
return ref;
} | [
"private",
"Ref",
"impOp",
"(",
")",
"throws",
"PageException",
"{",
"Ref",
"ref",
"=",
"eqvOp",
"(",
")",
";",
"while",
"(",
"cfml",
".",
"forwardIfCurrentAndNoWordAfter",
"(",
"\"imp\"",
")",
")",
"{",
"cfml",
".",
"removeSpace",
"(",
")",
";",
"ref",
... | Transfomiert eine Implication (imp) Operation. <br />
EBNF:<br />
<code>eqvOp {"imp" spaces eqvOp};</code>
@return CFXD Element
@throws PageException | [
"Transfomiert",
"eine",
"Implication",
"(",
"imp",
")",
"Operation",
".",
"<br",
"/",
">",
"EBNF",
":",
"<br",
"/",
">",
"<code",
">",
"eqvOp",
"{",
"imp",
"spaces",
"eqvOp",
"}",
";",
"<",
"/",
"code",
">"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/interpreter/CFMLExpressionInterpreter.java#L346-L353 |
j-easy/easy-random | easy-random-core/src/main/java/org/jeasy/random/util/CharacterUtils.java | CharacterUtils.collectPrintableCharactersOf | public static List<Character> collectPrintableCharactersOf(Charset charset) {
List<Character> chars = new ArrayList<>();
for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
char character = (char) i;
if (isPrintable(character)) {
String characterAsString = Character.toString(character);
byte[] encoded = characterAsString.getBytes(charset);
String decoded = new String(encoded, charset);
if (characterAsString.equals(decoded)) {
chars.add(character);
}
}
}
return chars;
} | java | public static List<Character> collectPrintableCharactersOf(Charset charset) {
List<Character> chars = new ArrayList<>();
for (int i = Character.MIN_VALUE; i < Character.MAX_VALUE; i++) {
char character = (char) i;
if (isPrintable(character)) {
String characterAsString = Character.toString(character);
byte[] encoded = characterAsString.getBytes(charset);
String decoded = new String(encoded, charset);
if (characterAsString.equals(decoded)) {
chars.add(character);
}
}
}
return chars;
} | [
"public",
"static",
"List",
"<",
"Character",
">",
"collectPrintableCharactersOf",
"(",
"Charset",
"charset",
")",
"{",
"List",
"<",
"Character",
">",
"chars",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"Character",
".",
"... | Returns a list of all printable charaters of the given charset.
@param charset
Charset to use
@return list of printable characters | [
"Returns",
"a",
"list",
"of",
"all",
"printable",
"charaters",
"of",
"the",
"given",
"charset",
"."
] | train | https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/util/CharacterUtils.java#L49-L63 |
esigate/esigate | esigate-core/src/main/java/org/esigate/DriverFactory.java | DriverFactory.put | public static void put(String instanceName, Driver instance) {
// Copy current instances
Map<String, Driver> newInstances = new HashMap<>();
synchronized (instances) {
Set<String> keys = instances.getInstances().keySet();
for (String key : keys) {
newInstances.put(key, instances.getInstances().get(key));
}
}
// Add new instance
newInstances.put(instanceName, instance);
instances = new IndexedInstances(newInstances);
} | java | public static void put(String instanceName, Driver instance) {
// Copy current instances
Map<String, Driver> newInstances = new HashMap<>();
synchronized (instances) {
Set<String> keys = instances.getInstances().keySet();
for (String key : keys) {
newInstances.put(key, instances.getInstances().get(key));
}
}
// Add new instance
newInstances.put(instanceName, instance);
instances = new IndexedInstances(newInstances);
} | [
"public",
"static",
"void",
"put",
"(",
"String",
"instanceName",
",",
"Driver",
"instance",
")",
"{",
"// Copy current instances",
"Map",
"<",
"String",
",",
"Driver",
">",
"newInstances",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"synchronized",
"(",
"in... | Add/replace instance in current instance map. Work on a copy of the current map and replace it atomically.
@param instanceName
The name of the provider
@param instance
The instance | [
"Add",
"/",
"replace",
"instance",
"in",
"current",
"instance",
"map",
".",
"Work",
"on",
"a",
"copy",
"of",
"the",
"current",
"map",
"and",
"replace",
"it",
"atomically",
"."
] | train | https://github.com/esigate/esigate/blob/50421fb224f16e1ec42715425109a72b3b55527b/esigate-core/src/main/java/org/esigate/DriverFactory.java#L297-L312 |
spring-projects/spring-security-oauth | spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java | OAuthProviderProcessingFilter.requiresAuthentication | protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
//copied from org.springframework.security.ui.AbstractProcessingFilter.requiresAuthentication
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
if ("".equals(request.getContextPath())) {
return uri.endsWith(filterProcessesUrl);
}
boolean match = uri.endsWith(request.getContextPath() + filterProcessesUrl);
if (log.isDebugEnabled()) {
log.debug(uri + (match ? " matches " : " does not match ") + filterProcessesUrl);
}
return match;
} | java | protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
//copied from org.springframework.security.ui.AbstractProcessingFilter.requiresAuthentication
String uri = request.getRequestURI();
int pathParamIndex = uri.indexOf(';');
if (pathParamIndex > 0) {
// strip everything after the first semi-colon
uri = uri.substring(0, pathParamIndex);
}
if ("".equals(request.getContextPath())) {
return uri.endsWith(filterProcessesUrl);
}
boolean match = uri.endsWith(request.getContextPath() + filterProcessesUrl);
if (log.isDebugEnabled()) {
log.debug(uri + (match ? " matches " : " does not match ") + filterProcessesUrl);
}
return match;
} | [
"protected",
"boolean",
"requiresAuthentication",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"FilterChain",
"filterChain",
")",
"{",
"//copied from org.springframework.security.ui.AbstractProcessingFilter.requiresAuthentication",
"String",
"uri... | Whether this filter is configured to process the specified request.
@param request The request.
@param response The response
@param filterChain The filter chain
@return Whether this filter is configured to process the specified request. | [
"Whether",
"this",
"filter",
"is",
"configured",
"to",
"process",
"the",
"specified",
"request",
"."
] | train | https://github.com/spring-projects/spring-security-oauth/blob/bbae0027eceb2c74a21ac26bbc86142dc732ffbe/spring-security-oauth/src/main/java/org/springframework/security/oauth/provider/filter/OAuthProviderProcessingFilter.java#L389-L408 |
alkacon/opencms-core | src/org/opencms/main/CmsShellCommands.java | CmsShellCommands.uploadFile | public CmsResource uploadFile(String localfile, String folder, String filename, String type)
throws Exception, CmsIllegalArgumentException {
I_CmsResourceType t = OpenCms.getResourceManager().getResourceType(type);
return m_cms.createResource(folder + filename, t, CmsFileUtil.readFile(new File(localfile)), null);
} | java | public CmsResource uploadFile(String localfile, String folder, String filename, String type)
throws Exception, CmsIllegalArgumentException {
I_CmsResourceType t = OpenCms.getResourceManager().getResourceType(type);
return m_cms.createResource(folder + filename, t, CmsFileUtil.readFile(new File(localfile)), null);
} | [
"public",
"CmsResource",
"uploadFile",
"(",
"String",
"localfile",
",",
"String",
"folder",
",",
"String",
"filename",
",",
"String",
"type",
")",
"throws",
"Exception",
",",
"CmsIllegalArgumentException",
"{",
"I_CmsResourceType",
"t",
"=",
"OpenCms",
".",
"getRe... | Loads a file from the "real" file system to the VFS.<p>
@param localfile the file upload
@param folder the folder in the VFS to place the file into
@param filename the name of the uploaded file in the VFS
@param type the type of the new file in the VFS
@return the createed file
@throws Exception if something goes wrong
@throws CmsIllegalArgumentException if the concatenation of String arguments
<code>folder</code> and <code>localfile</code> is of length 0 | [
"Loads",
"a",
"file",
"from",
"the",
"real",
"file",
"system",
"to",
"the",
"VFS",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShellCommands.java#L1769-L1774 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/data/AnyValueMap.java | AnyValueMap.fromMaps | public static AnyValueMap fromMaps(Map<?, ?>... maps) {
AnyValueMap result = new AnyValueMap();
if (maps == null || maps.length == 0)
return result;
for (Map<?, ?> map : maps) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
String key = StringConverter.toString(entry.getKey());
Object value = entry.getValue();
result.put(key, value);
}
}
return result;
} | java | public static AnyValueMap fromMaps(Map<?, ?>... maps) {
AnyValueMap result = new AnyValueMap();
if (maps == null || maps.length == 0)
return result;
for (Map<?, ?> map : maps) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
String key = StringConverter.toString(entry.getKey());
Object value = entry.getValue();
result.put(key, value);
}
}
return result;
} | [
"public",
"static",
"AnyValueMap",
"fromMaps",
"(",
"Map",
"<",
"?",
",",
"?",
">",
"...",
"maps",
")",
"{",
"AnyValueMap",
"result",
"=",
"new",
"AnyValueMap",
"(",
")",
";",
"if",
"(",
"maps",
"==",
"null",
"||",
"maps",
".",
"length",
"==",
"0",
... | Creates a new AnyValueMap by merging two or more maps. Maps defined later in
the list override values from previously defined maps.
@param maps an array of maps to be merged
@return a newly created AnyValueMap. | [
"Creates",
"a",
"new",
"AnyValueMap",
"by",
"merging",
"two",
"or",
"more",
"maps",
".",
"Maps",
"defined",
"later",
"in",
"the",
"list",
"override",
"values",
"from",
"previously",
"defined",
"maps",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/data/AnyValueMap.java#L705-L719 |
GeoLatte/geolatte-common | src/main/java/org/geolatte/common/dataformats/json/jackson/DefaultFeature.java | DefaultFeature.setGeometry | public void setGeometry(String name, Geometry value)
{
if (name == null)
{
geomPropertyName = null;
geomValue = null;
}
else
{
geomPropertyName= name;
geomValue = value;
}
} | java | public void setGeometry(String name, Geometry value)
{
if (name == null)
{
geomPropertyName = null;
geomValue = null;
}
else
{
geomPropertyName= name;
geomValue = value;
}
} | [
"public",
"void",
"setGeometry",
"(",
"String",
"name",
",",
"Geometry",
"value",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"geomPropertyName",
"=",
"null",
";",
"geomValue",
"=",
"null",
";",
"}",
"else",
"{",
"geomPropertyName",
"=",
"name",... | Sets the geometry property of the feature. This method also allows wiping the current geometry
by setting the name of the property to null. The value will in that case be ignored.
@param name the name of the geometry property, or null if the geometry property is to be wiped
@param value the value of the geometry property of this feature | [
"Sets",
"the",
"geometry",
"property",
"of",
"the",
"feature",
".",
"This",
"method",
"also",
"allows",
"wiping",
"the",
"current",
"geometry",
"by",
"setting",
"the",
"name",
"of",
"the",
"property",
"to",
"null",
".",
"The",
"value",
"will",
"in",
"that"... | train | https://github.com/GeoLatte/geolatte-common/blob/dc7f92b04d8c6cb706e78cb95e746d8f12089d95/src/main/java/org/geolatte/common/dataformats/json/jackson/DefaultFeature.java#L79-L91 |
DDTH/ddth-kafka | src/main/java/com/github/ddth/kafka/KafkaClient.java | KafkaClient.sendMessageRaw | public Future<RecordMetadata> sendMessageRaw(ProducerType type, KafkaMessage message) {
return sendMessageRaw(DEFAULT_PRODUCER_TYPE, message, null);
} | java | public Future<RecordMetadata> sendMessageRaw(ProducerType type, KafkaMessage message) {
return sendMessageRaw(DEFAULT_PRODUCER_TYPE, message, null);
} | [
"public",
"Future",
"<",
"RecordMetadata",
">",
"sendMessageRaw",
"(",
"ProducerType",
"type",
",",
"KafkaMessage",
"message",
")",
"{",
"return",
"sendMessageRaw",
"(",
"DEFAULT_PRODUCER_TYPE",
",",
"message",
",",
"null",
")",
";",
"}"
] | Sends a message asynchronously, specifying {@link ProducerType}.
<p>
This methods returns the underlying Kafka producer's output directly to
caller, not converting {@link RecordMetadata} to {@link KafkaMessage}.
</p>
@param type
@param message
@return
@since 1.3.1 | [
"Sends",
"a",
"message",
"asynchronously",
"specifying",
"{",
"@link",
"ProducerType",
"}",
"."
] | train | https://github.com/DDTH/ddth-kafka/blob/aaeb8536e28a109ac0b69022f0ea4bbf5696b76f/src/main/java/com/github/ddth/kafka/KafkaClient.java#L796-L798 |
zk1931/jzab | src/main/java/com/github/zk1931/jzab/SimpleLog.java | SimpleLog.firstDivergingPoint | @Override
public DivergingTuple firstDivergingPoint(Zxid zxid) throws IOException {
SimpleLogIterator iter =
(SimpleLogIterator)getIterator(Zxid.ZXID_NOT_EXIST);
Zxid prevZxid = Zxid.ZXID_NOT_EXIST;
while (iter.hasNext()) {
Zxid curZxid = iter.next().getZxid();
if (curZxid.compareTo(zxid) == 0) {
return new DivergingTuple(iter, zxid);
}
if (curZxid.compareTo(zxid) > 0) {
iter.backward();
return new DivergingTuple(iter, prevZxid);
}
prevZxid = curZxid;
}
return new DivergingTuple(iter, prevZxid);
} | java | @Override
public DivergingTuple firstDivergingPoint(Zxid zxid) throws IOException {
SimpleLogIterator iter =
(SimpleLogIterator)getIterator(Zxid.ZXID_NOT_EXIST);
Zxid prevZxid = Zxid.ZXID_NOT_EXIST;
while (iter.hasNext()) {
Zxid curZxid = iter.next().getZxid();
if (curZxid.compareTo(zxid) == 0) {
return new DivergingTuple(iter, zxid);
}
if (curZxid.compareTo(zxid) > 0) {
iter.backward();
return new DivergingTuple(iter, prevZxid);
}
prevZxid = curZxid;
}
return new DivergingTuple(iter, prevZxid);
} | [
"@",
"Override",
"public",
"DivergingTuple",
"firstDivergingPoint",
"(",
"Zxid",
"zxid",
")",
"throws",
"IOException",
"{",
"SimpleLogIterator",
"iter",
"=",
"(",
"SimpleLogIterator",
")",
"getIterator",
"(",
"Zxid",
".",
"ZXID_NOT_EXIST",
")",
";",
"Zxid",
"prevZ... | See {@link Log#firstDivergingPoint}.
@param zxid the id of the transaction.
@return a tuple holds first diverging zxid and an iterator points to
subsequent transactions.
@throws IOException in case of IO failures | [
"See",
"{",
"@link",
"Log#firstDivergingPoint",
"}",
"."
] | train | https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/SimpleLog.java#L246-L263 |
RestDocArchive/restdoc-api | src/main/java/org/restdoc/api/util/RestDocObject.java | RestDocObject.setAdditionalField | @JsonAnySetter
public void setAdditionalField(final String key, final Object value) {
this.additionalFields.put(key, value);
} | java | @JsonAnySetter
public void setAdditionalField(final String key, final Object value) {
this.additionalFields.put(key, value);
} | [
"@",
"JsonAnySetter",
"public",
"void",
"setAdditionalField",
"(",
"final",
"String",
"key",
",",
"final",
"Object",
"value",
")",
"{",
"this",
".",
"additionalFields",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"}"
] | Add additional field
@param key the field name
@param value the field value | [
"Add",
"additional",
"field"
] | train | https://github.com/RestDocArchive/restdoc-api/blob/4bda600d0303229518abf13dbb6ca6a84b4de415/src/main/java/org/restdoc/api/util/RestDocObject.java#L47-L50 |
airbnb/lottie-android | lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java | LottieAnimationView.setAnimation | public void setAnimation(JsonReader reader, @Nullable String cacheKey) {
setCompositionTask(LottieCompositionFactory.fromJsonReader(reader, cacheKey));
} | java | public void setAnimation(JsonReader reader, @Nullable String cacheKey) {
setCompositionTask(LottieCompositionFactory.fromJsonReader(reader, cacheKey));
} | [
"public",
"void",
"setAnimation",
"(",
"JsonReader",
"reader",
",",
"@",
"Nullable",
"String",
"cacheKey",
")",
"{",
"setCompositionTask",
"(",
"LottieCompositionFactory",
".",
"fromJsonReader",
"(",
"reader",
",",
"cacheKey",
")",
")",
";",
"}"
] | Sets the animation from a JSONReader.
This will load and deserialize the file asynchronously.
<p>
This is particularly useful for animations loaded from the network. You can fetch the
bodymovin json from the network and pass it directly here. | [
"Sets",
"the",
"animation",
"from",
"a",
"JSONReader",
".",
"This",
"will",
"load",
"and",
"deserialize",
"the",
"file",
"asynchronously",
".",
"<p",
">",
"This",
"is",
"particularly",
"useful",
"for",
"animations",
"loaded",
"from",
"the",
"network",
".",
"... | train | https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/LottieAnimationView.java#L333-L335 |
ReactiveX/RxJavaAsyncUtil | src/main/java/rx/util/async/Async.java | Async.startFuture | public static <T> Observable<T> startFuture(Func0<? extends Future<? extends T>> functionAsync) {
return OperatorStartFuture.startFuture(functionAsync);
} | java | public static <T> Observable<T> startFuture(Func0<? extends Future<? extends T>> functionAsync) {
return OperatorStartFuture.startFuture(functionAsync);
} | [
"public",
"static",
"<",
"T",
">",
"Observable",
"<",
"T",
">",
"startFuture",
"(",
"Func0",
"<",
"?",
"extends",
"Future",
"<",
"?",
"extends",
"T",
">",
">",
"functionAsync",
")",
"{",
"return",
"OperatorStartFuture",
".",
"startFuture",
"(",
"functionAs... | Invokes the asynchronous function immediately, surfacing the result through an Observable.
<p>
<em>Important note</em> subscribing to the resulting Observable blocks until the future completes.
<p>
<img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/startFuture.png" alt="">
@param <T> the result type
@param functionAsync the asynchronous function to run
@return an Observable that surfaces the result of the future
@see #startFuture(rx.functions.Func0, rx.Scheduler)
@see <a href="https://github.com/ReactiveX/RxJava/wiki/Async-Operators#wiki-startfuture">RxJava Wiki: startFuture()</a> | [
"Invokes",
"the",
"asynchronous",
"function",
"immediately",
"surfacing",
"the",
"result",
"through",
"an",
"Observable",
".",
"<p",
">",
"<em",
">",
"Important",
"note<",
"/",
"em",
">",
"subscribing",
"to",
"the",
"resulting",
"Observable",
"blocks",
"until",
... | train | https://github.com/ReactiveX/RxJavaAsyncUtil/blob/6294e1da30e639df79f76399906229314c14e74d/src/main/java/rx/util/async/Async.java#L1765-L1767 |
calrissian/mango | mango-core/src/main/java/org/calrissian/mango/collect/CloseableIterables.java | CloseableIterables.transform | public static <F, T> CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function) {
return wrap(Iterables.transform(iterable, function::apply), iterable);
} | java | public static <F, T> CloseableIterable<T> transform(final CloseableIterable<F> iterable, final Function<? super F, ? extends T> function) {
return wrap(Iterables.transform(iterable, function::apply), iterable);
} | [
"public",
"static",
"<",
"F",
",",
"T",
">",
"CloseableIterable",
"<",
"T",
">",
"transform",
"(",
"final",
"CloseableIterable",
"<",
"F",
">",
"iterable",
",",
"final",
"Function",
"<",
"?",
"super",
"F",
",",
"?",
"extends",
"T",
">",
"function",
")"... | Returns an iterable that applies {@code function} to each element of {@code
fromIterable}. | [
"Returns",
"an",
"iterable",
"that",
"applies",
"{"
] | train | https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/collect/CloseableIterables.java#L226-L228 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.