repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
xiaosunzhu/resource-utils | src/main/java/net/sunyijun/resource/config/Configs.java | Configs.getHavePathSelfConfig | public static String getHavePathSelfConfig(IConfigKeyWithPath key) {
String configAbsoluteClassPath = key.getConfigPath();
return getSelfConfig(configAbsoluteClassPath, key);
} | java | public static String getHavePathSelfConfig(IConfigKeyWithPath key) {
String configAbsoluteClassPath = key.getConfigPath();
return getSelfConfig(configAbsoluteClassPath, key);
} | [
"public",
"static",
"String",
"getHavePathSelfConfig",
"(",
"IConfigKeyWithPath",
"key",
")",
"{",
"String",
"configAbsoluteClassPath",
"=",
"key",
".",
"getConfigPath",
"(",
")",
";",
"return",
"getSelfConfig",
"(",
"configAbsoluteClassPath",
",",
"key",
")",
";",
... | Get self config string.
@param key config key with configAbsoluteClassPath in config file
@return config value string. Return null if not add config file or not config in config file.
@see #addSelfConfigs(String, OneProperties) | [
"Get",
"self",
"config",
"string",
"."
] | train | https://github.com/xiaosunzhu/resource-utils/blob/4f2bf3f36df10195a978f122ed682ba1eb0462b5/src/main/java/net/sunyijun/resource/config/Configs.java#L336-L339 |
amzn/ion-java | src/com/amazon/ion/impl/_Private_Utils.java | _Private_Utils.symtabExtends | public static boolean symtabExtends(SymbolTable superset, SymbolTable subset)
{
assert superset.isSystemTable() || superset.isLocalTable();
assert subset.isSystemTable() || subset.isLocalTable();
// NB: system symtab 1.0 is a singleton, hence if both symtabs
// are one this will be true.
if (superset == subset) return true;
// If the subset's symtab is a system symtab, the superset's is always
// an extension of the subset's as system symtab-ness is irrelevant to
// the conditions for copy opt. to be safe.
// TODO amzn/ion-java/issues/24 System symtab-ness ARE relevant if there's multiple
// versions.
if (subset.isSystemTable()) return true;
// From here on, subset is a LST because isSystemTable() is false.
if (superset.isLocalTable())
{
if (superset instanceof LocalSymbolTable && subset instanceof LocalSymbolTable)
{
// use the internal comparison
return ((LocalSymbolTable) superset).symtabExtends(subset);
}
// TODO reason about symbol tables that don't extend LocalSymbolTable but are still local
return localSymtabExtends(superset, subset);
}
// From here on, superset is a system symtab.
// If LST subset has no local symbols or imports, and it's system
// symbols are same as those of system symtab superset's, then
// superset extends subset
return subset.getMaxId() == superset.getMaxId();
} | java | public static boolean symtabExtends(SymbolTable superset, SymbolTable subset)
{
assert superset.isSystemTable() || superset.isLocalTable();
assert subset.isSystemTable() || subset.isLocalTable();
// NB: system symtab 1.0 is a singleton, hence if both symtabs
// are one this will be true.
if (superset == subset) return true;
// If the subset's symtab is a system symtab, the superset's is always
// an extension of the subset's as system symtab-ness is irrelevant to
// the conditions for copy opt. to be safe.
// TODO amzn/ion-java/issues/24 System symtab-ness ARE relevant if there's multiple
// versions.
if (subset.isSystemTable()) return true;
// From here on, subset is a LST because isSystemTable() is false.
if (superset.isLocalTable())
{
if (superset instanceof LocalSymbolTable && subset instanceof LocalSymbolTable)
{
// use the internal comparison
return ((LocalSymbolTable) superset).symtabExtends(subset);
}
// TODO reason about symbol tables that don't extend LocalSymbolTable but are still local
return localSymtabExtends(superset, subset);
}
// From here on, superset is a system symtab.
// If LST subset has no local symbols or imports, and it's system
// symbols are same as those of system symtab superset's, then
// superset extends subset
return subset.getMaxId() == superset.getMaxId();
} | [
"public",
"static",
"boolean",
"symtabExtends",
"(",
"SymbolTable",
"superset",
",",
"SymbolTable",
"subset",
")",
"{",
"assert",
"superset",
".",
"isSystemTable",
"(",
")",
"||",
"superset",
".",
"isLocalTable",
"(",
")",
";",
"assert",
"subset",
".",
"isSyst... | Determines whether the passed-in {@code superset} symtab is an extension
of {@code subset}.
<p>
If both are LSTs, their imported tables and locally declared symbols are
exhaustively checked, which can be expensive. Callers of this method
should cache the results of these comparisons.
@param superset
either a system or local symbol table
@param subset
either a system or local symbol table
@return true if {@code superset} extends {@code subset}, false if not | [
"Determines",
"whether",
"the",
"passed",
"-",
"in",
"{",
"@code",
"superset",
"}",
"symtab",
"is",
"an",
"extension",
"of",
"{",
"@code",
"subset",
"}",
".",
"<p",
">",
"If",
"both",
"are",
"LSTs",
"their",
"imported",
"tables",
"and",
"locally",
"decla... | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/_Private_Utils.java#L950-L985 |
alkacon/opencms-core | src/org/opencms/ade/configuration/CmsADEManager.java | CmsADEManager.getSubSiteRoot | public String getSubSiteRoot(CmsObject cms, String rootPath) {
CmsADEConfigData configData = lookupConfiguration(cms, rootPath);
String basePath = configData.getBasePath();
String siteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);
if (siteRoot == null) {
siteRoot = "";
}
if ((basePath == null) || !basePath.startsWith(siteRoot)) {
// the subsite root should always be below the site root
return siteRoot;
} else {
return basePath;
}
} | java | public String getSubSiteRoot(CmsObject cms, String rootPath) {
CmsADEConfigData configData = lookupConfiguration(cms, rootPath);
String basePath = configData.getBasePath();
String siteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);
if (siteRoot == null) {
siteRoot = "";
}
if ((basePath == null) || !basePath.startsWith(siteRoot)) {
// the subsite root should always be below the site root
return siteRoot;
} else {
return basePath;
}
} | [
"public",
"String",
"getSubSiteRoot",
"(",
"CmsObject",
"cms",
",",
"String",
"rootPath",
")",
"{",
"CmsADEConfigData",
"configData",
"=",
"lookupConfiguration",
"(",
"cms",
",",
"rootPath",
")",
";",
"String",
"basePath",
"=",
"configData",
".",
"getBasePath",
... | Tries to get the subsite root for a given resource root path.<p>
@param cms the current CMS context
@param rootPath the root path for which the subsite root should be found
@return the subsite root | [
"Tries",
"to",
"get",
"the",
"subsite",
"root",
"for",
"a",
"given",
"resource",
"root",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L924-L938 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/DateUtilities.java | DateUtilities.getCalendar | public static Calendar getCalendar(TimeZone tz, Locale locale)
{
if(tz == null)
tz = getCurrentTimeZone();
if(locale == null)
locale = getCurrentLocale();
return Calendar.getInstance(tz, locale);
} | java | public static Calendar getCalendar(TimeZone tz, Locale locale)
{
if(tz == null)
tz = getCurrentTimeZone();
if(locale == null)
locale = getCurrentLocale();
return Calendar.getInstance(tz, locale);
} | [
"public",
"static",
"Calendar",
"getCalendar",
"(",
"TimeZone",
"tz",
",",
"Locale",
"locale",
")",
"{",
"if",
"(",
"tz",
"==",
"null",
")",
"tz",
"=",
"getCurrentTimeZone",
"(",
")",
";",
"if",
"(",
"locale",
"==",
"null",
")",
"locale",
"=",
"getCurr... | Returns a new calendar object using the given timezone and locale.
@param tz The timezone associated with the new calendar
@param locale The locale associated with the new calendar
@return A new calendar object for the given timezone and locale | [
"Returns",
"a",
"new",
"calendar",
"object",
"using",
"the",
"given",
"timezone",
"and",
"locale",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/DateUtilities.java#L195-L202 |
apache/groovy | subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java | DateTimeExtensions.rightShift | public static Period rightShift(final LocalDate self, LocalDate other) {
return Period.between(self, other);
} | java | public static Period rightShift(final LocalDate self, LocalDate other) {
return Period.between(self, other);
} | [
"public",
"static",
"Period",
"rightShift",
"(",
"final",
"LocalDate",
"self",
",",
"LocalDate",
"other",
")",
"{",
"return",
"Period",
".",
"between",
"(",
"self",
",",
"other",
")",
";",
"}"
] | Returns a {@link java.time.Period} equivalent to the time between this date (inclusive)
and the provided {@link java.time.LocalDate} (exclusive).
@param self a LocalDate
@param other another LocalDate
@return a Period representing the time between the two LocalDates
@since 2.5.0 | [
"Returns",
"a",
"{",
"@link",
"java",
".",
"time",
".",
"Period",
"}",
"equivalent",
"to",
"the",
"time",
"between",
"this",
"date",
"(",
"inclusive",
")",
"and",
"the",
"provided",
"{",
"@link",
"java",
".",
"time",
".",
"LocalDate",
"}",
"(",
"exclus... | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L612-L614 |
classgraph/classgraph | src/main/java/io/github/classgraph/ClassInfo.java | ClassInfo.addScannedClass | static ClassInfo addScannedClass(final String className, final int classModifiers,
final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final Resource classfileResource) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, classfileResource));
} else {
// There was a previous placeholder ClassInfo class added, due to the class being referred
// to as a superclass, interface or annotation. The isScannedClass field should be false
// in this case, since the actual class definition wasn't reached before now.
if (classInfo.isScannedClass) {
// The class should not have been scanned more than once, because of classpath masking
throw new IllegalArgumentException("Class " + className
+ " should not have been encountered more than once due to classpath masking --"
+ " please report this bug at: https://github.com/classgraph/classgraph/issues");
}
}
// Mark the class as scanned
classInfo.isScannedClass = true;
// Mark the class as non-external if it is a whitelisted class
classInfo.isExternalClass = isExternalClass;
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
classInfo.classpathElement = classpathElement;
// Remember which classloader is used to load the class
classInfo.classLoader = classpathElement.getClassLoader();
return classInfo;
} | java | static ClassInfo addScannedClass(final String className, final int classModifiers,
final boolean isExternalClass, final Map<String, ClassInfo> classNameToClassInfo,
final ClasspathElement classpathElement, final Resource classfileResource) {
ClassInfo classInfo = classNameToClassInfo.get(className);
if (classInfo == null) {
// This is the first time this class has been seen, add it
classNameToClassInfo.put(className,
classInfo = new ClassInfo(className, classModifiers, classfileResource));
} else {
// There was a previous placeholder ClassInfo class added, due to the class being referred
// to as a superclass, interface or annotation. The isScannedClass field should be false
// in this case, since the actual class definition wasn't reached before now.
if (classInfo.isScannedClass) {
// The class should not have been scanned more than once, because of classpath masking
throw new IllegalArgumentException("Class " + className
+ " should not have been encountered more than once due to classpath masking --"
+ " please report this bug at: https://github.com/classgraph/classgraph/issues");
}
}
// Mark the class as scanned
classInfo.isScannedClass = true;
// Mark the class as non-external if it is a whitelisted class
classInfo.isExternalClass = isExternalClass;
// Remember which classpath element (zipfile / classpath root directory / module) the class was found in
classInfo.classpathElement = classpathElement;
// Remember which classloader is used to load the class
classInfo.classLoader = classpathElement.getClassLoader();
return classInfo;
} | [
"static",
"ClassInfo",
"addScannedClass",
"(",
"final",
"String",
"className",
",",
"final",
"int",
"classModifiers",
",",
"final",
"boolean",
"isExternalClass",
",",
"final",
"Map",
"<",
"String",
",",
"ClassInfo",
">",
"classNameToClassInfo",
",",
"final",
"Clas... | Add a class that has just been scanned (as opposed to just referenced by a scanned class). Not threadsafe,
should be run in single threaded context.
@param className
the class name
@param classModifiers
the class modifiers
@param isExternalClass
true if this is an external class
@param classNameToClassInfo
the map from class name to class info
@param classpathElement
the classpath element
@param classfileResource
the classfile resource
@return the class info | [
"Add",
"a",
"class",
"that",
"has",
"just",
"been",
"scanned",
"(",
"as",
"opposed",
"to",
"just",
"referenced",
"by",
"a",
"scanned",
"class",
")",
".",
"Not",
"threadsafe",
"should",
"be",
"run",
"in",
"single",
"threaded",
"context",
"."
] | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/io/github/classgraph/ClassInfo.java#L579-L612 |
google/closure-compiler | src/com/google/javascript/jscomp/BranchCoverageInstrumentationCallback.java | BranchCoverageInstrumentationCallback.newBranchInstrumentationNode | private Node newBranchInstrumentationNode(NodeTraversal traversal, Node node, int idx) {
String arrayName = createArrayName(traversal);
// Create instrumentation Node
Node getElemNode = IR.getelem(IR.name(arrayName), IR.number(idx)); // Make line number 0-based
Node exprNode = IR.exprResult(IR.assign(getElemNode, IR.trueNode()));
// Note line as instrumented
String fileName = traversal.getSourceName();
if (!instrumentationData.containsKey(fileName)) {
instrumentationData.put(fileName, new FileInstrumentationData(fileName, arrayName));
}
return exprNode.useSourceInfoIfMissingFromForTree(node);
} | java | private Node newBranchInstrumentationNode(NodeTraversal traversal, Node node, int idx) {
String arrayName = createArrayName(traversal);
// Create instrumentation Node
Node getElemNode = IR.getelem(IR.name(arrayName), IR.number(idx)); // Make line number 0-based
Node exprNode = IR.exprResult(IR.assign(getElemNode, IR.trueNode()));
// Note line as instrumented
String fileName = traversal.getSourceName();
if (!instrumentationData.containsKey(fileName)) {
instrumentationData.put(fileName, new FileInstrumentationData(fileName, arrayName));
}
return exprNode.useSourceInfoIfMissingFromForTree(node);
} | [
"private",
"Node",
"newBranchInstrumentationNode",
"(",
"NodeTraversal",
"traversal",
",",
"Node",
"node",
",",
"int",
"idx",
")",
"{",
"String",
"arrayName",
"=",
"createArrayName",
"(",
"traversal",
")",
";",
"// Create instrumentation Node",
"Node",
"getElemNode",
... | Create an assignment to the branch coverage data for the given index into the array.
@return the newly constructed assignment node. | [
"Create",
"an",
"assignment",
"to",
"the",
"branch",
"coverage",
"data",
"for",
"the",
"given",
"index",
"into",
"the",
"array",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/BranchCoverageInstrumentationCallback.java#L145-L158 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java | ServicesInner.checkStatus | public DataMigrationServiceStatusResponseInner checkStatus(String groupName, String serviceName) {
return checkStatusWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | java | public DataMigrationServiceStatusResponseInner checkStatus(String groupName, String serviceName) {
return checkStatusWithServiceResponseAsync(groupName, serviceName).toBlocking().single().body();
} | [
"public",
"DataMigrationServiceStatusResponseInner",
"checkStatus",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
")",
"{",
"return",
"checkStatusWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
")",
".",
"toBlocking",
"(",
")",
".",
"single"... | Check service health status.
The services resource is the top-level resource that represents the Data Migration Service. This action performs a health check and returns the status of the service and virtual machine size.
@param groupName Name of the resource group
@param serviceName Name of the service
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ApiErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the DataMigrationServiceStatusResponseInner object if successful. | [
"Check",
"service",
"health",
"status",
".",
"The",
"services",
"resource",
"is",
"the",
"top",
"-",
"level",
"resource",
"that",
"represents",
"the",
"Data",
"Migration",
"Service",
".",
"This",
"action",
"performs",
"a",
"health",
"check",
"and",
"returns",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L940-L942 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java | SARLQuickfixProvider.removeToPreviousSeparator | public boolean removeToPreviousSeparator(int offset, int length, IXtextDocument document, String separator)
throws BadLocationException {
// Skip spaces before the identifier until the separator
int index = offset - 1;
char c = document.getChar(index);
while (Character.isWhitespace(c)) {
index--;
c = document.getChar(index);
}
// Test if it previous non-space character is the separator
final boolean foundSeparator = document.getChar(index) == separator.charAt(0);
if (foundSeparator) {
index--;
c = document.getChar(index);
// Skip the previous spaces
while (Character.isWhitespace(c)) {
index--;
c = document.getChar(index);
}
final int delta = offset - index - 1;
document.replace(index + 1, length + delta, ""); //$NON-NLS-1$
}
return foundSeparator;
} | java | public boolean removeToPreviousSeparator(int offset, int length, IXtextDocument document, String separator)
throws BadLocationException {
// Skip spaces before the identifier until the separator
int index = offset - 1;
char c = document.getChar(index);
while (Character.isWhitespace(c)) {
index--;
c = document.getChar(index);
}
// Test if it previous non-space character is the separator
final boolean foundSeparator = document.getChar(index) == separator.charAt(0);
if (foundSeparator) {
index--;
c = document.getChar(index);
// Skip the previous spaces
while (Character.isWhitespace(c)) {
index--;
c = document.getChar(index);
}
final int delta = offset - index - 1;
document.replace(index + 1, length + delta, ""); //$NON-NLS-1$
}
return foundSeparator;
} | [
"public",
"boolean",
"removeToPreviousSeparator",
"(",
"int",
"offset",
",",
"int",
"length",
",",
"IXtextDocument",
"document",
",",
"String",
"separator",
")",
"throws",
"BadLocationException",
"{",
"// Skip spaces before the identifier until the separator",
"int",
"index... | Remove the portion of text, and the whitespaces before the text until the given separator.
@param offset the offset where to start to remove.
@param length the length of the text to remove.
@param document the document.
@param separator the separator to consider.
@return <code>true</code> if the separator was found, <code>false</code> if not.
@throws BadLocationException if there is a problem with the location of the element. | [
"Remove",
"the",
"portion",
"of",
"text",
"and",
"the",
"whitespaces",
"before",
"the",
"text",
"until",
"the",
"given",
"separator",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/quickfix/SARLQuickfixProvider.java#L329-L355 |
czyzby/gdx-lml | mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java | InterfaceService.registerController | public void registerController(final Class<?> mappedControllerClass, final ViewController controller) {
controllers.put(mappedControllerClass, controller);
if (Strings.isNotEmpty(controller.getViewId())) {
parser.getData().addActorConsumer(SCREEN_TRANSITION_ACTION_PREFIX + controller.getViewId(),
new ScreenTransitionAction(this, mappedControllerClass));
}
} | java | public void registerController(final Class<?> mappedControllerClass, final ViewController controller) {
controllers.put(mappedControllerClass, controller);
if (Strings.isNotEmpty(controller.getViewId())) {
parser.getData().addActorConsumer(SCREEN_TRANSITION_ACTION_PREFIX + controller.getViewId(),
new ScreenTransitionAction(this, mappedControllerClass));
}
} | [
"public",
"void",
"registerController",
"(",
"final",
"Class",
"<",
"?",
">",
"mappedControllerClass",
",",
"final",
"ViewController",
"controller",
")",
"{",
"controllers",
".",
"put",
"(",
"mappedControllerClass",
",",
"controller",
")",
";",
"if",
"(",
"Strin... | Allows to manually register a managed controller. For internal use mostly.
@param mappedControllerClass class with which the controller is accessible. This does not have to be controller's
actual class.
@param controller controller implementation, managing a single view. | [
"Allows",
"to",
"manually",
"register",
"a",
"managed",
"controller",
".",
"For",
"internal",
"use",
"mostly",
"."
] | train | https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/mvc/src/main/java/com/github/czyzby/autumn/mvc/component/ui/InterfaceService.java#L174-L180 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/InternalHelper.java | InternalHelper.inheritClientBehaviorsAndSetPublicProperty | public static void inheritClientBehaviorsAndSetPublicProperty(IInheritedBehaviors inheritingObject, Iterable<BatchClientBehavior> baseBehaviors) {
// implement inheritance of behaviors
List<BatchClientBehavior> customBehaviors = new ArrayList<>();
// if there were any behaviors, pre-populate the collection (ie: inherit)
if (null != baseBehaviors) {
for (BatchClientBehavior be : baseBehaviors) {
customBehaviors.add(be);
}
}
// set the public property
inheritingObject.withCustomBehaviors(customBehaviors);
} | java | public static void inheritClientBehaviorsAndSetPublicProperty(IInheritedBehaviors inheritingObject, Iterable<BatchClientBehavior> baseBehaviors) {
// implement inheritance of behaviors
List<BatchClientBehavior> customBehaviors = new ArrayList<>();
// if there were any behaviors, pre-populate the collection (ie: inherit)
if (null != baseBehaviors) {
for (BatchClientBehavior be : baseBehaviors) {
customBehaviors.add(be);
}
}
// set the public property
inheritingObject.withCustomBehaviors(customBehaviors);
} | [
"public",
"static",
"void",
"inheritClientBehaviorsAndSetPublicProperty",
"(",
"IInheritedBehaviors",
"inheritingObject",
",",
"Iterable",
"<",
"BatchClientBehavior",
">",
"baseBehaviors",
")",
"{",
"// implement inheritance of behaviors",
"List",
"<",
"BatchClientBehavior",
">... | Inherit the BatchClientBehavior classes from parent object
@param inheritingObject the inherit object
@param baseBehaviors base class behavior list | [
"Inherit",
"the",
"BatchClientBehavior",
"classes",
"from",
"parent",
"object"
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/InternalHelper.java#L19-L32 |
jaredrummler/AndroidShell | library/src/main/java/com/jaredrummler/android/shell/Shell.java | Shell.runWithEnv | @WorkerThread
public static Process runWithEnv(@NonNull String command, Map<String, String> environment) throws IOException {
String[] env;
if (environment != null && environment.size() != 0) {
Map<String, String> newEnvironment = new HashMap<>();
newEnvironment.putAll(System.getenv());
newEnvironment.putAll(environment);
int i = 0;
env = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
env[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
} else {
env = null;
}
return Runtime.getRuntime().exec(command, env);
} | java | @WorkerThread
public static Process runWithEnv(@NonNull String command, Map<String, String> environment) throws IOException {
String[] env;
if (environment != null && environment.size() != 0) {
Map<String, String> newEnvironment = new HashMap<>();
newEnvironment.putAll(System.getenv());
newEnvironment.putAll(environment);
int i = 0;
env = new String[newEnvironment.size()];
for (Map.Entry<String, String> entry : newEnvironment.entrySet()) {
env[i] = entry.getKey() + "=" + entry.getValue();
i++;
}
} else {
env = null;
}
return Runtime.getRuntime().exec(command, env);
} | [
"@",
"WorkerThread",
"public",
"static",
"Process",
"runWithEnv",
"(",
"@",
"NonNull",
"String",
"command",
",",
"Map",
"<",
"String",
",",
"String",
">",
"environment",
")",
"throws",
"IOException",
"{",
"String",
"[",
"]",
"env",
";",
"if",
"(",
"environ... | <p>This code is adapted from java.lang.ProcessBuilder.start().</p>
<p>The problem is that Android doesn't allow us to modify the map returned by ProcessBuilder.environment(), even
though the JavaDoc indicates that it should. This is because it simply returns the SystemEnvironment object that
System.getenv() gives us. The relevant portion in the source code is marked as "// android changed", so
presumably it's not the case in the original version of the Apache Harmony project.</p>
@param command
The name of the program to execute. E.g. "su" or "sh".
@param environment
Map of all environment variables
@return new {@link Process} instance.
@throws IOException
if the requested program could not be executed. | [
"<p",
">",
"This",
"code",
"is",
"adapted",
"from",
"java",
".",
"lang",
".",
"ProcessBuilder",
".",
"start",
"()",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/jaredrummler/AndroidShell/blob/0826b6f93c208b7bc95344dd20e2989d367a1e43/library/src/main/java/com/jaredrummler/android/shell/Shell.java#L203-L220 |
code4everything/util | src/main/java/com/zhazhapan/util/Checker.java | Checker.checkNull | public static Character checkNull(Character value, char elseValue) {
return checkNull(value, Character.valueOf(elseValue));
} | java | public static Character checkNull(Character value, char elseValue) {
return checkNull(value, Character.valueOf(elseValue));
} | [
"public",
"static",
"Character",
"checkNull",
"(",
"Character",
"value",
",",
"char",
"elseValue",
")",
"{",
"return",
"checkNull",
"(",
"value",
",",
"Character",
".",
"valueOf",
"(",
"elseValue",
")",
")",
";",
"}"
] | 检查Character是否为null
@param value 值
@param elseValue 为null返回的值
@return {@link Character}
@since 1.0.8 | [
"检查Character是否为null"
] | train | https://github.com/code4everything/util/blob/1fc9f0ead1108f4d7208ba7c000df4244f708418/src/main/java/com/zhazhapan/util/Checker.java#L1391-L1393 |
nguillaumin/slick2d-maven | slick2d-scalar/src/main/java/org/newdawn/slick/tools/scalar/ImageScale3x.java | ImageScale3x.getScaledImage | public BufferedImage getScaledImage()
{
RawScale3x scaler = new RawScale3x(srcData,width,height);
BufferedImage image = new BufferedImage(width*3,height*3,BufferedImage.TYPE_INT_ARGB);
image.setRGB(0,0,width*3,height*3,scaler.getScaledData(),0,width*3);
return image;
} | java | public BufferedImage getScaledImage()
{
RawScale3x scaler = new RawScale3x(srcData,width,height);
BufferedImage image = new BufferedImage(width*3,height*3,BufferedImage.TYPE_INT_ARGB);
image.setRGB(0,0,width*3,height*3,scaler.getScaledData(),0,width*3);
return image;
} | [
"public",
"BufferedImage",
"getScaledImage",
"(",
")",
"{",
"RawScale3x",
"scaler",
"=",
"new",
"RawScale3x",
"(",
"srcData",
",",
"width",
",",
"height",
")",
";",
"BufferedImage",
"image",
"=",
"new",
"BufferedImage",
"(",
"width",
"*",
"3",
",",
"height",... | Retrieve the scaled image. Note this is the method that actually
does the work so it may take some time to return
@return The newly scaled image | [
"Retrieve",
"the",
"scaled",
"image",
".",
"Note",
"this",
"is",
"the",
"method",
"that",
"actually",
"does",
"the",
"work",
"so",
"it",
"may",
"take",
"some",
"time",
"to",
"return"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-scalar/src/main/java/org/newdawn/slick/tools/scalar/ImageScale3x.java#L42-L50 |
google/closure-templates | java/src/com/google/template/soy/jbcsrc/shared/Names.java | Names.javaFileName | public static String javaFileName(String soyNamespace, String fileName) {
checkArgument(
BaseUtils.isDottedIdentifier(soyNamespace),
"%s is not a valid soy namspace name.",
soyNamespace);
return (CLASS_PREFIX + soyNamespace).replace('.', '/') + '/' + fileName;
} | java | public static String javaFileName(String soyNamespace, String fileName) {
checkArgument(
BaseUtils.isDottedIdentifier(soyNamespace),
"%s is not a valid soy namspace name.",
soyNamespace);
return (CLASS_PREFIX + soyNamespace).replace('.', '/') + '/' + fileName;
} | [
"public",
"static",
"String",
"javaFileName",
"(",
"String",
"soyNamespace",
",",
"String",
"fileName",
")",
"{",
"checkArgument",
"(",
"BaseUtils",
".",
"isDottedIdentifier",
"(",
"soyNamespace",
")",
",",
"\"%s is not a valid soy namspace name.\"",
",",
"soyNamespace"... | Given the soy namespace and file name returns the path where the corresponding resource should
be stored. | [
"Given",
"the",
"soy",
"namespace",
"and",
"file",
"name",
"returns",
"the",
"path",
"where",
"the",
"corresponding",
"resource",
"should",
"be",
"stored",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/shared/Names.java#L58-L64 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/common/ConfigUtils.java | ConfigUtils.populateCustomRequestParameterMap | public void populateCustomRequestParameterMap(ConfigurationAdmin configAdmin, HashMap<String, String> paramMapToPopulate, String[] configuredCustomRequestParams, String configAttrName, String configAttrValue) {
if (configuredCustomRequestParams == null) {
return;
}
for (String configuredParameter : configuredCustomRequestParams) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Configured custom request param [" + configuredParameter + "]");
}
Configuration config = getConfigurationFromConfigAdmin(configAdmin, configuredParameter);
if (config != null) {
addCustomRequestParameterValueToMap(config, paramMapToPopulate, configAttrName, configAttrValue);
}
}
} | java | public void populateCustomRequestParameterMap(ConfigurationAdmin configAdmin, HashMap<String, String> paramMapToPopulate, String[] configuredCustomRequestParams, String configAttrName, String configAttrValue) {
if (configuredCustomRequestParams == null) {
return;
}
for (String configuredParameter : configuredCustomRequestParams) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Configured custom request param [" + configuredParameter + "]");
}
Configuration config = getConfigurationFromConfigAdmin(configAdmin, configuredParameter);
if (config != null) {
addCustomRequestParameterValueToMap(config, paramMapToPopulate, configAttrName, configAttrValue);
}
}
} | [
"public",
"void",
"populateCustomRequestParameterMap",
"(",
"ConfigurationAdmin",
"configAdmin",
",",
"HashMap",
"<",
"String",
",",
"String",
">",
"paramMapToPopulate",
",",
"String",
"[",
"]",
"configuredCustomRequestParams",
",",
"String",
"configAttrName",
",",
"Str... | Populates a map of custom request parameter names and values to add to a certain OpenID Connect request type.
@param configAdmin
Config admin that has access to the necessary server configuration properties.
@param paramMapToPopulate
Request-specific map of custom parameters to populate (for example, a map of parameters to add to authorization
requests).
@param configuredCustomRequestParams
List of configured custom parameter elements for a particular request type.
@param configAttrName
Name of the config attribute that specifies the parameter name.
@param configAttrValue
Name of the config attribute that specifies the parameter value. | [
"Populates",
"a",
"map",
"of",
"custom",
"request",
"parameter",
"names",
"and",
"values",
"to",
"add",
"to",
"a",
"certain",
"OpenID",
"Connect",
"request",
"type",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.openidconnect.clients.common/src/com/ibm/ws/security/openidconnect/common/ConfigUtils.java#L408-L421 |
arquillian/arquillian-core | container/spi/src/main/java/org/jboss/arquillian/container/spi/client/deployment/Validate.java | Validate.notNull | public static void notNull(final Object obj, final String message) throws IllegalArgumentException {
if (obj == null) {
throw new IllegalArgumentException(message);
}
} | java | public static void notNull(final Object obj, final String message) throws IllegalArgumentException {
if (obj == null) {
throw new IllegalArgumentException(message);
}
} | [
"public",
"static",
"void",
"notNull",
"(",
"final",
"Object",
"obj",
",",
"final",
"String",
"message",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"obj",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"message",
")",
... | Checks that object is not null, throws exception if it is.
@param obj
The object to check
@param message
The exception message
@throws IllegalArgumentException
Thrown if obj is null | [
"Checks",
"that",
"object",
"is",
"not",
"null",
"throws",
"exception",
"if",
"it",
"is",
"."
] | train | https://github.com/arquillian/arquillian-core/blob/a85b91789b80cc77e0f0c2e2abac65c2255c0a81/container/spi/src/main/java/org/jboss/arquillian/container/spi/client/deployment/Validate.java#L85-L89 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getCurrencyInfo | public void getCurrencyInfo(int[] ids, Callback<List<Currency>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getCurrencyInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | java | public void getCurrencyInfo(int[] ids, Callback<List<Currency>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ids));
gw2API.getCurrencyInfo(processIds(ids), GuildWars2.lang.getValue()).enqueue(callback);
} | [
"public",
"void",
"getCurrencyInfo",
"(",
"int",
"[",
"]",
"ids",
",",
"Callback",
"<",
"List",
"<",
"Currency",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"NullPointerException",
"{",
"isParamValid",
"(",
"new",
"ParamChecker",
"(",
"ids... | For more info on Currency API go <a href="https://wiki.guildwars2.com/wiki/API:2/currencies">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param ids list of currency id
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception empty ID list
@throws NullPointerException if given {@link Callback} is empty
@see Currency currency info | [
"For",
"more",
"info",
"on",
"Currency",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"currencies",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">",
"Give",
"user"... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1258-L1261 |
neo4j-contrib/neo4j-apoc-procedures | src/main/java/apoc/es/ElasticSearch.java | ElasticSearch.getQueryUrl | protected String getQueryUrl(String hostOrKey, String index, String type, String id, Object query) {
return getElasticSearchUrl(hostOrKey) + formatQueryUrl(index, type, id, query);
} | java | protected String getQueryUrl(String hostOrKey, String index, String type, String id, Object query) {
return getElasticSearchUrl(hostOrKey) + formatQueryUrl(index, type, id, query);
} | [
"protected",
"String",
"getQueryUrl",
"(",
"String",
"hostOrKey",
",",
"String",
"index",
",",
"String",
"type",
",",
"String",
"id",
",",
"Object",
"query",
")",
"{",
"return",
"getElasticSearchUrl",
"(",
"hostOrKey",
")",
"+",
"formatQueryUrl",
"(",
"index",... | Get the full Elasticsearch url
@param hostOrKey
@param index
@param type
@param id
@param query
@return | [
"Get",
"the",
"full",
"Elasticsearch",
"url"
] | train | https://github.com/neo4j-contrib/neo4j-apoc-procedures/blob/e8386975d1c512c0e4388a1a61f5496121c04f86/src/main/java/apoc/es/ElasticSearch.java#L51-L53 |
AzureAD/azure-activedirectory-library-for-java | src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java | AuthenticationContext.acquireDeviceCode | public Future<DeviceCode> acquireDeviceCode(final String clientId, final String resource,
final AuthenticationCallback<DeviceCode> callback) {
validateDeviceCodeRequestInput(clientId, resource);
return service.submit(
new AcquireDeviceCodeCallable(this, clientId, resource, callback));
} | java | public Future<DeviceCode> acquireDeviceCode(final String clientId, final String resource,
final AuthenticationCallback<DeviceCode> callback) {
validateDeviceCodeRequestInput(clientId, resource);
return service.submit(
new AcquireDeviceCodeCallable(this, clientId, resource, callback));
} | [
"public",
"Future",
"<",
"DeviceCode",
">",
"acquireDeviceCode",
"(",
"final",
"String",
"clientId",
",",
"final",
"String",
"resource",
",",
"final",
"AuthenticationCallback",
"<",
"DeviceCode",
">",
"callback",
")",
"{",
"validateDeviceCodeRequestInput",
"(",
"cli... | Acquires a device code from the authority
@param clientId Identifier of the client requesting the token
@param resource Identifier of the target resource that is the recipient of the
requested token.
@param callback optional callback object for non-blocking execution.
@return A {@link Future} object representing the {@link DeviceCode} of the call.
It contains device code, user code, its expiration date,
message which should be displayed to the user.
@throws AuthenticationException thrown if the device code is not acquired successfully | [
"Acquires",
"a",
"device",
"code",
"from",
"the",
"authority"
] | train | https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/main/java/com/microsoft/aad/adal4j/AuthenticationContext.java#L620-L625 |
astrapi69/jaulp-wicket | jaulp-wicket-dialogs/src/main/java/de/alpharogroup/wicket/dialogs/ajax/modal/BaseModalWindow.java | BaseModalWindow.newContent | protected Component newContent(final String contentId, final IModel<T> model)
{
return new BaseModalPanel<T>(contentId, model)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected void onCancel(final AjaxRequestTarget target)
{
BaseModalWindow.this.onCancel(target);
}
/**
* {@inheritDoc}
*/
@Override
protected void onSelect(final AjaxRequestTarget target, final T object)
{
BaseModalWindow.this.onSelect(target, object);
}
};
} | java | protected Component newContent(final String contentId, final IModel<T> model)
{
return new BaseModalPanel<T>(contentId, model)
{
/**
* The serialVersionUID.
*/
private static final long serialVersionUID = 1L;
/**
* {@inheritDoc}
*/
@Override
protected void onCancel(final AjaxRequestTarget target)
{
BaseModalWindow.this.onCancel(target);
}
/**
* {@inheritDoc}
*/
@Override
protected void onSelect(final AjaxRequestTarget target, final T object)
{
BaseModalWindow.this.onSelect(target, object);
}
};
} | [
"protected",
"Component",
"newContent",
"(",
"final",
"String",
"contentId",
",",
"final",
"IModel",
"<",
"T",
">",
"model",
")",
"{",
"return",
"new",
"BaseModalPanel",
"<",
"T",
">",
"(",
"contentId",
",",
"model",
")",
"{",
"/**\r\n\t\t\t * The serialVersio... | Factory method for create the new {@link Component} for the content. This method is invoked
in the constructor from the derived classes and can be overridden so users can provide their
own version of a new {@link Component} for the content.
@param contentId
the content id
@param model
the model
@return the new {@link Component} for the content. | [
"Factory",
"method",
"for",
"create",
"the",
"new",
"{",
"@link",
"Component",
"}",
"for",
"the",
"content",
".",
"This",
"method",
"is",
"invoked",
"in",
"the",
"constructor",
"from",
"the",
"derived",
"classes",
"and",
"can",
"be",
"overridden",
"so",
"u... | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-dialogs/src/main/java/de/alpharogroup/wicket/dialogs/ajax/modal/BaseModalWindow.java#L97-L124 |
Stratio/bdt | src/main/java/com/stratio/qa/specs/CommonG.java | CommonG.generateRequest | @Deprecated
public Future<Response> generateRequest(String requestType, boolean secure, String endPoint, String data, String type, String codeBase64) throws Exception {
return generateRequest(requestType, false, null, null, endPoint, data, type, "");
} | java | @Deprecated
public Future<Response> generateRequest(String requestType, boolean secure, String endPoint, String data, String type, String codeBase64) throws Exception {
return generateRequest(requestType, false, null, null, endPoint, data, type, "");
} | [
"@",
"Deprecated",
"public",
"Future",
"<",
"Response",
">",
"generateRequest",
"(",
"String",
"requestType",
",",
"boolean",
"secure",
",",
"String",
"endPoint",
",",
"String",
"data",
",",
"String",
"type",
",",
"String",
"codeBase64",
")",
"throws",
"Except... | Generates the request based on the type of request, the end point, the data and type passed
@param requestType type of request to be sent
@param secure type of protocol
@param endPoint end point to sent the request to
@param data to be sent for PUT/POST requests
@param type type of data to be sent (json|string)
@throws Exception exception | [
"Generates",
"the",
"request",
"based",
"on",
"the",
"type",
"of",
"request",
"the",
"end",
"point",
"the",
"data",
"and",
"type",
"passed"
] | train | https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L1340-L1343 |
MariaDB/mariadb-connector-j | src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ed25519/math/GroupElement.java | GroupElement.select | org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement select(final int pos, final int b) {
// Is r_i negative?
final int bnegative = Utils.negative(b);
// |r_i|
final int babs = b - (((-bnegative) & b) << 1);
// 16^i |r_i| B
final org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement t = this.curve
.getZero(Representation.PRECOMP)
.cmov(this.precmp[pos][0], Utils.equal(babs, 1))
.cmov(this.precmp[pos][1], Utils.equal(babs, 2))
.cmov(this.precmp[pos][2], Utils.equal(babs, 3))
.cmov(this.precmp[pos][3], Utils.equal(babs, 4))
.cmov(this.precmp[pos][4], Utils.equal(babs, 5))
.cmov(this.precmp[pos][5], Utils.equal(babs, 6))
.cmov(this.precmp[pos][6], Utils.equal(babs, 7))
.cmov(this.precmp[pos][7], Utils.equal(babs, 8));
// -16^i |r_i| B
final org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement tminus = precomp(curve, t.Y,
t.X, t.Z.negate());
// 16^i r_i B
return t.cmov(tminus, bnegative);
} | java | org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement select(final int pos, final int b) {
// Is r_i negative?
final int bnegative = Utils.negative(b);
// |r_i|
final int babs = b - (((-bnegative) & b) << 1);
// 16^i |r_i| B
final org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement t = this.curve
.getZero(Representation.PRECOMP)
.cmov(this.precmp[pos][0], Utils.equal(babs, 1))
.cmov(this.precmp[pos][1], Utils.equal(babs, 2))
.cmov(this.precmp[pos][2], Utils.equal(babs, 3))
.cmov(this.precmp[pos][3], Utils.equal(babs, 4))
.cmov(this.precmp[pos][4], Utils.equal(babs, 5))
.cmov(this.precmp[pos][5], Utils.equal(babs, 6))
.cmov(this.precmp[pos][6], Utils.equal(babs, 7))
.cmov(this.precmp[pos][7], Utils.equal(babs, 8));
// -16^i |r_i| B
final org.mariadb.jdbc.internal.com.send.authentication.ed25519.math.GroupElement tminus = precomp(curve, t.Y,
t.X, t.Z.negate());
// 16^i r_i B
return t.cmov(tminus, bnegative);
} | [
"org",
".",
"mariadb",
".",
"jdbc",
".",
"internal",
".",
"com",
".",
"send",
".",
"authentication",
".",
"ed25519",
".",
"math",
".",
"GroupElement",
"select",
"(",
"final",
"int",
"pos",
",",
"final",
"int",
"b",
")",
"{",
"// Is r_i negative?",
"final... | Look up $16^i r_i B$ in the precomputed table.
<p>
No secret array indices, no secret branching. Constant time.
<p>
Must have previously precomputed.
<p>
Method is package private only so that tests run.
@param pos $= i/2$ for $i$ in $\{0, 2, 4,..., 62\}$
@param b $= r_i$
@return the GroupElement | [
"Look",
"up",
"$16^i",
"r_i",
"B$",
"in",
"the",
"precomputed",
"table",
".",
"<p",
">",
"No",
"secret",
"array",
"indices",
"no",
"secret",
"branching",
".",
"Constant",
"time",
".",
"<p",
">",
"Must",
"have",
"previously",
"precomputed",
".",
"<p",
">"... | train | https://github.com/MariaDB/mariadb-connector-j/blob/d148c7cd347c4680617be65d9e511b289d38a30b/src/main/java/org/mariadb/jdbc/internal/com/send/authentication/ed25519/math/GroupElement.java#L886-L908 |
RoaringBitmap/RoaringBitmap | roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java | BufferUtil.cardinalityInBitmapRange | public static int cardinalityInBitmapRange(LongBuffer bitmap, int start, int end) {
if (isBackedBySimpleArray(bitmap)) {
return Util.cardinalityInBitmapRange(bitmap.array(), start, end);
}
if (start >= end) {
return 0;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
return Long.bitCount(bitmap.get(firstword) & ((~0L << start) & (~0L >>> -end)));
}
int answer = Long.bitCount(bitmap.get(firstword) & (~0L << start));
for (int i = firstword + 1; i < endword; i++) {
answer += Long.bitCount(bitmap.get(i));
}
answer += Long.bitCount(bitmap.get(endword) & (~0L >>> -end));
return answer;
} | java | public static int cardinalityInBitmapRange(LongBuffer bitmap, int start, int end) {
if (isBackedBySimpleArray(bitmap)) {
return Util.cardinalityInBitmapRange(bitmap.array(), start, end);
}
if (start >= end) {
return 0;
}
int firstword = start / 64;
int endword = (end - 1) / 64;
if (firstword == endword) {
return Long.bitCount(bitmap.get(firstword) & ((~0L << start) & (~0L >>> -end)));
}
int answer = Long.bitCount(bitmap.get(firstword) & (~0L << start));
for (int i = firstword + 1; i < endword; i++) {
answer += Long.bitCount(bitmap.get(i));
}
answer += Long.bitCount(bitmap.get(endword) & (~0L >>> -end));
return answer;
} | [
"public",
"static",
"int",
"cardinalityInBitmapRange",
"(",
"LongBuffer",
"bitmap",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"if",
"(",
"isBackedBySimpleArray",
"(",
"bitmap",
")",
")",
"{",
"return",
"Util",
".",
"cardinalityInBitmapRange",
"(",
"bit... | Hamming weight of the bitset in the range
start, start+1,..., end-1
@param bitmap array of words representing a bitset
@param start first index (inclusive)
@param end last index (exclusive)
@return the hamming weight of the corresponding range | [
"Hamming",
"weight",
"of",
"the",
"bitset",
"in",
"the",
"range",
"start",
"start",
"+",
"1",
"...",
"end",
"-",
"1"
] | train | https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/BufferUtil.java#L402-L420 |
otto-de/edison-hal | src/main/java/de/otto/edison/hal/CuriTemplate.java | CuriTemplate.matchingCuriTemplateFor | public static Optional<CuriTemplate> matchingCuriTemplateFor(final List<Link> curies, final String rel) {
return curies
.stream()
.map(CuriTemplate::curiTemplateFor)
.filter(t->t.isMatching(rel))
.findAny();
} | java | public static Optional<CuriTemplate> matchingCuriTemplateFor(final List<Link> curies, final String rel) {
return curies
.stream()
.map(CuriTemplate::curiTemplateFor)
.filter(t->t.isMatching(rel))
.findAny();
} | [
"public",
"static",
"Optional",
"<",
"CuriTemplate",
">",
"matchingCuriTemplateFor",
"(",
"final",
"List",
"<",
"Link",
">",
"curies",
",",
"final",
"String",
"rel",
")",
"{",
"return",
"curies",
".",
"stream",
"(",
")",
".",
"map",
"(",
"CuriTemplate",
":... | Returns an optional CuriTemplate that is {@link #isMatching matching} the rel parameter, or empty if no matching CURI is found.
<p>
Example:
</p>
<pre><code>
List<Link> curies = asList(
Link.curi("x", "http://example.org/rels/{rel}"),
Link.curi("y", "http://example.com/link-relations/{rel}")
);
String rel = "y:example";
CuriTemplate template = CuriTemplate.matchingCuriTemplateFor(curies, rel);
</code></pre>
<p>
The returned UriTemplate is created from the second CURI, as only this is matching the curied rel parameter
{@code y:example}. Because of this, {@link #expandedRelFrom(String) template.expandedRelFrom(rel)} will
return {@code http://example.com/link-relations/example}
</p>
@param curies a List of curies Links
@param rel the link-relation type to check against the curies
@return optional CuriTemplate
@throws IllegalArgumentException if the {@code curies} parameter contains non-CURI links.
@since 2.0.0 | [
"Returns",
"an",
"optional",
"CuriTemplate",
"that",
"is",
"{",
"@link",
"#isMatching",
"matching",
"}",
"the",
"rel",
"parameter",
"or",
"empty",
"if",
"no",
"matching",
"CURI",
"is",
"found",
"."
] | train | https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/CuriTemplate.java#L137-L143 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java | ImgUtil.binary | public static void binary(InputStream srcStream, OutputStream destStream, String imageType) {
binary(read(srcStream), getImageOutputStream(destStream), imageType);
} | java | public static void binary(InputStream srcStream, OutputStream destStream, String imageType) {
binary(read(srcStream), getImageOutputStream(destStream), imageType);
} | [
"public",
"static",
"void",
"binary",
"(",
"InputStream",
"srcStream",
",",
"OutputStream",
"destStream",
",",
"String",
"imageType",
")",
"{",
"binary",
"(",
"read",
"(",
"srcStream",
")",
",",
"getImageOutputStream",
"(",
"destStream",
")",
",",
"imageType",
... | 彩色转为黑白二值化图片<br>
此方法并不关闭流
@param srcStream 源图像流
@param destStream 目标图像流
@param imageType 图片格式(扩展名)
@since 4.0.5 | [
"彩色转为黑白二值化图片<br",
">",
"此方法并不关闭流"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/img/ImgUtil.java#L675-L677 |
appium/java-client | src/main/java/io/appium/java_client/TouchAction.java | TouchAction.longPress | public T longPress(LongPressOptions longPressOptions) {
ActionParameter action = new ActionParameter("longPress", longPressOptions);
parameterBuilder.add(action);
//noinspection unchecked
return (T) this;
} | java | public T longPress(LongPressOptions longPressOptions) {
ActionParameter action = new ActionParameter("longPress", longPressOptions);
parameterBuilder.add(action);
//noinspection unchecked
return (T) this;
} | [
"public",
"T",
"longPress",
"(",
"LongPressOptions",
"longPressOptions",
")",
"{",
"ActionParameter",
"action",
"=",
"new",
"ActionParameter",
"(",
"\"longPress\"",
",",
"longPressOptions",
")",
";",
"parameterBuilder",
".",
"add",
"(",
"action",
")",
";",
"//noin... | Press and hold the at the center of an element until the context menu event has fired.
@param longPressOptions see {@link LongPressOptions}.
@return this TouchAction, for chaining. | [
"Press",
"and",
"hold",
"the",
"at",
"the",
"center",
"of",
"an",
"element",
"until",
"the",
"context",
"menu",
"event",
"has",
"fired",
"."
] | train | https://github.com/appium/java-client/blob/5a17759b05d6fda8ef425b3ab6e766c73ed2e8df/src/main/java/io/appium/java_client/TouchAction.java#L152-L157 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/media/MediaClient.java | MediaClient.createTranscodingJob | public CreateTranscodingJobResponse createTranscodingJob(CreateTranscodingJobRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
checkNotNull(request.getSource(), "The parameter source should NOT be null.");
checkNotNull(request.getTarget(), "The parameter target should NOT be null.");
checkStringNotEmpty(request.getTarget().getTargetKey(),
"The parameter targetKey should NOT be null or empty string.");
checkStringNotEmpty(request.getTarget().getPresetName(),
"The parameter presetName should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, TRANSCODE_JOB);
return invokeHttpClient(internalRequest, CreateTranscodingJobResponse.class);
} | java | public CreateTranscodingJobResponse createTranscodingJob(CreateTranscodingJobRequest request) {
checkNotNull(request, "The parameter request should NOT be null.");
checkStringNotEmpty(request.getPipelineName(),
"The parameter pipelineName should NOT be null or empty string.");
checkNotNull(request.getSource(), "The parameter source should NOT be null.");
checkNotNull(request.getTarget(), "The parameter target should NOT be null.");
checkStringNotEmpty(request.getTarget().getTargetKey(),
"The parameter targetKey should NOT be null or empty string.");
checkStringNotEmpty(request.getTarget().getPresetName(),
"The parameter presetName should NOT be null or empty string.");
InternalRequest internalRequest = createRequest(HttpMethodName.POST, request, TRANSCODE_JOB);
return invokeHttpClient(internalRequest, CreateTranscodingJobResponse.class);
} | [
"public",
"CreateTranscodingJobResponse",
"createTranscodingJob",
"(",
"CreateTranscodingJobRequest",
"request",
")",
"{",
"checkNotNull",
"(",
"request",
",",
"\"The parameter request should NOT be null.\"",
")",
";",
"checkStringNotEmpty",
"(",
"request",
".",
"getPipelineNam... | Creates a new transcoder job which converts media files in BOS buckets with specified preset.
@param request The request object containing all options for creating a job.
@return The newly created job ID. | [
"Creates",
"a",
"new",
"transcoder",
"job",
"which",
"converts",
"media",
"files",
"in",
"BOS",
"buckets",
"with",
"specified",
"preset",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/media/MediaClient.java#L422-L437 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getTPTransaction | public void getTPTransaction(String API, Transaction.Time time, Transaction.Type type, Callback<List<Transaction>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
gw2API.getTPTransaction(time.getValue(), type.getValue(), API).enqueue(callback);
} | java | public void getTPTransaction(String API, Transaction.Time time, Transaction.Type type, Callback<List<Transaction>> callback) throws GuildWars2Exception, NullPointerException {
isParamValid(new ParamChecker(ParamType.API, API));
if (time == null || type == null)
throw new GuildWars2Exception(ErrorCode.TransTime, "Transaction time/type cannot be empty");
gw2API.getTPTransaction(time.getValue(), type.getValue(), API).enqueue(callback);
} | [
"public",
"void",
"getTPTransaction",
"(",
"String",
"API",
",",
"Transaction",
".",
"Time",
"time",
",",
"Transaction",
".",
"Type",
"type",
",",
"Callback",
"<",
"List",
"<",
"Transaction",
">",
">",
"callback",
")",
"throws",
"GuildWars2Exception",
",",
"... | For more info on transactions API go <a href="https://wiki.guildwars2.com/wiki/API:2/commerce/transactions">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param API API key
@param time current | History
@param type buy | sell
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws GuildWars2Exception invalid API key
@throws NullPointerException if given {@link Callback} is empty
@see Transaction transaction info | [
"For",
"more",
"info",
"on",
"transactions",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"commerce",
"/",
"transactions",
">",
"here<",
"/",
"a",
">",
"<br",
"/"... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1002-L1007 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/NodeReportsInner.java | NodeReportsInner.getContent | public Object getContent(String resourceGroupName, String automationAccountName, String nodeId, String reportId) {
return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId, reportId).toBlocking().single().body();
} | java | public Object getContent(String resourceGroupName, String automationAccountName, String nodeId, String reportId) {
return getContentWithServiceResponseAsync(resourceGroupName, automationAccountName, nodeId, reportId).toBlocking().single().body();
} | [
"public",
"Object",
"getContent",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"nodeId",
",",
"String",
"reportId",
")",
"{",
"return",
"getContentWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountNam... | Retrieve the Dsc node reports by node id and report id.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param nodeId The Dsc node id.
@param reportId The report 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 Object object if successful. | [
"Retrieve",
"the",
"Dsc",
"node",
"reports",
"by",
"node",
"id",
"and",
"report",
"id",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/NodeReportsInner.java#L445-L447 |
jamesdbloom/mockserver | mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java | HttpRequest.withCookie | public HttpRequest withCookie(String name, String value) {
this.cookies.withEntry(name, value);
return this;
} | java | public HttpRequest withCookie(String name, String value) {
this.cookies.withEntry(name, value);
return this;
} | [
"public",
"HttpRequest",
"withCookie",
"(",
"String",
"name",
",",
"String",
"value",
")",
"{",
"this",
".",
"cookies",
".",
"withEntry",
"(",
"name",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Adds one cookie to match on, which can specified using either plain strings or regular expressions
(for more details of the supported regex syntax see http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html)
@param name the cookies name
@param value the cookies value | [
"Adds",
"one",
"cookie",
"to",
"match",
"on",
"which",
"can",
"specified",
"using",
"either",
"plain",
"strings",
"or",
"regular",
"expressions",
"(",
"for",
"more",
"details",
"of",
"the",
"supported",
"regex",
"syntax",
"see",
"http",
":",
"//",
"docs",
... | train | https://github.com/jamesdbloom/mockserver/blob/8b84fdd877e57b4eb780c9f8c8b1d65bcb448025/mockserver-core/src/main/java/org/mockserver/model/HttpRequest.java#L522-L525 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/ClassUtil.java | ClassUtil.loadInstance | public static Object loadInstance(Class clazz, Object defaultValue) {
try {
return clazz.newInstance();
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
} | java | public static Object loadInstance(Class clazz, Object defaultValue) {
try {
return clazz.newInstance();
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
return defaultValue;
}
} | [
"public",
"static",
"Object",
"loadInstance",
"(",
"Class",
"clazz",
",",
"Object",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"clazz",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"ExceptionUtil",
".",
"rethrowIfN... | loads a class from a String classname
@param clazz class to load
@return matching Class | [
"loads",
"a",
"class",
"from",
"a",
"String",
"classname"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/ClassUtil.java#L398-L406 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java | SwingBindingFactory.createBoundShuttleList | public Binding createBoundShuttleList( String selectionFormProperty, ValueModel selectableItemsHolder,
String renderedProperty ) {
Map context = ShuttleListBinder.createBindingContext(getFormModel(), selectionFormProperty,
selectableItemsHolder, renderedProperty);
return createBinding(ShuttleList.class, selectionFormProperty, context);
} | java | public Binding createBoundShuttleList( String selectionFormProperty, ValueModel selectableItemsHolder,
String renderedProperty ) {
Map context = ShuttleListBinder.createBindingContext(getFormModel(), selectionFormProperty,
selectableItemsHolder, renderedProperty);
return createBinding(ShuttleList.class, selectionFormProperty, context);
} | [
"public",
"Binding",
"createBoundShuttleList",
"(",
"String",
"selectionFormProperty",
",",
"ValueModel",
"selectableItemsHolder",
",",
"String",
"renderedProperty",
")",
"{",
"Map",
"context",
"=",
"ShuttleListBinder",
".",
"createBindingContext",
"(",
"getFormModel",
"(... | Binds the values specified in the collection contained within
<code>selectableItemsHolder</code> to a {@link ShuttleList}, with any
user selection being placed in the form property referred to by
<code>selectionFormProperty</code>. Each item in the list will be
rendered by looking up a property on the item by the name contained in
<code>renderedProperty</code>, retrieving the value of the property,
and rendering that value in the UI.
<p>
Note that the selection in the bound list will track any changes to the
<code>selectionFormProperty</code>. This is especially useful to
preselect items in the list - if <code>selectionFormProperty</code> is
not empty when the list is bound, then its content will be used for the
initial selection.
@param selectionFormProperty form property to hold user's selection. This
property must be a <code>Collection</code> or array type.
@param selectableItemsHolder <code>ValueModel</code> containing the
items with which to populate the list.
@param renderedProperty the property to be queried for each item in the
list, the result of which will be used to render that item in the
UI. May be null, in which case the selectable items will be
rendered as strings.
@return constructed {@link Binding}. Note that the bound control is of
type {@link ShuttleList}. Access this component to set specific
display properties. | [
"Binds",
"the",
"values",
"specified",
"in",
"the",
"collection",
"contained",
"within",
"<code",
">",
"selectableItemsHolder<",
"/",
"code",
">",
"to",
"a",
"{",
"@link",
"ShuttleList",
"}",
"with",
"any",
"user",
"selection",
"being",
"placed",
"in",
"the",
... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/form/binding/swing/SwingBindingFactory.java#L351-L356 |
mp911de/visualizr | visualizr-metrics/src/main/java/biz/paluch/visualizr/metrics/VisualizrReporter.java | VisualizrReporter.reportMeter | private void reportMeter(String name, Meter meter) {
String prefixedName = prefix(name);
if (!snapshots.hasDescriptor(prefixedName)) {
MetricItem.Builder builder = MetricItem.Builder.create();
builder.events("events");
builder.events("m1_rate", 1, rateUnit);
builder.events("m5_rate", 5, rateUnit);
builder.events("m15_rate", 15, rateUnit);
builder.events("mean_rate", rateUnit);
snapshots.setDescriptor(prefixedName, builder.build());
}
Map<String, Number> values = new HashMap<>();
addMetered(meter, values, "events");
snapshots.addSnapshot(prefixedName, getTimestamp(), values);
} | java | private void reportMeter(String name, Meter meter) {
String prefixedName = prefix(name);
if (!snapshots.hasDescriptor(prefixedName)) {
MetricItem.Builder builder = MetricItem.Builder.create();
builder.events("events");
builder.events("m1_rate", 1, rateUnit);
builder.events("m5_rate", 5, rateUnit);
builder.events("m15_rate", 15, rateUnit);
builder.events("mean_rate", rateUnit);
snapshots.setDescriptor(prefixedName, builder.build());
}
Map<String, Number> values = new HashMap<>();
addMetered(meter, values, "events");
snapshots.addSnapshot(prefixedName, getTimestamp(), values);
} | [
"private",
"void",
"reportMeter",
"(",
"String",
"name",
",",
"Meter",
"meter",
")",
"{",
"String",
"prefixedName",
"=",
"prefix",
"(",
"name",
")",
";",
"if",
"(",
"!",
"snapshots",
".",
"hasDescriptor",
"(",
"prefixedName",
")",
")",
"{",
"MetricItem",
... | Report a meter using fields events/m1_rate/m5_rate/m15_rate/mean_rate
@param name
@param meter | [
"Report",
"a",
"meter",
"using",
"fields",
"events",
"/",
"m1_rate",
"/",
"m5_rate",
"/",
"m15_rate",
"/",
"mean_rate"
] | train | https://github.com/mp911de/visualizr/blob/57206391692e88b2c59d52d4f18faa4cdfd32a98/visualizr-metrics/src/main/java/biz/paluch/visualizr/metrics/VisualizrReporter.java#L142-L162 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java | CPDefinitionInventoryPersistenceImpl.fetchByUUID_G | @Override
public CPDefinitionInventory fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | java | @Override
public CPDefinitionInventory fetchByUUID_G(String uuid, long groupId) {
return fetchByUUID_G(uuid, groupId, true);
} | [
"@",
"Override",
"public",
"CPDefinitionInventory",
"fetchByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"{",
"return",
"fetchByUUID_G",
"(",
"uuid",
",",
"groupId",
",",
"true",
")",
";",
"}"
] | Returns the cp definition inventory where uuid = ? and groupId = ? or returns <code>null</code> if it could not be found. Uses the finder cache.
@param uuid the uuid
@param groupId the group ID
@return the matching cp definition inventory, or <code>null</code> if a matching cp definition inventory could not be found | [
"Returns",
"the",
"cp",
"definition",
"inventory",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"or",
"returns",
"<code",
">",
"null<",
"/",
"code",
">",
"if",
"it",
"could",
"not",
"be",
"found",
".",
"Uses",
"the",
"finder",... | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CPDefinitionInventoryPersistenceImpl.java#L705-L708 |
demidenko05/beigesoft-webcrud-jar | src/main/java/org/beigesoft/web/service/SrvAddTheFirstUser.java | SrvAddTheFirstUser.addUser | @Override
public final void addUser(final String pUserName,
final String pPassw, final String pRole) throws Exception {
String query = "select USERTOMCAT.ITSUSER as ITSUSER, ITSROLE"
+ " from USERTOMCAT join USERROLETOMCAT"
+ " on USERROLETOMCAT.ITSUSER = USERTOMCAT.ITSUSER;";
IRecordSet<RS> recordSet = null;
try {
this.srvDatabase.setIsAutocommit(false);
this.srvDatabase.
setTransactionIsolation(ISrvDatabase.TRANSACTION_READ_UNCOMMITTED);
this.srvDatabase.beginTransaction();
recordSet = getSrvDatabase().retrieveRecords(query);
if (recordSet.moveToFirst()) {
throw new Exception("There are already user credentials!");
}
String addUserQ =
"insert into USERTOMCAT (ITSUSER, ITSPASSWORD) values ('" + pUserName
+ "', '" + pPassw + "');";
String addUserRoleQ =
"insert into USERROLETOMCAT (ITSUSER, ITSROLE) values ('" + pUserName
+ "', '" + pRole + "');";
this.srvDatabase.executeQuery(addUserQ);
this.srvDatabase.executeQuery(addUserRoleQ);
this.srvDatabase.commitTransaction();
this.isThereAnyUser = true;
} catch (Exception ex) {
this.srvDatabase.rollBackTransaction();
throw ex;
} finally {
this.srvDatabase.releaseResources();
if (recordSet != null) {
recordSet.close();
}
}
} | java | @Override
public final void addUser(final String pUserName,
final String pPassw, final String pRole) throws Exception {
String query = "select USERTOMCAT.ITSUSER as ITSUSER, ITSROLE"
+ " from USERTOMCAT join USERROLETOMCAT"
+ " on USERROLETOMCAT.ITSUSER = USERTOMCAT.ITSUSER;";
IRecordSet<RS> recordSet = null;
try {
this.srvDatabase.setIsAutocommit(false);
this.srvDatabase.
setTransactionIsolation(ISrvDatabase.TRANSACTION_READ_UNCOMMITTED);
this.srvDatabase.beginTransaction();
recordSet = getSrvDatabase().retrieveRecords(query);
if (recordSet.moveToFirst()) {
throw new Exception("There are already user credentials!");
}
String addUserQ =
"insert into USERTOMCAT (ITSUSER, ITSPASSWORD) values ('" + pUserName
+ "', '" + pPassw + "');";
String addUserRoleQ =
"insert into USERROLETOMCAT (ITSUSER, ITSROLE) values ('" + pUserName
+ "', '" + pRole + "');";
this.srvDatabase.executeQuery(addUserQ);
this.srvDatabase.executeQuery(addUserRoleQ);
this.srvDatabase.commitTransaction();
this.isThereAnyUser = true;
} catch (Exception ex) {
this.srvDatabase.rollBackTransaction();
throw ex;
} finally {
this.srvDatabase.releaseResources();
if (recordSet != null) {
recordSet.close();
}
}
} | [
"@",
"Override",
"public",
"final",
"void",
"addUser",
"(",
"final",
"String",
"pUserName",
",",
"final",
"String",
"pPassw",
",",
"final",
"String",
"pRole",
")",
"throws",
"Exception",
"{",
"String",
"query",
"=",
"\"select USERTOMCAT.ITSUSER as ITSUSER, ITSROLE\"... | <p>Add only user/password/role.</p>
@param pUserName User Name
@param pPassw User password
@param pRole User role
@throws Exception - an exception | [
"<p",
">",
"Add",
"only",
"user",
"/",
"password",
"/",
"role",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/demidenko05/beigesoft-webcrud-jar/blob/e973170f8fc1f164f0b67af9bb6a52b04579b64a/src/main/java/org/beigesoft/web/service/SrvAddTheFirstUser.java#L85-L120 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/io/FileUtils.java | FileUtils.deletePathRecursively | public static void deletePathRecursively(String path) throws IOException {
if (!exists(path)) {
return;
}
Path root = Paths.get(path);
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw e;
}
}
});
} | java | public static void deletePathRecursively(String path) throws IOException {
if (!exists(path)) {
return;
}
Path root = Paths.get(path);
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
if (e == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw e;
}
}
});
} | [
"public",
"static",
"void",
"deletePathRecursively",
"(",
"String",
"path",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"exists",
"(",
"path",
")",
")",
"{",
"return",
";",
"}",
"Path",
"root",
"=",
"Paths",
".",
"get",
"(",
"path",
")",
";",
... | Deletes a file or a directory, recursively if it is a directory.
If the path does not exist, nothing happens.
@param path pathname to be deleted | [
"Deletes",
"a",
"file",
"or",
"a",
"directory",
"recursively",
"if",
"it",
"is",
"a",
"directory",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/FileUtils.java#L228-L250 |
jenkinsci/gmaven | gmaven-runtime/gmaven-runtime-loader/src/main/java/org/codehaus/gmaven/runtime/loader/realm/DefaultRealmManager.java | DefaultRealmManager.setStrategy | private void setStrategy(final ClassRealm realm, final Strategy strategy) {
assert realm != null;
assert strategy != null;
try {
Field field = realm.getClass().getDeclaredField("strategy");
try {
field.set(realm, strategy);
}
catch (IllegalAccessException ignore) {
// try again
field.setAccessible(true);
try {
field.set(realm, strategy);
}
catch (IllegalAccessException e) {
throw new IllegalAccessError(e.getMessage());
}
}
}
catch (NoSuchFieldException e) {
throw new Error(e);
}
} | java | private void setStrategy(final ClassRealm realm, final Strategy strategy) {
assert realm != null;
assert strategy != null;
try {
Field field = realm.getClass().getDeclaredField("strategy");
try {
field.set(realm, strategy);
}
catch (IllegalAccessException ignore) {
// try again
field.setAccessible(true);
try {
field.set(realm, strategy);
}
catch (IllegalAccessException e) {
throw new IllegalAccessError(e.getMessage());
}
}
}
catch (NoSuchFieldException e) {
throw new Error(e);
}
} | [
"private",
"void",
"setStrategy",
"(",
"final",
"ClassRealm",
"realm",
",",
"final",
"Strategy",
"strategy",
")",
"{",
"assert",
"realm",
"!=",
"null",
";",
"assert",
"strategy",
"!=",
"null",
";",
"try",
"{",
"Field",
"field",
"=",
"realm",
".",
"getClass... | There is no public API to set/change a realms strategy, so we use some reflection muck to set the private field. | [
"There",
"is",
"no",
"public",
"API",
"to",
"set",
"/",
"change",
"a",
"realms",
"strategy",
"so",
"we",
"use",
"some",
"reflection",
"muck",
"to",
"set",
"the",
"private",
"field",
"."
] | train | https://github.com/jenkinsci/gmaven/blob/80d5f6657e15b3e05ffbb82128ed8bb280836e10/gmaven-runtime/gmaven-runtime-loader/src/main/java/org/codehaus/gmaven/runtime/loader/realm/DefaultRealmManager.java#L129-L154 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java | HttpBuilder.headAsync | public <T> CompletableFuture<T> headAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> head(type, configuration), getExecutor());
} | java | public <T> CompletableFuture<T> headAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> head(type, configuration), getExecutor());
} | [
"public",
"<",
"T",
">",
"CompletableFuture",
"<",
"T",
">",
"headAsync",
"(",
"final",
"Class",
"<",
"T",
">",
"type",
",",
"final",
"Consumer",
"<",
"HttpConfig",
">",
"configuration",
")",
"{",
"return",
"CompletableFuture",
".",
"supplyAsync",
"(",
"("... | Executes an asynchronous HEAD request on the configured URI (asynchronous alias to `head(Class,Consumer)`), with additional configuration
provided by the configuration function. The result will be cast to the specified `type`.
This method is generally used for Java-specific configuration.
[source,groovy]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
String result = http.headAsync(String.class, config -> {
config.getRequest().getUri().setPath("/foo");
});
----
The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface.
@param type the type of the response content
@param configuration the additional configuration function (delegated to {@link HttpConfig})
@return the resulting content cast to the specified type wrapped in a {@link CompletableFuture} | [
"Executes",
"an",
"asynchronous",
"HEAD",
"request",
"on",
"the",
"configured",
"URI",
"(",
"asynchronous",
"alias",
"to",
"head",
"(",
"Class",
"Consumer",
")",
")",
"with",
"additional",
"configuration",
"provided",
"by",
"the",
"configuration",
"function",
".... | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L685-L687 |
Azure/azure-sdk-for-java | streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/StreamingJobsInner.java | StreamingJobsInner.updateAsync | public Observable<StreamingJobInner> updateAsync(String resourceGroupName, String jobName, StreamingJobInner streamingJob, String ifMatch) {
return updateWithServiceResponseAsync(resourceGroupName, jobName, streamingJob, ifMatch).map(new Func1<ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsUpdateHeaders>, StreamingJobInner>() {
@Override
public StreamingJobInner call(ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsUpdateHeaders> response) {
return response.body();
}
});
} | java | public Observable<StreamingJobInner> updateAsync(String resourceGroupName, String jobName, StreamingJobInner streamingJob, String ifMatch) {
return updateWithServiceResponseAsync(resourceGroupName, jobName, streamingJob, ifMatch).map(new Func1<ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsUpdateHeaders>, StreamingJobInner>() {
@Override
public StreamingJobInner call(ServiceResponseWithHeaders<StreamingJobInner, StreamingJobsUpdateHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StreamingJobInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"jobName",
",",
"StreamingJobInner",
"streamingJob",
",",
"String",
"ifMatch",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceGr... | Updates an existing streaming job. This can be used to partially update (ie. update one or two properties) a streaming job without affecting the rest the job definition.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param jobName The name of the streaming job.
@param streamingJob A streaming job object. The properties specified here will overwrite the corresponding properties in the existing streaming job (ie. Those properties will be updated). Any properties that are set to null here will mean that the corresponding property in the existing input will remain the same and not change as a result of this PATCH operation.
@param ifMatch The ETag of the streaming job. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwritting concurrent changes.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StreamingJobInner object | [
"Updates",
"an",
"existing",
"streaming",
"job",
".",
"This",
"can",
"be",
"used",
"to",
"partially",
"update",
"(",
"ie",
".",
"update",
"one",
"or",
"two",
"properties",
")",
"a",
"streaming",
"job",
"without",
"affecting",
"the",
"rest",
"the",
"job",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/streamanalytics/resource-manager/v2016_03_01/src/main/java/com/microsoft/azure/management/streamanalytics/v2016_03_01/implementation/StreamingJobsInner.java#L616-L623 |
real-logic/agrona | agrona/src/main/java/org/agrona/References.java | References.isReferringTo | public static <T> boolean isReferringTo(final Reference<T> ref, final T obj)
{
return ref.get() == obj;
} | java | public static <T> boolean isReferringTo(final Reference<T> ref, final T obj)
{
return ref.get() == obj;
} | [
"public",
"static",
"<",
"T",
">",
"boolean",
"isReferringTo",
"(",
"final",
"Reference",
"<",
"T",
">",
"ref",
",",
"final",
"T",
"obj",
")",
"{",
"return",
"ref",
".",
"get",
"(",
")",
"==",
"obj",
";",
"}"
] | Indicate whether a Reference refers to a given object.
@param ref The {@link Reference} to be tested.
@param obj The object to which the {@link Reference} may, or may not, be referring.
@param <T> the class of the referent.
@return true if the {@link Reference}'s referent is obj, otherwise false. | [
"Indicate",
"whether",
"a",
"Reference",
"refers",
"to",
"a",
"given",
"object",
"."
] | train | https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/References.java#L70-L73 |
EdwardRaff/JSAT | JSAT/src/jsat/distributions/kernels/RBFKernel.java | RBFKernel.gammToSigma | public static double gammToSigma(double gamma)
{
if(gamma <= 0 || Double.isNaN(gamma) || Double.isInfinite(gamma))
throw new IllegalArgumentException("gamma must be positive, not " + gamma);
return 1/Math.sqrt(2*gamma);
} | java | public static double gammToSigma(double gamma)
{
if(gamma <= 0 || Double.isNaN(gamma) || Double.isInfinite(gamma))
throw new IllegalArgumentException("gamma must be positive, not " + gamma);
return 1/Math.sqrt(2*gamma);
} | [
"public",
"static",
"double",
"gammToSigma",
"(",
"double",
"gamma",
")",
"{",
"if",
"(",
"gamma",
"<=",
"0",
"||",
"Double",
".",
"isNaN",
"(",
"gamma",
")",
"||",
"Double",
".",
"isInfinite",
"(",
"gamma",
")",
")",
"throw",
"new",
"IllegalArgumentExce... | Another common (equivalent) form of the RBF kernel is k(x, y) =
exp(-γ||x-y||<sup>2</sup>). This method converts the γ value
equivalent σ value used by this class.
@param gamma the value of γ
@return the equivalent σ value | [
"Another",
"common",
"(",
"equivalent",
")",
"form",
"of",
"the",
"RBF",
"kernel",
"is",
"k",
"(",
"x",
"y",
")",
"=",
"exp",
"(",
"-",
"&gamma",
";",
"||x",
"-",
"y||<sup",
">",
"2<",
"/",
"sup",
">",
")",
".",
"This",
"method",
"converts",
"the... | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/RBFKernel.java#L125-L130 |
aNNiMON/Lightweight-Stream-API | stream/src/main/java/com/annimon/stream/Stream.java | Stream.findIndexed | @NotNull
public Optional<IntPair<T>> findIndexed(@NotNull IndexedPredicate<? super T> predicate) {
return findIndexed(0, 1, predicate);
} | java | @NotNull
public Optional<IntPair<T>> findIndexed(@NotNull IndexedPredicate<? super T> predicate) {
return findIndexed(0, 1, predicate);
} | [
"@",
"NotNull",
"public",
"Optional",
"<",
"IntPair",
"<",
"T",
">",
">",
"findIndexed",
"(",
"@",
"NotNull",
"IndexedPredicate",
"<",
"?",
"super",
"T",
">",
"predicate",
")",
"{",
"return",
"findIndexed",
"(",
"0",
",",
"1",
",",
"predicate",
")",
";... | Finds the first element and its index that matches the given predicate.
<p>This is a short-circuiting terminal operation.
<p>Example:
<pre>
predicate: (index, value) -> index + value == 7
stream: [1, 2, 3, 4, 5, 2, 0]
index: [0, 1, 2, 3, 4, 5, 6]
result: Optional.of(IntPair(3, 4))
</pre>
@param predicate the predicate to find value
@return an {@code Optional} with {@code IntPair}
or {@code Optional.empty()} if stream is empty or no value was found.
@since 1.1.8 | [
"Finds",
"the",
"first",
"element",
"and",
"its",
"index",
"that",
"matches",
"the",
"given",
"predicate",
"."
] | train | https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L1975-L1978 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/HasPositionalPredChecker.java | HasPositionalPredChecker.visitPredicate | public boolean visitPredicate(ExpressionOwner owner, Expression pred)
{
m_predDepth++;
if(m_predDepth == 1)
{
if((pred instanceof Variable) ||
(pred instanceof XNumber) ||
(pred instanceof Div) ||
(pred instanceof Plus) ||
(pred instanceof Minus) ||
(pred instanceof Mod) ||
(pred instanceof Quo) ||
(pred instanceof Mult) ||
(pred instanceof org.apache.xpath.operations.Number) ||
(pred instanceof Function))
m_hasPositionalPred = true;
else
pred.callVisitors(owner, this);
}
m_predDepth--;
// Don't go have the caller go any further down the subtree.
return false;
} | java | public boolean visitPredicate(ExpressionOwner owner, Expression pred)
{
m_predDepth++;
if(m_predDepth == 1)
{
if((pred instanceof Variable) ||
(pred instanceof XNumber) ||
(pred instanceof Div) ||
(pred instanceof Plus) ||
(pred instanceof Minus) ||
(pred instanceof Mod) ||
(pred instanceof Quo) ||
(pred instanceof Mult) ||
(pred instanceof org.apache.xpath.operations.Number) ||
(pred instanceof Function))
m_hasPositionalPred = true;
else
pred.callVisitors(owner, this);
}
m_predDepth--;
// Don't go have the caller go any further down the subtree.
return false;
} | [
"public",
"boolean",
"visitPredicate",
"(",
"ExpressionOwner",
"owner",
",",
"Expression",
"pred",
")",
"{",
"m_predDepth",
"++",
";",
"if",
"(",
"m_predDepth",
"==",
"1",
")",
"{",
"if",
"(",
"(",
"pred",
"instanceof",
"Variable",
")",
"||",
"(",
"pred",
... | Visit a predicate within a location path. Note that there isn't a
proper unique component for predicates, and that the expression will
be called also for whatever type Expression is.
@param owner The owner of the expression, to which the expression can
be reset if rewriting takes place.
@param pred The predicate object.
@return true if the sub expressions should be traversed. | [
"Visit",
"a",
"predicate",
"within",
"a",
"location",
"path",
".",
"Note",
"that",
"there",
"isn",
"t",
"a",
"proper",
"unique",
"component",
"for",
"predicates",
"and",
"that",
"the",
"expression",
"will",
"be",
"called",
"also",
"for",
"whatever",
"type",
... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/HasPositionalPredChecker.java#L95-L120 |
googleapis/google-cloud-java | google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/admin/v2/BigtableInstanceAdminClient.java | BigtableInstanceAdminClient.setIamPolicy | @SuppressWarnings("WeakerAccess")
public Policy setIamPolicy(String instanceId, Policy policy) {
return ApiExceptions.callAndTranslateApiException(setIamPolicyAsync(instanceId, policy));
} | java | @SuppressWarnings("WeakerAccess")
public Policy setIamPolicy(String instanceId, Policy policy) {
return ApiExceptions.callAndTranslateApiException(setIamPolicyAsync(instanceId, policy));
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"Policy",
"setIamPolicy",
"(",
"String",
"instanceId",
",",
"Policy",
"policy",
")",
"{",
"return",
"ApiExceptions",
".",
"callAndTranslateApiException",
"(",
"setIamPolicyAsync",
"(",
"instanceId",
",",... | Replaces the IAM policy associated with the specified instance.
<p>Sample code:
<pre>{@code
Policy newPolicy = client.setIamPolicy("my-instance",
Policy.newBuilder()
.addIdentity(Role.of("bigtable.user"), Identity.user("someone@example.com"))
.addIdentity(Role.of("bigtable.admin"), Identity.group("admins@example.com"))
.build());
}</pre>
@see <a
href="https://cloud.google.com/bigtable/docs/access-control#iam-management-instance">Instance-level
IAM management</a> | [
"Replaces",
"the",
"IAM",
"policy",
"associated",
"with",
"the",
"specified",
"instance",
"."
] | train | https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-bigtable/src/main/java/com/google/cloud/bigtable/admin/v2/BigtableInstanceAdminClient.java#L1162-L1165 |
andrehertwig/admintool | admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java | ATSecDBAbctractController.handleException | protected <E extends Throwable, V extends ATSecDBValidator> Set<ATError> handleException(E e, Log logger, V validator,
String key, String suffix, String defaultMessagePrefix, Object... arguments) {
if(null != logger) {
logger.error(e.getMessage(), e);
}
Set<ATError> errors = new HashSet<>(1);
if (null != validator) {
errors.add(new ATError(key,
validator.getMessageWithSuffix(suffix, arguments, defaultMessagePrefix + ": "+ e.getMessage())));
}
else if (null != messageSource) {
errors.add(new ATError(key,
messageSource.getMessage(key, null, defaultMessagePrefix + ": "+ e.getMessage(), LocaleContextHolder.getLocale())));
} else {
errors.add(new ATError(key, defaultMessagePrefix));
}
return errors;
} | java | protected <E extends Throwable, V extends ATSecDBValidator> Set<ATError> handleException(E e, Log logger, V validator,
String key, String suffix, String defaultMessagePrefix, Object... arguments) {
if(null != logger) {
logger.error(e.getMessage(), e);
}
Set<ATError> errors = new HashSet<>(1);
if (null != validator) {
errors.add(new ATError(key,
validator.getMessageWithSuffix(suffix, arguments, defaultMessagePrefix + ": "+ e.getMessage())));
}
else if (null != messageSource) {
errors.add(new ATError(key,
messageSource.getMessage(key, null, defaultMessagePrefix + ": "+ e.getMessage(), LocaleContextHolder.getLocale())));
} else {
errors.add(new ATError(key, defaultMessagePrefix));
}
return errors;
} | [
"protected",
"<",
"E",
"extends",
"Throwable",
",",
"V",
"extends",
"ATSecDBValidator",
">",
"Set",
"<",
"ATError",
">",
"handleException",
"(",
"E",
"e",
",",
"Log",
"logger",
",",
"V",
"validator",
",",
"String",
"key",
",",
"String",
"suffix",
",",
"S... | logging the error and creates {@link ATError} list output
@param e - required: the exception
@param logger - optional: (could be null), if not null, exception will be logged as error
@param validator - optional: (could be null)
@param key - required: the error key
@param suffix the suffix for resource message key (prefix and area is managed in validator), will be ignored if validator is null
@param defaultMessagePrefix message as prefix combined with exception.getMessage if no message resource has been found
@param arguments additional arguments
@return list of errors
@see #handleException(Throwable, Log, String, String, String)
@see #handleException(Throwable, Log, ATSecDBValidator, String, String, String) | [
"logging",
"the",
"error",
"and",
"creates",
"{",
"@link",
"ATError",
"}",
"list",
"output"
] | train | https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-security/admin-tools-security-dbuser/src/main/java/de/chandre/admintool/security/dbuser/contoller/ATSecDBAbctractController.java#L72-L89 |
spotbugs/spotbugs | eclipsePlugin/src/de/tobject/findbugs/io/IO.java | IO.writeFile | public static void writeFile(final File file, final FileOutput output, final IProgressMonitor monitor) throws CoreException {
try (FileOutputStream fout = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fout)) {
if (monitor != null) {
monitor.subTask("writing data to " + file.getName());
}
output.writeFile(bout);
bout.flush();
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
} | java | public static void writeFile(final File file, final FileOutput output, final IProgressMonitor monitor) throws CoreException {
try (FileOutputStream fout = new FileOutputStream(file);
BufferedOutputStream bout = new BufferedOutputStream(fout)) {
if (monitor != null) {
monitor.subTask("writing data to " + file.getName());
}
output.writeFile(bout);
bout.flush();
} catch (IOException e) {
IStatus status = FindbugsPlugin.createErrorStatus("Exception while " + output.getTaskDescription(), e);
throw new CoreException(status);
}
} | [
"public",
"static",
"void",
"writeFile",
"(",
"final",
"File",
"file",
",",
"final",
"FileOutput",
"output",
",",
"final",
"IProgressMonitor",
"monitor",
")",
"throws",
"CoreException",
"{",
"try",
"(",
"FileOutputStream",
"fout",
"=",
"new",
"FileOutputStream",
... | Write the contents of a java.io.File
@param file
the file to write to
@param output
the FileOutput object responsible for generating the data | [
"Write",
"the",
"contents",
"of",
"a",
"java",
".",
"io",
".",
"File"
] | train | https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/io/IO.java#L104-L116 |
OpenLiberty/open-liberty | dev/com.ibm.ws.channelfw/src/com/ibm/ws/udpchannel/internal/BufferDump.java | BufferDump.getHexDump | static public String getHexDump(byte[] data, int length) {
// boundary checks....
if (null == data || 0 > length) {
return null;
}
// if we have less than the target amount, just print what we have
if (data.length < length) {
length = data.length;
}
int numlines = (length / 16) + (((length % 16) > 0) ? 1 : 0);
StringBuilder buffer = new StringBuilder(73 * numlines);
for (int i = 0, line = 0; line < numlines; line++, i += 16) {
buffer = formatLineId(buffer, i);
buffer.append(": ");
// format the first 8 bytes as hex data
buffer = formatHexData(buffer, data, i);
buffer.append(" ");
// format the second 8 bytes as hex data
buffer = formatHexData(buffer, data, i + 8);
buffer.append(" ");
// now print the ascii version, filtering out non-ascii chars
buffer = formatTextData(buffer, data, i);
buffer.append('\n');
}
return buffer.toString();
} | java | static public String getHexDump(byte[] data, int length) {
// boundary checks....
if (null == data || 0 > length) {
return null;
}
// if we have less than the target amount, just print what we have
if (data.length < length) {
length = data.length;
}
int numlines = (length / 16) + (((length % 16) > 0) ? 1 : 0);
StringBuilder buffer = new StringBuilder(73 * numlines);
for (int i = 0, line = 0; line < numlines; line++, i += 16) {
buffer = formatLineId(buffer, i);
buffer.append(": ");
// format the first 8 bytes as hex data
buffer = formatHexData(buffer, data, i);
buffer.append(" ");
// format the second 8 bytes as hex data
buffer = formatHexData(buffer, data, i + 8);
buffer.append(" ");
// now print the ascii version, filtering out non-ascii chars
buffer = formatTextData(buffer, data, i);
buffer.append('\n');
}
return buffer.toString();
} | [
"static",
"public",
"String",
"getHexDump",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"length",
")",
"{",
"// boundary checks....",
"if",
"(",
"null",
"==",
"data",
"||",
"0",
">",
"length",
")",
"{",
"return",
"null",
";",
"}",
"// if we have less than t... | Debug print the input byte[] up to the input maximum length. This will be
a sequence of 16 byte lines, starting with a line indicator, the hex
bytes and then the ASCII representation.
@param data
@param length
@return String | [
"Debug",
"print",
"the",
"input",
"byte",
"[]",
"up",
"to",
"the",
"input",
"maximum",
"length",
".",
"This",
"will",
"be",
"a",
"sequence",
"of",
"16",
"byte",
"lines",
"starting",
"with",
"a",
"line",
"indicator",
"the",
"hex",
"bytes",
"and",
"then",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/ws/udpchannel/internal/BufferDump.java#L60-L85 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getUntilFirstIncl | @Nullable
public static String getUntilFirstIncl (@Nullable final String sStr, final char cSearch)
{
return _getUntilFirst (sStr, cSearch, true);
} | java | @Nullable
public static String getUntilFirstIncl (@Nullable final String sStr, final char cSearch)
{
return _getUntilFirst (sStr, cSearch, true);
} | [
"@",
"Nullable",
"public",
"static",
"String",
"getUntilFirstIncl",
"(",
"@",
"Nullable",
"final",
"String",
"sStr",
",",
"final",
"char",
"cSearch",
")",
"{",
"return",
"_getUntilFirst",
"(",
"sStr",
",",
"cSearch",
",",
"true",
")",
";",
"}"
] | Get everything from the string up to and including the first passed char.
@param sStr
The source string. May be <code>null</code>.
@param cSearch
The character to search.
@return <code>null</code> if the passed string does not contain the search
character. | [
"Get",
"everything",
"from",
"the",
"string",
"up",
"to",
"and",
"including",
"the",
"first",
"passed",
"char",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L4756-L4760 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WDataTableRenderer.java | WDataTableRenderer.paintPaginationElement | private void paintPaginationElement(final WDataTable table, final XmlStringBuilder xml) {
TableDataModel model = table.getDataModel();
xml.appendTagOpen("ui:pagination");
if (model instanceof TreeTableDataModel) {
// For tree tables, we only include top-level nodes for pagination.
TreeNode firstNode = ((TreeTableDataModel) model).getNodeAtLine(0);
xml.appendAttribute("rows", firstNode == null ? 0 : firstNode.getParent().
getChildCount());
} else {
xml.appendAttribute("rows", model.getRowCount());
}
xml.appendAttribute("rowsPerPage", table.getRowsPerPage());
xml.appendAttribute("currentPage", table.getCurrentPage());
switch (table.getPaginationMode()) {
case CLIENT:
xml.appendAttribute("mode", "client");
break;
case DYNAMIC:
case SERVER:
xml.appendAttribute("mode", "dynamic");
break;
case NONE:
break;
default:
throw new SystemException("Unknown pagination mode: " + table.
getPaginationMode());
}
xml.appendEnd();
} | java | private void paintPaginationElement(final WDataTable table, final XmlStringBuilder xml) {
TableDataModel model = table.getDataModel();
xml.appendTagOpen("ui:pagination");
if (model instanceof TreeTableDataModel) {
// For tree tables, we only include top-level nodes for pagination.
TreeNode firstNode = ((TreeTableDataModel) model).getNodeAtLine(0);
xml.appendAttribute("rows", firstNode == null ? 0 : firstNode.getParent().
getChildCount());
} else {
xml.appendAttribute("rows", model.getRowCount());
}
xml.appendAttribute("rowsPerPage", table.getRowsPerPage());
xml.appendAttribute("currentPage", table.getCurrentPage());
switch (table.getPaginationMode()) {
case CLIENT:
xml.appendAttribute("mode", "client");
break;
case DYNAMIC:
case SERVER:
xml.appendAttribute("mode", "dynamic");
break;
case NONE:
break;
default:
throw new SystemException("Unknown pagination mode: " + table.
getPaginationMode());
}
xml.appendEnd();
} | [
"private",
"void",
"paintPaginationElement",
"(",
"final",
"WDataTable",
"table",
",",
"final",
"XmlStringBuilder",
"xml",
")",
"{",
"TableDataModel",
"model",
"=",
"table",
".",
"getDataModel",
"(",
")",
";",
"xml",
".",
"appendTagOpen",
"(",
"\"ui:pagination\"",... | Paint the pagination aspects of the WDataTable.
@param table the WDataTable being rendered
@param xml the string builder in use | [
"Paint",
"the",
"pagination",
"aspects",
"of",
"the",
"WDataTable",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WDataTableRenderer.java#L120-L152 |
OpenLiberty/open-liberty | dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/cmdline/ExtensionUtils.java | ExtensionUtils.listProductExtensionDirectories | static List<File> listProductExtensionDirectories() {
List<File> dirs = new ArrayList<File>();
for (ProductExtensionInfo info : ProductExtension.getProductExtensions()) {
// there are some fat tests which constructs incorrect ProductExtensionInfo.
// in order to avoid the test failure, check null object and skip it if it is null.
String loc = info.getLocation();
if (loc != null) {
File extensionDir = new File(info.getLocation());
if (!extensionDir.isAbsolute()) {
File parentDir = Utils.getInstallDir().getParentFile();
extensionDir = new File(parentDir, info.getLocation());
}
dirs.add(extensionDir);
}
}
return dirs;
} | java | static List<File> listProductExtensionDirectories() {
List<File> dirs = new ArrayList<File>();
for (ProductExtensionInfo info : ProductExtension.getProductExtensions()) {
// there are some fat tests which constructs incorrect ProductExtensionInfo.
// in order to avoid the test failure, check null object and skip it if it is null.
String loc = info.getLocation();
if (loc != null) {
File extensionDir = new File(info.getLocation());
if (!extensionDir.isAbsolute()) {
File parentDir = Utils.getInstallDir().getParentFile();
extensionDir = new File(parentDir, info.getLocation());
}
dirs.add(extensionDir);
}
}
return dirs;
} | [
"static",
"List",
"<",
"File",
">",
"listProductExtensionDirectories",
"(",
")",
"{",
"List",
"<",
"File",
">",
"dirs",
"=",
"new",
"ArrayList",
"<",
"File",
">",
"(",
")",
";",
"for",
"(",
"ProductExtensionInfo",
"info",
":",
"ProductExtension",
".",
"get... | List all of product extension directory.
It returns empty List object if there is no product extension. | [
"List",
"all",
"of",
"product",
"extension",
"directory",
".",
"It",
"returns",
"empty",
"List",
"object",
"if",
"there",
"is",
"no",
"product",
"extension",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/boot/cmdline/ExtensionUtils.java#L71-L87 |
apache/incubator-gobblin | gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java | JobLauncherUtils.cleanTaskStagingData | public static void cleanTaskStagingData(State state, Logger logger) throws IOException {
int numBranches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1);
for (int branchId = 0; branchId < numBranches; branchId++) {
String writerFsUri = state.getProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, numBranches, branchId),
ConfigurationKeys.LOCAL_FS_URI);
FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state));
Path stagingPath = WriterUtils.getWriterStagingDir(state, numBranches, branchId);
if (fs.exists(stagingPath)) {
logger.info("Cleaning up staging directory " + stagingPath.toUri().getPath());
if (!fs.delete(stagingPath, true)) {
throw new IOException("Clean up staging directory " + stagingPath.toUri().getPath() + " failed");
}
}
Path outputPath = WriterUtils.getWriterOutputDir(state, numBranches, branchId);
if (fs.exists(outputPath)) {
logger.info("Cleaning up output directory " + outputPath.toUri().getPath());
if (!fs.delete(outputPath, true)) {
throw new IOException("Clean up output directory " + outputPath.toUri().getPath() + " failed");
}
}
}
} | java | public static void cleanTaskStagingData(State state, Logger logger) throws IOException {
int numBranches = state.getPropAsInt(ConfigurationKeys.FORK_BRANCHES_KEY, 1);
for (int branchId = 0; branchId < numBranches; branchId++) {
String writerFsUri = state.getProp(
ForkOperatorUtils.getPropertyNameForBranch(ConfigurationKeys.WRITER_FILE_SYSTEM_URI, numBranches, branchId),
ConfigurationKeys.LOCAL_FS_URI);
FileSystem fs = getFsWithProxy(state, writerFsUri, WriterUtils.getFsConfiguration(state));
Path stagingPath = WriterUtils.getWriterStagingDir(state, numBranches, branchId);
if (fs.exists(stagingPath)) {
logger.info("Cleaning up staging directory " + stagingPath.toUri().getPath());
if (!fs.delete(stagingPath, true)) {
throw new IOException("Clean up staging directory " + stagingPath.toUri().getPath() + " failed");
}
}
Path outputPath = WriterUtils.getWriterOutputDir(state, numBranches, branchId);
if (fs.exists(outputPath)) {
logger.info("Cleaning up output directory " + outputPath.toUri().getPath());
if (!fs.delete(outputPath, true)) {
throw new IOException("Clean up output directory " + outputPath.toUri().getPath() + " failed");
}
}
}
} | [
"public",
"static",
"void",
"cleanTaskStagingData",
"(",
"State",
"state",
",",
"Logger",
"logger",
")",
"throws",
"IOException",
"{",
"int",
"numBranches",
"=",
"state",
".",
"getPropAsInt",
"(",
"ConfigurationKeys",
".",
"FORK_BRANCHES_KEY",
",",
"1",
")",
";"... | Cleanup staging data of a Gobblin task.
@param state a {@link State} instance storing task configuration properties
@param logger a {@link Logger} used for logging | [
"Cleanup",
"staging",
"data",
"of",
"a",
"Gobblin",
"task",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-utility/src/main/java/org/apache/gobblin/util/JobLauncherUtils.java#L176-L201 |
virgo47/javasimon | spring/src/main/java/org/javasimon/spring/BasicMonitoringInterceptor.java | BasicMonitoringInterceptor.invoke | public final Object invoke(MethodInvocation invocation) throws Throwable {
final Split split = stopwatchSource.start(invocation);
try {
return processInvoke(invocation, split);
} finally {
split.stop();
}
} | java | public final Object invoke(MethodInvocation invocation) throws Throwable {
final Split split = stopwatchSource.start(invocation);
try {
return processInvoke(invocation, split);
} finally {
split.stop();
}
} | [
"public",
"final",
"Object",
"invoke",
"(",
"MethodInvocation",
"invocation",
")",
"throws",
"Throwable",
"{",
"final",
"Split",
"split",
"=",
"stopwatchSource",
".",
"start",
"(",
"invocation",
")",
";",
"try",
"{",
"return",
"processInvoke",
"(",
"invocation",... | Performs method invocation and wraps it with Stopwatch.
@param invocation method invocation
@return return object from the method
@throws Throwable anything thrown by the method | [
"Performs",
"method",
"invocation",
"and",
"wraps",
"it",
"with",
"Stopwatch",
"."
] | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/spring/src/main/java/org/javasimon/spring/BasicMonitoringInterceptor.java#L48-L55 |
ahome-it/lienzo-core | src/main/java/com/ait/lienzo/client/widget/DragContext.java | DragContext.dragUpdate | public void dragUpdate(final INodeXYEvent event)
{
m_evtx = event.getX();
m_evty = event.getY();
m_dstx = m_evtx - m_begx;
m_dsty = m_evty - m_begy;
final Point2D p2 = new Point2D(0, 0);
m_gtol.transform(new Point2D(m_dstx, m_dsty), p2);
m_lclp.setX(p2.getX() - m_pref.getX());
m_lclp.setY(p2.getY() - m_pref.getY());
// Let the constraints adjust the location if necessary
if (m_drag != null)
{
m_drag.adjust(m_lclp);
}
save();
} | java | public void dragUpdate(final INodeXYEvent event)
{
m_evtx = event.getX();
m_evty = event.getY();
m_dstx = m_evtx - m_begx;
m_dsty = m_evty - m_begy;
final Point2D p2 = new Point2D(0, 0);
m_gtol.transform(new Point2D(m_dstx, m_dsty), p2);
m_lclp.setX(p2.getX() - m_pref.getX());
m_lclp.setY(p2.getY() - m_pref.getY());
// Let the constraints adjust the location if necessary
if (m_drag != null)
{
m_drag.adjust(m_lclp);
}
save();
} | [
"public",
"void",
"dragUpdate",
"(",
"final",
"INodeXYEvent",
"event",
")",
"{",
"m_evtx",
"=",
"event",
".",
"getX",
"(",
")",
";",
"m_evty",
"=",
"event",
".",
"getY",
"(",
")",
";",
"m_dstx",
"=",
"m_evtx",
"-",
"m_begx",
";",
"m_dsty",
"=",
"m_ev... | Updates the context for the specified Drag Move event.
Used internally.
@param event Drag Move event | [
"Updates",
"the",
"context",
"for",
"the",
"specified",
"Drag",
"Move",
"event",
".",
"Used",
"internally",
"."
] | train | https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/widget/DragContext.java#L177-L202 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/basic/servicegroupbindings.java | servicegroupbindings.get | public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{
servicegroupbindings obj = new servicegroupbindings();
obj.set_servicegroupname(servicegroupname);
servicegroupbindings response = (servicegroupbindings) obj.get_resource(service);
return response;
} | java | public static servicegroupbindings get(nitro_service service, String servicegroupname) throws Exception{
servicegroupbindings obj = new servicegroupbindings();
obj.set_servicegroupname(servicegroupname);
servicegroupbindings response = (servicegroupbindings) obj.get_resource(service);
return response;
} | [
"public",
"static",
"servicegroupbindings",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"servicegroupname",
")",
"throws",
"Exception",
"{",
"servicegroupbindings",
"obj",
"=",
"new",
"servicegroupbindings",
"(",
")",
";",
"obj",
".",
"set_servicegroupname"... | Use this API to fetch servicegroupbindings resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"servicegroupbindings",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/basic/servicegroupbindings.java#L146-L151 |
netscaler/sdx_nitro | src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_monitor_temp.java | xen_health_monitor_temp.get_nitro_bulk_response | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_monitor_temp_responses result = (xen_health_monitor_temp_responses) service.get_payload_formatter().string_to_resource(xen_health_monitor_temp_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_monitor_temp_response_array);
}
xen_health_monitor_temp[] result_xen_health_monitor_temp = new xen_health_monitor_temp[result.xen_health_monitor_temp_response_array.length];
for(int i = 0; i < result.xen_health_monitor_temp_response_array.length; i++)
{
result_xen_health_monitor_temp[i] = result.xen_health_monitor_temp_response_array[i].xen_health_monitor_temp[0];
}
return result_xen_health_monitor_temp;
} | java | protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
{
xen_health_monitor_temp_responses result = (xen_health_monitor_temp_responses) service.get_payload_formatter().string_to_resource(xen_health_monitor_temp_responses.class, response);
if(result.errorcode != 0)
{
if (result.errorcode == SESSION_NOT_EXISTS)
service.clear_session();
throw new nitro_exception(result.message, result.errorcode, (base_response [])result.xen_health_monitor_temp_response_array);
}
xen_health_monitor_temp[] result_xen_health_monitor_temp = new xen_health_monitor_temp[result.xen_health_monitor_temp_response_array.length];
for(int i = 0; i < result.xen_health_monitor_temp_response_array.length; i++)
{
result_xen_health_monitor_temp[i] = result.xen_health_monitor_temp_response_array[i].xen_health_monitor_temp[0];
}
return result_xen_health_monitor_temp;
} | [
"protected",
"base_resource",
"[",
"]",
"get_nitro_bulk_response",
"(",
"nitro_service",
"service",
",",
"String",
"response",
")",
"throws",
"Exception",
"{",
"xen_health_monitor_temp_responses",
"result",
"=",
"(",
"xen_health_monitor_temp_responses",
")",
"service",
".... | <pre>
Converts API response of bulk operation into object and returns the object array in case of get request.
</pre> | [
"<pre",
">",
"Converts",
"API",
"response",
"of",
"bulk",
"operation",
"into",
"object",
"and",
"returns",
"the",
"object",
"array",
"in",
"case",
"of",
"get",
"request",
".",
"<",
"/",
"pre",
">"
] | train | https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/xen/xen_health_monitor_temp.java#L173-L190 |
jbundle/jbundle | base/base/src/main/java/org/jbundle/base/field/FloatField.java | FloatField.moveSQLToField | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
float fResult = resultset.getFloat(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
{
if ((!this.isNullable()) && (fResult == Float.NaN))
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setValue(fResult, false, DBConstants.READ_MOVE);
}
} | java | public void moveSQLToField(ResultSet resultset, int iColumn) throws SQLException
{
float fResult = resultset.getFloat(iColumn);
if (resultset.wasNull())
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
{
if ((!this.isNullable()) && (fResult == Float.NaN))
this.setString(Constants.BLANK, false, DBConstants.READ_MOVE); // Null value
else
this.setValue(fResult, false, DBConstants.READ_MOVE);
}
} | [
"public",
"void",
"moveSQLToField",
"(",
"ResultSet",
"resultset",
",",
"int",
"iColumn",
")",
"throws",
"SQLException",
"{",
"float",
"fResult",
"=",
"resultset",
".",
"getFloat",
"(",
"iColumn",
")",
";",
"if",
"(",
"resultset",
".",
"wasNull",
"(",
")",
... | Move the physical binary data to this SQL parameter row.
@param resultset The resultset to get the SQL data from.
@param iColumn the column in the resultset that has my data.
@exception SQLException From SQL calls. | [
"Move",
"the",
"physical",
"binary",
"data",
"to",
"this",
"SQL",
"parameter",
"row",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/FloatField.java#L170-L182 |
samskivert/samskivert | src/main/java/com/samskivert/servlet/util/HTMLUtil.java | HTMLUtil.restrictHTML | public static String restrictHTML (String src, boolean allowFormatting,
boolean allowImages, boolean allowLinks)
{
// TODO: these regexes should probably be checked to make
// sure that javascript can't live inside a link
ArrayList<String> allow = new ArrayList<String>();
if (allowFormatting) {
allow.add("<b>"); allow.add("</b>");
allow.add("<i>"); allow.add("</i>");
allow.add("<u>"); allow.add("</u>");
allow.add("<font [^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</font>");
allow.add("<br>"); allow.add("</br>"); allow.add("<br/>");
allow.add("<p>"); allow.add("</p>");
allow.add("<hr>"); allow.add("</hr>"); allow.add("<hr/>");
}
if (allowImages) {
// Until I find a way to disallow "---", no - can be in a url
allow.add("<img [^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</img>");
}
if (allowLinks) {
allow.add("<a href=[^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</a>");
}
return restrictHTML(src, allow.toArray(new String[allow.size()]));
} | java | public static String restrictHTML (String src, boolean allowFormatting,
boolean allowImages, boolean allowLinks)
{
// TODO: these regexes should probably be checked to make
// sure that javascript can't live inside a link
ArrayList<String> allow = new ArrayList<String>();
if (allowFormatting) {
allow.add("<b>"); allow.add("</b>");
allow.add("<i>"); allow.add("</i>");
allow.add("<u>"); allow.add("</u>");
allow.add("<font [^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</font>");
allow.add("<br>"); allow.add("</br>"); allow.add("<br/>");
allow.add("<p>"); allow.add("</p>");
allow.add("<hr>"); allow.add("</hr>"); allow.add("<hr/>");
}
if (allowImages) {
// Until I find a way to disallow "---", no - can be in a url
allow.add("<img [^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</img>");
}
if (allowLinks) {
allow.add("<a href=[^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
allow.add("</a>");
}
return restrictHTML(src, allow.toArray(new String[allow.size()]));
} | [
"public",
"static",
"String",
"restrictHTML",
"(",
"String",
"src",
",",
"boolean",
"allowFormatting",
",",
"boolean",
"allowImages",
",",
"boolean",
"allowLinks",
")",
"{",
"// TODO: these regexes should probably be checked to make",
"// sure that javascript can't live inside ... | Restrict HTML except for the specified tags.
@param allowFormatting enables <i>, <b>, <u>,
<font>, <br>, <p>, and
<hr>.
@param allowImages enabled <img ...>.
@param allowLinks enabled <a href ...>. | [
"Restrict",
"HTML",
"except",
"for",
"the",
"specified",
"tags",
"."
] | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/util/HTMLUtil.java#L160-L186 |
HanSolo/SteelSeries-Swing | src/main/java/eu/hansolo/steelseries/extras/LightBulb.java | LightBulb.createImage | private BufferedImage createImage(final int WIDTH, final int HEIGHT, final int TRANSPARENCY) {
final GraphicsConfiguration GFX_CONF = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
if (WIDTH <= 0 || HEIGHT <= 0) {
return GFX_CONF.createCompatibleImage(1, 1, TRANSPARENCY);
}
final BufferedImage IMAGE = GFX_CONF.createCompatibleImage(WIDTH, HEIGHT, TRANSPARENCY);
return IMAGE;
} | java | private BufferedImage createImage(final int WIDTH, final int HEIGHT, final int TRANSPARENCY) {
final GraphicsConfiguration GFX_CONF = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
if (WIDTH <= 0 || HEIGHT <= 0) {
return GFX_CONF.createCompatibleImage(1, 1, TRANSPARENCY);
}
final BufferedImage IMAGE = GFX_CONF.createCompatibleImage(WIDTH, HEIGHT, TRANSPARENCY);
return IMAGE;
} | [
"private",
"BufferedImage",
"createImage",
"(",
"final",
"int",
"WIDTH",
",",
"final",
"int",
"HEIGHT",
",",
"final",
"int",
"TRANSPARENCY",
")",
"{",
"final",
"GraphicsConfiguration",
"GFX_CONF",
"=",
"GraphicsEnvironment",
".",
"getLocalGraphicsEnvironment",
"(",
... | Returns a compatible image of the given size and transparency
@param WIDTH
@param HEIGHT
@param TRANSPARENCY
@return a compatible image of the given size and transparency | [
"Returns",
"a",
"compatible",
"image",
"of",
"the",
"given",
"size",
"and",
"transparency"
] | train | https://github.com/HanSolo/SteelSeries-Swing/blob/c2f7b45a477757ef21bbb6a1174ddedb2250ae57/src/main/java/eu/hansolo/steelseries/extras/LightBulb.java#L497-L504 |
nikkiii/embedhttp | src/main/java/org/nikkii/embedhttp/util/HttpUtil.java | HttpUtil.capitalizeHeader | public static String capitalizeHeader(String header) {
StringTokenizer st = new StringTokenizer(header, "-");
StringBuilder out = new StringBuilder();
while (st.hasMoreTokens()) {
String l = st.nextToken();
out.append(Character.toUpperCase(l.charAt(0)));
if (l.length() > 1) {
out.append(l.substring(1));
}
if (st.hasMoreTokens())
out.append('-');
}
return out.toString();
} | java | public static String capitalizeHeader(String header) {
StringTokenizer st = new StringTokenizer(header, "-");
StringBuilder out = new StringBuilder();
while (st.hasMoreTokens()) {
String l = st.nextToken();
out.append(Character.toUpperCase(l.charAt(0)));
if (l.length() > 1) {
out.append(l.substring(1));
}
if (st.hasMoreTokens())
out.append('-');
}
return out.toString();
} | [
"public",
"static",
"String",
"capitalizeHeader",
"(",
"String",
"header",
")",
"{",
"StringTokenizer",
"st",
"=",
"new",
"StringTokenizer",
"(",
"header",
",",
"\"-\"",
")",
";",
"StringBuilder",
"out",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"while",
"... | Fixes capitalization on headers
@param header The header input
@return A header with all characters after '-' capitalized | [
"Fixes",
"capitalization",
"on",
"headers"
] | train | https://github.com/nikkiii/embedhttp/blob/7c965b6910dc6ee4ea46d7ae188c0751b98c2615/src/main/java/org/nikkii/embedhttp/util/HttpUtil.java#L40-L53 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/MediaDefault.java | MediaDefault.getTempDir | private static String getTempDir(Class<?> loader)
{
final File temp = new File(TEMP, loader.getSimpleName());
final String path = temp.getAbsolutePath();
if (!temp.isDirectory() && !temp.mkdir())
{
Verbose.warning(ERROR_CREATE_TEMP_DIR, path);
}
return path;
} | java | private static String getTempDir(Class<?> loader)
{
final File temp = new File(TEMP, loader.getSimpleName());
final String path = temp.getAbsolutePath();
if (!temp.isDirectory() && !temp.mkdir())
{
Verbose.warning(ERROR_CREATE_TEMP_DIR, path);
}
return path;
} | [
"private",
"static",
"String",
"getTempDir",
"(",
"Class",
"<",
"?",
">",
"loader",
")",
"{",
"final",
"File",
"temp",
"=",
"new",
"File",
"(",
"TEMP",
",",
"loader",
".",
"getSimpleName",
"(",
")",
")",
";",
"final",
"String",
"path",
"=",
"temp",
"... | Create the temp directory relative to loader class name.
@param loader The class loader.
@return The temp directory absolute path. | [
"Create",
"the",
"temp",
"directory",
"relative",
"to",
"loader",
"class",
"name",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/MediaDefault.java#L61-L70 |
james-hu/jabb-core | src/main/java/net/sf/jabb/spring/service/AbstractSmartLifecycleService.java | AbstractSmartLifecycleService.setLifecycleConfigurations | protected void setLifecycleConfigurations(PropertyResolver configResolver, String configurationsCommonPrefix, Class<?> interfaceClass){
Integer phase = getConfigProperty(configResolver, configurationsCommonPrefix, ".phase", Integer.class, interfaceClass);
if (phase == null){
logger.warn("No configuration found for the phase of SmartLifecycle service '{}', 0 will be used.", this.getClass().getName());
phase = 0;
}
Boolean isAutoStart = getConfigProperty(configResolver, configurationsCommonPrefix, ".autoStart", Boolean.class, interfaceClass);
if (isAutoStart == null){
logger.warn("No configuration found for the auto-start of SmartLifecycle service '{}', false will be used.", this.getClass().getName());
isAutoStart = false;
}
this.phase = phase;
this.isAutoStart = isAutoStart;
} | java | protected void setLifecycleConfigurations(PropertyResolver configResolver, String configurationsCommonPrefix, Class<?> interfaceClass){
Integer phase = getConfigProperty(configResolver, configurationsCommonPrefix, ".phase", Integer.class, interfaceClass);
if (phase == null){
logger.warn("No configuration found for the phase of SmartLifecycle service '{}', 0 will be used.", this.getClass().getName());
phase = 0;
}
Boolean isAutoStart = getConfigProperty(configResolver, configurationsCommonPrefix, ".autoStart", Boolean.class, interfaceClass);
if (isAutoStart == null){
logger.warn("No configuration found for the auto-start of SmartLifecycle service '{}', false will be used.", this.getClass().getName());
isAutoStart = false;
}
this.phase = phase;
this.isAutoStart = isAutoStart;
} | [
"protected",
"void",
"setLifecycleConfigurations",
"(",
"PropertyResolver",
"configResolver",
",",
"String",
"configurationsCommonPrefix",
",",
"Class",
"<",
"?",
">",
"interfaceClass",
")",
"{",
"Integer",
"phase",
"=",
"getConfigProperty",
"(",
"configResolver",
",",
... | Configure isAutoStart and phase from properties.
For example, if the class name of the service is a.b.Xyz, then the properties will be some thing like:
<ul>
<li>lifecycle.a.b.Xyz.phase=3</li>
<li>lifecycle.a.b.Xyz.autoStart=true</li>
</ul>
This method is typically called from subclass after an instance of Environment is injected.
@param configResolver the PropertyResolver (normally the Environment) containing the configurations
@param configurationsCommonPrefix the common prefix of those configuration items, for example 'myapp.common.lifecycle.'.
If it is null, then there will be no prefix prepended.
@param interfaceClass the interface implemented. If it is not null, properties with the following names will be tried:
<ol>
<li>configurationsCommonPrefix + this.getClass().getName() + ".phase"</li>
<li>configurationsCommonPrefix + this.getClass().getSimpleName() + ".phase"</li>
<li>configurationsCommonPrefix + StringUtils.uncapitalize(this.getClass().getSimpleName()) + ".phase"</li>
<li>configurationsCommonPrefix + interfaceClass.getName() + ".phase"</li>
<li>configurationsCommonPrefix + interfaceClass.getSimpleName() + ".phase"</li>
<li>configurationsCommonPrefix + StringUtils.uncapitalize(interfaceClass.getSimpleName()) + ".phase"</li>
</ol>
for the phase, and
<ol>
<li>configurationsCommonPrefix + this.getClass().getName() + ".autoStart"</li>
<li>configurationsCommonPrefix + this.getClass().getSimpleName() + ".autoStart"</li>
<li>configurationsCommonPrefix + StringUtils.uncapitalize(this.getClass().getSimpleName()) + ".autoStart"</li>
<li>configurationsCommonPrefix + interfaceClass.getName() + ".autoStart"</li>
<li>configurationsCommonPrefix + interfaceClass.getSimpleName() + ".autoStart"</li>
<li>configurationsCommonPrefix + StringUtils.uncapitalize(interfaceClass.getSimpleName()) + ".autoStart"</li>
</ol>
for the auto-start.
<p>The first one with non-null value wins.</p> | [
"Configure",
"isAutoStart",
"and",
"phase",
"from",
"properties",
".",
"For",
"example",
"if",
"the",
"class",
"name",
"of",
"the",
"service",
"is",
"a",
".",
"b",
".",
"Xyz",
"then",
"the",
"properties",
"will",
"be",
"some",
"thing",
"like",
":",
"<ul"... | train | https://github.com/james-hu/jabb-core/blob/bceed441595c5e5195a7418795f03b69fa7b61e4/src/main/java/net/sf/jabb/spring/service/AbstractSmartLifecycleService.java#L99-L114 |
mijecu25/dsa | src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java | LinearSearch.searchLast | public static int searchLast(short[] shortArray, short value, int occurrence) {
if(occurrence <= 0 || occurrence > shortArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = shortArray.length-1; i >=0; i--) {
if(shortArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | java | public static int searchLast(short[] shortArray, short value, int occurrence) {
if(occurrence <= 0 || occurrence > shortArray.length) {
throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than "
+ "the array length: " + occurrence);
}
int valuesSeen = 0;
for(int i = shortArray.length-1; i >=0; i--) {
if(shortArray[i] == value) {
valuesSeen++;
if(valuesSeen == occurrence) {
return i;
}
}
}
return -1;
} | [
"public",
"static",
"int",
"searchLast",
"(",
"short",
"[",
"]",
"shortArray",
",",
"short",
"value",
",",
"int",
"occurrence",
")",
"{",
"if",
"(",
"occurrence",
"<=",
"0",
"||",
"occurrence",
">",
"shortArray",
".",
"length",
")",
"{",
"throw",
"new",
... | Search for the value in the short array and return the index of the first occurrence from the
end of the array.
@param shortArray array that we are searching in.
@param value value that is being searched in the array.
@param occurrence number of times we have seen the value before returning the index.
@return the index where the value is found in the array, else -1. | [
"Search",
"for",
"the",
"value",
"in",
"the",
"short",
"array",
"and",
"return",
"the",
"index",
"of",
"the",
"first",
"occurrence",
"from",
"the",
"end",
"of",
"the",
"array",
"."
] | train | https://github.com/mijecu25/dsa/blob/a22971b746833e78a3939ae4de65e8f6bf2e3fd4/src/main/java/com/mijecu25/dsa/algorithms/search/linear/LinearSearch.java#L1620-L1639 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java | CommerceAvailabilityEstimatePersistenceImpl.removeByUuid_C | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceAvailabilityEstimate commerceAvailabilityEstimate : findByUuid_C(
uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceAvailabilityEstimate);
}
} | java | @Override
public void removeByUuid_C(String uuid, long companyId) {
for (CommerceAvailabilityEstimate commerceAvailabilityEstimate : findByUuid_C(
uuid, companyId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
remove(commerceAvailabilityEstimate);
}
} | [
"@",
"Override",
"public",
"void",
"removeByUuid_C",
"(",
"String",
"uuid",
",",
"long",
"companyId",
")",
"{",
"for",
"(",
"CommerceAvailabilityEstimate",
"commerceAvailabilityEstimate",
":",
"findByUuid_C",
"(",
"uuid",
",",
"companyId",
",",
"QueryUtil",
".",
"... | Removes all the commerce availability estimates where uuid = ? and companyId = ? from the database.
@param uuid the uuid
@param companyId the company ID | [
"Removes",
"all",
"the",
"commerce",
"availability",
"estimates",
"where",
"uuid",
"=",
"?",
";",
"and",
"companyId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAvailabilityEstimatePersistenceImpl.java#L1428-L1434 |
line/armeria | grpc-protocol/src/main/java/com/linecorp/armeria/common/grpc/protocol/StatusMessageEscaper.java | StatusMessageEscaper.doEscape | private static String doEscape(byte[] valueBytes, int ri) {
final byte[] escapedBytes = new byte[ri + (valueBytes.length - ri) * 3];
// copy over the good bytes
if (ri != 0) {
System.arraycopy(valueBytes, 0, escapedBytes, 0, ri);
}
int wi = ri;
for (; ri < valueBytes.length; ri++) {
final byte b = valueBytes[ri];
// Manually implement URL encoding, per the gRPC spec.
if (isEscapingChar(b)) {
escapedBytes[wi] = '%';
escapedBytes[wi + 1] = HEX[(b >> 4) & 0xF];
escapedBytes[wi + 2] = HEX[b & 0xF];
wi += 3;
continue;
}
escapedBytes[wi++] = b;
}
final byte[] dest = new byte[wi];
System.arraycopy(escapedBytes, 0, dest, 0, wi);
return new String(dest, StandardCharsets.US_ASCII);
} | java | private static String doEscape(byte[] valueBytes, int ri) {
final byte[] escapedBytes = new byte[ri + (valueBytes.length - ri) * 3];
// copy over the good bytes
if (ri != 0) {
System.arraycopy(valueBytes, 0, escapedBytes, 0, ri);
}
int wi = ri;
for (; ri < valueBytes.length; ri++) {
final byte b = valueBytes[ri];
// Manually implement URL encoding, per the gRPC spec.
if (isEscapingChar(b)) {
escapedBytes[wi] = '%';
escapedBytes[wi + 1] = HEX[(b >> 4) & 0xF];
escapedBytes[wi + 2] = HEX[b & 0xF];
wi += 3;
continue;
}
escapedBytes[wi++] = b;
}
final byte[] dest = new byte[wi];
System.arraycopy(escapedBytes, 0, dest, 0, wi);
return new String(dest, StandardCharsets.US_ASCII);
} | [
"private",
"static",
"String",
"doEscape",
"(",
"byte",
"[",
"]",
"valueBytes",
",",
"int",
"ri",
")",
"{",
"final",
"byte",
"[",
"]",
"escapedBytes",
"=",
"new",
"byte",
"[",
"ri",
"+",
"(",
"valueBytes",
".",
"length",
"-",
"ri",
")",
"*",
"3",
"... | Escapes the given byte array.
@param valueBytes the UTF-8 bytes
@param ri The reader index, pointed at the first byte that needs escaping. | [
"Escapes",
"the",
"given",
"byte",
"array",
"."
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/grpc-protocol/src/main/java/com/linecorp/armeria/common/grpc/protocol/StatusMessageEscaper.java#L86-L109 |
groupon/odo | client/src/main/java/com/groupon/odo/client/Client.java | Client.enableServerMapping | public ServerRedirect enableServerMapping(int serverMappingId, Boolean enabled) {
ServerRedirect redirect = new ServerRedirect();
BasicNameValuePair[] params = {
new BasicNameValuePair("enabled", enabled.toString()),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
try {
JSONObject response = new JSONObject(doPost(BASE_SERVER + "/" + serverMappingId, params));
redirect = getServerRedirectFromJSON(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return redirect;
} | java | public ServerRedirect enableServerMapping(int serverMappingId, Boolean enabled) {
ServerRedirect redirect = new ServerRedirect();
BasicNameValuePair[] params = {
new BasicNameValuePair("enabled", enabled.toString()),
new BasicNameValuePair("profileIdentifier", this._profileName)
};
try {
JSONObject response = new JSONObject(doPost(BASE_SERVER + "/" + serverMappingId, params));
redirect = getServerRedirectFromJSON(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return redirect;
} | [
"public",
"ServerRedirect",
"enableServerMapping",
"(",
"int",
"serverMappingId",
",",
"Boolean",
"enabled",
")",
"{",
"ServerRedirect",
"redirect",
"=",
"new",
"ServerRedirect",
"(",
")",
";",
"BasicNameValuePair",
"[",
"]",
"params",
"=",
"{",
"new",
"BasicNameV... | Enable/disable a server mapping
@param serverMappingId ID of server mapping
@param enabled true to enable, false to disable
@return updated info for the ServerRedirect | [
"Enable",
"/",
"disable",
"a",
"server",
"mapping"
] | train | https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L1090-L1104 |
ZuInnoTe/hadoopoffice | fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/parser/msexcel/internal/EncryptedCachedDiskStringsTable.java | EncryptedCachedDiskStringsTable.accessTempFile | private void accessTempFile(long position) throws IOException {
if ((position == 0L) || (position < this.currentPos)) { // in those cases we have to read from scratch
this.in = new FileInputStream(this.tempFile);
if (this.ca != null) {
// decrypt
this.in = new CipherInputStream(this.in, this.ciDecrypt);
}
if (this.compressTempFile) { // decompress it
this.in = new GZIPInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
} else { // configure a buffer for reading it
this.in = new BufferedInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
}
this.currentPos = 0L;
} else if (position > this.currentPos) {
this.in.skip(position - this.currentPos);
this.currentPos = position; // attention needs to be updated after read!
}
} | java | private void accessTempFile(long position) throws IOException {
if ((position == 0L) || (position < this.currentPos)) { // in those cases we have to read from scratch
this.in = new FileInputStream(this.tempFile);
if (this.ca != null) {
// decrypt
this.in = new CipherInputStream(this.in, this.ciDecrypt);
}
if (this.compressTempFile) { // decompress it
this.in = new GZIPInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
} else { // configure a buffer for reading it
this.in = new BufferedInputStream(this.in, EncryptedCachedDiskStringsTable.compressBufferSize);
}
this.currentPos = 0L;
} else if (position > this.currentPos) {
this.in.skip(position - this.currentPos);
this.currentPos = position; // attention needs to be updated after read!
}
} | [
"private",
"void",
"accessTempFile",
"(",
"long",
"position",
")",
"throws",
"IOException",
"{",
"if",
"(",
"(",
"position",
"==",
"0L",
")",
"||",
"(",
"position",
"<",
"this",
".",
"currentPos",
")",
")",
"{",
"// in those cases we have to read from scratch",
... | *
Simulates random access to the tempfile even if not supported due to
encryption and/or compression
@param position
@throws IOException | [
"*",
"Simulates",
"random",
"access",
"to",
"the",
"tempfile",
"even",
"if",
"not",
"supported",
"due",
"to",
"encryption",
"and",
"/",
"or",
"compression"
] | train | https://github.com/ZuInnoTe/hadoopoffice/blob/58fc9223ee290bcb14847aaaff3fadf39c465e46/fileformat/src/main/java/org/zuinnote/hadoop/office/format/common/parser/msexcel/internal/EncryptedCachedDiskStringsTable.java#L413-L431 |
threerings/narya | core/src/main/java/com/threerings/presents/peer/server/PeerManager.java | PeerManager.invokeOnNodes | public int invokeOnNodes (Function<Tuple<Client,NodeObject>,Boolean> func)
{
int invoked = 0;
for (PeerNode peer : _peers.values()) {
if (peer.nodeobj != null) {
if (func.apply(Tuple.newTuple(peer.getClient(), peer.nodeobj))) {
invoked++;
}
}
}
return invoked;
} | java | public int invokeOnNodes (Function<Tuple<Client,NodeObject>,Boolean> func)
{
int invoked = 0;
for (PeerNode peer : _peers.values()) {
if (peer.nodeobj != null) {
if (func.apply(Tuple.newTuple(peer.getClient(), peer.nodeobj))) {
invoked++;
}
}
}
return invoked;
} | [
"public",
"int",
"invokeOnNodes",
"(",
"Function",
"<",
"Tuple",
"<",
"Client",
",",
"NodeObject",
">",
",",
"Boolean",
">",
"func",
")",
"{",
"int",
"invoked",
"=",
"0",
";",
"for",
"(",
"PeerNode",
"peer",
":",
"_peers",
".",
"values",
"(",
")",
")... | Invokes the supplied function on <em>all</em> node objects (except the local node). A caller
that needs to call an invocation service method on a remote node should use this mechanism
to locate the appropriate node (or nodes) and call the desired method.
@return the number of times the invoked function returned true. | [
"Invokes",
"the",
"supplied",
"function",
"on",
"<em",
">",
"all<",
"/",
"em",
">",
"node",
"objects",
"(",
"except",
"the",
"local",
"node",
")",
".",
"A",
"caller",
"that",
"needs",
"to",
"call",
"an",
"invocation",
"service",
"method",
"on",
"a",
"r... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/peer/server/PeerManager.java#L446-L457 |
jenkinsci/pipeline-maven-plugin | jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/MavenLinkerPublisher2.java | MavenLinkerPublisher2.process | @Override
public synchronized void process(StepContext context, Element mavenSpyLogsElt) throws IOException, InterruptedException {
Run<?, ?> run = context.get(Run.class);
// we replace instead of because we want to refresh the cache org.jenkinsci.plugins.pipeline.maven.publishers.MavenReport.getGeneratedArtifacts()
run.addOrReplaceAction(new MavenReport(run));
} | java | @Override
public synchronized void process(StepContext context, Element mavenSpyLogsElt) throws IOException, InterruptedException {
Run<?, ?> run = context.get(Run.class);
// we replace instead of because we want to refresh the cache org.jenkinsci.plugins.pipeline.maven.publishers.MavenReport.getGeneratedArtifacts()
run.addOrReplaceAction(new MavenReport(run));
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"process",
"(",
"StepContext",
"context",
",",
"Element",
"mavenSpyLogsElt",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"Run",
"<",
"?",
",",
"?",
">",
"run",
"=",
"context",
".",
"get",
... | Synchronize because {@link Run#addOrReplaceAction(hudson.model.Action)} is not thread safe | [
"Synchronize",
"because",
"{"
] | train | https://github.com/jenkinsci/pipeline-maven-plugin/blob/685d7dbb894fb4c976dbfa922e3caba8e8d5bed8/jenkins-plugin/src/main/java/org/jenkinsci/plugins/pipeline/maven/publishers/MavenLinkerPublisher2.java#L42-L47 |
sarl/sarl | main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/codebuilder/extractor/AbstractCodeElementExtractor.java | AbstractCodeElementExtractor.getContainerInRule | protected EObject getContainerInRule(EObject root, EObject content) {
EObject container = content;
do {
final EClassifier classifier = getGeneratedTypeFor(container);
if (classifier != null) {
return container;
}
container = container.eContainer();
} while (container != root);
final EClassifier classifier = getGeneratedTypeFor(root);
if (classifier != null) {
return root;
}
return null;
} | java | protected EObject getContainerInRule(EObject root, EObject content) {
EObject container = content;
do {
final EClassifier classifier = getGeneratedTypeFor(container);
if (classifier != null) {
return container;
}
container = container.eContainer();
} while (container != root);
final EClassifier classifier = getGeneratedTypeFor(root);
if (classifier != null) {
return root;
}
return null;
} | [
"protected",
"EObject",
"getContainerInRule",
"(",
"EObject",
"root",
",",
"EObject",
"content",
")",
"{",
"EObject",
"container",
"=",
"content",
";",
"do",
"{",
"final",
"EClassifier",
"classifier",
"=",
"getGeneratedTypeFor",
"(",
"container",
")",
";",
"if",... | Replies the container in the grammar rule for the given content element.
@param root the biggest enclosing element to consider in the grammar.
@param content the grammar element to search for the container.
@return the container of the content. | [
"Replies",
"the",
"container",
"in",
"the",
"grammar",
"rule",
"for",
"the",
"given",
"content",
"element",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/codebuilder/extractor/AbstractCodeElementExtractor.java#L157-L171 |
matthewhorridge/binaryowl | src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java | BinaryOWLMetadata.getLongAttribute | public Long getLongAttribute(String name, Long defaultValue) {
return getValue(longAttributes, name, defaultValue);
} | java | public Long getLongAttribute(String name, Long defaultValue) {
return getValue(longAttributes, name, defaultValue);
} | [
"public",
"Long",
"getLongAttribute",
"(",
"String",
"name",
",",
"Long",
"defaultValue",
")",
"{",
"return",
"getValue",
"(",
"longAttributes",
",",
"name",
",",
"defaultValue",
")",
";",
"}"
] | Gets the long value of an attribute.
@param name The name of the attribute. Not null.
@param defaultValue The default value for the attribute. May be null. This value will be returned if this
metadata object does not contain a long value for the specified attribute name.
@return Either the long value of the attribute with the specified name, or the value specified by the defaultValue
object if this metadata object does not contain a long value for the specified attribute name.
@throws NullPointerException if name is null. | [
"Gets",
"the",
"long",
"value",
"of",
"an",
"attribute",
"."
] | train | https://github.com/matthewhorridge/binaryowl/blob/7fccfe804120f86b38ca855ddbb569a81a042257/src/main/java/org/semanticweb/binaryowl/BinaryOWLMetadata.java#L323-L325 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/StructurizrDocumentationTemplate.java | StructurizrDocumentationTemplate.addComponentsSection | @Nonnull
public Section addComponentsSection(@Nullable Container container, @Nonnull Format format, @Nonnull String content) {
return addSection(container, "Components", format, content);
} | java | @Nonnull
public Section addComponentsSection(@Nullable Container container, @Nonnull Format format, @Nonnull String content) {
return addSection(container, "Components", format, content);
} | [
"@",
"Nonnull",
"public",
"Section",
"addComponentsSection",
"(",
"@",
"Nullable",
"Container",
"container",
",",
"@",
"Nonnull",
"Format",
"format",
",",
"@",
"Nonnull",
"String",
"content",
")",
"{",
"return",
"addSection",
"(",
"container",
",",
"\"Components... | Adds a "Components" section relating to a {@link Container}.
@param container the {@link Container} the documentation content relates to
@param format the {@link Format} of the documentation content
@param content a String containing the documentation content
@return a documentation {@link Section} | [
"Adds",
"a",
"Components",
"section",
"relating",
"to",
"a",
"{",
"@link",
"Container",
"}",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/StructurizrDocumentationTemplate.java#L252-L255 |
google/error-prone | core/src/main/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClash.java | FunctionalInterfaceClash.functionalInterfaceSignature | private static String functionalInterfaceSignature(VisitorState state, MethodSymbol msym) {
return String.format(
"%s(%s)",
msym.getSimpleName(),
msym.getParameters().stream()
.map(p -> functionalInterfaceSignature(state, p.type))
.collect(joining(",")));
} | java | private static String functionalInterfaceSignature(VisitorState state, MethodSymbol msym) {
return String.format(
"%s(%s)",
msym.getSimpleName(),
msym.getParameters().stream()
.map(p -> functionalInterfaceSignature(state, p.type))
.collect(joining(",")));
} | [
"private",
"static",
"String",
"functionalInterfaceSignature",
"(",
"VisitorState",
"state",
",",
"MethodSymbol",
"msym",
")",
"{",
"return",
"String",
".",
"format",
"(",
"\"%s(%s)\"",
",",
"msym",
".",
"getSimpleName",
"(",
")",
",",
"msym",
".",
"getParameter... | A string representation of a method descriptor, where all parameters whose type is a functional
interface are "erased" to the interface's function type. For example, `foo(Supplier<String>)`
is represented as `foo(()->Ljava/lang/String;)`. | [
"A",
"string",
"representation",
"of",
"a",
"method",
"descriptor",
"where",
"all",
"parameters",
"whose",
"type",
"is",
"a",
"functional",
"interface",
"are",
"erased",
"to",
"the",
"interface",
"s",
"function",
"type",
".",
"For",
"example",
"foo",
"(",
"S... | train | https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/FunctionalInterfaceClash.java#L138-L145 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/util/LightWeightHashSet.java | LightWeightHashSet.containsElem | protected boolean containsElem(int index, final T key, int hashCode) {
for (LinkedElement<T> e = entries[index]; e != null; e = e.next) {
// element found
if (hashCode == e.hashCode && e.element.equals(key)) {
return true;
}
}
// element not found
return false;
} | java | protected boolean containsElem(int index, final T key, int hashCode) {
for (LinkedElement<T> e = entries[index]; e != null; e = e.next) {
// element found
if (hashCode == e.hashCode && e.element.equals(key)) {
return true;
}
}
// element not found
return false;
} | [
"protected",
"boolean",
"containsElem",
"(",
"int",
"index",
",",
"final",
"T",
"key",
",",
"int",
"hashCode",
")",
"{",
"for",
"(",
"LinkedElement",
"<",
"T",
">",
"e",
"=",
"entries",
"[",
"index",
"]",
";",
"e",
"!=",
"null",
";",
"e",
"=",
"e",... | Check if the set contains given element at given index.
@return true if element present, false otherwise. | [
"Check",
"if",
"the",
"set",
"contains",
"given",
"element",
"at",
"given",
"index",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/util/LightWeightHashSet.java#L193-L202 |
liferay/com-liferay-commerce | commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java | CommerceWishListItemPersistenceImpl.findByCProductId | @Override
public List<CommerceWishListItem> findByCProductId(long CProductId,
int start, int end,
OrderByComparator<CommerceWishListItem> orderByComparator) {
return findByCProductId(CProductId, start, end, orderByComparator, true);
} | java | @Override
public List<CommerceWishListItem> findByCProductId(long CProductId,
int start, int end,
OrderByComparator<CommerceWishListItem> orderByComparator) {
return findByCProductId(CProductId, start, end, orderByComparator, true);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceWishListItem",
">",
"findByCProductId",
"(",
"long",
"CProductId",
",",
"int",
"start",
",",
"int",
"end",
",",
"OrderByComparator",
"<",
"CommerceWishListItem",
">",
"orderByComparator",
")",
"{",
"return",
"findBy... | Returns an ordered range of all the commerce wish list items where CProductId = ?.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceWishListItemModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param CProductId the c product ID
@param start the lower bound of the range of commerce wish list items
@param end the upper bound of the range of commerce wish list items (not inclusive)
@param orderByComparator the comparator to order the results by (optionally <code>null</code>)
@return the ordered range of matching commerce wish list items | [
"Returns",
"an",
"ordered",
"range",
"of",
"all",
"the",
"commerce",
"wish",
"list",
"items",
"where",
"CProductId",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-wish-list-service/src/main/java/com/liferay/commerce/wish/list/service/persistence/impl/CommerceWishListItemPersistenceImpl.java#L1260-L1265 |
wisdom-framework/wisdom | core/wisdom-vertx-engine/src/main/java/org/wisdom/framework/vertx/RequestFromVertx.java | RequestFromVertx.parameterAsBoolean | @Override
public Boolean parameterAsBoolean(String name, boolean defaultValue) {
// We have to check if the map contains the key, as the retrieval method returns false on missing key.
if (!request.params().contains(name)) {
return defaultValue;
}
Boolean parameter = parameterAsBoolean(name);
if (parameter == null) {
return defaultValue;
}
return parameter;
} | java | @Override
public Boolean parameterAsBoolean(String name, boolean defaultValue) {
// We have to check if the map contains the key, as the retrieval method returns false on missing key.
if (!request.params().contains(name)) {
return defaultValue;
}
Boolean parameter = parameterAsBoolean(name);
if (parameter == null) {
return defaultValue;
}
return parameter;
} | [
"@",
"Override",
"public",
"Boolean",
"parameterAsBoolean",
"(",
"String",
"name",
",",
"boolean",
"defaultValue",
")",
"{",
"// We have to check if the map contains the key, as the retrieval method returns false on missing key.",
"if",
"(",
"!",
"request",
".",
"params",
"("... | Same like {@link #parameter(String)}, but converts the parameter to
Boolean if found.
<p/>
The parameter is decoded by default.
@param name The name of the post or query parameter
@param defaultValue A default value if parameter not found.
@return The value of the parameter or the defaultValue if not found. | [
"Same",
"like",
"{",
"@link",
"#parameter",
"(",
"String",
")",
"}",
"but",
"converts",
"the",
"parameter",
"to",
"Boolean",
"if",
"found",
".",
"<p",
"/",
">",
"The",
"parameter",
"is",
"decoded",
"by",
"default",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/core/wisdom-vertx-engine/src/main/java/org/wisdom/framework/vertx/RequestFromVertx.java#L477-L488 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/config/util/DirectedAcyclicGraphVerifier.java | DirectedAcyclicGraphVerifier.addDependencies | private static <T> void addDependencies(final Vertex<T> vertex, final List<Vertex<T>> vertices)
{
if (!vertices.contains(vertex))
{
vertices.add(vertex);
for (Vertex<T> v : vertex.getDependencies())
{
addDependencies(v, vertices);
}
}
} | java | private static <T> void addDependencies(final Vertex<T> vertex, final List<Vertex<T>> vertices)
{
if (!vertices.contains(vertex))
{
vertices.add(vertex);
for (Vertex<T> v : vertex.getDependencies())
{
addDependencies(v, vertices);
}
}
} | [
"private",
"static",
"<",
"T",
">",
"void",
"addDependencies",
"(",
"final",
"Vertex",
"<",
"T",
">",
"vertex",
",",
"final",
"List",
"<",
"Vertex",
"<",
"T",
">",
">",
"vertices",
")",
"{",
"if",
"(",
"!",
"vertices",
".",
"contains",
"(",
"vertex",... | Recursively add a vertex and all of its dependencies to a list of
vertices
@param vertex Vertex to be added.
@param vertices Existing list of vertices. | [
"Recursively",
"add",
"a",
"vertex",
"and",
"all",
"of",
"its",
"dependencies",
"to",
"a",
"list",
"of",
"vertices"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/config/util/DirectedAcyclicGraphVerifier.java#L62-L73 |
rollbar/rollbar-java | rollbar-android/src/main/java/com/rollbar/android/Rollbar.java | Rollbar.reportMessage | @Deprecated
public static void reportMessage(final String message, final String level, final Map<String, String> params) {
ensureInit(new Runnable() {
@Override
public void run() {
notifier.log(message, params != null ? Collections.<String, Object>unmodifiableMap(params) : null, Level.lookupByName(level));
}
});
} | java | @Deprecated
public static void reportMessage(final String message, final String level, final Map<String, String> params) {
ensureInit(new Runnable() {
@Override
public void run() {
notifier.log(message, params != null ? Collections.<String, Object>unmodifiableMap(params) : null, Level.lookupByName(level));
}
});
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"reportMessage",
"(",
"final",
"String",
"message",
",",
"final",
"String",
"level",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"{",
"ensureInit",
"(",
"new",
"Runnable",
"(",
")",
... | Report a message to Rollbar, specifying the level, and including extra data.
@param message the message to send.
@param level the severity level.
@param params the extra data. | [
"Report",
"a",
"message",
"to",
"Rollbar",
"specifying",
"the",
"level",
"and",
"including",
"extra",
"data",
"."
] | train | https://github.com/rollbar/rollbar-java/blob/5eb4537d1363722b51cfcce55b427cbd8489f17b/rollbar-android/src/main/java/com/rollbar/android/Rollbar.java#L883-L891 |
unbescape/unbescape | src/main/java/org/unbescape/properties/PropertiesEscape.java | PropertiesEscape.escapePropertiesValueMinimal | public static void escapePropertiesValueMinimal(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapePropertiesValue(text, offset, len, writer, PropertiesValueEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET);
} | java | public static void escapePropertiesValueMinimal(final char[] text, final int offset, final int len, final Writer writer)
throws IOException {
escapePropertiesValue(text, offset, len, writer, PropertiesValueEscapeLevel.LEVEL_1_BASIC_ESCAPE_SET);
} | [
"public",
"static",
"void",
"escapePropertiesValueMinimal",
"(",
"final",
"char",
"[",
"]",
"text",
",",
"final",
"int",
"offset",
",",
"final",
"int",
"len",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"escapePropertiesValue",
"(",
"t... | <p>
Perform a Java Properties Value level 1 (only basic set) <strong>escape</strong> operation
on a <tt>char[]</tt> input.
</p>
<p>
<em>Level 1</em> means this method will only escape the Java Properties basic escape set:
</p>
<ul>
<li>The <em>Single Escape Characters</em>:
<tt>\t</tt> (<tt>U+0009</tt>),
<tt>\n</tt> (<tt>U+000A</tt>),
<tt>\f</tt> (<tt>U+000C</tt>),
<tt>\r</tt> (<tt>U+000D</tt>) and
<tt>\\</tt> (<tt>U+005C</tt>).
</li>
<li>
Two ranges of non-displayable, control characters (some of which are already part of the
<em>single escape characters</em> list): <tt>U+0000</tt> to <tt>U+001F</tt>
and <tt>U+007F</tt> to <tt>U+009F</tt>.
</li>
</ul>
<p>
This method calls {@link #escapePropertiesValue(char[], int, int, java.io.Writer, PropertiesValueEscapeLevel)}
with the following preconfigured values:
</p>
<ul>
<li><tt>level</tt>:
{@link PropertiesValueEscapeLevel#LEVEL_1_BASIC_ESCAPE_SET}</li>
</ul>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>char[]</tt> to be escaped.
@param offset the position in <tt>text</tt> at which the escape operation should start.
@param len the number of characters in <tt>text</tt> that should be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs | [
"<p",
">",
"Perform",
"a",
"Java",
"Properties",
"Value",
"level",
"1",
"(",
"only",
"basic",
"set",
")",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"char",
"[]",
"<",
"/",
"tt",
">",
"input",
".",
"<",
"/",
... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/properties/PropertiesEscape.java#L630-L633 |
structr/structr | structr-ui/src/main/java/org/structr/web/common/FileHelper.java | FileHelper.createFile | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final Class<T> fileType, final PropertyMap props)
throws FrameworkException, IOException {
T newFile = (T) StructrApp.getInstance(securityContext).create(fileType, props);
setFileData(newFile, fileStream, props.get(StructrApp.key(File.class, "contentType")));
// schedule indexing
newFile.notifyUploadCompletion();
return newFile;
} | java | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final Class<T> fileType, final PropertyMap props)
throws FrameworkException, IOException {
T newFile = (T) StructrApp.getInstance(securityContext).create(fileType, props);
setFileData(newFile, fileStream, props.get(StructrApp.key(File.class, "contentType")));
// schedule indexing
newFile.notifyUploadCompletion();
return newFile;
} | [
"public",
"static",
"<",
"T",
"extends",
"File",
">",
"T",
"createFile",
"(",
"final",
"SecurityContext",
"securityContext",
",",
"final",
"InputStream",
"fileStream",
",",
"final",
"Class",
"<",
"T",
">",
"fileType",
",",
"final",
"PropertyMap",
"props",
")",... | Create a new file node from the given input stream and sets the parentFolder
@param <T>
@param securityContext
@param fileStream
@param fileType defaults to File.class if null
@param props
@return file
@throws FrameworkException
@throws IOException | [
"Create",
"a",
"new",
"file",
"node",
"from",
"the",
"given",
"input",
"stream",
"and",
"sets",
"the",
"parentFolder"
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/common/FileHelper.java#L182-L193 |
sarl/sarl | docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/utils/Utils.java | Utils.findFirst | public static <T extends ProgramElementDoc> T findFirst(T[] original, boolean ignoreHidden, Predicate<T> filter) {
for (final T element : original) {
if (!ignoreHidden || !isHiddenMember(element.name())) {
if (filter.test(element)) {
return element;
}
}
}
return null;
} | java | public static <T extends ProgramElementDoc> T findFirst(T[] original, boolean ignoreHidden, Predicate<T> filter) {
for (final T element : original) {
if (!ignoreHidden || !isHiddenMember(element.name())) {
if (filter.test(element)) {
return element;
}
}
}
return null;
} | [
"public",
"static",
"<",
"T",
"extends",
"ProgramElementDoc",
">",
"T",
"findFirst",
"(",
"T",
"[",
"]",
"original",
",",
"boolean",
"ignoreHidden",
",",
"Predicate",
"<",
"T",
">",
"filter",
")",
"{",
"for",
"(",
"final",
"T",
"element",
":",
"original"... | Find the first element into the given array.
@param <T> the type of the elements to filter.
@param original the original array.
@param ignoreHidden indicates if the hidden elements should be ignored.
@param filter the filtering action.
@return the first element. | [
"Find",
"the",
"first",
"element",
"into",
"the",
"given",
"array",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/docs/io.sarl.docs.doclet/src/main/java/io/sarl/docs/doclet/utils/Utils.java#L170-L179 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/PeopleApi.java | PeopleApi.getPublicGroups | public Groups getPublicGroups(String userId, Boolean invitationOnly, boolean sign) throws JinxException {
JinxUtils.validateParams(userId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.people.getPublicGroups");
params.put("user_id", userId);
if (invitationOnly != null) {
params.put("invitation_only", invitationOnly ? "1" : "0");
}
return jinx.flickrGet(params, Groups.class, sign);
} | java | public Groups getPublicGroups(String userId, Boolean invitationOnly, boolean sign) throws JinxException {
JinxUtils.validateParams(userId);
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.people.getPublicGroups");
params.put("user_id", userId);
if (invitationOnly != null) {
params.put("invitation_only", invitationOnly ? "1" : "0");
}
return jinx.flickrGet(params, Groups.class, sign);
} | [
"public",
"Groups",
"getPublicGroups",
"(",
"String",
"userId",
",",
"Boolean",
"invitationOnly",
",",
"boolean",
"sign",
")",
"throws",
"JinxException",
"{",
"JinxUtils",
".",
"validateParams",
"(",
"userId",
")",
";",
"Map",
"<",
"String",
",",
"String",
">"... | Returns the list of public groups a user is a member of.
<br>
This method does not require authentication.
@param userId (Required) The userId of the user to fetch groups for.
@param invitationOnly (Optional) Include public groups that require an invitation or administrator approval to join.
@param sign if true, the request will be signed.
@return object with the public groups the user is a member of.
@throws JinxException if required parameters are missing, or if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.people.getPublicGroups.html">flickr.people.getPublicGroups</a> | [
"Returns",
"the",
"list",
"of",
"public",
"groups",
"a",
"user",
"is",
"a",
"member",
"of",
".",
"<br",
">",
"This",
"method",
"does",
"not",
"require",
"authentication",
"."
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PeopleApi.java#L260-L269 |
sagiegurari/fax4j | src/main/java/org/fax4j/bridge/http/SimpleHTTPRequestParser.java | SimpleHTTPRequestParser.updateFaxJobFromInputDataImpl | @Override
protected void updateFaxJobFromInputDataImpl(HTTPRequest inputData,FaxJob faxJob)
{
//get parameters text as map
Map<String,String> queryStringMap=this.convertParametersTextToMap(inputData);
//update fax job
this.updateFaxJobFromRequestImpl(inputData,faxJob,queryStringMap);
} | java | @Override
protected void updateFaxJobFromInputDataImpl(HTTPRequest inputData,FaxJob faxJob)
{
//get parameters text as map
Map<String,String> queryStringMap=this.convertParametersTextToMap(inputData);
//update fax job
this.updateFaxJobFromRequestImpl(inputData,faxJob,queryStringMap);
} | [
"@",
"Override",
"protected",
"void",
"updateFaxJobFromInputDataImpl",
"(",
"HTTPRequest",
"inputData",
",",
"FaxJob",
"faxJob",
")",
"{",
"//get parameters text as map",
"Map",
"<",
"String",
",",
"String",
">",
"queryStringMap",
"=",
"this",
".",
"convertParametersT... | This function update the fax job from the request data.<br>
This fax job will not have any file data.
@param inputData
The input data
@param faxJob
The fax job to update | [
"This",
"function",
"update",
"the",
"fax",
"job",
"from",
"the",
"request",
"data",
".",
"<br",
">",
"This",
"fax",
"job",
"will",
"not",
"have",
"any",
"file",
"data",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/bridge/http/SimpleHTTPRequestParser.java#L88-L96 |
apollographql/apollo-android | apollo-rx-support/src/main/java/com/apollographql/apollo/rx/RxApollo.java | RxApollo.from | @NotNull public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
return from(call, Emitter.BackpressureMode.BUFFER);
} | java | @NotNull public static <T> Observable<Response<T>> from(@NotNull final ApolloCall<T> call) {
return from(call, Emitter.BackpressureMode.BUFFER);
} | [
"@",
"NotNull",
"public",
"static",
"<",
"T",
">",
"Observable",
"<",
"Response",
"<",
"T",
">",
">",
"from",
"(",
"@",
"NotNull",
"final",
"ApolloCall",
"<",
"T",
">",
"call",
")",
"{",
"return",
"from",
"(",
"call",
",",
"Emitter",
".",
"Backpressu... | Converts an {@link ApolloCall} to a Observable with backpressure mode {@link rx.Emitter.BackpressureMode#BUFFER}.
The number of emissions this Observable will have is based on the {@link ResponseFetcher} used with the call.
@param call the ApolloCall to convert
@param <T> the value type
@return the converted Observable | [
"Converts",
"an",
"{",
"@link",
"ApolloCall",
"}",
"to",
"a",
"Observable",
"with",
"backpressure",
"mode",
"{",
"@link",
"rx",
".",
"Emitter",
".",
"BackpressureMode#BUFFER",
"}",
".",
"The",
"number",
"of",
"emissions",
"this",
"Observable",
"will",
"have",
... | train | https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-rx-support/src/main/java/com/apollographql/apollo/rx/RxApollo.java#L218-L220 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/core/Parser.java | Parser.parseDeleteKeyword | public static boolean parseDeleteKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'd'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'e'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | java | public static boolean parseDeleteKeyword(final char[] query, int offset) {
if (query.length < (offset + 6)) {
return false;
}
return (query[offset] | 32) == 'd'
&& (query[offset + 1] | 32) == 'e'
&& (query[offset + 2] | 32) == 'l'
&& (query[offset + 3] | 32) == 'e'
&& (query[offset + 4] | 32) == 't'
&& (query[offset + 5] | 32) == 'e';
} | [
"public",
"static",
"boolean",
"parseDeleteKeyword",
"(",
"final",
"char",
"[",
"]",
"query",
",",
"int",
"offset",
")",
"{",
"if",
"(",
"query",
".",
"length",
"<",
"(",
"offset",
"+",
"6",
")",
")",
"{",
"return",
"false",
";",
"}",
"return",
"(",
... | Parse string to check presence of DELETE keyword regardless of case. The initial character is
assumed to have been matched.
@param query char[] of the query statement
@param offset position of query to start checking
@return boolean indicates presence of word | [
"Parse",
"string",
"to",
"check",
"presence",
"of",
"DELETE",
"keyword",
"regardless",
"of",
"case",
".",
"The",
"initial",
"character",
"is",
"assumed",
"to",
"have",
"been",
"matched",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/core/Parser.java#L562-L573 |
Azure/azure-sdk-for-java | logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java | IntegrationAccountsInner.updateAsync | public Observable<IntegrationAccountInner> updateAsync(String resourceGroupName, String integrationAccountName, IntegrationAccountInner integrationAccount) {
return updateWithServiceResponseAsync(resourceGroupName, integrationAccountName, integrationAccount).map(new Func1<ServiceResponse<IntegrationAccountInner>, IntegrationAccountInner>() {
@Override
public IntegrationAccountInner call(ServiceResponse<IntegrationAccountInner> response) {
return response.body();
}
});
} | java | public Observable<IntegrationAccountInner> updateAsync(String resourceGroupName, String integrationAccountName, IntegrationAccountInner integrationAccount) {
return updateWithServiceResponseAsync(resourceGroupName, integrationAccountName, integrationAccount).map(new Func1<ServiceResponse<IntegrationAccountInner>, IntegrationAccountInner>() {
@Override
public IntegrationAccountInner call(ServiceResponse<IntegrationAccountInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"IntegrationAccountInner",
">",
"updateAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"integrationAccountName",
",",
"IntegrationAccountInner",
"integrationAccount",
")",
"{",
"return",
"updateWithServiceResponseAsync",
"(",
"resourceG... | Updates an integration account.
@param resourceGroupName The resource group name.
@param integrationAccountName The integration account name.
@param integrationAccount The integration account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the IntegrationAccountInner object | [
"Updates",
"an",
"integration",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/IntegrationAccountsInner.java#L785-L792 |
jhy/jsoup | src/main/java/org/jsoup/nodes/Document.java | Document.findFirstElementByTagName | private Element findFirstElementByTagName(String tag, Node node) {
if (node.nodeName().equals(tag))
return (Element) node;
else {
int size = node.childNodeSize();
for (int i = 0; i < size; i++) {
Element found = findFirstElementByTagName(tag, node.childNode(i));
if (found != null)
return found;
}
}
return null;
} | java | private Element findFirstElementByTagName(String tag, Node node) {
if (node.nodeName().equals(tag))
return (Element) node;
else {
int size = node.childNodeSize();
for (int i = 0; i < size; i++) {
Element found = findFirstElementByTagName(tag, node.childNode(i));
if (found != null)
return found;
}
}
return null;
} | [
"private",
"Element",
"findFirstElementByTagName",
"(",
"String",
"tag",
",",
"Node",
"node",
")",
"{",
"if",
"(",
"node",
".",
"nodeName",
"(",
")",
".",
"equals",
"(",
"tag",
")",
")",
"return",
"(",
"Element",
")",
"node",
";",
"else",
"{",
"int",
... | fast method to get first by tag name, used for html, head, body finders | [
"fast",
"method",
"to",
"get",
"first",
"by",
"tag",
"name",
"used",
"for",
"html",
"head",
"body",
"finders"
] | train | https://github.com/jhy/jsoup/blob/68ff8cbe7ad847059737a09c567a501a7f1d251f/src/main/java/org/jsoup/nodes/Document.java#L182-L194 |
opengeospatial/teamengine | teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java | SchematronValidatingParser.createSchematronDriver | ValidationDriver createSchematronDriver(String phase) {
SchemaReaderLoader loader = new SchemaReaderLoader();
SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
this.configPropBuilder = new PropertyMapBuilder();
SchematronProperty.DIAGNOSE.add(this.configPropBuilder);
if (this.outputLogger == null) {
this.outputLogger = new PrintWriter(System.out);
}
if (null != phase && !phase.isEmpty()) {
this.configPropBuilder.put(SchematronProperty.PHASE, phase);
}
ErrorHandler eh = new ErrorHandlerImpl("Schematron", outputLogger);
this.configPropBuilder.put(ValidateProperty.ERROR_HANDLER, eh);
ValidationDriver validator = new ValidationDriver(
this.configPropBuilder.toPropertyMap(), schReader);
return validator;
} | java | ValidationDriver createSchematronDriver(String phase) {
SchemaReaderLoader loader = new SchemaReaderLoader();
SchemaReader schReader = loader.createSchemaReader(SCHEMATRON_NS_URI);
this.configPropBuilder = new PropertyMapBuilder();
SchematronProperty.DIAGNOSE.add(this.configPropBuilder);
if (this.outputLogger == null) {
this.outputLogger = new PrintWriter(System.out);
}
if (null != phase && !phase.isEmpty()) {
this.configPropBuilder.put(SchematronProperty.PHASE, phase);
}
ErrorHandler eh = new ErrorHandlerImpl("Schematron", outputLogger);
this.configPropBuilder.put(ValidateProperty.ERROR_HANDLER, eh);
ValidationDriver validator = new ValidationDriver(
this.configPropBuilder.toPropertyMap(), schReader);
return validator;
} | [
"ValidationDriver",
"createSchematronDriver",
"(",
"String",
"phase",
")",
"{",
"SchemaReaderLoader",
"loader",
"=",
"new",
"SchemaReaderLoader",
"(",
")",
";",
"SchemaReader",
"schReader",
"=",
"loader",
".",
"createSchemaReader",
"(",
"SCHEMATRON_NS_URI",
")",
";",
... | Sets up the schematron reader with all the necessary parameters. Calls
initSchematronReader() to do further setup of the validation driver.
@param phase
The string phase name (contained in schematron file)
@return The ValidationDriver to use in validating the XML document | [
"Sets",
"up",
"the",
"schematron",
"reader",
"with",
"all",
"the",
"necessary",
"parameters",
".",
"Calls",
"initSchematronReader",
"()",
"to",
"do",
"further",
"setup",
"of",
"the",
"validation",
"driver",
"."
] | train | https://github.com/opengeospatial/teamengine/blob/b6b890214b6784bbe19460bf753bdf28a9514bee/teamengine-core/src/main/java/com/occamlab/te/parsers/SchematronValidatingParser.java#L257-L274 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfWriter.java | PdfCrossReference.toPdf | public void toPdf(int midSize, OutputStream os) throws IOException {
os.write((byte)type);
while (--midSize >= 0)
os.write((byte)((offset >>> (8 * midSize)) & 0xff));
os.write((byte)((generation >>> 8) & 0xff));
os.write((byte)(generation & 0xff));
} | java | public void toPdf(int midSize, OutputStream os) throws IOException {
os.write((byte)type);
while (--midSize >= 0)
os.write((byte)((offset >>> (8 * midSize)) & 0xff));
os.write((byte)((generation >>> 8) & 0xff));
os.write((byte)(generation & 0xff));
} | [
"public",
"void",
"toPdf",
"(",
"int",
"midSize",
",",
"OutputStream",
"os",
")",
"throws",
"IOException",
"{",
"os",
".",
"write",
"(",
"(",
"byte",
")",
"type",
")",
";",
"while",
"(",
"--",
"midSize",
">=",
"0",
")",
"os",
".",
"write",
"(",
"("... | Writes PDF syntax to the OutputStream
@param midSize
@param os
@throws IOException | [
"Writes",
"PDF",
"syntax",
"to",
"the",
"OutputStream"
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfWriter.java#L211-L217 |
GoogleCloudPlatform/appengine-mapreduce | java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQuerySchemaMarshallerByType.java | BigQuerySchemaMarshallerByType.validateType | private void validateType(Class<?> type, Map<Field, BigqueryFieldMarshaller> marshallers) {
if (typeToField.containsKey(type)) {
throw new IllegalArgumentException(this.type
+ " contains cyclic reference for the field with type "
+ type + ". Hence cannot be resolved into bigquery schema.");
}
try {
typeToField.put(type, null);
validateTypeForSchemaMarshalling(type);
Set<Field> fieldsToMap = getFieldsToSerialize(type);
for (Field field : fieldsToMap) {
if ((marshallers == null || !marshallers.containsKey(field))
&& BigqueryFieldMarshallers.getMarshaller(field.getType()) == null) {
validateType(field.getType(), marshallers);
}
}
} finally {
typeToField.remove(type);
}
} | java | private void validateType(Class<?> type, Map<Field, BigqueryFieldMarshaller> marshallers) {
if (typeToField.containsKey(type)) {
throw new IllegalArgumentException(this.type
+ " contains cyclic reference for the field with type "
+ type + ". Hence cannot be resolved into bigquery schema.");
}
try {
typeToField.put(type, null);
validateTypeForSchemaMarshalling(type);
Set<Field> fieldsToMap = getFieldsToSerialize(type);
for (Field field : fieldsToMap) {
if ((marshallers == null || !marshallers.containsKey(field))
&& BigqueryFieldMarshallers.getMarshaller(field.getType()) == null) {
validateType(field.getType(), marshallers);
}
}
} finally {
typeToField.remove(type);
}
} | [
"private",
"void",
"validateType",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Map",
"<",
"Field",
",",
"BigqueryFieldMarshaller",
">",
"marshallers",
")",
"{",
"if",
"(",
"typeToField",
".",
"containsKey",
"(",
"type",
")",
")",
"{",
"throw",
"new",
"Ill... | Validates that the type can be marshalled by using using the provided marshallers and the
internal marshallers to determine whether {@link TableSchema} can be generated for the given
type.
@param type to validate.
@param marshallers map of field to {@link BigqueryFieldMarshaller} for unsupported fields. | [
"Validates",
"that",
"the",
"type",
"can",
"be",
"marshalled",
"by",
"using",
"using",
"the",
"provided",
"marshallers",
"and",
"the",
"internal",
"marshallers",
"to",
"determine",
"whether",
"{",
"@link",
"TableSchema",
"}",
"can",
"be",
"generated",
"for",
"... | train | https://github.com/GoogleCloudPlatform/appengine-mapreduce/blob/2045eb3605b6ecb40c83d11dd5442a89fe5c5dd6/java/src/main/java/com/google/appengine/tools/mapreduce/impl/BigQuerySchemaMarshallerByType.java#L131-L150 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java | StringIterate.forEachChar | public static void forEachChar(String string, CharProcedure procedure)
{
int size = string.length();
for (int i = 0; i < size; i++)
{
procedure.value(string.charAt(i));
}
} | java | public static void forEachChar(String string, CharProcedure procedure)
{
int size = string.length();
for (int i = 0; i < size; i++)
{
procedure.value(string.charAt(i));
}
} | [
"public",
"static",
"void",
"forEachChar",
"(",
"String",
"string",
",",
"CharProcedure",
"procedure",
")",
"{",
"int",
"size",
"=",
"string",
".",
"length",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"size",
";",
"i",
"++",
")... | For each char in the {@code string}, execute the {@link CharProcedure}.
@since 7.0 | [
"For",
"each",
"char",
"in",
"the",
"{",
"@code",
"string",
"}",
"execute",
"the",
"{",
"@link",
"CharProcedure",
"}",
"."
] | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/StringIterate.java#L360-L367 |
agmip/agmip-common-functions | src/main/java/org/agmip/functions/PTSaxton2006.java | PTSaxton2006.calcAdjustedSaturatedMoisture | public static String calcAdjustedSaturatedMoisture(String slsnd, String slcly, String omPct, String df) {
String adjDensity = calcAdjustedDensity(slsnd, slcly, omPct, df);
String ret = substract("100", divide(adjDensity, "0.0265"));
LOG.debug("Calculate result for Saturated moisture (0 kPa), adjusted density, ([0,100]%) is {}", ret);
return ret;
} | java | public static String calcAdjustedSaturatedMoisture(String slsnd, String slcly, String omPct, String df) {
String adjDensity = calcAdjustedDensity(slsnd, slcly, omPct, df);
String ret = substract("100", divide(adjDensity, "0.0265"));
LOG.debug("Calculate result for Saturated moisture (0 kPa), adjusted density, ([0,100]%) is {}", ret);
return ret;
} | [
"public",
"static",
"String",
"calcAdjustedSaturatedMoisture",
"(",
"String",
"slsnd",
",",
"String",
"slcly",
",",
"String",
"omPct",
",",
"String",
"df",
")",
"{",
"String",
"adjDensity",
"=",
"calcAdjustedDensity",
"(",
"slsnd",
",",
"slcly",
",",
"omPct",
... | Equation 8 for calculating Saturated moisture (0 kPa), adjusted density,
([0,100]%)
@param slsnd Sand weight percentage by layer ([0,100]%)
@param slcly Clay weight percentage by layer ([0,100]%)
@param omPct Organic matter weight percentage by layer ([0,100]%), (=
SLOC * 1.72)
@param df Density adjustment Factor (0.9–1.3) | [
"Equation",
"8",
"for",
"calculating",
"Saturated",
"moisture",
"(",
"0",
"kPa",
")",
"adjusted",
"density",
"(",
"[",
"0",
"100",
"]",
"%",
")"
] | train | https://github.com/agmip/agmip-common-functions/blob/4efa3042178841b026ca6fba9c96da02fbfb9a8e/src/main/java/org/agmip/functions/PTSaxton2006.java#L266-L272 |
eclipse/xtext-core | org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/InternalNodeModelUtils.java | InternalNodeModelUtils.getLineAndColumn | protected static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) {
INode rootNode = anyNode.getRootNode();
int[] lineBreaks = getLineBreakOffsets(rootNode);
String document = rootNode.getText();
return getLineAndColumn(document, lineBreaks, documentOffset);
} | java | protected static LineAndColumn getLineAndColumn(INode anyNode, int documentOffset) {
INode rootNode = anyNode.getRootNode();
int[] lineBreaks = getLineBreakOffsets(rootNode);
String document = rootNode.getText();
return getLineAndColumn(document, lineBreaks, documentOffset);
} | [
"protected",
"static",
"LineAndColumn",
"getLineAndColumn",
"(",
"INode",
"anyNode",
",",
"int",
"documentOffset",
")",
"{",
"INode",
"rootNode",
"=",
"anyNode",
".",
"getRootNode",
"(",
")",
";",
"int",
"[",
"]",
"lineBreaks",
"=",
"getLineBreakOffsets",
"(",
... | Obtain the line breaks from the document and search / compute the line number
and column number at the given document offset. | [
"Obtain",
"the",
"line",
"breaks",
"from",
"the",
"document",
"and",
"search",
"/",
"compute",
"the",
"line",
"number",
"and",
"column",
"number",
"at",
"the",
"given",
"document",
"offset",
"."
] | train | https://github.com/eclipse/xtext-core/blob/bac941cb75cb24706519845ec174cfef874d7557/org.eclipse.xtext/src/org/eclipse/xtext/nodemodel/impl/InternalNodeModelUtils.java#L45-L50 |
alkacon/opencms-core | src/org/opencms/ade/upload/CmsUploadService.java | CmsUploadService.existsResource | private boolean existsResource(String path, boolean rootPath) {
CmsObject cms = getCmsObject();
if (rootPath) {
String origSiteRoot = cms.getRequestContext().getSiteRoot();
try {
cms.getRequestContext().setSiteRoot("");
if (cms.existsResource(path, CmsResourceFilter.ALL)) {
return true;
}
} finally {
cms.getRequestContext().setSiteRoot(origSiteRoot);
}
} else {
if (cms.existsResource(path, CmsResourceFilter.ALL)) {
return true;
}
}
return false;
} | java | private boolean existsResource(String path, boolean rootPath) {
CmsObject cms = getCmsObject();
if (rootPath) {
String origSiteRoot = cms.getRequestContext().getSiteRoot();
try {
cms.getRequestContext().setSiteRoot("");
if (cms.existsResource(path, CmsResourceFilter.ALL)) {
return true;
}
} finally {
cms.getRequestContext().setSiteRoot(origSiteRoot);
}
} else {
if (cms.existsResource(path, CmsResourceFilter.ALL)) {
return true;
}
}
return false;
} | [
"private",
"boolean",
"existsResource",
"(",
"String",
"path",
",",
"boolean",
"rootPath",
")",
"{",
"CmsObject",
"cms",
"=",
"getCmsObject",
"(",
")",
";",
"if",
"(",
"rootPath",
")",
"{",
"String",
"origSiteRoot",
"=",
"cms",
".",
"getRequestContext",
"(",... | Checks if a resource already exists for the given path.<p>
@param path the path
@param rootPath in case the path is a root path
@return true if a resource already exists | [
"Checks",
"if",
"a",
"resource",
"already",
"exists",
"for",
"the",
"given",
"path",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/upload/CmsUploadService.java#L140-L159 |
jeluard/semantic-versioning | api/src/main/java/org/osjava/jardiff/PublicDiffCriteria.java | PublicDiffCriteria.differs | public boolean differs(MethodInfo oldInfo, MethodInfo newInfo) {
if (Tools.isMethodAccessChange(oldInfo.getAccess(), newInfo.getAccess()))
return true;
if (oldInfo.getExceptions() == null
|| newInfo.getExceptions() == null) {
if (oldInfo.getExceptions() != newInfo.getExceptions())
return true;
} else {
final Set<String> oldExceptions
= new HashSet(Arrays.asList(oldInfo.getExceptions()));
final Set<String> newExceptions
= new HashSet(Arrays.asList(newInfo.getExceptions()));
if (!oldExceptions.equals(newExceptions))
return true;
}
return false;
} | java | public boolean differs(MethodInfo oldInfo, MethodInfo newInfo) {
if (Tools.isMethodAccessChange(oldInfo.getAccess(), newInfo.getAccess()))
return true;
if (oldInfo.getExceptions() == null
|| newInfo.getExceptions() == null) {
if (oldInfo.getExceptions() != newInfo.getExceptions())
return true;
} else {
final Set<String> oldExceptions
= new HashSet(Arrays.asList(oldInfo.getExceptions()));
final Set<String> newExceptions
= new HashSet(Arrays.asList(newInfo.getExceptions()));
if (!oldExceptions.equals(newExceptions))
return true;
}
return false;
} | [
"public",
"boolean",
"differs",
"(",
"MethodInfo",
"oldInfo",
",",
"MethodInfo",
"newInfo",
")",
"{",
"if",
"(",
"Tools",
".",
"isMethodAccessChange",
"(",
"oldInfo",
".",
"getAccess",
"(",
")",
",",
"newInfo",
".",
"getAccess",
"(",
")",
")",
")",
"return... | Check if there is a change between two versions of a method.
Returns true if the access flags differ, or if the thrown
exceptions differ.
@param oldInfo Info about the old version of the method.
@param newInfo Info about the new version of the method.
@return True if the methods differ, false otherwise. | [
"Check",
"if",
"there",
"is",
"a",
"change",
"between",
"two",
"versions",
"of",
"a",
"method",
".",
"Returns",
"true",
"if",
"the",
"access",
"flags",
"differ",
"or",
"if",
"the",
"thrown",
"exceptions",
"differ",
"."
] | train | https://github.com/jeluard/semantic-versioning/blob/d0bfbeddca8ac4202f5225810227c72a708360a9/api/src/main/java/org/osjava/jardiff/PublicDiffCriteria.java#L102-L118 |
Bandwidth/java-bandwidth | src/main/java/com/bandwidth/sdk/model/Application.java | Application.get | public static Application get(final BandwidthClient client, final String id) throws Exception {
assert(id != null);
final String applicationUri = client.getUserResourceInstanceUri(BandwidthConstants.APPLICATIONS_URI_PATH, id);
final JSONObject applicationObj = toJSONObject( client.get(applicationUri, null) );
final Application application = new Application(client, applicationObj);
return application;
} | java | public static Application get(final BandwidthClient client, final String id) throws Exception {
assert(id != null);
final String applicationUri = client.getUserResourceInstanceUri(BandwidthConstants.APPLICATIONS_URI_PATH, id);
final JSONObject applicationObj = toJSONObject( client.get(applicationUri, null) );
final Application application = new Application(client, applicationObj);
return application;
} | [
"public",
"static",
"Application",
"get",
"(",
"final",
"BandwidthClient",
"client",
",",
"final",
"String",
"id",
")",
"throws",
"Exception",
"{",
"assert",
"(",
"id",
"!=",
"null",
")",
";",
"final",
"String",
"applicationUri",
"=",
"client",
".",
"getUser... | Factory method for Application, returns Application object
@param client the client
@param id the application id
@return the application
@throws IOException unexpected error. | [
"Factory",
"method",
"for",
"Application",
"returns",
"Application",
"object"
] | train | https://github.com/Bandwidth/java-bandwidth/blob/2124c85148ad6a54d2f2949cb952eb3985830e2a/src/main/java/com/bandwidth/sdk/model/Application.java#L40-L47 |
khuxtable/seaglass | src/main/java/com/seaglasslookandfeel/effect/EffectUtils.java | EffectUtils.gaussianBlur | static BufferedImage gaussianBlur(BufferedImage src, BufferedImage dst, int radius) {
int width = src.getWidth();
int height = src.getHeight();
if (dst == null || dst.getWidth() != width || dst.getHeight() != height || src.getType() != dst.getType()) {
dst = createColorModelCompatibleImage(src);
}
float[] kernel = createGaussianKernel(radius);
if (src.getType() == BufferedImage.TYPE_INT_ARGB) {
int[] srcPixels = new int[width * height];
int[] dstPixels = new int[width * height];
getPixels(src, 0, 0, width, height, srcPixels);
// horizontal pass
blur(srcPixels, dstPixels, width, height, kernel, radius);
// vertical pass
// noinspection SuspiciousNameCombination
blur(dstPixels, srcPixels, height, width, kernel, radius);
// the result is now stored in srcPixels due to the 2nd pass
setPixels(dst, 0, 0, width, height, srcPixels);
} else if (src.getType() == BufferedImage.TYPE_BYTE_GRAY) {
byte[] srcPixels = new byte[width * height];
byte[] dstPixels = new byte[width * height];
getPixels(src, 0, 0, width, height, srcPixels);
// horizontal pass
blur(srcPixels, dstPixels, width, height, kernel, radius);
// vertical pass
// noinspection SuspiciousNameCombination
blur(dstPixels, srcPixels, height, width, kernel, radius);
// the result is now stored in srcPixels due to the 2nd pass
setPixels(dst, 0, 0, width, height, srcPixels);
} else {
throw new IllegalArgumentException("EffectUtils.gaussianBlur() src image is not a supported type, type=[" + src.getType()
+ "]");
}
return dst;
} | java | static BufferedImage gaussianBlur(BufferedImage src, BufferedImage dst, int radius) {
int width = src.getWidth();
int height = src.getHeight();
if (dst == null || dst.getWidth() != width || dst.getHeight() != height || src.getType() != dst.getType()) {
dst = createColorModelCompatibleImage(src);
}
float[] kernel = createGaussianKernel(radius);
if (src.getType() == BufferedImage.TYPE_INT_ARGB) {
int[] srcPixels = new int[width * height];
int[] dstPixels = new int[width * height];
getPixels(src, 0, 0, width, height, srcPixels);
// horizontal pass
blur(srcPixels, dstPixels, width, height, kernel, radius);
// vertical pass
// noinspection SuspiciousNameCombination
blur(dstPixels, srcPixels, height, width, kernel, radius);
// the result is now stored in srcPixels due to the 2nd pass
setPixels(dst, 0, 0, width, height, srcPixels);
} else if (src.getType() == BufferedImage.TYPE_BYTE_GRAY) {
byte[] srcPixels = new byte[width * height];
byte[] dstPixels = new byte[width * height];
getPixels(src, 0, 0, width, height, srcPixels);
// horizontal pass
blur(srcPixels, dstPixels, width, height, kernel, radius);
// vertical pass
// noinspection SuspiciousNameCombination
blur(dstPixels, srcPixels, height, width, kernel, radius);
// the result is now stored in srcPixels due to the 2nd pass
setPixels(dst, 0, 0, width, height, srcPixels);
} else {
throw new IllegalArgumentException("EffectUtils.gaussianBlur() src image is not a supported type, type=[" + src.getType()
+ "]");
}
return dst;
} | [
"static",
"BufferedImage",
"gaussianBlur",
"(",
"BufferedImage",
"src",
",",
"BufferedImage",
"dst",
",",
"int",
"radius",
")",
"{",
"int",
"width",
"=",
"src",
".",
"getWidth",
"(",
")",
";",
"int",
"height",
"=",
"src",
".",
"getHeight",
"(",
")",
";",... | Apply Gaussian Blur to Image
@param src The image tp
@param dst The destination image to draw blured src image into, null
if you want a new one created
@param radius The blur kernel radius
@return The blured image | [
"Apply",
"Gaussian",
"Blur",
"to",
"Image"
] | train | https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/effect/EffectUtils.java#L66-L112 |
airbnb/lottie-android | lottie/src/main/java/com/airbnb/lottie/LottieDrawable.java | LottieDrawable.setImageAssetDelegate | public void setImageAssetDelegate(
@SuppressWarnings("NullableProblems") ImageAssetDelegate assetDelegate) {
this.imageAssetDelegate = assetDelegate;
if (imageAssetManager != null) {
imageAssetManager.setDelegate(assetDelegate);
}
} | java | public void setImageAssetDelegate(
@SuppressWarnings("NullableProblems") ImageAssetDelegate assetDelegate) {
this.imageAssetDelegate = assetDelegate;
if (imageAssetManager != null) {
imageAssetManager.setDelegate(assetDelegate);
}
} | [
"public",
"void",
"setImageAssetDelegate",
"(",
"@",
"SuppressWarnings",
"(",
"\"NullableProblems\"",
")",
"ImageAssetDelegate",
"assetDelegate",
")",
"{",
"this",
".",
"imageAssetDelegate",
"=",
"assetDelegate",
";",
"if",
"(",
"imageAssetManager",
"!=",
"null",
")",... | Use this if you can't bundle images with your app. This may be useful if you download the
animations from the network or have the images saved to an SD Card. In that case, Lottie
will defer the loading of the bitmap to this delegate.
<p>
Be wary if you are using many images, however. Lottie is designed to work with vector shapes
from After Effects. If your images look like they could be represented with vector shapes,
see if it is possible to convert them to shape layers and re-export your animation. Check
the documentation at http://airbnb.io/lottie for more information about importing shapes from
Sketch or Illustrator to avoid this. | [
"Use",
"this",
"if",
"you",
"can",
"t",
"bundle",
"images",
"with",
"your",
"app",
".",
"This",
"may",
"be",
"useful",
"if",
"you",
"download",
"the",
"animations",
"from",
"the",
"network",
"or",
"have",
"the",
"images",
"saved",
"to",
"an",
"SD",
"Ca... | train | https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/LottieDrawable.java#L776-L782 |
Alluxio/alluxio | core/server/master/src/main/java/alluxio/master/metastore/caching/Cache.java | Cache.put | public void put(K key, V value) {
mMap.compute(key, (k, entry) -> {
onPut(key, value);
if (entry == null && cacheIsFull()) {
writeToBackingStore(key, value);
return null;
}
if (entry == null || entry.mValue == null) {
onCacheUpdate(key, value);
return new Entry(key, value);
}
entry.mValue = value;
entry.mReferenced = true;
entry.mDirty = true;
return entry;
});
wakeEvictionThreadIfNecessary();
} | java | public void put(K key, V value) {
mMap.compute(key, (k, entry) -> {
onPut(key, value);
if (entry == null && cacheIsFull()) {
writeToBackingStore(key, value);
return null;
}
if (entry == null || entry.mValue == null) {
onCacheUpdate(key, value);
return new Entry(key, value);
}
entry.mValue = value;
entry.mReferenced = true;
entry.mDirty = true;
return entry;
});
wakeEvictionThreadIfNecessary();
} | [
"public",
"void",
"put",
"(",
"K",
"key",
",",
"V",
"value",
")",
"{",
"mMap",
".",
"compute",
"(",
"key",
",",
"(",
"k",
",",
"entry",
")",
"->",
"{",
"onPut",
"(",
"key",
",",
"value",
")",
";",
"if",
"(",
"entry",
"==",
"null",
"&&",
"cach... | Writes a key/value pair to the cache.
@param key the key
@param value the value | [
"Writes",
"a",
"key",
"/",
"value",
"pair",
"to",
"the",
"cache",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/metastore/caching/Cache.java#L135-L152 |
jayantk/jklol | src/com/jayantkrish/jklol/util/PairCountAccumulator.java | PairCountAccumulator.getConditionalProbability | public double getConditionalProbability(A first, B second) {
return getCount(first, second) / conditionalCounts.get(first);
} | java | public double getConditionalProbability(A first, B second) {
return getCount(first, second) / conditionalCounts.get(first);
} | [
"public",
"double",
"getConditionalProbability",
"(",
"A",
"first",
",",
"B",
"second",
")",
"{",
"return",
"getCount",
"(",
"first",
",",
"second",
")",
"/",
"conditionalCounts",
".",
"get",
"(",
"first",
")",
";",
"}"
] | Gets the conditional probability of observing {@code second} given
{@code first}. Returns NaN if {@code first} has never been observed.
@param first
@param second
@return | [
"Gets",
"the",
"conditional",
"probability",
"of",
"observing",
"{",
"@code",
"second",
"}",
"given",
"{",
"@code",
"first",
"}",
".",
"Returns",
"NaN",
"if",
"{",
"@code",
"first",
"}",
"has",
"never",
"been",
"observed",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/PairCountAccumulator.java#L170-L172 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.