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
google/error-prone
core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java
ExpressionTemplate.replace
@Override public Fix replace(ExpressionTemplateMatch match) { Inliner inliner = match.createInliner(); Context context = inliner.getContext(); if (annotations().containsKey(UseImportPolicy.class)) { ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value()); } else { ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL); } int prec = getPrecedence(match.getLocation(), context); SuggestedFix.Builder fix = SuggestedFix.builder(); try { StringWriter writer = new StringWriter(); pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec); fix.replace(match.getLocation(), writer.toString()); } catch (CouldNotResolveImportException e) { logger.log(SEVERE, "Failure to resolve in replacement", e); } catch (IOException e) { throw new RuntimeException(e); } return addImports(inliner, fix); }
java
@Override public Fix replace(ExpressionTemplateMatch match) { Inliner inliner = match.createInliner(); Context context = inliner.getContext(); if (annotations().containsKey(UseImportPolicy.class)) { ImportPolicy.bind(context, annotations().getInstance(UseImportPolicy.class).value()); } else { ImportPolicy.bind(context, ImportPolicy.IMPORT_TOP_LEVEL); } int prec = getPrecedence(match.getLocation(), context); SuggestedFix.Builder fix = SuggestedFix.builder(); try { StringWriter writer = new StringWriter(); pretty(inliner.getContext(), writer).printExpr(expression().inline(inliner), prec); fix.replace(match.getLocation(), writer.toString()); } catch (CouldNotResolveImportException e) { logger.log(SEVERE, "Failure to resolve in replacement", e); } catch (IOException e) { throw new RuntimeException(e); } return addImports(inliner, fix); }
[ "@", "Override", "public", "Fix", "replace", "(", "ExpressionTemplateMatch", "match", ")", "{", "Inliner", "inliner", "=", "match", ".", "createInliner", "(", ")", ";", "Context", "context", "=", "inliner", ".", "getContext", "(", ")", ";", "if", "(", "ann...
Generates a {@link SuggestedFix} replacing the specified match (usually of another template) with this template.
[ "Generates", "a", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/refaster/ExpressionTemplate.java#L222-L243
Impetus/Kundera
src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java
CQLTranslator.buildEmbeddedValue
private void buildEmbeddedValue(final Object record, MetamodelImpl metaModel, StringBuilder embeddedValueBuilder, SingularAttribute attribute) { // TODO Auto-generated method stub Field field = (Field) attribute.getJavaMember(); EmbeddableType embeddableKey = metaModel.embeddable(field.getType()); Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field); if (embeddableKeyObj != null) { StringBuilder tempBuilder = new StringBuilder(); tempBuilder.append(Constants.OPEN_CURLY_BRACKET); for (Field embeddableColumn : field.getType().getDeclaredFields()) { if (!ReflectUtils.isTransientOrStatic(embeddableColumn)) { Attribute subAttribute = (SingularAttribute) embeddableKey.getAttribute(embeddableColumn.getName()); if (metaModel.isEmbeddable(((AbstractAttribute) subAttribute).getBindableJavaType())) { // construct map; recursive // send attribute buildEmbeddedValue(embeddableKeyObj, metaModel, tempBuilder, (SingularAttribute) subAttribute); } else { // append key value appendColumnName(tempBuilder, ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn .getName()))).getJPAColumnName()); tempBuilder.append(Constants.COLON); appendColumnValue(tempBuilder, embeddableKeyObj, embeddableColumn); } tempBuilder.append(Constants.COMMA); } } // strip last char and append '}' tempBuilder.deleteCharAt(tempBuilder.length() - 1); tempBuilder.append(Constants.CLOSE_CURLY_BRACKET); appendColumnName(embeddedValueBuilder, ((AbstractAttribute) attribute).getJPAColumnName()); embeddedValueBuilder.append(Constants.COLON); embeddedValueBuilder.append(tempBuilder); } else { embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1); } }
java
private void buildEmbeddedValue(final Object record, MetamodelImpl metaModel, StringBuilder embeddedValueBuilder, SingularAttribute attribute) { // TODO Auto-generated method stub Field field = (Field) attribute.getJavaMember(); EmbeddableType embeddableKey = metaModel.embeddable(field.getType()); Object embeddableKeyObj = PropertyAccessorHelper.getObject(record, field); if (embeddableKeyObj != null) { StringBuilder tempBuilder = new StringBuilder(); tempBuilder.append(Constants.OPEN_CURLY_BRACKET); for (Field embeddableColumn : field.getType().getDeclaredFields()) { if (!ReflectUtils.isTransientOrStatic(embeddableColumn)) { Attribute subAttribute = (SingularAttribute) embeddableKey.getAttribute(embeddableColumn.getName()); if (metaModel.isEmbeddable(((AbstractAttribute) subAttribute).getBindableJavaType())) { // construct map; recursive // send attribute buildEmbeddedValue(embeddableKeyObj, metaModel, tempBuilder, (SingularAttribute) subAttribute); } else { // append key value appendColumnName(tempBuilder, ((AbstractAttribute) (embeddableKey.getAttribute(embeddableColumn .getName()))).getJPAColumnName()); tempBuilder.append(Constants.COLON); appendColumnValue(tempBuilder, embeddableKeyObj, embeddableColumn); } tempBuilder.append(Constants.COMMA); } } // strip last char and append '}' tempBuilder.deleteCharAt(tempBuilder.length() - 1); tempBuilder.append(Constants.CLOSE_CURLY_BRACKET); appendColumnName(embeddedValueBuilder, ((AbstractAttribute) attribute).getJPAColumnName()); embeddedValueBuilder.append(Constants.COLON); embeddedValueBuilder.append(tempBuilder); } else { embeddedValueBuilder.deleteCharAt(embeddedValueBuilder.length() - 1); } }
[ "private", "void", "buildEmbeddedValue", "(", "final", "Object", "record", ",", "MetamodelImpl", "metaModel", ",", "StringBuilder", "embeddedValueBuilder", ",", "SingularAttribute", "attribute", ")", "{", "// TODO Auto-generated method stub", "Field", "field", "=", "(", ...
Builds the embedded value. @param record the record @param metaModel the meta model @param embeddedValueBuilder the embedded value builder @param attribute the attribute
[ "Builds", "the", "embedded", "value", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-cassandra/cassandra-core/src/main/java/com/impetus/client/cassandra/thrift/CQLTranslator.java#L684-L731
visallo/vertexium
elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java
Murmur3.hash64
public static long hash64(byte[] data, int offset, int length, int seed) { long hash = seed; final int nblocks = length >> 3; // body for (int i = 0; i < nblocks; i++) { final int i8 = i << 3; long k = ((long) data[offset + i8] & 0xff) | (((long) data[offset + i8 + 1] & 0xff) << 8) | (((long) data[offset + i8 + 2] & 0xff) << 16) | (((long) data[offset + i8 + 3] & 0xff) << 24) | (((long) data[offset + i8 + 4] & 0xff) << 32) | (((long) data[offset + i8 + 5] & 0xff) << 40) | (((long) data[offset + i8 + 6] & 0xff) << 48) | (((long) data[offset + i8 + 7] & 0xff) << 56); // mix functions k *= C1; k = Long.rotateLeft(k, R1); k *= C2; hash ^= k; hash = Long.rotateLeft(hash, R2) * M + N1; } // tail long k1 = 0; int tailStart = nblocks << 3; switch (length - tailStart) { case 7: k1 ^= ((long) data[offset + tailStart + 6] & 0xff) << 48; case 6: k1 ^= ((long) data[offset + tailStart + 5] & 0xff) << 40; case 5: k1 ^= ((long) data[offset + tailStart + 4] & 0xff) << 32; case 4: k1 ^= ((long) data[offset + tailStart + 3] & 0xff) << 24; case 3: k1 ^= ((long) data[offset + tailStart + 2] & 0xff) << 16; case 2: k1 ^= ((long) data[offset + tailStart + 1] & 0xff) << 8; case 1: k1 ^= ((long) data[offset + tailStart] & 0xff); k1 *= C1; k1 = Long.rotateLeft(k1, R1); k1 *= C2; hash ^= k1; } // finalization hash ^= length; hash = fmix64(hash); return hash; }
java
public static long hash64(byte[] data, int offset, int length, int seed) { long hash = seed; final int nblocks = length >> 3; // body for (int i = 0; i < nblocks; i++) { final int i8 = i << 3; long k = ((long) data[offset + i8] & 0xff) | (((long) data[offset + i8 + 1] & 0xff) << 8) | (((long) data[offset + i8 + 2] & 0xff) << 16) | (((long) data[offset + i8 + 3] & 0xff) << 24) | (((long) data[offset + i8 + 4] & 0xff) << 32) | (((long) data[offset + i8 + 5] & 0xff) << 40) | (((long) data[offset + i8 + 6] & 0xff) << 48) | (((long) data[offset + i8 + 7] & 0xff) << 56); // mix functions k *= C1; k = Long.rotateLeft(k, R1); k *= C2; hash ^= k; hash = Long.rotateLeft(hash, R2) * M + N1; } // tail long k1 = 0; int tailStart = nblocks << 3; switch (length - tailStart) { case 7: k1 ^= ((long) data[offset + tailStart + 6] & 0xff) << 48; case 6: k1 ^= ((long) data[offset + tailStart + 5] & 0xff) << 40; case 5: k1 ^= ((long) data[offset + tailStart + 4] & 0xff) << 32; case 4: k1 ^= ((long) data[offset + tailStart + 3] & 0xff) << 24; case 3: k1 ^= ((long) data[offset + tailStart + 2] & 0xff) << 16; case 2: k1 ^= ((long) data[offset + tailStart + 1] & 0xff) << 8; case 1: k1 ^= ((long) data[offset + tailStart] & 0xff); k1 *= C1; k1 = Long.rotateLeft(k1, R1); k1 *= C2; hash ^= k1; } // finalization hash ^= length; hash = fmix64(hash); return hash; }
[ "public", "static", "long", "hash64", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "length", ",", "int", "seed", ")", "{", "long", "hash", "=", "seed", ";", "final", "int", "nblocks", "=", "length", ">>", "3", ";", "// body", "f...
Murmur3 64-bit variant. This is essentially MSB 8 bytes of Murmur3 128-bit variant. @param data - input byte array @param length - length of array @param seed - seed. (default is 0) @return - hashcode
[ "Murmur3", "64", "-", "bit", "variant", ".", "This", "is", "essentially", "MSB", "8", "bytes", "of", "Murmur3", "128", "-", "bit", "variant", "." ]
train
https://github.com/visallo/vertexium/blob/bb132b5425ac168957667164e1409b78adbea769/elasticsearch5/src/main/java/org/vertexium/elasticsearch5/utils/Murmur3.java#L130-L183
javamelody/javamelody
javamelody-swing/src/main/java/net/bull/javamelody/swing/util/FastBlurFilter.java
FastBlurFilter.setPixels
private static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length >= w*h"); } final int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { final WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } }
java
private static void setPixels(BufferedImage img, int x, int y, int w, int h, int[] pixels) { if (pixels == null || w == 0 || h == 0) { return; } else if (pixels.length < w * h) { throw new IllegalArgumentException("pixels array must have a length >= w*h"); } final int imageType = img.getType(); if (imageType == BufferedImage.TYPE_INT_ARGB || imageType == BufferedImage.TYPE_INT_RGB) { final WritableRaster raster = img.getRaster(); raster.setDataElements(x, y, w, h, pixels); } else { // Unmanages the image img.setRGB(x, y, w, h, pixels, 0, w); } }
[ "private", "static", "void", "setPixels", "(", "BufferedImage", "img", ",", "int", "x", ",", "int", "y", ",", "int", "w", ",", "int", "h", ",", "int", "[", "]", "pixels", ")", "{", "if", "(", "pixels", "==", "null", "||", "w", "==", "0", "||", ...
<p>Writes a rectangular area of pixels in the destination <code>BufferedImage</code>. Calling this method on an image of type different from <code>BufferedImage.TYPE_INT_ARGB</code> and <code>BufferedImage.TYPE_INT_RGB</code> will unmanage the image.</p> @param img the destination image @param x the x location at which to start storing pixels @param y the y location at which to start storing pixels @param w the width of the rectangle of pixels to store @param h the height of the rectangle of pixels to store @param pixels an array of pixels, stored as integers @throws IllegalArgumentException is <code>pixels</code> is non-null and of length &lt; w*h
[ "<p", ">", "Writes", "a", "rectangular", "area", "of", "pixels", "in", "the", "destination", "<code", ">", "BufferedImage<", "/", "code", ">", ".", "Calling", "this", "method", "on", "an", "image", "of", "type", "different", "from", "<code", ">", "Buffered...
train
https://github.com/javamelody/javamelody/blob/18ad583ddeb5dcadd797dfda295409c6983ffd71/javamelody-swing/src/main/java/net/bull/javamelody/swing/util/FastBlurFilter.java#L141-L156
trellis-ldp/trellis
core/http/src/main/java/org/trellisldp/http/impl/MementoResource.java
MementoResource.getMementoLinks
public static Stream<Link> getMementoLinks(final String identifier, final SortedSet<Instant> mementos) { if (mementos.isEmpty()) { return empty(); } return concat(getTimeMap(identifier, mementos.first(), mementos.last()), mementos.stream().map(mementoToLink(identifier))); }
java
public static Stream<Link> getMementoLinks(final String identifier, final SortedSet<Instant> mementos) { if (mementos.isEmpty()) { return empty(); } return concat(getTimeMap(identifier, mementos.first(), mementos.last()), mementos.stream().map(mementoToLink(identifier))); }
[ "public", "static", "Stream", "<", "Link", ">", "getMementoLinks", "(", "final", "String", "identifier", ",", "final", "SortedSet", "<", "Instant", ">", "mementos", ")", "{", "if", "(", "mementos", ".", "isEmpty", "(", ")", ")", "{", "return", "empty", "...
Retrieve all of the Memento-related link headers given a collection of datetimes. @param identifier the public identifier for the resource @param mementos a collection of memento values @return a stream of link headers
[ "Retrieve", "all", "of", "the", "Memento", "-", "related", "link", "headers", "given", "a", "collection", "of", "datetimes", "." ]
train
https://github.com/trellis-ldp/trellis/blob/789fd7a3df86cab7ebba63e72bf4e58397e5f42d/core/http/src/main/java/org/trellisldp/http/impl/MementoResource.java#L170-L176
gosu-lang/gosu-lang
gosu-core-api/src/main/java/gw/util/GosuStringUtil.java
GosuStringUtil.indexOfAnyBut
public static int indexOfAnyBut(String str, char[] searchChars) { if (isEmpty(str) ||searchChars == null) { return -1; } outer : for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); for (int j = 0; j < searchChars.length; j++) { if (searchChars[j] == ch) { continue outer; } } return i; } return -1; }
java
public static int indexOfAnyBut(String str, char[] searchChars) { if (isEmpty(str) ||searchChars == null) { return -1; } outer : for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); for (int j = 0; j < searchChars.length; j++) { if (searchChars[j] == ch) { continue outer; } } return i; } return -1; }
[ "public", "static", "int", "indexOfAnyBut", "(", "String", "str", ",", "char", "[", "]", "searchChars", ")", "{", "if", "(", "isEmpty", "(", "str", ")", "||", "searchChars", "==", "null", ")", "{", "return", "-", "1", ";", "}", "outer", ":", "for", ...
<p>Search a String to find the first index of any character not in the given set of characters.</p> <p>A <code>null</code> String will return <code>-1</code>. A <code>null</code> or zero length search array will return <code>-1</code>.</p> <pre> GosuStringUtil.indexOfAnyBut(null, *) = -1 GosuStringUtil.indexOfAnyBut("", *) = -1 GosuStringUtil.indexOfAnyBut(*, null) = -1 GosuStringUtil.indexOfAnyBut(*, []) = -1 GosuStringUtil.indexOfAnyBut("zzabyycdxx",'za') = 3 GosuStringUtil.indexOfAnyBut("zzabyycdxx", '') = 0 GosuStringUtil.indexOfAnyBut("aba", 'ab') = -1 </pre> @param str the String to check, may be null @param searchChars the chars to search for, may be null @return the index of any of the chars, -1 if no match or null input @since 2.0
[ "<p", ">", "Search", "a", "String", "to", "find", "the", "first", "index", "of", "any", "character", "not", "in", "the", "given", "set", "of", "characters", ".", "<", "/", "p", ">" ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core-api/src/main/java/gw/util/GosuStringUtil.java#L1209-L1223
OpenLiberty/open-liberty
dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/servers/ServerBootstrapUtils.java
ServerBootstrapUtils.writeBootstrapProperties
public void writeBootstrapProperties(LibertyServer server, Map<String, String> miscParms) throws Exception { String thisMethod = "writeBootstrapProperties"; loggingUtils.printMethodName(thisMethod); if (miscParms == null) { return; } String bootPropFilePath = getBootstrapPropertiesFilePath(server); for (Map.Entry<String, String> entry : miscParms.entrySet()) { appendBootstrapPropertyToFile(bootPropFilePath, entry.getKey(), entry.getValue()); } }
java
public void writeBootstrapProperties(LibertyServer server, Map<String, String> miscParms) throws Exception { String thisMethod = "writeBootstrapProperties"; loggingUtils.printMethodName(thisMethod); if (miscParms == null) { return; } String bootPropFilePath = getBootstrapPropertiesFilePath(server); for (Map.Entry<String, String> entry : miscParms.entrySet()) { appendBootstrapPropertyToFile(bootPropFilePath, entry.getKey(), entry.getValue()); } }
[ "public", "void", "writeBootstrapProperties", "(", "LibertyServer", "server", ",", "Map", "<", "String", ",", "String", ">", "miscParms", ")", "throws", "Exception", "{", "String", "thisMethod", "=", "\"writeBootstrapProperties\"", ";", "loggingUtils", ".", "printMe...
Writes each of the specified bootstrap properties and values to the provided server's bootstrap.properties file.
[ "Writes", "each", "of", "the", "specified", "bootstrap", "properties", "and", "values", "to", "the", "provided", "server", "s", "bootstrap", ".", "properties", "file", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.fat.common/src/com/ibm/ws/security/fat/common/servers/ServerBootstrapUtils.java#L29-L40
larsga/Duke
duke-core/src/main/java/no/priv/garshol/duke/utils/PropertyUtils.java
PropertyUtils.get
public static String get(Properties props, String name, String defval) { String value = props.getProperty(name); if (value == null) value = defval; return value; }
java
public static String get(Properties props, String name, String defval) { String value = props.getProperty(name); if (value == null) value = defval; return value; }
[ "public", "static", "String", "get", "(", "Properties", "props", ",", "String", "name", ",", "String", "defval", ")", "{", "String", "value", "=", "props", ".", "getProperty", "(", "name", ")", ";", "if", "(", "value", "==", "null", ")", "value", "=", ...
Returns the value of an optional property, if the property is set. If it is not set defval is returned.
[ "Returns", "the", "value", "of", "an", "optional", "property", "if", "the", "property", "is", "set", ".", "If", "it", "is", "not", "set", "defval", "is", "returned", "." ]
train
https://github.com/larsga/Duke/blob/6263f9c6e984c26362a76241c7c7ea3bb4469bac/duke-core/src/main/java/no/priv/garshol/duke/utils/PropertyUtils.java#L28-L33
exoplatform/jcr
exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LnkProducer.java
LnkProducer.produceLink
@GET @Path("/{linkFilePath}/") @Produces("application/octet-stream") public Response produceLink(@PathParam("linkFilePath") String linkFilePath, @QueryParam("path") String path, @Context UriInfo uriInfo) { String host = uriInfo.getRequestUri().getHost(); String uri = uriInfo.getBaseUri().toString(); try { LinkGenerator linkGenerator = new LinkGenerator(host, uri, path); byte[] content = linkGenerator.generateLinkContent(); return Response.ok(content, MediaType.APPLICATION_OCTET_STREAM).header(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length)).build(); } catch (IOException exc) { LOG.error(exc.getMessage(), exc); throw new WebApplicationException(exc); } }
java
@GET @Path("/{linkFilePath}/") @Produces("application/octet-stream") public Response produceLink(@PathParam("linkFilePath") String linkFilePath, @QueryParam("path") String path, @Context UriInfo uriInfo) { String host = uriInfo.getRequestUri().getHost(); String uri = uriInfo.getBaseUri().toString(); try { LinkGenerator linkGenerator = new LinkGenerator(host, uri, path); byte[] content = linkGenerator.generateLinkContent(); return Response.ok(content, MediaType.APPLICATION_OCTET_STREAM).header(HttpHeaders.CONTENT_LENGTH, Integer.toString(content.length)).build(); } catch (IOException exc) { LOG.error(exc.getMessage(), exc); throw new WebApplicationException(exc); } }
[ "@", "GET", "@", "Path", "(", "\"/{linkFilePath}/\"", ")", "@", "Produces", "(", "\"application/octet-stream\"", ")", "public", "Response", "produceLink", "(", "@", "PathParam", "(", "\"linkFilePath\"", ")", "String", "linkFilePath", ",", "@", "QueryParam", "(", ...
Produces a link. @param linkFilePath link file path @param path path to resource @param uriInfo uriInfo @return generated link @response {code} "content" : the generated link file. {code} @LevelAPI Experimental
[ "Produces", "a", "link", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LnkProducer.java#L78-L103
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.findBestNameForUrlNameMapping
protected String findBestNameForUrlNameMapping(CmsDbContext dbc, String name, CmsUUID structureId) throws CmsDataAccessException { List<CmsUrlNameMappingEntry> entriesStartingWithName = getVfsDriver(dbc).readUrlNameMappingEntries( dbc, false, CmsUrlNameMappingFilter.ALL.filterNamePattern(name + "%").filterRejectStructureId(structureId)); Set<String> usedNames = new HashSet<String>(); for (CmsUrlNameMappingEntry entry : entriesStartingWithName) { usedNames.add(entry.getName()); } int counter = 0; String numberedName; do { numberedName = getNumberedName(name, counter); counter += 1; } while (usedNames.contains(numberedName)); return numberedName; }
java
protected String findBestNameForUrlNameMapping(CmsDbContext dbc, String name, CmsUUID structureId) throws CmsDataAccessException { List<CmsUrlNameMappingEntry> entriesStartingWithName = getVfsDriver(dbc).readUrlNameMappingEntries( dbc, false, CmsUrlNameMappingFilter.ALL.filterNamePattern(name + "%").filterRejectStructureId(structureId)); Set<String> usedNames = new HashSet<String>(); for (CmsUrlNameMappingEntry entry : entriesStartingWithName) { usedNames.add(entry.getName()); } int counter = 0; String numberedName; do { numberedName = getNumberedName(name, counter); counter += 1; } while (usedNames.contains(numberedName)); return numberedName; }
[ "protected", "String", "findBestNameForUrlNameMapping", "(", "CmsDbContext", "dbc", ",", "String", "name", ",", "CmsUUID", "structureId", ")", "throws", "CmsDataAccessException", "{", "List", "<", "CmsUrlNameMappingEntry", ">", "entriesStartingWithName", "=", "getVfsDrive...
Helper method for finding the 'best' URL name to use for a new URL name mapping.<p> Since the name given as a parameter may be already used, this method will try to append numeric suffixes to the name to find a mapping name which is not used.<p> @param dbc the current database context @param name the name of the mapping @param structureId the structure id to which the name is mapped @return the best name which was found for the new mapping @throws CmsDataAccessException if something goes wrong
[ "Helper", "method", "for", "finding", "the", "best", "URL", "name", "to", "use", "for", "a", "new", "URL", "name", "mapping", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L10465-L10483
joniles/mpxj
src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java
PrimaveraReader.processUserDefinedFields
public void processUserDefinedFields(List<Row> fields, List<Row> values) { // Process fields Map<Integer, String> tableNameMap = new HashMap<Integer, String>(); for (Row row : fields) { Integer fieldId = row.getInteger("udf_type_id"); String tableName = row.getString("table_name"); tableNameMap.put(fieldId, tableName); FieldTypeClass fieldType = FIELD_TYPE_MAP.get(tableName); if (fieldType != null) { String fieldDataType = row.getString("logical_data_type"); String fieldName = row.getString("udf_type_label"); m_udfFields.put(fieldId, fieldName); addUserDefinedField(fieldType, UserFieldDataType.valueOf(fieldDataType), fieldName); } } // Process values for (Row row : values) { Integer typeID = row.getInteger("udf_type_id"); String tableName = tableNameMap.get(typeID); Map<Integer, List<Row>> tableData = m_udfValues.get(tableName); if (tableData == null) { tableData = new HashMap<Integer, List<Row>>(); m_udfValues.put(tableName, tableData); } Integer id = row.getInteger("fk_id"); List<Row> list = tableData.get(id); if (list == null) { list = new ArrayList<Row>(); tableData.put(id, list); } list.add(row); } }
java
public void processUserDefinedFields(List<Row> fields, List<Row> values) { // Process fields Map<Integer, String> tableNameMap = new HashMap<Integer, String>(); for (Row row : fields) { Integer fieldId = row.getInteger("udf_type_id"); String tableName = row.getString("table_name"); tableNameMap.put(fieldId, tableName); FieldTypeClass fieldType = FIELD_TYPE_MAP.get(tableName); if (fieldType != null) { String fieldDataType = row.getString("logical_data_type"); String fieldName = row.getString("udf_type_label"); m_udfFields.put(fieldId, fieldName); addUserDefinedField(fieldType, UserFieldDataType.valueOf(fieldDataType), fieldName); } } // Process values for (Row row : values) { Integer typeID = row.getInteger("udf_type_id"); String tableName = tableNameMap.get(typeID); Map<Integer, List<Row>> tableData = m_udfValues.get(tableName); if (tableData == null) { tableData = new HashMap<Integer, List<Row>>(); m_udfValues.put(tableName, tableData); } Integer id = row.getInteger("fk_id"); List<Row> list = tableData.get(id); if (list == null) { list = new ArrayList<Row>(); tableData.put(id, list); } list.add(row); } }
[ "public", "void", "processUserDefinedFields", "(", "List", "<", "Row", ">", "fields", ",", "List", "<", "Row", ">", "values", ")", "{", "// Process fields", "Map", "<", "Integer", ",", "String", ">", "tableNameMap", "=", "new", "HashMap", "<", "Integer", "...
Process User Defined Fields (UDF). @param fields field definitions @param values field values
[ "Process", "User", "Defined", "Fields", "(", "UDF", ")", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/primavera/PrimaveraReader.java#L225-L267
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java
IntegralImageOps.block_unsafe
public static float block_unsafe(GrayF32 integral , int x0 , int y0 , int x1 , int y1 ) { return ImplIntegralImageOps.block_unsafe(integral,x0,y0,x1,y1); }
java
public static float block_unsafe(GrayF32 integral , int x0 , int y0 , int x1 , int y1 ) { return ImplIntegralImageOps.block_unsafe(integral,x0,y0,x1,y1); }
[ "public", "static", "float", "block_unsafe", "(", "GrayF32", "integral", ",", "int", "x0", ",", "int", "y0", ",", "int", "x1", ",", "int", "y1", ")", "{", "return", "ImplIntegralImageOps", ".", "block_unsafe", "(", "integral", ",", "x0", ",", "y0", ",", ...
<p> Computes the value of a block inside an integral image without bounds checking. The block is defined as follows: x0 &lt; x &le; x1 and y0 &lt; y &le; y1. </p> @param integral Integral image. @param x0 Lower bound of the block. Exclusive. @param y0 Lower bound of the block. Exclusive. @param x1 Upper bound of the block. Inclusive. @param y1 Upper bound of the block. Inclusive. @return Value inside the block.
[ "<p", ">", "Computes", "the", "value", "of", "a", "block", "inside", "an", "integral", "image", "without", "bounds", "checking", ".", "The", "block", "is", "defined", "as", "follows", ":", "x0", "&lt", ";", "x", "&le", ";", "x1", "and", "y0", "&lt", ...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/transform/ii/IntegralImageOps.java#L390-L393
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/SimpleBeanBoundTableModel.java
SimpleBeanBoundTableModel.getBeanPropertyValue
protected Object getBeanPropertyValue(final String property, final Object bean) { if (bean == null) { return null; } if (".".equals(property)) { return bean; } try { Object data = PropertyUtils.getProperty(bean, property); return data; } catch (Exception e) { LOG.error("Failed to get bean property " + property + " on " + bean, e); return null; } }
java
protected Object getBeanPropertyValue(final String property, final Object bean) { if (bean == null) { return null; } if (".".equals(property)) { return bean; } try { Object data = PropertyUtils.getProperty(bean, property); return data; } catch (Exception e) { LOG.error("Failed to get bean property " + property + " on " + bean, e); return null; } }
[ "protected", "Object", "getBeanPropertyValue", "(", "final", "String", "property", ",", "final", "Object", "bean", ")", "{", "if", "(", "bean", "==", "null", ")", "{", "return", "null", ";", "}", "if", "(", "\".\"", ".", "equals", "(", "property", ")", ...
Get the bean property value. @param property the bean property @param bean the bean @return the bean property value
[ "Get", "the", "bean", "property", "value", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/SimpleBeanBoundTableModel.java#L521-L537
apache/flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/ParquetInputFormat.java
ParquetInputFormat.getReadSchema
private MessageType getReadSchema(MessageType fileSchema, Path filePath) { RowTypeInfo fileTypeInfo = (RowTypeInfo) ParquetSchemaConverter.fromParquetType(fileSchema); List<Type> types = new ArrayList<>(); for (int i = 0; i < fieldNames.length; ++i) { String readFieldName = fieldNames[i]; TypeInformation<?> readFieldType = fieldTypes[i]; if (fileTypeInfo.getFieldIndex(readFieldName) < 0) { if (!skipWrongSchemaFileSplit) { throw new IllegalArgumentException("Field " + readFieldName + " cannot be found in schema of " + " Parquet file: " + filePath + "."); } else { this.skipThisSplit = true; return fileSchema; } } if (!readFieldType.equals(fileTypeInfo.getTypeAt(readFieldName))) { if (!skipWrongSchemaFileSplit) { throw new IllegalArgumentException("Expecting type " + readFieldType + " for field " + readFieldName + " but found type " + fileTypeInfo.getTypeAt(readFieldName) + " in Parquet file: " + filePath + "."); } else { this.skipThisSplit = true; return fileSchema; } } types.add(fileSchema.getType(readFieldName)); } return new MessageType(fileSchema.getName(), types); }
java
private MessageType getReadSchema(MessageType fileSchema, Path filePath) { RowTypeInfo fileTypeInfo = (RowTypeInfo) ParquetSchemaConverter.fromParquetType(fileSchema); List<Type> types = new ArrayList<>(); for (int i = 0; i < fieldNames.length; ++i) { String readFieldName = fieldNames[i]; TypeInformation<?> readFieldType = fieldTypes[i]; if (fileTypeInfo.getFieldIndex(readFieldName) < 0) { if (!skipWrongSchemaFileSplit) { throw new IllegalArgumentException("Field " + readFieldName + " cannot be found in schema of " + " Parquet file: " + filePath + "."); } else { this.skipThisSplit = true; return fileSchema; } } if (!readFieldType.equals(fileTypeInfo.getTypeAt(readFieldName))) { if (!skipWrongSchemaFileSplit) { throw new IllegalArgumentException("Expecting type " + readFieldType + " for field " + readFieldName + " but found type " + fileTypeInfo.getTypeAt(readFieldName) + " in Parquet file: " + filePath + "."); } else { this.skipThisSplit = true; return fileSchema; } } types.add(fileSchema.getType(readFieldName)); } return new MessageType(fileSchema.getName(), types); }
[ "private", "MessageType", "getReadSchema", "(", "MessageType", "fileSchema", ",", "Path", "filePath", ")", "{", "RowTypeInfo", "fileTypeInfo", "=", "(", "RowTypeInfo", ")", "ParquetSchemaConverter", ".", "fromParquetType", "(", "fileSchema", ")", ";", "List", "<", ...
Generates and returns the read schema based on the projected fields for a given file. @param fileSchema The schema of the given file. @param filePath The path of the given file. @return The read schema based on the given file's schema and the projected fields.
[ "Generates", "and", "returns", "the", "read", "schema", "based", "on", "the", "projected", "fields", "for", "a", "given", "file", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/ParquetInputFormat.java#L248-L278
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.getNetworkSettingsAsync
public Observable<NetworkSettingsInner> getNetworkSettingsAsync(String deviceName, String resourceGroupName) { return getNetworkSettingsWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<NetworkSettingsInner>, NetworkSettingsInner>() { @Override public NetworkSettingsInner call(ServiceResponse<NetworkSettingsInner> response) { return response.body(); } }); }
java
public Observable<NetworkSettingsInner> getNetworkSettingsAsync(String deviceName, String resourceGroupName) { return getNetworkSettingsWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<NetworkSettingsInner>, NetworkSettingsInner>() { @Override public NetworkSettingsInner call(ServiceResponse<NetworkSettingsInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NetworkSettingsInner", ">", "getNetworkSettingsAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "return", "getNetworkSettingsWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "...
Gets the network settings of the specified data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkSettingsInner object
[ "Gets", "the", "network", "settings", "of", "the", "specified", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1622-L1629
Alluxio/alluxio
core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java
BlockLockManager.lockBlock
public long lockBlock(long sessionId, long blockId, BlockLockType blockLockType) { ClientRWLock blockLock = getBlockLock(blockId); Lock lock; if (blockLockType == BlockLockType.READ) { lock = blockLock.readLock(); } else { // Make sure the session isn't already holding the block lock. if (sessionHoldsLock(sessionId, blockId)) { throw new IllegalStateException(String .format("Session %s attempted to take a write lock on block %s, but the session already" + " holds a lock on the block", sessionId, blockId)); } lock = blockLock.writeLock(); } lock.lock(); try { long lockId = LOCK_ID_GEN.getAndIncrement(); synchronized (mSharedMapsLock) { mLockIdToRecordMap.put(lockId, new LockRecord(sessionId, blockId, lock)); Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { mSessionIdToLockIdsMap.put(sessionId, Sets.newHashSet(lockId)); } else { sessionLockIds.add(lockId); } } return lockId; } catch (RuntimeException e) { // If an unexpected exception occurs, we should release the lock to be conservative. unlock(lock, blockId); throw e; } }
java
public long lockBlock(long sessionId, long blockId, BlockLockType blockLockType) { ClientRWLock blockLock = getBlockLock(blockId); Lock lock; if (blockLockType == BlockLockType.READ) { lock = blockLock.readLock(); } else { // Make sure the session isn't already holding the block lock. if (sessionHoldsLock(sessionId, blockId)) { throw new IllegalStateException(String .format("Session %s attempted to take a write lock on block %s, but the session already" + " holds a lock on the block", sessionId, blockId)); } lock = blockLock.writeLock(); } lock.lock(); try { long lockId = LOCK_ID_GEN.getAndIncrement(); synchronized (mSharedMapsLock) { mLockIdToRecordMap.put(lockId, new LockRecord(sessionId, blockId, lock)); Set<Long> sessionLockIds = mSessionIdToLockIdsMap.get(sessionId); if (sessionLockIds == null) { mSessionIdToLockIdsMap.put(sessionId, Sets.newHashSet(lockId)); } else { sessionLockIds.add(lockId); } } return lockId; } catch (RuntimeException e) { // If an unexpected exception occurs, we should release the lock to be conservative. unlock(lock, blockId); throw e; } }
[ "public", "long", "lockBlock", "(", "long", "sessionId", ",", "long", "blockId", ",", "BlockLockType", "blockLockType", ")", "{", "ClientRWLock", "blockLock", "=", "getBlockLock", "(", "blockId", ")", ";", "Lock", "lock", ";", "if", "(", "blockLockType", "==",...
Locks a block. Note that even if this block does not exist, a lock id is still returned. If all {@link PropertyKey#WORKER_TIERED_STORE_BLOCK_LOCKS} are already in use and no lock has been allocated for the specified block, this method will need to wait until a lock can be acquired from the lock pool. @param sessionId the session id @param blockId the block id @param blockLockType {@link BlockLockType#READ} or {@link BlockLockType#WRITE} @return lock id
[ "Locks", "a", "block", ".", "Note", "that", "even", "if", "this", "block", "does", "not", "exist", "a", "lock", "id", "is", "still", "returned", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockLockManager.java#L100-L132
mikepenz/FastAdapter
library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterDiffUtil.java
FastAdapterDiffUtil.calculateDiff
public static <A extends ModelAdapter<Model, Item>, Model, Item extends IItem> DiffUtil.DiffResult calculateDiff(final A adapter, final List<Item> items, final DiffCallback<Item> callback) { return calculateDiff(adapter, items, callback, true); }
java
public static <A extends ModelAdapter<Model, Item>, Model, Item extends IItem> DiffUtil.DiffResult calculateDiff(final A adapter, final List<Item> items, final DiffCallback<Item> callback) { return calculateDiff(adapter, items, callback, true); }
[ "public", "static", "<", "A", "extends", "ModelAdapter", "<", "Model", ",", "Item", ">", ",", "Model", ",", "Item", "extends", "IItem", ">", "DiffUtil", ".", "DiffResult", "calculateDiff", "(", "final", "A", "adapter", ",", "final", "List", "<", "Item", ...
convenient function for {@link #calculateDiff(ModelAdapter, List, DiffCallback, boolean)} @return the {@link androidx.recyclerview.widget.DiffUtil.DiffResult} computed.
[ "convenient", "function", "for", "{", "@link", "#calculateDiff", "(", "ModelAdapter", "List", "DiffCallback", "boolean", ")", "}" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterDiffUtil.java#L117-L119
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java
VirtualMachineScaleSetExtensionsInner.beginCreateOrUpdateAsync
public Observable<VirtualMachineScaleSetExtensionInner> beginCreateOrUpdateAsync(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, VirtualMachineScaleSetExtensionInner extensionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters).map(new Func1<ServiceResponse<VirtualMachineScaleSetExtensionInner>, VirtualMachineScaleSetExtensionInner>() { @Override public VirtualMachineScaleSetExtensionInner call(ServiceResponse<VirtualMachineScaleSetExtensionInner> response) { return response.body(); } }); }
java
public Observable<VirtualMachineScaleSetExtensionInner> beginCreateOrUpdateAsync(String resourceGroupName, String vmScaleSetName, String vmssExtensionName, VirtualMachineScaleSetExtensionInner extensionParameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters).map(new Func1<ServiceResponse<VirtualMachineScaleSetExtensionInner>, VirtualMachineScaleSetExtensionInner>() { @Override public VirtualMachineScaleSetExtensionInner call(ServiceResponse<VirtualMachineScaleSetExtensionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualMachineScaleSetExtensionInner", ">", "beginCreateOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "vmScaleSetName", ",", "String", "vmssExtensionName", ",", "VirtualMachineScaleSetExtensionInner", "extensionParameters", ")", ...
The operation to create or update an extension. @param resourceGroupName The name of the resource group. @param vmScaleSetName The name of the VM scale set where the extension should be create or updated. @param vmssExtensionName The name of the VM scale set extension. @param extensionParameters Parameters supplied to the Create VM scale set Extension operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the VirtualMachineScaleSetExtensionInner object
[ "The", "operation", "to", "create", "or", "update", "an", "extension", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachineScaleSetExtensionsInner.java#L219-L226
eclipse/xtext-lib
org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java
IteratorExtensions.maxBy
public static <T, C extends Comparable<? super C>> T maxBy(final Iterator<T> iterator, final Function1<? super T, C> compareBy) { if (compareBy == null) throw new NullPointerException("compareBy"); return max(iterator, new KeyComparator<T, C>(compareBy)); }
java
public static <T, C extends Comparable<? super C>> T maxBy(final Iterator<T> iterator, final Function1<? super T, C> compareBy) { if (compareBy == null) throw new NullPointerException("compareBy"); return max(iterator, new KeyComparator<T, C>(compareBy)); }
[ "public", "static", "<", "T", ",", "C", "extends", "Comparable", "<", "?", "super", "C", ">", ">", "T", "maxBy", "(", "final", "Iterator", "<", "T", ">", "iterator", ",", "final", "Function1", "<", "?", "super", "T", ",", "C", ">", "compareBy", ")"...
Finds the element that yields the maximum value when passed to <code>compareBy</code> If there are several maxima, the first one will be returned. @param iterator the elements to find the maximum of. May not be <code>null</code>. @param compareBy a function that returns a comparable characteristic to compare the elements by. May not be <code>null</code>. @return the maximum @throws NoSuchElementException if the iterator is empty @since 2.7
[ "Finds", "the", "element", "that", "yields", "the", "maximum", "value", "when", "passed", "to", "<code", ">", "compareBy<", "/", "code", ">", "If", "there", "are", "several", "maxima", "the", "first", "one", "will", "be", "returned", "." ]
train
https://github.com/eclipse/xtext-lib/blob/7063572e1f1bd713a3aa53bdf3a8dc60e25c169a/org.eclipse.xtext.xbase.lib/src/org/eclipse/xtext/xbase/lib/IteratorExtensions.java#L1017-L1021
fcrepo4/fcrepo4
fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/responses/ViewHelpers.java
ViewHelpers.isVersionedNode
public boolean isVersionedNode(final Graph graph, final Node subject) { return listObjects(graph, subject, RDF.type.asNode()).toList().stream().map(Node::getURI) .anyMatch((MEMENTO_TYPE)::equals); }
java
public boolean isVersionedNode(final Graph graph, final Node subject) { return listObjects(graph, subject, RDF.type.asNode()).toList().stream().map(Node::getURI) .anyMatch((MEMENTO_TYPE)::equals); }
[ "public", "boolean", "isVersionedNode", "(", "final", "Graph", "graph", ",", "final", "Node", "subject", ")", "{", "return", "listObjects", "(", "graph", ",", "subject", ",", "RDF", ".", "type", ".", "asNode", "(", ")", ")", ".", "toList", "(", ")", "....
Determines whether the subject is of type memento:Memento. @param graph the graph @param subject the subject @return whether the subject is a versioned node
[ "Determines", "whether", "the", "subject", "is", "of", "type", "memento", ":", "Memento", "." ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-commons/src/main/java/org/fcrepo/http/commons/responses/ViewHelpers.java#L213-L216
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/BootstrapTools.java
BootstrapTools.writeConfiguration
public static void writeConfiguration(Configuration cfg, File file) throws IOException { try (FileWriter fwrt = new FileWriter(file); PrintWriter out = new PrintWriter(fwrt)) { for (String key : cfg.keySet()) { String value = cfg.getString(key, null); out.print(key); out.print(": "); out.println(value); } } }
java
public static void writeConfiguration(Configuration cfg, File file) throws IOException { try (FileWriter fwrt = new FileWriter(file); PrintWriter out = new PrintWriter(fwrt)) { for (String key : cfg.keySet()) { String value = cfg.getString(key, null); out.print(key); out.print(": "); out.println(value); } } }
[ "public", "static", "void", "writeConfiguration", "(", "Configuration", "cfg", ",", "File", "file", ")", "throws", "IOException", "{", "try", "(", "FileWriter", "fwrt", "=", "new", "FileWriter", "(", "file", ")", ";", "PrintWriter", "out", "=", "new", "Print...
Writes a Flink YAML config file from a Flink Configuration object. @param cfg The Flink config @param file The File to write to @throws IOException
[ "Writes", "a", "Flink", "YAML", "config", "file", "from", "a", "Flink", "Configuration", "object", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/clusterframework/BootstrapTools.java#L311-L321
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/HashUtils.java
HashUtils.getSHA256String
public static String getSHA256String(String str) { MessageDigest messageDigest = getMessageDigest(SHA256); return getHashString(str, messageDigest); }
java
public static String getSHA256String(String str) { MessageDigest messageDigest = getMessageDigest(SHA256); return getHashString(str, messageDigest); }
[ "public", "static", "String", "getSHA256String", "(", "String", "str", ")", "{", "MessageDigest", "messageDigest", "=", "getMessageDigest", "(", "SHA256", ")", ";", "return", "getHashString", "(", "str", ",", "messageDigest", ")", ";", "}" ]
Calculate SHA-256 hash of a String @param str - the String to hash @return the SHA-256 hash value
[ "Calculate", "SHA", "-", "256", "hash", "of", "a", "String" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/HashUtils.java#L58-L61
alexvasilkov/AndroidCommons
library/src/main/java/com/alexvasilkov/android/commons/texts/Fonts.java
Fonts.apply
public static void apply(@NonNull TextView textView, @StringRes int fontStringId) { apply(textView, textView.getContext().getString(fontStringId)); }
java
public static void apply(@NonNull TextView textView, @StringRes int fontStringId) { apply(textView, textView.getContext().getString(fontStringId)); }
[ "public", "static", "void", "apply", "(", "@", "NonNull", "TextView", "textView", ",", "@", "StringRes", "int", "fontStringId", ")", "{", "apply", "(", "textView", ",", "textView", ".", "getContext", "(", ")", ".", "getString", "(", "fontStringId", ")", ")...
Applies font to provided TextView.<br/> Note: this class will only accept fonts under <code>fonts/</code> directory and fonts starting with <code>font:</code> prefix.
[ "Applies", "font", "to", "provided", "TextView", ".", "<br", "/", ">", "Note", ":", "this", "class", "will", "only", "accept", "fonts", "under", "<code", ">", "fonts", "/", "<", "/", "code", ">", "directory", "and", "fonts", "starting", "with", "<code", ...
train
https://github.com/alexvasilkov/AndroidCommons/blob/aca9f6d5acfc6bd3694984b7f89956e1a0146ddb/library/src/main/java/com/alexvasilkov/android/commons/texts/Fonts.java#L93-L95
alamkanak/Android-Week-View
library/src/main/java/com/alamkanak/weekview/WeekView.java
WeekView.getDateTimeInterpreter
public DateTimeInterpreter getDateTimeInterpreter() { if (mDateTimeInterpreter == null) { mDateTimeInterpreter = new DateTimeInterpreter() { @Override public String interpretDate(Calendar date) { try { SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault()); return sdf.format(date.getTime()).toUpperCase(); } catch (Exception e) { e.printStackTrace(); return ""; } } @Override public String interpretTime(int hour) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, 0); try { SimpleDateFormat sdf = DateFormat.is24HourFormat(getContext()) ? new SimpleDateFormat("HH:mm", Locale.getDefault()) : new SimpleDateFormat("hh a", Locale.getDefault()); return sdf.format(calendar.getTime()); } catch (Exception e) { e.printStackTrace(); return ""; } } }; } return mDateTimeInterpreter; }
java
public DateTimeInterpreter getDateTimeInterpreter() { if (mDateTimeInterpreter == null) { mDateTimeInterpreter = new DateTimeInterpreter() { @Override public String interpretDate(Calendar date) { try { SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", Locale.getDefault()) : new SimpleDateFormat("EEE M/dd", Locale.getDefault()); return sdf.format(date.getTime()).toUpperCase(); } catch (Exception e) { e.printStackTrace(); return ""; } } @Override public String interpretTime(int hour) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, 0); try { SimpleDateFormat sdf = DateFormat.is24HourFormat(getContext()) ? new SimpleDateFormat("HH:mm", Locale.getDefault()) : new SimpleDateFormat("hh a", Locale.getDefault()); return sdf.format(calendar.getTime()); } catch (Exception e) { e.printStackTrace(); return ""; } } }; } return mDateTimeInterpreter; }
[ "public", "DateTimeInterpreter", "getDateTimeInterpreter", "(", ")", "{", "if", "(", "mDateTimeInterpreter", "==", "null", ")", "{", "mDateTimeInterpreter", "=", "new", "DateTimeInterpreter", "(", ")", "{", "@", "Override", "public", "String", "interpretDate", "(", ...
Get the interpreter which provides the text to show in the header column and the header row. @return The date, time interpreter.
[ "Get", "the", "interpreter", "which", "provides", "the", "text", "to", "show", "in", "the", "header", "column", "and", "the", "header", "row", "." ]
train
https://github.com/alamkanak/Android-Week-View/blob/dc3f97d65d44785d1a761b52b58527c86c4eee1b/library/src/main/java/com/alamkanak/weekview/WeekView.java#L1299-L1330
jfinal/jfinal
src/main/java/com/jfinal/plugin/redis/Cache.java
Cache.lrem
public Long lrem(Object key, long count, Object value) { Jedis jedis = getJedis(); try { return jedis.lrem(keyToBytes(key), count, valueToBytes(value)); } finally {close(jedis);} }
java
public Long lrem(Object key, long count, Object value) { Jedis jedis = getJedis(); try { return jedis.lrem(keyToBytes(key), count, valueToBytes(value)); } finally {close(jedis);} }
[ "public", "Long", "lrem", "(", "Object", "key", ",", "long", "count", ",", "Object", "value", ")", "{", "Jedis", "jedis", "=", "getJedis", "(", ")", ";", "try", "{", "return", "jedis", ".", "lrem", "(", "keyToBytes", "(", "key", ")", ",", "count", ...
根据参数 count 的值,移除列表中与参数 value 相等的元素。 count 的值可以是以下几种: count > 0 : 从表头开始向表尾搜索,移除与 value 相等的元素,数量为 count 。 count < 0 : 从表尾开始向表头搜索,移除与 value 相等的元素,数量为 count 的绝对值。 count = 0 : 移除表中所有与 value 相等的值。
[ "根据参数", "count", "的值,移除列表中与参数", "value", "相等的元素。", "count", "的值可以是以下几种:", "count", ">", "0", ":", "从表头开始向表尾搜索,移除与", "value", "相等的元素,数量为", "count", "。", "count", "<", "0", ":", "从表尾开始向表头搜索,移除与", "value", "相等的元素,数量为", "count", "的绝对值。", "count", "=", "0", ":", ...
train
https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/plugin/redis/Cache.java#L701-L707
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java
DefaultSqlConfig.getConfig
public static SqlConfig getConfig(final DataSource dataSource, final boolean autoCommit, final boolean readOnly, final int transactionIsolation) { DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSource); connectionSupplier.setDefaultAutoCommit(autoCommit); connectionSupplier.setDefaultReadOnly(readOnly); connectionSupplier.setDefaultTransactionIsolation(transactionIsolation); return new DefaultSqlConfig(connectionSupplier, null); }
java
public static SqlConfig getConfig(final DataSource dataSource, final boolean autoCommit, final boolean readOnly, final int transactionIsolation) { DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSource); connectionSupplier.setDefaultAutoCommit(autoCommit); connectionSupplier.setDefaultReadOnly(readOnly); connectionSupplier.setDefaultTransactionIsolation(transactionIsolation); return new DefaultSqlConfig(connectionSupplier, null); }
[ "public", "static", "SqlConfig", "getConfig", "(", "final", "DataSource", "dataSource", ",", "final", "boolean", "autoCommit", ",", "final", "boolean", "readOnly", ",", "final", "int", "transactionIsolation", ")", "{", "DataSourceConnectionSupplierImpl", "connectionSupp...
データソースを指定してSqlConfigを取得する @param dataSource データソース @param autoCommit 自動コミットの指定 @param readOnly 読み取り専用モードの指定 @param transactionIsolation トランザクション隔離レベルの指定 @return SqlConfigオブジェクト
[ "データソースを指定してSqlConfigを取得する" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java#L196-L203
ZuInnoTe/hadoopcryptoledger
hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashSegwitUDF.java
BitcoinTransactionHashSegwitUDF.readListOfBitcoinScriptWitnessFromTable
private List<BitcoinScriptWitnessItem> readListOfBitcoinScriptWitnessFromTable(ListObjectInspector loi, Object listOfScriptWitnessItemObject) { int listLength=loi.getListLength(listOfScriptWitnessItemObject); List<BitcoinScriptWitnessItem> result = new ArrayList<>(listLength); StructObjectInspector listOfScriptwitnessItemElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector(); for (int i=0;i<listLength;i++) { Object currentlistofscriptwitnessitemObject = loi.getListElement(listOfScriptWitnessItemObject,i); StructField stackitemcounterSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("stackitemcounter"); StructField scriptwitnesslistSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("scriptwitnesslist"); boolean scriptwitnessitemNull = (stackitemcounterSF==null) || (scriptwitnesslistSF==null) ; if (scriptwitnessitemNull) { LOG.warn("Invalid BitcoinScriptWitnessItem detected at position "+i); return new ArrayList<>(); } byte[] stackItemCounter = wboi.getPrimitiveJavaObject(listOfScriptwitnessItemElementObjectInspector.getStructFieldData(currentlistofscriptwitnessitemObject,stackitemcounterSF)); Object listofscriptwitnessObject = soi.getStructFieldData(currentlistofscriptwitnessitemObject,scriptwitnesslistSF); ListObjectInspector loiScriptWitness=(ListObjectInspector)scriptwitnesslistSF.getFieldObjectInspector(); StructObjectInspector listOfScriptwitnessElementObjectInspector = (StructObjectInspector)loiScriptWitness.getListElementObjectInspector(); int listWitnessLength = loiScriptWitness.getListLength(listofscriptwitnessObject); List<BitcoinScriptWitness> currentScriptWitnessList = new ArrayList<>(listWitnessLength); for (int j=0;j<listWitnessLength;j++) { Object currentlistofscriptwitnessObject = loi.getListElement(listofscriptwitnessObject,j); StructField witnessscriptlengthSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscriptlength"); StructField witnessscriptSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscript"); boolean scriptwitnessNull = (witnessscriptlengthSF==null) || (witnessscriptSF==null); if (scriptwitnessNull) { LOG.warn("Invalid BitcoinScriptWitness detected at position "+j+ "for BitcoinScriptWitnessItem "+i); return new ArrayList<>(); } byte[] scriptWitnessLength = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptlengthSF)); byte[] scriptWitness = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptSF)); currentScriptWitnessList.add(new BitcoinScriptWitness(scriptWitnessLength,scriptWitness)); } BitcoinScriptWitnessItem currentBitcoinScriptWitnessItem = new BitcoinScriptWitnessItem(stackItemCounter,currentScriptWitnessList); result.add(currentBitcoinScriptWitnessItem); } return result; }
java
private List<BitcoinScriptWitnessItem> readListOfBitcoinScriptWitnessFromTable(ListObjectInspector loi, Object listOfScriptWitnessItemObject) { int listLength=loi.getListLength(listOfScriptWitnessItemObject); List<BitcoinScriptWitnessItem> result = new ArrayList<>(listLength); StructObjectInspector listOfScriptwitnessItemElementObjectInspector = (StructObjectInspector)loi.getListElementObjectInspector(); for (int i=0;i<listLength;i++) { Object currentlistofscriptwitnessitemObject = loi.getListElement(listOfScriptWitnessItemObject,i); StructField stackitemcounterSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("stackitemcounter"); StructField scriptwitnesslistSF = listOfScriptwitnessItemElementObjectInspector.getStructFieldRef("scriptwitnesslist"); boolean scriptwitnessitemNull = (stackitemcounterSF==null) || (scriptwitnesslistSF==null) ; if (scriptwitnessitemNull) { LOG.warn("Invalid BitcoinScriptWitnessItem detected at position "+i); return new ArrayList<>(); } byte[] stackItemCounter = wboi.getPrimitiveJavaObject(listOfScriptwitnessItemElementObjectInspector.getStructFieldData(currentlistofscriptwitnessitemObject,stackitemcounterSF)); Object listofscriptwitnessObject = soi.getStructFieldData(currentlistofscriptwitnessitemObject,scriptwitnesslistSF); ListObjectInspector loiScriptWitness=(ListObjectInspector)scriptwitnesslistSF.getFieldObjectInspector(); StructObjectInspector listOfScriptwitnessElementObjectInspector = (StructObjectInspector)loiScriptWitness.getListElementObjectInspector(); int listWitnessLength = loiScriptWitness.getListLength(listofscriptwitnessObject); List<BitcoinScriptWitness> currentScriptWitnessList = new ArrayList<>(listWitnessLength); for (int j=0;j<listWitnessLength;j++) { Object currentlistofscriptwitnessObject = loi.getListElement(listofscriptwitnessObject,j); StructField witnessscriptlengthSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscriptlength"); StructField witnessscriptSF = listOfScriptwitnessElementObjectInspector.getStructFieldRef("witnessscript"); boolean scriptwitnessNull = (witnessscriptlengthSF==null) || (witnessscriptSF==null); if (scriptwitnessNull) { LOG.warn("Invalid BitcoinScriptWitness detected at position "+j+ "for BitcoinScriptWitnessItem "+i); return new ArrayList<>(); } byte[] scriptWitnessLength = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptlengthSF)); byte[] scriptWitness = wboi.getPrimitiveJavaObject(listOfScriptwitnessElementObjectInspector.getStructFieldData(currentlistofscriptwitnessObject,witnessscriptSF)); currentScriptWitnessList.add(new BitcoinScriptWitness(scriptWitnessLength,scriptWitness)); } BitcoinScriptWitnessItem currentBitcoinScriptWitnessItem = new BitcoinScriptWitnessItem(stackItemCounter,currentScriptWitnessList); result.add(currentBitcoinScriptWitnessItem); } return result; }
[ "private", "List", "<", "BitcoinScriptWitnessItem", ">", "readListOfBitcoinScriptWitnessFromTable", "(", "ListObjectInspector", "loi", ",", "Object", "listOfScriptWitnessItemObject", ")", "{", "int", "listLength", "=", "loi", ".", "getListLength", "(", "listOfScriptWitnessI...
Read list of Bitcoin ScriptWitness items from a table in Hive in any format (e.g. ORC, Parquet) @param loi ObjectInspector for processing the Object containing a list @param listOfScriptWitnessItemObject object containing the list of scriptwitnessitems of a Bitcoin Transaction @return a list of BitcoinScriptWitnessItem
[ "Read", "list", "of", "Bitcoin", "ScriptWitness", "items", "from", "a", "table", "in", "Hive", "in", "any", "format", "(", "e", ".", "g", ".", "ORC", "Parquet", ")" ]
train
https://github.com/ZuInnoTe/hadoopcryptoledger/blob/5c9bfb61dd1a82374cd0de8413a7c66391ee4414/hiveudf/src/main/java/org/zuinnote/hadoop/bitcoin/hive/udf/BitcoinTransactionHashSegwitUDF.java#L274-L311
threerings/narya
core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java
ChatDirector.displaySystem
protected void displaySystem (String bundle, String message, byte attLevel, String localtype) { // nothing should be untranslated, so pass the default bundle if need be. if (bundle == null) { bundle = _bundle; } SystemMessage msg = new SystemMessage(message, bundle, attLevel); dispatchMessage(msg, localtype); }
java
protected void displaySystem (String bundle, String message, byte attLevel, String localtype) { // nothing should be untranslated, so pass the default bundle if need be. if (bundle == null) { bundle = _bundle; } SystemMessage msg = new SystemMessage(message, bundle, attLevel); dispatchMessage(msg, localtype); }
[ "protected", "void", "displaySystem", "(", "String", "bundle", ",", "String", "message", ",", "byte", "attLevel", ",", "String", "localtype", ")", "{", "// nothing should be untranslated, so pass the default bundle if need be.", "if", "(", "bundle", "==", "null", ")", ...
Display the specified system message as if it had come from the server.
[ "Display", "the", "specified", "system", "message", "as", "if", "it", "had", "come", "from", "the", "server", "." ]
train
https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/crowd/chat/client/ChatDirector.java#L1085-L1093
kiegroup/drools
drools-beliefs/src/main/java/org/drools/beliefs/bayes/BayesInstance.java
BayesInstance.passMessage
public void passMessage( JunctionTreeClique sourceClique, JunctionTreeSeparator sep, JunctionTreeClique targetClique) { double[] sepPots = separatorStates[sep.getId()].getPotentials(); double[] oldSepPots = Arrays.copyOf(sepPots, sepPots.length); BayesVariable[] sepVars = sep.getValues().toArray(new BayesVariable[sep.getValues().size()]); if ( passMessageListener != null ) { passMessageListener.beforeProjectAndAbsorb(sourceClique, sep, targetClique, oldSepPots); } project(sepVars, cliqueStates[sourceClique.getId()], separatorStates[sep.getId()]); if ( passMessageListener != null ) { passMessageListener.afterProject(sourceClique, sep, targetClique, oldSepPots); } absorb(sepVars, cliqueStates[targetClique.getId()], separatorStates[sep.getId()], oldSepPots); if ( passMessageListener != null ) { passMessageListener.afterAbsorb(sourceClique, sep, targetClique, oldSepPots); } }
java
public void passMessage( JunctionTreeClique sourceClique, JunctionTreeSeparator sep, JunctionTreeClique targetClique) { double[] sepPots = separatorStates[sep.getId()].getPotentials(); double[] oldSepPots = Arrays.copyOf(sepPots, sepPots.length); BayesVariable[] sepVars = sep.getValues().toArray(new BayesVariable[sep.getValues().size()]); if ( passMessageListener != null ) { passMessageListener.beforeProjectAndAbsorb(sourceClique, sep, targetClique, oldSepPots); } project(sepVars, cliqueStates[sourceClique.getId()], separatorStates[sep.getId()]); if ( passMessageListener != null ) { passMessageListener.afterProject(sourceClique, sep, targetClique, oldSepPots); } absorb(sepVars, cliqueStates[targetClique.getId()], separatorStates[sep.getId()], oldSepPots); if ( passMessageListener != null ) { passMessageListener.afterAbsorb(sourceClique, sep, targetClique, oldSepPots); } }
[ "public", "void", "passMessage", "(", "JunctionTreeClique", "sourceClique", ",", "JunctionTreeSeparator", "sep", ",", "JunctionTreeClique", "targetClique", ")", "{", "double", "[", "]", "sepPots", "=", "separatorStates", "[", "sep", ".", "getId", "(", ")", "]", ...
Passes a message from node1 to node2. node1 projects its trgPotentials into the separator. node2 then absorbs those trgPotentials from the separator. @param sourceClique @param sep @param targetClique
[ "Passes", "a", "message", "from", "node1", "to", "node2", ".", "node1", "projects", "its", "trgPotentials", "into", "the", "separator", ".", "node2", "then", "absorbs", "those", "trgPotentials", "from", "the", "separator", "." ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-beliefs/src/main/java/org/drools/beliefs/bayes/BayesInstance.java#L368-L387
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/statistics/kriging/OmsKriging.java
OmsKriging.storeResult
private void storeResult( double[] result2, int[] id ) throws SchemaException { outData = new HashMap<Integer, double[]>(); for( int i = 0; i < result2.length; i++ ) { outData.put(id[i], new double[]{checkResultValue(result2[i])}); } }
java
private void storeResult( double[] result2, int[] id ) throws SchemaException { outData = new HashMap<Integer, double[]>(); for( int i = 0; i < result2.length; i++ ) { outData.put(id[i], new double[]{checkResultValue(result2[i])}); } }
[ "private", "void", "storeResult", "(", "double", "[", "]", "result2", ",", "int", "[", "]", "id", ")", "throws", "SchemaException", "{", "outData", "=", "new", "HashMap", "<", "Integer", ",", "double", "[", "]", ">", "(", ")", ";", "for", "(", "int",...
Store the result in a HashMap (if the mode is 0 or 1) @param result2 the result of the model @param id the associated id of the calculating points. @throws SchemaException @throws SchemaException
[ "Store", "the", "result", "in", "a", "HashMap", "(", "if", "the", "mode", "is", "0", "or", "1", ")" ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/statistics/kriging/OmsKriging.java#L535-L540
alibaba/jstorm
jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncProcessEvent.java
SyncProcessEvent.readWorkerHeartbeat
public WorkerHeartbeat readWorkerHeartbeat(Map conf, String workerId) throws Exception { try { LocalState ls = StormConfig.worker_state(conf, workerId); return (WorkerHeartbeat) ls.get(Common.LS_WORKER_HEARTBEAT); } catch (Exception e) { LOG.error("Failed to get heartbeat for worker:{}", workerId, e); return null; } }
java
public WorkerHeartbeat readWorkerHeartbeat(Map conf, String workerId) throws Exception { try { LocalState ls = StormConfig.worker_state(conf, workerId); return (WorkerHeartbeat) ls.get(Common.LS_WORKER_HEARTBEAT); } catch (Exception e) { LOG.error("Failed to get heartbeat for worker:{}", workerId, e); return null; } }
[ "public", "WorkerHeartbeat", "readWorkerHeartbeat", "(", "Map", "conf", ",", "String", "workerId", ")", "throws", "Exception", "{", "try", "{", "LocalState", "ls", "=", "StormConfig", ".", "worker_state", "(", "conf", ",", "workerId", ")", ";", "return", "(", ...
get worker heartbeat by workerId @param conf conf @param workerId worker id @return WorkerHeartbeat
[ "get", "worker", "heartbeat", "by", "workerId" ]
train
https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-core/src/main/java/com/alibaba/jstorm/daemon/supervisor/SyncProcessEvent.java#L489-L497
TheCoder4eu/BootsFaces-OSP
src/main/java/net/bootsfaces/expressions/decorator/AFTagAttributes.java
AFTagAttributes.get
@Override public TagAttribute get(String ns, String localName) { if (ns != null && localName != null) for (TagAttribute a:attrs) if (localName.equals(a.getLocalName())) if (ns.equals(a.getNamespace())) return a; return null; }
java
@Override public TagAttribute get(String ns, String localName) { if (ns != null && localName != null) for (TagAttribute a:attrs) if (localName.equals(a.getLocalName())) if (ns.equals(a.getNamespace())) return a; return null; }
[ "@", "Override", "public", "TagAttribute", "get", "(", "String", "ns", ",", "String", "localName", ")", "{", "if", "(", "ns", "!=", "null", "&&", "localName", "!=", "null", ")", "for", "(", "TagAttribute", "a", ":", "attrs", ")", "if", "(", "localName"...
Find a TagAttribute that matches the passed namespace and local name. @param ns namespace of the desired attribute @param localName local name of the attribute @return a TagAttribute found, otherwise null
[ "Find", "a", "TagAttribute", "that", "matches", "the", "passed", "namespace", "and", "local", "name", "." ]
train
https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/expressions/decorator/AFTagAttributes.java#L107-L115
TheHortonMachine/hortonmachine
hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java
EpanetWrapper.ENopen
public void ENopen( String input, String report, String outputBin ) throws EpanetException { int errcode = epanet.ENopen(input, report, outputBin); checkError(errcode); }
java
public void ENopen( String input, String report, String outputBin ) throws EpanetException { int errcode = epanet.ENopen(input, report, outputBin); checkError(errcode); }
[ "public", "void", "ENopen", "(", "String", "input", ",", "String", "report", ",", "String", "outputBin", ")", "throws", "EpanetException", "{", "int", "errcode", "=", "epanet", ".", "ENopen", "(", "input", ",", "report", ",", "outputBin", ")", ";", "checkE...
Opens the Toolkit to analyze a particular distribution system. @param input name of an EPANET Input file. @param report name of an output Report file. @param outputBin name of an optional binary Output file. @throws IOException
[ "Opens", "the", "Toolkit", "to", "analyze", "a", "particular", "distribution", "system", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/hmachine/src/main/java/org/hortonmachine/hmachine/modules/networktools/epanet/core/EpanetWrapper.java#L82-L85
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsDomUtil.java
CmsDomUtil.getRelativeX
public static int getRelativeX(int x, Element target) { return (x - target.getAbsoluteLeft()) + /* target.getScrollLeft() + */target.getOwnerDocument().getScrollLeft(); }
java
public static int getRelativeX(int x, Element target) { return (x - target.getAbsoluteLeft()) + /* target.getScrollLeft() + */target.getOwnerDocument().getScrollLeft(); }
[ "public", "static", "int", "getRelativeX", "(", "int", "x", ",", "Element", "target", ")", "{", "return", "(", "x", "-", "target", ".", "getAbsoluteLeft", "(", ")", ")", "+", "/* target.getScrollLeft() + */", "target", ".", "getOwnerDocument", "(", ")", ".",...
Gets the horizontal position of the given x-coordinate relative to a given element.<p> @param x the coordinate to use @param target the element whose coordinate system is to be used @return the relative horizontal position @see com.google.gwt.event.dom.client.MouseEvent#getRelativeX(com.google.gwt.dom.client.Element)
[ "Gets", "the", "horizontal", "position", "of", "the", "given", "x", "-", "coordinate", "relative", "to", "a", "given", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsDomUtil.java#L1479-L1482
OpenLiberty/open-liberty
dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java
WsByteBufferUtils.putStringValue
public static void putStringValue(WsByteBuffer[] buff, String value, boolean bFlipLast) { if (null != value) { putByteArrayValue(buff, value.getBytes(), bFlipLast); } }
java
public static void putStringValue(WsByteBuffer[] buff, String value, boolean bFlipLast) { if (null != value) { putByteArrayValue(buff, value.getBytes(), bFlipLast); } }
[ "public", "static", "void", "putStringValue", "(", "WsByteBuffer", "[", "]", "buff", ",", "String", "value", ",", "boolean", "bFlipLast", ")", "{", "if", "(", "null", "!=", "value", ")", "{", "putByteArrayValue", "(", "buff", ",", "value", ".", "getBytes",...
Store a String into a wsbb[]. This will fill out each wsbb until all of the bytes are written. It will throw an exception if there is not enough space. Users must pass in a boolean to determine whether or not to flip() the last buffer -- i.e. pass in true if this is the only put you're doing, otherwise pass in false. Any intermediate buffers that are filled to capacity will be flip()'d automatically. A null input string will result in a no-op. @param buff @param value @param bFlipLast
[ "Store", "a", "String", "into", "a", "wsbb", "[]", ".", "This", "will", "fill", "out", "each", "wsbb", "until", "all", "of", "the", "bytes", "are", "written", ".", "It", "will", "throw", "an", "exception", "if", "there", "is", "not", "enough", "space",...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.channelfw/src/com/ibm/wsspi/bytebuffer/WsByteBufferUtils.java#L456-L460
groovy/groovy-core
src/main/org/codehaus/groovy/classgen/asm/CompileStack.java
CompileStack.defineTemporaryVariable
public int defineTemporaryVariable(org.codehaus.groovy.ast.Variable var, boolean store) { return defineTemporaryVariable(var.getName(), var.getType(),store); }
java
public int defineTemporaryVariable(org.codehaus.groovy.ast.Variable var, boolean store) { return defineTemporaryVariable(var.getName(), var.getType(),store); }
[ "public", "int", "defineTemporaryVariable", "(", "org", ".", "codehaus", ".", "groovy", ".", "ast", ".", "Variable", "var", ",", "boolean", "store", ")", "{", "return", "defineTemporaryVariable", "(", "var", ".", "getName", "(", ")", ",", "var", ".", "getT...
creates a temporary variable. @param var defines type and name @param store defines if the toplevel argument of the stack should be stored @return the index used for this temporary variable
[ "creates", "a", "temporary", "variable", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/classgen/asm/CompileStack.java#L260-L262
spring-projects/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONArray.java
JSONArray.optBoolean
public boolean optBoolean(int index, boolean fallback) { Object object = opt(index); Boolean result = JSON.toBoolean(object); return result != null ? result : fallback; }
java
public boolean optBoolean(int index, boolean fallback) { Object object = opt(index); Boolean result = JSON.toBoolean(object); return result != null ? result : fallback; }
[ "public", "boolean", "optBoolean", "(", "int", "index", ",", "boolean", "fallback", ")", "{", "Object", "object", "=", "opt", "(", "index", ")", ";", "Boolean", "result", "=", "JSON", ".", "toBoolean", "(", "object", ")", ";", "return", "result", "!=", ...
Returns the value at {@code index} if it exists and is a boolean or can be coerced to a boolean. Returns {@code fallback} otherwise. @param index the index to get the value from @param fallback the fallback value @return the value at {@code index} of {@code fallback}
[ "Returns", "the", "value", "at", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-configuration-processor/src/json-shade/java/org/springframework/boot/configurationprocessor/json/JSONArray.java#L356-L360
artikcloud/artikcloud-java
src/main/java/cloud/artik/api/RulesApi.java
RulesApi.createRule
public RuleEnvelope createRule(RuleCreationInfo ruleInfo, String userId) throws ApiException { ApiResponse<RuleEnvelope> resp = createRuleWithHttpInfo(ruleInfo, userId); return resp.getData(); }
java
public RuleEnvelope createRule(RuleCreationInfo ruleInfo, String userId) throws ApiException { ApiResponse<RuleEnvelope> resp = createRuleWithHttpInfo(ruleInfo, userId); return resp.getData(); }
[ "public", "RuleEnvelope", "createRule", "(", "RuleCreationInfo", "ruleInfo", ",", "String", "userId", ")", "throws", "ApiException", "{", "ApiResponse", "<", "RuleEnvelope", ">", "resp", "=", "createRuleWithHttpInfo", "(", "ruleInfo", ",", "userId", ")", ";", "ret...
Create Rule Create a new Rule @param ruleInfo Rule object that needs to be added (required) @param userId User ID (required) @return RuleEnvelope @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Create", "Rule", "Create", "a", "new", "Rule" ]
train
https://github.com/artikcloud/artikcloud-java/blob/412f447573e7796ab4f685c0bdd5eb76185a365c/src/main/java/cloud/artik/api/RulesApi.java#L133-L136
sundrio/sundrio
maven-plugin/src/main/java/io/sundr/maven/GenerateBomMojo.java
GenerateBomMojo.toBuild
private static MavenProject toBuild(MavenProject project, BomConfig config) { File outputDir = new File(project.getBuild().getOutputDirectory()); File bomDir = new File(outputDir, config.getArtifactId()); File generatedBom = new File(bomDir, BOM_NAME); MavenProject toBuild = project.clone(); //we want to avoid recursive "generate-bom". toBuild.setExecutionRoot(false); toBuild.setFile(generatedBom); toBuild.getModel().setPomFile(generatedBom); toBuild.setModelVersion(project.getModelVersion()); toBuild.setArtifact(new DefaultArtifact(project.getGroupId(), config.getArtifactId(), project.getVersion(), project.getArtifact().getScope(), project.getArtifact().getType(), project.getArtifact().getClassifier(), project.getArtifact().getArtifactHandler())); toBuild.setParent(project.getParent()); toBuild.getModel().setParent(project.getModel().getParent()); toBuild.setGroupId(project.getGroupId()); toBuild.setArtifactId(config.getArtifactId()); toBuild.setVersion(project.getVersion()); toBuild.setPackaging("pom"); toBuild.setName(config.getName()); toBuild.setDescription(config.getDescription()); toBuild.setUrl(project.getUrl()); toBuild.setLicenses(project.getLicenses()); toBuild.setScm(project.getScm()); toBuild.setDevelopers(project.getDevelopers()); toBuild.setDistributionManagement(project.getDistributionManagement()); toBuild.getModel().setProfiles(project.getModel().getProfiles()); //We want to avoid having the generated stuff wiped. toBuild.getProperties().put("clean.skip", "true"); toBuild.getModel().getBuild().setDirectory(bomDir.getAbsolutePath()); toBuild.getModel().getBuild().setOutputDirectory(new File(bomDir, "target").getAbsolutePath()); for (String key : config.getProperties().stringPropertyNames()) { toBuild.getProperties().put(key, config.getProperties().getProperty(key)); } return toBuild; }
java
private static MavenProject toBuild(MavenProject project, BomConfig config) { File outputDir = new File(project.getBuild().getOutputDirectory()); File bomDir = new File(outputDir, config.getArtifactId()); File generatedBom = new File(bomDir, BOM_NAME); MavenProject toBuild = project.clone(); //we want to avoid recursive "generate-bom". toBuild.setExecutionRoot(false); toBuild.setFile(generatedBom); toBuild.getModel().setPomFile(generatedBom); toBuild.setModelVersion(project.getModelVersion()); toBuild.setArtifact(new DefaultArtifact(project.getGroupId(), config.getArtifactId(), project.getVersion(), project.getArtifact().getScope(), project.getArtifact().getType(), project.getArtifact().getClassifier(), project.getArtifact().getArtifactHandler())); toBuild.setParent(project.getParent()); toBuild.getModel().setParent(project.getModel().getParent()); toBuild.setGroupId(project.getGroupId()); toBuild.setArtifactId(config.getArtifactId()); toBuild.setVersion(project.getVersion()); toBuild.setPackaging("pom"); toBuild.setName(config.getName()); toBuild.setDescription(config.getDescription()); toBuild.setUrl(project.getUrl()); toBuild.setLicenses(project.getLicenses()); toBuild.setScm(project.getScm()); toBuild.setDevelopers(project.getDevelopers()); toBuild.setDistributionManagement(project.getDistributionManagement()); toBuild.getModel().setProfiles(project.getModel().getProfiles()); //We want to avoid having the generated stuff wiped. toBuild.getProperties().put("clean.skip", "true"); toBuild.getModel().getBuild().setDirectory(bomDir.getAbsolutePath()); toBuild.getModel().getBuild().setOutputDirectory(new File(bomDir, "target").getAbsolutePath()); for (String key : config.getProperties().stringPropertyNames()) { toBuild.getProperties().put(key, config.getProperties().getProperty(key)); } return toBuild; }
[ "private", "static", "MavenProject", "toBuild", "(", "MavenProject", "project", ",", "BomConfig", "config", ")", "{", "File", "outputDir", "=", "new", "File", "(", "project", ".", "getBuild", "(", ")", ".", "getOutputDirectory", "(", ")", ")", ";", "File", ...
Returns the generated {@link org.apache.maven.project.MavenProject} to build. This version of the project contains all the stuff needed for building (parents, profiles, properties etc). @param project The source {@link org.apache.maven.project.MavenProject}. @param config The {@link io.sundr.maven.BomConfig}. @return The build {@link org.apache.maven.project.MavenProject}.
[ "Returns", "the", "generated", "{", "@link", "org", ".", "apache", ".", "maven", ".", "project", ".", "MavenProject", "}", "to", "build", ".", "This", "version", "of", "the", "project", "contains", "all", "the", "stuff", "needed", "for", "building", "(", ...
train
https://github.com/sundrio/sundrio/blob/4e38368f4db0d950f7c41a8c75e15b0baff1f69a/maven-plugin/src/main/java/io/sundr/maven/GenerateBomMojo.java#L343-L386
microfocus-idol/java-configuration-impl
src/main/java/com/hp/autonomy/frontend/configuration/server/HostAndPort.java
HostAndPort.basicValidate
@Override public void basicValidate(final String section) throws ConfigException { if (StringUtils.isEmpty(host) || port == null || port <= 0 || port > MAX_PORT) { throw new ConfigException(section, "Invalid host and port"); } }
java
@Override public void basicValidate(final String section) throws ConfigException { if (StringUtils.isEmpty(host) || port == null || port <= 0 || port > MAX_PORT) { throw new ConfigException(section, "Invalid host and port"); } }
[ "@", "Override", "public", "void", "basicValidate", "(", "final", "String", "section", ")", "throws", "ConfigException", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "host", ")", "||", "port", "==", "null", "||", "port", "<=", "0", "||", "port", "...
Returns the validation state of the config @throws ConfigException if the hostname is empty or the port is not between 0 and 65536
[ "Returns", "the", "validation", "state", "of", "the", "config" ]
train
https://github.com/microfocus-idol/java-configuration-impl/blob/cd9d744cacfaaae3c76cacc211e65742bbc7b00a/src/main/java/com/hp/autonomy/frontend/configuration/server/HostAndPort.java#L35-L40
moparisthebest/beehive
beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/javascript/ScriptRequestState.java
ScriptRequestState.getString
public static String getString(String aKey, Object[] args) { assert (aKey != null); String pattern = getBundle().getString(aKey); if (args == null) return pattern; MessageFormat format = new MessageFormat(pattern); return format.format(args).toString(); }
java
public static String getString(String aKey, Object[] args) { assert (aKey != null); String pattern = getBundle().getString(aKey); if (args == null) return pattern; MessageFormat format = new MessageFormat(pattern); return format.format(args).toString(); }
[ "public", "static", "String", "getString", "(", "String", "aKey", ",", "Object", "[", "]", "args", ")", "{", "assert", "(", "aKey", "!=", "null", ")", ";", "String", "pattern", "=", "getBundle", "(", ")", ".", "getString", "(", "aKey", ")", ";", "if"...
Returns the string specified by aKey from the errors.properties bundle. @param aKey The key for the message pattern in the bundle. @param args The args to use in the message format.
[ "Returns", "the", "string", "specified", "by", "aKey", "from", "the", "errors", ".", "properties", "bundle", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/javascript/ScriptRequestState.java#L83-L93
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/filter/AbstractSecretColumnSqlFilter.java
AbstractSecretColumnSqlFilter.createDecryptor
private Function<Object, String> createDecryptor() throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(transformationType); if (useIV) { cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptCipher.getParameters().getParameterSpec(IvParameterSpec.class)); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } return secret -> { if (secret == null) { return null; } String secretStr = secret.toString(); if (!secretStr.isEmpty()) { synchronized (cipher) { try { return decrypt(cipher, secretKey, secretStr); } catch (Exception ex) { return secretStr; } } } else { return secretStr; } }; }
java
private Function<Object, String> createDecryptor() throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(transformationType); if (useIV) { cipher.init(Cipher.DECRYPT_MODE, secretKey, encryptCipher.getParameters().getParameterSpec(IvParameterSpec.class)); } else { cipher.init(Cipher.DECRYPT_MODE, secretKey); } return secret -> { if (secret == null) { return null; } String secretStr = secret.toString(); if (!secretStr.isEmpty()) { synchronized (cipher) { try { return decrypt(cipher, secretKey, secretStr); } catch (Exception ex) { return secretStr; } } } else { return secretStr; } }; }
[ "private", "Function", "<", "Object", ",", "String", ">", "createDecryptor", "(", ")", "throws", "GeneralSecurityException", "{", "Cipher", "cipher", "=", "Cipher", ".", "getInstance", "(", "transformationType", ")", ";", "if", "(", "useIV", ")", "{", "cipher"...
{@link SecretResultSet} が復号に使用するラムダを構築する。 @return 暗号を受け取り平文を返すラムダ @throws GeneralSecurityException サブクラスでの拡張に備えて javax.crypto パッケージ配下の例外の親クラス
[ "{", "@link", "SecretResultSet", "}", "が復号に使用するラムダを構築する。" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/filter/AbstractSecretColumnSqlFilter.java#L251-L278
alkacon/opencms-core
src/org/opencms/site/CmsSiteManagerImpl.java
CmsSiteManagerImpl.addSite
public void addSite(CmsObject cms, CmsSite site) throws CmsException { // check permissions if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_1_CORE_OBJECT) { // simple unit tests will have runlevel 1 and no CmsObject OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); } // un-freeze m_frozen = false; // set aliases and parameters, they will be used in the addSite method // this is necessary because of a digester workaround m_siteParams = site.getParameters(); m_aliases = site.getAliases(); String secureUrl = null; if (site.hasSecureServer()) { secureUrl = site.getSecureUrl(); } // add the site addSite( site.getUrl(), site.getSiteRoot(), site.getTitle(), Float.toString(site.getPosition()), site.getErrorPage(), Boolean.toString(site.isWebserver()), site.getSSLMode().getXMLValue(), secureUrl, Boolean.toString(site.isExclusiveUrl()), Boolean.toString(site.isExclusiveError()), Boolean.toString(site.usesPermanentRedirects())); // re-initialize, will freeze the state when finished initialize(cms); OpenCms.writeConfiguration(CmsSitesConfiguration.class); }
java
public void addSite(CmsObject cms, CmsSite site) throws CmsException { // check permissions if (OpenCms.getRunLevel() > OpenCms.RUNLEVEL_1_CORE_OBJECT) { // simple unit tests will have runlevel 1 and no CmsObject OpenCms.getRoleManager().checkRole(cms, CmsRole.DATABASE_MANAGER); } // un-freeze m_frozen = false; // set aliases and parameters, they will be used in the addSite method // this is necessary because of a digester workaround m_siteParams = site.getParameters(); m_aliases = site.getAliases(); String secureUrl = null; if (site.hasSecureServer()) { secureUrl = site.getSecureUrl(); } // add the site addSite( site.getUrl(), site.getSiteRoot(), site.getTitle(), Float.toString(site.getPosition()), site.getErrorPage(), Boolean.toString(site.isWebserver()), site.getSSLMode().getXMLValue(), secureUrl, Boolean.toString(site.isExclusiveUrl()), Boolean.toString(site.isExclusiveError()), Boolean.toString(site.usesPermanentRedirects())); // re-initialize, will freeze the state when finished initialize(cms); OpenCms.writeConfiguration(CmsSitesConfiguration.class); }
[ "public", "void", "addSite", "(", "CmsObject", "cms", ",", "CmsSite", "site", ")", "throws", "CmsException", "{", "// check permissions", "if", "(", "OpenCms", ".", "getRunLevel", "(", ")", ">", "OpenCms", ".", "RUNLEVEL_1_CORE_OBJECT", ")", "{", "// simple unit...
Adds a site.<p> @param cms the CMS object @param site the site to add @throws CmsException if something goes wrong
[ "Adds", "a", "site", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/site/CmsSiteManagerImpl.java#L240-L278
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java
JsonObjectDeserializer.getRequiredNode
protected final JsonNode getRequiredNode(JsonNode tree, String fieldName) { Assert.notNull(tree, "Tree must not be null"); JsonNode node = tree.get(fieldName); Assert.state(node != null && !(node instanceof NullNode), () -> "Missing JSON field '" + fieldName + "'"); return node; }
java
protected final JsonNode getRequiredNode(JsonNode tree, String fieldName) { Assert.notNull(tree, "Tree must not be null"); JsonNode node = tree.get(fieldName); Assert.state(node != null && !(node instanceof NullNode), () -> "Missing JSON field '" + fieldName + "'"); return node; }
[ "protected", "final", "JsonNode", "getRequiredNode", "(", "JsonNode", "tree", ",", "String", "fieldName", ")", "{", "Assert", ".", "notNull", "(", "tree", ",", "\"Tree must not be null\"", ")", ";", "JsonNode", "node", "=", "tree", ".", "get", "(", "fieldName"...
Helper method to return a {@link JsonNode} from the tree. @param tree the source tree @param fieldName the field name to extract @return the {@link JsonNode}
[ "Helper", "method", "to", "return", "a", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/jackson/JsonObjectDeserializer.java#L130-L136
betfair/cougar
cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java
JmsEventTransportImpl.initThreadPool
public void initThreadPool() { CustomizableThreadFactory ctf = new CustomizableThreadFactory(); ctf.setDaemon(true); ctf.setThreadNamePrefix(getTransportName()+"-Publisher-"); threadPool = new JMXReportingThreadPoolExecutor(threadPoolSize, threadPoolSize, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), ctf); }
java
public void initThreadPool() { CustomizableThreadFactory ctf = new CustomizableThreadFactory(); ctf.setDaemon(true); ctf.setThreadNamePrefix(getTransportName()+"-Publisher-"); threadPool = new JMXReportingThreadPoolExecutor(threadPoolSize, threadPoolSize, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), ctf); }
[ "public", "void", "initThreadPool", "(", ")", "{", "CustomizableThreadFactory", "ctf", "=", "new", "CustomizableThreadFactory", "(", ")", ";", "ctf", ".", "setDaemon", "(", "true", ")", ";", "ctf", ".", "setThreadNamePrefix", "(", "getTransportName", "(", ")", ...
Initialise the thread pool to have the requested number of threads available, life span of threads (set to 0) not used as threads will never be eligible to die as coreSize = maxSize
[ "Initialise", "the", "thread", "pool", "to", "have", "the", "requested", "number", "of", "threads", "available", "life", "span", "of", "threads", "(", "set", "to", "0", ")", "not", "used", "as", "threads", "will", "never", "be", "eligible", "to", "die", ...
train
https://github.com/betfair/cougar/blob/08d1fe338fbd0e8572a9c2305bb5796402d5b1f5/cougar-framework/jms-transport/src/main/java/com/betfair/cougar/transport/jms/JmsEventTransportImpl.java#L177-L182
alexcojocaru/elasticsearch-maven-plugin
src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java
Monitor.isProcessRunning
public static boolean isProcessRunning(String baseDir) { File pidFile = new File(baseDir, "pid"); boolean exists = pidFile.isFile(); return exists; }
java
public static boolean isProcessRunning(String baseDir) { File pidFile = new File(baseDir, "pid"); boolean exists = pidFile.isFile(); return exists; }
[ "public", "static", "boolean", "isProcessRunning", "(", "String", "baseDir", ")", "{", "File", "pidFile", "=", "new", "File", "(", "baseDir", ",", "\"pid\"", ")", ";", "boolean", "exists", "=", "pidFile", ".", "isFile", "(", ")", ";", "return", "exists", ...
Check whether the PID file created by the ES process exists or not. @param baseDir the ES base directory @return true if the process is running, false otherwise
[ "Check", "whether", "the", "PID", "file", "created", "by", "the", "ES", "process", "exists", "or", "not", "." ]
train
https://github.com/alexcojocaru/elasticsearch-maven-plugin/blob/c283053cf99dc6b6d411b58629364b6aae62b7f8/src/main/java/com/github/alexcojocaru/mojo/elasticsearch/v2/client/Monitor.java#L56-L61
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.injectBean
@Internal @SuppressWarnings({"WeakerAccess", "unused"}) @UsedByGeneratedCode protected Object injectBean(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { return bean; }
java
@Internal @SuppressWarnings({"WeakerAccess", "unused"}) @UsedByGeneratedCode protected Object injectBean(BeanResolutionContext resolutionContext, BeanContext context, Object bean) { return bean; }
[ "@", "Internal", "@", "SuppressWarnings", "(", "{", "\"WeakerAccess\"", ",", "\"unused\"", "}", ")", "@", "UsedByGeneratedCode", "protected", "Object", "injectBean", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "Object", "bean...
The default implementation which provides no injection. To be overridden by compile time tooling. @param resolutionContext The resolution context @param context The bean context @param bean The bean @return The injected bean
[ "The", "default", "implementation", "which", "provides", "no", "injection", ".", "To", "be", "overridden", "by", "compile", "time", "tooling", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L582-L587
xwiki/xwiki-rendering
xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java
IconTransformation.blockEquals
private boolean blockEquals(Block target, Block source) { boolean found = false; if (source instanceof SpecialSymbolBlock && target instanceof SpecialSymbolBlock) { if (((SpecialSymbolBlock) target).getSymbol() == ((SpecialSymbolBlock) source).getSymbol()) { found = true; } } else if (source instanceof WordBlock && target instanceof WordBlock) { if (((WordBlock) target).getWord().equals(((WordBlock) source).getWord())) { found = true; } } else if (source.equals(target)) { found = true; } return found; }
java
private boolean blockEquals(Block target, Block source) { boolean found = false; if (source instanceof SpecialSymbolBlock && target instanceof SpecialSymbolBlock) { if (((SpecialSymbolBlock) target).getSymbol() == ((SpecialSymbolBlock) source).getSymbol()) { found = true; } } else if (source instanceof WordBlock && target instanceof WordBlock) { if (((WordBlock) target).getWord().equals(((WordBlock) source).getWord())) { found = true; } } else if (source.equals(target)) { found = true; } return found; }
[ "private", "boolean", "blockEquals", "(", "Block", "target", ",", "Block", "source", ")", "{", "boolean", "found", "=", "false", ";", "if", "(", "source", "instanceof", "SpecialSymbolBlock", "&&", "target", "instanceof", "SpecialSymbolBlock", ")", "{", "if", "...
Compares two nodes in a shallow manner (children data are not compared). @param target the target node to compare @param source the source node to compare @return true if the two blocks are equals in a shallow manner (children data are not compared)
[ "Compares", "two", "nodes", "in", "a", "shallow", "manner", "(", "children", "data", "are", "not", "compared", ")", "." ]
train
https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-transformations/xwiki-rendering-transformation-icon/src/main/java/org/xwiki/rendering/internal/transformation/icon/IconTransformation.java#L196-L211
seam/faces
impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java
SecurityPhaseListener.isAnnotationApplicableToPhase
public boolean isAnnotationApplicableToPhase(Annotation annotation, PhaseIdType currentPhase, PhaseIdType[] defaultPhases) { Method restrictAtViewMethod = getRestrictAtViewMethod(annotation); PhaseIdType[] phasedIds = null; if (restrictAtViewMethod != null) { log.warnf("Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead."); phasedIds = getRestrictedPhaseIds(restrictAtViewMethod, annotation); } RestrictAtPhase restrictAtPhaseQualifier = AnnotationInspector.getAnnotation(annotation.annotationType(), RestrictAtPhase.class, beanManager); if (restrictAtPhaseQualifier != null) { log.debug("Using Phases found in @RestrictAtView qualifier on the annotation."); phasedIds = restrictAtPhaseQualifier.value(); } if (phasedIds == null) { log.debug("Falling back on default phase ids"); phasedIds = defaultPhases; } if (Arrays.binarySearch(phasedIds, currentPhase) >= 0) { return true; } return false; }
java
public boolean isAnnotationApplicableToPhase(Annotation annotation, PhaseIdType currentPhase, PhaseIdType[] defaultPhases) { Method restrictAtViewMethod = getRestrictAtViewMethod(annotation); PhaseIdType[] phasedIds = null; if (restrictAtViewMethod != null) { log.warnf("Annotation %s is using the restrictAtViewMethod. Use a @RestrictAtPhase qualifier on the annotation instead."); phasedIds = getRestrictedPhaseIds(restrictAtViewMethod, annotation); } RestrictAtPhase restrictAtPhaseQualifier = AnnotationInspector.getAnnotation(annotation.annotationType(), RestrictAtPhase.class, beanManager); if (restrictAtPhaseQualifier != null) { log.debug("Using Phases found in @RestrictAtView qualifier on the annotation."); phasedIds = restrictAtPhaseQualifier.value(); } if (phasedIds == null) { log.debug("Falling back on default phase ids"); phasedIds = defaultPhases; } if (Arrays.binarySearch(phasedIds, currentPhase) >= 0) { return true; } return false; }
[ "public", "boolean", "isAnnotationApplicableToPhase", "(", "Annotation", "annotation", ",", "PhaseIdType", "currentPhase", ",", "PhaseIdType", "[", "]", "defaultPhases", ")", "{", "Method", "restrictAtViewMethod", "=", "getRestrictAtViewMethod", "(", "annotation", ")", ...
Inspect an annotation to see if it specifies a view in which it should be. Fall back on default view otherwise. @param annotation @param currentPhase @param defaultPhases @return true if the annotation is applicable to this view and phase, false otherwise
[ "Inspect", "an", "annotation", "to", "see", "if", "it", "specifies", "a", "view", "in", "which", "it", "should", "be", ".", "Fall", "back", "on", "default", "view", "otherwise", "." ]
train
https://github.com/seam/faces/blob/2fdedbc7070318c2c58bfffb8a26f1ea1d0ee1e3/impl/src/main/java/org/jboss/seam/faces/security/SecurityPhaseListener.java#L190-L210
windup/windup
config/api/src/main/java/org/jboss/windup/config/Variables.java
Variables.setSingletonVariable
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
java
public void setSingletonVariable(String name, WindupVertexFrame frame) { setVariable(name, Collections.singletonList(frame)); }
[ "public", "void", "setSingletonVariable", "(", "String", "name", ",", "WindupVertexFrame", "frame", ")", "{", "setVariable", "(", "name", ",", "Collections", ".", "singletonList", "(", "frame", ")", ")", ";", "}" ]
Type-safe wrapper around setVariable which sets only one framed vertex.
[ "Type", "-", "safe", "wrapper", "around", "setVariable", "which", "sets", "only", "one", "framed", "vertex", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/config/api/src/main/java/org/jboss/windup/config/Variables.java#L90-L93
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/util/HashUtil.java
HashUtil.MurmurHash3_x64_64
public static long MurmurHash3_x64_64(byte[] data, int offset, int len) { return MurmurHash3_x64_64(BYTE_ARRAY_LOADER, data, offset, len, DEFAULT_MURMUR_SEED); }
java
public static long MurmurHash3_x64_64(byte[] data, int offset, int len) { return MurmurHash3_x64_64(BYTE_ARRAY_LOADER, data, offset, len, DEFAULT_MURMUR_SEED); }
[ "public", "static", "long", "MurmurHash3_x64_64", "(", "byte", "[", "]", "data", ",", "int", "offset", ",", "int", "len", ")", "{", "return", "MurmurHash3_x64_64", "(", "BYTE_ARRAY_LOADER", ",", "data", ",", "offset", ",", "len", ",", "DEFAULT_MURMUR_SEED", ...
Returns the MurmurHash3_x86_32 hash of a block inside a byte array.
[ "Returns", "the", "MurmurHash3_x86_32", "hash", "of", "a", "block", "inside", "a", "byte", "array", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/util/HashUtil.java#L139-L141
wuman/android-oauth-client
library/src/main/java/com/wuman/android/auth/AuthorizationFlow.java
AuthorizationFlow.new10aCredential
private OAuthHmacCredential new10aCredential(String userId) { ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication(); OAuthHmacCredential.Builder builder = new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(), clientAuthentication.getClientSecret()) .setTransport(getTransport()) .setJsonFactory(getJsonFactory()) .setTokenServerEncodedUrl(getTokenServerEncodedUrl()) .setClientAuthentication(getClientAuthentication()) .setRequestInitializer(getRequestInitializer()) .setClock(getClock()); if (getCredentialStore() != null) { builder.addRefreshListener( new CredentialStoreRefreshListener(userId, getCredentialStore())); } builder.getRefreshListeners().addAll(getRefreshListeners()); return builder.build(); }
java
private OAuthHmacCredential new10aCredential(String userId) { ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication(); OAuthHmacCredential.Builder builder = new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(), clientAuthentication.getClientSecret()) .setTransport(getTransport()) .setJsonFactory(getJsonFactory()) .setTokenServerEncodedUrl(getTokenServerEncodedUrl()) .setClientAuthentication(getClientAuthentication()) .setRequestInitializer(getRequestInitializer()) .setClock(getClock()); if (getCredentialStore() != null) { builder.addRefreshListener( new CredentialStoreRefreshListener(userId, getCredentialStore())); } builder.getRefreshListeners().addAll(getRefreshListeners()); return builder.build(); }
[ "private", "OAuthHmacCredential", "new10aCredential", "(", "String", "userId", ")", "{", "ClientParametersAuthentication", "clientAuthentication", "=", "(", "ClientParametersAuthentication", ")", "getClientAuthentication", "(", ")", ";", "OAuthHmacCredential", ".", "Builder",...
Returns a new OAuth 1.0a credential instance based on the given user ID. @param userId user ID or {@code null} if not using a persisted credential store
[ "Returns", "a", "new", "OAuth", "1", ".", "0a", "credential", "instance", "based", "on", "the", "given", "user", "ID", "." ]
train
https://github.com/wuman/android-oauth-client/blob/6e01b81b7319a6954a1156e8b93c0b5cbeb61446/library/src/main/java/com/wuman/android/auth/AuthorizationFlow.java#L345-L364
UrielCh/ovh-java-sdk
ovh-java-sdk-sslGateway/src/main/java/net/minidev/ovh/api/ApiOvhSslGateway.java
ApiOvhSslGateway.eligibility_GET
public OvhEligibilityStatus eligibility_GET(String domain) throws IOException { String qPath = "/sslGateway/eligibility"; StringBuilder sb = path(qPath); query(sb, "domain", domain); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhEligibilityStatus.class); }
java
public OvhEligibilityStatus eligibility_GET(String domain) throws IOException { String qPath = "/sslGateway/eligibility"; StringBuilder sb = path(qPath); query(sb, "domain", domain); String resp = execN(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhEligibilityStatus.class); }
[ "public", "OvhEligibilityStatus", "eligibility_GET", "(", "String", "domain", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/sslGateway/eligibility\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "query", "(", "sb", ",", "\"d...
Check domain eligibility. Return list of eligible IP(s) for this domain. REST: GET /sslGateway/eligibility @param domain [required] domain to check eligibility for SSL Gateway offer API beta
[ "Check", "domain", "eligibility", ".", "Return", "list", "of", "eligible", "IP", "(", "s", ")", "for", "this", "domain", "." ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sslGateway/src/main/java/net/minidev/ovh/api/ApiOvhSslGateway.java#L37-L43
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixtureWithMap.java
SlimFixtureWithMap.setValuesFor
public void setValuesFor(String values, String name) { getMapHelper().setValuesForIn(values, name, getCurrentValues()); }
java
public void setValuesFor(String values, String name) { getMapHelper().setValuesForIn(values, name, getCurrentValues()); }
[ "public", "void", "setValuesFor", "(", "String", "values", ",", "String", "name", ")", "{", "getMapHelper", "(", ")", ".", "setValuesForIn", "(", "values", ",", "name", ",", "getCurrentValues", "(", ")", ")", ";", "}" ]
Stores list of values in map. @param values comma separated list of values. @param name name to use this list for.
[ "Stores", "list", "of", "values", "in", "map", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/slim/SlimFixtureWithMap.java#L89-L91
alkacon/opencms-core
src-modules/org/opencms/workplace/administration/CmsAdminMenu.java
CmsAdminMenu.addItem
public CmsAdminMenuItem addItem( String groupName, String name, String icon, String link, String helpText, boolean enabled, float position, String target) { groupName = CmsToolMacroResolver.resolveMacros(groupName, this); CmsAdminMenuGroup group = getGroup(groupName); if (group == null) { String gid = "group" + m_groupContainer.elementList().size(); group = new CmsAdminMenuGroup(gid, groupName); addGroup(group, position); } String id = "item" + group.getId() + group.getMenuItems().size(); CmsAdminMenuItem item = new CmsAdminMenuItem(id, name, icon, link, helpText, enabled, target); group.addMenuItem(item, position); return item; }
java
public CmsAdminMenuItem addItem( String groupName, String name, String icon, String link, String helpText, boolean enabled, float position, String target) { groupName = CmsToolMacroResolver.resolveMacros(groupName, this); CmsAdminMenuGroup group = getGroup(groupName); if (group == null) { String gid = "group" + m_groupContainer.elementList().size(); group = new CmsAdminMenuGroup(gid, groupName); addGroup(group, position); } String id = "item" + group.getId() + group.getMenuItems().size(); CmsAdminMenuItem item = new CmsAdminMenuItem(id, name, icon, link, helpText, enabled, target); group.addMenuItem(item, position); return item; }
[ "public", "CmsAdminMenuItem", "addItem", "(", "String", "groupName", ",", "String", "name", ",", "String", "icon", ",", "String", "link", ",", "String", "helpText", ",", "boolean", "enabled", ",", "float", "position", ",", "String", "target", ")", "{", "grou...
Adds a new item to the specified menu.<p> If the menu does not exist, it will be created.<p> @param groupName the name of the group @param name the name of the item @param icon the icon to display @param link the link to open when selected @param helpText the help text to display @param enabled if enabled or not @param position the relative position to install the item @param target the target frame to open the link into @return the new item
[ "Adds", "a", "new", "item", "to", "the", "specified", "menu", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/administration/CmsAdminMenu.java#L121-L142
foundation-runtime/service-directory
2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java
WebSocketSerializer.serializeResponse
private static String serializeResponse(ResponseHeader header, Response response) throws JsonGenerationException, JsonMappingException, IOException{ ResponsePair p = new ResponsePair(); p.setResponseHeader(header); if(response == null){ p.setType(null); }else{ p.setType(response.getClass()); } p.setResponse(toJsonStr(response)); return toJsonStr(p); }
java
private static String serializeResponse(ResponseHeader header, Response response) throws JsonGenerationException, JsonMappingException, IOException{ ResponsePair p = new ResponsePair(); p.setResponseHeader(header); if(response == null){ p.setType(null); }else{ p.setType(response.getClass()); } p.setResponse(toJsonStr(response)); return toJsonStr(p); }
[ "private", "static", "String", "serializeResponse", "(", "ResponseHeader", "header", ",", "Response", "response", ")", "throws", "JsonGenerationException", ",", "JsonMappingException", ",", "IOException", "{", "ResponsePair", "p", "=", "new", "ResponsePair", "(", ")",...
Serialize the Response. @param header the ResponseHeader. @param response the Response. @return the JSON String. @throws JsonGenerationException @throws JsonMappingException @throws IOException
[ "Serialize", "the", "Response", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-core/src/main/java/com/cisco/oss/foundation/directory/utils/WebSocketSerializer.java#L173-L183
spotify/styx
styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java
TimeUtil.isAligned
public static boolean isAligned(Instant instant, Schedule schedule) { // executionTime.isMatch ignores seconds for unix cron // so we fail the check immediately if there is a sub-minute value if (!instant.truncatedTo(ChronoUnit.MINUTES).equals(instant)) { return false; } final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule)); final ZonedDateTime utcDateTime = instant.atZone(UTC); return executionTime.isMatch(utcDateTime); }
java
public static boolean isAligned(Instant instant, Schedule schedule) { // executionTime.isMatch ignores seconds for unix cron // so we fail the check immediately if there is a sub-minute value if (!instant.truncatedTo(ChronoUnit.MINUTES).equals(instant)) { return false; } final ExecutionTime executionTime = ExecutionTime.forCron(cron(schedule)); final ZonedDateTime utcDateTime = instant.atZone(UTC); return executionTime.isMatch(utcDateTime); }
[ "public", "static", "boolean", "isAligned", "(", "Instant", "instant", ",", "Schedule", "schedule", ")", "{", "// executionTime.isMatch ignores seconds for unix cron", "// so we fail the check immediately if there is a sub-minute value", "if", "(", "!", "instant", ".", "truncat...
Tests if a given instant is aligned with the execution times of a {@link Schedule}. @param instant The instant to test @param schedule The schedule to test against @return true if the given instant aligns with the schedule
[ "Tests", "if", "a", "given", "instant", "is", "aligned", "with", "the", "execution", "times", "of", "a", "{", "@link", "Schedule", "}", "." ]
train
https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-common/src/main/java/com/spotify/styx/util/TimeUtil.java#L189-L200
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
FormLayout.takeIntoAccount
private boolean takeIntoAccount(Component component, CellConstraints cc) { return component.isVisible() || cc.honorsVisibility == null && !getHonorsVisibility() || Boolean.FALSE.equals(cc.honorsVisibility); }
java
private boolean takeIntoAccount(Component component, CellConstraints cc) { return component.isVisible() || cc.honorsVisibility == null && !getHonorsVisibility() || Boolean.FALSE.equals(cc.honorsVisibility); }
[ "private", "boolean", "takeIntoAccount", "(", "Component", "component", ",", "CellConstraints", "cc", ")", "{", "return", "component", ".", "isVisible", "(", ")", "||", "cc", ".", "honorsVisibility", "==", "null", "&&", "!", "getHonorsVisibility", "(", ")", "|...
Checks and answers whether the given component with the specified CellConstraints shall be taken into account for the layout. @param component the component to test @param cc the component's associated CellConstraints @return {@code true} if a) {@code component} is visible, or b) {@code component} has no individual setting and the container-wide settings ignores the visibility, or c) {@code cc} indicates that this individual component ignores the visibility.
[ "Checks", "and", "answers", "whether", "the", "given", "component", "with", "the", "specified", "CellConstraints", "shall", "be", "taken", "into", "account", "for", "the", "layout", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L1665-L1669
knightliao/apollo
src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java
DateUtils.isOverlay
public static boolean isOverlay(Date date1Start, Date date1End, Date date2Start, Date date2End) { return ((date1Start.getTime() >= date2Start.getTime()) && date1Start.getTime() <= date2End.getTime()) || ((date2Start.getTime() >= date1Start.getTime()) && date2Start.getTime() <= date1End.getTime()); }
java
public static boolean isOverlay(Date date1Start, Date date1End, Date date2Start, Date date2End) { return ((date1Start.getTime() >= date2Start.getTime()) && date1Start.getTime() <= date2End.getTime()) || ((date2Start.getTime() >= date1Start.getTime()) && date2Start.getTime() <= date1End.getTime()); }
[ "public", "static", "boolean", "isOverlay", "(", "Date", "date1Start", ",", "Date", "date1End", ",", "Date", "date2Start", ",", "Date", "date2End", ")", "{", "return", "(", "(", "date1Start", ".", "getTime", "(", ")", ">=", "date2Start", ".", "getTime", "(...
校验两段时间是否有重合 @param date1Start 时间段1开始 @param date1End 时间段1结束 @param date2Start 时间段2开始 @param date2End 时间段2结束 @return <p/> <code>true</code>:有重合 <p/> <code>false</code>:无重合
[ "校验两段时间是否有重合" ]
train
https://github.com/knightliao/apollo/blob/d7a283659fa3e67af6375db8969b2d065a8ce6eb/src/main/java/com/github/knightliao/apollo/utils/time/DateUtils.java#L1132-L1135
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/functions/DifferentialFunctionFactory.java
DifferentialFunctionFactory.reductionBroadcastableWithOrigShape
public SDVariable reductionBroadcastableWithOrigShape(int origRank, int[] reduceDims, SDVariable toExpand) { if (Shape.isWholeArray(origRank, reduceDims)) { //Output is [1,1] which is already broadcastable return toExpand; } else if (origRank == 2 && reduceDims.length == 1) { //In this case: [a,b] -> [1,b] or [a,b] -> [a,1] //both are already broadcastable return toExpand; } else { //Example: [a,b,c].sum(1) -> [a,c]... want [a,1,c] for (int d : reduceDims) { toExpand = sameDiff().expandDims(toExpand, d); } return toExpand; } }
java
public SDVariable reductionBroadcastableWithOrigShape(int origRank, int[] reduceDims, SDVariable toExpand) { if (Shape.isWholeArray(origRank, reduceDims)) { //Output is [1,1] which is already broadcastable return toExpand; } else if (origRank == 2 && reduceDims.length == 1) { //In this case: [a,b] -> [1,b] or [a,b] -> [a,1] //both are already broadcastable return toExpand; } else { //Example: [a,b,c].sum(1) -> [a,c]... want [a,1,c] for (int d : reduceDims) { toExpand = sameDiff().expandDims(toExpand, d); } return toExpand; } }
[ "public", "SDVariable", "reductionBroadcastableWithOrigShape", "(", "int", "origRank", ",", "int", "[", "]", "reduceDims", ",", "SDVariable", "toExpand", ")", "{", "if", "(", "Shape", ".", "isWholeArray", "(", "origRank", ",", "reduceDims", ")", ")", "{", "//O...
Add 1s as required to the array make an array possible to be broadcast with the original (pre-reduce) array. <p> Example: if doing [a,b,c].sum(1), result is [a,c]. To 'undo' this in a way that can be auto-broadcast, we want to expand as required - i.e., [a,c] -> [a,1,c] which can be auto-broadcast with the original [a,b,c]. This is typically only used with reduction operations backprop. @param origRank Rank of the original array, before the reduction was executed @param reduceDims Dimensions that the original array was reduced from @param toExpand Array to add 1s to the shape to (such that it can be @return Reshaped array.
[ "Add", "1s", "as", "required", "to", "the", "array", "make", "an", "array", "possible", "to", "be", "broadcast", "with", "the", "original", "(", "pre", "-", "reduce", ")", "array", ".", "<p", ">", "Example", ":", "if", "doing", "[", "a", "b", "c", ...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/functions/DifferentialFunctionFactory.java#L791-L806
prolificinteractive/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java
MaterialCalendarView.onDateClicked
protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) { switch (selectionMode) { case SELECTION_MODE_MULTIPLE: { adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } break; case SELECTION_MODE_RANGE: { final List<CalendarDay> currentSelection = adapter.getSelectedDates(); if (currentSelection.size() == 0) { // Selecting the first date of a range adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } else if (currentSelection.size() == 1) { // Selecting the second date of a range final CalendarDay firstDaySelected = currentSelection.get(0); if (firstDaySelected.equals(date)) { // Right now, we are not supporting a range of one day, so we are removing the day instead. adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } else if (firstDaySelected.isAfter(date)) { // Selecting a range, dispatching in reverse order... adapter.selectRange(date, firstDaySelected); dispatchOnRangeSelected(adapter.getSelectedDates()); } else { // Selecting a range, dispatching in order... adapter.selectRange(firstDaySelected, date); dispatchOnRangeSelected(adapter.getSelectedDates()); } } else { // Clearing selection and making a selection of the new date. adapter.clearSelections(); adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } } break; default: case SELECTION_MODE_SINGLE: { adapter.clearSelections(); adapter.setDateSelected(date, true); dispatchOnDateSelected(date, true); } break; } }
java
protected void onDateClicked(@NonNull CalendarDay date, boolean nowSelected) { switch (selectionMode) { case SELECTION_MODE_MULTIPLE: { adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } break; case SELECTION_MODE_RANGE: { final List<CalendarDay> currentSelection = adapter.getSelectedDates(); if (currentSelection.size() == 0) { // Selecting the first date of a range adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } else if (currentSelection.size() == 1) { // Selecting the second date of a range final CalendarDay firstDaySelected = currentSelection.get(0); if (firstDaySelected.equals(date)) { // Right now, we are not supporting a range of one day, so we are removing the day instead. adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } else if (firstDaySelected.isAfter(date)) { // Selecting a range, dispatching in reverse order... adapter.selectRange(date, firstDaySelected); dispatchOnRangeSelected(adapter.getSelectedDates()); } else { // Selecting a range, dispatching in order... adapter.selectRange(firstDaySelected, date); dispatchOnRangeSelected(adapter.getSelectedDates()); } } else { // Clearing selection and making a selection of the new date. adapter.clearSelections(); adapter.setDateSelected(date, nowSelected); dispatchOnDateSelected(date, nowSelected); } } break; default: case SELECTION_MODE_SINGLE: { adapter.clearSelections(); adapter.setDateSelected(date, true); dispatchOnDateSelected(date, true); } break; } }
[ "protected", "void", "onDateClicked", "(", "@", "NonNull", "CalendarDay", "date", ",", "boolean", "nowSelected", ")", "{", "switch", "(", "selectionMode", ")", "{", "case", "SELECTION_MODE_MULTIPLE", ":", "{", "adapter", ".", "setDateSelected", "(", "date", ",",...
Call by {@link CalendarPagerView} to indicate that a day was clicked and we should handle it. This method will always process the click to the selected date. @param date date of the day that was clicked @param nowSelected true if the date is now selected, false otherwise
[ "Call", "by", "{", "@link", "CalendarPagerView", "}", "to", "indicate", "that", "a", "day", "was", "clicked", "and", "we", "should", "handle", "it", ".", "This", "method", "will", "always", "process", "the", "click", "to", "the", "selected", "date", "." ]
train
https://github.com/prolificinteractive/material-calendarview/blob/04fae8175fd034d0a7131f8cb253cae883a88aa2/library/src/main/java/com/prolificinteractive/materialcalendarview/MaterialCalendarView.java#L1397-L1443
virgo47/javasimon
core/src/main/java/org/javasimon/callback/timeline/TimelineCallback.java
TimelineCallback.onSimonCreated
@Override public void onSimonCreated(Simon simon) { if (simon instanceof Stopwatch) { simon.setAttribute(timelineAttributeName, new StopwatchTimeline(timelineCapacity, timeRangeWidth)); } }
java
@Override public void onSimonCreated(Simon simon) { if (simon instanceof Stopwatch) { simon.setAttribute(timelineAttributeName, new StopwatchTimeline(timelineCapacity, timeRangeWidth)); } }
[ "@", "Override", "public", "void", "onSimonCreated", "(", "Simon", "simon", ")", "{", "if", "(", "simon", "instanceof", "Stopwatch", ")", "{", "simon", ".", "setAttribute", "(", "timelineAttributeName", ",", "new", "StopwatchTimeline", "(", "timelineCapacity", "...
On simon creation a timeline attribute is added (for Stopwatches only). @param simon created simon
[ "On", "simon", "creation", "a", "timeline", "attribute", "is", "added", "(", "for", "Stopwatches", "only", ")", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/timeline/TimelineCallback.java#L77-L82
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/DiscountSettingsUrl.java
DiscountSettingsUrl.getDiscountSettingsUrl
public static MozuUrl getDiscountSettingsUrl(Integer catalogId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/discountsettings/{catalogId}?responseFields={responseFields}"); formatter.formatUrl("catalogId", catalogId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getDiscountSettingsUrl(Integer catalogId, String responseFields) { UrlFormatter formatter = new UrlFormatter("/api/commerce/catalog/admin/discountsettings/{catalogId}?responseFields={responseFields}"); formatter.formatUrl("catalogId", catalogId); formatter.formatUrl("responseFields", responseFields); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getDiscountSettingsUrl", "(", "Integer", "catalogId", ",", "String", "responseFields", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/catalog/admin/discountsettings/{catalogId}?responseFields={responseField...
Get Resource Url for GetDiscountSettings @param catalogId Unique identifier for a catalog. @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetDiscountSettings" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/catalog/admin/DiscountSettingsUrl.java#L22-L28
policeman-tools/forbidden-apis
src/main/java/de/thetaphi/forbiddenapis/Signatures.java
Signatures.parseSignaturesStream
public void parseSignaturesStream(InputStream in, String name) throws IOException,ParseException { logger.info("Reading API signatures: " + name); final Set<String> missingClasses = new TreeSet<String>(); parseSignaturesStream(in, false, missingClasses); reportMissingSignatureClasses(missingClasses); }
java
public void parseSignaturesStream(InputStream in, String name) throws IOException,ParseException { logger.info("Reading API signatures: " + name); final Set<String> missingClasses = new TreeSet<String>(); parseSignaturesStream(in, false, missingClasses); reportMissingSignatureClasses(missingClasses); }
[ "public", "void", "parseSignaturesStream", "(", "InputStream", "in", ",", "String", "name", ")", "throws", "IOException", ",", "ParseException", "{", "logger", ".", "info", "(", "\"Reading API signatures: \"", "+", "name", ")", ";", "final", "Set", "<", "String"...
Reads a list of API signatures. Closes the Reader when done (on Exception, too)!
[ "Reads", "a", "list", "of", "API", "signatures", ".", "Closes", "the", "Reader", "when", "done", "(", "on", "Exception", "too", ")", "!" ]
train
https://github.com/policeman-tools/forbidden-apis/blob/df5f00c6bb779875ec6bae967f7cec96670b27d9/src/main/java/de/thetaphi/forbiddenapis/Signatures.java#L301-L306
ogaclejapan/SmartTabLayout
utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java
Bundler.putIntegerArrayList
public Bundler putIntegerArrayList(String key, ArrayList<Integer> value) { bundle.putIntegerArrayList(key, value); return this; }
java
public Bundler putIntegerArrayList(String key, ArrayList<Integer> value) { bundle.putIntegerArrayList(key, value); return this; }
[ "public", "Bundler", "putIntegerArrayList", "(", "String", "key", ",", "ArrayList", "<", "Integer", ">", "value", ")", "{", "bundle", ".", "putIntegerArrayList", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts an ArrayList<Integer> value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value an ArrayList<Integer> object, or null @return this
[ "Inserts", "an", "ArrayList<Integer", ">", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/ogaclejapan/SmartTabLayout/blob/712e81a92f1e12a3c33dcbda03d813e0162e8589/utils-v4/src/main/java/com/ogaclejapan/smarttablayout/utils/v4/Bundler.java#L225-L228
ZieIony/Carbon
carbon/src/main/java/carbon/shadow/ShapePath.java
ShapePath.addArc
public void addArc(float left, float top, float right, float bottom, float startAngle, float sweepAngle) { PathArcOperation operation = new PathArcOperation(left, top, right, bottom); operation.startAngle = startAngle; operation.sweepAngle = sweepAngle; operations.add(operation); ArcShadowOperation arcShadowOperation = new ArcShadowOperation(operation); float endAngle = startAngle + sweepAngle; // Flip the startAngle and endAngle when drawing the shadow inside the bounds. They represent // the angles from the center of the circle to the start or end of the arc, respectively. When // the shadow is drawn inside the arc, it is going the opposite direction. boolean drawShadowInsideBounds = sweepAngle < 0; addShadowCompatOperation( arcShadowOperation, drawShadowInsideBounds ? (180 + startAngle) % 360 : startAngle, drawShadowInsideBounds ? (180 + endAngle) % 360 : endAngle); endX = (left + right) * 0.5f + (right - left) / 2 * (float) Math.cos(Math.toRadians(startAngle + sweepAngle)); endY = (top + bottom) * 0.5f + (bottom - top) / 2 * (float) Math.sin(Math.toRadians(startAngle + sweepAngle)); }
java
public void addArc(float left, float top, float right, float bottom, float startAngle, float sweepAngle) { PathArcOperation operation = new PathArcOperation(left, top, right, bottom); operation.startAngle = startAngle; operation.sweepAngle = sweepAngle; operations.add(operation); ArcShadowOperation arcShadowOperation = new ArcShadowOperation(operation); float endAngle = startAngle + sweepAngle; // Flip the startAngle and endAngle when drawing the shadow inside the bounds. They represent // the angles from the center of the circle to the start or end of the arc, respectively. When // the shadow is drawn inside the arc, it is going the opposite direction. boolean drawShadowInsideBounds = sweepAngle < 0; addShadowCompatOperation( arcShadowOperation, drawShadowInsideBounds ? (180 + startAngle) % 360 : startAngle, drawShadowInsideBounds ? (180 + endAngle) % 360 : endAngle); endX = (left + right) * 0.5f + (right - left) / 2 * (float) Math.cos(Math.toRadians(startAngle + sweepAngle)); endY = (top + bottom) * 0.5f + (bottom - top) / 2 * (float) Math.sin(Math.toRadians(startAngle + sweepAngle)); }
[ "public", "void", "addArc", "(", "float", "left", ",", "float", "top", ",", "float", "right", ",", "float", "bottom", ",", "float", "startAngle", ",", "float", "sweepAngle", ")", "{", "PathArcOperation", "operation", "=", "new", "PathArcOperation", "(", "lef...
Add an arc to the ShapePath. @param left the X coordinate of the left side of the rectangle containing the arc oval. @param top the Y coordinate of the top of the rectangle containing the arc oval. @param right the X coordinate of the right side of the rectangle containing the arc oval. @param bottom the Y coordinate of the bottom of the rectangle containing the arc oval. @param startAngle start angle of the arc. @param sweepAngle sweep angle of the arc.
[ "Add", "an", "arc", "to", "the", "ShapePath", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShapePath.java#L129-L151
FasterXML/woodstox
src/main/java/com/ctc/wstx/dtd/DTDSchemaFactory.java
DTDSchemaFactory.doCreateSchema
@SuppressWarnings("resource") protected XMLValidationSchema doCreateSchema (ReaderConfig rcfg, InputBootstrapper bs, String publicId, String systemIdStr, URL ctxt) throws XMLStreamException { try { Reader r = bs.bootstrapInput(rcfg, false, XmlConsts.XML_V_UNKNOWN); if (bs.declaredXml11()) { rcfg.enableXml11(true); } if (ctxt == null) { // this is just needed as context for param entity expansion ctxt = URLUtil.urlFromCurrentDir(); } /* Note: need to pass unknown for 'xmlVersion' here (as well as * above for bootstrapping), since this is assumed to be the main * level parsed document and no xml version compatibility checks * should be done. */ SystemId systemId = SystemId.construct(systemIdStr, ctxt); WstxInputSource src = InputSourceFactory.constructEntitySource (rcfg, null, null, bs, publicId, systemId, XmlConsts.XML_V_UNKNOWN, r); /* true -> yes, fully construct for validation * (does not mean it has to be used for validation, but required * if it is to be used for that purpose) */ return FullDTDReader.readExternalSubset(src, rcfg, /*int.subset*/null, true, bs.getDeclaredVersion()); } catch (IOException ioe) { throw new WstxIOException(ioe); } }
java
@SuppressWarnings("resource") protected XMLValidationSchema doCreateSchema (ReaderConfig rcfg, InputBootstrapper bs, String publicId, String systemIdStr, URL ctxt) throws XMLStreamException { try { Reader r = bs.bootstrapInput(rcfg, false, XmlConsts.XML_V_UNKNOWN); if (bs.declaredXml11()) { rcfg.enableXml11(true); } if (ctxt == null) { // this is just needed as context for param entity expansion ctxt = URLUtil.urlFromCurrentDir(); } /* Note: need to pass unknown for 'xmlVersion' here (as well as * above for bootstrapping), since this is assumed to be the main * level parsed document and no xml version compatibility checks * should be done. */ SystemId systemId = SystemId.construct(systemIdStr, ctxt); WstxInputSource src = InputSourceFactory.constructEntitySource (rcfg, null, null, bs, publicId, systemId, XmlConsts.XML_V_UNKNOWN, r); /* true -> yes, fully construct for validation * (does not mean it has to be used for validation, but required * if it is to be used for that purpose) */ return FullDTDReader.readExternalSubset(src, rcfg, /*int.subset*/null, true, bs.getDeclaredVersion()); } catch (IOException ioe) { throw new WstxIOException(ioe); } }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "protected", "XMLValidationSchema", "doCreateSchema", "(", "ReaderConfig", "rcfg", ",", "InputBootstrapper", "bs", ",", "String", "publicId", ",", "String", "systemIdStr", ",", "URL", "ctxt", ")", "throws", "XMLStre...
The main validator construction method, called by all externally visible methods.
[ "The", "main", "validator", "construction", "method", "called", "by", "all", "externally", "visible", "methods", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDSchemaFactory.java#L168-L198
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/mock/servlet/MockHttpServletRequest.java
MockHttpServletRequest.setParameter
public void setParameter(final String name, final String value) { String[] currentValue = (String[]) parameters.get(name); if (currentValue == null) { currentValue = new String[]{value}; } else { // convert the current values into a new array.. String[] newValues = new String[currentValue.length + 1]; System.arraycopy(currentValue, 0, newValues, 0, currentValue.length); newValues[newValues.length - 1] = value; currentValue = newValues; } parameters.put(name, currentValue); }
java
public void setParameter(final String name, final String value) { String[] currentValue = (String[]) parameters.get(name); if (currentValue == null) { currentValue = new String[]{value}; } else { // convert the current values into a new array.. String[] newValues = new String[currentValue.length + 1]; System.arraycopy(currentValue, 0, newValues, 0, currentValue.length); newValues[newValues.length - 1] = value; currentValue = newValues; } parameters.put(name, currentValue); }
[ "public", "void", "setParameter", "(", "final", "String", "name", ",", "final", "String", "value", ")", "{", "String", "[", "]", "currentValue", "=", "(", "String", "[", "]", ")", "parameters", ".", "get", "(", "name", ")", ";", "if", "(", "currentValu...
Sets a parameter. If the parameter already exists, another value will be added to the parameter values. @param name the parameter name @param value the parameter value
[ "Sets", "a", "parameter", ".", "If", "the", "parameter", "already", "exists", "another", "value", "will", "be", "added", "to", "the", "parameter", "values", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/mock/servlet/MockHttpServletRequest.java#L490-L504
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java
CommonDatabaseMetaData.getProcedures
public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) throws SQLException { log.info("getting empty result set, procedures"); return getEmptyResultSet(); }
java
public ResultSet getProcedures(final String catalog, final String schemaPattern, final String procedureNamePattern) throws SQLException { log.info("getting empty result set, procedures"); return getEmptyResultSet(); }
[ "public", "ResultSet", "getProcedures", "(", "final", "String", "catalog", ",", "final", "String", "schemaPattern", ",", "final", "String", "procedureNamePattern", ")", "throws", "SQLException", "{", "log", ".", "info", "(", "\"getting empty result set, procedures\"", ...
Retrieves a description of the stored procedures available in the given catalog. <p/> Only procedure descriptions matching the schema and procedure name criteria are returned. They are ordered by <code>PROCEDURE_CAT</code>, <code>PROCEDURE_SCHEM</code>, <code>PROCEDURE_NAME</code> and <code>SPECIFIC_ NAME</code>. <p/> <P>Each procedure description has the the following columns: <OL> <LI><B>PROCEDURE_CAT</B> String => procedure catalog (may be <code>null</code>) <LI><B>PROCEDURE_SCHEM</B> String => procedure schema (may be <code>null</code>) <LI><B>PROCEDURE_NAME</B> String => procedure name <LI> reserved for future use <LI> reserved for future use <LI> reserved for future use <LI><B>REMARKS</B> String => explanatory comment on the procedure <LI><B>PROCEDURE_TYPE</B> short => kind of procedure: <UL> <LI> procedureResultUnknown - Cannot determine if a return value will be returned <LI> procedureNoResult - Does not return a return value <LI> procedureReturnsResult - Returns a return value </UL> <LI><B>SPECIFIC_NAME</B> String => The name which uniquely identifies this procedure within its schema. </OL> <p/> A user may not have permissions to execute any of the procedures that are returned by <code>getProcedures</code> @param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog; <code>null</code> means that the catalog name should not be used to narrow the search @param schemaPattern a schema name pattern; must match the schema name as it is stored in the database; "" retrieves those without a schema; <code>null</code> means that the schema name should not be used to narrow the search @param procedureNamePattern a procedure name pattern; must match the procedure name as it is stored in the database @return <code>ResultSet</code> - each row is a procedure description @throws java.sql.SQLException if a database access error occurs @see #getSearchStringEscape
[ "Retrieves", "a", "description", "of", "the", "stored", "procedures", "available", "in", "the", "given", "catalog", ".", "<p", "/", ">", "Only", "procedure", "descriptions", "matching", "the", "schema", "and", "procedure", "name", "criteria", "are", "returned", ...
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java#L1342-L1346
TGIO/RNCryptorNative
jncryptor/src/main/java/org/cryptonode/jncryptor/StreamUtils.java
StreamUtils.readAllBytes
static int readAllBytes(InputStream in, byte[] buffer) throws IOException { int index = 0; while (index < buffer.length) { int read = in.read(buffer, index, buffer.length - index); if (read == -1) { return index; } index += read; } return index; }
java
static int readAllBytes(InputStream in, byte[] buffer) throws IOException { int index = 0; while (index < buffer.length) { int read = in.read(buffer, index, buffer.length - index); if (read == -1) { return index; } index += read; } return index; }
[ "static", "int", "readAllBytes", "(", "InputStream", "in", ",", "byte", "[", "]", "buffer", ")", "throws", "IOException", "{", "int", "index", "=", "0", ";", "while", "(", "index", "<", "buffer", ".", "length", ")", "{", "int", "read", "=", "in", "."...
Attempts to fill the buffer by reading as many bytes as available. The returned number indicates how many bytes were read, which may be smaller than the buffer size if EOF was reached. @param in input stream @param buffer buffer to fill @return the number of bytes read @throws IOException
[ "Attempts", "to", "fill", "the", "buffer", "by", "reading", "as", "many", "bytes", "as", "available", ".", "The", "returned", "number", "indicates", "how", "many", "bytes", "were", "read", "which", "may", "be", "smaller", "than", "the", "buffer", "size", "...
train
https://github.com/TGIO/RNCryptorNative/blob/5209f10b988e4033c0b769a40b0d6cc99ea16af7/jncryptor/src/main/java/org/cryptonode/jncryptor/StreamUtils.java#L38-L50
davidmoten/rxjava-extras
src/main/java/com/github/davidmoten/rx/Serialized.java
Serialized.read
public static <T extends Serializable> Observable<T> read(final ObjectInputStream ois) { return Observable.create(new SyncOnSubscribe<ObjectInputStream,T>() { @Override protected ObjectInputStream generateState() { return ois; } @Override protected ObjectInputStream next(ObjectInputStream ois, Observer<? super T> observer) { try { @SuppressWarnings("unchecked") T t = (T) ois.readObject(); observer.onNext(t); } catch (EOFException e) { observer.onCompleted(); } catch (ClassNotFoundException e) { observer.onError(e); } catch (IOException e) { observer.onError(e); } return ois; } }); }
java
public static <T extends Serializable> Observable<T> read(final ObjectInputStream ois) { return Observable.create(new SyncOnSubscribe<ObjectInputStream,T>() { @Override protected ObjectInputStream generateState() { return ois; } @Override protected ObjectInputStream next(ObjectInputStream ois, Observer<? super T> observer) { try { @SuppressWarnings("unchecked") T t = (T) ois.readObject(); observer.onNext(t); } catch (EOFException e) { observer.onCompleted(); } catch (ClassNotFoundException e) { observer.onError(e); } catch (IOException e) { observer.onError(e); } return ois; } }); }
[ "public", "static", "<", "T", "extends", "Serializable", ">", "Observable", "<", "T", ">", "read", "(", "final", "ObjectInputStream", "ois", ")", "{", "return", "Observable", ".", "create", "(", "new", "SyncOnSubscribe", "<", "ObjectInputStream", ",", "T", "...
Returns the deserialized objects from the given {@link InputStream} as an {@link Observable} stream. @param ois the {@link ObjectInputStream} @param <T> the generic type of the returned stream @return the stream of deserialized objects from the {@link InputStream} as an {@link Observable}.
[ "Returns", "the", "deserialized", "objects", "from", "the", "given", "{", "@link", "InputStream", "}", "as", "an", "{", "@link", "Observable", "}", "stream", "." ]
train
https://github.com/davidmoten/rxjava-extras/blob/a91d2ba7d454843250e0b0fce36084f9fb02a551/src/main/java/com/github/davidmoten/rx/Serialized.java#L46-L70
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/MultipleStrategyRunner.java
MultipleStrategyRunner.generateOutput
public static void generateOutput(final DataModelIF<Long, Long> testModel, final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations, final EvaluationStrategy<Long, Long> strategy, final EvaluationStrategy.OUTPUT_FORMAT format, final File rankingFolder, final File groundtruthFolder, final String inputFileName, final String strategyClassSimpleName, final String threshold, final String suffix, final Boolean overwrite) throws FileNotFoundException, UnsupportedEncodingException { File outRanking = new File(rankingFolder, "out" + "__" + inputFileName + "__" + strategyClassSimpleName + "__" + threshold + suffix); File outGroundtruth = new File(groundtruthFolder, "gr" + "__" + inputFileName + "__" + strategyClassSimpleName + "__" + threshold + suffix); StrategyRunner.generateOutput(testModel, mapUserRecommendations, strategy, format, outRanking, outGroundtruth, overwrite); }
java
public static void generateOutput(final DataModelIF<Long, Long> testModel, final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations, final EvaluationStrategy<Long, Long> strategy, final EvaluationStrategy.OUTPUT_FORMAT format, final File rankingFolder, final File groundtruthFolder, final String inputFileName, final String strategyClassSimpleName, final String threshold, final String suffix, final Boolean overwrite) throws FileNotFoundException, UnsupportedEncodingException { File outRanking = new File(rankingFolder, "out" + "__" + inputFileName + "__" + strategyClassSimpleName + "__" + threshold + suffix); File outGroundtruth = new File(groundtruthFolder, "gr" + "__" + inputFileName + "__" + strategyClassSimpleName + "__" + threshold + suffix); StrategyRunner.generateOutput(testModel, mapUserRecommendations, strategy, format, outRanking, outGroundtruth, overwrite); }
[ "public", "static", "void", "generateOutput", "(", "final", "DataModelIF", "<", "Long", ",", "Long", ">", "testModel", ",", "final", "Map", "<", "Long", ",", "List", "<", "Pair", "<", "Long", ",", "Double", ">", ">", ">", "mapUserRecommendations", ",", "...
Runs multiple strategies on some data and outputs the result into a file. @param testModel The test datamodel. @param mapUserRecommendations A map with the recommendations for the users. @param strategy The strategy to use. @param format The format of the printer @param rankingFolder Where to write output. @param groundtruthFolder Where to read test set. @param inputFileName The file names to read. @param strategyClassSimpleName The class name of the strategy. @param threshold The relevance threshold. @param suffix The file suffix. @param overwrite Whether or not to overwrite the results file. @throws FileNotFoundException see {@link StrategyRunner#generateOutput(net.recommenders.rival.core.DataModelIF, java.util.Map, net.recommenders.rival.evaluation.strategy.EvaluationStrategy, net.recommenders.rival.evaluation.strategy.EvaluationStrategy.OUTPUT_FORMAT, java.io.File, java.io.File, java.lang.Boolean)} @throws UnsupportedEncodingException see {@link StrategyRunner#generateOutput(net.recommenders.rival.core.DataModelIF, java.util.Map, net.recommenders.rival.evaluation.strategy.EvaluationStrategy, net.recommenders.rival.evaluation.strategy.EvaluationStrategy.OUTPUT_FORMAT, java.io.File, java.io.File, java.lang.Boolean)}
[ "Runs", "multiple", "strategies", "on", "some", "data", "and", "outputs", "the", "result", "into", "a", "file", "." ]
train
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/MultipleStrategyRunner.java#L300-L308
krummas/DrizzleJDBC
src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java
CommonDatabaseMetaData.getColumnPrivileges
public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern) throws SQLException { log.info("getting empty result set, column privileges"); return getEmptyResultSet(); }
java
public ResultSet getColumnPrivileges(final String catalog, final String schema, final String table, final String columnNamePattern) throws SQLException { log.info("getting empty result set, column privileges"); return getEmptyResultSet(); }
[ "public", "ResultSet", "getColumnPrivileges", "(", "final", "String", "catalog", ",", "final", "String", "schema", ",", "final", "String", "table", ",", "final", "String", "columnNamePattern", ")", "throws", "SQLException", "{", "log", ".", "info", "(", "\"getti...
Retrieves a description of the access rights for a table's columns. <p/> <P>Only privileges matching the column name criteria are returned. They are ordered by COLUMN_NAME and PRIVILEGE. <p/> <P>Each privilige description has the following columns: <OL> <LI><B>TABLE_CAT</B> String => table catalog (may be <code>null</code>) <LI><B>TABLE_SCHEM</B> String => table schema (may be <code>null</code>) <LI><B>TABLE_NAME</B> String => table name <LI><B>COLUMN_NAME</B> String => column name <LI><B>GRANTOR</B> String => grantor of access (may be <code>null</code>) <LI><B>GRANTEE</B> String => grantee of access <LI><B>PRIVILEGE</B> String => name of access (SELECT, INSERT, UPDATE, REFRENCES, ...) <LI><B>IS_GRANTABLE</B> String => "YES" if grantee is permitted to grant to others; "NO" if not; <code>null</code> if unknown </OL> @param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog; <code>null</code> means that the catalog name should not be used to narrow the search @param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those without a schema; <code>null</code> means that the schema name should not be used to narrow the search @param table a table name; must match the table name as it is stored in the database @param columnNamePattern a column name pattern; must match the column name as it is stored in the database @return <code>ResultSet</code> - each row is a column privilege description @throws java.sql.SQLException if a database access error occurs @see #getSearchStringEscape
[ "Retrieves", "a", "description", "of", "the", "access", "rights", "for", "a", "table", "s", "columns", ".", "<p", "/", ">", "<P", ">", "Only", "privileges", "matching", "the", "column", "name", "criteria", "are", "returned", ".", "They", "are", "ordered", ...
train
https://github.com/krummas/DrizzleJDBC/blob/716f31fd71f3cc289edf69844d8117deb86d98d6/src/main/java/org/drizzle/jdbc/CommonDatabaseMetaData.java#L1586-L1590
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/interpolate/array/Interpolate1D_F32.java
Interpolate1D_F32.setInput
public void setInput(float x[], float y[], int size) { if (x.length < size || y.length < size) { throw new IllegalArgumentException("Arrays too small for size."); } if (size < M) { throw new IllegalArgumentException("Not enough data points for M"); } this.x = x; this.y = y; this.size = size; this.dj = Math.min(1, (int) Math.pow(size, 0.25)); ascend = x[size - 1] >= x[0]; }
java
public void setInput(float x[], float y[], int size) { if (x.length < size || y.length < size) { throw new IllegalArgumentException("Arrays too small for size."); } if (size < M) { throw new IllegalArgumentException("Not enough data points for M"); } this.x = x; this.y = y; this.size = size; this.dj = Math.min(1, (int) Math.pow(size, 0.25)); ascend = x[size - 1] >= x[0]; }
[ "public", "void", "setInput", "(", "float", "x", "[", "]", ",", "float", "y", "[", "]", ",", "int", "size", ")", "{", "if", "(", "x", ".", "length", "<", "size", "||", "y", ".", "length", "<", "size", ")", "{", "throw", "new", "IllegalArgumentExc...
Sets the data that is being interpolated. @param x Where the points are sample at. Not modifed. Reference saved. @param y The value at the sample points. Not modifed. Reference saved. @param size The number of points used.
[ "Sets", "the", "data", "that", "is", "being", "interpolated", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/interpolate/array/Interpolate1D_F32.java#L80-L93
CloudSlang/cs-actions
cs-commons/src/main/java/io/cloudslang/content/utils/NumberUtilities.java
NumberUtilities.isValidLong
public static boolean isValidLong(@Nullable final String longStr, final long lowerBound, final long upperBound, final boolean includeLowerBound, final boolean includeUpperBound) { if (lowerBound > upperBound) { throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS); } else if (!isValidLong(longStr)) { return false; } final long aLong = toLong(longStr); final boolean respectsLowerBound = includeLowerBound ? lowerBound <= aLong : lowerBound < aLong; final boolean respectsUpperBound = includeUpperBound ? aLong <= upperBound : aLong < upperBound; return respectsLowerBound && respectsUpperBound; }
java
public static boolean isValidLong(@Nullable final String longStr, final long lowerBound, final long upperBound, final boolean includeLowerBound, final boolean includeUpperBound) { if (lowerBound > upperBound) { throw new IllegalArgumentException(ExceptionValues.INVALID_BOUNDS); } else if (!isValidLong(longStr)) { return false; } final long aLong = toLong(longStr); final boolean respectsLowerBound = includeLowerBound ? lowerBound <= aLong : lowerBound < aLong; final boolean respectsUpperBound = includeUpperBound ? aLong <= upperBound : aLong < upperBound; return respectsLowerBound && respectsUpperBound; }
[ "public", "static", "boolean", "isValidLong", "(", "@", "Nullable", "final", "String", "longStr", ",", "final", "long", "lowerBound", ",", "final", "long", "upperBound", ",", "final", "boolean", "includeLowerBound", ",", "final", "boolean", "includeUpperBound", ")...
Given a long integer string, it checks if it's a valid long (base on apaches NumberUtils.createLong) and if it's between the lowerBound and upperBound. @param longStr the long integer string to check @param lowerBound the lower bound of the interval @param upperBound the upper bound of the interval @param includeLowerBound boolean if to include the lower bound of the interval @param includeUpperBound boolean if to include the upper bound of the interval @return true if the long integer string is valid and in between the lowerBound and upperBound, false otherwise @throws IllegalArgumentException if the lowerBound is not less than the upperBound
[ "Given", "a", "long", "integer", "string", "it", "checks", "if", "it", "s", "a", "valid", "long", "(", "base", "on", "apaches", "NumberUtils", ".", "createLong", ")", "and", "if", "it", "s", "between", "the", "lowerBound", "and", "upperBound", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-commons/src/main/java/io/cloudslang/content/utils/NumberUtilities.java#L108-L118
pressgang-ccms/PressGangCCMSContentSpec
src/main/java/org/jboss/pressgang/ccms/contentspec/utils/CSTransformer.java
CSTransformer.transformMetaData
public static KeyValueNode<?> transformMetaData(final CSNodeWrapper node) { return transformMetaData(node, new HashMap<Integer, Node>(), new HashMap<String, SpecTopic>(), new ArrayList<CSNodeWrapper>()); }
java
public static KeyValueNode<?> transformMetaData(final CSNodeWrapper node) { return transformMetaData(node, new HashMap<Integer, Node>(), new HashMap<String, SpecTopic>(), new ArrayList<CSNodeWrapper>()); }
[ "public", "static", "KeyValueNode", "<", "?", ">", "transformMetaData", "(", "final", "CSNodeWrapper", "node", ")", "{", "return", "transformMetaData", "(", "node", ",", "new", "HashMap", "<", "Integer", ",", "Node", ">", "(", ")", ",", "new", "HashMap", "...
Transforms a MetaData CSNode into a KeyValuePair that can be added to a ContentSpec object. @param node The CSNode to be transformed. @return The transformed KeyValuePair object.
[ "Transforms", "a", "MetaData", "CSNode", "into", "a", "KeyValuePair", "that", "can", "be", "added", "to", "a", "ContentSpec", "object", "." ]
train
https://github.com/pressgang-ccms/PressGangCCMSContentSpec/blob/2bc02e2971e4522b47a130fb7ae5a0f5ad377df1/src/main/java/org/jboss/pressgang/ccms/contentspec/utils/CSTransformer.java#L259-L261
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/FileUtils.java
FileUtils.changeLocalFileUser
public static void changeLocalFileUser(String path, String user) throws IOException { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); PosixFileAttributeView view = Files.getFileAttributeView(Paths.get(path), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(user); view.setOwner(userPrincipal); }
java
public static void changeLocalFileUser(String path, String user) throws IOException { UserPrincipalLookupService lookupService = FileSystems.getDefault().getUserPrincipalLookupService(); PosixFileAttributeView view = Files.getFileAttributeView(Paths.get(path), PosixFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); UserPrincipal userPrincipal = lookupService.lookupPrincipalByName(user); view.setOwner(userPrincipal); }
[ "public", "static", "void", "changeLocalFileUser", "(", "String", "path", ",", "String", "user", ")", "throws", "IOException", "{", "UserPrincipalLookupService", "lookupService", "=", "FileSystems", ".", "getDefault", "(", ")", ".", "getUserPrincipalLookupService", "(...
Changes the local file's user. @param path that will change owner @param user the new user
[ "Changes", "the", "local", "file", "s", "user", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/FileUtils.java#L143-L151
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/MemoryUtil.java
MemoryUtil.checkSize
public static void checkSize(final int size, final String className) { if (MemoryUtil.WARN_THRESHOLD < size) { MemoryUtil.log(className + " may be leaking memory, it contains a large number of items: " + size); } }
java
public static void checkSize(final int size, final String className) { if (MemoryUtil.WARN_THRESHOLD < size) { MemoryUtil.log(className + " may be leaking memory, it contains a large number of items: " + size); } }
[ "public", "static", "void", "checkSize", "(", "final", "int", "size", ",", "final", "String", "className", ")", "{", "if", "(", "MemoryUtil", ".", "WARN_THRESHOLD", "<", "size", ")", "{", "MemoryUtil", ".", "log", "(", "className", "+", "\" may be leaking me...
Performs default check on the size of a "registry" of UI widgets (or similar). In practice "size" is likely to be the size of a java Collection but it could be anything you want. This is a convenience which should be adequate for the majority of cases. @param size The current size of a component registry (or similar). @param className The name of the class which holds the registry.
[ "Performs", "default", "check", "on", "the", "size", "of", "a", "registry", "of", "UI", "widgets", "(", "or", "similar", ")", ".", "In", "practice", "size", "is", "likely", "to", "be", "the", "size", "of", "a", "java", "Collection", "but", "it", "could...
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/util/MemoryUtil.java#L43-L47
hypercube1024/firefly
firefly-common/src/main/java/com/firefly/utils/function/Actions.java
Actions.toFunc
public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Func9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> toFunc( final Action9<T1, T2, T3, T4, T5, T6, T7, T8, T9> action, final R result) { return new Func9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R>() { @Override public R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) { action.call(t1, t2, t3, t4, t5, t6, t7, t8, t9); return result; } }; }
java
public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Func9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> toFunc( final Action9<T1, T2, T3, T4, T5, T6, T7, T8, T9> action, final R result) { return new Func9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R>() { @Override public R call(T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8, T9 t9) { action.call(t1, t2, t3, t4, t5, t6, t7, t8, t9); return result; } }; }
[ "public", "static", "<", "T1", ",", "T2", ",", "T3", ",", "T4", ",", "T5", ",", "T6", ",", "T7", ",", "T8", ",", "T9", ",", "R", ">", "Func9", "<", "T1", ",", "T2", ",", "T3", ",", "T4", ",", "T5", ",", "T6", ",", "T7", ",", "T8", ",", ...
Converts an {@link Action9} to a function that calls the action and returns a specified value. @param action the {@link Action9} to convert @param result the value to return from the function call @return a {@link Func9} that calls {@code action} and returns {@code result}
[ "Converts", "an", "{", "@link", "Action9", "}", "to", "a", "function", "that", "calls", "the", "action", "and", "returns", "a", "specified", "value", "." ]
train
https://github.com/hypercube1024/firefly/blob/ed3fc75b7c54a65b1e7d8141d01b49144bb423a3/firefly-common/src/main/java/com/firefly/utils/function/Actions.java#L359-L368
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/destination/PubSubRealization.java
PubSubRealization.createConsumerDispatcher
private ConsumerDispatcher createConsumerDispatcher( ConsumerDispatcherState state, SubscriptionItemStream subscription) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "createConsumerDispatcher", new Object[] { state, subscription }); /* * Now create the consumer dispatcher, * passing it the subscription reference stream that has been created */ final ConsumerDispatcher newConsumerDispatcher = new ConsumerDispatcher(_baseDestinationHandler, subscription, state); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createConsumerDispatcher", newConsumerDispatcher); return newConsumerDispatcher; }
java
private ConsumerDispatcher createConsumerDispatcher( ConsumerDispatcherState state, SubscriptionItemStream subscription) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry( tc, "createConsumerDispatcher", new Object[] { state, subscription }); /* * Now create the consumer dispatcher, * passing it the subscription reference stream that has been created */ final ConsumerDispatcher newConsumerDispatcher = new ConsumerDispatcher(_baseDestinationHandler, subscription, state); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createConsumerDispatcher", newConsumerDispatcher); return newConsumerDispatcher; }
[ "private", "ConsumerDispatcher", "createConsumerDispatcher", "(", "ConsumerDispatcherState", "state", ",", "SubscriptionItemStream", "subscription", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")",...
<p>This method is used to create a consumer dispatcher for subscriptions A subscription can be either durable or non-durable. If the subscription is durable, the reference stream should be persistent, otherwise it can be a temporary reference stream.</p> @param state The state object @param subscription The subscription referenceStream to pass to the Consumer Dispatcher. @return ConsumerDispatcher The created Consumer dispatcher
[ "<p", ">", "This", "method", "is", "used", "to", "create", "a", "consumer", "dispatcher", "for", "subscriptions", "A", "subscription", "can", "be", "either", "durable", "or", "non", "-", "durable", ".", "If", "the", "subscription", "is", "durable", "the", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/destination/PubSubRealization.java#L570-L591
undera/jmeter-plugins
plugins/jmxmon/src/main/java/kg/apc/jmeter/jmxmon/JMXMonConnectionPool.java
JMXMonConnectionPool.getConnection
public MBeanServerConnection getConnection(String jmxUrl, Hashtable attributes, boolean wait) { JMXMonConnection connection = (JMXMonConnection)pool.get(jmxUrl); if (connection == null) { connection = new JMXMonConnection(jmxUrl); pool.put(jmxUrl, connection); } return connection.connect(attributes, wait); }
java
public MBeanServerConnection getConnection(String jmxUrl, Hashtable attributes, boolean wait) { JMXMonConnection connection = (JMXMonConnection)pool.get(jmxUrl); if (connection == null) { connection = new JMXMonConnection(jmxUrl); pool.put(jmxUrl, connection); } return connection.connect(attributes, wait); }
[ "public", "MBeanServerConnection", "getConnection", "(", "String", "jmxUrl", ",", "Hashtable", "attributes", ",", "boolean", "wait", ")", "{", "JMXMonConnection", "connection", "=", "(", "JMXMonConnection", ")", "pool", ".", "get", "(", "jmxUrl", ")", ";", "if",...
Try to get a connection to the specified jmx url @param jmxUrl the jmx url @param attributes jmx connection attributes @param wait if true wait the current thread until the end of the connection attempt @return a jmx connection
[ "Try", "to", "get", "a", "connection", "to", "the", "specified", "jmx", "url" ]
train
https://github.com/undera/jmeter-plugins/blob/416d2a77249ab921c7e4134c3e6a9639901ef7e8/plugins/jmxmon/src/main/java/kg/apc/jmeter/jmxmon/JMXMonConnectionPool.java#L61-L70
spring-projects/spring-hateoas
src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorHandlerMethodReturnValueHandler.java
RepresentationModelProcessorHandlerMethodReturnValueHandler.rewrapResult
Object rewrapResult(RepresentationModel<?> newBody, @Nullable Object originalValue) { if (!(originalValue instanceof HttpEntity)) { return rootLinksAsHeaders ? HeaderLinksResponseEntity.wrap(newBody) : newBody; } HttpEntity<RepresentationModel<?>> entity = null; if (originalValue instanceof ResponseEntity) { ResponseEntity<?> source = (ResponseEntity<?>) originalValue; entity = new ResponseEntity<>(newBody, source.getHeaders(), source.getStatusCode()); } else { HttpEntity<?> source = (HttpEntity<?>) originalValue; entity = new HttpEntity<>(newBody, source.getHeaders()); } return rootLinksAsHeaders ? HeaderLinksResponseEntity.wrap(entity) : entity; }
java
Object rewrapResult(RepresentationModel<?> newBody, @Nullable Object originalValue) { if (!(originalValue instanceof HttpEntity)) { return rootLinksAsHeaders ? HeaderLinksResponseEntity.wrap(newBody) : newBody; } HttpEntity<RepresentationModel<?>> entity = null; if (originalValue instanceof ResponseEntity) { ResponseEntity<?> source = (ResponseEntity<?>) originalValue; entity = new ResponseEntity<>(newBody, source.getHeaders(), source.getStatusCode()); } else { HttpEntity<?> source = (HttpEntity<?>) originalValue; entity = new HttpEntity<>(newBody, source.getHeaders()); } return rootLinksAsHeaders ? HeaderLinksResponseEntity.wrap(entity) : entity; }
[ "Object", "rewrapResult", "(", "RepresentationModel", "<", "?", ">", "newBody", ",", "@", "Nullable", "Object", "originalValue", ")", "{", "if", "(", "!", "(", "originalValue", "instanceof", "HttpEntity", ")", ")", "{", "return", "rootLinksAsHeaders", "?", "He...
Re-wraps the result of the post-processing work into an {@link HttpEntity} or {@link ResponseEntity} if the original value was one of those two types. Copies headers and status code from the original value but uses the new body. @param newBody the post-processed value. @param originalValue the original input value. @return
[ "Re", "-", "wraps", "the", "result", "of", "the", "post", "-", "processing", "work", "into", "an", "{", "@link", "HttpEntity", "}", "or", "{", "@link", "ResponseEntity", "}", "if", "the", "original", "value", "was", "one", "of", "those", "two", "types", ...
train
https://github.com/spring-projects/spring-hateoas/blob/70ebff9309f086cd8d6a97daf67e0dc215c87d9c/src/main/java/org/springframework/hateoas/server/mvc/RepresentationModelProcessorHandlerMethodReturnValueHandler.java#L138-L155
dashbuilder/dashbuilder
dashbuilder-client/dashbuilder-displayer-client/src/main/java/org/dashbuilder/displayer/client/AbstractDisplayer.java
AbstractDisplayer.filterApply
public void filterApply(String columnId, List<Interval> intervalList) { if (displayerSettings.isFilterEnabled()) { // For string column filters, init the group interval selection operation. DataSetGroup groupOp = dataSetHandler.getGroupOperation(columnId); groupOp.setSelectedIntervalList(intervalList); // Notify to those interested parties the selection event. if (displayerSettings.isFilterNotificationEnabled()) { for (DisplayerListener listener : listenerList) { listener.onFilterEnabled(this, groupOp); } } // Drill-down support if (displayerSettings.isFilterSelfApplyEnabled()) { dataSetHandler.drillDown(groupOp); redraw(); } } }
java
public void filterApply(String columnId, List<Interval> intervalList) { if (displayerSettings.isFilterEnabled()) { // For string column filters, init the group interval selection operation. DataSetGroup groupOp = dataSetHandler.getGroupOperation(columnId); groupOp.setSelectedIntervalList(intervalList); // Notify to those interested parties the selection event. if (displayerSettings.isFilterNotificationEnabled()) { for (DisplayerListener listener : listenerList) { listener.onFilterEnabled(this, groupOp); } } // Drill-down support if (displayerSettings.isFilterSelfApplyEnabled()) { dataSetHandler.drillDown(groupOp); redraw(); } } }
[ "public", "void", "filterApply", "(", "String", "columnId", ",", "List", "<", "Interval", ">", "intervalList", ")", "{", "if", "(", "displayerSettings", ".", "isFilterEnabled", "(", ")", ")", "{", "// For string column filters, init the group interval selection operatio...
Filter the values of the given column. @param columnId The name of the column to filter. @param intervalList A list of interval selections to filter for.
[ "Filter", "the", "values", "of", "the", "given", "column", "." ]
train
https://github.com/dashbuilder/dashbuilder/blob/50ef88210726b4f2f33f1a82eaf0f542e38dedd9/dashbuilder-client/dashbuilder-displayer-client/src/main/java/org/dashbuilder/displayer/client/AbstractDisplayer.java#L651-L670
tvesalainen/util
util/src/main/java/org/vesalainen/util/CharSequences.java
CharSequences.endsWith
public static boolean endsWith(CharSequence seq, CharSequence pattern, IntUnaryOperator op) { if (pattern.length() > seq.length()) { return false; } int ls = seq.length(); int lp = pattern.length(); for (int ii=1;ii<=lp;ii++) { if (op.applyAsInt(seq.charAt(ls-ii)) != op.applyAsInt(pattern.charAt(lp-ii))) { return false; } } return true; }
java
public static boolean endsWith(CharSequence seq, CharSequence pattern, IntUnaryOperator op) { if (pattern.length() > seq.length()) { return false; } int ls = seq.length(); int lp = pattern.length(); for (int ii=1;ii<=lp;ii++) { if (op.applyAsInt(seq.charAt(ls-ii)) != op.applyAsInt(pattern.charAt(lp-ii))) { return false; } } return true; }
[ "public", "static", "boolean", "endsWith", "(", "CharSequence", "seq", ",", "CharSequence", "pattern", ",", "IntUnaryOperator", "op", ")", "{", "if", "(", "pattern", ".", "length", "(", ")", ">", "seq", ".", "length", "(", ")", ")", "{", "return", "false...
Return true if seq end match pattern after both characters have been converted @param seq @param pattern @param op @return
[ "Return", "true", "if", "seq", "end", "match", "pattern", "after", "both", "characters", "have", "been", "converted" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/CharSequences.java#L114-L130
goldmansachs/gs-collections
collections/src/main/java/com/gs/collections/impl/utility/Iterate.java
Iterate.forEachWithIndex
public static <T> void forEachWithIndex(Iterable<T> iterable, ObjectIntProcedure<? super T> objectIntProcedure) { if (iterable instanceof InternalIterable) { ((InternalIterable<T>) iterable).forEachWithIndex(objectIntProcedure); } else if (iterable instanceof ArrayList) { ArrayListIterate.forEachWithIndex((ArrayList<T>) iterable, objectIntProcedure); } else if (iterable instanceof List) { ListIterate.forEachWithIndex((List<T>) iterable, objectIntProcedure); } else if (iterable != null) { IterableIterate.forEachWithIndex(iterable, objectIntProcedure); } else { throw new IllegalArgumentException("Cannot perform a forEachWithIndex on null"); } }
java
public static <T> void forEachWithIndex(Iterable<T> iterable, ObjectIntProcedure<? super T> objectIntProcedure) { if (iterable instanceof InternalIterable) { ((InternalIterable<T>) iterable).forEachWithIndex(objectIntProcedure); } else if (iterable instanceof ArrayList) { ArrayListIterate.forEachWithIndex((ArrayList<T>) iterable, objectIntProcedure); } else if (iterable instanceof List) { ListIterate.forEachWithIndex((List<T>) iterable, objectIntProcedure); } else if (iterable != null) { IterableIterate.forEachWithIndex(iterable, objectIntProcedure); } else { throw new IllegalArgumentException("Cannot perform a forEachWithIndex on null"); } }
[ "public", "static", "<", "T", ">", "void", "forEachWithIndex", "(", "Iterable", "<", "T", ">", "iterable", ",", "ObjectIntProcedure", "<", "?", "super", "T", ">", "objectIntProcedure", ")", "{", "if", "(", "iterable", "instanceof", "InternalIterable", ")", "...
Iterates over a collection passing each element and the current relative int index to the specified instance of ObjectIntProcedure. <p> Example using a Java 8 lambda expression: <pre> Iterate.<b>forEachWithIndex</b>(people, (Person person, int index) -> LOGGER.info("Index: " + index + " person: " + person.getName())); </pre> <p> Example using anonymous inner class: <pre> Iterate.<b>forEachWithIndex</b>(people, new ObjectIntProcedure<Person>() { public void value(Person person, int index) { LOGGER.info("Index: " + index + " person: " + person.getName()); } }); </pre>
[ "Iterates", "over", "a", "collection", "passing", "each", "element", "and", "the", "current", "relative", "int", "index", "to", "the", "specified", "instance", "of", "ObjectIntProcedure", ".", "<p", ">", "Example", "using", "a", "Java", "8", "lambda", "express...
train
https://github.com/goldmansachs/gs-collections/blob/fa8bf3e103689efa18bca2ab70203e71cde34b52/collections/src/main/java/com/gs/collections/impl/utility/Iterate.java#L224-L246
rhuss/jolokia
agent/jvm/src/main/java/org/jolokia/jvmagent/JvmAgent.java
JvmAgent.premain
public static void premain(String agentArgs, Instrumentation inst) { startAgent(new JvmAgentConfig(agentArgs), true /* register and detect lazy */, inst); }
java
public static void premain(String agentArgs, Instrumentation inst) { startAgent(new JvmAgentConfig(agentArgs), true /* register and detect lazy */, inst); }
[ "public", "static", "void", "premain", "(", "String", "agentArgs", ",", "Instrumentation", "inst", ")", "{", "startAgent", "(", "new", "JvmAgentConfig", "(", "agentArgs", ")", ",", "true", "/* register and detect lazy */", ",", "inst", ")", ";", "}" ]
Entry point for the agent, using command line attach (that is via -javaagent command line argument) @param agentArgs arguments as given on the command line
[ "Entry", "point", "for", "the", "agent", "using", "command", "line", "attach", "(", "that", "is", "via", "-", "javaagent", "command", "line", "argument", ")" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/agent/jvm/src/main/java/org/jolokia/jvmagent/JvmAgent.java#L71-L73
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/query/plan/PlanNode.java
PlanNode.findAncestor
public PlanNode findAncestor( Type firstTypeToFind, Type... additionalTypesToFind ) { return findAncestor(EnumSet.of(firstTypeToFind, additionalTypesToFind)); }
java
public PlanNode findAncestor( Type firstTypeToFind, Type... additionalTypesToFind ) { return findAncestor(EnumSet.of(firstTypeToFind, additionalTypesToFind)); }
[ "public", "PlanNode", "findAncestor", "(", "Type", "firstTypeToFind", ",", "Type", "...", "additionalTypesToFind", ")", "{", "return", "findAncestor", "(", "EnumSet", ".", "of", "(", "firstTypeToFind", ",", "additionalTypesToFind", ")", ")", ";", "}" ]
Starting at the parent of this node, find the lowest (also closest) ancestor that has one of the specified types. @param firstTypeToFind the first type to find; may not be null @param additionalTypesToFind additional types to find; may not be null @return the node with the specified type, or null if there is no such ancestor
[ "Starting", "at", "the", "parent", "of", "this", "node", "find", "the", "lowest", "(", "also", "closest", ")", "ancestor", "that", "has", "one", "of", "the", "specified", "types", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/query/plan/PlanNode.java#L1121-L1124
HubSpot/Singularity
SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java
SingularityClient.getSlaves
public Collection<SingularitySlave> getSlaves(Optional<MachineState> slaveState) { final Function<String, String> requestUri = (host) -> String.format(SLAVES_FORMAT, getApiBase(host)); Optional<Map<String, Object>> maybeQueryParams = Optional.absent(); String type = "slaves"; if (slaveState.isPresent()) { maybeQueryParams = Optional.of(ImmutableMap.of("state", slaveState.get().toString())); type = String.format("%s slaves", slaveState.get().toString()); } return getCollectionWithParams(requestUri, type, maybeQueryParams, SLAVES_COLLECTION); }
java
public Collection<SingularitySlave> getSlaves(Optional<MachineState> slaveState) { final Function<String, String> requestUri = (host) -> String.format(SLAVES_FORMAT, getApiBase(host)); Optional<Map<String, Object>> maybeQueryParams = Optional.absent(); String type = "slaves"; if (slaveState.isPresent()) { maybeQueryParams = Optional.of(ImmutableMap.of("state", slaveState.get().toString())); type = String.format("%s slaves", slaveState.get().toString()); } return getCollectionWithParams(requestUri, type, maybeQueryParams, SLAVES_COLLECTION); }
[ "public", "Collection", "<", "SingularitySlave", ">", "getSlaves", "(", "Optional", "<", "MachineState", ">", "slaveState", ")", "{", "final", "Function", "<", "String", ",", "String", ">", "requestUri", "=", "(", "host", ")", "-", ">", "String", ".", "for...
Retrieve the list of all known slaves, optionally filtering by a particular slave state @param slaveState Optionally specify a particular state to filter slaves by @return A collection of {@link SingularitySlave}
[ "Retrieve", "the", "list", "of", "all", "known", "slaves", "optionally", "filtering", "by", "a", "particular", "slave", "state" ]
train
https://github.com/HubSpot/Singularity/blob/384a8c16a10aa076af5ca45c8dfcedab9e5122c8/SingularityClient/src/main/java/com/hubspot/singularity/client/SingularityClient.java#L948-L962
Samsung/GearVRf
GVRf/Framework/framework/src/main/java/org/gearvrf/GVRSceneObject.java
GVRSceneObject.expandBoundingVolume
public final BoundingVolume expandBoundingVolume(final float pointX, final float pointY, final float pointZ) { return new BoundingVolume( NativeSceneObject.expandBoundingVolumeByPoint( getNative(), pointX, pointY, pointZ)); }
java
public final BoundingVolume expandBoundingVolume(final float pointX, final float pointY, final float pointZ) { return new BoundingVolume( NativeSceneObject.expandBoundingVolumeByPoint( getNative(), pointX, pointY, pointZ)); }
[ "public", "final", "BoundingVolume", "expandBoundingVolume", "(", "final", "float", "pointX", ",", "final", "float", "pointY", ",", "final", "float", "pointZ", ")", "{", "return", "new", "BoundingVolume", "(", "NativeSceneObject", ".", "expandBoundingVolumeByPoint", ...
Expand the current volume by the given point @param pointX x coordinate of point @param pointY y coordinate of point @param pointZ z coordinate of point @return the updated BoundingVolume.
[ "Expand", "the", "current", "volume", "by", "the", "given", "point" ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRSceneObject.java#L1261-L1265
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java
CommandLine.addSwitchWithOptionalExtraPart
public void addSwitchWithOptionalExtraPart(String option, String optionExtraPartSynopsis, String description) { optionList.add(option); optionExtraPartSynopsisMap.put(option, optionExtraPartSynopsis); optionDescriptionMap.put(option, description); // Option will display as -foo[:extraPartSynopsis] int length = option.length() + optionExtraPartSynopsis.length() + 3; if (length > maxWidth) { maxWidth = length; } }
java
public void addSwitchWithOptionalExtraPart(String option, String optionExtraPartSynopsis, String description) { optionList.add(option); optionExtraPartSynopsisMap.put(option, optionExtraPartSynopsis); optionDescriptionMap.put(option, description); // Option will display as -foo[:extraPartSynopsis] int length = option.length() + optionExtraPartSynopsis.length() + 3; if (length > maxWidth) { maxWidth = length; } }
[ "public", "void", "addSwitchWithOptionalExtraPart", "(", "String", "option", ",", "String", "optionExtraPartSynopsis", ",", "String", "description", ")", "{", "optionList", ".", "add", "(", "option", ")", ";", "optionExtraPartSynopsisMap", ".", "put", "(", "option",...
Add a command line switch that allows optional extra information to be specified as part of it. @param option the option, must start with "-" @param optionExtraPartSynopsis synopsis of the optional extra information @param description single-line description of the option
[ "Add", "a", "command", "line", "switch", "that", "allows", "optional", "extra", "information", "to", "be", "specified", "as", "part", "of", "it", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/config/CommandLine.java#L114-L124
facebook/fresco
imagepipeline-base/src/main/java/com/facebook/cache/disk/ScoreBasedEvictionComparatorSupplier.java
ScoreBasedEvictionComparatorSupplier.calculateScore
@VisibleForTesting float calculateScore(DiskStorage.Entry entry, long now) { long ageMs = now - entry.getTimestamp(); long bytes = entry.getSize(); return mAgeWeight * ageMs + mSizeWeight * bytes; }
java
@VisibleForTesting float calculateScore(DiskStorage.Entry entry, long now) { long ageMs = now - entry.getTimestamp(); long bytes = entry.getSize(); return mAgeWeight * ageMs + mSizeWeight * bytes; }
[ "@", "VisibleForTesting", "float", "calculateScore", "(", "DiskStorage", ".", "Entry", "entry", ",", "long", "now", ")", "{", "long", "ageMs", "=", "now", "-", "entry", ".", "getTimestamp", "(", ")", ";", "long", "bytes", "=", "entry", ".", "getSize", "(...
Calculates an eviction score. Entries with a higher eviction score should be evicted first.
[ "Calculates", "an", "eviction", "score", "." ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline-base/src/main/java/com/facebook/cache/disk/ScoreBasedEvictionComparatorSupplier.java#L48-L53
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/PdfPKCS7.java
PdfPKCS7.verifyTimestampCertificates
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) { if (provider == null) provider = "BC"; try { for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) { try { String alias = (String)aliases.nextElement(); if (!keystore.isCertificateEntry(alias)) continue; X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias); SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509); ts.validate(siv); return true; } catch (Exception ex) { } } } catch (Exception e) { } return false; }
java
public static boolean verifyTimestampCertificates(TimeStampToken ts, KeyStore keystore, String provider) { if (provider == null) provider = "BC"; try { for (Enumeration aliases = keystore.aliases(); aliases.hasMoreElements();) { try { String alias = (String)aliases.nextElement(); if (!keystore.isCertificateEntry(alias)) continue; X509Certificate certStoreX509 = (X509Certificate)keystore.getCertificate(alias); SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider(provider).build(certStoreX509); ts.validate(siv); return true; } catch (Exception ex) { } } } catch (Exception e) { } return false; }
[ "public", "static", "boolean", "verifyTimestampCertificates", "(", "TimeStampToken", "ts", ",", "KeyStore", "keystore", ",", "String", "provider", ")", "{", "if", "(", "provider", "==", "null", ")", "provider", "=", "\"BC\"", ";", "try", "{", "for", "(", "En...
Verifies a timestamp against a KeyStore. @param ts the timestamp @param keystore the <CODE>KeyStore</CODE> @param provider the provider or <CODE>null</CODE> to use the BouncyCastle provider @return <CODE>true</CODE> is a certificate was found @since 2.1.6
[ "Verifies", "a", "timestamp", "against", "a", "KeyStore", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfPKCS7.java#L934-L955
cantrowitz/RxBroadcast
rxbroadcast/src/main/java/com/cantrowitz/rxbroadcast/RxBroadcast.java
RxBroadcast.fromBroadcast
public static Observable<Intent> fromBroadcast(Context context, IntentFilter intentFilter) { return fromBroadcast(context, intentFilter, NO_OP_ORDERED_BROADCAST_STRATEGY); }
java
public static Observable<Intent> fromBroadcast(Context context, IntentFilter intentFilter) { return fromBroadcast(context, intentFilter, NO_OP_ORDERED_BROADCAST_STRATEGY); }
[ "public", "static", "Observable", "<", "Intent", ">", "fromBroadcast", "(", "Context", "context", ",", "IntentFilter", "intentFilter", ")", "{", "return", "fromBroadcast", "(", "context", ",", "intentFilter", ",", "NO_OP_ORDERED_BROADCAST_STRATEGY", ")", ";", "}" ]
Create {@link Observable} that wraps {@link BroadcastReceiver} and emits received intents. @param context the context the {@link BroadcastReceiver} will be created from @param intentFilter the filter for the particular intent @return {@link Observable} of {@link Intent} that matches the filter
[ "Create", "{", "@link", "Observable", "}", "that", "wraps", "{", "@link", "BroadcastReceiver", "}", "and", "emits", "received", "intents", "." ]
train
https://github.com/cantrowitz/RxBroadcast/blob/8b479d0e28617e9b86fa4d462c6675c131b0c5d0/rxbroadcast/src/main/java/com/cantrowitz/rxbroadcast/RxBroadcast.java#L41-L43
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/ClusterManager.java
ClusterManager.recoverClusterManagerFromDisk
private void recoverClusterManagerFromDisk(HostsFileReader hostsReader) throws IOException { LOG.info("Restoring state from " + new java.io.File(conf.getCMStateFile()).getAbsolutePath()); // This will prevent the expireNodes and expireSessions threads from // expiring the nodes and sessions respectively safeMode = true; LOG.info("Safe mode is now: " + (this.safeMode ? "ON" : "OFF")); CoronaSerializer coronaSerializer = new CoronaSerializer(conf); // Expecting the START_OBJECT token for ClusterManager coronaSerializer.readStartObjectToken("ClusterManager"); coronaSerializer.readField("startTime"); startTime = coronaSerializer.readValueAs(Long.class); coronaSerializer.readField("nodeManager"); nodeManager = new NodeManager(this, hostsReader, coronaSerializer); nodeManager.setConf(conf); coronaSerializer.readField("sessionManager"); sessionManager = new SessionManager(this, coronaSerializer); coronaSerializer.readField("sessionNotifier"); sessionNotifier = new SessionNotifier(sessionManager, this, metrics, coronaSerializer); // Expecting the END_OBJECT token for ClusterManager coronaSerializer.readEndObjectToken("ClusterManager"); lastRestartTime = clock.getTime(); }
java
private void recoverClusterManagerFromDisk(HostsFileReader hostsReader) throws IOException { LOG.info("Restoring state from " + new java.io.File(conf.getCMStateFile()).getAbsolutePath()); // This will prevent the expireNodes and expireSessions threads from // expiring the nodes and sessions respectively safeMode = true; LOG.info("Safe mode is now: " + (this.safeMode ? "ON" : "OFF")); CoronaSerializer coronaSerializer = new CoronaSerializer(conf); // Expecting the START_OBJECT token for ClusterManager coronaSerializer.readStartObjectToken("ClusterManager"); coronaSerializer.readField("startTime"); startTime = coronaSerializer.readValueAs(Long.class); coronaSerializer.readField("nodeManager"); nodeManager = new NodeManager(this, hostsReader, coronaSerializer); nodeManager.setConf(conf); coronaSerializer.readField("sessionManager"); sessionManager = new SessionManager(this, coronaSerializer); coronaSerializer.readField("sessionNotifier"); sessionNotifier = new SessionNotifier(sessionManager, this, metrics, coronaSerializer); // Expecting the END_OBJECT token for ClusterManager coronaSerializer.readEndObjectToken("ClusterManager"); lastRestartTime = clock.getTime(); }
[ "private", "void", "recoverClusterManagerFromDisk", "(", "HostsFileReader", "hostsReader", ")", "throws", "IOException", "{", "LOG", ".", "info", "(", "\"Restoring state from \"", "+", "new", "java", ".", "io", ".", "File", "(", "conf", ".", "getCMStateFile", "(",...
This method is used when the ClusterManager is restarting after going down while in Safe Mode. It starts the process of recovering the original CM state by reading back the state in JSON form. @param hostsReader The HostsReader instance @throws IOException
[ "This", "method", "is", "used", "when", "the", "ClusterManager", "is", "restarting", "after", "going", "down", "while", "in", "Safe", "Mode", ".", "It", "starts", "the", "process", "of", "recovering", "the", "original", "CM", "state", "by", "reading", "back"...
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/ClusterManager.java#L198-L231
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/LineReader.java
LineReader.readLine
public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { if (this.recordDelimiterBytes != null) { return readCustomLine(str, maxLineLength, maxBytesToConsume); } else { return readDefaultLine(str, maxLineLength, maxBytesToConsume); } }
java
public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { if (this.recordDelimiterBytes != null) { return readCustomLine(str, maxLineLength, maxBytesToConsume); } else { return readDefaultLine(str, maxLineLength, maxBytesToConsume); } }
[ "public", "int", "readLine", "(", "Text", "str", ",", "int", "maxLineLength", ",", "int", "maxBytesToConsume", ")", "throws", "IOException", "{", "if", "(", "this", ".", "recordDelimiterBytes", "!=", "null", ")", "{", "return", "readCustomLine", "(", "str", ...
Read one line from the InputStream into the given Text. @param str the object to store the given line (without newline) @param maxLineLength the maximum number of bytes to store into str; @param maxBytesToConsume the maximum number of bytes to consume in this call. This is only a hint, because if the line cross this threshold, we allow it to happen. It can overshoot potentially by as much as one buffer length.
[ "Read", "one", "line", "from", "the", "InputStream", "into", "the", "given", "Text", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/LineReader.java#L156-L163
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java
AbstractTextFileConverter.convertFile
public final void convertFile(final String inputFileName, final String outputFileName) throws IOException, ConversionException { openInputFile(inputFileName); openOutputFile(outputFileName); doConvertFile(myLineReader, myBufferedWriter); closeOutputFile(); closeInputFile(); }
java
public final void convertFile(final String inputFileName, final String outputFileName) throws IOException, ConversionException { openInputFile(inputFileName); openOutputFile(outputFileName); doConvertFile(myLineReader, myBufferedWriter); closeOutputFile(); closeInputFile(); }
[ "public", "final", "void", "convertFile", "(", "final", "String", "inputFileName", ",", "final", "String", "outputFileName", ")", "throws", "IOException", ",", "ConversionException", "{", "openInputFile", "(", "inputFileName", ")", ";", "openOutputFile", "(", "outpu...
The file conversion process. @param inputFileName Name of the file to convert @param outputFileName Name of the converted file @throws IOException IO Exceptions are not processed. It is up to the calling process to decide what to do, typically retry, abort or ignore. @throws ConversionException if a conversion problem occurs.
[ "The", "file", "conversion", "process", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java#L271-L278
lessthanoptimal/ddogleg
src/org/ddogleg/nn/alg/VpTree.java
VpTree.partitionItems
private int partitionItems(int left, int right, int pivot, double[] origin) { double pivotDistance = distance(origin, items[pivot]); listSwap(items, pivot, right - 1); listSwap(indexes, pivot, right - 1); int storeIndex = left; for (int i = left; i < right - 1; i++) { if (distance(origin, items[i]) <= pivotDistance) { listSwap(items, i, storeIndex); listSwap(indexes, i, storeIndex); storeIndex++; } } listSwap(items, storeIndex, right - 1); listSwap(indexes, storeIndex, right - 1); return storeIndex; }
java
private int partitionItems(int left, int right, int pivot, double[] origin) { double pivotDistance = distance(origin, items[pivot]); listSwap(items, pivot, right - 1); listSwap(indexes, pivot, right - 1); int storeIndex = left; for (int i = left; i < right - 1; i++) { if (distance(origin, items[i]) <= pivotDistance) { listSwap(items, i, storeIndex); listSwap(indexes, i, storeIndex); storeIndex++; } } listSwap(items, storeIndex, right - 1); listSwap(indexes, storeIndex, right - 1); return storeIndex; }
[ "private", "int", "partitionItems", "(", "int", "left", ",", "int", "right", ",", "int", "pivot", ",", "double", "[", "]", "origin", ")", "{", "double", "pivotDistance", "=", "distance", "(", "origin", ",", "items", "[", "pivot", "]", ")", ";", "listSw...
Partition the points based on their distance to origin around the selected pivot. @param left range start @param right range end (exclusive) @param pivot pivot for the partition @param origin origin to compute the distance to @return index of the pivot
[ "Partition", "the", "points", "based", "on", "their", "distance", "to", "origin", "around", "the", "selected", "pivot", "." ]
train
https://github.com/lessthanoptimal/ddogleg/blob/3786bf448ba23d0e04962dd08c34fa68de276029/src/org/ddogleg/nn/alg/VpTree.java#L149-L164
facebookarchive/hadoop-20
src/core/org/apache/hadoop/util/bloom/RetouchedBloomFilter.java
RetouchedBloomFilter.selectiveClearing
public void selectiveClearing(Key k, short scheme) { if (k == null) { throw new NullPointerException("Key can not be null"); } if (!membershipTest(k)) { throw new IllegalArgumentException("Key is not a member"); } int index = 0; int[] h = hash.hash(k); switch(scheme) { case RANDOM: index = randomRemove(); break; case MINIMUM_FN: index = minimumFnRemove(h); break; case MAXIMUM_FP: index = maximumFpRemove(h); break; case RATIO: index = ratioRemove(h); break; default: throw new AssertionError("Undefined selective clearing scheme"); } clearBit(index); }
java
public void selectiveClearing(Key k, short scheme) { if (k == null) { throw new NullPointerException("Key can not be null"); } if (!membershipTest(k)) { throw new IllegalArgumentException("Key is not a member"); } int index = 0; int[] h = hash.hash(k); switch(scheme) { case RANDOM: index = randomRemove(); break; case MINIMUM_FN: index = minimumFnRemove(h); break; case MAXIMUM_FP: index = maximumFpRemove(h); break; case RATIO: index = ratioRemove(h); break; default: throw new AssertionError("Undefined selective clearing scheme"); } clearBit(index); }
[ "public", "void", "selectiveClearing", "(", "Key", "k", ",", "short", "scheme", ")", "{", "if", "(", "k", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"Key can not be null\"", ")", ";", "}", "if", "(", "!", "membershipTest", "(", ...
Performs the selective clearing for a given key. @param k The false positive key to remove from <i>this</i> retouched Bloom filter. @param scheme The selective clearing scheme to apply.
[ "Performs", "the", "selective", "clearing", "for", "a", "given", "key", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/bloom/RetouchedBloomFilter.java#L194-L230
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java
BoundingBox.extendMeters
public BoundingBox extendMeters(int meters) { if (meters == 0) { return this; } else if (meters < 0) { throw new IllegalArgumentException("BoundingBox extend operation does not accept negative values"); } double verticalExpansion = LatLongUtils.latitudeDistance(meters); double horizontalExpansion = LatLongUtils.longitudeDistance(meters, Math.max(Math.abs(minLatitude), Math.abs(maxLatitude))); double minLat = Math.max(MercatorProjection.LATITUDE_MIN, this.minLatitude - verticalExpansion); double minLon = Math.max(-180, this.minLongitude - horizontalExpansion); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, this.maxLatitude + verticalExpansion); double maxLon = Math.min(180, this.maxLongitude + horizontalExpansion); return new BoundingBox(minLat, minLon, maxLat, maxLon); }
java
public BoundingBox extendMeters(int meters) { if (meters == 0) { return this; } else if (meters < 0) { throw new IllegalArgumentException("BoundingBox extend operation does not accept negative values"); } double verticalExpansion = LatLongUtils.latitudeDistance(meters); double horizontalExpansion = LatLongUtils.longitudeDistance(meters, Math.max(Math.abs(minLatitude), Math.abs(maxLatitude))); double minLat = Math.max(MercatorProjection.LATITUDE_MIN, this.minLatitude - verticalExpansion); double minLon = Math.max(-180, this.minLongitude - horizontalExpansion); double maxLat = Math.min(MercatorProjection.LATITUDE_MAX, this.maxLatitude + verticalExpansion); double maxLon = Math.min(180, this.maxLongitude + horizontalExpansion); return new BoundingBox(minLat, minLon, maxLat, maxLon); }
[ "public", "BoundingBox", "extendMeters", "(", "int", "meters", ")", "{", "if", "(", "meters", "==", "0", ")", "{", "return", "this", ";", "}", "else", "if", "(", "meters", "<", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"BoundingBo...
Creates a BoundingBox that is a fixed meter amount larger on all sides (but does not cross date line/poles). @param meters extension (must be >= 0) @return an extended BoundingBox or this (if meters == 0)
[ "Creates", "a", "BoundingBox", "that", "is", "a", "fixed", "meter", "amount", "larger", "on", "all", "sides", "(", "but", "does", "not", "cross", "date", "line", "/", "poles", ")", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java#L244-L260
groupon/odo
client/src/main/java/com/groupon/odo/client/Client.java
Client.setCustomResponse
public boolean setCustomResponse(String pathName, String customResponse) throws Exception { // figure out the new ordinal int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName); // add override this.addMethodToResponseOverride(pathName, "-1"); // set argument return this.setMethodArguments(pathName, "-1", nextOrdinal, customResponse); }
java
public boolean setCustomResponse(String pathName, String customResponse) throws Exception { // figure out the new ordinal int nextOrdinal = this.getNextOrdinalForMethodId(-1, pathName); // add override this.addMethodToResponseOverride(pathName, "-1"); // set argument return this.setMethodArguments(pathName, "-1", nextOrdinal, customResponse); }
[ "public", "boolean", "setCustomResponse", "(", "String", "pathName", ",", "String", "customResponse", ")", "throws", "Exception", "{", "// figure out the new ordinal", "int", "nextOrdinal", "=", "this", ".", "getNextOrdinalForMethodId", "(", "-", "1", ",", "pathName",...
Set a custom response for this path @param pathName name of path @param customResponse value of custom response @return true if success, false otherwise @throws Exception exception
[ "Set", "a", "custom", "response", "for", "this", "path" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/client/src/main/java/com/groupon/odo/client/Client.java#L568-L577