repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
lessthanoptimal/BoofCV | main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/SplitMergeLineFitLoop.java | SplitMergeLineFitLoop.selectSplitOffset | protected int selectSplitOffset( int indexStart , int length ) {
int bestOffset = -1;
int indexEnd = (indexStart + length) % N;
Point2D_I32 startPt = contour.get(indexStart);
Point2D_I32 endPt = contour.get(indexEnd);
line.p.set(startPt.x,startPt.y);
line.slope.set(endPt.x-startPt.x,endPt.y-startPt.y);
double bestDistanceSq = splitThresholdSq(contour.get(indexStart), contour.get(indexEnd));
// adjusting using 'minimumSideLengthPixel' to ensure it doesn't create a new line which is too short
int minLength = Math.max(1,minimumSideLengthPixel);// 1 is the minimum so that you don't split on the same corner
length -= minLength;
for( int i = minLength; i <= length; i++ ) {
Point2D_I32 b = contour.get((indexStart+i)%N);
point2D.set(b.x,b.y);
double dist = Distance2D_F64.distanceSq(line, point2D);
if( dist >= bestDistanceSq ) {
bestDistanceSq = dist;
bestOffset = i;
}
}
return bestOffset;
} | java | protected int selectSplitOffset( int indexStart , int length ) {
int bestOffset = -1;
int indexEnd = (indexStart + length) % N;
Point2D_I32 startPt = contour.get(indexStart);
Point2D_I32 endPt = contour.get(indexEnd);
line.p.set(startPt.x,startPt.y);
line.slope.set(endPt.x-startPt.x,endPt.y-startPt.y);
double bestDistanceSq = splitThresholdSq(contour.get(indexStart), contour.get(indexEnd));
// adjusting using 'minimumSideLengthPixel' to ensure it doesn't create a new line which is too short
int minLength = Math.max(1,minimumSideLengthPixel);// 1 is the minimum so that you don't split on the same corner
length -= minLength;
for( int i = minLength; i <= length; i++ ) {
Point2D_I32 b = contour.get((indexStart+i)%N);
point2D.set(b.x,b.y);
double dist = Distance2D_F64.distanceSq(line, point2D);
if( dist >= bestDistanceSq ) {
bestDistanceSq = dist;
bestOffset = i;
}
}
return bestOffset;
} | [
"protected",
"int",
"selectSplitOffset",
"(",
"int",
"indexStart",
",",
"int",
"length",
")",
"{",
"int",
"bestOffset",
"=",
"-",
"1",
";",
"int",
"indexEnd",
"=",
"(",
"indexStart",
"+",
"length",
")",
"%",
"N",
";",
"Point2D_I32",
"startPt",
"=",
"cont... | Finds the point between indexStart and the end point which is the greater distance from the line
(set up prior to calling). Returns the index of the element with a distances greater than tolerance, otherwise -1
@return Selected offset from start of the split. -1 if no split was selected | [
"Finds",
"the",
"point",
"between",
"indexStart",
"and",
"the",
"end",
"point",
"which",
"is",
"the",
"greater",
"distance",
"from",
"the",
"line",
"(",
"set",
"up",
"prior",
"to",
"calling",
")",
".",
"Returns",
"the",
"index",
"of",
"the",
"element",
"... | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/shapes/polyline/splitmerge/SplitMergeLineFitLoop.java#L228-L255 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/http/HttpHeaderMap.java | HttpHeaderMap.addDateHeader | public void addDateHeader (@Nonnull @Nonempty final String sName, @Nonnull final ZonedDateTime aDT)
{
_addHeader (sName, getDateTimeAsString (aDT));
} | java | public void addDateHeader (@Nonnull @Nonempty final String sName, @Nonnull final ZonedDateTime aDT)
{
_addHeader (sName, getDateTimeAsString (aDT));
} | [
"public",
"void",
"addDateHeader",
"(",
"@",
"Nonnull",
"@",
"Nonempty",
"final",
"String",
"sName",
",",
"@",
"Nonnull",
"final",
"ZonedDateTime",
"aDT",
")",
"{",
"_addHeader",
"(",
"sName",
",",
"getDateTimeAsString",
"(",
"aDT",
")",
")",
";",
"}"
] | Add the passed header as a date header.
@param sName
Header name. May neither be <code>null</code> nor empty.
@param aDT
The DateTime to set as a date. May not be <code>null</code>. | [
"Add",
"the",
"passed",
"header",
"as",
"a",
"date",
"header",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/http/HttpHeaderMap.java#L330-L333 |
GII/broccoli | broccoli-api/src/main/java/com/hi3project/broccoli/bsdl/impl/meta/MetaPropertyVersion.java | MetaPropertyVersion.compareTo | private static int compareTo(Deque<String> first, Deque<String> second) {
if (0 == first.size() && 0 == second.size()) {
return 0;
}
if (0 == first.size()) {
return 1;
}
if (0 == second.size()) {
return -1;
}
int headsComparation = (Integer.valueOf(first.remove())).compareTo(Integer.parseInt(second.remove()));
if (0 == headsComparation) {
return compareTo(first, second);
} else {
return headsComparation;
}
} | java | private static int compareTo(Deque<String> first, Deque<String> second) {
if (0 == first.size() && 0 == second.size()) {
return 0;
}
if (0 == first.size()) {
return 1;
}
if (0 == second.size()) {
return -1;
}
int headsComparation = (Integer.valueOf(first.remove())).compareTo(Integer.parseInt(second.remove()));
if (0 == headsComparation) {
return compareTo(first, second);
} else {
return headsComparation;
}
} | [
"private",
"static",
"int",
"compareTo",
"(",
"Deque",
"<",
"String",
">",
"first",
",",
"Deque",
"<",
"String",
">",
"second",
")",
"{",
"if",
"(",
"0",
"==",
"first",
".",
"size",
"(",
")",
"&&",
"0",
"==",
"second",
".",
"size",
"(",
")",
")",... | Compares two string ordered lists containing numbers.
@return -1 when first group is higher, 0 if equals, 1 when second group is higher | [
"Compares",
"two",
"string",
"ordered",
"lists",
"containing",
"numbers",
"."
] | train | https://github.com/GII/broccoli/blob/a3033a90322cbcee4dc0f1719143b84b822bc4ba/broccoli-api/src/main/java/com/hi3project/broccoli/bsdl/impl/meta/MetaPropertyVersion.java#L82-L98 |
hellosign/hellosign-java-sdk | src/main/java/com/hellosign/sdk/resource/TemplateSignatureRequest.java | TemplateSignatureRequest.setCustomFieldValue | public void setCustomFieldValue(String fieldNameOrApiId, String value) {
CustomField f = new CustomField();
f.setName(fieldNameOrApiId);
f.setValue(value);
customFields.add(f);
} | java | public void setCustomFieldValue(String fieldNameOrApiId, String value) {
CustomField f = new CustomField();
f.setName(fieldNameOrApiId);
f.setValue(value);
customFields.add(f);
} | [
"public",
"void",
"setCustomFieldValue",
"(",
"String",
"fieldNameOrApiId",
",",
"String",
"value",
")",
"{",
"CustomField",
"f",
"=",
"new",
"CustomField",
"(",
")",
";",
"f",
".",
"setName",
"(",
"fieldNameOrApiId",
")",
";",
"f",
".",
"setValue",
"(",
"... | Adds the value to fill in for a custom field with the given field name.
@param fieldNameOrApiId String name (or "Field Label") of the custom field
to be filled in. The "api_id" can also be used instead of the name.
@param value String value | [
"Adds",
"the",
"value",
"to",
"fill",
"in",
"for",
"a",
"custom",
"field",
"with",
"the",
"given",
"field",
"name",
"."
] | train | https://github.com/hellosign/hellosign-java-sdk/blob/08fa7aeb3b0c68ddb6c7ea797d114d55d36d36b1/src/main/java/com/hellosign/sdk/resource/TemplateSignatureRequest.java#L202-L207 |
anotheria/moskito | moskito-core/src/main/java/net/anotheria/moskito/core/plugins/PluginRepository.java | PluginRepository.addPlugin | public void addPlugin(String name, MoskitoPlugin plugin, PluginConfig config){
plugins.put(name, plugin);
try{
plugin.initialize();
configs.put(name, config);
}catch(Exception e){
log.warn("couldn't initialize plugin "+name+" - "+plugin+", removing", e);
plugins.remove(name);
}
} | java | public void addPlugin(String name, MoskitoPlugin plugin, PluginConfig config){
plugins.put(name, plugin);
try{
plugin.initialize();
configs.put(name, config);
}catch(Exception e){
log.warn("couldn't initialize plugin "+name+" - "+plugin+", removing", e);
plugins.remove(name);
}
} | [
"public",
"void",
"addPlugin",
"(",
"String",
"name",
",",
"MoskitoPlugin",
"plugin",
",",
"PluginConfig",
"config",
")",
"{",
"plugins",
".",
"put",
"(",
"name",
",",
"plugin",
")",
";",
"try",
"{",
"plugin",
".",
"initialize",
"(",
")",
";",
"configs",... | Adds a new loaded plugin.
@param name name of the plugin for ui.
@param plugin the plugin instance.
@param config plugin config which was used to load the plugin. | [
"Adds",
"a",
"new",
"loaded",
"plugin",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/plugins/PluginRepository.java#L82-L91 |
ehcache/ehcache3 | core/src/main/java/org/ehcache/core/EhcacheManager.java | EhcacheManager.closeEhcache | protected void closeEhcache(final String alias, final InternalCache<?, ?> ehcache) {
for (ResourceType<?> resourceType : ehcache.getRuntimeConfiguration().getResourcePools().getResourceTypeSet()) {
if (resourceType.isPersistable()) {
ResourcePool resourcePool = ehcache.getRuntimeConfiguration()
.getResourcePools()
.getPoolForResource(resourceType);
if (!resourcePool.isPersistent()) {
PersistableResourceService persistableResourceService = getPersistableResourceService(resourceType);
try {
persistableResourceService.destroy(alias);
} catch (CachePersistenceException e) {
LOGGER.warn("Unable to clear persistence space for cache {}", alias, e);
}
}
}
}
} | java | protected void closeEhcache(final String alias, final InternalCache<?, ?> ehcache) {
for (ResourceType<?> resourceType : ehcache.getRuntimeConfiguration().getResourcePools().getResourceTypeSet()) {
if (resourceType.isPersistable()) {
ResourcePool resourcePool = ehcache.getRuntimeConfiguration()
.getResourcePools()
.getPoolForResource(resourceType);
if (!resourcePool.isPersistent()) {
PersistableResourceService persistableResourceService = getPersistableResourceService(resourceType);
try {
persistableResourceService.destroy(alias);
} catch (CachePersistenceException e) {
LOGGER.warn("Unable to clear persistence space for cache {}", alias, e);
}
}
}
}
} | [
"protected",
"void",
"closeEhcache",
"(",
"final",
"String",
"alias",
",",
"final",
"InternalCache",
"<",
"?",
",",
"?",
">",
"ehcache",
")",
"{",
"for",
"(",
"ResourceType",
"<",
"?",
">",
"resourceType",
":",
"ehcache",
".",
"getRuntimeConfiguration",
"(",... | Perform cache closure actions specific to a cache manager implementation.
This method is called <i>after</i> the {@code InternalCache} instance is closed.
@param alias the cache alias
@param ehcache the {@code InternalCache} instance for the cache to close | [
"Perform",
"cache",
"closure",
"actions",
"specific",
"to",
"a",
"cache",
"manager",
"implementation",
".",
"This",
"method",
"is",
"called",
"<i",
">",
"after<",
"/",
"i",
">",
"the",
"{",
"@code",
"InternalCache",
"}",
"instance",
"is",
"closed",
"."
] | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/core/src/main/java/org/ehcache/core/EhcacheManager.java#L229-L245 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSEditLogLoader.java | FSEditLogLoader.loadFSEdits | int loadFSEdits(EditLogInputStream edits, long lastAppliedTxId)
throws IOException {
long startTime = now();
this.lastAppliedTxId = lastAppliedTxId;
int numEdits = loadFSEdits(edits, true);
FSImage.LOG.info("Edits file " + edits.toString()
+ " of size: " + edits.length() + ", # of edits: " + numEdits
+ " loaded in: " + (now()-startTime)/1000 + " seconds.");
return numEdits;
} | java | int loadFSEdits(EditLogInputStream edits, long lastAppliedTxId)
throws IOException {
long startTime = now();
this.lastAppliedTxId = lastAppliedTxId;
int numEdits = loadFSEdits(edits, true);
FSImage.LOG.info("Edits file " + edits.toString()
+ " of size: " + edits.length() + ", # of edits: " + numEdits
+ " loaded in: " + (now()-startTime)/1000 + " seconds.");
return numEdits;
} | [
"int",
"loadFSEdits",
"(",
"EditLogInputStream",
"edits",
",",
"long",
"lastAppliedTxId",
")",
"throws",
"IOException",
"{",
"long",
"startTime",
"=",
"now",
"(",
")",
";",
"this",
".",
"lastAppliedTxId",
"=",
"lastAppliedTxId",
";",
"int",
"numEdits",
"=",
"l... | Load an edit log, and apply the changes to the in-memory structure
This is where we apply edits that we've been writing to disk all
along. | [
"Load",
"an",
"edit",
"log",
"and",
"apply",
"the",
"changes",
"to",
"the",
"in",
"-",
"memory",
"structure",
"This",
"is",
"where",
"we",
"apply",
"edits",
"that",
"we",
"ve",
"been",
"writing",
"to",
"disk",
"all",
"along",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSEditLogLoader.java#L107-L116 |
javagl/Common | src/main/java/de/javagl/common/collections/Maps.java | Maps.incrementCount | public static <K> void incrementCount(Map<K, Integer> map, K k)
{
map.put(k, getCount(map, k)+1);
} | java | public static <K> void incrementCount(Map<K, Integer> map, K k)
{
map.put(k, getCount(map, k)+1);
} | [
"public",
"static",
"<",
"K",
">",
"void",
"incrementCount",
"(",
"Map",
"<",
"K",
",",
"Integer",
">",
"map",
",",
"K",
"k",
")",
"{",
"map",
".",
"put",
"(",
"k",
",",
"getCount",
"(",
"map",
",",
"k",
")",
"+",
"1",
")",
";",
"}"
] | Increments the value that is stored for the given key in the given
map by one, or sets it to 1 if there was no value stored for the
given key.
@param <K> The key type
@param map The map
@param k The key | [
"Increments",
"the",
"value",
"that",
"is",
"stored",
"for",
"the",
"given",
"key",
"in",
"the",
"given",
"map",
"by",
"one",
"or",
"sets",
"it",
"to",
"1",
"if",
"there",
"was",
"no",
"value",
"stored",
"for",
"the",
"given",
"key",
"."
] | train | https://github.com/javagl/Common/blob/5a4876b48c3a2dc61d21324733cf37512d721c33/src/main/java/de/javagl/common/collections/Maps.java#L52-L55 |
baratine/baratine | core/src/main/java/com/caucho/v5/util/LruCache.java | LruCache.updateLru | private void updateLru(CacheItem<K,V> item)
{
long lruCounter = _lruCounter;
long itemCounter = item._lruCounter;
long delta = (lruCounter - itemCounter) & 0x3fffffff;
if (_lruTimeout < delta || delta < 0) {
// update LRU only if not used recently
updateLruImpl(item);
}
} | java | private void updateLru(CacheItem<K,V> item)
{
long lruCounter = _lruCounter;
long itemCounter = item._lruCounter;
long delta = (lruCounter - itemCounter) & 0x3fffffff;
if (_lruTimeout < delta || delta < 0) {
// update LRU only if not used recently
updateLruImpl(item);
}
} | [
"private",
"void",
"updateLru",
"(",
"CacheItem",
"<",
"K",
",",
"V",
">",
"item",
")",
"{",
"long",
"lruCounter",
"=",
"_lruCounter",
";",
"long",
"itemCounter",
"=",
"item",
".",
"_lruCounter",
";",
"long",
"delta",
"=",
"(",
"lruCounter",
"-",
"itemCo... | Put item at the head of the used-twice lru list.
This is always called while synchronized. | [
"Put",
"item",
"at",
"the",
"head",
"of",
"the",
"used",
"-",
"twice",
"lru",
"list",
".",
"This",
"is",
"always",
"called",
"while",
"synchronized",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/core/src/main/java/com/caucho/v5/util/LruCache.java#L413-L424 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java | CommonOps_DDRM.elementMult | public static void elementMult(DMatrixD1 a , DMatrixD1 b )
{
if( a.numCols != b.numCols || a.numRows != b.numRows ) {
throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions");
}
int length = a.getNumElements();
for( int i = 0; i < length; i++ ) {
a.times(i, b.get(i));
}
} | java | public static void elementMult(DMatrixD1 a , DMatrixD1 b )
{
if( a.numCols != b.numCols || a.numRows != b.numRows ) {
throw new MatrixDimensionException("The 'a' and 'b' matrices do not have compatible dimensions");
}
int length = a.getNumElements();
for( int i = 0; i < length; i++ ) {
a.times(i, b.get(i));
}
} | [
"public",
"static",
"void",
"elementMult",
"(",
"DMatrixD1",
"a",
",",
"DMatrixD1",
"b",
")",
"{",
"if",
"(",
"a",
".",
"numCols",
"!=",
"b",
".",
"numCols",
"||",
"a",
".",
"numRows",
"!=",
"b",
".",
"numRows",
")",
"{",
"throw",
"new",
"MatrixDimen... | <p>Performs the an element by element multiplication operation:<br>
<br>
a<sub>ij</sub> = a<sub>ij</sub> * b<sub>ij</sub> <br>
</p>
@param a The left matrix in the multiplication operation. Modified.
@param b The right matrix in the multiplication operation. Not modified. | [
"<p",
">",
"Performs",
"the",
"an",
"element",
"by",
"element",
"multiplication",
"operation",
":",
"<br",
">",
"<br",
">",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"=",
"a<sub",
">",
"ij<",
"/",
"sub",
">",
"*",
"b<sub",
">",
"ij<",
"/",
"sub",
">",
... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/CommonOps_DDRM.java#L1507-L1518 |
Omertron/api-thetvdb | src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java | DOMHelper.getValueFromElement | public static String getValueFromElement(Element element, String tagName) {
NodeList elementNodeList = element.getElementsByTagName(tagName);
if (elementNodeList == null) {
return "";
} else {
Element tagElement = (Element) elementNodeList.item(0);
if (tagElement == null) {
return "";
}
NodeList tagNodeList = tagElement.getChildNodes();
if (tagNodeList == null || tagNodeList.getLength() == 0) {
return "";
}
return tagNodeList.item(0).getNodeValue();
}
} | java | public static String getValueFromElement(Element element, String tagName) {
NodeList elementNodeList = element.getElementsByTagName(tagName);
if (elementNodeList == null) {
return "";
} else {
Element tagElement = (Element) elementNodeList.item(0);
if (tagElement == null) {
return "";
}
NodeList tagNodeList = tagElement.getChildNodes();
if (tagNodeList == null || tagNodeList.getLength() == 0) {
return "";
}
return tagNodeList.item(0).getNodeValue();
}
} | [
"public",
"static",
"String",
"getValueFromElement",
"(",
"Element",
"element",
",",
"String",
"tagName",
")",
"{",
"NodeList",
"elementNodeList",
"=",
"element",
".",
"getElementsByTagName",
"(",
"tagName",
")",
";",
"if",
"(",
"elementNodeList",
"==",
"null",
... | Gets the string value of the tag element name passed
@param element
@param tagName
@return | [
"Gets",
"the",
"string",
"value",
"of",
"the",
"tag",
"element",
"name",
"passed"
] | train | https://github.com/Omertron/api-thetvdb/blob/2ff9f9580e76043f19d2fc3234d87e16a95fa485/src/main/java/com/omertron/thetvdbapi/tools/DOMHelper.java#L93-L109 |
canoo/dolphin-platform | platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java | TypeUtils.substituteTypeVariables | private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) {
if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
final Type replacementType = typeVarAssigns.get(type);
if (replacementType == null) {
throw new IllegalArgumentException("missing assignment type for type variable "
+ type);
}
return replacementType;
}
return type;
} | java | private static Type substituteTypeVariables(final Type type, final Map<TypeVariable<?>, Type> typeVarAssigns) {
if (type instanceof TypeVariable<?> && typeVarAssigns != null) {
final Type replacementType = typeVarAssigns.get(type);
if (replacementType == null) {
throw new IllegalArgumentException("missing assignment type for type variable "
+ type);
}
return replacementType;
}
return type;
} | [
"private",
"static",
"Type",
"substituteTypeVariables",
"(",
"final",
"Type",
"type",
",",
"final",
"Map",
"<",
"TypeVariable",
"<",
"?",
">",
",",
"Type",
">",
"typeVarAssigns",
")",
"{",
"if",
"(",
"type",
"instanceof",
"TypeVariable",
"<",
"?",
">",
"&&... | <p>Find the mapping for {@code type} in {@code typeVarAssigns}.</p>
@param type the type to be replaced
@param typeVarAssigns the map with type variables
@return the replaced type
@throws IllegalArgumentException if the type cannot be substituted | [
"<p",
">",
"Find",
"the",
"mapping",
"for",
"{",
"@code",
"type",
"}",
"in",
"{",
"@code",
"typeVarAssigns",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/canoo/dolphin-platform/blob/fb99c1fab24df80d2fa094d8688b546140146874/platform/dolphin-platform-core/src/main/java/com/canoo/dp/impl/platform/core/commons/lang/TypeUtils.java#L654-L665 |
joniles/mpxj | src/main/java/net/sf/mpxj/primavera/p3/P3DatabaseReader.java | P3DatabaseReader.listProjectNames | public static final List<String> listProjectNames(File directory)
{
List<String> result = new ArrayList<String>();
File[] files = directory.listFiles(new FilenameFilter()
{
@Override public boolean accept(File dir, String name)
{
return name.toUpperCase().endsWith("STR.P3");
}
});
if (files != null)
{
for (File file : files)
{
String fileName = file.getName();
String prefix = fileName.substring(0, fileName.length() - 6);
result.add(prefix);
}
}
Collections.sort(result);
return result;
} | java | public static final List<String> listProjectNames(File directory)
{
List<String> result = new ArrayList<String>();
File[] files = directory.listFiles(new FilenameFilter()
{
@Override public boolean accept(File dir, String name)
{
return name.toUpperCase().endsWith("STR.P3");
}
});
if (files != null)
{
for (File file : files)
{
String fileName = file.getName();
String prefix = fileName.substring(0, fileName.length() - 6);
result.add(prefix);
}
}
Collections.sort(result);
return result;
} | [
"public",
"static",
"final",
"List",
"<",
"String",
">",
"listProjectNames",
"(",
"File",
"directory",
")",
"{",
"List",
"<",
"String",
">",
"result",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"File",
"[",
"]",
"files",
"=",
"director... | Retrieve a list of the available P3 project names from a directory.
@param directory directory containing P3 files
@return list of project names | [
"Retrieve",
"a",
"list",
"of",
"the",
"available",
"P3",
"project",
"names",
"from",
"a",
"directory",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/p3/P3DatabaseReader.java#L118-L143 |
Deep-Symmetry/beat-link | src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java | Client.buildRMST | @SuppressWarnings("WeakerAccess")
public static NumberField buildRMST(int requestingPlayer, Message.MenuIdentifier targetMenu,
CdjStatus.TrackSourceSlot slot) {
return buildRMST(requestingPlayer, targetMenu, slot, CdjStatus.TrackType.REKORDBOX);
} | java | @SuppressWarnings("WeakerAccess")
public static NumberField buildRMST(int requestingPlayer, Message.MenuIdentifier targetMenu,
CdjStatus.TrackSourceSlot slot) {
return buildRMST(requestingPlayer, targetMenu, slot, CdjStatus.TrackType.REKORDBOX);
} | [
"@",
"SuppressWarnings",
"(",
"\"WeakerAccess\"",
")",
"public",
"static",
"NumberField",
"buildRMST",
"(",
"int",
"requestingPlayer",
",",
"Message",
".",
"MenuIdentifier",
"targetMenu",
",",
"CdjStatus",
".",
"TrackSourceSlot",
"slot",
")",
"{",
"return",
"buildRM... | <p>Build the <em>R:M:S:T</em> parameter that begins many queries, when T=1.</p>
<p>Many request messages take, as their first argument, a 4-byte value where each byte has a special meaning.
The first byte is the player number of the requesting player. The second identifies the menu into which
the response is being loaded, as described by {@link Message.MenuIdentifier}. The third specifies the media
slot from which information is desired, as described by {@link CdjStatus.TrackSourceSlot}, and the fourth
byte identifies the type of track about which information is being requested; in most requests this has the
value 1, which corresponds to rekordbox tracks, and this version of the function assumes that.</p>
@param requestingPlayer the player number that is asking the question
@param targetMenu the destination for the response to this query
@param slot the media library of interest for this query
@return the first argument to send with the query in order to obtain the desired information | [
"<p",
">",
"Build",
"the",
"<em",
">",
"R",
":",
"M",
":",
"S",
":",
"T<",
"/",
"em",
">",
"parameter",
"that",
"begins",
"many",
"queries",
"when",
"T",
"=",
"1",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/dbserver/Client.java#L262-L266 |
JOML-CI/JOML | src/org/joml/sampling/SpiralSampling.java | SpiralSampling.createEquiAngle | public void createEquiAngle(float radius, int numRotations, int numSamples, Callback2d callback) {
for (int sample = 0; sample < numSamples; sample++) {
float angle = 2.0f * (float) Math.PI * (sample * numRotations) / numSamples;
float r = radius * sample / (numSamples - 1);
float x = (float) Math.sin_roquen_9(angle + 0.5f * (float) Math.PI) * r;
float y = (float) Math.sin_roquen_9(angle) * r;
callback.onNewSample(x, y);
}
} | java | public void createEquiAngle(float radius, int numRotations, int numSamples, Callback2d callback) {
for (int sample = 0; sample < numSamples; sample++) {
float angle = 2.0f * (float) Math.PI * (sample * numRotations) / numSamples;
float r = radius * sample / (numSamples - 1);
float x = (float) Math.sin_roquen_9(angle + 0.5f * (float) Math.PI) * r;
float y = (float) Math.sin_roquen_9(angle) * r;
callback.onNewSample(x, y);
}
} | [
"public",
"void",
"createEquiAngle",
"(",
"float",
"radius",
",",
"int",
"numRotations",
",",
"int",
"numSamples",
",",
"Callback2d",
"callback",
")",
"{",
"for",
"(",
"int",
"sample",
"=",
"0",
";",
"sample",
"<",
"numSamples",
";",
"sample",
"++",
")",
... | Create <code>numSamples</code> number of samples on a spiral with maximum radius <code>radius</code> around the center using <code>numRotations</code> number of rotations
along the spiral, and call the given <code>callback</code> for each sample generated.
<p>
The generated sample points are distributed with equal angle differences around the spiral, so they concentrate towards the center.
@param radius
the maximum radius of the spiral
@param numRotations
the number of rotations of the spiral
@param numSamples
the number of samples to generate
@param callback
will be called for each sample generated | [
"Create",
"<code",
">",
"numSamples<",
"/",
"code",
">",
"number",
"of",
"samples",
"on",
"a",
"spiral",
"with",
"maximum",
"radius",
"<code",
">",
"radius<",
"/",
"code",
">",
"around",
"the",
"center",
"using",
"<code",
">",
"numRotations<",
"/",
"code",... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/sampling/SpiralSampling.java#L61-L69 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java | SheetUpdateRequestResourcesImpl.createUpdateRequest | public UpdateRequest createUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException {
return this.createResource("sheets/" + sheetId + "/updaterequests", UpdateRequest.class, updateRequest);
} | java | public UpdateRequest createUpdateRequest(long sheetId, UpdateRequest updateRequest) throws SmartsheetException {
return this.createResource("sheets/" + sheetId + "/updaterequests", UpdateRequest.class, updateRequest);
} | [
"public",
"UpdateRequest",
"createUpdateRequest",
"(",
"long",
"sheetId",
",",
"UpdateRequest",
"updateRequest",
")",
"throws",
"SmartsheetException",
"{",
"return",
"this",
".",
"createResource",
"(",
"\"sheets/\"",
"+",
"sheetId",
"+",
"\"/updaterequests\"",
",",
"U... | Creates an Update Request for the specified Row(s) within the Sheet. An email notification
(containing a link to the update request) will be asynchronously sent to the specified recipient(s).
It mirrors to the following Smartsheet REST API method: POST /sheets/{sheetId}/updaterequests
@param sheetId the Id of the sheet
@param updateRequest the update request object
@return the update request resource.
@throws IllegalArgumentException if any argument is null or empty string
@throws InvalidRequestException if there is any problem with the REST API request
@throws AuthorizationException if there is any problem with the REST API authorization (access token)
@throws ResourceNotFoundException if the resource cannot be found
@throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
@throws SmartsheetException if there is any other error during the operation | [
"Creates",
"an",
"Update",
"Request",
"for",
"the",
"specified",
"Row",
"(",
"s",
")",
"within",
"the",
"Sheet",
".",
"An",
"email",
"notification",
"(",
"containing",
"a",
"link",
"to",
"the",
"update",
"request",
")",
"will",
"be",
"asynchronously",
"sen... | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetUpdateRequestResourcesImpl.java#L112-L114 |
phax/ph-commons | ph-xml/src/main/java/com/helger/xml/microdom/AbstractMicroNode.java | AbstractMicroNode.onInsertAfter | @OverrideOnDemand
protected void onInsertAfter (@Nonnull final AbstractMicroNode aChildNode, @Nonnull final IMicroNode aPredecessor)
{
throw new MicroException ("Cannot insert children in class " + getClass ().getName ());
} | java | @OverrideOnDemand
protected void onInsertAfter (@Nonnull final AbstractMicroNode aChildNode, @Nonnull final IMicroNode aPredecessor)
{
throw new MicroException ("Cannot insert children in class " + getClass ().getName ());
} | [
"@",
"OverrideOnDemand",
"protected",
"void",
"onInsertAfter",
"(",
"@",
"Nonnull",
"final",
"AbstractMicroNode",
"aChildNode",
",",
"@",
"Nonnull",
"final",
"IMicroNode",
"aPredecessor",
")",
"{",
"throw",
"new",
"MicroException",
"(",
"\"Cannot insert children in clas... | Callback that is invoked once a child is to be inserted after another
child.
@param aChildNode
The new child node to be inserted.
@param aPredecessor
The node after which the new node will be inserted. | [
"Callback",
"that",
"is",
"invoked",
"once",
"a",
"child",
"is",
"to",
"be",
"inserted",
"after",
"another",
"child",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/microdom/AbstractMicroNode.java#L89-L93 |
geomajas/geomajas-project-client-gwt2 | plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java | TileBasedLayerClient.createDefaultOsmLayer | public OsmLayer createDefaultOsmLayer(String id, int nrOfLevels) {
OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels));
layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS));
return layer;
} | java | public OsmLayer createDefaultOsmLayer(String id, int nrOfLevels) {
OsmLayer layer = new OsmLayer(id, createOsmTileConfiguration(nrOfLevels));
layer.addUrls(Arrays.asList(DEFAULT_OSM_URLS));
return layer;
} | [
"public",
"OsmLayer",
"createDefaultOsmLayer",
"(",
"String",
"id",
",",
"int",
"nrOfLevels",
")",
"{",
"OsmLayer",
"layer",
"=",
"new",
"OsmLayer",
"(",
"id",
",",
"createOsmTileConfiguration",
"(",
"nrOfLevels",
")",
")",
";",
"layer",
".",
"addUrls",
"(",
... | Create a new OSM layer with the given ID and tile configuration. The layer will be configured
with the default OSM tile services so you don't have to specify these URLs yourself.
@param id The unique ID of the layer.
@param conf The tile configuration.
@return A new OSM layer.
@since 2.2.1 | [
"Create",
"a",
"new",
"OSM",
"layer",
"with",
"the",
"given",
"ID",
"and",
"tile",
"configuration",
".",
"The",
"layer",
"will",
"be",
"configured",
"with",
"the",
"default",
"OSM",
"tile",
"services",
"so",
"you",
"don",
"t",
"have",
"to",
"specify",
"t... | train | https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/tilebasedlayer/impl/src/main/java/org/geomajas/gwt2/plugin/tilebasedlayer/client/TileBasedLayerClient.java#L117-L121 |
Stratio/deep-spark | deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java | MongoNativeExtractor.getSplitData | private BasicDBList getSplitData(DBCollection collection) {
final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName())
.add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1))
.add("force", false)
.add("maxChunkSize", splitSize)
.get();
CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd);
return (BasicDBList) splitVectorResult.get(SPLIT_KEYS);
} | java | private BasicDBList getSplitData(DBCollection collection) {
final DBObject cmd = BasicDBObjectBuilder.start("splitVector", collection.getFullName())
.add("keyPattern", new BasicDBObject(MONGO_DEFAULT_ID, 1))
.add("force", false)
.add("maxChunkSize", splitSize)
.get();
CommandResult splitVectorResult = collection.getDB().getSisterDB("admin").command(cmd);
return (BasicDBList) splitVectorResult.get(SPLIT_KEYS);
} | [
"private",
"BasicDBList",
"getSplitData",
"(",
"DBCollection",
"collection",
")",
"{",
"final",
"DBObject",
"cmd",
"=",
"BasicDBObjectBuilder",
".",
"start",
"(",
"\"splitVector\"",
",",
"collection",
".",
"getFullName",
"(",
")",
")",
".",
"add",
"(",
"\"keyPat... | Gets split data.
@param collection the collection
@return the split data | [
"Gets",
"split",
"data",
"."
] | train | https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java#L237-L248 |
google/gson | gson/src/main/java/com/google/gson/TypeAdapter.java | TypeAdapter.nullSafe | public final TypeAdapter<T> nullSafe() {
return new TypeAdapter<T>() {
@Override public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
} else {
TypeAdapter.this.write(out, value);
}
}
@Override public T read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
return TypeAdapter.this.read(reader);
}
};
} | java | public final TypeAdapter<T> nullSafe() {
return new TypeAdapter<T>() {
@Override public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
out.nullValue();
} else {
TypeAdapter.this.write(out, value);
}
}
@Override public T read(JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
return TypeAdapter.this.read(reader);
}
};
} | [
"public",
"final",
"TypeAdapter",
"<",
"T",
">",
"nullSafe",
"(",
")",
"{",
"return",
"new",
"TypeAdapter",
"<",
"T",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"void",
"write",
"(",
"JsonWriter",
"out",
",",
"T",
"value",
")",
"throws",
"IOExcepti... | This wrapper method is used to make a type adapter null tolerant. In general, a
type adapter is required to handle nulls in write and read methods. Here is how this
is typically done:<br>
<pre> {@code
Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
new TypeAdapter<Foo>() {
public Foo read(JsonReader in) throws IOException {
if (in.peek() == JsonToken.NULL) {
in.nextNull();
return null;
}
// read a Foo from in and return it
}
public void write(JsonWriter out, Foo src) throws IOException {
if (src == null) {
out.nullValue();
return;
}
// write src as JSON to out
}
}).create();
}</pre>
You can avoid this boilerplate handling of nulls by wrapping your type adapter with
this method. Here is how we will rewrite the above example:
<pre> {@code
Gson gson = new GsonBuilder().registerTypeAdapter(Foo.class,
new TypeAdapter<Foo>() {
public Foo read(JsonReader in) throws IOException {
// read a Foo from in and return it
}
public void write(JsonWriter out, Foo src) throws IOException {
// write src as JSON to out
}
}.nullSafe()).create();
}</pre>
Note that we didn't need to check for nulls in our type adapter after we used nullSafe. | [
"This",
"wrapper",
"method",
"is",
"used",
"to",
"make",
"a",
"type",
"adapter",
"null",
"tolerant",
".",
"In",
"general",
"a",
"type",
"adapter",
"is",
"required",
"to",
"handle",
"nulls",
"in",
"write",
"and",
"read",
"methods",
".",
"Here",
"is",
"how... | train | https://github.com/google/gson/blob/63ee47cb642c8018e5cddd639aa2be143220ad4b/gson/src/main/java/com/google/gson/TypeAdapter.java#L185-L202 |
cternes/openkeepass | src/main/java/de/slackspace/openkeepass/KeePassDatabase.java | KeePassDatabase.openDatabase | public KeePassFile openDatabase(String password, InputStream keyFileStream) {
if (password == null) {
throw new IllegalArgumentException(MSG_EMPTY_MASTER_KEY);
}
if (keyFileStream == null) {
throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream.");
}
try {
byte[] passwordBytes = password.getBytes(UTF_8);
byte[] hashedPassword = Sha256.hash(passwordBytes);
byte[] protectedBuffer = new KeyFileReader().readKeyFile(keyFileStream);
return new KeePassDatabaseReader(keepassHeader).decryptAndParseDatabase(ByteUtils.concat(hashedPassword, protectedBuffer), keepassFile);
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(MSG_UTF8_NOT_SUPPORTED, e);
}
} | java | public KeePassFile openDatabase(String password, InputStream keyFileStream) {
if (password == null) {
throw new IllegalArgumentException(MSG_EMPTY_MASTER_KEY);
}
if (keyFileStream == null) {
throw new IllegalArgumentException("You must provide a non-empty KeePass keyfile stream.");
}
try {
byte[] passwordBytes = password.getBytes(UTF_8);
byte[] hashedPassword = Sha256.hash(passwordBytes);
byte[] protectedBuffer = new KeyFileReader().readKeyFile(keyFileStream);
return new KeePassDatabaseReader(keepassHeader).decryptAndParseDatabase(ByteUtils.concat(hashedPassword, protectedBuffer), keepassFile);
} catch (UnsupportedEncodingException e) {
throw new UnsupportedOperationException(MSG_UTF8_NOT_SUPPORTED, e);
}
} | [
"public",
"KeePassFile",
"openDatabase",
"(",
"String",
"password",
",",
"InputStream",
"keyFileStream",
")",
"{",
"if",
"(",
"password",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"MSG_EMPTY_MASTER_KEY",
")",
";",
"}",
"if",
"(",
... | Opens a KeePass database with the given password and keyfile stream and
returns the KeePassFile for further processing.
<p>
If the database cannot be decrypted with the provided password and
keyfile stream an exception will be thrown.
@param password
the password to open the database
@param keyFileStream
the keyfile to open the database as stream
@return a KeePassFile
@see KeePassFile | [
"Opens",
"a",
"KeePass",
"database",
"with",
"the",
"given",
"password",
"and",
"keyfile",
"stream",
"and",
"returns",
"the",
"KeePassFile",
"for",
"further",
"processing",
".",
"<p",
">",
"If",
"the",
"database",
"cannot",
"be",
"decrypted",
"with",
"the",
... | train | https://github.com/cternes/openkeepass/blob/4a354aecaea38af3c0dce5eb81b533f297e8d94f/src/main/java/de/slackspace/openkeepass/KeePassDatabase.java#L225-L242 |
UrielCh/ovh-java-sdk | ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java | ApiOvhOrder.cart_cartId_item_itemId_GET | public OvhItem cart_cartId_item_itemId_GET(String cartId, Long itemId) throws IOException {
String qPath = "/order/cart/{cartId}/item/{itemId}";
StringBuilder sb = path(qPath, cartId, itemId);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhItem.class);
} | java | public OvhItem cart_cartId_item_itemId_GET(String cartId, Long itemId) throws IOException {
String qPath = "/order/cart/{cartId}/item/{itemId}";
StringBuilder sb = path(qPath, cartId, itemId);
String resp = execN(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhItem.class);
} | [
"public",
"OvhItem",
"cart_cartId_item_itemId_GET",
"(",
"String",
"cartId",
",",
"Long",
"itemId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/order/cart/{cartId}/item/{itemId}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPath",
",",
"cart... | Retrieve information about a specific item of a cart
REST: GET /order/cart/{cartId}/item/{itemId}
@param cartId [required] Cart identifier
@param itemId [required] Product item identifier | [
"Retrieve",
"information",
"about",
"a",
"specific",
"item",
"of",
"a",
"cart"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L8005-L8010 |
orbisgis/h2gis | h2gis-network/src/main/java/org/h2gis/network/functions/ST_GraphAnalysis.java | ST_GraphAnalysis.doGraphAnalysis | public static boolean doGraphAnalysis(Connection connection,
String inputTable,
String orientation)
throws SQLException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
return doGraphAnalysis(connection, inputTable, orientation, null);
} | java | public static boolean doGraphAnalysis(Connection connection,
String inputTable,
String orientation)
throws SQLException, NoSuchMethodException, InstantiationException,
IllegalAccessException, InvocationTargetException {
return doGraphAnalysis(connection, inputTable, orientation, null);
} | [
"public",
"static",
"boolean",
"doGraphAnalysis",
"(",
"Connection",
"connection",
",",
"String",
"inputTable",
",",
"String",
"orientation",
")",
"throws",
"SQLException",
",",
"NoSuchMethodException",
",",
"InstantiationException",
",",
"IllegalAccessException",
",",
... | Calculate centrality indices on the nodes and edges of a graph
constructed from the input table.
@param connection Connection
@param inputTable Input table
@param orientation Global orientation
@return True if the calculation was successful
@throws SQLException
@throws NoSuchMethodException
@throws InstantiationException
@throws IllegalAccessException
@throws InvocationTargetException | [
"Calculate",
"centrality",
"indices",
"on",
"the",
"nodes",
"and",
"edges",
"of",
"a",
"graph",
"constructed",
"from",
"the",
"input",
"table",
"."
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-network/src/main/java/org/h2gis/network/functions/ST_GraphAnalysis.java#L104-L110 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UResourceBundle.java | UResourceBundle.getBundleInstance | public static UResourceBundle getBundleInstance(String baseName, ULocale locale,
ClassLoader loader) {
if (baseName == null) {
baseName = ICUData.ICU_BASE_NAME;
}
if (locale == null) {
locale = ULocale.getDefault();
}
return getBundleInstance(baseName, locale.getBaseName(), loader, false);
} | java | public static UResourceBundle getBundleInstance(String baseName, ULocale locale,
ClassLoader loader) {
if (baseName == null) {
baseName = ICUData.ICU_BASE_NAME;
}
if (locale == null) {
locale = ULocale.getDefault();
}
return getBundleInstance(baseName, locale.getBaseName(), loader, false);
} | [
"public",
"static",
"UResourceBundle",
"getBundleInstance",
"(",
"String",
"baseName",
",",
"ULocale",
"locale",
",",
"ClassLoader",
"loader",
")",
"{",
"if",
"(",
"baseName",
"==",
"null",
")",
"{",
"baseName",
"=",
"ICUData",
".",
"ICU_BASE_NAME",
";",
"}",
... | <strong>[icu]</strong> Creates a UResourceBundle, from which users can extract resources by using
their corresponding keys.<br><br>
Note: Please use this API for loading non-ICU resources. Java security does not
allow loading of resources across jar files. You must provide your class loader
to load the resources
@param baseName string containing the name of the data package.
If null the default ICU package name is used.
@param locale specifies the locale for which we want to open the resource.
If null the bundle for default locale is opened.
@param loader the loader to use
@return a resource bundle for the given base name and locale | [
"<strong",
">",
"[",
"icu",
"]",
"<",
"/",
"strong",
">",
"Creates",
"a",
"UResourceBundle",
"from",
"which",
"users",
"can",
"extract",
"resources",
"by",
"using",
"their",
"corresponding",
"keys",
".",
"<br",
">",
"<br",
">",
"Note",
":",
"Please",
"us... | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/UResourceBundle.java#L261-L270 |
opsmatters/newrelic-api | src/main/java/com/opsmatters/newrelic/api/NewRelicClient.java | NewRelicClient.initialize | public NewRelicClient initialize()
{
Client client = provider.getClient();
String protocol = provider.useSsl() ? "https" : "http";
httpContext = new HttpContext(client, protocol, hostname, port);
httpContext.setUriPrefix(getUriPrefix());
httpContext.setThrowExceptions(handleErrors);
String className = getClass().getName();
logger.fine(className.substring(className.lastIndexOf(".")+1)+" initialized");
return this;
} | java | public NewRelicClient initialize()
{
Client client = provider.getClient();
String protocol = provider.useSsl() ? "https" : "http";
httpContext = new HttpContext(client, protocol, hostname, port);
httpContext.setUriPrefix(getUriPrefix());
httpContext.setThrowExceptions(handleErrors);
String className = getClass().getName();
logger.fine(className.substring(className.lastIndexOf(".")+1)+" initialized");
return this;
} | [
"public",
"NewRelicClient",
"initialize",
"(",
")",
"{",
"Client",
"client",
"=",
"provider",
".",
"getClient",
"(",
")",
";",
"String",
"protocol",
"=",
"provider",
".",
"useSsl",
"(",
")",
"?",
"\"https\"",
":",
"\"http\"",
";",
"httpContext",
"=",
"new"... | Called after setting configuration properties.
@return This object | [
"Called",
"after",
"setting",
"configuration",
"properties",
"."
] | train | https://github.com/opsmatters/newrelic-api/blob/5bc2ea62ec368db891e4fd5fe3dcdf529d086b5e/src/main/java/com/opsmatters/newrelic/api/NewRelicClient.java#L68-L78 |
hibernate/hibernate-ogm | core/src/main/java/org/hibernate/ogm/dialect/impl/GridDialects.java | GridDialects.getDelegateOrNull | public static <T extends GridDialect> T getDelegateOrNull(GridDialect gridDialect, Class<T> delegateType) {
if ( gridDialect.getClass() == delegateType ) {
return delegateType.cast( gridDialect );
}
else if ( gridDialect instanceof ForwardingGridDialect ) {
return getDelegateOrNull( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), delegateType );
}
else {
return null;
}
} | java | public static <T extends GridDialect> T getDelegateOrNull(GridDialect gridDialect, Class<T> delegateType) {
if ( gridDialect.getClass() == delegateType ) {
return delegateType.cast( gridDialect );
}
else if ( gridDialect instanceof ForwardingGridDialect ) {
return getDelegateOrNull( ( (ForwardingGridDialect<?>) gridDialect ).getGridDialect(), delegateType );
}
else {
return null;
}
} | [
"public",
"static",
"<",
"T",
"extends",
"GridDialect",
">",
"T",
"getDelegateOrNull",
"(",
"GridDialect",
"gridDialect",
",",
"Class",
"<",
"T",
">",
"delegateType",
")",
"{",
"if",
"(",
"gridDialect",
".",
"getClass",
"(",
")",
"==",
"delegateType",
")",
... | Returns that delegate of the given grid dialect of the given type. In case the given dialect itself is of the
given type, it will be returned itself. In case the given grid dialect is a {@link ForwardingGridDialect}, its
delegates will recursively be searched, until the first delegate of the given type is found. | [
"Returns",
"that",
"delegate",
"of",
"the",
"given",
"grid",
"dialect",
"of",
"the",
"given",
"type",
".",
"In",
"case",
"the",
"given",
"dialect",
"itself",
"is",
"of",
"the",
"given",
"type",
"it",
"will",
"be",
"returned",
"itself",
".",
"In",
"case",... | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/core/src/main/java/org/hibernate/ogm/dialect/impl/GridDialects.java#L81-L91 |
goldmansachs/gs-collections | collections/src/main/java/com/gs/collections/impl/utility/Iterate.java | Iterate.forEach | public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure)
{
if (iterable instanceof InternalIterable)
{
((InternalIterable<T>) iterable).forEach(procedure);
}
else if (iterable instanceof ArrayList)
{
ArrayListIterate.forEach((ArrayList<T>) iterable, procedure);
}
else if (iterable instanceof List)
{
ListIterate.forEach((List<T>) iterable, procedure);
}
else if (iterable != null)
{
IterableIterate.forEach(iterable, procedure);
}
else
{
throw new IllegalArgumentException("Cannot perform a forEach on null");
}
} | java | public static <T> void forEach(Iterable<T> iterable, Procedure<? super T> procedure)
{
if (iterable instanceof InternalIterable)
{
((InternalIterable<T>) iterable).forEach(procedure);
}
else if (iterable instanceof ArrayList)
{
ArrayListIterate.forEach((ArrayList<T>) iterable, procedure);
}
else if (iterable instanceof List)
{
ListIterate.forEach((List<T>) iterable, procedure);
}
else if (iterable != null)
{
IterableIterate.forEach(iterable, procedure);
}
else
{
throw new IllegalArgumentException("Cannot perform a forEach on null");
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"forEach",
"(",
"Iterable",
"<",
"T",
">",
"iterable",
",",
"Procedure",
"<",
"?",
"super",
"T",
">",
"procedure",
")",
"{",
"if",
"(",
"iterable",
"instanceof",
"InternalIterable",
")",
"{",
"(",
"(",
"Intern... | The procedure is evaluated for each element of the iterable.
<p>
Example using a Java 8 lambda expression:
<pre>
Iterate.<b>forEach</b>(people, person -> LOGGER.info(person.getName());
</pre>
<p>
Example using an anonymous inner class:
<pre>
Iterate.<b>forEach</b>(people, new Procedure<Person>()
{
public void value(Person person)
{
LOGGER.info(person.getName());
}
});
</pre> | [
"The",
"procedure",
"is",
"evaluated",
"for",
"each",
"element",
"of",
"the",
"iterable",
".",
"<p",
">",
"Example",
"using",
"a",
"Java",
"8",
"lambda",
"expression",
":",
"<pre",
">",
"Iterate",
".",
"<b",
">",
"forEach<",
"/",
"b",
">",
"(",
"people... | train | https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L125-L147 |
krummas/DrizzleJDBC | src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java | DrizzlePreparedStatement.setTimestamp | public void setTimestamp(final int parameterIndex, final Timestamp x) throws SQLException {
if(x == null) {
setNull(parameterIndex, Types.TIMESTAMP);
return;
}
setParameter(parameterIndex, new TimestampParameter(x.getTime()));
} | java | public void setTimestamp(final int parameterIndex, final Timestamp x) throws SQLException {
if(x == null) {
setNull(parameterIndex, Types.TIMESTAMP);
return;
}
setParameter(parameterIndex, new TimestampParameter(x.getTime()));
} | [
"public",
"void",
"setTimestamp",
"(",
"final",
"int",
"parameterIndex",
",",
"final",
"Timestamp",
"x",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"x",
"==",
"null",
")",
"{",
"setNull",
"(",
"parameterIndex",
",",
"Types",
".",
"TIMESTAMP",
")",
";",... | Sets the designated parameter to the given <code>java.sql.Timestamp</code> value. The driver converts this to an
SQL <code>TIMESTAMP</code> value when it sends it to the database.
@param parameterIndex the first parameter is 1, the second is 2, ...
@param x the parameter value
@throws java.sql.SQLException if parameterIndex does not correspond to a parameter marker in the SQL statement;
if a database access error occurs or this method is called on a closed
<code>PreparedStatement</code> | [
"Sets",
"the",
"designated",
"parameter",
"to",
"the",
"given",
"<code",
">",
"java",
".",
"sql",
".",
"Timestamp<",
"/",
"code",
">",
"value",
".",
"The",
"driver",
"converts",
"this",
"to",
"an",
"SQL",
"<code",
">",
"TIMESTAMP<",
"/",
"code",
">",
"... | train | https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/DrizzlePreparedStatement.java#L1174-L1182 |
box/box-android-sdk | box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java | BoxApiMetadata.getMetadataTemplateSchemaRequest | public BoxRequestsMetadata.GetMetadataTemplateSchema getMetadataTemplateSchemaRequest(String scope, String template) {
BoxRequestsMetadata.GetMetadataTemplateSchema request = new BoxRequestsMetadata.GetMetadataTemplateSchema(getMetadataTemplatesUrl(scope, template), mSession);
return request;
} | java | public BoxRequestsMetadata.GetMetadataTemplateSchema getMetadataTemplateSchemaRequest(String scope, String template) {
BoxRequestsMetadata.GetMetadataTemplateSchema request = new BoxRequestsMetadata.GetMetadataTemplateSchema(getMetadataTemplatesUrl(scope, template), mSession);
return request;
} | [
"public",
"BoxRequestsMetadata",
".",
"GetMetadataTemplateSchema",
"getMetadataTemplateSchemaRequest",
"(",
"String",
"scope",
",",
"String",
"template",
")",
"{",
"BoxRequestsMetadata",
".",
"GetMetadataTemplateSchema",
"request",
"=",
"new",
"BoxRequestsMetadata",
".",
"G... | Gets a request that retrieves a metadata template schema (scope defaults to BOX_API_SCOPE_ENTERPRISE)
@param scope currently only global and enterprise scopes are supported
@param template metadata template to use
@return request to retrieve a metadata template schema | [
"Gets",
"a",
"request",
"that",
"retrieves",
"a",
"metadata",
"template",
"schema",
"(",
"scope",
"defaults",
"to",
"BOX_API_SCOPE_ENTERPRISE",
")"
] | train | https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java#L300-L303 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.badConversion | public static void badConversion(Field destinationField, Class<?> destinationClass, Field sourceField, Class<?> sourceClass,String plus){
throw new UndefinedMappingException(MSG.INSTANCE.message(undefinedMappingException,destinationField.getName(),destinationClass.getSimpleName(),sourceField.getName(),sourceClass.getSimpleName()) + ". More information: "+plus);
} | java | public static void badConversion(Field destinationField, Class<?> destinationClass, Field sourceField, Class<?> sourceClass,String plus){
throw new UndefinedMappingException(MSG.INSTANCE.message(undefinedMappingException,destinationField.getName(),destinationClass.getSimpleName(),sourceField.getName(),sourceClass.getSimpleName()) + ". More information: "+plus);
} | [
"public",
"static",
"void",
"badConversion",
"(",
"Field",
"destinationField",
",",
"Class",
"<",
"?",
">",
"destinationClass",
",",
"Field",
"sourceField",
",",
"Class",
"<",
"?",
">",
"sourceClass",
",",
"String",
"plus",
")",
"{",
"throw",
"new",
"Undefin... | Thrown when conversions are badly written.
@param destinationField destination field
@param destinationClass destination class
@param sourceField source field
@param sourceClass source class
@param plus added messages of internal exceptions thrown | [
"Thrown",
"when",
"conversions",
"are",
"badly",
"written",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L408-L410 |
ManfredTremmel/gwt-bean-validators | gwt-bean-validators/src/main/java/de/knightsoftnet/validators/rebind/BeanHelperCache.java | BeanHelperCache.createHelper | BeanHelper createHelper(final JClassType pjtype, final TreeLogger plogger,
final GeneratorContext pcontext) throws UnableToCompleteException {
final JClassType erasedType = pjtype.getErasedType();
try {
final Class<?> clazz = Class.forName(erasedType.getQualifiedBinaryName());
return doCreateHelper(clazz, erasedType, plogger, pcontext);
} catch (final ClassNotFoundException e) {
plogger.log(TreeLogger.ERROR, "Unable to create BeanHelper for " + erasedType, e);
throw new UnableToCompleteException(); // NOPMD
}
} | java | BeanHelper createHelper(final JClassType pjtype, final TreeLogger plogger,
final GeneratorContext pcontext) throws UnableToCompleteException {
final JClassType erasedType = pjtype.getErasedType();
try {
final Class<?> clazz = Class.forName(erasedType.getQualifiedBinaryName());
return doCreateHelper(clazz, erasedType, plogger, pcontext);
} catch (final ClassNotFoundException e) {
plogger.log(TreeLogger.ERROR, "Unable to create BeanHelper for " + erasedType, e);
throw new UnableToCompleteException(); // NOPMD
}
} | [
"BeanHelper",
"createHelper",
"(",
"final",
"JClassType",
"pjtype",
",",
"final",
"TreeLogger",
"plogger",
",",
"final",
"GeneratorContext",
"pcontext",
")",
"throws",
"UnableToCompleteException",
"{",
"final",
"JClassType",
"erasedType",
"=",
"pjtype",
".",
"getErase... | Creates a BeanHelper and writes an interface containing its instance. Also, recursively creates
any BeanHelpers on its constrained properties. | [
"Creates",
"a",
"BeanHelper",
"and",
"writes",
"an",
"interface",
"containing",
"its",
"instance",
".",
"Also",
"recursively",
"creates",
"any",
"BeanHelpers",
"on",
"its",
"constrained",
"properties",
"."
] | train | https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwt-bean-validators/src/main/java/de/knightsoftnet/validators/rebind/BeanHelperCache.java#L84-L94 |
azkaban/azkaban | azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java | ProjectManagerServlet.lockFlowsForProject | private void lockFlowsForProject(Project project, List<String> lockedFlows) {
for (String flowId: lockedFlows) {
Flow flow = project.getFlow(flowId);
if (flow != null) {
flow.setLocked(true);
}
}
} | java | private void lockFlowsForProject(Project project, List<String> lockedFlows) {
for (String flowId: lockedFlows) {
Flow flow = project.getFlow(flowId);
if (flow != null) {
flow.setLocked(true);
}
}
} | [
"private",
"void",
"lockFlowsForProject",
"(",
"Project",
"project",
",",
"List",
"<",
"String",
">",
"lockedFlows",
")",
"{",
"for",
"(",
"String",
"flowId",
":",
"lockedFlows",
")",
"{",
"Flow",
"flow",
"=",
"project",
".",
"getFlow",
"(",
"flowId",
")",... | Lock the specified flows for the project.
@param project the project
@param lockedFlows list of flow IDs of flows to lock | [
"Lock",
"the",
"specified",
"flows",
"for",
"the",
"project",
"."
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-web-server/src/main/java/azkaban/webapp/servlet/ProjectManagerServlet.java#L1925-L1932 |
OpenNTF/JavascriptAggregator | jaggr-core/src/main/java/com/ibm/jaggr/core/cachekeygenerator/KeyGenUtil.java | KeyGenUtil.generateKey | static public String generateKey(HttpServletRequest request, Iterable<ICacheKeyGenerator> keyGens) {
StringBuffer sb = new StringBuffer();
for (ICacheKeyGenerator keyGen : keyGens) {
String key = keyGen.generateKey(request);
if (key != null && key.length() > 0) {
sb.append(sb.length() > 0 ? ";" : "").append(key); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return sb.toString();
} | java | static public String generateKey(HttpServletRequest request, Iterable<ICacheKeyGenerator> keyGens) {
StringBuffer sb = new StringBuffer();
for (ICacheKeyGenerator keyGen : keyGens) {
String key = keyGen.generateKey(request);
if (key != null && key.length() > 0) {
sb.append(sb.length() > 0 ? ";" : "").append(key); //$NON-NLS-1$ //$NON-NLS-2$
}
}
return sb.toString();
} | [
"static",
"public",
"String",
"generateKey",
"(",
"HttpServletRequest",
"request",
",",
"Iterable",
"<",
"ICacheKeyGenerator",
">",
"keyGens",
")",
"{",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"for",
"(",
"ICacheKeyGenerator",
"keyGen",
... | Generates a cache key by aggregating (concatenating) the output of
each of the cache key generators in the array.
@param request The request object
@param keyGens The array
@return The aggregated cache key | [
"Generates",
"a",
"cache",
"key",
"by",
"aggregating",
"(",
"concatenating",
")",
"the",
"output",
"of",
"each",
"of",
"the",
"cache",
"key",
"generators",
"in",
"the",
"array",
"."
] | train | https://github.com/OpenNTF/JavascriptAggregator/blob/9f47a96d778251638b1df9a368462176216d5b29/jaggr-core/src/main/java/com/ibm/jaggr/core/cachekeygenerator/KeyGenUtil.java#L58-L67 |
pressgang-ccms/PressGangCCMSBuilder | src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java | DocBookBuilder.buildTranslatedBook | public HashMap<String, byte[]> buildTranslatedBook(final ContentSpec contentSpec, final String requester,
final DocBookBuildingOptions buildingOptions, final Map<String, byte[]> overrideFiles,
final ZanataDetails zanataDetails) throws BuilderCreationException, BuildProcessingException {
return buildBook(contentSpec, requester, buildingOptions, overrideFiles, zanataDetails, true);
} | java | public HashMap<String, byte[]> buildTranslatedBook(final ContentSpec contentSpec, final String requester,
final DocBookBuildingOptions buildingOptions, final Map<String, byte[]> overrideFiles,
final ZanataDetails zanataDetails) throws BuilderCreationException, BuildProcessingException {
return buildBook(contentSpec, requester, buildingOptions, overrideFiles, zanataDetails, true);
} | [
"public",
"HashMap",
"<",
"String",
",",
"byte",
"[",
"]",
">",
"buildTranslatedBook",
"(",
"final",
"ContentSpec",
"contentSpec",
",",
"final",
"String",
"requester",
",",
"final",
"DocBookBuildingOptions",
"buildingOptions",
",",
"final",
"Map",
"<",
"String",
... | Builds a DocBook Formatted Book using a Content Specification to define the structure and contents of the book.
@param contentSpec The content specification to build from.
@param requester The user who requested the build.
@param buildingOptions The options to be used when building.
@param overrideFiles
@param zanataDetails The Zanata server details to be used when populating links
@return Returns a mapping of file names/locations to files. This HashMap can be used to build a ZIP archive.
@throws BuilderCreationException Thrown if the builder is unable to start due to incorrect passed variables.
@throws BuildProcessingException Any build issue that should not occur under normal circumstances. Ie a Template can't be
converted to a DOM Document. | [
"Builds",
"a",
"DocBook",
"Formatted",
"Book",
"using",
"a",
"Content",
"Specification",
"to",
"define",
"the",
"structure",
"and",
"contents",
"of",
"the",
"book",
"."
] | train | https://github.com/pressgang-ccms/PressGangCCMSBuilder/blob/5436d36ba1b3c5baa246b270e5fc350e6778bce8/src/main/java/org/jboss/pressgang/ccms/contentspec/builder/DocBookBuilder.java#L442-L446 |
sothawo/mapjfx | src/main/java/com/sothawo/mapjfx/MapView.java | JavaConnector.singleClickAt | public void singleClickAt(double lat, double lon) {
final Coordinate coordinate = new Coordinate(lat, lon);
if (logger.isTraceEnabled()) {
logger.trace("JS reports single click at {}", coordinate);
}
fireEvent(new MapViewEvent(MapViewEvent.MAP_CLICKED, coordinate));
} | java | public void singleClickAt(double lat, double lon) {
final Coordinate coordinate = new Coordinate(lat, lon);
if (logger.isTraceEnabled()) {
logger.trace("JS reports single click at {}", coordinate);
}
fireEvent(new MapViewEvent(MapViewEvent.MAP_CLICKED, coordinate));
} | [
"public",
"void",
"singleClickAt",
"(",
"double",
"lat",
",",
"double",
"lon",
")",
"{",
"final",
"Coordinate",
"coordinate",
"=",
"new",
"Coordinate",
"(",
"lat",
",",
"lon",
")",
";",
"if",
"(",
"logger",
".",
"isTraceEnabled",
"(",
")",
")",
"{",
"l... | called when the user has single-clicked in the map. the coordinates are EPSG:4326 (WGS) values.
@param lat
new latitude value
@param lon
new longitude value | [
"called",
"when",
"the",
"user",
"has",
"single",
"-",
"clicked",
"in",
"the",
"map",
".",
"the",
"coordinates",
"are",
"EPSG",
":",
"4326",
"(",
"WGS",
")",
"values",
"."
] | train | https://github.com/sothawo/mapjfx/blob/202091de492ab7a8b000c77efd833029f7f0ef92/src/main/java/com/sothawo/mapjfx/MapView.java#L1372-L1378 |
ihaolin/session | session-api/src/main/java/me/hao0/session/util/WebUtil.java | WebUtil.findCookie | public static Cookie findCookie(HttpServletRequest request, String name) {
if (request != null) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
}
return null;
} | java | public static Cookie findCookie(HttpServletRequest request, String name) {
if (request != null) {
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
}
return null;
} | [
"public",
"static",
"Cookie",
"findCookie",
"(",
"HttpServletRequest",
"request",
",",
"String",
"name",
")",
"{",
"if",
"(",
"request",
"!=",
"null",
")",
"{",
"Cookie",
"[",
"]",
"cookies",
"=",
"request",
".",
"getCookies",
"(",
")",
";",
"if",
"(",
... | find cookie from request
@param request current request
@param name cookie name
@return cookie value or null | [
"find",
"cookie",
"from",
"request"
] | train | https://github.com/ihaolin/session/blob/322c3a9f47b305a39345135fa8163dd7e065b4f8/session-api/src/main/java/me/hao0/session/util/WebUtil.java#L61-L73 |
pravega/pravega | shared/cluster/src/main/java/io/pravega/common/cluster/ClusterException.java | ClusterException.create | public static ClusterException create(Type type, String message) {
switch (type) {
case METASTORE:
return new MetaStoreException(message);
default:
throw new IllegalArgumentException("Invalid exception type");
}
} | java | public static ClusterException create(Type type, String message) {
switch (type) {
case METASTORE:
return new MetaStoreException(message);
default:
throw new IllegalArgumentException("Invalid exception type");
}
} | [
"public",
"static",
"ClusterException",
"create",
"(",
"Type",
"type",
",",
"String",
"message",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"METASTORE",
":",
"return",
"new",
"MetaStoreException",
"(",
"message",
")",
";",
"default",
":",
"throw",
... | Factory method to construct Store exceptions.
@param type Type of Exception.
@param message Exception message
@return Instance of ClusterException. | [
"Factory",
"method",
"to",
"construct",
"Store",
"exceptions",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/shared/cluster/src/main/java/io/pravega/common/cluster/ClusterException.java#L32-L39 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/clientsupport/CATMainConsumer.java | CATMainConsumer.unsetAsynchConsumerCallback | public void unsetAsynchConsumerCallback(int requestNumber, boolean stoppable) //SIB0115d.comms
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unsetAsynchConsumerCallback", "requestNumber="+requestNumber+",stoppable="+stoppable);
checkNotBrowserSession(); // F171893
if (subConsumer != null)
{
subConsumer.unsetAsynchConsumerCallback(requestNumber, stoppable); //SIB0115d.comms
}
subConsumer = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "unsetAsynchConsumerCallback");
} | java | public void unsetAsynchConsumerCallback(int requestNumber, boolean stoppable) //SIB0115d.comms
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "unsetAsynchConsumerCallback", "requestNumber="+requestNumber+",stoppable="+stoppable);
checkNotBrowserSession(); // F171893
if (subConsumer != null)
{
subConsumer.unsetAsynchConsumerCallback(requestNumber, stoppable); //SIB0115d.comms
}
subConsumer = null;
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "unsetAsynchConsumerCallback");
} | [
"public",
"void",
"unsetAsynchConsumerCallback",
"(",
"int",
"requestNumber",
",",
"boolean",
"stoppable",
")",
"//SIB0115d.comms",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",
"SibTr",
... | This method will unset the asynch consumer callback. This means that the
client has requested that the session should be converted from asynchronous to
synchronous and so the sub consumer must be changed
@param requestNumber | [
"This",
"method",
"will",
"unset",
"the",
"asynch",
"consumer",
"callback",
".",
"This",
"means",
"that",
"the",
"client",
"has",
"requested",
"that",
"the",
"session",
"should",
"be",
"converted",
"from",
"asynchronous",
"to",
"synchronous",
"and",
"so",
"the... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.server/src/com/ibm/ws/sib/comms/server/clientsupport/CATMainConsumer.java#L594-L608 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java | JobsImpl.listPreparationAndReleaseTaskStatusAsync | public ServiceFuture<List<JobPreparationAndReleaseTaskExecutionInformation>> listPreparationAndReleaseTaskStatusAsync(final String jobId, final ListOperationCallback<JobPreparationAndReleaseTaskExecutionInformation> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listPreparationAndReleaseTaskStatusSinglePageAsync(jobId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(String nextPageLink) {
return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | java | public ServiceFuture<List<JobPreparationAndReleaseTaskExecutionInformation>> listPreparationAndReleaseTaskStatusAsync(final String jobId, final ListOperationCallback<JobPreparationAndReleaseTaskExecutionInformation> serviceCallback) {
return AzureServiceFuture.fromHeaderPageResponse(
listPreparationAndReleaseTaskStatusSinglePageAsync(jobId),
new Func1<String, Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Page<JobPreparationAndReleaseTaskExecutionInformation>, JobListPreparationAndReleaseTaskStatusHeaders>> call(String nextPageLink) {
return listPreparationAndReleaseTaskStatusNextSinglePageAsync(nextPageLink, null);
}
},
serviceCallback);
} | [
"public",
"ServiceFuture",
"<",
"List",
"<",
"JobPreparationAndReleaseTaskExecutionInformation",
">",
">",
"listPreparationAndReleaseTaskStatusAsync",
"(",
"final",
"String",
"jobId",
",",
"final",
"ListOperationCallback",
"<",
"JobPreparationAndReleaseTaskExecutionInformation",
... | Lists the execution status of the Job Preparation and Job Release task for the specified job across the compute nodes where the job has run.
This API returns the Job Preparation and Job Release task status on all compute nodes that have run the Job Preparation or Job Release task. This includes nodes which have since been removed from the pool. If this API is invoked on a job which has no Job Preparation or Job Release task, the Batch service returns HTTP status code 409 (Conflict) with an error code of JobPreparationTaskNotSpecified.
@param jobId The ID of the job.
@param serviceCallback the async ServiceCallback to handle successful and failed responses.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceFuture} object | [
"Lists",
"the",
"execution",
"status",
"of",
"the",
"Job",
"Preparation",
"and",
"Job",
"Release",
"task",
"for",
"the",
"specified",
"job",
"across",
"the",
"compute",
"nodes",
"where",
"the",
"job",
"has",
"run",
".",
"This",
"API",
"returns",
"the",
"Jo... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/JobsImpl.java#L2833-L2843 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/SharedFlowController.java | SharedFlowController.getPreviousPageInfoLegacy | public PreviousPageInfo getPreviousPageInfoLegacy( PageFlowController curJpf, HttpServletRequest request )
{
assert curJpf != null;
return curJpf.getCurrentPageInfo();
} | java | public PreviousPageInfo getPreviousPageInfoLegacy( PageFlowController curJpf, HttpServletRequest request )
{
assert curJpf != null;
return curJpf.getCurrentPageInfo();
} | [
"public",
"PreviousPageInfo",
"getPreviousPageInfoLegacy",
"(",
"PageFlowController",
"curJpf",
",",
"HttpServletRequest",
"request",
")",
"{",
"assert",
"curJpf",
"!=",
"null",
";",
"return",
"curJpf",
".",
"getCurrentPageInfo",
"(",
")",
";",
"}"
] | Get a legacy PreviousPageInfo.
@deprecated This method will be removed without replacement in a future release. | [
"Get",
"a",
"legacy",
"PreviousPageInfo",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/SharedFlowController.java#L172-L176 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java | HashtableOnDisk.iterateKeys | public int iterateKeys(HashtableAction action, int index, int length)
throws IOException,
EOFException,
FileManagerException,
ClassNotFoundException,
HashtableOnDiskException {
return walkHash(action, RETRIEVE_KEY, index, length);
} | java | public int iterateKeys(HashtableAction action, int index, int length)
throws IOException,
EOFException,
FileManagerException,
ClassNotFoundException,
HashtableOnDiskException {
return walkHash(action, RETRIEVE_KEY, index, length);
} | [
"public",
"int",
"iterateKeys",
"(",
"HashtableAction",
"action",
",",
"int",
"index",
",",
"int",
"length",
")",
"throws",
"IOException",
",",
"EOFException",
",",
"FileManagerException",
",",
"ClassNotFoundException",
",",
"HashtableOnDiskException",
"{",
"return",
... | ************************************************************************
This invokes the action's "execute" method once for every
object passing only the key to the method, to avoid the
overhead of reading the object if it is not necessary.
The iteration is synchronized with concurrent get and put operations
to avoid locking the HTOD for long periods of time. Some objects which
are added during iteration may not be seen by the iteration.
@param action The object to be "invoked" for each object.
*********************************************************************** | [
"************************************************************************",
"This",
"invokes",
"the",
"action",
"s",
"execute",
"method",
"once",
"for",
"every",
"object",
"passing",
"only",
"the",
"key",
"to",
"the",
"method",
"to",
"avoid",
"the",
"overhead",
"of",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache/src/com/ibm/ws/cache/persistent/htod/HashtableOnDisk.java#L1340-L1347 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java | GraphEdgeIdFinder.findClosestEdgeToPoint | public void findClosestEdgeToPoint(GHIntHashSet edgeIds, GHPoint point, EdgeFilter filter) {
findClosestEdge(edgeIds, point.getLat(), point.getLon(), filter);
} | java | public void findClosestEdgeToPoint(GHIntHashSet edgeIds, GHPoint point, EdgeFilter filter) {
findClosestEdge(edgeIds, point.getLat(), point.getLon(), filter);
} | [
"public",
"void",
"findClosestEdgeToPoint",
"(",
"GHIntHashSet",
"edgeIds",
",",
"GHPoint",
"point",
",",
"EdgeFilter",
"filter",
")",
"{",
"findClosestEdge",
"(",
"edgeIds",
",",
"point",
".",
"getLat",
"(",
")",
",",
"point",
".",
"getLon",
"(",
")",
",",
... | This method fills the edgeIds hash with edgeIds found close (exact match) to the specified point | [
"This",
"method",
"fills",
"the",
"edgeIds",
"hash",
"with",
"edgeIds",
"found",
"close",
"(",
"exact",
"match",
")",
"to",
"the",
"specified",
"point"
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/GraphEdgeIdFinder.java#L55-L57 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/RecurrenceUtility.java | RecurrenceUtility.getDuration | public static Duration getDuration(ProjectProperties properties, Integer durationValue, Integer unitsValue)
{
Duration result;
if (durationValue == null)
{
result = null;
}
else
{
result = Duration.getInstance(durationValue.intValue(), TimeUnit.MINUTES);
TimeUnit units = getDurationUnits(unitsValue);
if (result.getUnits() != units)
{
result = result.convertUnits(units, properties);
}
}
return (result);
} | java | public static Duration getDuration(ProjectProperties properties, Integer durationValue, Integer unitsValue)
{
Duration result;
if (durationValue == null)
{
result = null;
}
else
{
result = Duration.getInstance(durationValue.intValue(), TimeUnit.MINUTES);
TimeUnit units = getDurationUnits(unitsValue);
if (result.getUnits() != units)
{
result = result.convertUnits(units, properties);
}
}
return (result);
} | [
"public",
"static",
"Duration",
"getDuration",
"(",
"ProjectProperties",
"properties",
",",
"Integer",
"durationValue",
",",
"Integer",
"unitsValue",
")",
"{",
"Duration",
"result",
";",
"if",
"(",
"durationValue",
"==",
"null",
")",
"{",
"result",
"=",
"null",
... | Convert the integer representation of a duration value and duration units
into an MPXJ Duration instance.
@param properties project properties, used for duration units conversion
@param durationValue integer duration value
@param unitsValue integer units value
@return Duration instance | [
"Convert",
"the",
"integer",
"representation",
"of",
"a",
"duration",
"value",
"and",
"duration",
"units",
"into",
"an",
"MPXJ",
"Duration",
"instance",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/RecurrenceUtility.java#L63-L80 |
apache/incubator-gobblin | gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java | JsonSchema.getTypeOfArrayItems | public Type getTypeOfArrayItems()
throws DataConversionException {
JsonSchema arrayValues = getItemsWithinDataType();
if (arrayValues == null) {
throw new DataConversionException("Array types only allow values as primitive, null or JsonObject");
}
return arrayValues.getType();
} | java | public Type getTypeOfArrayItems()
throws DataConversionException {
JsonSchema arrayValues = getItemsWithinDataType();
if (arrayValues == null) {
throw new DataConversionException("Array types only allow values as primitive, null or JsonObject");
}
return arrayValues.getType();
} | [
"public",
"Type",
"getTypeOfArrayItems",
"(",
")",
"throws",
"DataConversionException",
"{",
"JsonSchema",
"arrayValues",
"=",
"getItemsWithinDataType",
"(",
")",
";",
"if",
"(",
"arrayValues",
"==",
"null",
")",
"{",
"throw",
"new",
"DataConversionException",
"(",
... | Fetches the nested or primitive array items type from schema.
@return
@throws DataConversionException | [
"Fetches",
"the",
"nested",
"or",
"primitive",
"array",
"items",
"type",
"from",
"schema",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/converter/json/JsonSchema.java#L232-L239 |
strator-dev/greenpepper | greenpepper-maven-plugin/src/main/java/com/greenpepper/maven/plugin/FixtureCompilerMojo.java | FixtureCompilerMojo.getSourceInclusionScanner | @SuppressWarnings("unchecked")
protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis )
{
SourceInclusionScanner scanner;
if ( testIncludes.isEmpty() && testExcludes.isEmpty() )
{
scanner = new StaleSourceScanner( staleMillis );
}
else
{
if ( testIncludes.isEmpty() )
{
testIncludes.add( "**/*.java" );
}
scanner = new StaleSourceScanner( staleMillis, testIncludes, testExcludes );
}
return scanner;
} | java | @SuppressWarnings("unchecked")
protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis )
{
SourceInclusionScanner scanner;
if ( testIncludes.isEmpty() && testExcludes.isEmpty() )
{
scanner = new StaleSourceScanner( staleMillis );
}
else
{
if ( testIncludes.isEmpty() )
{
testIncludes.add( "**/*.java" );
}
scanner = new StaleSourceScanner( staleMillis, testIncludes, testExcludes );
}
return scanner;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"SourceInclusionScanner",
"getSourceInclusionScanner",
"(",
"int",
"staleMillis",
")",
"{",
"SourceInclusionScanner",
"scanner",
";",
"if",
"(",
"testIncludes",
".",
"isEmpty",
"(",
")",
"&&",
"testExclu... | <p>getSourceInclusionScanner.</p>
@param staleMillis a int.
@return a {@link org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner} object. | [
"<p",
">",
"getSourceInclusionScanner",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-maven-plugin/src/main/java/com/greenpepper/maven/plugin/FixtureCompilerMojo.java#L144-L163 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/search/queries/DateRangeQuery.java | DateRangeQuery.start | public DateRangeQuery start(Date start, boolean inclusive) {
this.start = SearchUtils.toFtsUtcString(start);
this.inclusiveStart = inclusive;
return this;
} | java | public DateRangeQuery start(Date start, boolean inclusive) {
this.start = SearchUtils.toFtsUtcString(start);
this.inclusiveStart = inclusive;
return this;
} | [
"public",
"DateRangeQuery",
"start",
"(",
"Date",
"start",
",",
"boolean",
"inclusive",
")",
"{",
"this",
".",
"start",
"=",
"SearchUtils",
".",
"toFtsUtcString",
"(",
"start",
")",
";",
"this",
".",
"inclusiveStart",
"=",
"inclusive",
";",
"return",
"this",... | Sets the lower boundary of the range, inclusive or not depending on the second parameter.
Works with a {@link Date} object, which is converted to RFC 3339 format using
{@link SearchUtils#toFtsUtcString(Date)}, so you shouldn't use a non-default {@link #dateTimeParser(String)}
after that. | [
"Sets",
"the",
"lower",
"boundary",
"of",
"the",
"range",
"inclusive",
"or",
"not",
"depending",
"on",
"the",
"second",
"parameter",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/search/queries/DateRangeQuery.java#L96-L100 |
UrielCh/ovh-java-sdk | ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java | ApiOvhVrack.serviceName_dedicatedServer_dedicatedServer_GET | public OvhDedicatedServer serviceName_dedicatedServer_dedicatedServer_GET(String serviceName, String dedicatedServer) throws IOException {
String qPath = "/vrack/{serviceName}/dedicatedServer/{dedicatedServer}";
StringBuilder sb = path(qPath, serviceName, dedicatedServer);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhDedicatedServer.class);
} | java | public OvhDedicatedServer serviceName_dedicatedServer_dedicatedServer_GET(String serviceName, String dedicatedServer) throws IOException {
String qPath = "/vrack/{serviceName}/dedicatedServer/{dedicatedServer}";
StringBuilder sb = path(qPath, serviceName, dedicatedServer);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhDedicatedServer.class);
} | [
"public",
"OvhDedicatedServer",
"serviceName_dedicatedServer_dedicatedServer_GET",
"(",
"String",
"serviceName",
",",
"String",
"dedicatedServer",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/vrack/{serviceName}/dedicatedServer/{dedicatedServer}\"",
";",
"String... | Get this object properties
REST: GET /vrack/{serviceName}/dedicatedServer/{dedicatedServer}
@param serviceName [required] The internal name of your vrack
@param dedicatedServer [required] Dedicated Server | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-vrack/src/main/java/net/minidev/ovh/api/ApiOvhVrack.java#L292-L297 |
Netflix/servo | servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java | Monitors.newThreadPoolMonitor | public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) {
return newObjectMonitor(id, new MonitoredThreadPool(pool));
} | java | public static CompositeMonitor<?> newThreadPoolMonitor(String id, ThreadPoolExecutor pool) {
return newObjectMonitor(id, new MonitoredThreadPool(pool));
} | [
"public",
"static",
"CompositeMonitor",
"<",
"?",
">",
"newThreadPoolMonitor",
"(",
"String",
"id",
",",
"ThreadPoolExecutor",
"pool",
")",
"{",
"return",
"newObjectMonitor",
"(",
"id",
",",
"new",
"MonitoredThreadPool",
"(",
"pool",
")",
")",
";",
"}"
] | Creates a new monitor for a thread pool with standard metrics for the pool size, queue size,
task counts, etc.
@param id id to differentiate metrics for this pool from others.
@param pool thread pool instance to monitor.
@return composite monitor based on stats provided for the pool | [
"Creates",
"a",
"new",
"monitor",
"for",
"a",
"thread",
"pool",
"with",
"standard",
"metrics",
"for",
"the",
"pool",
"size",
"queue",
"size",
"task",
"counts",
"etc",
"."
] | train | https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/Monitors.java#L168-L170 |
VoltDB/voltdb | src/frontend/org/voltdb/utils/CatalogUtil.java | CatalogUtil.isSnapshotablePersistentTableView | public static boolean isSnapshotablePersistentTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false;
}
if (CatalogUtil.isTableExportOnly(db, materializer)) {
// The view source table should not be a streamed table.
return false;
}
if (! table.getIsreplicated() && table.getPartitioncolumn() == null) {
// If the view table is implicitly partitioned (maybe was not in snapshot),
// its maintenance is not turned off during the snapshot restore process.
// Let it take care of its own data by itself.
// Do not attempt to restore data for it.
return false;
}
return true;
} | java | public static boolean isSnapshotablePersistentTableView(Database db, Table table) {
Table materializer = table.getMaterializer();
if (materializer == null) {
// Return false if it is not a materialized view.
return false;
}
if (CatalogUtil.isTableExportOnly(db, materializer)) {
// The view source table should not be a streamed table.
return false;
}
if (! table.getIsreplicated() && table.getPartitioncolumn() == null) {
// If the view table is implicitly partitioned (maybe was not in snapshot),
// its maintenance is not turned off during the snapshot restore process.
// Let it take care of its own data by itself.
// Do not attempt to restore data for it.
return false;
}
return true;
} | [
"public",
"static",
"boolean",
"isSnapshotablePersistentTableView",
"(",
"Database",
"db",
",",
"Table",
"table",
")",
"{",
"Table",
"materializer",
"=",
"table",
".",
"getMaterializer",
"(",
")",
";",
"if",
"(",
"materializer",
"==",
"null",
")",
"{",
"// Ret... | Test if a table is a persistent table view and should be included in the snapshot.
@param db The database catalog
@param table The table to test.</br>
@return If the table is a persistent table view that should be snapshotted. | [
"Test",
"if",
"a",
"table",
"is",
"a",
"persistent",
"table",
"view",
"and",
"should",
"be",
"included",
"in",
"the",
"snapshot",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/utils/CatalogUtil.java#L418-L436 |
ugli/jocote | src/main/java/se/ugli/jocote/lpr/SocketFactory.java | SocketFactory.create | static Socket create(String hostName, int port, boolean useOutOfBoundsPorts) throws IOException {
if (useOutOfBoundsPorts) {
return IntStream.rangeClosed(721, 731).mapToObj(localPort -> {
try {
return Optional.of(new Socket(hostName, port, InetAddress.getLocalHost(), localPort));
} catch (IOException e) {
return Optional.<Socket>empty();
}
}).filter(Optional::isPresent).map(Optional::get).findFirst().orElseThrow(() -> new BindException("Can't bind to local port/address"));
}
return new Socket(hostName, port);
} | java | static Socket create(String hostName, int port, boolean useOutOfBoundsPorts) throws IOException {
if (useOutOfBoundsPorts) {
return IntStream.rangeClosed(721, 731).mapToObj(localPort -> {
try {
return Optional.of(new Socket(hostName, port, InetAddress.getLocalHost(), localPort));
} catch (IOException e) {
return Optional.<Socket>empty();
}
}).filter(Optional::isPresent).map(Optional::get).findFirst().orElseThrow(() -> new BindException("Can't bind to local port/address"));
}
return new Socket(hostName, port);
} | [
"static",
"Socket",
"create",
"(",
"String",
"hostName",
",",
"int",
"port",
",",
"boolean",
"useOutOfBoundsPorts",
")",
"throws",
"IOException",
"{",
"if",
"(",
"useOutOfBoundsPorts",
")",
"{",
"return",
"IntStream",
".",
"rangeClosed",
"(",
"721",
",",
"731"... | /*
The RFC for lpr specifies the use of local ports numbered 721 - 731, however
TCP/IP also requires that any port that is used will not be released for 3 minutes
which means that it get stuck on the 12th job if prints are sent quickly.
To resolve this issue you can use out of bounds ports which most print servers
will support | [
"/",
"*",
"The",
"RFC",
"for",
"lpr",
"specifies",
"the",
"use",
"of",
"local",
"ports",
"numbered",
"721",
"-",
"731",
"however",
"TCP",
"/",
"IP",
"also",
"requires",
"that",
"any",
"port",
"that",
"is",
"used",
"will",
"not",
"be",
"released",
"for"... | train | https://github.com/ugli/jocote/blob/28c34eb5aadbca6597bf006bb92d4fc340c71b41/src/main/java/se/ugli/jocote/lpr/SocketFactory.java#L22-L33 |
quattor/pan | panc/src/main/java/org/quattor/pan/statement/IncludeStatement.java | IncludeStatement.executeWithNamedTemplate | protected void executeWithNamedTemplate(Context context, String name)
throws EvaluationException {
assert (context != null);
assert (name != null);
Template template = null;
boolean runStatic = false;
try {
template = context.localLoad(name);
if (template == null) {
template = context.globalLoad(name);
runStatic = true;
}
} catch (EvaluationException ee) {
throw ee.addExceptionInfo(getSourceRange(), context);
}
// Check that the template was actually loaded.
if (template == null) {
throw new EvaluationException("failed to load template: " + name,
getSourceRange());
}
TemplateType includeeType = context.getCurrentTemplate().type;
TemplateType includedType = template.type;
// Check that the template types are correct for the inclusion.
if (!Template.checkValidInclude(includeeType, includedType)) {
throw new EvaluationException(includeeType
+ " template cannot include " + includedType + " template",
getSourceRange());
}
// Push the template, execute it, then pop it from the stack.
// Template loops will be caught by the call depth check when pushing
// the template.
context.pushTemplate(template, getSourceRange(), Level.INFO,
includedType.toString());
template.execute(context, runStatic);
context.popTemplate(Level.INFO, includedType.toString());
} | java | protected void executeWithNamedTemplate(Context context, String name)
throws EvaluationException {
assert (context != null);
assert (name != null);
Template template = null;
boolean runStatic = false;
try {
template = context.localLoad(name);
if (template == null) {
template = context.globalLoad(name);
runStatic = true;
}
} catch (EvaluationException ee) {
throw ee.addExceptionInfo(getSourceRange(), context);
}
// Check that the template was actually loaded.
if (template == null) {
throw new EvaluationException("failed to load template: " + name,
getSourceRange());
}
TemplateType includeeType = context.getCurrentTemplate().type;
TemplateType includedType = template.type;
// Check that the template types are correct for the inclusion.
if (!Template.checkValidInclude(includeeType, includedType)) {
throw new EvaluationException(includeeType
+ " template cannot include " + includedType + " template",
getSourceRange());
}
// Push the template, execute it, then pop it from the stack.
// Template loops will be caught by the call depth check when pushing
// the template.
context.pushTemplate(template, getSourceRange(), Level.INFO,
includedType.toString());
template.execute(context, runStatic);
context.popTemplate(Level.INFO, includedType.toString());
} | [
"protected",
"void",
"executeWithNamedTemplate",
"(",
"Context",
"context",
",",
"String",
"name",
")",
"throws",
"EvaluationException",
"{",
"assert",
"(",
"context",
"!=",
"null",
")",
";",
"assert",
"(",
"name",
"!=",
"null",
")",
";",
"Template",
"template... | This is a utility method which performs an include from a fixed template
name. The validity of the name should be checked by the subclass; this
avoids unnecessary regular expression matching.
@param context
evaluation context to use
@param name
fixed template name
@throws EvaluationException | [
"This",
"is",
"a",
"utility",
"method",
"which",
"performs",
"an",
"include",
"from",
"a",
"fixed",
"template",
"name",
".",
"The",
"validity",
"of",
"the",
"name",
"should",
"be",
"checked",
"by",
"the",
"subclass",
";",
"this",
"avoids",
"unnecessary",
"... | train | https://github.com/quattor/pan/blob/009934a603dd0c08d3fa4bb7d9389c380a916f54/panc/src/main/java/org/quattor/pan/statement/IncludeStatement.java#L122-L165 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.getAt | @SuppressWarnings("unchecked")
public static List<Long> getAt(long[] array, ObjectRange range) {
return primitiveArrayGet(array, range);
} | java | @SuppressWarnings("unchecked")
public static List<Long> getAt(long[] array, ObjectRange range) {
return primitiveArrayGet(array, range);
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"List",
"<",
"Long",
">",
"getAt",
"(",
"long",
"[",
"]",
"array",
",",
"ObjectRange",
"range",
")",
"{",
"return",
"primitiveArrayGet",
"(",
"array",
",",
"range",
")",
";",
"}"
] | Support the subscript operator with an ObjectRange for a long array
@param array a long array
@param range an ObjectRange indicating the indices for the items to retrieve
@return list of the retrieved longs
@since 1.0 | [
"Support",
"the",
"subscript",
"operator",
"with",
"an",
"ObjectRange",
"for",
"a",
"long",
"array"
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L13886-L13889 |
jhg023/SimpleNet | src/main/java/simplenet/packet/Packet.java | Packet.putDouble | public Packet putDouble(double d, ByteOrder order) {
return putLong(Double.doubleToRawLongBits(d), order);
} | java | public Packet putDouble(double d, ByteOrder order) {
return putLong(Double.doubleToRawLongBits(d), order);
} | [
"public",
"Packet",
"putDouble",
"(",
"double",
"d",
",",
"ByteOrder",
"order",
")",
"{",
"return",
"putLong",
"(",
"Double",
".",
"doubleToRawLongBits",
"(",
"d",
")",
",",
"order",
")",
";",
"}"
] | Writes a single {@code double} with the specified {@link ByteOrder} to this {@link Packet}'s payload.
@param d A {@code double}.
@param order The internal byte order of the {@code double}.
@return The {@link Packet} to allow for chained writes.
@see #putLong(long, ByteOrder) | [
"Writes",
"a",
"single",
"{",
"@code",
"double",
"}",
"with",
"the",
"specified",
"{",
"@link",
"ByteOrder",
"}",
"to",
"this",
"{",
"@link",
"Packet",
"}",
"s",
"payload",
"."
] | train | https://github.com/jhg023/SimpleNet/blob/a5b55cbfe1768c6a28874f12adac3c748f2b509a/src/main/java/simplenet/packet/Packet.java#L185-L187 |
lessthanoptimal/ejml | examples/src/org/ejml/example/PrincipalComponentAnalysis.java | PrincipalComponentAnalysis.response | public double response( double[] sample ) {
if( sample.length != A.numCols )
throw new IllegalArgumentException("Expected input vector to be in sample space");
DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);
DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);
CommonOps_DDRM.mult(V_t,s,dots);
return NormOps_DDRM.normF(dots);
} | java | public double response( double[] sample ) {
if( sample.length != A.numCols )
throw new IllegalArgumentException("Expected input vector to be in sample space");
DMatrixRMaj dots = new DMatrixRMaj(numComponents,1);
DMatrixRMaj s = DMatrixRMaj.wrap(A.numCols,1,sample);
CommonOps_DDRM.mult(V_t,s,dots);
return NormOps_DDRM.normF(dots);
} | [
"public",
"double",
"response",
"(",
"double",
"[",
"]",
"sample",
")",
"{",
"if",
"(",
"sample",
".",
"length",
"!=",
"A",
".",
"numCols",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Expected input vector to be in sample space\"",
")",
";",
"DMatri... | Computes the dot product of each basis vector against the sample. Can be used as a measure
for membership in the training sample set. High values correspond to a better fit.
@param sample Sample of original data.
@return Higher value indicates it is more likely to be a member of input dataset. | [
"Computes",
"the",
"dot",
"product",
"of",
"each",
"basis",
"vector",
"against",
"the",
"sample",
".",
"Can",
"be",
"used",
"as",
"a",
"measure",
"for",
"membership",
"in",
"the",
"training",
"sample",
"set",
".",
"High",
"values",
"correspond",
"to",
"a",... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/examples/src/org/ejml/example/PrincipalComponentAnalysis.java#L247-L257 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java | TransformerIdentityImpl.setParameter | public void setParameter(String name, Object value)
{
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
} | java | public void setParameter(String name, Object value)
{
if (value == null) {
throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_INVALID_SET_PARAM_VALUE, new Object[]{name}));
}
if (null == m_params)
{
m_params = new Hashtable();
}
m_params.put(name, value);
} | [
"public",
"void",
"setParameter",
"(",
"String",
"name",
",",
"Object",
"value",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"XSLMessages",
".",
"createMessage",
"(",
"XSLTErrorResources",
".",
"ER_INV... | Add a parameter for the transformation.
<p>Pass a qualified name as a two-part string, the namespace URI
enclosed in curly braces ({}), followed by the local name. If the
name has a null URL, the String only contain the local name. An
application can safely check for a non-null URI by testing to see if the first
character of the name is a '{' character.</p>
<p>For example, if a URI and local name were obtained from an element
defined with <xyz:foo xmlns:xyz="http://xyz.foo.com/yada/baz.html"/>,
then the qualified name would be "{http://xyz.foo.com/yada/baz.html}foo". Note that
no prefix is used.</p>
@param name The name of the parameter, which may begin with a namespace URI
in curly braces ({}).
@param value The value object. This can be any valid Java object. It is
up to the processor to provide the proper object coersion or to simply
pass the object on for use in an extension. | [
"Add",
"a",
"parameter",
"for",
"the",
"transformation",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerIdentityImpl.java#L546-L558 |
elki-project/elki | elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/AbstractObjDynamicHistogram.java | AbstractObjDynamicHistogram.aggregateSpecial | protected void aggregateSpecial(T value, int bin) {
final T exist = getSpecial(bin);
// Note: do not inline above accessor, as getSpecial will initialize the
// special variable used below!
special[bin] = aggregate(exist, value);
} | java | protected void aggregateSpecial(T value, int bin) {
final T exist = getSpecial(bin);
// Note: do not inline above accessor, as getSpecial will initialize the
// special variable used below!
special[bin] = aggregate(exist, value);
} | [
"protected",
"void",
"aggregateSpecial",
"(",
"T",
"value",
",",
"int",
"bin",
")",
"{",
"final",
"T",
"exist",
"=",
"getSpecial",
"(",
"bin",
")",
";",
"// Note: do not inline above accessor, as getSpecial will initialize the",
"// special variable used below!",
"special... | Aggregate for a special value.
@param value Parameter value
@param bin Special bin index. | [
"Aggregate",
"for",
"a",
"special",
"value",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/histogram/AbstractObjDynamicHistogram.java#L161-L166 |
dropbox/dropbox-sdk-java | src/main/java/com/dropbox/core/v1/DbxClientV1.java | DbxClientV1.getMetadataWithChildrenC | public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, final Collector<DbxEntry, ? extends C> collector)
throws DbxException
{
return getMetadataWithChildrenC(path, false, collector);
} | java | public <C> DbxEntry./*@Nullable*/WithChildrenC<C> getMetadataWithChildrenC(String path, final Collector<DbxEntry, ? extends C> collector)
throws DbxException
{
return getMetadataWithChildrenC(path, false, collector);
} | [
"public",
"<",
"C",
">",
"DbxEntry",
".",
"/*@Nullable*/",
"WithChildrenC",
"<",
"C",
">",
"getMetadataWithChildrenC",
"(",
"String",
"path",
",",
"final",
"Collector",
"<",
"DbxEntry",
",",
"?",
"extends",
"C",
">",
"collector",
")",
"throws",
"DbxException",... | Same as {@link #getMetadataWithChildrenC(String, boolean, Collector)} with {@code includeMediaInfo} set
to {@code false}. | [
"Same",
"as",
"{"
] | train | https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L214-L218 |
zxing/zxing | core/src/main/java/com/google/zxing/aztec/detector/Detector.java | Detector.extractParameters | private void extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException {
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3])) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides = {
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
} | java | private void extractParameters(ResultPoint[] bullsEyeCorners) throws NotFoundException {
if (!isValid(bullsEyeCorners[0]) || !isValid(bullsEyeCorners[1]) ||
!isValid(bullsEyeCorners[2]) || !isValid(bullsEyeCorners[3])) {
throw NotFoundException.getNotFoundInstance();
}
int length = 2 * nbCenterLayers;
// Get the bits around the bull's eye
int[] sides = {
sampleLine(bullsEyeCorners[0], bullsEyeCorners[1], length), // Right side
sampleLine(bullsEyeCorners[1], bullsEyeCorners[2], length), // Bottom
sampleLine(bullsEyeCorners[2], bullsEyeCorners[3], length), // Left side
sampleLine(bullsEyeCorners[3], bullsEyeCorners[0], length) // Top
};
// bullsEyeCorners[shift] is the corner of the bulls'eye that has three
// orientation marks.
// sides[shift] is the row/column that goes from the corner with three
// orientation marks to the corner with two.
shift = getRotation(sides, length);
// Flatten the parameter bits into a single 28- or 40-bit long
long parameterData = 0;
for (int i = 0; i < 4; i++) {
int side = sides[(shift + i) % 4];
if (compact) {
// Each side of the form ..XXXXXXX. where Xs are parameter data
parameterData <<= 7;
parameterData += (side >> 1) & 0x7F;
} else {
// Each side of the form ..XXXXX.XXXXX. where Xs are parameter data
parameterData <<= 10;
parameterData += ((side >> 2) & (0x1f << 5)) + ((side >> 1) & 0x1F);
}
}
// Corrects parameter data using RS. Returns just the data portion
// without the error correction.
int correctedData = getCorrectedParameterData(parameterData, compact);
if (compact) {
// 8 bits: 2 bits layers and 6 bits data blocks
nbLayers = (correctedData >> 6) + 1;
nbDataBlocks = (correctedData & 0x3F) + 1;
} else {
// 16 bits: 5 bits layers and 11 bits data blocks
nbLayers = (correctedData >> 11) + 1;
nbDataBlocks = (correctedData & 0x7FF) + 1;
}
} | [
"private",
"void",
"extractParameters",
"(",
"ResultPoint",
"[",
"]",
"bullsEyeCorners",
")",
"throws",
"NotFoundException",
"{",
"if",
"(",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"0",
"]",
")",
"||",
"!",
"isValid",
"(",
"bullsEyeCorners",
"[",
"1",
"... | Extracts the number of data layers and data blocks from the layer around the bull's eye.
@param bullsEyeCorners the array of bull's eye corners
@throws NotFoundException in case of too many errors or invalid parameters | [
"Extracts",
"the",
"number",
"of",
"data",
"layers",
"and",
"data",
"blocks",
"from",
"the",
"layer",
"around",
"the",
"bull",
"s",
"eye",
"."
] | train | https://github.com/zxing/zxing/blob/653ac2a3beb11481eff82e7d5f2bab8a745f7fac/core/src/main/java/com/google/zxing/aztec/detector/Detector.java#L106-L154 |
citrusframework/citrus | modules/citrus-jms/src/main/java/com/consol/citrus/jms/endpoint/JmsSyncConsumer.java | JmsSyncConsumer.saveReplyDestination | public void saveReplyDestination(JmsMessage jmsMessage, TestContext context) {
if (jmsMessage.getReplyTo() != null) {
String correlationKeyName = endpointConfiguration.getCorrelator().getCorrelationKeyName(getName());
String correlationKey = endpointConfiguration.getCorrelator().getCorrelationKey(jmsMessage);
correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);
correlationManager.store(correlationKey, jmsMessage.getReplyTo());
} else {
log.warn("Unable to retrieve reply to destination for message \n" +
jmsMessage + "\n - no reply to destination found in message headers!");
}
} | java | public void saveReplyDestination(JmsMessage jmsMessage, TestContext context) {
if (jmsMessage.getReplyTo() != null) {
String correlationKeyName = endpointConfiguration.getCorrelator().getCorrelationKeyName(getName());
String correlationKey = endpointConfiguration.getCorrelator().getCorrelationKey(jmsMessage);
correlationManager.saveCorrelationKey(correlationKeyName, correlationKey, context);
correlationManager.store(correlationKey, jmsMessage.getReplyTo());
} else {
log.warn("Unable to retrieve reply to destination for message \n" +
jmsMessage + "\n - no reply to destination found in message headers!");
}
} | [
"public",
"void",
"saveReplyDestination",
"(",
"JmsMessage",
"jmsMessage",
",",
"TestContext",
"context",
")",
"{",
"if",
"(",
"jmsMessage",
".",
"getReplyTo",
"(",
")",
"!=",
"null",
")",
"{",
"String",
"correlationKeyName",
"=",
"endpointConfiguration",
".",
"... | Store the reply destination either straight forward or with a given
message correlation key.
@param jmsMessage
@param context | [
"Store",
"the",
"reply",
"destination",
"either",
"straight",
"forward",
"or",
"with",
"a",
"given",
"message",
"correlation",
"key",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-jms/src/main/java/com/consol/citrus/jms/endpoint/JmsSyncConsumer.java#L105-L115 |
AzureAD/azure-activedirectory-library-for-java | src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/BasicFilter.java | BasicFilter.validateState | private StateData validateState(HttpSession session, String state) throws Exception {
if (StringUtils.isNotEmpty(state)) {
StateData stateDataInSession = removeStateFromSession(session, state);
if (stateDataInSession != null) {
return stateDataInSession;
}
}
throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
} | java | private StateData validateState(HttpSession session, String state) throws Exception {
if (StringUtils.isNotEmpty(state)) {
StateData stateDataInSession = removeStateFromSession(session, state);
if (stateDataInSession != null) {
return stateDataInSession;
}
}
throw new Exception(FAILED_TO_VALIDATE_MESSAGE + "could not validate state");
} | [
"private",
"StateData",
"validateState",
"(",
"HttpSession",
"session",
",",
"String",
"state",
")",
"throws",
"Exception",
"{",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"state",
")",
")",
"{",
"StateData",
"stateDataInSession",
"=",
"removeStateFromSessi... | make sure that state is stored in the session,
delete it from session - should be used only once
@param session
@param state
@throws Exception | [
"make",
"sure",
"that",
"state",
"is",
"stored",
"in",
"the",
"session",
"delete",
"it",
"from",
"session",
"-",
"should",
"be",
"used",
"only",
"once"
] | train | https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/BasicFilter.java#L182-L190 |
oboehm/jfachwert | src/main/java/de/jfachwert/net/Domainname.java | Domainname.getLevelDomain | public Domainname getLevelDomain(int level) {
String[] parts = this.getCode().split("\\.");
int firstPart = parts.length - level;
if ((firstPart < 0) || (level < 1)) {
throw new LocalizedIllegalArgumentException(level, "level", Range.between(1, parts.length));
}
StringBuilder name = new StringBuilder(parts[firstPart]);
for (int i = firstPart + 1; i < parts.length; i++) {
name.append('.');
name.append(parts[i]);
}
return new Domainname(name.toString());
} | java | public Domainname getLevelDomain(int level) {
String[] parts = this.getCode().split("\\.");
int firstPart = parts.length - level;
if ((firstPart < 0) || (level < 1)) {
throw new LocalizedIllegalArgumentException(level, "level", Range.between(1, parts.length));
}
StringBuilder name = new StringBuilder(parts[firstPart]);
for (int i = firstPart + 1; i < parts.length; i++) {
name.append('.');
name.append(parts[i]);
}
return new Domainname(name.toString());
} | [
"public",
"Domainname",
"getLevelDomain",
"(",
"int",
"level",
")",
"{",
"String",
"[",
"]",
"parts",
"=",
"this",
".",
"getCode",
"(",
")",
".",
"split",
"(",
"\"\\\\.\"",
")",
";",
"int",
"firstPart",
"=",
"parts",
".",
"length",
"-",
"level",
";",
... | Waehrend die Top-Level-Domain die oberste Ebende wie "de" ist, ist die
2nd-Level-Domain von "www.jfachwert.de" die Domain "jfachwert.de" und
die 3rd-Level-Domain ist in diesem Beispiel die komplette Domain.
@param level z.B. 2 fuer 2nd-Level-Domain
@return z.B. "jfachwert.de" | [
"Waehrend",
"die",
"Top",
"-",
"Level",
"-",
"Domain",
"die",
"oberste",
"Ebende",
"wie",
"de",
"ist",
"ist",
"die",
"2nd",
"-",
"Level",
"-",
"Domain",
"von",
"www",
".",
"jfachwert",
".",
"de",
"die",
"Domain",
"jfachwert",
".",
"de",
"und",
"die",
... | train | https://github.com/oboehm/jfachwert/blob/67b513d29e3114c7aee65cd1ea7a5b7e540b0d1b/src/main/java/de/jfachwert/net/Domainname.java#L107-L119 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java | MutateInBuilder.arrayAppend | public <T> MutateInBuilder arrayAppend(String path, T value) {
asyncBuilder.arrayAppend(path, value);
return this;
} | java | public <T> MutateInBuilder arrayAppend(String path, T value) {
asyncBuilder.arrayAppend(path, value);
return this;
} | [
"public",
"<",
"T",
">",
"MutateInBuilder",
"arrayAppend",
"(",
"String",
"path",
",",
"T",
"value",
")",
"{",
"asyncBuilder",
".",
"arrayAppend",
"(",
"path",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Append to an existing array, pushing the value to the back/last position in
the array.
@param path the path of the array.
@param value the value to insert at the back of the array. | [
"Append",
"to",
"an",
"existing",
"array",
"pushing",
"the",
"value",
"to",
"the",
"back",
"/",
"last",
"position",
"in",
"the",
"array",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/subdoc/MutateInBuilder.java#L821-L824 |
fuinorg/utils4j | src/main/java/org/fuin/utils4j/filter/TokenFilter.java | TokenFilter.complies | protected final boolean complies(final String value, final String constValue, final String separators) {
if (value == null) {
return false;
} else {
final StringTokenizer tok = new StringTokenizer(value, separators);
while (tok.hasMoreTokens()) {
final String t = tok.nextToken();
if (t.equals(constValue)) {
return true;
}
}
return false;
}
} | java | protected final boolean complies(final String value, final String constValue, final String separators) {
if (value == null) {
return false;
} else {
final StringTokenizer tok = new StringTokenizer(value, separators);
while (tok.hasMoreTokens()) {
final String t = tok.nextToken();
if (t.equals(constValue)) {
return true;
}
}
return false;
}
} | [
"protected",
"final",
"boolean",
"complies",
"(",
"final",
"String",
"value",
",",
"final",
"String",
"constValue",
",",
"final",
"String",
"separators",
")",
"{",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"else",
"{",
"fin... | Helper method for subclasses to do the comparation.
@param value
Object that contains the property.
@param constValue
Value to compare with.
@param separators
Separators
@return If object property contains the value as one of the tokens TRUE else FALSE. | [
"Helper",
"method",
"for",
"subclasses",
"to",
"do",
"the",
"comparation",
"."
] | train | https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/filter/TokenFilter.java#L80-L94 |
protostuff/protostuff | protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java | XmlIOUtil.mergeFrom | public static <T> void mergeFrom(byte[] data, int offset, int len, T message,
Schema<T> schema, XMLInputFactory inFactory)
{
final ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len);
try
{
mergeFrom(in, message, schema, inFactory);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
} | java | public static <T> void mergeFrom(byte[] data, int offset, int len, T message,
Schema<T> schema, XMLInputFactory inFactory)
{
final ByteArrayInputStream in = new ByteArrayInputStream(data, offset, len);
try
{
mergeFrom(in, message, schema, inFactory);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
} | [
"public",
"static",
"<",
"T",
">",
"void",
"mergeFrom",
"(",
"byte",
"[",
"]",
"data",
",",
"int",
"offset",
",",
"int",
"len",
",",
"T",
"message",
",",
"Schema",
"<",
"T",
">",
"schema",
",",
"XMLInputFactory",
"inFactory",
")",
"{",
"final",
"Byte... | Merges the {@code message} with the byte array using the given {@code schema}. | [
"Merges",
"the",
"{"
] | train | https://github.com/protostuff/protostuff/blob/af669cf089057d0ec83220266131ce411854af7b/protostuff-xml/src/main/java/io/protostuff/XmlIOUtil.java#L198-L210 |
stratosphere/stratosphere | stratosphere-core/src/main/java/eu/stratosphere/api/common/io/FileInputFormat.java | FileInputFormat.getStatistics | @Override
public FileBaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException {
final FileBaseStatistics cachedFileStats = (cachedStats != null && cachedStats instanceof FileBaseStatistics) ?
(FileBaseStatistics) cachedStats : null;
try {
final Path path = this.filePath;
final FileSystem fs = FileSystem.get(path.toUri());
return getFileStats(cachedFileStats, path, fs, new ArrayList<FileStatus>(1));
} catch (IOException ioex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not determine statistics for file '" + this.filePath + "' due to an io error: "
+ ioex.getMessage());
}
}
catch (Throwable t) {
if (LOG.isErrorEnabled()) {
LOG.error("Unexpected problen while getting the file statistics for file '" + this.filePath + "': "
+ t.getMessage(), t);
}
}
// no statistics available
return null;
} | java | @Override
public FileBaseStatistics getStatistics(BaseStatistics cachedStats) throws IOException {
final FileBaseStatistics cachedFileStats = (cachedStats != null && cachedStats instanceof FileBaseStatistics) ?
(FileBaseStatistics) cachedStats : null;
try {
final Path path = this.filePath;
final FileSystem fs = FileSystem.get(path.toUri());
return getFileStats(cachedFileStats, path, fs, new ArrayList<FileStatus>(1));
} catch (IOException ioex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not determine statistics for file '" + this.filePath + "' due to an io error: "
+ ioex.getMessage());
}
}
catch (Throwable t) {
if (LOG.isErrorEnabled()) {
LOG.error("Unexpected problen while getting the file statistics for file '" + this.filePath + "': "
+ t.getMessage(), t);
}
}
// no statistics available
return null;
} | [
"@",
"Override",
"public",
"FileBaseStatistics",
"getStatistics",
"(",
"BaseStatistics",
"cachedStats",
")",
"throws",
"IOException",
"{",
"final",
"FileBaseStatistics",
"cachedFileStats",
"=",
"(",
"cachedStats",
"!=",
"null",
"&&",
"cachedStats",
"instanceof",
"FileBa... | Obtains basic file statistics containing only file size. If the input is a directory, then the size is the sum of all contained files.
@see eu.stratosphere.api.common.io.InputFormat#getStatistics(eu.stratosphere.api.common.io.statistics.BaseStatistics) | [
"Obtains",
"basic",
"file",
"statistics",
"containing",
"only",
"file",
"size",
".",
"If",
"the",
"input",
"is",
"a",
"directory",
"then",
"the",
"size",
"is",
"the",
"sum",
"of",
"all",
"contained",
"files",
"."
] | train | https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/api/common/io/FileInputFormat.java#L307-L333 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java | ApiOvhDedicatedhousing.serviceName_task_taskId_cancel_POST | public void serviceName_task_taskId_cancel_POST(String serviceName, Long taskId) throws IOException {
String qPath = "/dedicated/housing/{serviceName}/task/{taskId}/cancel";
StringBuilder sb = path(qPath, serviceName, taskId);
exec(qPath, "POST", sb.toString(), null);
} | java | public void serviceName_task_taskId_cancel_POST(String serviceName, Long taskId) throws IOException {
String qPath = "/dedicated/housing/{serviceName}/task/{taskId}/cancel";
StringBuilder sb = path(qPath, serviceName, taskId);
exec(qPath, "POST", sb.toString(), null);
} | [
"public",
"void",
"serviceName_task_taskId_cancel_POST",
"(",
"String",
"serviceName",
",",
"Long",
"taskId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dedicated/housing/{serviceName}/task/{taskId}/cancel\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"... | this action stop the task progression if it's possible
REST: POST /dedicated/housing/{serviceName}/task/{taskId}/cancel
@param serviceName [required] The internal name of your Housing bay
@param taskId [required] the id of the task | [
"this",
"action",
"stop",
"the",
"task",
"progression",
"if",
"it",
"s",
"possible"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedhousing/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedhousing.java#L80-L84 |
prestodb/presto | presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/IndexLookup.java | IndexLookup.applyIndex | public boolean applyIndex(
String schema,
String table,
ConnectorSession session,
Collection<AccumuloColumnConstraint> constraints,
Collection<Range> rowIdRanges,
List<TabletSplitMetadata> tabletSplits,
AccumuloRowSerializer serializer,
Authorizations auths)
throws Exception
{
// Early out if index is disabled
if (!isOptimizeIndexEnabled(session)) {
LOG.debug("Secondary index is disabled");
return false;
}
LOG.debug("Secondary index is enabled");
// Collect Accumulo ranges for each indexed column constraint
Multimap<AccumuloColumnConstraint, Range> constraintRanges = getIndexedConstraintRanges(constraints, serializer);
// If there is no constraints on an index column, we again will bail out
if (constraintRanges.isEmpty()) {
LOG.debug("Query contains no constraints on indexed columns, skipping secondary index");
return false;
}
// If metrics are not enabled
if (!isIndexMetricsEnabled(session)) {
LOG.debug("Use of index metrics is disabled");
// Get the ranges via the index table
List<Range> indexRanges = getIndexRanges(getIndexTableName(schema, table), constraintRanges, rowIdRanges, auths);
if (!indexRanges.isEmpty()) {
// Bin the ranges into TabletMetadataSplits and return true to use the tablet splits
binRanges(getNumIndexRowsPerSplit(session), indexRanges, tabletSplits);
LOG.debug("Number of splits for %s.%s is %d with %d ranges", schema, table, tabletSplits.size(), indexRanges.size());
}
else {
LOG.debug("Query would return no results, returning empty list of splits");
}
return true;
}
else {
LOG.debug("Use of index metrics is enabled");
// Get ranges using the metrics
return getRangesWithMetrics(session, schema, table, constraintRanges, rowIdRanges, tabletSplits, auths);
}
} | java | public boolean applyIndex(
String schema,
String table,
ConnectorSession session,
Collection<AccumuloColumnConstraint> constraints,
Collection<Range> rowIdRanges,
List<TabletSplitMetadata> tabletSplits,
AccumuloRowSerializer serializer,
Authorizations auths)
throws Exception
{
// Early out if index is disabled
if (!isOptimizeIndexEnabled(session)) {
LOG.debug("Secondary index is disabled");
return false;
}
LOG.debug("Secondary index is enabled");
// Collect Accumulo ranges for each indexed column constraint
Multimap<AccumuloColumnConstraint, Range> constraintRanges = getIndexedConstraintRanges(constraints, serializer);
// If there is no constraints on an index column, we again will bail out
if (constraintRanges.isEmpty()) {
LOG.debug("Query contains no constraints on indexed columns, skipping secondary index");
return false;
}
// If metrics are not enabled
if (!isIndexMetricsEnabled(session)) {
LOG.debug("Use of index metrics is disabled");
// Get the ranges via the index table
List<Range> indexRanges = getIndexRanges(getIndexTableName(schema, table), constraintRanges, rowIdRanges, auths);
if (!indexRanges.isEmpty()) {
// Bin the ranges into TabletMetadataSplits and return true to use the tablet splits
binRanges(getNumIndexRowsPerSplit(session), indexRanges, tabletSplits);
LOG.debug("Number of splits for %s.%s is %d with %d ranges", schema, table, tabletSplits.size(), indexRanges.size());
}
else {
LOG.debug("Query would return no results, returning empty list of splits");
}
return true;
}
else {
LOG.debug("Use of index metrics is enabled");
// Get ranges using the metrics
return getRangesWithMetrics(session, schema, table, constraintRanges, rowIdRanges, tabletSplits, auths);
}
} | [
"public",
"boolean",
"applyIndex",
"(",
"String",
"schema",
",",
"String",
"table",
",",
"ConnectorSession",
"session",
",",
"Collection",
"<",
"AccumuloColumnConstraint",
">",
"constraints",
",",
"Collection",
"<",
"Range",
">",
"rowIdRanges",
",",
"List",
"<",
... | Scans the index table, applying the index based on the given column constraints to return a set of tablet splits.
<p>
If this function returns true, the output parameter tabletSplits contains a list of TabletSplitMetadata objects.
These in turn contain a collection of Ranges containing the exact row IDs determined using the index.
<p>
If this function returns false, the secondary index should not be used. In this case,
either the accumulo session has disabled secondary indexing,
or the number of row IDs that would be used by the secondary index is greater than the configured threshold
(again retrieved from the session).
@param schema Schema name
@param table Table name
@param session Current client session
@param constraints All column constraints (this method will filter for if the column is indexed)
@param rowIdRanges Collection of Accumulo ranges based on any predicate against a record key
@param tabletSplits Output parameter containing the bundles of row IDs determined by the use of the index.
@param serializer Instance of a row serializer
@param auths Scan-time authorizations
@return True if the tablet splits are valid and should be used, false otherwise
@throws Exception If something bad happens. What are the odds? | [
"Scans",
"the",
"index",
"table",
"applying",
"the",
"index",
"based",
"on",
"the",
"given",
"column",
"constraints",
"to",
"return",
"a",
"set",
"of",
"tablet",
"splits",
".",
"<p",
">",
"If",
"this",
"function",
"returns",
"true",
"the",
"output",
"param... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-accumulo/src/main/java/com/facebook/presto/accumulo/index/IndexLookup.java#L129-L179 |
fabric8io/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java | DockerFileUtil.createInterpolator | public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) {
String[] delimiters = extractDelimiters(filter);
if (delimiters == null) {
// Don't interpolate anything
return FixedStringSearchInterpolator.create();
}
DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null);
// Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator
return AssemblyInterpolator
.fullInterpolator(params.getProject(),
DefaultAssemblyReader.createProjectInterpolator(params.getProject())
.withExpressionMarkers(delimiters[0], delimiters[1]), configSource)
.withExpressionMarkers(delimiters[0], delimiters[1]);
} | java | public static FixedStringSearchInterpolator createInterpolator(MojoParameters params, String filter) {
String[] delimiters = extractDelimiters(filter);
if (delimiters == null) {
// Don't interpolate anything
return FixedStringSearchInterpolator.create();
}
DockerAssemblyConfigurationSource configSource = new DockerAssemblyConfigurationSource(params, null, null);
// Patterned after org.apache.maven.plugins.assembly.interpolation.AssemblyExpressionEvaluator
return AssemblyInterpolator
.fullInterpolator(params.getProject(),
DefaultAssemblyReader.createProjectInterpolator(params.getProject())
.withExpressionMarkers(delimiters[0], delimiters[1]), configSource)
.withExpressionMarkers(delimiters[0], delimiters[1]);
} | [
"public",
"static",
"FixedStringSearchInterpolator",
"createInterpolator",
"(",
"MojoParameters",
"params",
",",
"String",
"filter",
")",
"{",
"String",
"[",
"]",
"delimiters",
"=",
"extractDelimiters",
"(",
"filter",
")",
";",
"if",
"(",
"delimiters",
"==",
"null... | Create an interpolator for the given maven parameters and filter configuration.
@param params The maven parameters.
@param filter The filter configuration.
@return An interpolator for replacing maven properties. | [
"Create",
"an",
"interpolator",
"for",
"the",
"given",
"maven",
"parameters",
"and",
"filter",
"configuration",
"."
] | train | https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/DockerFileUtil.java#L113-L127 |
inkstand-io/scribble | scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java | XMLContentHandler.startElementNode | private void startElementNode(final Attributes attributes) {
LOG.debug("Found node");
try {
this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes));
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
}
} | java | private void startElementNode(final Attributes attributes) {
LOG.debug("Found node");
try {
this.nodeStack.push(this.newNode(this.nodeStack.peek(), attributes));
} catch (final RepositoryException e) {
throw new AssertionError("Could not create node", e);
}
} | [
"private",
"void",
"startElementNode",
"(",
"final",
"Attributes",
"attributes",
")",
"{",
"LOG",
".",
"debug",
"(",
"\"Found node\"",
")",
";",
"try",
"{",
"this",
".",
"nodeStack",
".",
"push",
"(",
"this",
".",
"newNode",
"(",
"this",
".",
"nodeStack",
... | Invoked on node element.
@param attributes
the DOM attributes of the node element
@throws SAXException
if the node for the new element can not be added | [
"Invoked",
"on",
"node",
"element",
"."
] | train | https://github.com/inkstand-io/scribble/blob/66e67553bad4b1ff817e1715fd1d3dd833406744/scribble-jcr/src/main/java/io/inkstand/scribble/jcr/rules/util/XMLContentHandler.java#L354-L362 |
JodaOrg/joda-money | src/main/java/org/joda/money/BigMoney.java | BigMoney.plusRetainScale | public BigMoney plusRetainScale(BigMoneyProvider moneyToAdd, RoundingMode roundingMode) {
BigMoney toAdd = checkCurrencyEqual(moneyToAdd);
return plusRetainScale(toAdd.getAmount(), roundingMode);
} | java | public BigMoney plusRetainScale(BigMoneyProvider moneyToAdd, RoundingMode roundingMode) {
BigMoney toAdd = checkCurrencyEqual(moneyToAdd);
return plusRetainScale(toAdd.getAmount(), roundingMode);
} | [
"public",
"BigMoney",
"plusRetainScale",
"(",
"BigMoneyProvider",
"moneyToAdd",
",",
"RoundingMode",
"roundingMode",
")",
"{",
"BigMoney",
"toAdd",
"=",
"checkCurrencyEqual",
"(",
"moneyToAdd",
")",
";",
"return",
"plusRetainScale",
"(",
"toAdd",
".",
"getAmount",
"... | Returns a copy of this monetary value with the amount in the same currency added
retaining the scale by rounding the result.
<p>
The scale of the result will be the same as the scale of this instance.
For example,'USD 25.95' plus 'USD 3.021' gives 'USD 28.97' with most rounding modes.
<p>
This instance is immutable and unaffected by this method.
@param moneyToAdd the monetary value to add, not null
@param roundingMode the rounding mode to use to adjust the scale, not null
@return the new instance with the input amount added, never null | [
"Returns",
"a",
"copy",
"of",
"this",
"monetary",
"value",
"with",
"the",
"amount",
"in",
"the",
"same",
"currency",
"added",
"retaining",
"the",
"scale",
"by",
"rounding",
"the",
"result",
".",
"<p",
">",
"The",
"scale",
"of",
"the",
"result",
"will",
"... | train | https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L967-L970 |
meltmedia/cadmium | servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java | BasicFileServlet.calculateRangeLength | public static Long calculateRangeLength(FileRequestContext context, Range range) {
if(range.start == -1) range.start = 0;
if(range.end == -1) range.end = context.file.length() - 1;
range.length = range.end - range.start + 1;
return range.length;
} | java | public static Long calculateRangeLength(FileRequestContext context, Range range) {
if(range.start == -1) range.start = 0;
if(range.end == -1) range.end = context.file.length() - 1;
range.length = range.end - range.start + 1;
return range.length;
} | [
"public",
"static",
"Long",
"calculateRangeLength",
"(",
"FileRequestContext",
"context",
",",
"Range",
"range",
")",
"{",
"if",
"(",
"range",
".",
"start",
"==",
"-",
"1",
")",
"range",
".",
"start",
"=",
"0",
";",
"if",
"(",
"range",
".",
"end",
"=="... | Calculates the length of a given range.
@param context
@param range
@return | [
"Calculates",
"the",
"length",
"of",
"a",
"given",
"range",
"."
] | train | https://github.com/meltmedia/cadmium/blob/bca585030e141803a73b58abb128d130157b6ddf/servlets/src/main/java/com/meltmedia/cadmium/servlets/BasicFileServlet.java#L236-L241 |
reactor/reactor-netty | src/main/java/reactor/netty/http/server/ConnectionInfo.java | ConnectionInfo.newForwardedConnectionInfo | static ConnectionInfo newForwardedConnectionInfo(HttpRequest request, Channel channel) {
if (request.headers().contains(FORWARDED_HEADER)) {
return parseForwardedInfo(request, (SocketChannel)channel);
}
else {
return parseXForwardedInfo(request, (SocketChannel)channel);
}
} | java | static ConnectionInfo newForwardedConnectionInfo(HttpRequest request, Channel channel) {
if (request.headers().contains(FORWARDED_HEADER)) {
return parseForwardedInfo(request, (SocketChannel)channel);
}
else {
return parseXForwardedInfo(request, (SocketChannel)channel);
}
} | [
"static",
"ConnectionInfo",
"newForwardedConnectionInfo",
"(",
"HttpRequest",
"request",
",",
"Channel",
"channel",
")",
"{",
"if",
"(",
"request",
".",
"headers",
"(",
")",
".",
"contains",
"(",
"FORWARDED_HEADER",
")",
")",
"{",
"return",
"parseForwardedInfo",
... | Retrieve the connection information from the {@code "Forwarded"}/{@code "X-Forwarded-*"}
HTTP request headers, or from the current connection directly if none are found.
@param request the current server request
@param channel the current channel
@return the connection information | [
"Retrieve",
"the",
"connection",
"information",
"from",
"the",
"{"
] | train | https://github.com/reactor/reactor-netty/blob/4ed14316e1d7fca3cecd18d6caa5f2251e159e49/src/main/java/reactor/netty/http/server/ConnectionInfo.java#L92-L99 |
lucee/Lucee | core/src/main/java/lucee/runtime/config/ConfigWebUtil.java | ConfigWebUtil.hasAccess | public static boolean hasAccess(Config config, int type) {
boolean has = true;
if (config instanceof ConfigWeb) {
has = ((ConfigWeb) config).getSecurityManager().getAccess(type) != SecurityManager.VALUE_NO;
}
return has;
} | java | public static boolean hasAccess(Config config, int type) {
boolean has = true;
if (config instanceof ConfigWeb) {
has = ((ConfigWeb) config).getSecurityManager().getAccess(type) != SecurityManager.VALUE_NO;
}
return has;
} | [
"public",
"static",
"boolean",
"hasAccess",
"(",
"Config",
"config",
",",
"int",
"type",
")",
"{",
"boolean",
"has",
"=",
"true",
";",
"if",
"(",
"config",
"instanceof",
"ConfigWeb",
")",
"{",
"has",
"=",
"(",
"(",
"ConfigWeb",
")",
"config",
")",
".",... | has access checks if config object has access to given type
@param config
@param type
@return has access | [
"has",
"access",
"checks",
"if",
"config",
"object",
"has",
"access",
"to",
"given",
"type"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/ConfigWebUtil.java#L427-L434 |
astrapi69/jaulp-wicket | jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java | WicketImageExtensions.getImage | public static Image getImage(final String wicketId, final String contentType, final Byte[] data)
{
final byte[] byteArrayData = ArrayUtils.toPrimitive(data);
return getImage(wicketId, contentType, byteArrayData);
} | java | public static Image getImage(final String wicketId, final String contentType, final Byte[] data)
{
final byte[] byteArrayData = ArrayUtils.toPrimitive(data);
return getImage(wicketId, contentType, byteArrayData);
} | [
"public",
"static",
"Image",
"getImage",
"(",
"final",
"String",
"wicketId",
",",
"final",
"String",
"contentType",
",",
"final",
"Byte",
"[",
"]",
"data",
")",
"{",
"final",
"byte",
"[",
"]",
"byteArrayData",
"=",
"ArrayUtils",
".",
"toPrimitive",
"(",
"d... | Gets the image.
@param wicketId
the id from the image for the html template.
@param contentType
the content type
@param data
the data
@return the image | [
"Gets",
"the",
"image",
"."
] | train | https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketImageExtensions.java#L58-L62 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/JFAPCommunicator.java | JFAPCommunicator.invalidateConnection | protected void invalidateConnection(boolean notifyPeer, Throwable throwable, String debugReason)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "invalidateConnection", new Object[]{new Boolean(notifyPeer),
throwable,
debugReason});
if (con != null)
{
ConnectionInterface connection = con.getConnectionReference();
if (connection != null)
{
connection.invalidate(notifyPeer, throwable, debugReason);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "invalidateConnection");
} | java | protected void invalidateConnection(boolean notifyPeer, Throwable throwable, String debugReason)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "invalidateConnection", new Object[]{new Boolean(notifyPeer),
throwable,
debugReason});
if (con != null)
{
ConnectionInterface connection = con.getConnectionReference();
if (connection != null)
{
connection.invalidate(notifyPeer, throwable, debugReason);
}
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "invalidateConnection");
} | [
"protected",
"void",
"invalidateConnection",
"(",
"boolean",
"notifyPeer",
",",
"Throwable",
"throwable",
",",
"String",
"debugReason",
")",
"{",
"if",
"(",
"TraceComponent",
".",
"isAnyTracingEnabled",
"(",
")",
"&&",
"tc",
".",
"isEntryEnabled",
"(",
")",
")",... | Utility method to invalidate Connection. Parameters passed to ConnectionInterface.invalidate
@param notifyPeer
@param throwable
@param debugReason | [
"Utility",
"method",
"to",
"invalidate",
"Connection",
".",
"Parameters",
"passed",
"to",
"ConnectionInterface",
".",
"invalidate"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/comms/common/JFAPCommunicator.java#L1430-L1444 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java | CollUtil.newHashSet | public static <T> HashSet<T> newHashSet(boolean isSorted, Iterator<T> iter) {
if (null == iter) {
return newHashSet(isSorted, (T[]) null);
}
final HashSet<T> set = isSorted ? new LinkedHashSet<T>() : new HashSet<T>();
while (iter.hasNext()) {
set.add(iter.next());
}
return set;
} | java | public static <T> HashSet<T> newHashSet(boolean isSorted, Iterator<T> iter) {
if (null == iter) {
return newHashSet(isSorted, (T[]) null);
}
final HashSet<T> set = isSorted ? new LinkedHashSet<T>() : new HashSet<T>();
while (iter.hasNext()) {
set.add(iter.next());
}
return set;
} | [
"public",
"static",
"<",
"T",
">",
"HashSet",
"<",
"T",
">",
"newHashSet",
"(",
"boolean",
"isSorted",
",",
"Iterator",
"<",
"T",
">",
"iter",
")",
"{",
"if",
"(",
"null",
"==",
"iter",
")",
"{",
"return",
"newHashSet",
"(",
"isSorted",
",",
"(",
"... | 新建一个HashSet
@param <T> 集合元素类型
@param isSorted 是否有序,有序返回 {@link LinkedHashSet},否则返回{@link HashSet}
@param iter {@link Iterator}
@return HashSet对象
@since 3.0.8 | [
"新建一个HashSet"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/collection/CollUtil.java#L472-L481 |
spring-projects/spring-android | spring-android-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java | ConcurrentReferenceHashMap.calculateShift | protected static int calculateShift(int minimumValue, int maximumValue) {
int shift = 0;
int value = 1;
while (value < minimumValue && value < maximumValue) {
value <<= 1;
shift++;
}
return shift;
} | java | protected static int calculateShift(int minimumValue, int maximumValue) {
int shift = 0;
int value = 1;
while (value < minimumValue && value < maximumValue) {
value <<= 1;
shift++;
}
return shift;
} | [
"protected",
"static",
"int",
"calculateShift",
"(",
"int",
"minimumValue",
",",
"int",
"maximumValue",
")",
"{",
"int",
"shift",
"=",
"0",
";",
"int",
"value",
"=",
"1",
";",
"while",
"(",
"value",
"<",
"minimumValue",
"&&",
"value",
"<",
"maximumValue",
... | Calculate a shift value that can be used to create a power-of-two value between
the specified maximum and minimum values.
@param minimumValue the minimum value
@param maximumValue the maximum value
@return the calculated shift (use {@code 1 << shift} to obtain a value) | [
"Calculate",
"a",
"shift",
"value",
"that",
"can",
"be",
"used",
"to",
"create",
"a",
"power",
"-",
"of",
"-",
"two",
"value",
"between",
"the",
"specified",
"maximum",
"and",
"minimum",
"values",
"."
] | train | https://github.com/spring-projects/spring-android/blob/941296e152d49a40e0745a3e81628a974f72b7e4/spring-android-core/src/main/java/org/springframework/util/ConcurrentReferenceHashMap.java#L383-L391 |
nats-io/java-nats | src/main/java/io/nats/client/impl/FileAuthHandler.java | FileAuthHandler.getID | public char[] getID() {
try {
char[] keyChars = this.readKeyChars();
NKey nkey = NKey.fromSeed(keyChars);
char[] pubKey = nkey.getPublicKey();
nkey.clear();
return pubKey;
} catch (Exception exp) {
throw new IllegalStateException("problem getting public key", exp);
}
} | java | public char[] getID() {
try {
char[] keyChars = this.readKeyChars();
NKey nkey = NKey.fromSeed(keyChars);
char[] pubKey = nkey.getPublicKey();
nkey.clear();
return pubKey;
} catch (Exception exp) {
throw new IllegalStateException("problem getting public key", exp);
}
} | [
"public",
"char",
"[",
"]",
"getID",
"(",
")",
"{",
"try",
"{",
"char",
"[",
"]",
"keyChars",
"=",
"this",
".",
"readKeyChars",
"(",
")",
";",
"NKey",
"nkey",
"=",
"NKey",
".",
"fromSeed",
"(",
"keyChars",
")",
";",
"char",
"[",
"]",
"pubKey",
"=... | getID should return a public key associated with a client key known to the server.
If the server is not in nonce-mode, this array can be empty.
@return the public key as a char array | [
"getID",
"should",
"return",
"a",
"public",
"key",
"associated",
"with",
"a",
"client",
"key",
"known",
"to",
"the",
"server",
".",
"If",
"the",
"server",
"is",
"not",
"in",
"nonce",
"-",
"mode",
"this",
"array",
"can",
"be",
"empty",
"."
] | train | https://github.com/nats-io/java-nats/blob/5f291048fd30192ba39b3fe2925ecd60aaad6b48/src/main/java/io/nats/client/impl/FileAuthHandler.java#L170-L180 |
looly/hutool | hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/AbstractAsymmetricCrypto.java | AbstractAsymmetricCrypto.encryptBcd | public String encryptBcd(String data, KeyType keyType) {
return encryptBcd(data, keyType, CharsetUtil.CHARSET_UTF_8);
} | java | public String encryptBcd(String data, KeyType keyType) {
return encryptBcd(data, keyType, CharsetUtil.CHARSET_UTF_8);
} | [
"public",
"String",
"encryptBcd",
"(",
"String",
"data",
",",
"KeyType",
"keyType",
")",
"{",
"return",
"encryptBcd",
"(",
"data",
",",
"keyType",
",",
"CharsetUtil",
".",
"CHARSET_UTF_8",
")",
";",
"}"
] | 分组加密
@param data 数据
@param keyType 密钥类型
@return 加密后的密文
@throws CryptoException 加密异常
@since 4.1.0 | [
"分组加密"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/asymmetric/AbstractAsymmetricCrypto.java#L198-L200 |
osmdroid/osmdroid | osmdroid-android/src/main/java/org/osmdroid/util/TileSystem.java | TileSystem.PixelXYToLatLong | @Deprecated
public GeoPoint PixelXYToLatLong(
final int pixelX, final int pixelY, final int levelOfDetail, final GeoPoint reuse) {
return getGeoFromMercator(pixelX, pixelY, MapSize(levelOfDetail), reuse, true, true);
} | java | @Deprecated
public GeoPoint PixelXYToLatLong(
final int pixelX, final int pixelY, final int levelOfDetail, final GeoPoint reuse) {
return getGeoFromMercator(pixelX, pixelY, MapSize(levelOfDetail), reuse, true, true);
} | [
"@",
"Deprecated",
"public",
"GeoPoint",
"PixelXYToLatLong",
"(",
"final",
"int",
"pixelX",
",",
"final",
"int",
"pixelY",
",",
"final",
"int",
"levelOfDetail",
",",
"final",
"GeoPoint",
"reuse",
")",
"{",
"return",
"getGeoFromMercator",
"(",
"pixelX",
",",
"p... | Use {@link TileSystem#getGeoFromMercator(long, long, double, GeoPoint, boolean, boolean)} instead | [
"Use",
"{"
] | train | https://github.com/osmdroid/osmdroid/blob/3b178b2f078497dd88c137110e87aafe45ad2b16/osmdroid-android/src/main/java/org/osmdroid/util/TileSystem.java#L185-L189 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/Record.java | Record.getDateTime | public Date getDateTime(int field) throws MPXJException
{
Date result = null;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getDateTimeFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
// Failed to parse a full date time.
}
//
// Fall back to trying just parsing the date component
//
if (result == null)
{
try
{
result = m_formats.getDateFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse date time", ex);
}
}
}
return result;
} | java | public Date getDateTime(int field) throws MPXJException
{
Date result = null;
if ((field < m_fields.length) && (m_fields[field].length() != 0))
{
try
{
result = m_formats.getDateTimeFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
// Failed to parse a full date time.
}
//
// Fall back to trying just parsing the date component
//
if (result == null)
{
try
{
result = m_formats.getDateFormat().parse(m_fields[field]);
}
catch (ParseException ex)
{
throw new MPXJException("Failed to parse date time", ex);
}
}
}
return result;
} | [
"public",
"Date",
"getDateTime",
"(",
"int",
"field",
")",
"throws",
"MPXJException",
"{",
"Date",
"result",
"=",
"null",
";",
"if",
"(",
"(",
"field",
"<",
"m_fields",
".",
"length",
")",
"&&",
"(",
"m_fields",
"[",
"field",
"]",
".",
"length",
"(",
... | Accessor method used to retrieve an Date instance representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field
@throws MPXJException normally thrown when parsing fails | [
"Accessor",
"method",
"used",
"to",
"retrieve",
"an",
"Date",
"instance",
"representing",
"the",
"contents",
"of",
"an",
"individual",
"field",
".",
"If",
"the",
"field",
"does",
"not",
"exist",
"in",
"the",
"record",
"null",
"is",
"returned",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/Record.java#L238-L272 |
att/AAF | authz/authz-cass/src/main/java/com/att/dao/Loader.java | Loader.readString | public static String readString(DataInputStream is, byte[] _buff) throws IOException {
int l = is.readInt();
byte[] buff = _buff;
switch(l) {
case -1: return null;
case 0: return "";
default:
// Cover case where there is a large string, without always allocating a large buffer.
if(l>buff.length) {
buff = new byte[l];
}
is.read(buff,0,l);
return new String(buff,0,l);
}
} | java | public static String readString(DataInputStream is, byte[] _buff) throws IOException {
int l = is.readInt();
byte[] buff = _buff;
switch(l) {
case -1: return null;
case 0: return "";
default:
// Cover case where there is a large string, without always allocating a large buffer.
if(l>buff.length) {
buff = new byte[l];
}
is.read(buff,0,l);
return new String(buff,0,l);
}
} | [
"public",
"static",
"String",
"readString",
"(",
"DataInputStream",
"is",
",",
"byte",
"[",
"]",
"_buff",
")",
"throws",
"IOException",
"{",
"int",
"l",
"=",
"is",
".",
"readInt",
"(",
")",
";",
"byte",
"[",
"]",
"buff",
"=",
"_buff",
";",
"switch",
... | We use bytes here to set a Maximum
@param is
@param MAX
@return
@throws IOException | [
"We",
"use",
"bytes",
"here",
"to",
"set",
"a",
"Maximum"
] | train | https://github.com/att/AAF/blob/090562e956c0035db972aafba844dc6d3fc948ee/authz/authz-cass/src/main/java/com/att/dao/Loader.java#L84-L98 |
landawn/AbacusUtil | src/com/landawn/abacus/util/StringUtil.java | StringUtil.removeStartIgnoreCase | public static String removeStartIgnoreCase(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (startsWithIgnoreCase(str, removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | java | public static String removeStartIgnoreCase(final String str, final String removeStr) {
if (N.isNullOrEmpty(str) || N.isNullOrEmpty(removeStr)) {
return str;
}
if (startsWithIgnoreCase(str, removeStr)) {
return str.substring(removeStr.length());
}
return str;
} | [
"public",
"static",
"String",
"removeStartIgnoreCase",
"(",
"final",
"String",
"str",
",",
"final",
"String",
"removeStr",
")",
"{",
"if",
"(",
"N",
".",
"isNullOrEmpty",
"(",
"str",
")",
"||",
"N",
".",
"isNullOrEmpty",
"(",
"removeStr",
")",
")",
"{",
... | <p>
Case insensitive removal of a substring if it is at the beginning of a
source string, otherwise returns the source string.
</p>
<p>
A {@code null} source string will return {@code null}. An empty ("")
source string will return the empty string. A {@code null} search string
will return the source string.
</p>
<pre>
N.removeStartIgnoreCase(null, *) = null
N.removeStartIgnoreCase("", *) = ""
N.removeStartIgnoreCase(*, null) = *
N.removeStartIgnoreCase("www.domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "WWW.") = "domain.com"
N.removeStartIgnoreCase("domain.com", "www.") = "domain.com"
N.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
N.removeStartIgnoreCase("abc", "") = "abc"
</pre>
@param str
the source String to search, may be null
@param removeStr
the String to search for (case insensitive) and remove, may be
null
@return the substring with the string removed if found, {@code null} if
null String input
@since 2.4 | [
"<p",
">",
"Case",
"insensitive",
"removal",
"of",
"a",
"substring",
"if",
"it",
"is",
"at",
"the",
"beginning",
"of",
"a",
"source",
"string",
"otherwise",
"returns",
"the",
"source",
"string",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/StringUtil.java#L1191-L1201 |
alkacon/opencms-core | src/org/opencms/importexport/CmsExportHelper.java | CmsExportHelper.writeFile | public void writeFile(CmsFile file, String name) throws IOException {
if (m_isExportAsFiles) {
writeFile2Rfs(file, name);
} else {
writeFile2Zip(file, name);
}
} | java | public void writeFile(CmsFile file, String name) throws IOException {
if (m_isExportAsFiles) {
writeFile2Rfs(file, name);
} else {
writeFile2Zip(file, name);
}
} | [
"public",
"void",
"writeFile",
"(",
"CmsFile",
"file",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"if",
"(",
"m_isExportAsFiles",
")",
"{",
"writeFile2Rfs",
"(",
"file",
",",
"name",
")",
";",
"}",
"else",
"{",
"writeFile2Zip",
"(",
"file",
... | Writes a single OpenCms VFS file to the export.<p>
@param file the OpenCms VFS file to write
@param name the name of the file in the export
@throws IOException in case of file access issues | [
"Writes",
"a",
"single",
"OpenCms",
"VFS",
"file",
"to",
"the",
"export",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExportHelper.java#L144-L151 |
artikcloud/artikcloud-java | src/main/java/cloud/artik/api/MonetizationApi.java | MonetizationApi.getPricingTiers | public DevicePricingTiersEnvelope getPricingTiers(String did, Boolean active) throws ApiException {
ApiResponse<DevicePricingTiersEnvelope> resp = getPricingTiersWithHttpInfo(did, active);
return resp.getData();
} | java | public DevicePricingTiersEnvelope getPricingTiers(String did, Boolean active) throws ApiException {
ApiResponse<DevicePricingTiersEnvelope> resp = getPricingTiersWithHttpInfo(did, active);
return resp.getData();
} | [
"public",
"DevicePricingTiersEnvelope",
"getPricingTiers",
"(",
"String",
"did",
",",
"Boolean",
"active",
")",
"throws",
"ApiException",
"{",
"ApiResponse",
"<",
"DevicePricingTiersEnvelope",
">",
"resp",
"=",
"getPricingTiersWithHttpInfo",
"(",
"did",
",",
"active",
... | Get a device's pricing tiers
Get a device's pricing tiers
@param did Device ID (required)
@param active Filter by active (optional)
@return DevicePricingTiersEnvelope
@throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body | [
"Get",
"a",
"device'",
";",
"s",
"pricing",
"tiers",
"Get",
"a",
"device'",
";",
"s",
"pricing",
"tiers"
] | train | https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/MonetizationApi.java#L259-L262 |
openengsb/openengsb | components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java | EngineeringObjectEnhancer.getReferenceBasedUpdates | private List<AdvancedModelWrapper> getReferenceBasedUpdates(AdvancedModelWrapper model,
Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) throws EKBException {
List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>();
List<EDBObject> references = model.getModelsReferringToThisModel(edbService);
for (EDBObject reference : references) {
EDBModelObject modelReference = new EDBModelObject(reference, modelRegistry, edbConverter);
AdvancedModelWrapper ref = updateEOByUpdatedModel(modelReference, model, updated);
if (!updated.containsKey(ref.getCompleteModelOID())) {
updates.add(ref);
}
}
return updates;
} | java | private List<AdvancedModelWrapper> getReferenceBasedUpdates(AdvancedModelWrapper model,
Map<Object, AdvancedModelWrapper> updated, EKBCommit commit) throws EKBException {
List<AdvancedModelWrapper> updates = new ArrayList<AdvancedModelWrapper>();
List<EDBObject> references = model.getModelsReferringToThisModel(edbService);
for (EDBObject reference : references) {
EDBModelObject modelReference = new EDBModelObject(reference, modelRegistry, edbConverter);
AdvancedModelWrapper ref = updateEOByUpdatedModel(modelReference, model, updated);
if (!updated.containsKey(ref.getCompleteModelOID())) {
updates.add(ref);
}
}
return updates;
} | [
"private",
"List",
"<",
"AdvancedModelWrapper",
">",
"getReferenceBasedUpdates",
"(",
"AdvancedModelWrapper",
"model",
",",
"Map",
"<",
"Object",
",",
"AdvancedModelWrapper",
">",
"updated",
",",
"EKBCommit",
"commit",
")",
"throws",
"EKBException",
"{",
"List",
"<"... | Returns engineering objects to the commit, which are changed by a model which was committed in the EKBCommit | [
"Returns",
"engineering",
"objects",
"to",
"the",
"commit",
"which",
"are",
"changed",
"by",
"a",
"model",
"which",
"was",
"committed",
"in",
"the",
"EKBCommit"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/persistence-persist-edb/src/main/java/org/openengsb/core/ekb/persistence/persist/edb/internal/EngineeringObjectEnhancer.java#L213-L225 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/StringUtil.java | StringUtil.rtrim | public static String rtrim(String str, String defaultValue) {
if (str == null) return defaultValue;
int len = str.length();
while ((0 < len) && (str.charAt(len - 1) <= ' ')) {
len--;
}
return (len < str.length()) ? str.substring(0, len) : str;
} | java | public static String rtrim(String str, String defaultValue) {
if (str == null) return defaultValue;
int len = str.length();
while ((0 < len) && (str.charAt(len - 1) <= ' ')) {
len--;
}
return (len < str.length()) ? str.substring(0, len) : str;
} | [
"public",
"static",
"String",
"rtrim",
"(",
"String",
"str",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"str",
"==",
"null",
")",
"return",
"defaultValue",
";",
"int",
"len",
"=",
"str",
".",
"length",
"(",
")",
";",
"while",
"(",
"(",
"0",
... | This function returns a string with whitespace stripped from the end of str
@param str String to clean
@return cleaned String | [
"This",
"function",
"returns",
"a",
"string",
"with",
"whitespace",
"stripped",
"from",
"the",
"end",
"of",
"str"
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L500-L508 |
liferay/com-liferay-commerce | commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java | CommerceCurrencyPersistenceImpl.removeByUUID_G | @Override
public CommerceCurrency removeByUUID_G(String uuid, long groupId)
throws NoSuchCurrencyException {
CommerceCurrency commerceCurrency = findByUUID_G(uuid, groupId);
return remove(commerceCurrency);
} | java | @Override
public CommerceCurrency removeByUUID_G(String uuid, long groupId)
throws NoSuchCurrencyException {
CommerceCurrency commerceCurrency = findByUUID_G(uuid, groupId);
return remove(commerceCurrency);
} | [
"@",
"Override",
"public",
"CommerceCurrency",
"removeByUUID_G",
"(",
"String",
"uuid",
",",
"long",
"groupId",
")",
"throws",
"NoSuchCurrencyException",
"{",
"CommerceCurrency",
"commerceCurrency",
"=",
"findByUUID_G",
"(",
"uuid",
",",
"groupId",
")",
";",
"return... | Removes the commerce currency where uuid = ? and groupId = ? from the database.
@param uuid the uuid
@param groupId the group ID
@return the commerce currency that was removed | [
"Removes",
"the",
"commerce",
"currency",
"where",
"uuid",
"=",
"?",
";",
"and",
"groupId",
"=",
"?",
";",
"from",
"the",
"database",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-currency-service/src/main/java/com/liferay/commerce/currency/service/persistence/impl/CommerceCurrencyPersistenceImpl.java#L812-L818 |
linkhub-sdk/popbill.sdk.java | src/main/java/com/popbill/api/message/MessageServiceImp.java | MessageServiceImp.sendMMS | @Override
public String sendMMS(String CorpNum, String sender, String receiver,
String receiverName, String subject, String content, File file,
Date reserveDT, String UserID) throws PopbillException {
Message message = new Message();
message.setSender(sender);
message.setReceiver(receiver);
message.setReceiverName(receiverName);
message.setContent(content);
message.setSubject(subject);
return sendMMS(CorpNum, new Message[]{message}, file, reserveDT, UserID);
} | java | @Override
public String sendMMS(String CorpNum, String sender, String receiver,
String receiverName, String subject, String content, File file,
Date reserveDT, String UserID) throws PopbillException {
Message message = new Message();
message.setSender(sender);
message.setReceiver(receiver);
message.setReceiverName(receiverName);
message.setContent(content);
message.setSubject(subject);
return sendMMS(CorpNum, new Message[]{message}, file, reserveDT, UserID);
} | [
"@",
"Override",
"public",
"String",
"sendMMS",
"(",
"String",
"CorpNum",
",",
"String",
"sender",
",",
"String",
"receiver",
",",
"String",
"receiverName",
",",
"String",
"subject",
",",
"String",
"content",
",",
"File",
"file",
",",
"Date",
"reserveDT",
",... | /*
(non-Javadoc)
@see com.popbill.api.MessageService#sendMMS(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.io.File, java.util.Date, java.lang.String) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/linkhub-sdk/popbill.sdk.java/blob/63a341fefe96d60a368776638f3d4c81888238b7/src/main/java/com/popbill/api/message/MessageServiceImp.java#L717-L731 |
shrinkwrap/shrinkwrap | impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapFileSystemProvider.java | ShrinkWrapFileSystemProvider.copy | private void copy(final InputStream in, final SeekableByteChannel out) throws IOException {
assert in != null : "InStream must be specified";
assert out != null : "Channel must be specified";
final byte[] backingBuffer = new byte[1024 * 4];
final ByteBuffer byteBuffer = ByteBuffer.wrap(backingBuffer);
int bytesRead = 0;
while ((bytesRead = in.read(backingBuffer, 0, backingBuffer.length)) > -1) {
// Limit to the amount we've actually read in, so we don't overflow into old data blocks
byteBuffer.limit(bytesRead);
out.write(byteBuffer);
// Position back to 0
byteBuffer.clear();
}
} | java | private void copy(final InputStream in, final SeekableByteChannel out) throws IOException {
assert in != null : "InStream must be specified";
assert out != null : "Channel must be specified";
final byte[] backingBuffer = new byte[1024 * 4];
final ByteBuffer byteBuffer = ByteBuffer.wrap(backingBuffer);
int bytesRead = 0;
while ((bytesRead = in.read(backingBuffer, 0, backingBuffer.length)) > -1) {
// Limit to the amount we've actually read in, so we don't overflow into old data blocks
byteBuffer.limit(bytesRead);
out.write(byteBuffer);
// Position back to 0
byteBuffer.clear();
}
} | [
"private",
"void",
"copy",
"(",
"final",
"InputStream",
"in",
",",
"final",
"SeekableByteChannel",
"out",
")",
"throws",
"IOException",
"{",
"assert",
"in",
"!=",
"null",
":",
"\"InStream must be specified\"",
";",
"assert",
"out",
"!=",
"null",
":",
"\"Channel ... | Writes the contents of the {@link InputStream} to the {@link SeekableByteChannel}
@param in
@param out
@throws IOException | [
"Writes",
"the",
"contents",
"of",
"the",
"{",
"@link",
"InputStream",
"}",
"to",
"the",
"{",
"@link",
"SeekableByteChannel",
"}"
] | train | https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/nio2/file/ShrinkWrapFileSystemProvider.java#L626-L640 |
CloudSlang/cs-actions | cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureHelper.java | AwsSignatureHelper.canonicalizedQueryString | public String canonicalizedQueryString(Map<String, String> queryParameters) {
List<Map.Entry<String, String>> sortedList = getSortedMapEntries(queryParameters);
StringBuilder queryString = new StringBuilder();
for (Map.Entry<String, String> entry : sortedList) {
queryString.append(entryToQuery(entry));
}
if (queryString.length() > START_INDEX) {
queryString.deleteCharAt(queryString.length() - ONE); //removing last '&'
}
return queryString.toString();
} | java | public String canonicalizedQueryString(Map<String, String> queryParameters) {
List<Map.Entry<String, String>> sortedList = getSortedMapEntries(queryParameters);
StringBuilder queryString = new StringBuilder();
for (Map.Entry<String, String> entry : sortedList) {
queryString.append(entryToQuery(entry));
}
if (queryString.length() > START_INDEX) {
queryString.deleteCharAt(queryString.length() - ONE); //removing last '&'
}
return queryString.toString();
} | [
"public",
"String",
"canonicalizedQueryString",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"queryParameters",
")",
"{",
"List",
"<",
"Map",
".",
"Entry",
"<",
"String",
",",
"String",
">",
">",
"sortedList",
"=",
"getSortedMapEntries",
"(",
"queryParameter... | Canonicalized (standardized) query string is formed by first sorting all the query
parameters, then URI encoding both the key and value and then
joining them, in order, separating key value pairs with an '&'.
@param queryParameters Query parameters to be canonicalized.
@return A canonicalized form for the specified query parameters. | [
"Canonicalized",
"(",
"standardized",
")",
"query",
"string",
"is",
"formed",
"by",
"first",
"sorting",
"all",
"the",
"query",
"parameters",
"then",
"URI",
"encoding",
"both",
"the",
"key",
"and",
"value",
"and",
"then",
"joining",
"them",
"in",
"order",
"se... | train | https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-amazon/src/main/java/io/cloudslang/content/amazon/services/helpers/AwsSignatureHelper.java#L66-L79 |
akberc/ceylon-maven-plugin | src/main/java/com/dgwave/car/common/CeylonUtil.java | CeylonUtil.ceylonModuleName | public static String ceylonModuleName(final String groupId, final String artifactId, final String version,
final String classifier, final String extension) {
if (version == null || "".equals(version) || version.contains("-")) {
// TODO fix the '-' based on the new Herd rules
throw new IllegalArgumentException(" Null, empty, or '-' is not allowed in version");
}
StringBuilder name = new StringBuilder(STRING_BUILDER_SIZE);
name.append(ceylonModuleBaseName(groupId, artifactId))
.append(ARTIFACT_SEPARATOR).append(version);
if (extension != null) {
name.append(GROUP_SEPARATOR).append(extension);
} else {
name.append(GROUP_SEPARATOR).append("car");
}
return name.toString();
} | java | public static String ceylonModuleName(final String groupId, final String artifactId, final String version,
final String classifier, final String extension) {
if (version == null || "".equals(version) || version.contains("-")) {
// TODO fix the '-' based on the new Herd rules
throw new IllegalArgumentException(" Null, empty, or '-' is not allowed in version");
}
StringBuilder name = new StringBuilder(STRING_BUILDER_SIZE);
name.append(ceylonModuleBaseName(groupId, artifactId))
.append(ARTIFACT_SEPARATOR).append(version);
if (extension != null) {
name.append(GROUP_SEPARATOR).append(extension);
} else {
name.append(GROUP_SEPARATOR).append("car");
}
return name.toString();
} | [
"public",
"static",
"String",
"ceylonModuleName",
"(",
"final",
"String",
"groupId",
",",
"final",
"String",
"artifactId",
",",
"final",
"String",
"version",
",",
"final",
"String",
"classifier",
",",
"final",
"String",
"extension",
")",
"{",
"if",
"(",
"versi... | Comes up with a Ceylon module name based on Maven coordinates.
@param groupId Maven group id
@param artifactId Maven artifact id
@param version Version
@param classifier Sources, javadoc etc.
@param extension The extension or packaging of the artifact
@return String The module name | [
"Comes",
"up",
"with",
"a",
"Ceylon",
"module",
"name",
"based",
"on",
"Maven",
"coordinates",
"."
] | train | https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/common/CeylonUtil.java#L141-L161 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java | SegmentMetadataUpdateTransaction.updateStorageState | void updateStorageState(long storageLength, boolean storageSealed, boolean deleted, boolean storageDeleted) {
this.storageLength = storageLength;
this.sealedInStorage = storageSealed;
this.deleted = deleted;
this.deletedInStorage = storageDeleted;
this.isChanged = true;
} | java | void updateStorageState(long storageLength, boolean storageSealed, boolean deleted, boolean storageDeleted) {
this.storageLength = storageLength;
this.sealedInStorage = storageSealed;
this.deleted = deleted;
this.deletedInStorage = storageDeleted;
this.isChanged = true;
} | [
"void",
"updateStorageState",
"(",
"long",
"storageLength",
",",
"boolean",
"storageSealed",
",",
"boolean",
"deleted",
",",
"boolean",
"storageDeleted",
")",
"{",
"this",
".",
"storageLength",
"=",
"storageLength",
";",
"this",
".",
"sealedInStorage",
"=",
"stora... | Updates the transaction with the given state of the segment in storage.
This method is only meant to be used during recovery mode when we need to restore the state of a segment.
During normal operations, these values are set asynchronously by the Writer.
@param storageLength The value to set as StorageLength.
@param storageSealed The value to set as SealedInStorage.
@param deleted The value to set as Deleted.
@param storageDeleted The value to set as DeletedInStorage. | [
"Updates",
"the",
"transaction",
"with",
"the",
"given",
"state",
"of",
"the",
"segment",
"in",
"storage",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/logs/SegmentMetadataUpdateTransaction.java#L638-L644 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.deleteCompositeEntityChildAsync | public Observable<OperationStatus> deleteCompositeEntityChildAsync(UUID appId, String versionId, UUID cEntityId, UUID cChildId) {
return deleteCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, cChildId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | java | public Observable<OperationStatus> deleteCompositeEntityChildAsync(UUID appId, String versionId, UUID cEntityId, UUID cChildId) {
return deleteCompositeEntityChildWithServiceResponseAsync(appId, versionId, cEntityId, cChildId).map(new Func1<ServiceResponse<OperationStatus>, OperationStatus>() {
@Override
public OperationStatus call(ServiceResponse<OperationStatus> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"OperationStatus",
">",
"deleteCompositeEntityChildAsync",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"cEntityId",
",",
"UUID",
"cChildId",
")",
"{",
"return",
"deleteCompositeEntityChildWithServiceResponseAsync",
"(",
"a... | Deletes a composite entity extractor child from the application.
@param appId The application ID.
@param versionId The version ID.
@param cEntityId The composite entity extractor ID.
@param cChildId The hierarchical entity extractor child ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the OperationStatus object | [
"Deletes",
"a",
"composite",
"entity",
"extractor",
"child",
"from",
"the",
"application",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L7051-L7058 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.getDeletedStorageAccountAsync | public Observable<DeletedStorageBundle> getDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return getDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<DeletedStorageBundle>, DeletedStorageBundle>() {
@Override
public DeletedStorageBundle call(ServiceResponse<DeletedStorageBundle> response) {
return response.body();
}
});
} | java | public Observable<DeletedStorageBundle> getDeletedStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return getDeletedStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<DeletedStorageBundle>, DeletedStorageBundle>() {
@Override
public DeletedStorageBundle call(ServiceResponse<DeletedStorageBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"DeletedStorageBundle",
">",
"getDeletedStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"storageAccountName",
")",
"{",
"return",
"getDeletedStorageAccountWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName",... | Gets the specified deleted storage account.
The Get Deleted Storage Account operation returns the specified deleted storage account along with its attributes. This operation requires the storage/get permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the DeletedStorageBundle object | [
"Gets",
"the",
"specified",
"deleted",
"storage",
"account",
".",
"The",
"Get",
"Deleted",
"Storage",
"Account",
"operation",
"returns",
"the",
"specified",
"deleted",
"storage",
"account",
"along",
"with",
"its",
"attributes",
".",
"This",
"operation",
"requires"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L9284-L9291 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java | DefinitionsDocument.apply | @Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, DefinitionsDocument.Parameters params) {
Map<String, Model> definitions = params.definitions;
if (MapUtils.isNotEmpty(definitions)) {
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildDefinitionsTitle(markupDocBuilder, labels.getLabel(Labels.DEFINITIONS));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildDefinitionsSection(markupDocBuilder, definitions);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
}
return markupDocBuilder;
} | java | @Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, DefinitionsDocument.Parameters params) {
Map<String, Model> definitions = params.definitions;
if (MapUtils.isNotEmpty(definitions)) {
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
buildDefinitionsTitle(markupDocBuilder, labels.getLabel(Labels.DEFINITIONS));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
buildDefinitionsSection(markupDocBuilder, definitions);
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
applyDefinitionsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
}
return markupDocBuilder;
} | [
"@",
"Override",
"public",
"MarkupDocBuilder",
"apply",
"(",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"DefinitionsDocument",
".",
"Parameters",
"params",
")",
"{",
"Map",
"<",
"String",
",",
"Model",
">",
"definitions",
"=",
"params",
".",
"definitions",
";",
... | Builds the definitions MarkupDocument.
@return the definitions MarkupDocument | [
"Builds",
"the",
"definitions",
"MarkupDocument",
"."
] | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/document/DefinitionsDocument.java#L79-L91 |
williamwebb/alogger | BillingHelper/src/main/java/com/jug6ernaut/billing/Security.java | Security.verifyPurchase | public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
} | java | public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
} | [
"public",
"static",
"boolean",
"verifyPurchase",
"(",
"String",
"base64PublicKey",
",",
"String",
"signedData",
",",
"String",
"signature",
")",
"{",
"if",
"(",
"TextUtils",
".",
"isEmpty",
"(",
"signedData",
")",
"||",
"TextUtils",
".",
"isEmpty",
"(",
"base6... | Verifies that the data was signed with the given signature, and returns
the verified purchase. The data is in JSON format and signed
with a private key. The data also contains the {@link PurchaseState}
and product ID of the purchase.
@param base64PublicKey the base64-encoded public key to use for verifying.
@param signedData the signed JSON string (signed, not encrypted)
@param signature the signature for the data, signed with the private key | [
"Verifies",
"that",
"the",
"data",
"was",
"signed",
"with",
"the",
"given",
"signature",
"and",
"returns",
"the",
"verified",
"purchase",
".",
"The",
"data",
"is",
"in",
"JSON",
"format",
"and",
"signed",
"with",
"a",
"private",
"key",
".",
"The",
"data",
... | train | https://github.com/williamwebb/alogger/blob/61fca49e0b8d9c3a76c40da8883ac354b240351e/BillingHelper/src/main/java/com/jug6ernaut/billing/Security.java#L49-L58 |
alkacon/opencms-core | src/org/opencms/i18n/CmsVfsBundleManager.java | CmsVfsBundleManager.getNameAndLocale | private NameAndLocale getNameAndLocale(CmsResource bundleRes) {
String fileName = bundleRes.getName();
if (TYPE_PROPERTIES_BUNDLE.equals(OpenCms.getResourceManager().getResourceType(bundleRes).getTypeName())) {
String localeSuffix = CmsStringUtil.getLocaleSuffixForName(fileName);
if (localeSuffix == null) {
return new NameAndLocale(fileName, null);
} else {
String base = fileName.substring(
0,
fileName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));
Locale locale = CmsLocaleManager.getLocale(localeSuffix);
return new NameAndLocale(base, locale);
}
} else {
return new NameAndLocale(fileName, null);
}
} | java | private NameAndLocale getNameAndLocale(CmsResource bundleRes) {
String fileName = bundleRes.getName();
if (TYPE_PROPERTIES_BUNDLE.equals(OpenCms.getResourceManager().getResourceType(bundleRes).getTypeName())) {
String localeSuffix = CmsStringUtil.getLocaleSuffixForName(fileName);
if (localeSuffix == null) {
return new NameAndLocale(fileName, null);
} else {
String base = fileName.substring(
0,
fileName.lastIndexOf(localeSuffix) - (1 /* cut off trailing underscore, too*/));
Locale locale = CmsLocaleManager.getLocale(localeSuffix);
return new NameAndLocale(base, locale);
}
} else {
return new NameAndLocale(fileName, null);
}
} | [
"private",
"NameAndLocale",
"getNameAndLocale",
"(",
"CmsResource",
"bundleRes",
")",
"{",
"String",
"fileName",
"=",
"bundleRes",
".",
"getName",
"(",
")",
";",
"if",
"(",
"TYPE_PROPERTIES_BUNDLE",
".",
"equals",
"(",
"OpenCms",
".",
"getResourceManager",
"(",
... | Extracts the locale and base name from a resource's file name.<p>
@param bundleRes the resource for which to get the base name and locale
@return a bean containing the base name and locale | [
"Extracts",
"the",
"locale",
"and",
"base",
"name",
"from",
"a",
"resource",
"s",
"file",
"name",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsVfsBundleManager.java#L339-L356 |
Impetus/Kundera | src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java | CassandraDataHandlerBase.setUdtValue | private Object setUdtValue(Object entity, Object thriftColumnValue, MetamodelImpl metaModel, Attribute attribute)
{
List<FieldIdentifier> fieldNames = new ArrayList<FieldIdentifier>();
List<AbstractType<?>> fieldTypes = new ArrayList<AbstractType<?>>();
String val = null;
// get from cqlMetadata, details of types and names (for maintaining
// order)
Map<ByteBuffer, String> schemaTypes = this.clientBase.getCqlMetadata().getValue_types();
for (Map.Entry<ByteBuffer, String> schemaType : schemaTypes.entrySet())
{
UTF8Serializer utf8Serializer = UTF8Serializer.instance;
String key = utf8Serializer.deserialize((schemaType.getKey()));
if (key.equals(((AbstractAttribute) attribute).getJavaMember().getName()))
{
val = schemaType.getValue();
break;
}
}
UserType userType = null;
try
{
userType = UserType.getInstance(new TypeParser(val.substring(val.indexOf("UserType(") + 8, val.length())));
}
catch (ConfigurationException | SyntaxException e)
{
log.error(e.getMessage());
throw new KunderaException("Error while getting instance of UserType " + e);
}
fieldNames = userType.fieldNames();
fieldTypes = userType.allTypes();
Field field = (Field) ((AbstractAttribute) attribute).getJavaMember();
Class embeddedClass = ((AbstractAttribute) attribute).getBindableJavaType();
Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);
Object finalValue = populateEmbeddedRecursive((ByteBuffer.wrap((byte[]) thriftColumnValue)), fieldTypes,
fieldNames, embeddedObject, metaModel);
PropertyAccessorHelper.set(entity, field, finalValue);
return entity;
} | java | private Object setUdtValue(Object entity, Object thriftColumnValue, MetamodelImpl metaModel, Attribute attribute)
{
List<FieldIdentifier> fieldNames = new ArrayList<FieldIdentifier>();
List<AbstractType<?>> fieldTypes = new ArrayList<AbstractType<?>>();
String val = null;
// get from cqlMetadata, details of types and names (for maintaining
// order)
Map<ByteBuffer, String> schemaTypes = this.clientBase.getCqlMetadata().getValue_types();
for (Map.Entry<ByteBuffer, String> schemaType : schemaTypes.entrySet())
{
UTF8Serializer utf8Serializer = UTF8Serializer.instance;
String key = utf8Serializer.deserialize((schemaType.getKey()));
if (key.equals(((AbstractAttribute) attribute).getJavaMember().getName()))
{
val = schemaType.getValue();
break;
}
}
UserType userType = null;
try
{
userType = UserType.getInstance(new TypeParser(val.substring(val.indexOf("UserType(") + 8, val.length())));
}
catch (ConfigurationException | SyntaxException e)
{
log.error(e.getMessage());
throw new KunderaException("Error while getting instance of UserType " + e);
}
fieldNames = userType.fieldNames();
fieldTypes = userType.allTypes();
Field field = (Field) ((AbstractAttribute) attribute).getJavaMember();
Class embeddedClass = ((AbstractAttribute) attribute).getBindableJavaType();
Object embeddedObject = KunderaCoreUtils.createNewInstance(embeddedClass);
Object finalValue = populateEmbeddedRecursive((ByteBuffer.wrap((byte[]) thriftColumnValue)), fieldTypes,
fieldNames, embeddedObject, metaModel);
PropertyAccessorHelper.set(entity, field, finalValue);
return entity;
} | [
"private",
"Object",
"setUdtValue",
"(",
"Object",
"entity",
",",
"Object",
"thriftColumnValue",
",",
"MetamodelImpl",
"metaModel",
",",
"Attribute",
"attribute",
")",
"{",
"List",
"<",
"FieldIdentifier",
">",
"fieldNames",
"=",
"new",
"ArrayList",
"<",
"FieldIden... | Sets the udt value.
@param entity
the entity
@param thriftColumnValue
the thrift column value
@param metaModel
the meta model
@param attribute
the attribute
@return the object | [
"Sets",
"the",
"udt",
"value",
"."
] | train | https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/datahandler/CassandraDataHandlerBase.java#L1327-L1374 |
graknlabs/grakn | server/src/server/kb/concept/ElementFactory.java | ElementFactory.buildRelation | RelationImpl buildRelation(EdgeElement edge, RelationType type, Role owner, Role value) {
return getOrBuildConcept(edge, (e) -> RelationImpl.create(RelationEdge.create(type, owner, value, edge)));
} | java | RelationImpl buildRelation(EdgeElement edge, RelationType type, Role owner, Role value) {
return getOrBuildConcept(edge, (e) -> RelationImpl.create(RelationEdge.create(type, owner, value, edge)));
} | [
"RelationImpl",
"buildRelation",
"(",
"EdgeElement",
"edge",
",",
"RelationType",
"type",
",",
"Role",
"owner",
",",
"Role",
"value",
")",
"{",
"return",
"getOrBuildConcept",
"(",
"edge",
",",
"(",
"e",
")",
"-",
">",
"RelationImpl",
".",
"create",
"(",
"R... | Used to build a RelationEdge by ThingImpl when it needs to connect itself with an attribute (implicit relation) | [
"Used",
"to",
"build",
"a",
"RelationEdge",
"by",
"ThingImpl",
"when",
"it",
"needs",
"to",
"connect",
"itself",
"with",
"an",
"attribute",
"(",
"implicit",
"relation",
")"
] | train | https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/server/kb/concept/ElementFactory.java#L106-L108 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.