repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java
GeometryUtilities.getPolygonArea
public static double getPolygonArea( int[] x, int[] y, int N ) { """ Calculates the area of a polygon from its vertices. @param x the array of x coordinates. @param y the array of y coordinates. @param N the number of sides of the polygon. @return the area of the polygon. """ int i, j; double area = 0; for( i = 0; i < N; i++ ) { j = (i + 1) % N; area += x[i] * y[j]; area -= y[i] * x[j]; } area /= 2; return (area < 0 ? -area : area); }
java
public static double getPolygonArea( int[] x, int[] y, int N ) { int i, j; double area = 0; for( i = 0; i < N; i++ ) { j = (i + 1) % N; area += x[i] * y[j]; area -= y[i] * x[j]; } area /= 2; return (area < 0 ? -area : area); }
[ "public", "static", "double", "getPolygonArea", "(", "int", "[", "]", "x", ",", "int", "[", "]", "y", ",", "int", "N", ")", "{", "int", "i", ",", "j", ";", "double", "area", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "j", "=", "(", "i", "+", "1", ")", "%", "N", ";", "area", "+=", "x", "[", "i", "]", "*", "y", "[", "j", "]", ";", "area", "-=", "y", "[", "i", "]", "*", "x", "[", "j", "]", ";", "}", "area", "/=", "2", ";", "return", "(", "area", "<", "0", "?", "-", "area", ":", "area", ")", ";", "}" ]
Calculates the area of a polygon from its vertices. @param x the array of x coordinates. @param y the array of y coordinates. @param N the number of sides of the polygon. @return the area of the polygon.
[ "Calculates", "the", "area", "of", "a", "polygon", "from", "its", "vertices", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/geometry/GeometryUtilities.java#L284-L296
elibom/jogger
src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java
AbstractFileRoutesLoader.validateHttpMethod
private String validateHttpMethod(String httpMethod, int line) throws ParseException { """ Helper method. It validates if the HTTP method is valid (i.e. is a GET, POST, PUT or DELETE). @param httpMethod the HTTP method to validate. @return the same httpMethod that was received as an argument. @throws ParseException if the HTTP method is not recognized. """ if (!httpMethod.equalsIgnoreCase("GET") && !httpMethod.equalsIgnoreCase("POST") && !httpMethod.equalsIgnoreCase("PUT") && !httpMethod.equalsIgnoreCase("DELETE")) { throw new ParseException("Unrecognized HTTP method: " + httpMethod, line); } return httpMethod; }
java
private String validateHttpMethod(String httpMethod, int line) throws ParseException { if (!httpMethod.equalsIgnoreCase("GET") && !httpMethod.equalsIgnoreCase("POST") && !httpMethod.equalsIgnoreCase("PUT") && !httpMethod.equalsIgnoreCase("DELETE")) { throw new ParseException("Unrecognized HTTP method: " + httpMethod, line); } return httpMethod; }
[ "private", "String", "validateHttpMethod", "(", "String", "httpMethod", ",", "int", "line", ")", "throws", "ParseException", "{", "if", "(", "!", "httpMethod", ".", "equalsIgnoreCase", "(", "\"GET\"", ")", "&&", "!", "httpMethod", ".", "equalsIgnoreCase", "(", "\"POST\"", ")", "&&", "!", "httpMethod", ".", "equalsIgnoreCase", "(", "\"PUT\"", ")", "&&", "!", "httpMethod", ".", "equalsIgnoreCase", "(", "\"DELETE\"", ")", ")", "{", "throw", "new", "ParseException", "(", "\"Unrecognized HTTP method: \"", "+", "httpMethod", ",", "line", ")", ";", "}", "return", "httpMethod", ";", "}" ]
Helper method. It validates if the HTTP method is valid (i.e. is a GET, POST, PUT or DELETE). @param httpMethod the HTTP method to validate. @return the same httpMethod that was received as an argument. @throws ParseException if the HTTP method is not recognized.
[ "Helper", "method", ".", "It", "validates", "if", "the", "HTTP", "method", "is", "valid", "(", "i", ".", "e", ".", "is", "a", "GET", "POST", "PUT", "or", "DELETE", ")", "." ]
train
https://github.com/elibom/jogger/blob/d5892ff45e76328d444a68b5a38c26e7bdd0692b/src/main/java/com/elibom/jogger/middleware/router/loader/AbstractFileRoutesLoader.java#L147-L157
mapsforge/mapsforge
mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java
AndroidUtil.getMinimumCacheSize
public static int getMinimumCacheSize(int tileSize, double overdrawFactor, int width, int height) { """ Compute the minimum cache size for a view, using the size of the map view. For the view size we use the frame buffer calculated dimension. @param tileSize the tile size @param overdrawFactor the overdraw factor applied to the mapview @param width the width of the map view @param height the height of the map view @return the minimum cache size for the view """ // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return Math.max(4, (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
java
public static int getMinimumCacheSize(int tileSize, double overdrawFactor, int width, int height) { // height * overdrawFactor / tileSize calculates the number of tiles that would cover // the view port, adding 1 is required since we can have part tiles on either side, // adding 2 adds another row/column as spare and ensures that we will generally have // a larger number of tiles in the cache than a TileLayer will render for a view. // For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the // middle of a view. Dimension dimension = FrameBufferController.calculateFrameBufferDimension(new Dimension(width, height), overdrawFactor); return Math.max(4, (2 + (dimension.height / tileSize)) * (2 + (dimension.width / tileSize))); }
[ "public", "static", "int", "getMinimumCacheSize", "(", "int", "tileSize", ",", "double", "overdrawFactor", ",", "int", "width", ",", "int", "height", ")", "{", "// height * overdrawFactor / tileSize calculates the number of tiles that would cover", "// the view port, adding 1 is required since we can have part tiles on either side,", "// adding 2 adds another row/column as spare and ensures that we will generally have", "// a larger number of tiles in the cache than a TileLayer will render for a view.", "// For any size we need a minimum of 4 (as the intersection of 4 tiles can always be in the", "// middle of a view.", "Dimension", "dimension", "=", "FrameBufferController", ".", "calculateFrameBufferDimension", "(", "new", "Dimension", "(", "width", ",", "height", ")", ",", "overdrawFactor", ")", ";", "return", "Math", ".", "max", "(", "4", ",", "(", "2", "+", "(", "dimension", ".", "height", "/", "tileSize", ")", ")", "*", "(", "2", "+", "(", "dimension", ".", "width", "/", "tileSize", ")", ")", ")", ";", "}" ]
Compute the minimum cache size for a view, using the size of the map view. For the view size we use the frame buffer calculated dimension. @param tileSize the tile size @param overdrawFactor the overdraw factor applied to the mapview @param width the width of the map view @param height the height of the map view @return the minimum cache size for the view
[ "Compute", "the", "minimum", "cache", "size", "for", "a", "view", "using", "the", "size", "of", "the", "map", "view", ".", "For", "the", "view", "size", "we", "use", "the", "frame", "buffer", "calculated", "dimension", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-map-android/src/main/java/org/mapsforge/map/android/util/AndroidUtil.java#L391-L401
joniles/mpxj
src/main/java/net/sf/mpxj/ProjectFile.java
ProjectFile.getDuration
@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException { """ This method is used to calculate the duration of work between two fixed dates according to the work schedule defined in the named calendar. The calendar used is the "Standard" calendar. If this calendar does not exist, and exception will be thrown. @param startDate start of the period @param endDate end of the period @return new Duration object @throws MPXJException normally when no Standard calendar is available @deprecated use calendar.getDuration(startDate, endDate) """ return (getDuration("Standard", startDate, endDate)); }
java
@Deprecated public Duration getDuration(Date startDate, Date endDate) throws MPXJException { return (getDuration("Standard", startDate, endDate)); }
[ "@", "Deprecated", "public", "Duration", "getDuration", "(", "Date", "startDate", ",", "Date", "endDate", ")", "throws", "MPXJException", "{", "return", "(", "getDuration", "(", "\"Standard\"", ",", "startDate", ",", "endDate", ")", ")", ";", "}" ]
This method is used to calculate the duration of work between two fixed dates according to the work schedule defined in the named calendar. The calendar used is the "Standard" calendar. If this calendar does not exist, and exception will be thrown. @param startDate start of the period @param endDate end of the period @return new Duration object @throws MPXJException normally when no Standard calendar is available @deprecated use calendar.getDuration(startDate, endDate)
[ "This", "method", "is", "used", "to", "calculate", "the", "duration", "of", "work", "between", "two", "fixed", "dates", "according", "to", "the", "work", "schedule", "defined", "in", "the", "named", "calendar", ".", "The", "calendar", "used", "is", "the", "Standard", "calendar", ".", "If", "this", "calendar", "does", "not", "exist", "and", "exception", "will", "be", "thrown", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/ProjectFile.java#L336-L339
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.unaryOperator
public static <T> UnaryOperator<T> unaryOperator(CheckedUnaryOperator<T> operator) { """ Wrap a {@link CheckedUnaryOperator} in a {@link UnaryOperator}. <p> Example: <code><pre> Stream.of("a", "b", "c").map(Unchecked.unaryOperator(s -> { if (s.length() > 10) throw new Exception("Only short strings allowed"); return s; })); </pre></code> """ return unaryOperator(operator, THROWABLE_TO_RUNTIME_EXCEPTION); }
java
public static <T> UnaryOperator<T> unaryOperator(CheckedUnaryOperator<T> operator) { return unaryOperator(operator, THROWABLE_TO_RUNTIME_EXCEPTION); }
[ "public", "static", "<", "T", ">", "UnaryOperator", "<", "T", ">", "unaryOperator", "(", "CheckedUnaryOperator", "<", "T", ">", "operator", ")", "{", "return", "unaryOperator", "(", "operator", ",", "THROWABLE_TO_RUNTIME_EXCEPTION", ")", ";", "}" ]
Wrap a {@link CheckedUnaryOperator} in a {@link UnaryOperator}. <p> Example: <code><pre> Stream.of("a", "b", "c").map(Unchecked.unaryOperator(s -> { if (s.length() > 10) throw new Exception("Only short strings allowed"); return s; })); </pre></code>
[ "Wrap", "a", "{", "@link", "CheckedUnaryOperator", "}", "in", "a", "{", "@link", "UnaryOperator", "}", ".", "<p", ">", "Example", ":", "<code", ">", "<pre", ">", "Stream", ".", "of", "(", "a", "b", "c", ")", ".", "map", "(", "Unchecked", ".", "unaryOperator", "(", "s", "-", ">", "{", "if", "(", "s", ".", "length", "()", ">", "10", ")", "throw", "new", "Exception", "(", "Only", "short", "strings", "allowed", ")", ";" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1886-L1888
phax/ph-commons
ph-xml/src/main/java/com/helger/xml/transform/XMLTransformerFactory.java
XMLTransformerFactory.newTransformer
@Nullable public static Transformer newTransformer (@Nonnull final TransformerFactory aTransformerFactory, @Nonnull final IReadableResource aResource) { """ Create a new XSLT transformer for the passed resource. @param aTransformerFactory The transformer factory to be used. May not be <code>null</code>. @param aResource The resource to be transformed. May not be <code>null</code>. @return <code>null</code> if something goes wrong """ ValueEnforcer.notNull (aResource, "Resource"); return newTransformer (aTransformerFactory, TransformSourceFactory.create (aResource)); }
java
@Nullable public static Transformer newTransformer (@Nonnull final TransformerFactory aTransformerFactory, @Nonnull final IReadableResource aResource) { ValueEnforcer.notNull (aResource, "Resource"); return newTransformer (aTransformerFactory, TransformSourceFactory.create (aResource)); }
[ "@", "Nullable", "public", "static", "Transformer", "newTransformer", "(", "@", "Nonnull", "final", "TransformerFactory", "aTransformerFactory", ",", "@", "Nonnull", "final", "IReadableResource", "aResource", ")", "{", "ValueEnforcer", ".", "notNull", "(", "aResource", ",", "\"Resource\"", ")", ";", "return", "newTransformer", "(", "aTransformerFactory", ",", "TransformSourceFactory", ".", "create", "(", "aResource", ")", ")", ";", "}" ]
Create a new XSLT transformer for the passed resource. @param aTransformerFactory The transformer factory to be used. May not be <code>null</code>. @param aResource The resource to be transformed. May not be <code>null</code>. @return <code>null</code> if something goes wrong
[ "Create", "a", "new", "XSLT", "transformer", "for", "the", "passed", "resource", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-xml/src/main/java/com/helger/xml/transform/XMLTransformerFactory.java#L186-L193
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUResourceBundle.java
ICUResourceBundle.getResPathKeys
private void getResPathKeys(String[] keys, int depth) { """ Fills some of the keys array with the keys on the path to this resource object. Writes the top-level key into index 0 and increments from there. @param keys @param depth must be {@link #getResDepth()} """ ICUResourceBundle b = this; while (depth > 0) { keys[--depth] = b.key; b = b.container; assert (depth == 0) == (b.container == null); } }
java
private void getResPathKeys(String[] keys, int depth) { ICUResourceBundle b = this; while (depth > 0) { keys[--depth] = b.key; b = b.container; assert (depth == 0) == (b.container == null); } }
[ "private", "void", "getResPathKeys", "(", "String", "[", "]", "keys", ",", "int", "depth", ")", "{", "ICUResourceBundle", "b", "=", "this", ";", "while", "(", "depth", ">", "0", ")", "{", "keys", "[", "--", "depth", "]", "=", "b", ".", "key", ";", "b", "=", "b", ".", "container", ";", "assert", "(", "depth", "==", "0", ")", "==", "(", "b", ".", "container", "==", "null", ")", ";", "}", "}" ]
Fills some of the keys array with the keys on the path to this resource object. Writes the top-level key into index 0 and increments from there. @param keys @param depth must be {@link #getResDepth()}
[ "Fills", "some", "of", "the", "keys", "array", "with", "the", "keys", "on", "the", "path", "to", "this", "resource", "object", ".", "Writes", "the", "top", "-", "level", "key", "into", "index", "0", "and", "increments", "from", "there", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/impl/ICUResourceBundle.java#L976-L983
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/misc/GImageBandMath.java
GImageBandMath.stdDev
public static <T extends ImageGray<T>> void stdDev(Planar<T> input, T output, @Nullable T avg) { """ Computes the standard deviation for each pixel across all bands in the {@link Planar} image. @param input Planar image @param output Gray scale image containing average pixel values @param avg Gray scale image containing average projection of input """ stdDev(input, output, avg, 0, input.getNumBands() - 1); }
java
public static <T extends ImageGray<T>> void stdDev(Planar<T> input, T output, @Nullable T avg) { stdDev(input, output, avg, 0, input.getNumBands() - 1); }
[ "public", "static", "<", "T", "extends", "ImageGray", "<", "T", ">", ">", "void", "stdDev", "(", "Planar", "<", "T", ">", "input", ",", "T", "output", ",", "@", "Nullable", "T", "avg", ")", "{", "stdDev", "(", "input", ",", "output", ",", "avg", ",", "0", ",", "input", ".", "getNumBands", "(", ")", "-", "1", ")", ";", "}" ]
Computes the standard deviation for each pixel across all bands in the {@link Planar} image. @param input Planar image @param output Gray scale image containing average pixel values @param avg Gray scale image containing average projection of input
[ "Computes", "the", "standard", "deviation", "for", "each", "pixel", "across", "all", "bands", "in", "the", "{", "@link", "Planar", "}", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/GImageBandMath.java#L196-L198
Harium/keel
src/main/java/com/harium/keel/catalano/math/ComplexNumber.java
ComplexNumber.Pow
public static ComplexNumber Pow(ComplexNumber z1, double n) { """ Calculate power of a complex number. @param z1 Complex Number. @param n Power. @return Returns a new complex number containing the power of a specified number. """ double norm = Math.pow(z1.getMagnitude(), n); double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real))); double common = n * angle; double r = norm * Math.cos(Math.toRadians(common)); double i = norm * Math.sin(Math.toRadians(common)); return new ComplexNumber(r, i); }
java
public static ComplexNumber Pow(ComplexNumber z1, double n) { double norm = Math.pow(z1.getMagnitude(), n); double angle = 360 - Math.abs(Math.toDegrees(Math.atan(z1.imaginary / z1.real))); double common = n * angle; double r = norm * Math.cos(Math.toRadians(common)); double i = norm * Math.sin(Math.toRadians(common)); return new ComplexNumber(r, i); }
[ "public", "static", "ComplexNumber", "Pow", "(", "ComplexNumber", "z1", ",", "double", "n", ")", "{", "double", "norm", "=", "Math", ".", "pow", "(", "z1", ".", "getMagnitude", "(", ")", ",", "n", ")", ";", "double", "angle", "=", "360", "-", "Math", ".", "abs", "(", "Math", ".", "toDegrees", "(", "Math", ".", "atan", "(", "z1", ".", "imaginary", "/", "z1", ".", "real", ")", ")", ")", ";", "double", "common", "=", "n", "*", "angle", ";", "double", "r", "=", "norm", "*", "Math", ".", "cos", "(", "Math", ".", "toRadians", "(", "common", ")", ")", ";", "double", "i", "=", "norm", "*", "Math", ".", "sin", "(", "Math", ".", "toRadians", "(", "common", ")", ")", ";", "return", "new", "ComplexNumber", "(", "r", ",", "i", ")", ";", "}" ]
Calculate power of a complex number. @param z1 Complex Number. @param n Power. @return Returns a new complex number containing the power of a specified number.
[ "Calculate", "power", "of", "a", "complex", "number", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/ComplexNumber.java#L414-L426
JM-Lab/utils-java8
src/main/java/kr/jm/utils/helper/JMFiles.java
JMFiles.readString
public static String readString(File targetFile, String charsetName) { """ Read string string. @param targetFile the target file @param charsetName the charset name @return the string """ return readString(targetFile.toPath(), charsetName); }
java
public static String readString(File targetFile, String charsetName) { return readString(targetFile.toPath(), charsetName); }
[ "public", "static", "String", "readString", "(", "File", "targetFile", ",", "String", "charsetName", ")", "{", "return", "readString", "(", "targetFile", ".", "toPath", "(", ")", ",", "charsetName", ")", ";", "}" ]
Read string string. @param targetFile the target file @param charsetName the charset name @return the string
[ "Read", "string", "string", "." ]
train
https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMFiles.java#L135-L137
eFaps/eFaps-Kernel
src/main/java/org/efaps/admin/index/Index.java
Index.getDirectory
public static Directory getDirectory() throws EFapsException { """ Gets the directory. @return the directory @throws EFapsException on error """ IDirectoryProvider provider = null; if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXDIRECTORYPROVCLASS)) { final String clazzname = EFapsSystemConfiguration.get().getAttributeValue( KernelSettings.INDEXDIRECTORYPROVCLASS); try { final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance()); provider = (IDirectoryProvider) clazz.newInstance(); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Index.class, "Could not instanciate IDirectoryProvider", e); } } else { provider = new IDirectoryProvider() { @Override public Directory getDirectory() throws EFapsException { return new RAMDirectory(); } @Override public Directory getTaxonomyDirectory() throws EFapsException { return null; } }; } return provider.getDirectory(); }
java
public static Directory getDirectory() throws EFapsException { IDirectoryProvider provider = null; if (EFapsSystemConfiguration.get().containsAttributeValue(KernelSettings.INDEXDIRECTORYPROVCLASS)) { final String clazzname = EFapsSystemConfiguration.get().getAttributeValue( KernelSettings.INDEXDIRECTORYPROVCLASS); try { final Class<?> clazz = Class.forName(clazzname, false, EFapsClassLoader.getInstance()); provider = (IDirectoryProvider) clazz.newInstance(); } catch (final ClassNotFoundException | InstantiationException | IllegalAccessException e) { throw new EFapsException(Index.class, "Could not instanciate IDirectoryProvider", e); } } else { provider = new IDirectoryProvider() { @Override public Directory getDirectory() throws EFapsException { return new RAMDirectory(); } @Override public Directory getTaxonomyDirectory() throws EFapsException { return null; } }; } return provider.getDirectory(); }
[ "public", "static", "Directory", "getDirectory", "(", ")", "throws", "EFapsException", "{", "IDirectoryProvider", "provider", "=", "null", ";", "if", "(", "EFapsSystemConfiguration", ".", "get", "(", ")", ".", "containsAttributeValue", "(", "KernelSettings", ".", "INDEXDIRECTORYPROVCLASS", ")", ")", "{", "final", "String", "clazzname", "=", "EFapsSystemConfiguration", ".", "get", "(", ")", ".", "getAttributeValue", "(", "KernelSettings", ".", "INDEXDIRECTORYPROVCLASS", ")", ";", "try", "{", "final", "Class", "<", "?", ">", "clazz", "=", "Class", ".", "forName", "(", "clazzname", ",", "false", ",", "EFapsClassLoader", ".", "getInstance", "(", ")", ")", ";", "provider", "=", "(", "IDirectoryProvider", ")", "clazz", ".", "newInstance", "(", ")", ";", "}", "catch", "(", "final", "ClassNotFoundException", "|", "InstantiationException", "|", "IllegalAccessException", "e", ")", "{", "throw", "new", "EFapsException", "(", "Index", ".", "class", ",", "\"Could not instanciate IDirectoryProvider\"", ",", "e", ")", ";", "}", "}", "else", "{", "provider", "=", "new", "IDirectoryProvider", "(", ")", "{", "@", "Override", "public", "Directory", "getDirectory", "(", ")", "throws", "EFapsException", "{", "return", "new", "RAMDirectory", "(", ")", ";", "}", "@", "Override", "public", "Directory", "getTaxonomyDirectory", "(", ")", "throws", "EFapsException", "{", "return", "null", ";", "}", "}", ";", "}", "return", "provider", ".", "getDirectory", "(", ")", ";", "}" ]
Gets the directory. @return the directory @throws EFapsException on error
[ "Gets", "the", "directory", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/admin/index/Index.java#L95-L127
OpenLiberty/open-liberty
dev/com.ibm.ws.transaction.cdi/src/com/ibm/tx/jta/cdi/interceptors/NotSupported.java
NotSupported.notSupported
@AroundInvoke public Object notSupported(final InvocationContext context) throws Exception { """ <p>If called outside a transaction context, managed bean method execution must then continue outside a transaction context.</p> <p>If called inside a transaction context, the current transaction context must be suspended, the managed bean method execution must then continue outside a transaction context, and the previously suspended transaction must be resumed by the interceptor that suspended it after the method execution has completed.</p> """ return runUnderUOWNoEnablement(UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION, true, context, "NOT_SUPPORTED"); }
java
@AroundInvoke public Object notSupported(final InvocationContext context) throws Exception { return runUnderUOWNoEnablement(UOWSynchronizationRegistry.UOW_TYPE_LOCAL_TRANSACTION, true, context, "NOT_SUPPORTED"); }
[ "@", "AroundInvoke", "public", "Object", "notSupported", "(", "final", "InvocationContext", "context", ")", "throws", "Exception", "{", "return", "runUnderUOWNoEnablement", "(", "UOWSynchronizationRegistry", ".", "UOW_TYPE_LOCAL_TRANSACTION", ",", "true", ",", "context", ",", "\"NOT_SUPPORTED\"", ")", ";", "}" ]
<p>If called outside a transaction context, managed bean method execution must then continue outside a transaction context.</p> <p>If called inside a transaction context, the current transaction context must be suspended, the managed bean method execution must then continue outside a transaction context, and the previously suspended transaction must be resumed by the interceptor that suspended it after the method execution has completed.</p>
[ "<p", ">", "If", "called", "outside", "a", "transaction", "context", "managed", "bean", "method", "execution", "must", "then", "continue", "outside", "a", "transaction", "context", ".", "<", "/", "p", ">", "<p", ">", "If", "called", "inside", "a", "transaction", "context", "the", "current", "transaction", "context", "must", "be", "suspended", "the", "managed", "bean", "method", "execution", "must", "then", "continue", "outside", "a", "transaction", "context", "and", "the", "previously", "suspended", "transaction", "must", "be", "resumed", "by", "the", "interceptor", "that", "suspended", "it", "after", "the", "method", "execution", "has", "completed", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.transaction.cdi/src/com/ibm/tx/jta/cdi/interceptors/NotSupported.java#L38-L43
passwordmaker/java-passwordmaker-lib
src/main/java/org/daveware/passwordmaker/PasswordMaker.java
PasswordMaker.makePassword
public SecureUTF8String makePassword(final SecureUTF8String masterPassword, final Account account, final String inputText) throws Exception { """ Generates a hash of the master password with settings from the account. It will use the username assigned to the account. @param masterPassword The password to use as a key for the various algorithms. @param account The account with the specific settings for the hash. @param inputText The text to use as the input into the password maker algorithm @return A SecureCharArray with the hashed data. @throws Exception if something bad happened. """ return makePassword(masterPassword, account, inputText, account.getUsername()); }
java
public SecureUTF8String makePassword(final SecureUTF8String masterPassword, final Account account, final String inputText) throws Exception { return makePassword(masterPassword, account, inputText, account.getUsername()); }
[ "public", "SecureUTF8String", "makePassword", "(", "final", "SecureUTF8String", "masterPassword", ",", "final", "Account", "account", ",", "final", "String", "inputText", ")", "throws", "Exception", "{", "return", "makePassword", "(", "masterPassword", ",", "account", ",", "inputText", ",", "account", ".", "getUsername", "(", ")", ")", ";", "}" ]
Generates a hash of the master password with settings from the account. It will use the username assigned to the account. @param masterPassword The password to use as a key for the various algorithms. @param account The account with the specific settings for the hash. @param inputText The text to use as the input into the password maker algorithm @return A SecureCharArray with the hashed data. @throws Exception if something bad happened.
[ "Generates", "a", "hash", "of", "the", "master", "password", "with", "settings", "from", "the", "account", ".", "It", "will", "use", "the", "username", "assigned", "to", "the", "account", "." ]
train
https://github.com/passwordmaker/java-passwordmaker-lib/blob/18c22fca7dd9a47f08161425b85a5bd257afbb2b/src/main/java/org/daveware/passwordmaker/PasswordMaker.java#L377-L381
apache/incubator-gobblin
gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/qualitychecker/InstrumentedRowLevelPolicyBase.java
InstrumentedRowLevelPolicyBase.afterCheck
public void afterCheck(Result result, long startTimeNanos) { """ Called after check is run. @param result result from check. @param startTimeNanos start time of check. """ switch (result) { case FAILED: Instrumented.markMeter(this.failedRecordsMeter); break; case PASSED: Instrumented.markMeter(this.passedRecordsMeter); break; default: } Instrumented.updateTimer(this.policyTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); }
java
public void afterCheck(Result result, long startTimeNanos) { switch (result) { case FAILED: Instrumented.markMeter(this.failedRecordsMeter); break; case PASSED: Instrumented.markMeter(this.passedRecordsMeter); break; default: } Instrumented.updateTimer(this.policyTimer, System.nanoTime() - startTimeNanos, TimeUnit.NANOSECONDS); }
[ "public", "void", "afterCheck", "(", "Result", "result", ",", "long", "startTimeNanos", ")", "{", "switch", "(", "result", ")", "{", "case", "FAILED", ":", "Instrumented", ".", "markMeter", "(", "this", ".", "failedRecordsMeter", ")", ";", "break", ";", "case", "PASSED", ":", "Instrumented", ".", "markMeter", "(", "this", ".", "passedRecordsMeter", ")", ";", "break", ";", "default", ":", "}", "Instrumented", ".", "updateTimer", "(", "this", ".", "policyTimer", ",", "System", ".", "nanoTime", "(", ")", "-", "startTimeNanos", ",", "TimeUnit", ".", "NANOSECONDS", ")", ";", "}" ]
Called after check is run. @param result result from check. @param startTimeNanos start time of check.
[ "Called", "after", "check", "is", "run", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core-base/src/main/java/org/apache/gobblin/instrumented/qualitychecker/InstrumentedRowLevelPolicyBase.java#L144-L156
playn/playn
android/src/playn/android/AndroidGraphics.java
AndroidGraphics.onSurfaceChanged
public void onSurfaceChanged (int pixelWidth, int pixelHeight, int orient) { """ Informs the graphics system that the surface into which it is rendering has changed size. The supplied width and height are in pixels, not display units. """ viewportChanged(pixelWidth, pixelHeight); screenSize.setSize(viewSize); switch (orient) { case Configuration.ORIENTATION_LANDSCAPE: orientDetailM.update(OrientationDetail.LANDSCAPE_LEFT); break; case Configuration.ORIENTATION_PORTRAIT: orientDetailM.update(OrientationDetail.PORTRAIT); break; default: // Configuration.ORIENTATION_UNDEFINED orientDetailM.update(OrientationDetail.UNKNOWN); break; } }
java
public void onSurfaceChanged (int pixelWidth, int pixelHeight, int orient) { viewportChanged(pixelWidth, pixelHeight); screenSize.setSize(viewSize); switch (orient) { case Configuration.ORIENTATION_LANDSCAPE: orientDetailM.update(OrientationDetail.LANDSCAPE_LEFT); break; case Configuration.ORIENTATION_PORTRAIT: orientDetailM.update(OrientationDetail.PORTRAIT); break; default: // Configuration.ORIENTATION_UNDEFINED orientDetailM.update(OrientationDetail.UNKNOWN); break; } }
[ "public", "void", "onSurfaceChanged", "(", "int", "pixelWidth", ",", "int", "pixelHeight", ",", "int", "orient", ")", "{", "viewportChanged", "(", "pixelWidth", ",", "pixelHeight", ")", ";", "screenSize", ".", "setSize", "(", "viewSize", ")", ";", "switch", "(", "orient", ")", "{", "case", "Configuration", ".", "ORIENTATION_LANDSCAPE", ":", "orientDetailM", ".", "update", "(", "OrientationDetail", ".", "LANDSCAPE_LEFT", ")", ";", "break", ";", "case", "Configuration", ".", "ORIENTATION_PORTRAIT", ":", "orientDetailM", ".", "update", "(", "OrientationDetail", ".", "PORTRAIT", ")", ";", "break", ";", "default", ":", "// Configuration.ORIENTATION_UNDEFINED", "orientDetailM", ".", "update", "(", "OrientationDetail", ".", "UNKNOWN", ")", ";", "break", ";", "}", "}" ]
Informs the graphics system that the surface into which it is rendering has changed size. The supplied width and height are in pixels, not display units.
[ "Informs", "the", "graphics", "system", "that", "the", "surface", "into", "which", "it", "is", "rendering", "has", "changed", "size", ".", "The", "supplied", "width", "and", "height", "are", "in", "pixels", "not", "display", "units", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/android/src/playn/android/AndroidGraphics.java#L134-L148
xm-online/xm-commons
xm-commons-security/src/main/java/com/icthh/xm/commons/security/oauth2/ConfigSignatureVerifierClient.java
ConfigSignatureVerifierClient.getSignatureVerifier
@Override public SignatureVerifier getSignatureVerifier() throws Exception { """ Fetches the public key from the MS Config. @return the public key used to verify JWT tokens; or null. """ try { HttpEntity<Void> request = new HttpEntity<>(new HttpHeaders()); String content = restTemplate.exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isEmpty(content)) { log.info("Public key not fetched"); return null; } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return new RsaVerifier(String.format(PUBLIC_KEY, new String(Base64.getEncoder().encode(pk.getEncoded())))); } catch (IllegalStateException ex) { log.warn("could not contact Config to get public key"); return null; } }
java
@Override public SignatureVerifier getSignatureVerifier() throws Exception { try { HttpEntity<Void> request = new HttpEntity<>(new HttpHeaders()); String content = restTemplate.exchange(getPublicKeyEndpoint(), HttpMethod.GET, request, String.class).getBody(); if (StringUtils.isEmpty(content)) { log.info("Public key not fetched"); return null; } InputStream fin = new ByteArrayInputStream(content.getBytes()); CertificateFactory f = CertificateFactory.getInstance("X.509"); X509Certificate certificate = (X509Certificate) f.generateCertificate(fin); PublicKey pk = certificate.getPublicKey(); return new RsaVerifier(String.format(PUBLIC_KEY, new String(Base64.getEncoder().encode(pk.getEncoded())))); } catch (IllegalStateException ex) { log.warn("could not contact Config to get public key"); return null; } }
[ "@", "Override", "public", "SignatureVerifier", "getSignatureVerifier", "(", ")", "throws", "Exception", "{", "try", "{", "HttpEntity", "<", "Void", ">", "request", "=", "new", "HttpEntity", "<>", "(", "new", "HttpHeaders", "(", ")", ")", ";", "String", "content", "=", "restTemplate", ".", "exchange", "(", "getPublicKeyEndpoint", "(", ")", ",", "HttpMethod", ".", "GET", ",", "request", ",", "String", ".", "class", ")", ".", "getBody", "(", ")", ";", "if", "(", "StringUtils", ".", "isEmpty", "(", "content", ")", ")", "{", "log", ".", "info", "(", "\"Public key not fetched\"", ")", ";", "return", "null", ";", "}", "InputStream", "fin", "=", "new", "ByteArrayInputStream", "(", "content", ".", "getBytes", "(", ")", ")", ";", "CertificateFactory", "f", "=", "CertificateFactory", ".", "getInstance", "(", "\"X.509\"", ")", ";", "X509Certificate", "certificate", "=", "(", "X509Certificate", ")", "f", ".", "generateCertificate", "(", "fin", ")", ";", "PublicKey", "pk", "=", "certificate", ".", "getPublicKey", "(", ")", ";", "return", "new", "RsaVerifier", "(", "String", ".", "format", "(", "PUBLIC_KEY", ",", "new", "String", "(", "Base64", ".", "getEncoder", "(", ")", ".", "encode", "(", "pk", ".", "getEncoded", "(", ")", ")", ")", ")", ")", ";", "}", "catch", "(", "IllegalStateException", "ex", ")", "{", "log", ".", "warn", "(", "\"could not contact Config to get public key\"", ")", ";", "return", "null", ";", "}", "}" ]
Fetches the public key from the MS Config. @return the public key used to verify JWT tokens; or null.
[ "Fetches", "the", "public", "key", "from", "the", "MS", "Config", "." ]
train
https://github.com/xm-online/xm-commons/blob/43eb2273adb96f40830d7b905ee3a767b8715caf/xm-commons-security/src/main/java/com/icthh/xm/commons/security/oauth2/ConfigSignatureVerifierClient.java#L44-L67
querydsl/querydsl
querydsl-lucene5/src/main/java/com/querydsl/lucene5/LuceneSerializer.java
LuceneSerializer.createBooleanClause
private BooleanClause createBooleanClause(Query query, Occur occur) { """ If the query is a BooleanQuery and it contains a single Occur.MUST_NOT clause it will be returned as is. Otherwise it will be wrapped in a BooleanClause with the given Occur. """ if (query instanceof BooleanQuery) { BooleanClause[] clauses = ((BooleanQuery) query).getClauses(); if (clauses.length == 1 && clauses[0].getOccur().equals(Occur.MUST_NOT)) { return clauses[0]; } } return new BooleanClause(query, occur); }
java
private BooleanClause createBooleanClause(Query query, Occur occur) { if (query instanceof BooleanQuery) { BooleanClause[] clauses = ((BooleanQuery) query).getClauses(); if (clauses.length == 1 && clauses[0].getOccur().equals(Occur.MUST_NOT)) { return clauses[0]; } } return new BooleanClause(query, occur); }
[ "private", "BooleanClause", "createBooleanClause", "(", "Query", "query", ",", "Occur", "occur", ")", "{", "if", "(", "query", "instanceof", "BooleanQuery", ")", "{", "BooleanClause", "[", "]", "clauses", "=", "(", "(", "BooleanQuery", ")", "query", ")", ".", "getClauses", "(", ")", ";", "if", "(", "clauses", ".", "length", "==", "1", "&&", "clauses", "[", "0", "]", ".", "getOccur", "(", ")", ".", "equals", "(", "Occur", ".", "MUST_NOT", ")", ")", "{", "return", "clauses", "[", "0", "]", ";", "}", "}", "return", "new", "BooleanClause", "(", "query", ",", "occur", ")", ";", "}" ]
If the query is a BooleanQuery and it contains a single Occur.MUST_NOT clause it will be returned as is. Otherwise it will be wrapped in a BooleanClause with the given Occur.
[ "If", "the", "query", "is", "a", "BooleanQuery", "and", "it", "contains", "a", "single", "Occur", ".", "MUST_NOT", "clause", "it", "will", "be", "returned", "as", "is", ".", "Otherwise", "it", "will", "be", "wrapped", "in", "a", "BooleanClause", "with", "the", "given", "Occur", "." ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-lucene5/src/main/java/com/querydsl/lucene5/LuceneSerializer.java#L179-L188
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSet.java
NodeSet.addNodes
public void addNodes(NodeList nodelist) { """ Copy NodeList members into this nodelist, adding in document order. If a node is null, don't add it. @param nodelist List of nodes which should now be referenced by this NodeSet. @throws RuntimeException thrown if this NodeSet is not of a mutable type. """ if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); if (null != nodelist) // defensive to fix a bug that Sanjiva reported. { int nChildren = nodelist.getLength(); for (int i = 0; i < nChildren; i++) { Node obj = nodelist.item(i); if (null != obj) { addElement(obj); } } } // checkDups(); }
java
public void addNodes(NodeList nodelist) { if (!m_mutable) throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_NODESET_NOT_MUTABLE, null)); //"This NodeSet is not mutable!"); if (null != nodelist) // defensive to fix a bug that Sanjiva reported. { int nChildren = nodelist.getLength(); for (int i = 0; i < nChildren; i++) { Node obj = nodelist.item(i); if (null != obj) { addElement(obj); } } } // checkDups(); }
[ "public", "void", "addNodes", "(", "NodeList", "nodelist", ")", "{", "if", "(", "!", "m_mutable", ")", "throw", "new", "RuntimeException", "(", "XSLMessages", ".", "createXPATHMessage", "(", "XPATHErrorResources", ".", "ER_NODESET_NOT_MUTABLE", ",", "null", ")", ")", ";", "//\"This NodeSet is not mutable!\");", "if", "(", "null", "!=", "nodelist", ")", "// defensive to fix a bug that Sanjiva reported.", "{", "int", "nChildren", "=", "nodelist", ".", "getLength", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nChildren", ";", "i", "++", ")", "{", "Node", "obj", "=", "nodelist", ".", "item", "(", "i", ")", ";", "if", "(", "null", "!=", "obj", ")", "{", "addElement", "(", "obj", ")", ";", "}", "}", "}", "// checkDups();", "}" ]
Copy NodeList members into this nodelist, adding in document order. If a node is null, don't add it. @param nodelist List of nodes which should now be referenced by this NodeSet. @throws RuntimeException thrown if this NodeSet is not of a mutable type.
[ "Copy", "NodeList", "members", "into", "this", "nodelist", "adding", "in", "document", "order", ".", "If", "a", "node", "is", "null", "don", "t", "add", "it", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/NodeSet.java#L431-L453
amaembo/streamex
src/main/java/one/util/streamex/LongStreamEx.java
LongStreamEx.mapLast
public LongStreamEx mapLast(LongUnaryOperator mapper) { """ Returns a stream where the last element is the replaced with the result of applying the given function while the other elements are left intact. <p> This is a <a href="package-summary.html#StreamOps">quasi-intermediate operation</a>. <p> The mapper function is called at most once. It could be not called at all if the stream is empty or there is short-circuiting operation downstream. @param mapper a <a href="package-summary.html#NonInterference">non-interfering </a>, <a href="package-summary.html#Statelessness">stateless</a> function to apply to the last element @return the new stream @since 0.4.1 """ return delegate(new PairSpliterator.PSOfLong((a, b) -> a, mapper, spliterator(), PairSpliterator.MODE_MAP_LAST)); }
java
public LongStreamEx mapLast(LongUnaryOperator mapper) { return delegate(new PairSpliterator.PSOfLong((a, b) -> a, mapper, spliterator(), PairSpliterator.MODE_MAP_LAST)); }
[ "public", "LongStreamEx", "mapLast", "(", "LongUnaryOperator", "mapper", ")", "{", "return", "delegate", "(", "new", "PairSpliterator", ".", "PSOfLong", "(", "(", "a", ",", "b", ")", "->", "a", ",", "mapper", ",", "spliterator", "(", ")", ",", "PairSpliterator", ".", "MODE_MAP_LAST", ")", ")", ";", "}" ]
Returns a stream where the last element is the replaced with the result of applying the given function while the other elements are left intact. <p> This is a <a href="package-summary.html#StreamOps">quasi-intermediate operation</a>. <p> The mapper function is called at most once. It could be not called at all if the stream is empty or there is short-circuiting operation downstream. @param mapper a <a href="package-summary.html#NonInterference">non-interfering </a>, <a href="package-summary.html#Statelessness">stateless</a> function to apply to the last element @return the new stream @since 0.4.1
[ "Returns", "a", "stream", "where", "the", "last", "element", "is", "the", "replaced", "with", "the", "result", "of", "applying", "the", "given", "function", "while", "the", "other", "elements", "are", "left", "intact", "." ]
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/LongStreamEx.java#L258-L261
aleksandr-m/gitflow-maven-plugin
src/main/java/com/amashchenko/maven/plugin/gitflow/AbstractGitFlowMojo.java
AbstractGitFlowMojo.gitCommit
protected void gitCommit(String message, Map<String, String> messageProperties) throws MojoFailureException, CommandLineException { """ Executes git commit -a -m, replacing <code>@{map.key}</code> with <code>map.value</code>. @param message Commit message. @param messageProperties Properties to replace in message. @throws MojoFailureException @throws CommandLineException """ message = replaceProperties(message, messageProperties); if (gpgSignCommit) { getLog().info("Committing changes. GPG-signed."); executeGitCommand("commit", "-a", "-S", "-m", message); } else { getLog().info("Committing changes."); executeGitCommand("commit", "-a", "-m", message); } }
java
protected void gitCommit(String message, Map<String, String> messageProperties) throws MojoFailureException, CommandLineException { message = replaceProperties(message, messageProperties); if (gpgSignCommit) { getLog().info("Committing changes. GPG-signed."); executeGitCommand("commit", "-a", "-S", "-m", message); } else { getLog().info("Committing changes."); executeGitCommand("commit", "-a", "-m", message); } }
[ "protected", "void", "gitCommit", "(", "String", "message", ",", "Map", "<", "String", ",", "String", ">", "messageProperties", ")", "throws", "MojoFailureException", ",", "CommandLineException", "{", "message", "=", "replaceProperties", "(", "message", ",", "messageProperties", ")", ";", "if", "(", "gpgSignCommit", ")", "{", "getLog", "(", ")", ".", "info", "(", "\"Committing changes. GPG-signed.\"", ")", ";", "executeGitCommand", "(", "\"commit\"", ",", "\"-a\"", ",", "\"-S\"", ",", "\"-m\"", ",", "message", ")", ";", "}", "else", "{", "getLog", "(", ")", ".", "info", "(", "\"Committing changes.\"", ")", ";", "executeGitCommand", "(", "\"commit\"", ",", "\"-a\"", ",", "\"-m\"", ",", "message", ")", ";", "}", "}" ]
Executes git commit -a -m, replacing <code>@{map.key}</code> with <code>map.value</code>. @param message Commit message. @param messageProperties Properties to replace in message. @throws MojoFailureException @throws CommandLineException
[ "Executes", "git", "commit", "-", "a", "-", "m", "replacing", "<code", ">", "@", "{", "map", ".", "key", "}", "<", "/", "code", ">", "with", "<code", ">", "map", ".", "value<", "/", "code", ">", "." ]
train
https://github.com/aleksandr-m/gitflow-maven-plugin/blob/d7be13c653d885c1cb1d8cd0337fa9db985c381e/src/main/java/com/amashchenko/maven/plugin/gitflow/AbstractGitFlowMojo.java#L637-L650
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/UcsApi.java
UcsApi.deleteContact
public ApiSuccessResponse deleteContact(String id, DeletelData deletelData) throws ApiException { """ Delete an existing contact @param id id of the Contact (required) @param deletelData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body """ ApiResponse<ApiSuccessResponse> resp = deleteContactWithHttpInfo(id, deletelData); return resp.getData(); }
java
public ApiSuccessResponse deleteContact(String id, DeletelData deletelData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = deleteContactWithHttpInfo(id, deletelData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "deleteContact", "(", "String", "id", ",", "DeletelData", "deletelData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "deleteContactWithHttpInfo", "(", "id", ",", "deletelData", ")", ";", "return", "resp", ".", "getData", "(", ")", ";", "}" ]
Delete an existing contact @param id id of the Contact (required) @param deletelData Request parameters. (optional) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Delete", "an", "existing", "contact" ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/UcsApi.java#L403-L406
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/ScrollBarButtonPainter.java
ScrollBarButtonPainter.paintBackgroundCap
private void paintBackgroundCap(Graphics2D g, int width, int height) { """ DOCUMENT ME! @param g DOCUMENT ME! @param width DOCUMENT ME! @param height DOCUMENT ME! """ Shape s = shapeGenerator.createScrollCap(0, 0, width, height); dropShadow.fill(g, s); fillScrollBarButtonInteriorColors(g, s, isIncrease, buttonsTogether); }
java
private void paintBackgroundCap(Graphics2D g, int width, int height) { Shape s = shapeGenerator.createScrollCap(0, 0, width, height); dropShadow.fill(g, s); fillScrollBarButtonInteriorColors(g, s, isIncrease, buttonsTogether); }
[ "private", "void", "paintBackgroundCap", "(", "Graphics2D", "g", ",", "int", "width", ",", "int", "height", ")", "{", "Shape", "s", "=", "shapeGenerator", ".", "createScrollCap", "(", "0", ",", "0", ",", "width", ",", "height", ")", ";", "dropShadow", ".", "fill", "(", "g", ",", "s", ")", ";", "fillScrollBarButtonInteriorColors", "(", "g", ",", "s", ",", "isIncrease", ",", "buttonsTogether", ")", ";", "}" ]
DOCUMENT ME! @param g DOCUMENT ME! @param width DOCUMENT ME! @param height DOCUMENT ME!
[ "DOCUMENT", "ME!" ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/ScrollBarButtonPainter.java#L241-L246
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java
DisasterRecoveryConfigurationsInner.createOrUpdateAsync
public Observable<DisasterRecoveryConfigurationInner> createOrUpdateAsync(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) { """ Creates or updates a disaster recovery configuration. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param disasterRecoveryConfigurationName The name of the disaster recovery configuration to be created/updated. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).map(new Func1<ServiceResponse<DisasterRecoveryConfigurationInner>, DisasterRecoveryConfigurationInner>() { @Override public DisasterRecoveryConfigurationInner call(ServiceResponse<DisasterRecoveryConfigurationInner> response) { return response.body(); } }); }
java
public Observable<DisasterRecoveryConfigurationInner> createOrUpdateAsync(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).map(new Func1<ServiceResponse<DisasterRecoveryConfigurationInner>, DisasterRecoveryConfigurationInner>() { @Override public DisasterRecoveryConfigurationInner call(ServiceResponse<DisasterRecoveryConfigurationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DisasterRecoveryConfigurationInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "disasterRecoveryConfigurationName", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "disasterRecoveryConfigurationName", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DisasterRecoveryConfigurationInner", ">", ",", "DisasterRecoveryConfigurationInner", ">", "(", ")", "{", "@", "Override", "public", "DisasterRecoveryConfigurationInner", "call", "(", "ServiceResponse", "<", "DisasterRecoveryConfigurationInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a disaster recovery configuration. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param disasterRecoveryConfigurationName The name of the disaster recovery configuration to be created/updated. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Creates", "or", "updates", "a", "disaster", "recovery", "configuration", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java#L398-L405
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
LambdaToMethod.makeSyntheticVar
private VarSymbol makeSyntheticVar(long flags, Name name, Type type, Symbol owner) { """ Create new synthetic variable with given flags, name, type, owner """ return new VarSymbol(flags | SYNTHETIC, name, type, owner); }
java
private VarSymbol makeSyntheticVar(long flags, Name name, Type type, Symbol owner) { return new VarSymbol(flags | SYNTHETIC, name, type, owner); }
[ "private", "VarSymbol", "makeSyntheticVar", "(", "long", "flags", ",", "Name", "name", ",", "Type", "type", ",", "Symbol", "owner", ")", "{", "return", "new", "VarSymbol", "(", "flags", "|", "SYNTHETIC", ",", "name", ",", "type", ",", "owner", ")", ";", "}" ]
Create new synthetic variable with given flags, name, type, owner
[ "Create", "new", "synthetic", "variable", "with", "given", "flags", "name", "type", "owner" ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java#L782-L784
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java
ObjectDataTypesInner.listFieldsByModuleAndType
public List<TypeFieldInner> listFieldsByModuleAndType(String resourceGroupName, String automationAccountName, String moduleName, String typeName) { """ Retrieve a list of fields of a given type identified by module name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param moduleName The name of module. @param typeName The name of type. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;TypeFieldInner&gt; object if successful. """ return listFieldsByModuleAndTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, typeName).toBlocking().single().body(); }
java
public List<TypeFieldInner> listFieldsByModuleAndType(String resourceGroupName, String automationAccountName, String moduleName, String typeName) { return listFieldsByModuleAndTypeWithServiceResponseAsync(resourceGroupName, automationAccountName, moduleName, typeName).toBlocking().single().body(); }
[ "public", "List", "<", "TypeFieldInner", ">", "listFieldsByModuleAndType", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "moduleName", ",", "String", "typeName", ")", "{", "return", "listFieldsByModuleAndTypeWithServiceResponseAsync", "(", "resourceGroupName", ",", "automationAccountName", ",", "moduleName", ",", "typeName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Retrieve a list of fields of a given type identified by module name. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param moduleName The name of module. @param typeName The name of type. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the List&lt;TypeFieldInner&gt; object if successful.
[ "Retrieve", "a", "list", "of", "fields", "of", "a", "given", "type", "identified", "by", "module", "name", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ObjectDataTypesInner.java#L77-L79
albfernandez/itext2
src/main/java/com/lowagie/text/rtf/document/output/RtfByteArrayBuffer.java
RtfByteArrayBuffer.write
public void write(final byte[] src, int off, int len) { """ Copies len bytes starting at position off from the array src to the internal buffer. @param src @param off @param len """ if(src == null) throw new NullPointerException(); if((off < 0) || (off > src.length) || (len < 0) || ((off + len) > src.length) || ((off + len) < 0)) throw new IndexOutOfBoundsException(); writeLoop(src, off, len); }
java
public void write(final byte[] src, int off, int len) { if(src == null) throw new NullPointerException(); if((off < 0) || (off > src.length) || (len < 0) || ((off + len) > src.length) || ((off + len) < 0)) throw new IndexOutOfBoundsException(); writeLoop(src, off, len); }
[ "public", "void", "write", "(", "final", "byte", "[", "]", "src", ",", "int", "off", ",", "int", "len", ")", "{", "if", "(", "src", "==", "null", ")", "throw", "new", "NullPointerException", "(", ")", ";", "if", "(", "(", "off", "<", "0", ")", "||", "(", "off", ">", "src", ".", "length", ")", "||", "(", "len", "<", "0", ")", "||", "(", "(", "off", "+", "len", ")", ">", "src", ".", "length", ")", "||", "(", "(", "off", "+", "len", ")", "<", "0", ")", ")", "throw", "new", "IndexOutOfBoundsException", "(", ")", ";", "writeLoop", "(", "src", ",", "off", ",", "len", ")", ";", "}" ]
Copies len bytes starting at position off from the array src to the internal buffer. @param src @param off @param len
[ "Copies", "len", "bytes", "starting", "at", "position", "off", "from", "the", "array", "src", "to", "the", "internal", "buffer", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/document/output/RtfByteArrayBuffer.java#L182-L188
derari/cthul
matchers/src/main/java/org/cthul/matchers/diagnose/nested/Nested.java
Nested.describeTo
public static void describeTo(PrecedencedSelfDescribing self, SelfDescribing nested, Description d) { """ Appends description of {@code s} to {@code d}, enclosed in parentheses if necessary. @param self @param d @param nested """ boolean paren = useParen(self, nested); describeTo(paren, nested, d); }
java
public static void describeTo(PrecedencedSelfDescribing self, SelfDescribing nested, Description d) { boolean paren = useParen(self, nested); describeTo(paren, nested, d); }
[ "public", "static", "void", "describeTo", "(", "PrecedencedSelfDescribing", "self", ",", "SelfDescribing", "nested", ",", "Description", "d", ")", "{", "boolean", "paren", "=", "useParen", "(", "self", ",", "nested", ")", ";", "describeTo", "(", "paren", ",", "nested", ",", "d", ")", ";", "}" ]
Appends description of {@code s} to {@code d}, enclosed in parentheses if necessary. @param self @param d @param nested
[ "Appends", "description", "of", "{" ]
train
https://github.com/derari/cthul/blob/74a31e3cb6a94f5f25cc5253d1dbd42e19a17ebc/matchers/src/main/java/org/cthul/matchers/diagnose/nested/Nested.java#L58-L61
aws/aws-sdk-java
aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/ListPoliciesGrantingServiceAccessRequest.java
ListPoliciesGrantingServiceAccessRequest.getServiceNamespaces
public java.util.List<String> getServiceNamespaces() { """ <p> The service namespace for the AWS services whose policies you want to list. </p> <p> To learn the service namespace for a service, go to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html" >Actions, Resources, and Condition Keys for AWS Services</a> in the <i>IAM User Guide</i>. Choose the name of the service to view details for that service. In the first paragraph, find the service prefix. For example, <code>(service prefix: a4b)</code>. For more information about service namespaces, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces" >AWS Service Namespaces</a> in the <i>AWS General Reference</i>. </p> @return The service namespace for the AWS services whose policies you want to list.</p> <p> To learn the service namespace for a service, go to <a href= "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html" >Actions, Resources, and Condition Keys for AWS Services</a> in the <i>IAM User Guide</i>. Choose the name of the service to view details for that service. In the first paragraph, find the service prefix. For example, <code>(service prefix: a4b)</code>. For more information about service namespaces, see <a href= "https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces" >AWS Service Namespaces</a> in the <i>AWS General Reference</i>. """ if (serviceNamespaces == null) { serviceNamespaces = new com.amazonaws.internal.SdkInternalList<String>(); } return serviceNamespaces; }
java
public java.util.List<String> getServiceNamespaces() { if (serviceNamespaces == null) { serviceNamespaces = new com.amazonaws.internal.SdkInternalList<String>(); } return serviceNamespaces; }
[ "public", "java", ".", "util", ".", "List", "<", "String", ">", "getServiceNamespaces", "(", ")", "{", "if", "(", "serviceNamespaces", "==", "null", ")", "{", "serviceNamespaces", "=", "new", "com", ".", "amazonaws", ".", "internal", ".", "SdkInternalList", "<", "String", ">", "(", ")", ";", "}", "return", "serviceNamespaces", ";", "}" ]
<p> The service namespace for the AWS services whose policies you want to list. </p> <p> To learn the service namespace for a service, go to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html" >Actions, Resources, and Condition Keys for AWS Services</a> in the <i>IAM User Guide</i>. Choose the name of the service to view details for that service. In the first paragraph, find the service prefix. For example, <code>(service prefix: a4b)</code>. For more information about service namespaces, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces" >AWS Service Namespaces</a> in the <i>AWS General Reference</i>. </p> @return The service namespace for the AWS services whose policies you want to list.</p> <p> To learn the service namespace for a service, go to <a href= "https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html" >Actions, Resources, and Condition Keys for AWS Services</a> in the <i>IAM User Guide</i>. Choose the name of the service to view details for that service. In the first paragraph, find the service prefix. For example, <code>(service prefix: a4b)</code>. For more information about service namespaces, see <a href= "https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-aws-service-namespaces" >AWS Service Namespaces</a> in the <i>AWS General Reference</i>.
[ "<p", ">", "The", "service", "namespace", "for", "the", "AWS", "services", "whose", "policies", "you", "want", "to", "list", ".", "<", "/", "p", ">", "<p", ">", "To", "learn", "the", "service", "namespace", "for", "a", "service", "go", "to", "<a", "href", "=", "https", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "IAM", "/", "latest", "/", "UserGuide", "/", "reference_policies_actions", "-", "resources", "-", "contextkeys", ".", "html", ">", "Actions", "Resources", "and", "Condition", "Keys", "for", "AWS", "Services<", "/", "a", ">", "in", "the", "<i", ">", "IAM", "User", "Guide<", "/", "i", ">", ".", "Choose", "the", "name", "of", "the", "service", "to", "view", "details", "for", "that", "service", ".", "In", "the", "first", "paragraph", "find", "the", "service", "prefix", ".", "For", "example", "<code", ">", "(", "service", "prefix", ":", "a4b", ")", "<", "/", "code", ">", ".", "For", "more", "information", "about", "service", "namespaces", "see", "<a", "href", "=", "https", ":", "//", "docs", ".", "aws", ".", "amazon", ".", "com", "/", "general", "/", "latest", "/", "gr", "/", "aws", "-", "arns", "-", "and", "-", "namespaces", ".", "html#genref", "-", "aws", "-", "service", "-", "namespaces", ">", "AWS", "Service", "Namespaces<", "/", "a", ">", "in", "the", "<i", ">", "AWS", "General", "Reference<", "/", "i", ">", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iam/src/main/java/com/amazonaws/services/identitymanagement/model/ListPoliciesGrantingServiceAccessRequest.java#L176-L181
grpc/grpc-java
core/src/main/java/io/grpc/internal/ManagedChannelImpl.java
ManagedChannelImpl.exitIdleMode
@VisibleForTesting void exitIdleMode() { """ Make the channel exit idle mode, if it's in it. <p>Must be called from syncContext """ syncContext.throwIfNotInThisSynchronizationContext(); if (shutdown.get() || panicMode) { return; } if (inUseStateAggregator.isInUse()) { // Cancel the timer now, so that a racing due timer will not put Channel on idleness // when the caller of exitIdleMode() is about to use the returned loadBalancer. cancelIdleTimer(false); } else { // exitIdleMode() may be called outside of inUseStateAggregator.handleNotInUse() while // isInUse() == false, in which case we still need to schedule the timer. rescheduleIdleTimer(); } if (lbHelper != null) { return; } channelLogger.log(ChannelLogLevel.INFO, "Exiting idle mode"); LbHelperImpl lbHelper = new LbHelperImpl(); lbHelper.lb = loadBalancerFactory.newLoadBalancer(lbHelper); // Delay setting lbHelper until fully initialized, since loadBalancerFactory is user code and // may throw. We don't want to confuse our state, even if we will enter panic mode. this.lbHelper = lbHelper; NameResolverObserver observer = new NameResolverObserver(lbHelper, nameResolver); nameResolver.start(observer); nameResolverStarted = true; }
java
@VisibleForTesting void exitIdleMode() { syncContext.throwIfNotInThisSynchronizationContext(); if (shutdown.get() || panicMode) { return; } if (inUseStateAggregator.isInUse()) { // Cancel the timer now, so that a racing due timer will not put Channel on idleness // when the caller of exitIdleMode() is about to use the returned loadBalancer. cancelIdleTimer(false); } else { // exitIdleMode() may be called outside of inUseStateAggregator.handleNotInUse() while // isInUse() == false, in which case we still need to schedule the timer. rescheduleIdleTimer(); } if (lbHelper != null) { return; } channelLogger.log(ChannelLogLevel.INFO, "Exiting idle mode"); LbHelperImpl lbHelper = new LbHelperImpl(); lbHelper.lb = loadBalancerFactory.newLoadBalancer(lbHelper); // Delay setting lbHelper until fully initialized, since loadBalancerFactory is user code and // may throw. We don't want to confuse our state, even if we will enter panic mode. this.lbHelper = lbHelper; NameResolverObserver observer = new NameResolverObserver(lbHelper, nameResolver); nameResolver.start(observer); nameResolverStarted = true; }
[ "@", "VisibleForTesting", "void", "exitIdleMode", "(", ")", "{", "syncContext", ".", "throwIfNotInThisSynchronizationContext", "(", ")", ";", "if", "(", "shutdown", ".", "get", "(", ")", "||", "panicMode", ")", "{", "return", ";", "}", "if", "(", "inUseStateAggregator", ".", "isInUse", "(", ")", ")", "{", "// Cancel the timer now, so that a racing due timer will not put Channel on idleness", "// when the caller of exitIdleMode() is about to use the returned loadBalancer.", "cancelIdleTimer", "(", "false", ")", ";", "}", "else", "{", "// exitIdleMode() may be called outside of inUseStateAggregator.handleNotInUse() while", "// isInUse() == false, in which case we still need to schedule the timer.", "rescheduleIdleTimer", "(", ")", ";", "}", "if", "(", "lbHelper", "!=", "null", ")", "{", "return", ";", "}", "channelLogger", ".", "log", "(", "ChannelLogLevel", ".", "INFO", ",", "\"Exiting idle mode\"", ")", ";", "LbHelperImpl", "lbHelper", "=", "new", "LbHelperImpl", "(", ")", ";", "lbHelper", ".", "lb", "=", "loadBalancerFactory", ".", "newLoadBalancer", "(", "lbHelper", ")", ";", "// Delay setting lbHelper until fully initialized, since loadBalancerFactory is user code and", "// may throw. We don't want to confuse our state, even if we will enter panic mode.", "this", ".", "lbHelper", "=", "lbHelper", ";", "NameResolverObserver", "observer", "=", "new", "NameResolverObserver", "(", "lbHelper", ",", "nameResolver", ")", ";", "nameResolver", ".", "start", "(", "observer", ")", ";", "nameResolverStarted", "=", "true", ";", "}" ]
Make the channel exit idle mode, if it's in it. <p>Must be called from syncContext
[ "Make", "the", "channel", "exit", "idle", "mode", "if", "it", "s", "in", "it", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/core/src/main/java/io/grpc/internal/ManagedChannelImpl.java#L354-L382
spring-projects/spring-boot
spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java
CommandRunner.runAndHandleErrors
public int runAndHandleErrors(String... args) { """ Run the appropriate and handle and errors. @param args the input arguments @return a return status code (non boot is used to indicate an error) """ String[] argsWithoutDebugFlags = removeDebugFlags(args); boolean debug = argsWithoutDebugFlags.length != args.length; if (debug) { System.setProperty("debug", "true"); } try { ExitStatus result = run(argsWithoutDebugFlags); // The caller will hang up if it gets a non-zero status if (result != null && result.isHangup()) { return (result.getCode() > 0) ? result.getCode() : 0; } return 0; } catch (NoArgumentsException ex) { showUsage(); return 1; } catch (Exception ex) { return handleError(debug, ex); } }
java
public int runAndHandleErrors(String... args) { String[] argsWithoutDebugFlags = removeDebugFlags(args); boolean debug = argsWithoutDebugFlags.length != args.length; if (debug) { System.setProperty("debug", "true"); } try { ExitStatus result = run(argsWithoutDebugFlags); // The caller will hang up if it gets a non-zero status if (result != null && result.isHangup()) { return (result.getCode() > 0) ? result.getCode() : 0; } return 0; } catch (NoArgumentsException ex) { showUsage(); return 1; } catch (Exception ex) { return handleError(debug, ex); } }
[ "public", "int", "runAndHandleErrors", "(", "String", "...", "args", ")", "{", "String", "[", "]", "argsWithoutDebugFlags", "=", "removeDebugFlags", "(", "args", ")", ";", "boolean", "debug", "=", "argsWithoutDebugFlags", ".", "length", "!=", "args", ".", "length", ";", "if", "(", "debug", ")", "{", "System", ".", "setProperty", "(", "\"debug\"", ",", "\"true\"", ")", ";", "}", "try", "{", "ExitStatus", "result", "=", "run", "(", "argsWithoutDebugFlags", ")", ";", "// The caller will hang up if it gets a non-zero status", "if", "(", "result", "!=", "null", "&&", "result", ".", "isHangup", "(", ")", ")", "{", "return", "(", "result", ".", "getCode", "(", ")", ">", "0", ")", "?", "result", ".", "getCode", "(", ")", ":", "0", ";", "}", "return", "0", ";", "}", "catch", "(", "NoArgumentsException", "ex", ")", "{", "showUsage", "(", ")", ";", "return", "1", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "return", "handleError", "(", "debug", ",", "ex", ")", ";", "}", "}" ]
Run the appropriate and handle and errors. @param args the input arguments @return a return status code (non boot is used to indicate an error)
[ "Run", "the", "appropriate", "and", "handle", "and", "errors", "." ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/CommandRunner.java#L164-L185
lucee/Lucee
core/src/main/java/lucee/commons/collection/LinkedHashMapPro.java
LinkedHashMapPro.createEntry
@Override void createEntry(int hash, K key, V value, int bucketIndex) { """ This override differs from addEntry in that it doesn't resize the table or remove the eldest entry. """ HashMapPro.Entry<K, V> old = table[bucketIndex]; Entry<K, V> e = new Entry<K, V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
java
@Override void createEntry(int hash, K key, V value, int bucketIndex) { HashMapPro.Entry<K, V> old = table[bucketIndex]; Entry<K, V> e = new Entry<K, V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
[ "@", "Override", "void", "createEntry", "(", "int", "hash", ",", "K", "key", ",", "V", "value", ",", "int", "bucketIndex", ")", "{", "HashMapPro", ".", "Entry", "<", "K", ",", "V", ">", "old", "=", "table", "[", "bucketIndex", "]", ";", "Entry", "<", "K", ",", "V", ">", "e", "=", "new", "Entry", "<", "K", ",", "V", ">", "(", "hash", ",", "key", ",", "value", ",", "old", ")", ";", "table", "[", "bucketIndex", "]", "=", "e", ";", "e", ".", "addBefore", "(", "header", ")", ";", "size", "++", ";", "}" ]
This override differs from addEntry in that it doesn't resize the table or remove the eldest entry.
[ "This", "override", "differs", "from", "addEntry", "in", "that", "it", "doesn", "t", "resize", "the", "table", "or", "remove", "the", "eldest", "entry", "." ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/collection/LinkedHashMapPro.java#L368-L375
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java
PageFlowUtils.addActionOutput
public static void addActionOutput( String name, Object value, ServletRequest request ) { """ Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag. The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context. @param name the name of the action output. @param value the value of the action output. @param request the current ServletRequest. """ Map map = InternalUtils.getActionOutputMap( request, true ); if ( map.containsKey( name ) ) { if ( _log.isWarnEnabled() ) { _log.warn( "Overwriting action output\"" + name + "\"." ); } } map.put( name, value ); }
java
public static void addActionOutput( String name, Object value, ServletRequest request ) { Map map = InternalUtils.getActionOutputMap( request, true ); if ( map.containsKey( name ) ) { if ( _log.isWarnEnabled() ) { _log.warn( "Overwriting action output\"" + name + "\"." ); } } map.put( name, value ); }
[ "public", "static", "void", "addActionOutput", "(", "String", "name", ",", "Object", "value", ",", "ServletRequest", "request", ")", "{", "Map", "map", "=", "InternalUtils", ".", "getActionOutputMap", "(", "request", ",", "true", ")", ";", "if", "(", "map", ".", "containsKey", "(", "name", ")", ")", "{", "if", "(", "_log", ".", "isWarnEnabled", "(", ")", ")", "{", "_log", ".", "warn", "(", "\"Overwriting action output\\\"\"", "+", "name", "+", "\"\\\".\"", ")", ";", "}", "}", "map", ".", "put", "(", "name", ",", "value", ")", ";", "}" ]
Set a named action output, which corresponds to an input declared by the <code>pageInput</code> JSP tag. The actual value can be read from within a JSP using the <code>"pageInput"</code> databinding context. @param name the name of the action output. @param value the value of the action output. @param request the current ServletRequest.
[ "Set", "a", "named", "action", "output", "which", "corresponds", "to", "an", "input", "declared", "by", "the", "<code", ">", "pageInput<", "/", "code", ">", "JSP", "tag", ".", "The", "actual", "value", "can", "be", "read", "from", "within", "a", "JSP", "using", "the", "<code", ">", "pageInput", "<", "/", "code", ">", "databinding", "context", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowUtils.java#L934-L947
rhuss/jolokia
client/java/src/main/java/org/jolokia/client/request/J4pRequestHandler.java
J4pRequestHandler.getHttpRequest
public <T extends J4pRequest> HttpUriRequest getHttpRequest(List<T> pRequests,Map<J4pQueryParameter,String> pProcessingOptions) throws UnsupportedEncodingException, URISyntaxException { """ Get an HTTP Request for requesting multiples requests at once @param pRequests requests to put into a HTTP request @return HTTP request to send to the server """ JSONArray bulkRequest = new JSONArray(); String queryParams = prepareQueryParameters(pProcessingOptions); HttpPost postReq = new HttpPost(createRequestURI(j4pServerUrl.getPath(),queryParams)); for (T request : pRequests) { JSONObject requestContent = getJsonRequestContent(request); bulkRequest.add(requestContent); } postReq.setEntity(new StringEntity(bulkRequest.toJSONString(),"utf-8")); return postReq; }
java
public <T extends J4pRequest> HttpUriRequest getHttpRequest(List<T> pRequests,Map<J4pQueryParameter,String> pProcessingOptions) throws UnsupportedEncodingException, URISyntaxException { JSONArray bulkRequest = new JSONArray(); String queryParams = prepareQueryParameters(pProcessingOptions); HttpPost postReq = new HttpPost(createRequestURI(j4pServerUrl.getPath(),queryParams)); for (T request : pRequests) { JSONObject requestContent = getJsonRequestContent(request); bulkRequest.add(requestContent); } postReq.setEntity(new StringEntity(bulkRequest.toJSONString(),"utf-8")); return postReq; }
[ "public", "<", "T", "extends", "J4pRequest", ">", "HttpUriRequest", "getHttpRequest", "(", "List", "<", "T", ">", "pRequests", ",", "Map", "<", "J4pQueryParameter", ",", "String", ">", "pProcessingOptions", ")", "throws", "UnsupportedEncodingException", ",", "URISyntaxException", "{", "JSONArray", "bulkRequest", "=", "new", "JSONArray", "(", ")", ";", "String", "queryParams", "=", "prepareQueryParameters", "(", "pProcessingOptions", ")", ";", "HttpPost", "postReq", "=", "new", "HttpPost", "(", "createRequestURI", "(", "j4pServerUrl", ".", "getPath", "(", ")", ",", "queryParams", ")", ")", ";", "for", "(", "T", "request", ":", "pRequests", ")", "{", "JSONObject", "requestContent", "=", "getJsonRequestContent", "(", "request", ")", ";", "bulkRequest", ".", "add", "(", "requestContent", ")", ";", "}", "postReq", ".", "setEntity", "(", "new", "StringEntity", "(", "bulkRequest", ".", "toJSONString", "(", ")", ",", "\"utf-8\"", ")", ")", ";", "return", "postReq", ";", "}" ]
Get an HTTP Request for requesting multiples requests at once @param pRequests requests to put into a HTTP request @return HTTP request to send to the server
[ "Get", "an", "HTTP", "Request", "for", "requesting", "multiples", "requests", "at", "once" ]
train
https://github.com/rhuss/jolokia/blob/dc95e7bef859b1829776c5a84c8f7738f5d7d9c3/client/java/src/main/java/org/jolokia/client/request/J4pRequestHandler.java#L132-L143
weld/core
impl/src/main/java/org/jboss/weld/bean/proxy/ProxyFactory.java
ProxyFactory.setBeanInstance
public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) { """ Convenience method to set the underlying bean instance for a proxy. @param proxy the proxy instance @param beanInstance the instance of the bean """ if (proxy instanceof ProxyObject) { ProxyObject proxyView = (ProxyObject) proxy; proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean)); } }
java
public static <T> void setBeanInstance(String contextId, T proxy, BeanInstance beanInstance, Bean<?> bean) { if (proxy instanceof ProxyObject) { ProxyObject proxyView = (ProxyObject) proxy; proxyView.weld_setHandler(new ProxyMethodHandler(contextId, beanInstance, bean)); } }
[ "public", "static", "<", "T", ">", "void", "setBeanInstance", "(", "String", "contextId", ",", "T", "proxy", ",", "BeanInstance", "beanInstance", ",", "Bean", "<", "?", ">", "bean", ")", "{", "if", "(", "proxy", "instanceof", "ProxyObject", ")", "{", "ProxyObject", "proxyView", "=", "(", "ProxyObject", ")", "proxy", ";", "proxyView", ".", "weld_setHandler", "(", "new", "ProxyMethodHandler", "(", "contextId", ",", "beanInstance", ",", "bean", ")", ")", ";", "}", "}" ]
Convenience method to set the underlying bean instance for a proxy. @param proxy the proxy instance @param beanInstance the instance of the bean
[ "Convenience", "method", "to", "set", "the", "underlying", "bean", "instance", "for", "a", "proxy", "." ]
train
https://github.com/weld/core/blob/567a2eaf95b168597d23a56be89bf05a7834b2aa/impl/src/main/java/org/jboss/weld/bean/proxy/ProxyFactory.java#L400-L405
sarxos/win-registry
src/main/java/com/github/sarxos/winreg/WindowsRegistry.java
WindowsRegistry.deleteKey
public void deleteKey(HKey hk, String key) throws RegistryException { """ Delete given key from registry. @param hk the HKEY @param key the key to be deleted @throws RegistryException when something is not right """ int rc = -1; try { rc = ReflectedMethods.deleteKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot delete key " + key, e); } if (rc != RC.SUCCESS) { throw new RegistryException("Cannot delete key " + key + ". Return code is " + rc); } }
java
public void deleteKey(HKey hk, String key) throws RegistryException { int rc = -1; try { rc = ReflectedMethods.deleteKey(hk.root(), hk.hex(), key); } catch (Exception e) { throw new RegistryException("Cannot delete key " + key, e); } if (rc != RC.SUCCESS) { throw new RegistryException("Cannot delete key " + key + ". Return code is " + rc); } }
[ "public", "void", "deleteKey", "(", "HKey", "hk", ",", "String", "key", ")", "throws", "RegistryException", "{", "int", "rc", "=", "-", "1", ";", "try", "{", "rc", "=", "ReflectedMethods", ".", "deleteKey", "(", "hk", ".", "root", "(", ")", ",", "hk", ".", "hex", "(", ")", ",", "key", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RegistryException", "(", "\"Cannot delete key \"", "+", "key", ",", "e", ")", ";", "}", "if", "(", "rc", "!=", "RC", ".", "SUCCESS", ")", "{", "throw", "new", "RegistryException", "(", "\"Cannot delete key \"", "+", "key", "+", "\". Return code is \"", "+", "rc", ")", ";", "}", "}" ]
Delete given key from registry. @param hk the HKEY @param key the key to be deleted @throws RegistryException when something is not right
[ "Delete", "given", "key", "from", "registry", "." ]
train
https://github.com/sarxos/win-registry/blob/5ccbe2157ae0ee894de7c41bec4bd7b1e0f5c437/src/main/java/com/github/sarxos/winreg/WindowsRegistry.java#L171-L181
Azure/azure-sdk-for-java
compute/resource-manager/v2017_03_30/src/main/java/com/microsoft/azure/management/compute/v2017_03_30/implementation/VirtualMachinesInner.java
VirtualMachinesInner.captureAsync
public Observable<VirtualMachineCaptureResultInner> captureAsync(String resourceGroupName, String vmName, VirtualMachineCaptureParameters parameters) { """ Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create similar VMs. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @param parameters Parameters supplied to the Capture Virtual Machine operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return captureWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<VirtualMachineCaptureResultInner>, VirtualMachineCaptureResultInner>() { @Override public VirtualMachineCaptureResultInner call(ServiceResponse<VirtualMachineCaptureResultInner> response) { return response.body(); } }); }
java
public Observable<VirtualMachineCaptureResultInner> captureAsync(String resourceGroupName, String vmName, VirtualMachineCaptureParameters parameters) { return captureWithServiceResponseAsync(resourceGroupName, vmName, parameters).map(new Func1<ServiceResponse<VirtualMachineCaptureResultInner>, VirtualMachineCaptureResultInner>() { @Override public VirtualMachineCaptureResultInner call(ServiceResponse<VirtualMachineCaptureResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "VirtualMachineCaptureResultInner", ">", "captureAsync", "(", "String", "resourceGroupName", ",", "String", "vmName", ",", "VirtualMachineCaptureParameters", "parameters", ")", "{", "return", "captureWithServiceResponseAsync", "(", "resourceGroupName", ",", "vmName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "VirtualMachineCaptureResultInner", ">", ",", "VirtualMachineCaptureResultInner", ">", "(", ")", "{", "@", "Override", "public", "VirtualMachineCaptureResultInner", "call", "(", "ServiceResponse", "<", "VirtualMachineCaptureResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Captures the VM by copying virtual hard disks of the VM and outputs a template that can be used to create similar VMs. @param resourceGroupName The name of the resource group. @param vmName The name of the virtual machine. @param parameters Parameters supplied to the Capture Virtual Machine operation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Captures", "the", "VM", "by", "copying", "virtual", "hard", "disks", "of", "the", "VM", "and", "outputs", "a", "template", "that", "can", "be", "used", "to", "create", "similar", "VMs", "." ]
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/VirtualMachinesInner.java#L405-L412
spring-projects/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java
MainClassFinder.findSingleMainClass
public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException { """ Find a single main class in a given jar file. @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @return the main class or {@code null} @throws IOException if the jar file cannot be read """ return findSingleMainClass(jarFile, classesLocation, null); }
java
public static String findSingleMainClass(JarFile jarFile, String classesLocation) throws IOException { return findSingleMainClass(jarFile, classesLocation, null); }
[ "public", "static", "String", "findSingleMainClass", "(", "JarFile", "jarFile", ",", "String", "classesLocation", ")", "throws", "IOException", "{", "return", "findSingleMainClass", "(", "jarFile", ",", "classesLocation", ",", "null", ")", ";", "}" ]
Find a single main class in a given jar file. @param jarFile the jar file to search @param classesLocation the location within the jar containing classes @return the main class or {@code null} @throws IOException if the jar file cannot be read
[ "Find", "a", "single", "main", "class", "in", "a", "given", "jar", "file", "." ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/MainClassFinder.java#L185-L188
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.addClosedList
public UUID addClosedList(UUID appId, String versionId, ClosedListModelCreateObject closedListModelCreateObject) { """ Adds a closed list model to the application. @param appId The application ID. @param versionId The version ID. @param closedListModelCreateObject A model containing the name and words for the new closed list entity extractor. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the UUID object if successful. """ return addClosedListWithServiceResponseAsync(appId, versionId, closedListModelCreateObject).toBlocking().single().body(); }
java
public UUID addClosedList(UUID appId, String versionId, ClosedListModelCreateObject closedListModelCreateObject) { return addClosedListWithServiceResponseAsync(appId, versionId, closedListModelCreateObject).toBlocking().single().body(); }
[ "public", "UUID", "addClosedList", "(", "UUID", "appId", ",", "String", "versionId", ",", "ClosedListModelCreateObject", "closedListModelCreateObject", ")", "{", "return", "addClosedListWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "closedListModelCreateObject", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Adds a closed list model to the application. @param appId The application ID. @param versionId The version ID. @param closedListModelCreateObject A model containing the name and words for the new closed list entity extractor. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the UUID object if successful.
[ "Adds", "a", "closed", "list", "model", "to", "the", "application", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L1998-L2000
QSFT/Doradus
doradus-common/src/main/java/com/dell/doradus/common/ObjectResult.java
ObjectResult.newErrorResult
public static ObjectResult newErrorResult(String errMsg, String objID) { """ Create an ObjectResult with a status of ERROR and the given error message and optional object ID. @param errMsg Error message. @param objID Optional object ID. @return {@link ObjectResult} with an error status and message. """ ObjectResult result = new ObjectResult(); result.setStatus(Status.ERROR); result.setErrorMessage(errMsg); if (!Utils.isEmpty(objID)) { result.setObjectID(objID); } return result; }
java
public static ObjectResult newErrorResult(String errMsg, String objID) { ObjectResult result = new ObjectResult(); result.setStatus(Status.ERROR); result.setErrorMessage(errMsg); if (!Utils.isEmpty(objID)) { result.setObjectID(objID); } return result; }
[ "public", "static", "ObjectResult", "newErrorResult", "(", "String", "errMsg", ",", "String", "objID", ")", "{", "ObjectResult", "result", "=", "new", "ObjectResult", "(", ")", ";", "result", ".", "setStatus", "(", "Status", ".", "ERROR", ")", ";", "result", ".", "setErrorMessage", "(", "errMsg", ")", ";", "if", "(", "!", "Utils", ".", "isEmpty", "(", "objID", ")", ")", "{", "result", ".", "setObjectID", "(", "objID", ")", ";", "}", "return", "result", ";", "}" ]
Create an ObjectResult with a status of ERROR and the given error message and optional object ID. @param errMsg Error message. @param objID Optional object ID. @return {@link ObjectResult} with an error status and message.
[ "Create", "an", "ObjectResult", "with", "a", "status", "of", "ERROR", "and", "the", "given", "error", "message", "and", "optional", "object", "ID", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-common/src/main/java/com/dell/doradus/common/ObjectResult.java#L50-L58
spotify/crtauth-java
src/main/java/com/spotify/crtauth/CrtAuthServer.java
CrtAuthServer.createToken
public String createToken(String response) throws IllegalArgumentException, ProtocolVersionException { """ Given the response to a previous challenge, produce a token used by the client to authenticate. @param response The client's response to the initial challenge. @return A token used to authenticate subsequent requests. @throws IllegalArgumentException if there is an encoding error in the response message """ final Response decodedResponse; final Challenge challenge; decodedResponse = CrtAuthCodec.deserializeResponse(decode(response)); challenge = CrtAuthCodec.deserializeChallengeAuthenticated( decodedResponse.getPayload(), secret); if (!challenge.getServerName().equals(serverName)) { throw new IllegalArgumentException("Got challenge with the wrong server_name encoded."); } PublicKey publicKey; try { publicKey = getKeyForUser(challenge.getUserName()); } catch (KeyNotFoundException e) { // If the user requesting authentication doesn't have a public key, we throw an // InvalidInputException. This normally shouldn't happen, since at this stage a challenge // should have already been sent, which in turn requires knowledge of the user's public key. throw new IllegalArgumentException(e); } boolean signatureVerified; try { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicKey); signature.update(decodedResponse.getPayload()); signatureVerified = signature.verify(decodedResponse.getSignature()); } catch (Exception e) { throw new RuntimeException(e); } if (challenge.isExpired(timeSupplier)) { throw new IllegalArgumentException("The challenge is out of its validity period"); } if (!signatureVerified) { throw new IllegalArgumentException("Client did not provide proof that it controls the " + "secret key."); } UnsignedInteger validFrom = timeSupplier.getTime().minus(CLOCK_FUDGE); UnsignedInteger validTo = timeSupplier.getTime().plus(tokenLifetimeSeconds); Token token = new Token(validFrom.intValue(), validTo.intValue(), challenge.getUserName()); return encode(CrtAuthCodec.serialize(token, secret)); }
java
public String createToken(String response) throws IllegalArgumentException, ProtocolVersionException { final Response decodedResponse; final Challenge challenge; decodedResponse = CrtAuthCodec.deserializeResponse(decode(response)); challenge = CrtAuthCodec.deserializeChallengeAuthenticated( decodedResponse.getPayload(), secret); if (!challenge.getServerName().equals(serverName)) { throw new IllegalArgumentException("Got challenge with the wrong server_name encoded."); } PublicKey publicKey; try { publicKey = getKeyForUser(challenge.getUserName()); } catch (KeyNotFoundException e) { // If the user requesting authentication doesn't have a public key, we throw an // InvalidInputException. This normally shouldn't happen, since at this stage a challenge // should have already been sent, which in turn requires knowledge of the user's public key. throw new IllegalArgumentException(e); } boolean signatureVerified; try { Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initVerify(publicKey); signature.update(decodedResponse.getPayload()); signatureVerified = signature.verify(decodedResponse.getSignature()); } catch (Exception e) { throw new RuntimeException(e); } if (challenge.isExpired(timeSupplier)) { throw new IllegalArgumentException("The challenge is out of its validity period"); } if (!signatureVerified) { throw new IllegalArgumentException("Client did not provide proof that it controls the " + "secret key."); } UnsignedInteger validFrom = timeSupplier.getTime().minus(CLOCK_FUDGE); UnsignedInteger validTo = timeSupplier.getTime().plus(tokenLifetimeSeconds); Token token = new Token(validFrom.intValue(), validTo.intValue(), challenge.getUserName()); return encode(CrtAuthCodec.serialize(token, secret)); }
[ "public", "String", "createToken", "(", "String", "response", ")", "throws", "IllegalArgumentException", ",", "ProtocolVersionException", "{", "final", "Response", "decodedResponse", ";", "final", "Challenge", "challenge", ";", "decodedResponse", "=", "CrtAuthCodec", ".", "deserializeResponse", "(", "decode", "(", "response", ")", ")", ";", "challenge", "=", "CrtAuthCodec", ".", "deserializeChallengeAuthenticated", "(", "decodedResponse", ".", "getPayload", "(", ")", ",", "secret", ")", ";", "if", "(", "!", "challenge", ".", "getServerName", "(", ")", ".", "equals", "(", "serverName", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Got challenge with the wrong server_name encoded.\"", ")", ";", "}", "PublicKey", "publicKey", ";", "try", "{", "publicKey", "=", "getKeyForUser", "(", "challenge", ".", "getUserName", "(", ")", ")", ";", "}", "catch", "(", "KeyNotFoundException", "e", ")", "{", "// If the user requesting authentication doesn't have a public key, we throw an", "// InvalidInputException. This normally shouldn't happen, since at this stage a challenge", "// should have already been sent, which in turn requires knowledge of the user's public key.", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "boolean", "signatureVerified", ";", "try", "{", "Signature", "signature", "=", "Signature", ".", "getInstance", "(", "SIGNATURE_ALGORITHM", ")", ";", "signature", ".", "initVerify", "(", "publicKey", ")", ";", "signature", ".", "update", "(", "decodedResponse", ".", "getPayload", "(", ")", ")", ";", "signatureVerified", "=", "signature", ".", "verify", "(", "decodedResponse", ".", "getSignature", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "e", ")", ";", "}", "if", "(", "challenge", ".", "isExpired", "(", "timeSupplier", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The challenge is out of its validity period\"", ")", ";", "}", "if", "(", "!", "signatureVerified", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Client did not provide proof that it controls the \"", "+", "\"secret key.\"", ")", ";", "}", "UnsignedInteger", "validFrom", "=", "timeSupplier", ".", "getTime", "(", ")", ".", "minus", "(", "CLOCK_FUDGE", ")", ";", "UnsignedInteger", "validTo", "=", "timeSupplier", ".", "getTime", "(", ")", ".", "plus", "(", "tokenLifetimeSeconds", ")", ";", "Token", "token", "=", "new", "Token", "(", "validFrom", ".", "intValue", "(", ")", ",", "validTo", ".", "intValue", "(", ")", ",", "challenge", ".", "getUserName", "(", ")", ")", ";", "return", "encode", "(", "CrtAuthCodec", ".", "serialize", "(", "token", ",", "secret", ")", ")", ";", "}" ]
Given the response to a previous challenge, produce a token used by the client to authenticate. @param response The client's response to the initial challenge. @return A token used to authenticate subsequent requests. @throws IllegalArgumentException if there is an encoding error in the response message
[ "Given", "the", "response", "to", "a", "previous", "challenge", "produce", "a", "token", "used", "by", "the", "client", "to", "authenticate", "." ]
train
https://github.com/spotify/crtauth-java/blob/90f3b40323848740c915b195ad1b547fbeb41700/src/main/java/com/spotify/crtauth/CrtAuthServer.java#L262-L302
alkacon/opencms-core
src-gwt/org/opencms/acacia/client/CmsAttributeHandler.java
CmsAttributeHandler.addChoiceOption
private void addChoiceOption(CmsAttributeValueView reference, List<String> choicePath) { """ Adds a new choice option.<p> @param reference the reference view @param choicePath the choice attribute path """ String attributeChoice = choicePath.get(0); CmsType optionType = getAttributeType().getAttributeType(attributeChoice); int valueIndex = reference.getValueIndex() + 1; CmsEntity choiceEntity = m_entityBackEnd.createEntity(null, getAttributeType().getId()); CmsAttributeValueView valueWidget = reference; if (reference.hasValue()) { valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(attributeChoice), m_widgetService.getAttributeHelp(attributeChoice)); if (optionType.isSimpleType() && m_widgetService.isDisplaySingleLine(attributeChoice)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); } } List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), true); for (CmsChoiceMenuEntryBean menuEntry : menuEntries) { valueWidget.addChoice(m_widgetService, menuEntry); } m_entity.insertAttributeValue(m_attributeName, choiceEntity, valueIndex); ((FlowPanel)reference.getParent()).insert(valueWidget, valueIndex); insertHandlers(valueWidget.getValueIndex()); if (optionType.isSimpleType()) { String defaultValue = m_widgetService.getDefaultAttributeValue(attributeChoice, getSimplePath(valueIndex)); I_CmsFormEditWidget widget = m_widgetService.getAttributeFormWidget(attributeChoice); choiceEntity.addAttributeValue(attributeChoice, defaultValue); valueWidget.setValueWidget(widget, defaultValue, defaultValue, true); } else { CmsEntity value = m_entityBackEnd.createEntity(null, optionType.getId()); choiceEntity.addAttributeValue(attributeChoice, value); List<String> remainingAttributeNames = tail(choicePath); createNestedEntitiesForChoicePath(value, remainingAttributeNames); I_CmsEntityRenderer renderer = m_widgetService.getRendererForAttribute(attributeChoice, optionType); valueWidget.setValueEntity(renderer, value); } updateButtonVisisbility(); }
java
private void addChoiceOption(CmsAttributeValueView reference, List<String> choicePath) { String attributeChoice = choicePath.get(0); CmsType optionType = getAttributeType().getAttributeType(attributeChoice); int valueIndex = reference.getValueIndex() + 1; CmsEntity choiceEntity = m_entityBackEnd.createEntity(null, getAttributeType().getId()); CmsAttributeValueView valueWidget = reference; if (reference.hasValue()) { valueWidget = new CmsAttributeValueView( this, m_widgetService.getAttributeLabel(attributeChoice), m_widgetService.getAttributeHelp(attributeChoice)); if (optionType.isSimpleType() && m_widgetService.isDisplaySingleLine(attributeChoice)) { valueWidget.setCompactMode(CmsAttributeValueView.COMPACT_MODE_SINGLE_LINE); } } List<CmsChoiceMenuEntryBean> menuEntries = CmsRenderer.getChoiceEntries(getAttributeType(), true); for (CmsChoiceMenuEntryBean menuEntry : menuEntries) { valueWidget.addChoice(m_widgetService, menuEntry); } m_entity.insertAttributeValue(m_attributeName, choiceEntity, valueIndex); ((FlowPanel)reference.getParent()).insert(valueWidget, valueIndex); insertHandlers(valueWidget.getValueIndex()); if (optionType.isSimpleType()) { String defaultValue = m_widgetService.getDefaultAttributeValue(attributeChoice, getSimplePath(valueIndex)); I_CmsFormEditWidget widget = m_widgetService.getAttributeFormWidget(attributeChoice); choiceEntity.addAttributeValue(attributeChoice, defaultValue); valueWidget.setValueWidget(widget, defaultValue, defaultValue, true); } else { CmsEntity value = m_entityBackEnd.createEntity(null, optionType.getId()); choiceEntity.addAttributeValue(attributeChoice, value); List<String> remainingAttributeNames = tail(choicePath); createNestedEntitiesForChoicePath(value, remainingAttributeNames); I_CmsEntityRenderer renderer = m_widgetService.getRendererForAttribute(attributeChoice, optionType); valueWidget.setValueEntity(renderer, value); } updateButtonVisisbility(); }
[ "private", "void", "addChoiceOption", "(", "CmsAttributeValueView", "reference", ",", "List", "<", "String", ">", "choicePath", ")", "{", "String", "attributeChoice", "=", "choicePath", ".", "get", "(", "0", ")", ";", "CmsType", "optionType", "=", "getAttributeType", "(", ")", ".", "getAttributeType", "(", "attributeChoice", ")", ";", "int", "valueIndex", "=", "reference", ".", "getValueIndex", "(", ")", "+", "1", ";", "CmsEntity", "choiceEntity", "=", "m_entityBackEnd", ".", "createEntity", "(", "null", ",", "getAttributeType", "(", ")", ".", "getId", "(", ")", ")", ";", "CmsAttributeValueView", "valueWidget", "=", "reference", ";", "if", "(", "reference", ".", "hasValue", "(", ")", ")", "{", "valueWidget", "=", "new", "CmsAttributeValueView", "(", "this", ",", "m_widgetService", ".", "getAttributeLabel", "(", "attributeChoice", ")", ",", "m_widgetService", ".", "getAttributeHelp", "(", "attributeChoice", ")", ")", ";", "if", "(", "optionType", ".", "isSimpleType", "(", ")", "&&", "m_widgetService", ".", "isDisplaySingleLine", "(", "attributeChoice", ")", ")", "{", "valueWidget", ".", "setCompactMode", "(", "CmsAttributeValueView", ".", "COMPACT_MODE_SINGLE_LINE", ")", ";", "}", "}", "List", "<", "CmsChoiceMenuEntryBean", ">", "menuEntries", "=", "CmsRenderer", ".", "getChoiceEntries", "(", "getAttributeType", "(", ")", ",", "true", ")", ";", "for", "(", "CmsChoiceMenuEntryBean", "menuEntry", ":", "menuEntries", ")", "{", "valueWidget", ".", "addChoice", "(", "m_widgetService", ",", "menuEntry", ")", ";", "}", "m_entity", ".", "insertAttributeValue", "(", "m_attributeName", ",", "choiceEntity", ",", "valueIndex", ")", ";", "(", "(", "FlowPanel", ")", "reference", ".", "getParent", "(", ")", ")", ".", "insert", "(", "valueWidget", ",", "valueIndex", ")", ";", "insertHandlers", "(", "valueWidget", ".", "getValueIndex", "(", ")", ")", ";", "if", "(", "optionType", ".", "isSimpleType", "(", ")", ")", "{", "String", "defaultValue", "=", "m_widgetService", ".", "getDefaultAttributeValue", "(", "attributeChoice", ",", "getSimplePath", "(", "valueIndex", ")", ")", ";", "I_CmsFormEditWidget", "widget", "=", "m_widgetService", ".", "getAttributeFormWidget", "(", "attributeChoice", ")", ";", "choiceEntity", ".", "addAttributeValue", "(", "attributeChoice", ",", "defaultValue", ")", ";", "valueWidget", ".", "setValueWidget", "(", "widget", ",", "defaultValue", ",", "defaultValue", ",", "true", ")", ";", "}", "else", "{", "CmsEntity", "value", "=", "m_entityBackEnd", ".", "createEntity", "(", "null", ",", "optionType", ".", "getId", "(", ")", ")", ";", "choiceEntity", ".", "addAttributeValue", "(", "attributeChoice", ",", "value", ")", ";", "List", "<", "String", ">", "remainingAttributeNames", "=", "tail", "(", "choicePath", ")", ";", "createNestedEntitiesForChoicePath", "(", "value", ",", "remainingAttributeNames", ")", ";", "I_CmsEntityRenderer", "renderer", "=", "m_widgetService", ".", "getRendererForAttribute", "(", "attributeChoice", ",", "optionType", ")", ";", "valueWidget", ".", "setValueEntity", "(", "renderer", ",", "value", ")", ";", "}", "updateButtonVisisbility", "(", ")", ";", "}" ]
Adds a new choice option.<p> @param reference the reference view @param choicePath the choice attribute path
[ "Adds", "a", "new", "choice", "option", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/acacia/client/CmsAttributeHandler.java#L1128-L1169
cycorp/api-suite
core-api/src/main/java/com/cyc/kb/exception/VariableArityException.java
VariableArityException.fromThrowable
public static VariableArityException fromThrowable(String message, Throwable cause) { """ Converts a Throwable to a VariableArityException with the specified detail message. If the Throwable is a VariableArityException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new VariableArityException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a VariableArityException """ return (cause instanceof VariableArityException && Objects.equals(message, cause.getMessage())) ? (VariableArityException) cause : new VariableArityException(message, cause); }
java
public static VariableArityException fromThrowable(String message, Throwable cause) { return (cause instanceof VariableArityException && Objects.equals(message, cause.getMessage())) ? (VariableArityException) cause : new VariableArityException(message, cause); }
[ "public", "static", "VariableArityException", "fromThrowable", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "return", "(", "cause", "instanceof", "VariableArityException", "&&", "Objects", ".", "equals", "(", "message", ",", "cause", ".", "getMessage", "(", ")", ")", ")", "?", "(", "VariableArityException", ")", "cause", ":", "new", "VariableArityException", "(", "message", ",", "cause", ")", ";", "}" ]
Converts a Throwable to a VariableArityException with the specified detail message. If the Throwable is a VariableArityException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new VariableArityException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a VariableArityException
[ "Converts", "a", "Throwable", "to", "a", "VariableArityException", "with", "the", "specified", "detail", "message", ".", "If", "the", "Throwable", "is", "a", "VariableArityException", "and", "if", "the", "Throwable", "s", "message", "is", "identical", "to", "the", "one", "supplied", "the", "Throwable", "will", "be", "passed", "through", "unmodified", ";", "otherwise", "it", "will", "be", "wrapped", "in", "a", "new", "VariableArityException", "with", "the", "detail", "message", "." ]
train
https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/kb/exception/VariableArityException.java#L50-L54
dkpro/dkpro-jwpl
de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/Wikipedia.java
Wikipedia.getPages
public Set<Page> getPages(String title) throws WikiApiException { """ Get all pages which match all lowercase/uppercase version of the given title.<br> If the title is a redirect, the corresponding page is returned.<br> Spaces in the title are converted to underscores, as this is a convention for Wikipedia article titles. @param title The title of the page. @return A set of page objects matching this title. @throws WikiApiException If no page or redirect with this title exists or the title could not be properly parsed. """ Set<Integer> ids = new HashSet<Integer>(getPageIdsCaseInsensitive(title)); Set<Page> pages = new HashSet<Page>(); for (Integer id : ids) { pages.add(new Page(this, id)); } return pages; }
java
public Set<Page> getPages(String title) throws WikiApiException { Set<Integer> ids = new HashSet<Integer>(getPageIdsCaseInsensitive(title)); Set<Page> pages = new HashSet<Page>(); for (Integer id : ids) { pages.add(new Page(this, id)); } return pages; }
[ "public", "Set", "<", "Page", ">", "getPages", "(", "String", "title", ")", "throws", "WikiApiException", "{", "Set", "<", "Integer", ">", "ids", "=", "new", "HashSet", "<", "Integer", ">", "(", "getPageIdsCaseInsensitive", "(", "title", ")", ")", ";", "Set", "<", "Page", ">", "pages", "=", "new", "HashSet", "<", "Page", ">", "(", ")", ";", "for", "(", "Integer", "id", ":", "ids", ")", "{", "pages", ".", "add", "(", "new", "Page", "(", "this", ",", "id", ")", ")", ";", "}", "return", "pages", ";", "}" ]
Get all pages which match all lowercase/uppercase version of the given title.<br> If the title is a redirect, the corresponding page is returned.<br> Spaces in the title are converted to underscores, as this is a convention for Wikipedia article titles. @param title The title of the page. @return A set of page objects matching this title. @throws WikiApiException If no page or redirect with this title exists or the title could not be properly parsed.
[ "Get", "all", "pages", "which", "match", "all", "lowercase", "/", "uppercase", "version", "of", "the", "given", "title", ".", "<br", ">", "If", "the", "title", "is", "a", "redirect", "the", "corresponding", "page", "is", "returned", ".", "<br", ">", "Spaces", "in", "the", "title", "are", "converted", "to", "underscores", "as", "this", "is", "a", "convention", "for", "Wikipedia", "article", "titles", "." ]
train
https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.api/src/main/java/de/tudarmstadt/ukp/wikipedia/api/Wikipedia.java#L146-L154
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/CompressionUtil.java
CompressionUtil.decompress
public static File decompress(CompressionMethod _method, String _compressedFile, String _outputFileName) { """ Extract a file using the given {@link CompressionMethod}. @param _method @param _compressedFile @param _outputFileName @return file object which represents the uncompressed file or null on error """ if (_method == null || _compressedFile == null) { return null; } File inputFile = new File(_compressedFile); if (!inputFile.exists()) { return null; } try { Constructor<? extends InputStream> constructor = _method.getInputStreamClass().getConstructor(InputStream.class); if (constructor != null) { InputStream inputStream = constructor.newInstance(new FileInputStream(inputFile)); // write decompressed stream to new file Path destPath = Paths.get(_outputFileName); Files.copy(inputStream, destPath, StandardCopyOption.REPLACE_EXISTING); return destPath.toFile(); } } catch (IOException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException iOException) { LOGGER.error("Cannot uncompress file: ", iOException); } return null; }
java
public static File decompress(CompressionMethod _method, String _compressedFile, String _outputFileName) { if (_method == null || _compressedFile == null) { return null; } File inputFile = new File(_compressedFile); if (!inputFile.exists()) { return null; } try { Constructor<? extends InputStream> constructor = _method.getInputStreamClass().getConstructor(InputStream.class); if (constructor != null) { InputStream inputStream = constructor.newInstance(new FileInputStream(inputFile)); // write decompressed stream to new file Path destPath = Paths.get(_outputFileName); Files.copy(inputStream, destPath, StandardCopyOption.REPLACE_EXISTING); return destPath.toFile(); } } catch (IOException | NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException iOException) { LOGGER.error("Cannot uncompress file: ", iOException); } return null; }
[ "public", "static", "File", "decompress", "(", "CompressionMethod", "_method", ",", "String", "_compressedFile", ",", "String", "_outputFileName", ")", "{", "if", "(", "_method", "==", "null", "||", "_compressedFile", "==", "null", ")", "{", "return", "null", ";", "}", "File", "inputFile", "=", "new", "File", "(", "_compressedFile", ")", ";", "if", "(", "!", "inputFile", ".", "exists", "(", ")", ")", "{", "return", "null", ";", "}", "try", "{", "Constructor", "<", "?", "extends", "InputStream", ">", "constructor", "=", "_method", ".", "getInputStreamClass", "(", ")", ".", "getConstructor", "(", "InputStream", ".", "class", ")", ";", "if", "(", "constructor", "!=", "null", ")", "{", "InputStream", "inputStream", "=", "constructor", ".", "newInstance", "(", "new", "FileInputStream", "(", "inputFile", ")", ")", ";", "// write decompressed stream to new file", "Path", "destPath", "=", "Paths", ".", "get", "(", "_outputFileName", ")", ";", "Files", ".", "copy", "(", "inputStream", ",", "destPath", ",", "StandardCopyOption", ".", "REPLACE_EXISTING", ")", ";", "return", "destPath", ".", "toFile", "(", ")", ";", "}", "}", "catch", "(", "IOException", "|", "NoSuchMethodException", "|", "SecurityException", "|", "InstantiationException", "|", "IllegalAccessException", "|", "IllegalArgumentException", "|", "InvocationTargetException", "iOException", ")", "{", "LOGGER", ".", "error", "(", "\"Cannot uncompress file: \"", ",", "iOException", ")", ";", "}", "return", "null", ";", "}" ]
Extract a file using the given {@link CompressionMethod}. @param _method @param _compressedFile @param _outputFileName @return file object which represents the uncompressed file or null on error
[ "Extract", "a", "file", "using", "the", "given", "{" ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/CompressionUtil.java#L63-L90
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java
ContextedRuntimeException.addContextValue
@Override public ContextedRuntimeException addContextValue(final String label, final Object value) { """ Adds information helpful to a developer in diagnosing and correcting the problem. For the information to be meaningful, the value passed should have a reasonable toString() implementation. Different values can be added with the same label multiple times. <p> Note: This exception is only serializable if the object added is serializable. </p> @param label a textual label associated with information, {@code null} not recommended @param value information needed to understand exception, may be {@code null} @return {@code this}, for method chaining, not {@code null} """ exceptionContext.addContextValue(label, value); return this; }
java
@Override public ContextedRuntimeException addContextValue(final String label, final Object value) { exceptionContext.addContextValue(label, value); return this; }
[ "@", "Override", "public", "ContextedRuntimeException", "addContextValue", "(", "final", "String", "label", ",", "final", "Object", "value", ")", "{", "exceptionContext", ".", "addContextValue", "(", "label", ",", "value", ")", ";", "return", "this", ";", "}" ]
Adds information helpful to a developer in diagnosing and correcting the problem. For the information to be meaningful, the value passed should have a reasonable toString() implementation. Different values can be added with the same label multiple times. <p> Note: This exception is only serializable if the object added is serializable. </p> @param label a textual label associated with information, {@code null} not recommended @param value information needed to understand exception, may be {@code null} @return {@code this}, for method chaining, not {@code null}
[ "Adds", "information", "helpful", "to", "a", "developer", "in", "diagnosing", "and", "correcting", "the", "problem", ".", "For", "the", "information", "to", "be", "meaningful", "the", "value", "passed", "should", "have", "a", "reasonable", "toString", "()", "implementation", ".", "Different", "values", "can", "be", "added", "with", "the", "same", "label", "multiple", "times", ".", "<p", ">", "Note", ":", "This", "exception", "is", "only", "serializable", "if", "the", "object", "added", "is", "serializable", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/exception/ContextedRuntimeException.java#L172-L176
cdk/cdk
storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java
CxSmilesParser.processIntList
private static boolean processIntList(CharIter iter, char sep, List<Integer> dest) { """ Process a list of unsigned integers. @param iter char iter @param sep the separator @param dest output @return int-list was successfully processed """ while (iter.hasNext()) { char c = iter.curr(); if (isDigit(c)) { int r = processUnsignedInt(iter); if (r < 0) return false; iter.nextIf(sep); dest.add(r); } else { return true; } } // ran off end return false; }
java
private static boolean processIntList(CharIter iter, char sep, List<Integer> dest) { while (iter.hasNext()) { char c = iter.curr(); if (isDigit(c)) { int r = processUnsignedInt(iter); if (r < 0) return false; iter.nextIf(sep); dest.add(r); } else { return true; } } // ran off end return false; }
[ "private", "static", "boolean", "processIntList", "(", "CharIter", "iter", ",", "char", "sep", ",", "List", "<", "Integer", ">", "dest", ")", "{", "while", "(", "iter", ".", "hasNext", "(", ")", ")", "{", "char", "c", "=", "iter", ".", "curr", "(", ")", ";", "if", "(", "isDigit", "(", "c", ")", ")", "{", "int", "r", "=", "processUnsignedInt", "(", "iter", ")", ";", "if", "(", "r", "<", "0", ")", "return", "false", ";", "iter", ".", "nextIf", "(", "sep", ")", ";", "dest", ".", "add", "(", "r", ")", ";", "}", "else", "{", "return", "true", ";", "}", "}", "// ran off end", "return", "false", ";", "}" ]
Process a list of unsigned integers. @param iter char iter @param sep the separator @param dest output @return int-list was successfully processed
[ "Process", "a", "list", "of", "unsigned", "integers", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/storage/smiles/src/main/java/org/openscience/cdk/smiles/CxSmilesParser.java#L567-L581
micronaut-projects/micronaut-core
tracing/src/main/java/io/micronaut/tracing/instrument/http/AbstractOpenTracingFilter.java
AbstractOpenTracingFilter.newSpan
protected Tracer.SpanBuilder newSpan(HttpRequest<?> request, SpanContext spanContext) { """ Creates a new span for the given request and span context. @param request The request @param spanContext The span context @return The span builder """ String spanName = resolveSpanName(request); Tracer.SpanBuilder spanBuilder = tracer.buildSpan( spanName ).asChildOf(spanContext); spanBuilder.withTag(TAG_METHOD, request.getMethod().name()); String path = request.getPath(); spanBuilder.withTag(TAG_PATH, path); return spanBuilder; }
java
protected Tracer.SpanBuilder newSpan(HttpRequest<?> request, SpanContext spanContext) { String spanName = resolveSpanName(request); Tracer.SpanBuilder spanBuilder = tracer.buildSpan( spanName ).asChildOf(spanContext); spanBuilder.withTag(TAG_METHOD, request.getMethod().name()); String path = request.getPath(); spanBuilder.withTag(TAG_PATH, path); return spanBuilder; }
[ "protected", "Tracer", ".", "SpanBuilder", "newSpan", "(", "HttpRequest", "<", "?", ">", "request", ",", "SpanContext", "spanContext", ")", "{", "String", "spanName", "=", "resolveSpanName", "(", "request", ")", ";", "Tracer", ".", "SpanBuilder", "spanBuilder", "=", "tracer", ".", "buildSpan", "(", "spanName", ")", ".", "asChildOf", "(", "spanContext", ")", ";", "spanBuilder", ".", "withTag", "(", "TAG_METHOD", ",", "request", ".", "getMethod", "(", ")", ".", "name", "(", ")", ")", ";", "String", "path", "=", "request", ".", "getPath", "(", ")", ";", "spanBuilder", ".", "withTag", "(", "TAG_PATH", ",", "path", ")", ";", "return", "spanBuilder", ";", "}" ]
Creates a new span for the given request and span context. @param request The request @param spanContext The span context @return The span builder
[ "Creates", "a", "new", "span", "for", "the", "given", "request", "and", "span", "context", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/tracing/src/main/java/io/micronaut/tracing/instrument/http/AbstractOpenTracingFilter.java#L108-L118
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.flatMapping
@NotNull public static <T, U, A, R> Collector<T, ?, R> flatMapping( @NotNull final Function<? super T, ? extends Stream<? extends U>> mapper, @NotNull final Collector<? super U, A, R> downstream) { """ Returns a {@code Collector} that performs flat-mapping before accumulation. @param <T> the type of the input elements @param <U> the result type of flat-mapping function @param <A> the accumulation type @param <R> the result type of collector @param mapper a function that performs flat-mapping to input elements @param downstream the collector of flat-mapped elements @return a {@code Collector} @since 1.1.3 """ final BiConsumer<A, ? super U> accumulator = downstream.accumulator(); return new CollectorsImpl<T, A, R>( downstream.supplier(), new BiConsumer<A, T>() { @Override public void accept(final A a, T t) { final Stream<? extends U> stream = mapper.apply(t); if (stream == null) return; stream.forEach(new Consumer<U>() { @Override public void accept(U u) { accumulator.accept(a, u); } }); } }, downstream.finisher() ); }
java
@NotNull public static <T, U, A, R> Collector<T, ?, R> flatMapping( @NotNull final Function<? super T, ? extends Stream<? extends U>> mapper, @NotNull final Collector<? super U, A, R> downstream) { final BiConsumer<A, ? super U> accumulator = downstream.accumulator(); return new CollectorsImpl<T, A, R>( downstream.supplier(), new BiConsumer<A, T>() { @Override public void accept(final A a, T t) { final Stream<? extends U> stream = mapper.apply(t); if (stream == null) return; stream.forEach(new Consumer<U>() { @Override public void accept(U u) { accumulator.accept(a, u); } }); } }, downstream.finisher() ); }
[ "@", "NotNull", "public", "static", "<", "T", ",", "U", ",", "A", ",", "R", ">", "Collector", "<", "T", ",", "?", ",", "R", ">", "flatMapping", "(", "@", "NotNull", "final", "Function", "<", "?", "super", "T", ",", "?", "extends", "Stream", "<", "?", "extends", "U", ">", ">", "mapper", ",", "@", "NotNull", "final", "Collector", "<", "?", "super", "U", ",", "A", ",", "R", ">", "downstream", ")", "{", "final", "BiConsumer", "<", "A", ",", "?", "super", "U", ">", "accumulator", "=", "downstream", ".", "accumulator", "(", ")", ";", "return", "new", "CollectorsImpl", "<", "T", ",", "A", ",", "R", ">", "(", "downstream", ".", "supplier", "(", ")", ",", "new", "BiConsumer", "<", "A", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "final", "A", "a", ",", "T", "t", ")", "{", "final", "Stream", "<", "?", "extends", "U", ">", "stream", "=", "mapper", ".", "apply", "(", "t", ")", ";", "if", "(", "stream", "==", "null", ")", "return", ";", "stream", ".", "forEach", "(", "new", "Consumer", "<", "U", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "U", "u", ")", "{", "accumulator", ".", "accept", "(", "a", ",", "u", ")", ";", "}", "}", ")", ";", "}", "}", ",", "downstream", ".", "finisher", "(", ")", ")", ";", "}" ]
Returns a {@code Collector} that performs flat-mapping before accumulation. @param <T> the type of the input elements @param <U> the result type of flat-mapping function @param <A> the accumulation type @param <R> the result type of collector @param mapper a function that performs flat-mapping to input elements @param downstream the collector of flat-mapped elements @return a {@code Collector} @since 1.1.3
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "performs", "flat", "-", "mapping", "before", "accumulation", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L838-L864
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java
Execution.triggerSynchronousSavepoint
public void triggerSynchronousSavepoint(long checkpointId, long timestamp, CheckpointOptions checkpointOptions, boolean advanceToEndOfEventTime) { """ Trigger a new checkpoint on the task of this execution. @param checkpointId of th checkpoint to trigger @param timestamp of the checkpoint to trigger @param checkpointOptions of the checkpoint to trigger @param advanceToEndOfEventTime Flag indicating if the source should inject a {@code MAX_WATERMARK} in the pipeline to fire any registered event-time timers """ triggerCheckpointHelper(checkpointId, timestamp, checkpointOptions, advanceToEndOfEventTime); }
java
public void triggerSynchronousSavepoint(long checkpointId, long timestamp, CheckpointOptions checkpointOptions, boolean advanceToEndOfEventTime) { triggerCheckpointHelper(checkpointId, timestamp, checkpointOptions, advanceToEndOfEventTime); }
[ "public", "void", "triggerSynchronousSavepoint", "(", "long", "checkpointId", ",", "long", "timestamp", ",", "CheckpointOptions", "checkpointOptions", ",", "boolean", "advanceToEndOfEventTime", ")", "{", "triggerCheckpointHelper", "(", "checkpointId", ",", "timestamp", ",", "checkpointOptions", ",", "advanceToEndOfEventTime", ")", ";", "}" ]
Trigger a new checkpoint on the task of this execution. @param checkpointId of th checkpoint to trigger @param timestamp of the checkpoint to trigger @param checkpointOptions of the checkpoint to trigger @param advanceToEndOfEventTime Flag indicating if the source should inject a {@code MAX_WATERMARK} in the pipeline to fire any registered event-time timers
[ "Trigger", "a", "new", "checkpoint", "on", "the", "task", "of", "this", "execution", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java#L881-L883
UrielCh/ovh-java-sdk
ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java
ApiOvhCdndedicated.serviceName_domains_domain_statistics_GET
public ArrayList<OvhStatsDataType> serviceName_domains_domain_statistics_GET(String serviceName, String domain, OvhStatsPeriodEnum period, OvhStatsTypeEnum type, OvhStatsValueEnum value) throws IOException { """ Return stats about a domain REST: GET /cdn/dedicated/{serviceName}/domains/{domain}/statistics @param period [required] @param type [required] @param value [required] @param serviceName [required] The internal name of your CDN offer @param domain [required] Domain of this object """ String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/statistics"; StringBuilder sb = path(qPath, serviceName, domain); query(sb, "period", period); query(sb, "type", type); query(sb, "value", value); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
java
public ArrayList<OvhStatsDataType> serviceName_domains_domain_statistics_GET(String serviceName, String domain, OvhStatsPeriodEnum period, OvhStatsTypeEnum type, OvhStatsValueEnum value) throws IOException { String qPath = "/cdn/dedicated/{serviceName}/domains/{domain}/statistics"; StringBuilder sb = path(qPath, serviceName, domain); query(sb, "period", period); query(sb, "type", type); query(sb, "value", value); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t3); }
[ "public", "ArrayList", "<", "OvhStatsDataType", ">", "serviceName_domains_domain_statistics_GET", "(", "String", "serviceName", ",", "String", "domain", ",", "OvhStatsPeriodEnum", "period", ",", "OvhStatsTypeEnum", "type", ",", "OvhStatsValueEnum", "value", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cdn/dedicated/{serviceName}/domains/{domain}/statistics\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "domain", ")", ";", "query", "(", "sb", ",", "\"period\"", ",", "period", ")", ";", "query", "(", "sb", ",", "\"type\"", ",", "type", ")", ";", "query", "(", "sb", ",", "\"value\"", ",", "value", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t3", ")", ";", "}" ]
Return stats about a domain REST: GET /cdn/dedicated/{serviceName}/domains/{domain}/statistics @param period [required] @param type [required] @param value [required] @param serviceName [required] The internal name of your CDN offer @param domain [required] Domain of this object
[ "Return", "stats", "about", "a", "domain" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cdndedicated/src/main/java/net/minidev/ovh/api/ApiOvhCdndedicated.java#L336-L344
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/DateTimeField.java
DateTimeField.setTime
public int setTime(java.util.Date time, boolean bDisplayOption, int iMoveMode) { """ Change the time without changing the date. @param time The date to set (only time portion is used). @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN). """ java.util.Date m_DateTime = (java.util.Date)m_data; int iYear = DBConstants.FIRST_YEAR; int iMonth = DBConstants.FIRST_DAY; int iDate = DBConstants.FIRST_MONTH; if (m_DateTime != null) //|| (m_CurrentLength == 0)) { m_calendar.setTime(m_DateTime); iYear = m_calendar.get(Calendar.YEAR); iMonth = m_calendar.get(Calendar.MONTH); iDate = m_calendar.get(Calendar.DATE); } m_calendar.setTime(time); int iHour = m_calendar.get(Calendar.HOUR_OF_DAY); int iMinute = m_calendar.get(Calendar.MINUTE); int iSecond = m_calendar.get(Calendar.SECOND); m_calendar.set(iYear, iMonth, iDate, iHour, iMinute, iSecond); java.util.Date dateNew = m_calendar.getTime(); return this.setDateTime(dateNew, bDisplayOption, iMoveMode); }
java
public int setTime(java.util.Date time, boolean bDisplayOption, int iMoveMode) { java.util.Date m_DateTime = (java.util.Date)m_data; int iYear = DBConstants.FIRST_YEAR; int iMonth = DBConstants.FIRST_DAY; int iDate = DBConstants.FIRST_MONTH; if (m_DateTime != null) //|| (m_CurrentLength == 0)) { m_calendar.setTime(m_DateTime); iYear = m_calendar.get(Calendar.YEAR); iMonth = m_calendar.get(Calendar.MONTH); iDate = m_calendar.get(Calendar.DATE); } m_calendar.setTime(time); int iHour = m_calendar.get(Calendar.HOUR_OF_DAY); int iMinute = m_calendar.get(Calendar.MINUTE); int iSecond = m_calendar.get(Calendar.SECOND); m_calendar.set(iYear, iMonth, iDate, iHour, iMinute, iSecond); java.util.Date dateNew = m_calendar.getTime(); return this.setDateTime(dateNew, bDisplayOption, iMoveMode); }
[ "public", "int", "setTime", "(", "java", ".", "util", ".", "Date", "time", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "java", ".", "util", ".", "Date", "m_DateTime", "=", "(", "java", ".", "util", ".", "Date", ")", "m_data", ";", "int", "iYear", "=", "DBConstants", ".", "FIRST_YEAR", ";", "int", "iMonth", "=", "DBConstants", ".", "FIRST_DAY", ";", "int", "iDate", "=", "DBConstants", ".", "FIRST_MONTH", ";", "if", "(", "m_DateTime", "!=", "null", ")", "//|| (m_CurrentLength == 0))", "{", "m_calendar", ".", "setTime", "(", "m_DateTime", ")", ";", "iYear", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "YEAR", ")", ";", "iMonth", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "MONTH", ")", ";", "iDate", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "DATE", ")", ";", "}", "m_calendar", ".", "setTime", "(", "time", ")", ";", "int", "iHour", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "HOUR_OF_DAY", ")", ";", "int", "iMinute", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "MINUTE", ")", ";", "int", "iSecond", "=", "m_calendar", ".", "get", "(", "Calendar", ".", "SECOND", ")", ";", "m_calendar", ".", "set", "(", "iYear", ",", "iMonth", ",", "iDate", ",", "iHour", ",", "iMinute", ",", "iSecond", ")", ";", "java", ".", "util", ".", "Date", "dateNew", "=", "m_calendar", ".", "getTime", "(", ")", ";", "return", "this", ".", "setDateTime", "(", "dateNew", ",", "bDisplayOption", ",", "iMoveMode", ")", ";", "}" ]
Change the time without changing the date. @param time The date to set (only time portion is used). @param bDisplayOption Display changed fields if true. @param iMoveMode The move mode. @return The error code (or NORMAL_RETURN).
[ "Change", "the", "time", "without", "changing", "the", "date", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/DateTimeField.java#L331-L351
oehf/ipf-oht-atna
auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java
GenericIHEAuditEventMessage.addDocumentParticipantObject
public void addDocumentParticipantObject(String documentUniqueId, String repositoryUniqueId, String homeCommunityId) { """ Adds a Participant Object representing a document for XDS Exports @param documentUniqueId The Document Entry Unique Id @param repositoryUniqueId The Repository Unique Id of the Repository housing the document @param homeCommunityId The Home Community Id """ List<TypeValuePairType> tvp = new LinkedList<>(); //SEK - 10/19/2011 - added check for empty or null, RE: Issue Tracker artifact artf2295 (was Issue 135) if (!EventUtils.isEmptyOrNull(repositoryUniqueId)) { tvp.add(getTypeValuePair("Repository Unique Id", repositoryUniqueId.getBytes())); } if (!EventUtils.isEmptyOrNull(homeCommunityId)) { tvp.add(getTypeValuePair("ihe:homeCommunityID", homeCommunityId.getBytes())); } addParticipantObjectIdentification( new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.ReportNumber(), null, null, tvp, documentUniqueId, RFC3881ParticipantObjectTypeCodes.SYSTEM, RFC3881ParticipantObjectTypeRoleCodes.REPORT, null, null); }
java
public void addDocumentParticipantObject(String documentUniqueId, String repositoryUniqueId, String homeCommunityId) { List<TypeValuePairType> tvp = new LinkedList<>(); //SEK - 10/19/2011 - added check for empty or null, RE: Issue Tracker artifact artf2295 (was Issue 135) if (!EventUtils.isEmptyOrNull(repositoryUniqueId)) { tvp.add(getTypeValuePair("Repository Unique Id", repositoryUniqueId.getBytes())); } if (!EventUtils.isEmptyOrNull(homeCommunityId)) { tvp.add(getTypeValuePair("ihe:homeCommunityID", homeCommunityId.getBytes())); } addParticipantObjectIdentification( new RFC3881ParticipantObjectCodes.RFC3881ParticipantObjectIDTypeCodes.ReportNumber(), null, null, tvp, documentUniqueId, RFC3881ParticipantObjectTypeCodes.SYSTEM, RFC3881ParticipantObjectTypeRoleCodes.REPORT, null, null); }
[ "public", "void", "addDocumentParticipantObject", "(", "String", "documentUniqueId", ",", "String", "repositoryUniqueId", ",", "String", "homeCommunityId", ")", "{", "List", "<", "TypeValuePairType", ">", "tvp", "=", "new", "LinkedList", "<>", "(", ")", ";", "//SEK - 10/19/2011 - added check for empty or null, RE: Issue Tracker artifact artf2295 (was Issue 135)", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "repositoryUniqueId", ")", ")", "{", "tvp", ".", "add", "(", "getTypeValuePair", "(", "\"Repository Unique Id\"", ",", "repositoryUniqueId", ".", "getBytes", "(", ")", ")", ")", ";", "}", "if", "(", "!", "EventUtils", ".", "isEmptyOrNull", "(", "homeCommunityId", ")", ")", "{", "tvp", ".", "add", "(", "getTypeValuePair", "(", "\"ihe:homeCommunityID\"", ",", "homeCommunityId", ".", "getBytes", "(", ")", ")", ")", ";", "}", "addParticipantObjectIdentification", "(", "new", "RFC3881ParticipantObjectCodes", ".", "RFC3881ParticipantObjectIDTypeCodes", ".", "ReportNumber", "(", ")", ",", "null", ",", "null", ",", "tvp", ",", "documentUniqueId", ",", "RFC3881ParticipantObjectTypeCodes", ".", "SYSTEM", ",", "RFC3881ParticipantObjectTypeRoleCodes", ".", "REPORT", ",", "null", ",", "null", ")", ";", "}" ]
Adds a Participant Object representing a document for XDS Exports @param documentUniqueId The Document Entry Unique Id @param repositoryUniqueId The Repository Unique Id of the Repository housing the document @param homeCommunityId The Home Community Id
[ "Adds", "a", "Participant", "Object", "representing", "a", "document", "for", "XDS", "Exports" ]
train
https://github.com/oehf/ipf-oht-atna/blob/25ed1e926825169c94923a2c89a4618f60478ae8/auditor/src/main/java/org/openhealthtools/ihe/atna/auditor/events/ihe/GenericIHEAuditEventMessage.java#L233-L254
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.asType
@SuppressWarnings("unchecked") public static <T> T asType(Object[] ary, Class<T> clazz) { """ Converts the given array to either a List, Set, or SortedSet. If the given class is something else, the call is deferred to {@link #asType(Object,Class)}. @param ary an array @param clazz the desired class @return the object resulting from this type conversion @see #asType(java.lang.Object, java.lang.Class) @since 1.5.1 """ if (clazz == List.class) { return (T) new ArrayList(Arrays.asList(ary)); } if (clazz == Set.class) { return (T) new HashSet(Arrays.asList(ary)); } if (clazz == SortedSet.class) { return (T) new TreeSet(Arrays.asList(ary)); } return asType((Object) ary, clazz); }
java
@SuppressWarnings("unchecked") public static <T> T asType(Object[] ary, Class<T> clazz) { if (clazz == List.class) { return (T) new ArrayList(Arrays.asList(ary)); } if (clazz == Set.class) { return (T) new HashSet(Arrays.asList(ary)); } if (clazz == SortedSet.class) { return (T) new TreeSet(Arrays.asList(ary)); } return asType((Object) ary, clazz); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "asType", "(", "Object", "[", "]", "ary", ",", "Class", "<", "T", ">", "clazz", ")", "{", "if", "(", "clazz", "==", "List", ".", "class", ")", "{", "return", "(", "T", ")", "new", "ArrayList", "(", "Arrays", ".", "asList", "(", "ary", ")", ")", ";", "}", "if", "(", "clazz", "==", "Set", ".", "class", ")", "{", "return", "(", "T", ")", "new", "HashSet", "(", "Arrays", ".", "asList", "(", "ary", ")", ")", ";", "}", "if", "(", "clazz", "==", "SortedSet", ".", "class", ")", "{", "return", "(", "T", ")", "new", "TreeSet", "(", "Arrays", ".", "asList", "(", "ary", ")", ")", ";", "}", "return", "asType", "(", "(", "Object", ")", "ary", ",", "clazz", ")", ";", "}" ]
Converts the given array to either a List, Set, or SortedSet. If the given class is something else, the call is deferred to {@link #asType(Object,Class)}. @param ary an array @param clazz the desired class @return the object resulting from this type conversion @see #asType(java.lang.Object, java.lang.Class) @since 1.5.1
[ "Converts", "the", "given", "array", "to", "either", "a", "List", "Set", "or", "SortedSet", ".", "If", "the", "given", "class", "is", "something", "else", "the", "call", "is", "deferred", "to", "{", "@link", "#asType", "(", "Object", "Class", ")", "}", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L11747-L11760
cycorp/api-suite
core-api/src/main/java/com/cyc/session/exception/SessionInitializationException.java
SessionInitializationException.fromThrowable
public static SessionInitializationException fromThrowable(String message, Throwable cause) { """ Converts a Throwable to a SessionInitializationException with the specified detail message. If the Throwable is a SessionInitializationException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new SessionInitializationException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a SessionInitializationException """ return (cause instanceof SessionInitializationException && Objects.equals(message, cause.getMessage())) ? (SessionInitializationException) cause : new SessionInitializationException(message, cause); }
java
public static SessionInitializationException fromThrowable(String message, Throwable cause) { return (cause instanceof SessionInitializationException && Objects.equals(message, cause.getMessage())) ? (SessionInitializationException) cause : new SessionInitializationException(message, cause); }
[ "public", "static", "SessionInitializationException", "fromThrowable", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "return", "(", "cause", "instanceof", "SessionInitializationException", "&&", "Objects", ".", "equals", "(", "message", ",", "cause", ".", "getMessage", "(", ")", ")", ")", "?", "(", "SessionInitializationException", ")", "cause", ":", "new", "SessionInitializationException", "(", "message", ",", "cause", ")", ";", "}" ]
Converts a Throwable to a SessionInitializationException with the specified detail message. If the Throwable is a SessionInitializationException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new SessionInitializationException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a SessionInitializationException
[ "Converts", "a", "Throwable", "to", "a", "SessionInitializationException", "with", "the", "specified", "detail", "message", ".", "If", "the", "Throwable", "is", "a", "SessionInitializationException", "and", "if", "the", "Throwable", "s", "message", "is", "identical", "to", "the", "one", "supplied", "the", "Throwable", "will", "be", "passed", "through", "unmodified", ";", "otherwise", "it", "will", "be", "wrapped", "in", "a", "new", "SessionInitializationException", "with", "the", "detail", "message", "." ]
train
https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/session/exception/SessionInitializationException.java#L62-L66
comapi/comapi-sdk-android
COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java
InternalService.getConversations
@Deprecated public void getConversations(@NonNull final Scope scope, @Nullable Callback<ComapiResult<List<ConversationDetails>>> callback) { """ Returns observable to get all visible conversations. @param scope {@link Scope} of the query @param callback Callback to deliver new session instance. @deprecated Please use {@link InternalService#getConversations(boolean, Callback)} instead. """ adapter.adapt(getConversations(scope), callback); }
java
@Deprecated public void getConversations(@NonNull final Scope scope, @Nullable Callback<ComapiResult<List<ConversationDetails>>> callback) { adapter.adapt(getConversations(scope), callback); }
[ "@", "Deprecated", "public", "void", "getConversations", "(", "@", "NonNull", "final", "Scope", "scope", ",", "@", "Nullable", "Callback", "<", "ComapiResult", "<", "List", "<", "ConversationDetails", ">", ">", ">", "callback", ")", "{", "adapter", ".", "adapt", "(", "getConversations", "(", "scope", ")", ",", "callback", ")", ";", "}" ]
Returns observable to get all visible conversations. @param scope {@link Scope} of the query @param callback Callback to deliver new session instance. @deprecated Please use {@link InternalService#getConversations(boolean, Callback)} instead.
[ "Returns", "observable", "to", "get", "all", "visible", "conversations", "." ]
train
https://github.com/comapi/comapi-sdk-android/blob/53140a58d5a62afe196047ccc5120bfe090ef211/COMAPI/foundation/src/main/java/com/comapi/internal/network/InternalService.java#L561-L564
jlinn/quartz-redis-jobstore
src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java
RedisJobStore.doWithLock
private <T> T doWithLock(LockCallback<T> callback, String errorMessage) throws JobPersistenceException { """ Perform a redis operation while lock is acquired @param callback a callback containing the actions to perform during lock @param errorMessage optional error message to include in exception should an error arise @param <T> return class @return the result of the actions performed while locked, if any @throws JobPersistenceException """ JedisCommands jedis = null; try { jedis = getResource(); try { storage.waitForLock(jedis); return callback.doWithLock(jedis); } catch (ObjectAlreadyExistsException e) { throw e; } catch (Exception e) { if (errorMessage == null || errorMessage.isEmpty()) { errorMessage = "Job storage error."; } throw new JobPersistenceException(errorMessage, e); } finally { storage.unlock(jedis); } } finally { if (jedis != null && jedis instanceof Jedis) { // only close if we're not using a JedisCluster instance ((Jedis) jedis).close(); } } }
java
private <T> T doWithLock(LockCallback<T> callback, String errorMessage) throws JobPersistenceException { JedisCommands jedis = null; try { jedis = getResource(); try { storage.waitForLock(jedis); return callback.doWithLock(jedis); } catch (ObjectAlreadyExistsException e) { throw e; } catch (Exception e) { if (errorMessage == null || errorMessage.isEmpty()) { errorMessage = "Job storage error."; } throw new JobPersistenceException(errorMessage, e); } finally { storage.unlock(jedis); } } finally { if (jedis != null && jedis instanceof Jedis) { // only close if we're not using a JedisCluster instance ((Jedis) jedis).close(); } } }
[ "private", "<", "T", ">", "T", "doWithLock", "(", "LockCallback", "<", "T", ">", "callback", ",", "String", "errorMessage", ")", "throws", "JobPersistenceException", "{", "JedisCommands", "jedis", "=", "null", ";", "try", "{", "jedis", "=", "getResource", "(", ")", ";", "try", "{", "storage", ".", "waitForLock", "(", "jedis", ")", ";", "return", "callback", ".", "doWithLock", "(", "jedis", ")", ";", "}", "catch", "(", "ObjectAlreadyExistsException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "if", "(", "errorMessage", "==", "null", "||", "errorMessage", ".", "isEmpty", "(", ")", ")", "{", "errorMessage", "=", "\"Job storage error.\"", ";", "}", "throw", "new", "JobPersistenceException", "(", "errorMessage", ",", "e", ")", ";", "}", "finally", "{", "storage", ".", "unlock", "(", "jedis", ")", ";", "}", "}", "finally", "{", "if", "(", "jedis", "!=", "null", "&&", "jedis", "instanceof", "Jedis", ")", "{", "// only close if we're not using a JedisCluster instance", "(", "(", "Jedis", ")", "jedis", ")", ".", "close", "(", ")", ";", "}", "}", "}" ]
Perform a redis operation while lock is acquired @param callback a callback containing the actions to perform during lock @param errorMessage optional error message to include in exception should an error arise @param <T> return class @return the result of the actions performed while locked, if any @throws JobPersistenceException
[ "Perform", "a", "redis", "operation", "while", "lock", "is", "acquired" ]
train
https://github.com/jlinn/quartz-redis-jobstore/blob/be9a52ee776d8a09866fe99fd9718bc13a0cb992/src/main/java/net/joelinn/quartz/jobstore/RedisJobStore.java#L1148-L1171
jaxio/celerio
celerio-engine/src/main/java/com/jaxio/celerio/template/PreviousEngine.java
PreviousEngine.convertFileNameToBaseClassName
private String convertFileNameToBaseClassName(String filename) { """ add Base to a given java filename it is used for transparently subclassing generated classes """ if (filename.endsWith("_.java")) { return substringBeforeLast(filename, "_.java") + BASE_SUFFIX_; } else { return substringBeforeLast(filename, ".java") + BASE_SUFFIX; } }
java
private String convertFileNameToBaseClassName(String filename) { if (filename.endsWith("_.java")) { return substringBeforeLast(filename, "_.java") + BASE_SUFFIX_; } else { return substringBeforeLast(filename, ".java") + BASE_SUFFIX; } }
[ "private", "String", "convertFileNameToBaseClassName", "(", "String", "filename", ")", "{", "if", "(", "filename", ".", "endsWith", "(", "\"_.java\"", ")", ")", "{", "return", "substringBeforeLast", "(", "filename", ",", "\"_.java\"", ")", "+", "BASE_SUFFIX_", ";", "}", "else", "{", "return", "substringBeforeLast", "(", "filename", ",", "\".java\"", ")", "+", "BASE_SUFFIX", ";", "}", "}" ]
add Base to a given java filename it is used for transparently subclassing generated classes
[ "add", "Base", "to", "a", "given", "java", "filename", "it", "is", "used", "for", "transparently", "subclassing", "generated", "classes" ]
train
https://github.com/jaxio/celerio/blob/fbfacb639e286f9f3f3a18986f74ea275bebd887/celerio-engine/src/main/java/com/jaxio/celerio/template/PreviousEngine.java#L303-L309
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.slurpFileNoExceptions
public static String slurpFileNoExceptions(String filename, String encoding) { """ Returns all the text in the given file with the given encoding. If the file cannot be read (non-existent, etc.), then and only then the method returns <code>null</code>. """ try { return slurpFile(filename, encoding); } catch (Exception e) { throw new RuntimeIOException("slurpFile IO problem", e); } }
java
public static String slurpFileNoExceptions(String filename, String encoding) { try { return slurpFile(filename, encoding); } catch (Exception e) { throw new RuntimeIOException("slurpFile IO problem", e); } }
[ "public", "static", "String", "slurpFileNoExceptions", "(", "String", "filename", ",", "String", "encoding", ")", "{", "try", "{", "return", "slurpFile", "(", "filename", ",", "encoding", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeIOException", "(", "\"slurpFile IO problem\"", ",", "e", ")", ";", "}", "}" ]
Returns all the text in the given file with the given encoding. If the file cannot be read (non-existent, etc.), then and only then the method returns <code>null</code>.
[ "Returns", "all", "the", "text", "in", "the", "given", "file", "with", "the", "given", "encoding", ".", "If", "the", "file", "cannot", "be", "read", "(", "non", "-", "existent", "etc", ".", ")", "then", "and", "only", "then", "the", "method", "returns", "<code", ">", "null<", "/", "code", ">", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L737-L743
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java
DNSUtil.resolveXMPPServiceDomain
public static List<HostAddress> resolveXMPPServiceDomain(DnsName domain, List<HostAddress> failedAddresses, DnssecMode dnssecMode) { """ Returns a list of HostAddresses under which the specified XMPP server can be reached at for client-to-server communication. A DNS lookup for a SRV record in the form "_xmpp-client._tcp.example.com" is attempted, according to section 3.2.1 of RFC 6120. If that lookup fails, it's assumed that the XMPP server lives at the host resolved by a DNS lookup at the specified domain on the default port of 5222. <p> As an example, a lookup for "example.com" may return "im.example.com:5269". </p> @param domain the domain. @param failedAddresses on optional list that will be populated with host addresses that failed to resolve. @param dnssecMode DNSSec mode. @return List of HostAddress, which encompasses the hostname and port that the XMPP server can be reached at for the specified domain. """ return resolveDomain(domain, DomainType.client, failedAddresses, dnssecMode); }
java
public static List<HostAddress> resolveXMPPServiceDomain(DnsName domain, List<HostAddress> failedAddresses, DnssecMode dnssecMode) { return resolveDomain(domain, DomainType.client, failedAddresses, dnssecMode); }
[ "public", "static", "List", "<", "HostAddress", ">", "resolveXMPPServiceDomain", "(", "DnsName", "domain", ",", "List", "<", "HostAddress", ">", "failedAddresses", ",", "DnssecMode", "dnssecMode", ")", "{", "return", "resolveDomain", "(", "domain", ",", "DomainType", ".", "client", ",", "failedAddresses", ",", "dnssecMode", ")", ";", "}" ]
Returns a list of HostAddresses under which the specified XMPP server can be reached at for client-to-server communication. A DNS lookup for a SRV record in the form "_xmpp-client._tcp.example.com" is attempted, according to section 3.2.1 of RFC 6120. If that lookup fails, it's assumed that the XMPP server lives at the host resolved by a DNS lookup at the specified domain on the default port of 5222. <p> As an example, a lookup for "example.com" may return "im.example.com:5269". </p> @param domain the domain. @param failedAddresses on optional list that will be populated with host addresses that failed to resolve. @param dnssecMode DNSSec mode. @return List of HostAddress, which encompasses the hostname and port that the XMPP server can be reached at for the specified domain.
[ "Returns", "a", "list", "of", "HostAddresses", "under", "which", "the", "specified", "XMPP", "server", "can", "be", "reached", "at", "for", "client", "-", "to", "-", "server", "communication", ".", "A", "DNS", "lookup", "for", "a", "SRV", "record", "in", "the", "form", "_xmpp", "-", "client", ".", "_tcp", ".", "example", ".", "com", "is", "attempted", "according", "to", "section", "3", ".", "2", ".", "1", "of", "RFC", "6120", ".", "If", "that", "lookup", "fails", "it", "s", "assumed", "that", "the", "XMPP", "server", "lives", "at", "the", "host", "resolved", "by", "a", "DNS", "lookup", "at", "the", "specified", "domain", "on", "the", "default", "port", "of", "5222", ".", "<p", ">", "As", "an", "example", "a", "lookup", "for", "example", ".", "com", "may", "return", "im", ".", "example", ".", "com", ":", "5269", ".", "<", "/", "p", ">" ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/DNSUtil.java#L114-L116
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/distances/Distance.java
Distance.euclideanWeighted
public static double euclideanWeighted(AssociativeArray a1, AssociativeArray a2, Map<Object, Double> columnWeights) { """ Estimates the weighted euclidean distance of two Associative Arrays. @param a1 @param a2 @param columnWeights @return """ Map<Object, Double> columnDistances = columnDistances(a1, a2, columnWeights.keySet()); double distance = 0.0; for(Map.Entry<Object, Double> entry : columnDistances.entrySet()) { double columnDistance = entry.getValue(); distance+=(columnDistance*columnDistance)*columnWeights.get(entry.getKey()); } return Math.sqrt(distance); }
java
public static double euclideanWeighted(AssociativeArray a1, AssociativeArray a2, Map<Object, Double> columnWeights) { Map<Object, Double> columnDistances = columnDistances(a1, a2, columnWeights.keySet()); double distance = 0.0; for(Map.Entry<Object, Double> entry : columnDistances.entrySet()) { double columnDistance = entry.getValue(); distance+=(columnDistance*columnDistance)*columnWeights.get(entry.getKey()); } return Math.sqrt(distance); }
[ "public", "static", "double", "euclideanWeighted", "(", "AssociativeArray", "a1", ",", "AssociativeArray", "a2", ",", "Map", "<", "Object", ",", "Double", ">", "columnWeights", ")", "{", "Map", "<", "Object", ",", "Double", ">", "columnDistances", "=", "columnDistances", "(", "a1", ",", "a2", ",", "columnWeights", ".", "keySet", "(", ")", ")", ";", "double", "distance", "=", "0.0", ";", "for", "(", "Map", ".", "Entry", "<", "Object", ",", "Double", ">", "entry", ":", "columnDistances", ".", "entrySet", "(", ")", ")", "{", "double", "columnDistance", "=", "entry", ".", "getValue", "(", ")", ";", "distance", "+=", "(", "columnDistance", "*", "columnDistance", ")", "*", "columnWeights", ".", "get", "(", "entry", ".", "getKey", "(", ")", ")", ";", "}", "return", "Math", ".", "sqrt", "(", "distance", ")", ";", "}" ]
Estimates the weighted euclidean distance of two Associative Arrays. @param a1 @param a2 @param columnWeights @return
[ "Estimates", "the", "weighted", "euclidean", "distance", "of", "two", "Associative", "Arrays", "." ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/mathematics/distances/Distance.java#L57-L66
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/CollectionUtils.java
CollectionUtils.getIndex
public static <T> int getIndex(List<T> l, T o) { """ Returns the index of the first occurrence in the list of the specified object, using object identity (==) not equality as the criterion for object presence. If this list does not contain the element, return -1. @param l The {@link List} to find the object in. @param o The sought-after object. @return Whether or not the List was changed. """ int i = 0; for (Object o1 : l) { if (o == o1) return i; else i++; } return -1; }
java
public static <T> int getIndex(List<T> l, T o) { int i = 0; for (Object o1 : l) { if (o == o1) return i; else i++; } return -1; }
[ "public", "static", "<", "T", ">", "int", "getIndex", "(", "List", "<", "T", ">", "l", ",", "T", "o", ")", "{", "int", "i", "=", "0", ";", "for", "(", "Object", "o1", ":", "l", ")", "{", "if", "(", "o", "==", "o1", ")", "return", "i", ";", "else", "i", "++", ";", "}", "return", "-", "1", ";", "}" ]
Returns the index of the first occurrence in the list of the specified object, using object identity (==) not equality as the criterion for object presence. If this list does not contain the element, return -1. @param l The {@link List} to find the object in. @param o The sought-after object. @return Whether or not the List was changed.
[ "Returns", "the", "index", "of", "the", "first", "occurrence", "in", "the", "list", "of", "the", "specified", "object", "using", "object", "identity", "(", "==", ")", "not", "equality", "as", "the", "criterion", "for", "object", "presence", ".", "If", "this", "list", "does", "not", "contain", "the", "element", "return", "-", "1", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/CollectionUtils.java#L284-L293
greatman/GreatmancodeTools
src/main/java/com/greatmancode/tools/utils/Vector.java
Vector.getMaximum
public static Vector getMaximum(Vector v1, Vector v2) { """ Gets the maximum components of two vectors. @param v1 The first vector. @param v2 The second vector. @return maximum """ return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z)); }
java
public static Vector getMaximum(Vector v1, Vector v2) { return new Vector(Math.max(v1.x, v2.x), Math.max(v1.y, v2.y), Math.max(v1.z, v2.z)); }
[ "public", "static", "Vector", "getMaximum", "(", "Vector", "v1", ",", "Vector", "v2", ")", "{", "return", "new", "Vector", "(", "Math", ".", "max", "(", "v1", ".", "x", ",", "v2", ".", "x", ")", ",", "Math", ".", "max", "(", "v1", ".", "y", ",", "v2", ".", "y", ")", ",", "Math", ".", "max", "(", "v1", ".", "z", ",", "v2", ".", "z", ")", ")", ";", "}" ]
Gets the maximum components of two vectors. @param v1 The first vector. @param v2 The second vector. @return maximum
[ "Gets", "the", "maximum", "components", "of", "two", "vectors", "." ]
train
https://github.com/greatman/GreatmancodeTools/blob/4c9d2656c5c8298ff9e1f235c9be8b148e43c9f1/src/main/java/com/greatmancode/tools/utils/Vector.java#L610-L612
google/closure-compiler
src/com/google/javascript/jscomp/CheckGlobalNames.java
CheckGlobalNames.checkForBadModuleReference
private boolean checkForBadModuleReference(Name name, Ref ref) { """ Returns true if this name is potentially referenced before being defined in a different module <p>For example: <ul> <li>Module B depends on Module A. name is set in Module A and referenced in Module B. this is fine, and this method returns false. <li>Module A and Module B are unrelated. name is set in Module A and referenced in Module B. this is an error, and this method returns true. <li>name is referenced in Module A, and never set globally. This warning is not specific to modules, so is emitted elsewhere. </ul> """ JSModuleGraph moduleGraph = compiler.getModuleGraph(); if (name.getGlobalSets() == 0 || ref.type == Ref.Type.SET_FROM_GLOBAL) { // Back off if either 1) this name was never set, or 2) this reference /is/ a set. return false; } if (name.getGlobalSets() == 1) { // there is only one global set - it should be set as name.declaration // just look at that declaration instead of iterating through every single reference. Ref declaration = checkNotNull(name.getDeclaration()); return !isSetFromPrecedingModule(ref, declaration, moduleGraph); } // there are multiple sets, so check if any of them happens in this module or a module earlier // in the dependency chain. for (Ref set : name.getRefs()) { if (isSetFromPrecedingModule(ref, set, moduleGraph)) { return false; } } return true; }
java
private boolean checkForBadModuleReference(Name name, Ref ref) { JSModuleGraph moduleGraph = compiler.getModuleGraph(); if (name.getGlobalSets() == 0 || ref.type == Ref.Type.SET_FROM_GLOBAL) { // Back off if either 1) this name was never set, or 2) this reference /is/ a set. return false; } if (name.getGlobalSets() == 1) { // there is only one global set - it should be set as name.declaration // just look at that declaration instead of iterating through every single reference. Ref declaration = checkNotNull(name.getDeclaration()); return !isSetFromPrecedingModule(ref, declaration, moduleGraph); } // there are multiple sets, so check if any of them happens in this module or a module earlier // in the dependency chain. for (Ref set : name.getRefs()) { if (isSetFromPrecedingModule(ref, set, moduleGraph)) { return false; } } return true; }
[ "private", "boolean", "checkForBadModuleReference", "(", "Name", "name", ",", "Ref", "ref", ")", "{", "JSModuleGraph", "moduleGraph", "=", "compiler", ".", "getModuleGraph", "(", ")", ";", "if", "(", "name", ".", "getGlobalSets", "(", ")", "==", "0", "||", "ref", ".", "type", "==", "Ref", ".", "Type", ".", "SET_FROM_GLOBAL", ")", "{", "// Back off if either 1) this name was never set, or 2) this reference /is/ a set.", "return", "false", ";", "}", "if", "(", "name", ".", "getGlobalSets", "(", ")", "==", "1", ")", "{", "// there is only one global set - it should be set as name.declaration", "// just look at that declaration instead of iterating through every single reference.", "Ref", "declaration", "=", "checkNotNull", "(", "name", ".", "getDeclaration", "(", ")", ")", ";", "return", "!", "isSetFromPrecedingModule", "(", "ref", ",", "declaration", ",", "moduleGraph", ")", ";", "}", "// there are multiple sets, so check if any of them happens in this module or a module earlier", "// in the dependency chain.", "for", "(", "Ref", "set", ":", "name", ".", "getRefs", "(", ")", ")", "{", "if", "(", "isSetFromPrecedingModule", "(", "ref", ",", "set", ",", "moduleGraph", ")", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
Returns true if this name is potentially referenced before being defined in a different module <p>For example: <ul> <li>Module B depends on Module A. name is set in Module A and referenced in Module B. this is fine, and this method returns false. <li>Module A and Module B are unrelated. name is set in Module A and referenced in Module B. this is an error, and this method returns true. <li>name is referenced in Module A, and never set globally. This warning is not specific to modules, so is emitted elsewhere. </ul>
[ "Returns", "true", "if", "this", "name", "is", "potentially", "referenced", "before", "being", "defined", "in", "a", "different", "module" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/CheckGlobalNames.java#L229-L249
haraldk/TwelveMonkeys
common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java
IndexImage.getIndexedImage
public static BufferedImage getIndexedImage(BufferedImage pImage, IndexColorModel pColors, int pHints) { """ Converts the input image (must be {@code TYPE_INT_RGB} or {@code TYPE_INT_ARGB}) to an indexed image. Using the supplied {@code IndexColorModel}'s palette. Dithering, transparency and color selection is controlled with the {@code pHints}parameter. <p/> The image returned is a new image, the input image is not modified. @param pImage the BufferedImage to index @param pColors an {@code IndexColorModel} containing the color information @param pHints RenderingHints that control output quality and speed. @return the indexed BufferedImage. The image will be of type {@code BufferedImage.TYPE_BYTE_INDEXED} or {@code BufferedImage.TYPE_BYTE_BINARY}, and use an {@code IndexColorModel}. @see #DITHER_DIFFUSION @see #DITHER_NONE @see #COLOR_SELECTION_FAST @see #COLOR_SELECTION_QUALITY @see #TRANSPARENCY_OPAQUE @see #TRANSPARENCY_BITMASK @see BufferedImage#TYPE_BYTE_INDEXED @see BufferedImage#TYPE_BYTE_BINARY @see IndexColorModel """ return getIndexedImage(pImage, pColors, null, pHints); }
java
public static BufferedImage getIndexedImage(BufferedImage pImage, IndexColorModel pColors, int pHints) { return getIndexedImage(pImage, pColors, null, pHints); }
[ "public", "static", "BufferedImage", "getIndexedImage", "(", "BufferedImage", "pImage", ",", "IndexColorModel", "pColors", ",", "int", "pHints", ")", "{", "return", "getIndexedImage", "(", "pImage", ",", "pColors", ",", "null", ",", "pHints", ")", ";", "}" ]
Converts the input image (must be {@code TYPE_INT_RGB} or {@code TYPE_INT_ARGB}) to an indexed image. Using the supplied {@code IndexColorModel}'s palette. Dithering, transparency and color selection is controlled with the {@code pHints}parameter. <p/> The image returned is a new image, the input image is not modified. @param pImage the BufferedImage to index @param pColors an {@code IndexColorModel} containing the color information @param pHints RenderingHints that control output quality and speed. @return the indexed BufferedImage. The image will be of type {@code BufferedImage.TYPE_BYTE_INDEXED} or {@code BufferedImage.TYPE_BYTE_BINARY}, and use an {@code IndexColorModel}. @see #DITHER_DIFFUSION @see #DITHER_NONE @see #COLOR_SELECTION_FAST @see #COLOR_SELECTION_QUALITY @see #TRANSPARENCY_OPAQUE @see #TRANSPARENCY_BITMASK @see BufferedImage#TYPE_BYTE_INDEXED @see BufferedImage#TYPE_BYTE_BINARY @see IndexColorModel
[ "Converts", "the", "input", "image", "(", "must", "be", "{", "@code", "TYPE_INT_RGB", "}", "or", "{", "@code", "TYPE_INT_ARGB", "}", ")", "to", "an", "indexed", "image", ".", "Using", "the", "supplied", "{", "@code", "IndexColorModel", "}", "s", "palette", ".", "Dithering", "transparency", "and", "color", "selection", "is", "controlled", "with", "the", "{", "@code", "pHints", "}", "parameter", ".", "<p", "/", ">", "The", "image", "returned", "is", "a", "new", "image", "the", "input", "image", "is", "not", "modified", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/IndexImage.java#L1122-L1124
wellner/jcarafe
jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java
ObjectArrayList.removeAll
public boolean removeAll(ObjectArrayList other, boolean testForEquality) { """ Removes from the receiver all elements that are contained in the specified list. Tests for equality or identity as specified by <code>testForEquality</code>. @param other the other list. @param testForEquality if <code>true</code> -> test for equality, otherwise for identity. @return <code>true</code> if the receiver changed as a result of the call. """ if (other.size==0) return false; //nothing to do int limit = other.size-1; int j=0; Object[] theElements = elements; for (int i=0; i<size ; i++) { if (other.indexOfFromTo(theElements[i], 0, limit, testForEquality) < 0) theElements[j++]=theElements[i]; } boolean modified = (j!=size); setSize(j); return modified; }
java
public boolean removeAll(ObjectArrayList other, boolean testForEquality) { if (other.size==0) return false; //nothing to do int limit = other.size-1; int j=0; Object[] theElements = elements; for (int i=0; i<size ; i++) { if (other.indexOfFromTo(theElements[i], 0, limit, testForEquality) < 0) theElements[j++]=theElements[i]; } boolean modified = (j!=size); setSize(j); return modified; }
[ "public", "boolean", "removeAll", "(", "ObjectArrayList", "other", ",", "boolean", "testForEquality", ")", "{", "if", "(", "other", ".", "size", "==", "0", ")", "return", "false", ";", "//nothing to do\r", "int", "limit", "=", "other", ".", "size", "-", "1", ";", "int", "j", "=", "0", ";", "Object", "[", "]", "theElements", "=", "elements", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "if", "(", "other", ".", "indexOfFromTo", "(", "theElements", "[", "i", "]", ",", "0", ",", "limit", ",", "testForEquality", ")", "<", "0", ")", "theElements", "[", "j", "++", "]", "=", "theElements", "[", "i", "]", ";", "}", "boolean", "modified", "=", "(", "j", "!=", "size", ")", ";", "setSize", "(", "j", ")", ";", "return", "modified", ";", "}" ]
Removes from the receiver all elements that are contained in the specified list. Tests for equality or identity as specified by <code>testForEquality</code>. @param other the other list. @param testForEquality if <code>true</code> -> test for equality, otherwise for identity. @return <code>true</code> if the receiver changed as a result of the call.
[ "Removes", "from", "the", "receiver", "all", "elements", "that", "are", "contained", "in", "the", "specified", "list", ".", "Tests", "for", "equality", "or", "identity", "as", "specified", "by", "<code", ">", "testForEquality<", "/", "code", ">", "." ]
train
https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/ObjectArrayList.java#L642-L654
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/URIDestinationCreator.java
URIDestinationCreator.charIsEscaped
private static boolean charIsEscaped(String str, int index) { """ Test if the specified character is escaped. Checks whether the character at the specified index is preceded by an escape character. The test is non-trivial because it has to check that the escape character is itself non-escaped. @param str The string in which to perform the check @param index The index in the string of the character that we are interested in. @return true if the specified character is escaped. """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "charIsEscaped", new Object[]{str, index}); // precondition, null str or out of range index returns false. if (str == null || index < 0 || index >= str.length()) return false; // A character is escaped if it is preceded by an odd number of '\'s. int nEscape = 0; int i = index-1; while(i>=0 && str.charAt(i) == '\\') { nEscape++; i--; } boolean result = nEscape % 2 == 1 ; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "charIsEscaped", result); return result; }
java
private static boolean charIsEscaped(String str, int index) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "charIsEscaped", new Object[]{str, index}); // precondition, null str or out of range index returns false. if (str == null || index < 0 || index >= str.length()) return false; // A character is escaped if it is preceded by an odd number of '\'s. int nEscape = 0; int i = index-1; while(i>=0 && str.charAt(i) == '\\') { nEscape++; i--; } boolean result = nEscape % 2 == 1 ; if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "charIsEscaped", result); return result; }
[ "private", "static", "boolean", "charIsEscaped", "(", "String", "str", ",", "int", "index", ")", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"charIsEscaped\"", ",", "new", "Object", "[", "]", "{", "str", ",", "index", "}", ")", ";", "// precondition, null str or out of range index returns false.", "if", "(", "str", "==", "null", "||", "index", "<", "0", "||", "index", ">=", "str", ".", "length", "(", ")", ")", "return", "false", ";", "// A character is escaped if it is preceded by an odd number of '\\'s.", "int", "nEscape", "=", "0", ";", "int", "i", "=", "index", "-", "1", ";", "while", "(", "i", ">=", "0", "&&", "str", ".", "charAt", "(", "i", ")", "==", "'", "'", ")", "{", "nEscape", "++", ";", "i", "--", ";", "}", "boolean", "result", "=", "nEscape", "%", "2", "==", "1", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"charIsEscaped\"", ",", "result", ")", ";", "return", "result", ";", "}" ]
Test if the specified character is escaped. Checks whether the character at the specified index is preceded by an escape character. The test is non-trivial because it has to check that the escape character is itself non-escaped. @param str The string in which to perform the check @param index The index in the string of the character that we are interested in. @return true if the specified character is escaped.
[ "Test", "if", "the", "specified", "character", "is", "escaped", ".", "Checks", "whether", "the", "character", "at", "the", "specified", "index", "is", "preceded", "by", "an", "escape", "character", ".", "The", "test", "is", "non", "-", "trivial", "because", "it", "has", "to", "check", "that", "the", "escape", "character", "is", "itself", "non", "-", "escaped", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/api/jms/impl/URIDestinationCreator.java#L1012-L1029
rey5137/material
material/src/main/java/com/rey/material/widget/TimePicker.java
TimePicker.setMode
public void setMode(int mode, boolean animation) { """ Set the select mode of this TimePicker. @param mode The select mode. Can be {@link #MODE_HOUR} or {@link #MODE_MINUTE}. @param animation Indicate that should show animation when switch select mode or not. """ if(mMode != mode){ mMode = mode; if(mOnTimeChangedListener != null) mOnTimeChangedListener.onModeChanged(mMode); if(animation) startAnimation(); else invalidate(); } }
java
public void setMode(int mode, boolean animation){ if(mMode != mode){ mMode = mode; if(mOnTimeChangedListener != null) mOnTimeChangedListener.onModeChanged(mMode); if(animation) startAnimation(); else invalidate(); } }
[ "public", "void", "setMode", "(", "int", "mode", ",", "boolean", "animation", ")", "{", "if", "(", "mMode", "!=", "mode", ")", "{", "mMode", "=", "mode", ";", "if", "(", "mOnTimeChangedListener", "!=", "null", ")", "mOnTimeChangedListener", ".", "onModeChanged", "(", "mMode", ")", ";", "if", "(", "animation", ")", "startAnimation", "(", ")", ";", "else", "invalidate", "(", ")", ";", "}", "}" ]
Set the select mode of this TimePicker. @param mode The select mode. Can be {@link #MODE_HOUR} or {@link #MODE_MINUTE}. @param animation Indicate that should show animation when switch select mode or not.
[ "Set", "the", "select", "mode", "of", "this", "TimePicker", "." ]
train
https://github.com/rey5137/material/blob/1bbcac2686a0023ef7720d3fe455bb116d115af8/material/src/main/java/com/rey/material/widget/TimePicker.java#L326-L338
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.scrollToSide
public void scrollToSide(int side, float scrollPosition) { """ Scrolls horizontally. @param side the side to scroll; {@link #RIGHT} or {@link #LEFT} @param scrollPosition the position to scroll to, from 0 to 1 where 1 is all the way. Example is: 0.60 """ if(config.commandLogging){ Log.d(config.commandLoggingTag, "scrollToSide("+scrollPosition+")"); } scrollToSide(side, scrollPosition, 20); }
java
public void scrollToSide(int side, float scrollPosition) { if(config.commandLogging){ Log.d(config.commandLoggingTag, "scrollToSide("+scrollPosition+")"); } scrollToSide(side, scrollPosition, 20); }
[ "public", "void", "scrollToSide", "(", "int", "side", ",", "float", "scrollPosition", ")", "{", "if", "(", "config", ".", "commandLogging", ")", "{", "Log", ".", "d", "(", "config", ".", "commandLoggingTag", ",", "\"scrollToSide(\"", "+", "scrollPosition", "+", "\")\"", ")", ";", "}", "scrollToSide", "(", "side", ",", "scrollPosition", ",", "20", ")", ";", "}" ]
Scrolls horizontally. @param side the side to scroll; {@link #RIGHT} or {@link #LEFT} @param scrollPosition the position to scroll to, from 0 to 1 where 1 is all the way. Example is: 0.60
[ "Scrolls", "horizontally", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2325-L2331
dita-ot/dita-ot
src/main/java/org/dita/dost/util/XMLSerializer.java
XMLSerializer.writeProcessingInstruction
public void writeProcessingInstruction(final String target, final String data) throws SAXException { """ Write processing instruction. @param target processing instruction name @param data processing instruction data, {@code null} if no data @throws SAXException if processing the event failed """ processStartElement(); transformer.processingInstruction(target, data != null ? data : ""); }
java
public void writeProcessingInstruction(final String target, final String data) throws SAXException { processStartElement(); transformer.processingInstruction(target, data != null ? data : ""); }
[ "public", "void", "writeProcessingInstruction", "(", "final", "String", "target", ",", "final", "String", "data", ")", "throws", "SAXException", "{", "processStartElement", "(", ")", ";", "transformer", ".", "processingInstruction", "(", "target", ",", "data", "!=", "null", "?", "data", ":", "\"\"", ")", ";", "}" ]
Write processing instruction. @param target processing instruction name @param data processing instruction data, {@code null} if no data @throws SAXException if processing the event failed
[ "Write", "processing", "instruction", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/util/XMLSerializer.java#L286-L289
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/CalendarUtil.java
CalendarUtil.addMonths
public XMLGregorianCalendar addMonths(final XMLGregorianCalendar cal, final int amount) { """ Add Months to a Gregorian Calendar. @param cal The XMLGregorianCalendar source @param amount The amount of months. Can be a negative Integer to substract. @return A XMLGregorianCalendar with the new Date """ XMLGregorianCalendar to = buildXMLGregorianCalendarDate(cal); // Add amount of months to.add(addMonths(amount)); return to; }
java
public XMLGregorianCalendar addMonths(final XMLGregorianCalendar cal, final int amount) { XMLGregorianCalendar to = buildXMLGregorianCalendarDate(cal); // Add amount of months to.add(addMonths(amount)); return to; }
[ "public", "XMLGregorianCalendar", "addMonths", "(", "final", "XMLGregorianCalendar", "cal", ",", "final", "int", "amount", ")", "{", "XMLGregorianCalendar", "to", "=", "buildXMLGregorianCalendarDate", "(", "cal", ")", ";", "// Add amount of months", "to", ".", "add", "(", "addMonths", "(", "amount", ")", ")", ";", "return", "to", ";", "}" ]
Add Months to a Gregorian Calendar. @param cal The XMLGregorianCalendar source @param amount The amount of months. Can be a negative Integer to substract. @return A XMLGregorianCalendar with the new Date
[ "Add", "Months", "to", "a", "Gregorian", "Calendar", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/CalendarUtil.java#L48-L53
LearnLib/learnlib
oracles/membership-oracles/src/main/java/de/learnlib/oracle/membership/AbstractSULOmegaOracle.java
AbstractSULOmegaOracle.newOracle
public static <S, I, O> AbstractSULOmegaOracle<S, I, O, ?> newOracle(ObservableSUL<S, I, O> sul) { """ Creates a new {@link AbstractSULOmegaOracle} that assumes the {@link SUL} can not make deep copies. @see #newOracle(ObservableSUL, boolean) @param <S> the state type @param <I> the input type @param <O> the output type """ return newOracle(sul, !sul.canFork()); }
java
public static <S, I, O> AbstractSULOmegaOracle<S, I, O, ?> newOracle(ObservableSUL<S, I, O> sul) { return newOracle(sul, !sul.canFork()); }
[ "public", "static", "<", "S", ",", "I", ",", "O", ">", "AbstractSULOmegaOracle", "<", "S", ",", "I", ",", "O", ",", "?", ">", "newOracle", "(", "ObservableSUL", "<", "S", ",", "I", ",", "O", ">", "sul", ")", "{", "return", "newOracle", "(", "sul", ",", "!", "sul", ".", "canFork", "(", ")", ")", ";", "}" ]
Creates a new {@link AbstractSULOmegaOracle} that assumes the {@link SUL} can not make deep copies. @see #newOracle(ObservableSUL, boolean) @param <S> the state type @param <I> the input type @param <O> the output type
[ "Creates", "a", "new", "{", "@link", "AbstractSULOmegaOracle", "}", "that", "assumes", "the", "{", "@link", "SUL", "}", "can", "not", "make", "deep", "copies", "." ]
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/oracles/membership-oracles/src/main/java/de/learnlib/oracle/membership/AbstractSULOmegaOracle.java#L185-L187
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/dynamic/output/CommandOutputResolverSupport.java
CommandOutputResolverSupport.isAssignableFrom
protected boolean isAssignableFrom(OutputSelector selector, OutputType provider) { """ Overridable hook to check whether {@code selector} can be assigned from the provider type {@code provider}. <p> This method descends the component type hierarchy and considers primitive/wrapper type conversion. @param selector must not be {@literal null}. @param provider must not be {@literal null}. @return {@literal true} if selector can be assigned from its provider type. """ ResolvableType selectorType = selector.getOutputType(); ResolvableType resolvableType = provider.withCodec(selector.getRedisCodec()); return selectorType.isAssignableFrom(resolvableType); }
java
protected boolean isAssignableFrom(OutputSelector selector, OutputType provider) { ResolvableType selectorType = selector.getOutputType(); ResolvableType resolvableType = provider.withCodec(selector.getRedisCodec()); return selectorType.isAssignableFrom(resolvableType); }
[ "protected", "boolean", "isAssignableFrom", "(", "OutputSelector", "selector", ",", "OutputType", "provider", ")", "{", "ResolvableType", "selectorType", "=", "selector", ".", "getOutputType", "(", ")", ";", "ResolvableType", "resolvableType", "=", "provider", ".", "withCodec", "(", "selector", ".", "getRedisCodec", "(", ")", ")", ";", "return", "selectorType", ".", "isAssignableFrom", "(", "resolvableType", ")", ";", "}" ]
Overridable hook to check whether {@code selector} can be assigned from the provider type {@code provider}. <p> This method descends the component type hierarchy and considers primitive/wrapper type conversion. @param selector must not be {@literal null}. @param provider must not be {@literal null}. @return {@literal true} if selector can be assigned from its provider type.
[ "Overridable", "hook", "to", "check", "whether", "{", "@code", "selector", "}", "can", "be", "assigned", "from", "the", "provider", "type", "{", "@code", "provider", "}", ".", "<p", ">", "This", "method", "descends", "the", "component", "type", "hierarchy", "and", "considers", "primitive", "/", "wrapper", "type", "conversion", "." ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/dynamic/output/CommandOutputResolverSupport.java#L39-L45
jbundle/webapp
base/src/main/java/org/jbundle/util/webapp/base/BaseWebappServlet.java
BaseWebappServlet.getRequestParam
public String getRequestParam(HttpServletRequest request, String param, String defaultValue) { """ Get this param from the request or from the servlet's properties. @param request @param param @param defaultValue @return """ String value = request.getParameter(servicePid + '.' + param); if ((value == null) && (properties != null)) value = properties.get(servicePid + '.' + param); if (value == null) value = request.getParameter(param); if ((value == null) && (properties != null)) value = properties.get(param); if (value == null) value = defaultValue; return value; }
java
public String getRequestParam(HttpServletRequest request, String param, String defaultValue) { String value = request.getParameter(servicePid + '.' + param); if ((value == null) && (properties != null)) value = properties.get(servicePid + '.' + param); if (value == null) value = request.getParameter(param); if ((value == null) && (properties != null)) value = properties.get(param); if (value == null) value = defaultValue; return value; }
[ "public", "String", "getRequestParam", "(", "HttpServletRequest", "request", ",", "String", "param", ",", "String", "defaultValue", ")", "{", "String", "value", "=", "request", ".", "getParameter", "(", "servicePid", "+", "'", "'", "+", "param", ")", ";", "if", "(", "(", "value", "==", "null", ")", "&&", "(", "properties", "!=", "null", ")", ")", "value", "=", "properties", ".", "get", "(", "servicePid", "+", "'", "'", "+", "param", ")", ";", "if", "(", "value", "==", "null", ")", "value", "=", "request", ".", "getParameter", "(", "param", ")", ";", "if", "(", "(", "value", "==", "null", ")", "&&", "(", "properties", "!=", "null", ")", ")", "value", "=", "properties", ".", "get", "(", "param", ")", ";", "if", "(", "value", "==", "null", ")", "value", "=", "defaultValue", ";", "return", "value", ";", "}" ]
Get this param from the request or from the servlet's properties. @param request @param param @param defaultValue @return
[ "Get", "this", "param", "from", "the", "request", "or", "from", "the", "servlet", "s", "properties", "." ]
train
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/base/src/main/java/org/jbundle/util/webapp/base/BaseWebappServlet.java#L124-L136
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/hoverbar/CmsEditMenuEntry.java
CmsEditMenuEntry.createEntryEditor
protected A_CmsPropertyEditor createEntryEditor( I_CmsPropertyEditorHandler handler, Map<String, CmsXmlContentProperty> propConfig) { """ Creates the right sitemap entry editor for the current mode.<p> @param handler the entry editor handler @param propConfig the property configuration to use @return a sitemap entry editor instance """ if (CmsSitemapView.getInstance().isNavigationMode()) { return new CmsNavModePropertyEditor(propConfig, handler); } else { boolean isFolder = handler.isFolder(); CmsVfsModePropertyEditor result = new CmsVfsModePropertyEditor(propConfig, handler); result.setShowResourceProperties(!isFolder); return result; } }
java
protected A_CmsPropertyEditor createEntryEditor( I_CmsPropertyEditorHandler handler, Map<String, CmsXmlContentProperty> propConfig) { if (CmsSitemapView.getInstance().isNavigationMode()) { return new CmsNavModePropertyEditor(propConfig, handler); } else { boolean isFolder = handler.isFolder(); CmsVfsModePropertyEditor result = new CmsVfsModePropertyEditor(propConfig, handler); result.setShowResourceProperties(!isFolder); return result; } }
[ "protected", "A_CmsPropertyEditor", "createEntryEditor", "(", "I_CmsPropertyEditorHandler", "handler", ",", "Map", "<", "String", ",", "CmsXmlContentProperty", ">", "propConfig", ")", "{", "if", "(", "CmsSitemapView", ".", "getInstance", "(", ")", ".", "isNavigationMode", "(", ")", ")", "{", "return", "new", "CmsNavModePropertyEditor", "(", "propConfig", ",", "handler", ")", ";", "}", "else", "{", "boolean", "isFolder", "=", "handler", ".", "isFolder", "(", ")", ";", "CmsVfsModePropertyEditor", "result", "=", "new", "CmsVfsModePropertyEditor", "(", "propConfig", ",", "handler", ")", ";", "result", ".", "setShowResourceProperties", "(", "!", "isFolder", ")", ";", "return", "result", ";", "}", "}" ]
Creates the right sitemap entry editor for the current mode.<p> @param handler the entry editor handler @param propConfig the property configuration to use @return a sitemap entry editor instance
[ "Creates", "the", "right", "sitemap", "entry", "editor", "for", "the", "current", "mode", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/hoverbar/CmsEditMenuEntry.java#L202-L214
ben-manes/caffeine
caffeine/src/main/java/com/github/benmanes/caffeine/cache/TimerWheel.java
TimerWheel.deschedule
public void deschedule(@NonNull Node<K, V> node) { """ Removes a timer event for this entry if present. @param node the entry in the cache """ unlink(node); node.setNextInVariableOrder(null); node.setPreviousInVariableOrder(null); }
java
public void deschedule(@NonNull Node<K, V> node) { unlink(node); node.setNextInVariableOrder(null); node.setPreviousInVariableOrder(null); }
[ "public", "void", "deschedule", "(", "@", "NonNull", "Node", "<", "K", ",", "V", ">", "node", ")", "{", "unlink", "(", "node", ")", ";", "node", ".", "setNextInVariableOrder", "(", "null", ")", ";", "node", ".", "setPreviousInVariableOrder", "(", "null", ")", ";", "}" ]
Removes a timer event for this entry if present. @param node the entry in the cache
[ "Removes", "a", "timer", "event", "for", "this", "entry", "if", "present", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/caffeine/src/main/java/com/github/benmanes/caffeine/cache/TimerWheel.java#L191-L195
threerings/nenya
core/src/main/java/com/threerings/openal/SoundGroup.java
SoundGroup.acquireSource
protected Source acquireSource (Sound acquirer) { """ Called by a {@link Sound} when it wants to obtain a source on which to play its clip. """ // start at the beginning of the list looking for an available source for (int ii = 0, ll = _sources.size(); ii < ll; ii++) { PooledSource pooled = _sources.get(ii); if (pooled.holder == null || pooled.holder.reclaim()) { // note this source's new holder pooled.holder = acquirer; // move this source to the end of the list _sources.remove(ii); _sources.add(pooled); return pooled.source; } } return null; }
java
protected Source acquireSource (Sound acquirer) { // start at the beginning of the list looking for an available source for (int ii = 0, ll = _sources.size(); ii < ll; ii++) { PooledSource pooled = _sources.get(ii); if (pooled.holder == null || pooled.holder.reclaim()) { // note this source's new holder pooled.holder = acquirer; // move this source to the end of the list _sources.remove(ii); _sources.add(pooled); return pooled.source; } } return null; }
[ "protected", "Source", "acquireSource", "(", "Sound", "acquirer", ")", "{", "// start at the beginning of the list looking for an available source", "for", "(", "int", "ii", "=", "0", ",", "ll", "=", "_sources", ".", "size", "(", ")", ";", "ii", "<", "ll", ";", "ii", "++", ")", "{", "PooledSource", "pooled", "=", "_sources", ".", "get", "(", "ii", ")", ";", "if", "(", "pooled", ".", "holder", "==", "null", "||", "pooled", ".", "holder", ".", "reclaim", "(", ")", ")", "{", "// note this source's new holder", "pooled", ".", "holder", "=", "acquirer", ";", "// move this source to the end of the list", "_sources", ".", "remove", "(", "ii", ")", ";", "_sources", ".", "add", "(", "pooled", ")", ";", "return", "pooled", ".", "source", ";", "}", "}", "return", "null", ";", "}" ]
Called by a {@link Sound} when it wants to obtain a source on which to play its clip.
[ "Called", "by", "a", "{" ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/openal/SoundGroup.java#L141-L156
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java
ByteBufJsonParser.pushLevel
private void pushLevel(final Mode mode) { """ Pushes a new {@link JsonLevel} onto the level stack. @param mode the mode for this level. """ JsonLevel newJsonLevel = null; if (mode == Mode.BOM) { newJsonLevel = new JsonLevel(mode, new JsonPointer()); //not a valid nesting level } else if (mode == Mode.JSON_OBJECT) { if (levelStack.size() > 0) { JsonLevel current = levelStack.peek(); newJsonLevel = new JsonLevel(mode, new JsonPointer(current.jsonPointer().tokens())); } else { newJsonLevel = new JsonLevel(mode, new JsonPointer()); } } else if (mode == Mode.JSON_ARRAY) { if (levelStack.size() > 0) { JsonLevel current = levelStack.peek(); newJsonLevel = new JsonLevel(mode, new JsonPointer(current.jsonPointer().tokens())); } else { newJsonLevel = new JsonLevel(mode, new JsonPointer()); } newJsonLevel.isArray(true); newJsonLevel.setArrayIndexOnJsonPointer(); } levelStack.push(newJsonLevel); }
java
private void pushLevel(final Mode mode) { JsonLevel newJsonLevel = null; if (mode == Mode.BOM) { newJsonLevel = new JsonLevel(mode, new JsonPointer()); //not a valid nesting level } else if (mode == Mode.JSON_OBJECT) { if (levelStack.size() > 0) { JsonLevel current = levelStack.peek(); newJsonLevel = new JsonLevel(mode, new JsonPointer(current.jsonPointer().tokens())); } else { newJsonLevel = new JsonLevel(mode, new JsonPointer()); } } else if (mode == Mode.JSON_ARRAY) { if (levelStack.size() > 0) { JsonLevel current = levelStack.peek(); newJsonLevel = new JsonLevel(mode, new JsonPointer(current.jsonPointer().tokens())); } else { newJsonLevel = new JsonLevel(mode, new JsonPointer()); } newJsonLevel.isArray(true); newJsonLevel.setArrayIndexOnJsonPointer(); } levelStack.push(newJsonLevel); }
[ "private", "void", "pushLevel", "(", "final", "Mode", "mode", ")", "{", "JsonLevel", "newJsonLevel", "=", "null", ";", "if", "(", "mode", "==", "Mode", ".", "BOM", ")", "{", "newJsonLevel", "=", "new", "JsonLevel", "(", "mode", ",", "new", "JsonPointer", "(", ")", ")", ";", "//not a valid nesting level", "}", "else", "if", "(", "mode", "==", "Mode", ".", "JSON_OBJECT", ")", "{", "if", "(", "levelStack", ".", "size", "(", ")", ">", "0", ")", "{", "JsonLevel", "current", "=", "levelStack", ".", "peek", "(", ")", ";", "newJsonLevel", "=", "new", "JsonLevel", "(", "mode", ",", "new", "JsonPointer", "(", "current", ".", "jsonPointer", "(", ")", ".", "tokens", "(", ")", ")", ")", ";", "}", "else", "{", "newJsonLevel", "=", "new", "JsonLevel", "(", "mode", ",", "new", "JsonPointer", "(", ")", ")", ";", "}", "}", "else", "if", "(", "mode", "==", "Mode", ".", "JSON_ARRAY", ")", "{", "if", "(", "levelStack", ".", "size", "(", ")", ">", "0", ")", "{", "JsonLevel", "current", "=", "levelStack", ".", "peek", "(", ")", ";", "newJsonLevel", "=", "new", "JsonLevel", "(", "mode", ",", "new", "JsonPointer", "(", "current", ".", "jsonPointer", "(", ")", ".", "tokens", "(", ")", ")", ")", ";", "}", "else", "{", "newJsonLevel", "=", "new", "JsonLevel", "(", "mode", ",", "new", "JsonPointer", "(", ")", ")", ";", "}", "newJsonLevel", ".", "isArray", "(", "true", ")", ";", "newJsonLevel", ".", "setArrayIndexOnJsonPointer", "(", ")", ";", "}", "levelStack", ".", "push", "(", "newJsonLevel", ")", ";", "}" ]
Pushes a new {@link JsonLevel} onto the level stack. @param mode the mode for this level.
[ "Pushes", "a", "new", "{", "@link", "JsonLevel", "}", "onto", "the", "level", "stack", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/utils/yasjl/ByteBufJsonParser.java#L163-L187
spotify/styx
styx-service-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java
DatastoreStorage.asBuilderOrNew
static Entity.Builder asBuilderOrNew(Optional<Entity> entityOpt, Key key) { """ Convert an optional {@link Entity} into a builder if it exists, otherwise create a new builder. @param entityOpt The optional entity @param key The key for which to create a new builder if the entity is not present @return an entity builder either based of the given entity or a new one using the key. """ return entityOpt .map(c -> Entity.newBuilder(key, c)) .orElse(Entity.newBuilder(key)); }
java
static Entity.Builder asBuilderOrNew(Optional<Entity> entityOpt, Key key) { return entityOpt .map(c -> Entity.newBuilder(key, c)) .orElse(Entity.newBuilder(key)); }
[ "static", "Entity", ".", "Builder", "asBuilderOrNew", "(", "Optional", "<", "Entity", ">", "entityOpt", ",", "Key", "key", ")", "{", "return", "entityOpt", ".", "map", "(", "c", "->", "Entity", ".", "newBuilder", "(", "key", ",", "c", ")", ")", ".", "orElse", "(", "Entity", ".", "newBuilder", "(", "key", ")", ")", ";", "}" ]
Convert an optional {@link Entity} into a builder if it exists, otherwise create a new builder. @param entityOpt The optional entity @param key The key for which to create a new builder if the entity is not present @return an entity builder either based of the given entity or a new one using the key.
[ "Convert", "an", "optional", "{", "@link", "Entity", "}", "into", "a", "builder", "if", "it", "exists", "otherwise", "create", "a", "new", "builder", "." ]
train
https://github.com/spotify/styx/blob/0d63999beeb93a17447e3bbccaa62175b74cf6e4/styx-service-common/src/main/java/com/spotify/styx/storage/DatastoreStorage.java#L720-L724
jbundle/jbundle
base/db/client/src/main/java/org/jbundle/base/db/client/ClientTable.java
ClientTable.doMove
public int doMove(int iRelPosition) throws DBException { """ Move the position of the record. @param iRelPosition - Relative position positive or negative or FIRST_RECORD/LAST_RECORD. @return NORMAL_RETURN - The following are NOT mutually exclusive @exception DBException File exception. """ this.checkCacheMode(Boolean.TRUE); // Make sure the cache is set up correctly for this type of query (typically needed) int iErrorCode = DBConstants.NORMAL_RETURN; try { Object objData = null; synchronized (this.getSyncObject()) { // In case this is called from another task objData = m_tableRemote.doMove(iRelPosition, 1); } if (objData instanceof Vector) { Vector<Object> data = (Vector)objData; //m_tableRemote.dataToFields(); Record recordBase = this.getRecord(); int iFieldTypes = BaseBuffer.PHYSICAL_FIELDS; if (!recordBase.isAllSelected()) iFieldTypes = BaseBuffer.DATA_FIELDS; // SELECTED_FIELDS; (selected and physical) BaseBuffer buffer = new VectorBuffer(data, iFieldTypes); if (DBParams.RECORD.equals(buffer.getHeader())) { // Warning: The target record was a multitable and This is the record name! String strTableNames = buffer.getHeader().toString(); Utility.getLogger().warning("ClientTable.doMove() - Warning: Multitable needs to be specified: " + strTableNames); } else buffer.resetPosition(); m_dataSource = buffer; iErrorCode = DBConstants.NORMAL_RETURN; } else if (objData instanceof Number) iErrorCode = ((Number)objData).intValue(); else iErrorCode = DBConstants.ERROR_RETURN; // Never return iErrorCode; } catch (Exception ex) { ex.printStackTrace(); throw DatabaseException.toDatabaseException(ex); } }
java
public int doMove(int iRelPosition) throws DBException { this.checkCacheMode(Boolean.TRUE); // Make sure the cache is set up correctly for this type of query (typically needed) int iErrorCode = DBConstants.NORMAL_RETURN; try { Object objData = null; synchronized (this.getSyncObject()) { // In case this is called from another task objData = m_tableRemote.doMove(iRelPosition, 1); } if (objData instanceof Vector) { Vector<Object> data = (Vector)objData; //m_tableRemote.dataToFields(); Record recordBase = this.getRecord(); int iFieldTypes = BaseBuffer.PHYSICAL_FIELDS; if (!recordBase.isAllSelected()) iFieldTypes = BaseBuffer.DATA_FIELDS; // SELECTED_FIELDS; (selected and physical) BaseBuffer buffer = new VectorBuffer(data, iFieldTypes); if (DBParams.RECORD.equals(buffer.getHeader())) { // Warning: The target record was a multitable and This is the record name! String strTableNames = buffer.getHeader().toString(); Utility.getLogger().warning("ClientTable.doMove() - Warning: Multitable needs to be specified: " + strTableNames); } else buffer.resetPosition(); m_dataSource = buffer; iErrorCode = DBConstants.NORMAL_RETURN; } else if (objData instanceof Number) iErrorCode = ((Number)objData).intValue(); else iErrorCode = DBConstants.ERROR_RETURN; // Never return iErrorCode; } catch (Exception ex) { ex.printStackTrace(); throw DatabaseException.toDatabaseException(ex); } }
[ "public", "int", "doMove", "(", "int", "iRelPosition", ")", "throws", "DBException", "{", "this", ".", "checkCacheMode", "(", "Boolean", ".", "TRUE", ")", ";", "// Make sure the cache is set up correctly for this type of query (typically needed)", "int", "iErrorCode", "=", "DBConstants", ".", "NORMAL_RETURN", ";", "try", "{", "Object", "objData", "=", "null", ";", "synchronized", "(", "this", ".", "getSyncObject", "(", ")", ")", "{", "// In case this is called from another task", "objData", "=", "m_tableRemote", ".", "doMove", "(", "iRelPosition", ",", "1", ")", ";", "}", "if", "(", "objData", "instanceof", "Vector", ")", "{", "Vector", "<", "Object", ">", "data", "=", "(", "Vector", ")", "objData", ";", "//m_tableRemote.dataToFields();", "Record", "recordBase", "=", "this", ".", "getRecord", "(", ")", ";", "int", "iFieldTypes", "=", "BaseBuffer", ".", "PHYSICAL_FIELDS", ";", "if", "(", "!", "recordBase", ".", "isAllSelected", "(", ")", ")", "iFieldTypes", "=", "BaseBuffer", ".", "DATA_FIELDS", ";", "// SELECTED_FIELDS; (selected and physical)", "BaseBuffer", "buffer", "=", "new", "VectorBuffer", "(", "data", ",", "iFieldTypes", ")", ";", "if", "(", "DBParams", ".", "RECORD", ".", "equals", "(", "buffer", ".", "getHeader", "(", ")", ")", ")", "{", "// Warning: The target record was a multitable and This is the record name!", "String", "strTableNames", "=", "buffer", ".", "getHeader", "(", ")", ".", "toString", "(", ")", ";", "Utility", ".", "getLogger", "(", ")", ".", "warning", "(", "\"ClientTable.doMove() - Warning: Multitable needs to be specified: \"", "+", "strTableNames", ")", ";", "}", "else", "buffer", ".", "resetPosition", "(", ")", ";", "m_dataSource", "=", "buffer", ";", "iErrorCode", "=", "DBConstants", ".", "NORMAL_RETURN", ";", "}", "else", "if", "(", "objData", "instanceof", "Number", ")", "iErrorCode", "=", "(", "(", "Number", ")", "objData", ")", ".", "intValue", "(", ")", ";", "else", "iErrorCode", "=", "DBConstants", ".", "ERROR_RETURN", ";", "// Never", "return", "iErrorCode", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", ")", ";", "throw", "DatabaseException", ".", "toDatabaseException", "(", "ex", ")", ";", "}", "}" ]
Move the position of the record. @param iRelPosition - Relative position positive or negative or FIRST_RECORD/LAST_RECORD. @return NORMAL_RETURN - The following are NOT mutually exclusive @exception DBException File exception.
[ "Move", "the", "position", "of", "the", "record", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/db/client/src/main/java/org/jbundle/base/db/client/ClientTable.java#L354-L391
alkacon/opencms-core
src/org/opencms/util/CmsPair.java
CmsPair.getLexicalComparator
public static <A extends Comparable<A>, B extends Comparable<B>> Comparator<CmsPair<A, B>> getLexicalComparator() { """ Utility method which creates a new comparator for lexically ordering pairs.<p> Lexical ordering means that a pair is considered "less" than another if either its first component is less than that of the other one, or their first components are equal and the second component of the first pair is less than that of the other one.<p> @param <A> the type parameter for the first pair component @param <B> the type parameter for the second pair component @return a new comparator for lexically ordering pairs """ return new Comparator<CmsPair<A, B>>() { /** * @see java.util.Comparator#compare(Object,Object) */ public int compare(CmsPair<A, B> pair1, CmsPair<A, B> pair2) { int c = pair1.getFirst().compareTo(pair2.getFirst()); if (c != 0) { return c; } return pair1.getSecond().compareTo(pair2.getSecond()); } }; }
java
public static <A extends Comparable<A>, B extends Comparable<B>> Comparator<CmsPair<A, B>> getLexicalComparator() { return new Comparator<CmsPair<A, B>>() { /** * @see java.util.Comparator#compare(Object,Object) */ public int compare(CmsPair<A, B> pair1, CmsPair<A, B> pair2) { int c = pair1.getFirst().compareTo(pair2.getFirst()); if (c != 0) { return c; } return pair1.getSecond().compareTo(pair2.getSecond()); } }; }
[ "public", "static", "<", "A", "extends", "Comparable", "<", "A", ">", ",", "B", "extends", "Comparable", "<", "B", ">", ">", "Comparator", "<", "CmsPair", "<", "A", ",", "B", ">", ">", "getLexicalComparator", "(", ")", "{", "return", "new", "Comparator", "<", "CmsPair", "<", "A", ",", "B", ">", ">", "(", ")", "{", "/**\n * @see java.util.Comparator#compare(Object,Object)\n */", "public", "int", "compare", "(", "CmsPair", "<", "A", ",", "B", ">", "pair1", ",", "CmsPair", "<", "A", ",", "B", ">", "pair2", ")", "{", "int", "c", "=", "pair1", ".", "getFirst", "(", ")", ".", "compareTo", "(", "pair2", ".", "getFirst", "(", ")", ")", ";", "if", "(", "c", "!=", "0", ")", "{", "return", "c", ";", "}", "return", "pair1", ".", "getSecond", "(", ")", ".", "compareTo", "(", "pair2", ".", "getSecond", "(", ")", ")", ";", "}", "}", ";", "}" ]
Utility method which creates a new comparator for lexically ordering pairs.<p> Lexical ordering means that a pair is considered "less" than another if either its first component is less than that of the other one, or their first components are equal and the second component of the first pair is less than that of the other one.<p> @param <A> the type parameter for the first pair component @param <B> the type parameter for the second pair component @return a new comparator for lexically ordering pairs
[ "Utility", "method", "which", "creates", "a", "new", "comparator", "for", "lexically", "ordering", "pairs", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsPair.java#L105-L121
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java
SimpleMMcifConsumer.addInfoFromESS
private void addInfoFromESS(EntitySrcSyn ess, int eId, EntityInfo c) { """ Add the information from ESS to Entity info. @param ess @param eId @param c """ c.setOrganismCommon(ess.getOrganism_common_name()); c.setOrganismScientific(ess.getOrganism_scientific()); c.setOrganismTaxId(ess.getNcbi_taxonomy_id()); }
java
private void addInfoFromESS(EntitySrcSyn ess, int eId, EntityInfo c) { c.setOrganismCommon(ess.getOrganism_common_name()); c.setOrganismScientific(ess.getOrganism_scientific()); c.setOrganismTaxId(ess.getNcbi_taxonomy_id()); }
[ "private", "void", "addInfoFromESS", "(", "EntitySrcSyn", "ess", ",", "int", "eId", ",", "EntityInfo", "c", ")", "{", "c", ".", "setOrganismCommon", "(", "ess", ".", "getOrganism_common_name", "(", ")", ")", ";", "c", ".", "setOrganismScientific", "(", "ess", ".", "getOrganism_scientific", "(", ")", ")", ";", "c", ".", "setOrganismTaxId", "(", "ess", ".", "getNcbi_taxonomy_id", "(", ")", ")", ";", "}" ]
Add the information from ESS to Entity info. @param ess @param eId @param c
[ "Add", "the", "information", "from", "ESS", "to", "Entity", "info", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/SimpleMMcifConsumer.java#L1227-L1232
JodaOrg/joda-time
src/main/java/org/joda/time/chrono/GJDayOfWeekDateTimeField.java
GJDayOfWeekDateTimeField.convertText
protected int convertText(String text, Locale locale) { """ Convert the specified text and locale into a value. @param text the text to convert @param locale the locale to convert using @return the value extracted from the text @throws IllegalArgumentException if the text is invalid """ return GJLocaleSymbols.forLocale(locale).dayOfWeekTextToValue(text); }
java
protected int convertText(String text, Locale locale) { return GJLocaleSymbols.forLocale(locale).dayOfWeekTextToValue(text); }
[ "protected", "int", "convertText", "(", "String", "text", ",", "Locale", "locale", ")", "{", "return", "GJLocaleSymbols", ".", "forLocale", "(", "locale", ")", ".", "dayOfWeekTextToValue", "(", "text", ")", ";", "}" ]
Convert the specified text and locale into a value. @param text the text to convert @param locale the locale to convert using @return the value extracted from the text @throws IllegalArgumentException if the text is invalid
[ "Convert", "the", "specified", "text", "and", "locale", "into", "a", "value", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/chrono/GJDayOfWeekDateTimeField.java#L90-L92
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java
AbstractTextFileConverter.openOutputFile
private void openOutputFile(final String outputFileName) throws IOException { """ Prepare the output stream. @param outputFileName the file to write into. @throws IOException if a problem occurs. """ myOutputFile = new File(outputFileName); myOutputStream = new FileOutputStream(myOutputFile); myStreamWriter = new OutputStreamWriter(myOutputStream, getOutputEncodingCode()); myBufferedWriter = new BufferedWriter(myStreamWriter); }
java
private void openOutputFile(final String outputFileName) throws IOException { myOutputFile = new File(outputFileName); myOutputStream = new FileOutputStream(myOutputFile); myStreamWriter = new OutputStreamWriter(myOutputStream, getOutputEncodingCode()); myBufferedWriter = new BufferedWriter(myStreamWriter); }
[ "private", "void", "openOutputFile", "(", "final", "String", "outputFileName", ")", "throws", "IOException", "{", "myOutputFile", "=", "new", "File", "(", "outputFileName", ")", ";", "myOutputStream", "=", "new", "FileOutputStream", "(", "myOutputFile", ")", ";", "myStreamWriter", "=", "new", "OutputStreamWriter", "(", "myOutputStream", ",", "getOutputEncodingCode", "(", ")", ")", ";", "myBufferedWriter", "=", "new", "BufferedWriter", "(", "myStreamWriter", ")", ";", "}" ]
Prepare the output stream. @param outputFileName the file to write into. @throws IOException if a problem occurs.
[ "Prepare", "the", "output", "stream", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/AbstractTextFileConverter.java#L420-L426
google/closure-templates
java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java
JbcSrcRuntime.propagateClose
public static ClosePropagatingAppendable propagateClose( LoggingAdvisingAppendable delegate, ImmutableList<Closeable> closeables) { """ Returns a {@link LoggingAdvisingAppendable} that: <ul> <li>Forwards all {@link LoggingAdvisingAppendable} methods to {@code delegate} <li>Implements {@link Closeable} and forwards all {@link Closeable#close} calls to the given closeables in order. </ul> <p>This strategy allows us to make certain directives closeable without requiring them all to be since this wrapper can propagate the close signals in the rare case that a closeable directive is wrapped with a non closeable one (or multiple closeable wrappers are composed) """ return new ClosePropagatingAppendable(delegate, closeables); }
java
public static ClosePropagatingAppendable propagateClose( LoggingAdvisingAppendable delegate, ImmutableList<Closeable> closeables) { return new ClosePropagatingAppendable(delegate, closeables); }
[ "public", "static", "ClosePropagatingAppendable", "propagateClose", "(", "LoggingAdvisingAppendable", "delegate", ",", "ImmutableList", "<", "Closeable", ">", "closeables", ")", "{", "return", "new", "ClosePropagatingAppendable", "(", "delegate", ",", "closeables", ")", ";", "}" ]
Returns a {@link LoggingAdvisingAppendable} that: <ul> <li>Forwards all {@link LoggingAdvisingAppendable} methods to {@code delegate} <li>Implements {@link Closeable} and forwards all {@link Closeable#close} calls to the given closeables in order. </ul> <p>This strategy allows us to make certain directives closeable without requiring them all to be since this wrapper can propagate the close signals in the rare case that a closeable directive is wrapped with a non closeable one (or multiple closeable wrappers are composed)
[ "Returns", "a", "{", "@link", "LoggingAdvisingAppendable", "}", "that", ":" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/runtime/JbcSrcRuntime.java#L736-L739
OrienteerBAP/wicket-orientdb
wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/proto/AbstractPrototyper.java
AbstractPrototyper.getDefaultValue
protected Object getDefaultValue(String propName, Class<?> returnType) { """ Method for obtaining default value of required property @param propName name of a property @param returnType type of a property @return default value for particular property """ Object ret = null; if(returnType.isPrimitive()) { if(returnType.equals(boolean.class)) { return false; } else if(returnType.equals(char.class)) { return '\0'; } else { try { Class<?> wrapperClass = Primitives.wrap(returnType); return wrapperClass.getMethod("valueOf", String.class).invoke(null, "0"); } catch (Throwable e) { throw new WicketRuntimeException("Can't create default value for '"+propName+"' which should have type '"+returnType.getName()+"'"); } } } return ret; }
java
protected Object getDefaultValue(String propName, Class<?> returnType) { Object ret = null; if(returnType.isPrimitive()) { if(returnType.equals(boolean.class)) { return false; } else if(returnType.equals(char.class)) { return '\0'; } else { try { Class<?> wrapperClass = Primitives.wrap(returnType); return wrapperClass.getMethod("valueOf", String.class).invoke(null, "0"); } catch (Throwable e) { throw new WicketRuntimeException("Can't create default value for '"+propName+"' which should have type '"+returnType.getName()+"'"); } } } return ret; }
[ "protected", "Object", "getDefaultValue", "(", "String", "propName", ",", "Class", "<", "?", ">", "returnType", ")", "{", "Object", "ret", "=", "null", ";", "if", "(", "returnType", ".", "isPrimitive", "(", ")", ")", "{", "if", "(", "returnType", ".", "equals", "(", "boolean", ".", "class", ")", ")", "{", "return", "false", ";", "}", "else", "if", "(", "returnType", ".", "equals", "(", "char", ".", "class", ")", ")", "{", "return", "'", "'", ";", "}", "else", "{", "try", "{", "Class", "<", "?", ">", "wrapperClass", "=", "Primitives", ".", "wrap", "(", "returnType", ")", ";", "return", "wrapperClass", ".", "getMethod", "(", "\"valueOf\"", ",", "String", ".", "class", ")", ".", "invoke", "(", "null", ",", "\"0\"", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "throw", "new", "WicketRuntimeException", "(", "\"Can't create default value for '\"", "+", "propName", "+", "\"' which should have type '\"", "+", "returnType", ".", "getName", "(", ")", "+", "\"'\"", ")", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Method for obtaining default value of required property @param propName name of a property @param returnType type of a property @return default value for particular property
[ "Method", "for", "obtaining", "default", "value", "of", "required", "property" ]
train
https://github.com/OrienteerBAP/wicket-orientdb/blob/eb1d94f00a6bff9e266c5c032baa6043afc1db92/wicket-orientdb/src/main/java/ru/ydn/wicket/wicketorientdb/proto/AbstractPrototyper.java#L265-L291
aws/aws-sdk-java
aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/SearchProductsAsAdminRequest.java
SearchProductsAsAdminRequest.setFilters
public void setFilters(java.util.Map<String, java.util.List<String>> filters) { """ <p> The search filters. If no search filters are specified, the output includes all products to which the administrator has access. </p> @param filters The search filters. If no search filters are specified, the output includes all products to which the administrator has access. """ this.filters = filters; }
java
public void setFilters(java.util.Map<String, java.util.List<String>> filters) { this.filters = filters; }
[ "public", "void", "setFilters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "java", ".", "util", ".", "List", "<", "String", ">", ">", "filters", ")", "{", "this", ".", "filters", "=", "filters", ";", "}" ]
<p> The search filters. If no search filters are specified, the output includes all products to which the administrator has access. </p> @param filters The search filters. If no search filters are specified, the output includes all products to which the administrator has access.
[ "<p", ">", "The", "search", "filters", ".", "If", "no", "search", "filters", "are", "specified", "the", "output", "includes", "all", "products", "to", "which", "the", "administrator", "has", "access", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-servicecatalog/src/main/java/com/amazonaws/services/servicecatalog/model/SearchProductsAsAdminRequest.java#L299-L301
UrielCh/ovh-java-sdk
ovh-java-sdk-licenseoffice/src/main/java/net/minidev/ovh/api/ApiOvhLicenseoffice.java
ApiOvhLicenseoffice.serviceName_domain_domainName_GET
public OvhOfficeDomain serviceName_domain_domainName_GET(String serviceName, String domainName) throws IOException { """ Get this object properties REST: GET /license/office/{serviceName}/domain/{domainName} @param serviceName [required] The unique identifier of your Office service @param domainName [required] Domain name """ String qPath = "/license/office/{serviceName}/domain/{domainName}"; StringBuilder sb = path(qPath, serviceName, domainName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOfficeDomain.class); }
java
public OvhOfficeDomain serviceName_domain_domainName_GET(String serviceName, String domainName) throws IOException { String qPath = "/license/office/{serviceName}/domain/{domainName}"; StringBuilder sb = path(qPath, serviceName, domainName); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOfficeDomain.class); }
[ "public", "OvhOfficeDomain", "serviceName_domain_domainName_GET", "(", "String", "serviceName", ",", "String", "domainName", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/license/office/{serviceName}/domain/{domainName}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "domainName", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOfficeDomain", ".", "class", ")", ";", "}" ]
Get this object properties REST: GET /license/office/{serviceName}/domain/{domainName} @param serviceName [required] The unique identifier of your Office service @param domainName [required] Domain name
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-licenseoffice/src/main/java/net/minidev/ovh/api/ApiOvhLicenseoffice.java#L48-L53
Cornutum/tcases
tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java
TupleGenerator.byUsage
private Comparator<VarBindingDef> byUsage( final VarTupleSet varTupleSet) { """ Returns a comparator that orders bindings by decreasing preference, preferring bindings that are less used. """ return new Comparator<VarBindingDef>() { public int compare( VarBindingDef binding1, VarBindingDef binding2) { // Compare by usage score: higher score is preferred. int resultScore = getScore( binding2).compareTo( getScore( binding1)); return // If equal usage score... resultScore == 0 // ...then compare lexigraphically ? varBindingDefSorter_.compare( binding1, binding2) : resultScore; } private Integer getScore( VarBindingDef binding) { Integer score = bindingScores_.get( binding); if( score == null) { // Preferred higher "unused-ness" and lower "used-ness" (especially among once-only tuples) int maxScore = 1000; int unusedScore = (int) (varTupleSet.getUnusedScore( binding) * maxScore); int usedScore = (int) ((1.0 - varTupleSet.getUsedScore( binding)) * (maxScore - 1)); int usedOnceScore = (int) ((1.0 - varTupleSet.getUsedOnceScore( binding)) * (maxScore - 1)); score = ((unusedScore * maxScore) + usedOnceScore) * maxScore + usedScore; bindingScores_.put( binding, score); } return score; } private Map<VarBindingDef,Integer> bindingScores_ = new HashMap<VarBindingDef,Integer>(); }; }
java
private Comparator<VarBindingDef> byUsage( final VarTupleSet varTupleSet) { return new Comparator<VarBindingDef>() { public int compare( VarBindingDef binding1, VarBindingDef binding2) { // Compare by usage score: higher score is preferred. int resultScore = getScore( binding2).compareTo( getScore( binding1)); return // If equal usage score... resultScore == 0 // ...then compare lexigraphically ? varBindingDefSorter_.compare( binding1, binding2) : resultScore; } private Integer getScore( VarBindingDef binding) { Integer score = bindingScores_.get( binding); if( score == null) { // Preferred higher "unused-ness" and lower "used-ness" (especially among once-only tuples) int maxScore = 1000; int unusedScore = (int) (varTupleSet.getUnusedScore( binding) * maxScore); int usedScore = (int) ((1.0 - varTupleSet.getUsedScore( binding)) * (maxScore - 1)); int usedOnceScore = (int) ((1.0 - varTupleSet.getUsedOnceScore( binding)) * (maxScore - 1)); score = ((unusedScore * maxScore) + usedOnceScore) * maxScore + usedScore; bindingScores_.put( binding, score); } return score; } private Map<VarBindingDef,Integer> bindingScores_ = new HashMap<VarBindingDef,Integer>(); }; }
[ "private", "Comparator", "<", "VarBindingDef", ">", "byUsage", "(", "final", "VarTupleSet", "varTupleSet", ")", "{", "return", "new", "Comparator", "<", "VarBindingDef", ">", "(", ")", "{", "public", "int", "compare", "(", "VarBindingDef", "binding1", ",", "VarBindingDef", "binding2", ")", "{", "// Compare by usage score: higher score is preferred.", "int", "resultScore", "=", "getScore", "(", "binding2", ")", ".", "compareTo", "(", "getScore", "(", "binding1", ")", ")", ";", "return", "// If equal usage score...", "resultScore", "==", "0", "// ...then compare lexigraphically", "?", "varBindingDefSorter_", ".", "compare", "(", "binding1", ",", "binding2", ")", ":", "resultScore", ";", "}", "private", "Integer", "getScore", "(", "VarBindingDef", "binding", ")", "{", "Integer", "score", "=", "bindingScores_", ".", "get", "(", "binding", ")", ";", "if", "(", "score", "==", "null", ")", "{", "// Preferred higher \"unused-ness\" and lower \"used-ness\" (especially among once-only tuples)", "int", "maxScore", "=", "1000", ";", "int", "unusedScore", "=", "(", "int", ")", "(", "varTupleSet", ".", "getUnusedScore", "(", "binding", ")", "*", "maxScore", ")", ";", "int", "usedScore", "=", "(", "int", ")", "(", "(", "1.0", "-", "varTupleSet", ".", "getUsedScore", "(", "binding", ")", ")", "*", "(", "maxScore", "-", "1", ")", ")", ";", "int", "usedOnceScore", "=", "(", "int", ")", "(", "(", "1.0", "-", "varTupleSet", ".", "getUsedOnceScore", "(", "binding", ")", ")", "*", "(", "maxScore", "-", "1", ")", ")", ";", "score", "=", "(", "(", "unusedScore", "*", "maxScore", ")", "+", "usedOnceScore", ")", "*", "maxScore", "+", "usedScore", ";", "bindingScores_", ".", "put", "(", "binding", ",", "score", ")", ";", "}", "return", "score", ";", "}", "private", "Map", "<", "VarBindingDef", ",", "Integer", ">", "bindingScores_", "=", "new", "HashMap", "<", "VarBindingDef", ",", "Integer", ">", "(", ")", ";", "}", ";", "}" ]
Returns a comparator that orders bindings by decreasing preference, preferring bindings that are less used.
[ "Returns", "a", "comparator", "that", "orders", "bindings", "by", "decreasing", "preference", "preferring", "bindings", "that", "are", "less", "used", "." ]
train
https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-lib/src/main/java/org/cornutum/tcases/generator/TupleGenerator.java#L783-L818
cdapio/tigon
tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java
DatumWriterGenerator.encodeSimple
private void encodeSimple(GeneratorAdapter mg, TypeToken<?> type, Schema schema, String encodeMethod, int value, int encoder) { """ Generates method body for encoding simple schema type by calling corresponding write method in Encoder. @param mg Method body generator @param type Data type to encode @param encodeMethod Name of the encode method to invoke on the given encoder. @param value Argument index of the value to encode. @param encoder Method argument index of the encoder """ // encoder.writeXXX(value); TypeToken<?> encodeType = type; mg.loadArg(encoder); mg.loadArg(value); if (Primitives.isWrapperType(encodeType.getRawType())) { encodeType = TypeToken.of(Primitives.unwrap(encodeType.getRawType())); mg.unbox(Type.getType(encodeType.getRawType())); // A special case since INT type represents (byte, char, short and int). if (schema.getType() == Schema.Type.INT && !int.class.equals(encodeType.getRawType())) { encodeType = TypeToken.of(int.class); } } else if (schema.getType() == Schema.Type.STRING && !String.class.equals(encodeType.getRawType())) { // For non-string object that has a String schema, invoke toString(). mg.invokeVirtual(Type.getType(encodeType.getRawType()), getMethod(String.class, "toString")); encodeType = TypeToken.of(String.class); } else if (schema.getType() == Schema.Type.BYTES && UUID.class.equals(encodeType.getRawType())) { // Special case UUID, encode as byte array // ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2) // .putLong(uuid.getMostSignificantBits()) // .putLong(uuid.getLeastSignificantBits()); // encoder.writeBytes((ByteBuffer) buf.flip()); Type byteBufferType = Type.getType(ByteBuffer.class); Type uuidType = Type.getType(UUID.class); mg.push(Longs.BYTES * 2); mg.invokeStatic(byteBufferType, getMethod(ByteBuffer.class, "allocate", int.class)); mg.swap(); mg.invokeVirtual(uuidType, getMethod(long.class, "getMostSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.loadArg(value); mg.invokeVirtual(uuidType, getMethod(long.class, "getLeastSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.invokeVirtual(Type.getType(Buffer.class), getMethod(Buffer.class, "flip")); mg.checkCast(byteBufferType); encodeType = TypeToken.of(ByteBuffer.class); } mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, encodeMethod, encodeType.getRawType())); mg.pop(); }
java
private void encodeSimple(GeneratorAdapter mg, TypeToken<?> type, Schema schema, String encodeMethod, int value, int encoder) { // encoder.writeXXX(value); TypeToken<?> encodeType = type; mg.loadArg(encoder); mg.loadArg(value); if (Primitives.isWrapperType(encodeType.getRawType())) { encodeType = TypeToken.of(Primitives.unwrap(encodeType.getRawType())); mg.unbox(Type.getType(encodeType.getRawType())); // A special case since INT type represents (byte, char, short and int). if (schema.getType() == Schema.Type.INT && !int.class.equals(encodeType.getRawType())) { encodeType = TypeToken.of(int.class); } } else if (schema.getType() == Schema.Type.STRING && !String.class.equals(encodeType.getRawType())) { // For non-string object that has a String schema, invoke toString(). mg.invokeVirtual(Type.getType(encodeType.getRawType()), getMethod(String.class, "toString")); encodeType = TypeToken.of(String.class); } else if (schema.getType() == Schema.Type.BYTES && UUID.class.equals(encodeType.getRawType())) { // Special case UUID, encode as byte array // ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2) // .putLong(uuid.getMostSignificantBits()) // .putLong(uuid.getLeastSignificantBits()); // encoder.writeBytes((ByteBuffer) buf.flip()); Type byteBufferType = Type.getType(ByteBuffer.class); Type uuidType = Type.getType(UUID.class); mg.push(Longs.BYTES * 2); mg.invokeStatic(byteBufferType, getMethod(ByteBuffer.class, "allocate", int.class)); mg.swap(); mg.invokeVirtual(uuidType, getMethod(long.class, "getMostSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.loadArg(value); mg.invokeVirtual(uuidType, getMethod(long.class, "getLeastSignificantBits")); mg.invokeVirtual(byteBufferType, getMethod(ByteBuffer.class, "putLong", long.class)); mg.invokeVirtual(Type.getType(Buffer.class), getMethod(Buffer.class, "flip")); mg.checkCast(byteBufferType); encodeType = TypeToken.of(ByteBuffer.class); } mg.invokeInterface(Type.getType(Encoder.class), getMethod(Encoder.class, encodeMethod, encodeType.getRawType())); mg.pop(); }
[ "private", "void", "encodeSimple", "(", "GeneratorAdapter", "mg", ",", "TypeToken", "<", "?", ">", "type", ",", "Schema", "schema", ",", "String", "encodeMethod", ",", "int", "value", ",", "int", "encoder", ")", "{", "// encoder.writeXXX(value);", "TypeToken", "<", "?", ">", "encodeType", "=", "type", ";", "mg", ".", "loadArg", "(", "encoder", ")", ";", "mg", ".", "loadArg", "(", "value", ")", ";", "if", "(", "Primitives", ".", "isWrapperType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "encodeType", "=", "TypeToken", ".", "of", "(", "Primitives", ".", "unwrap", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "mg", ".", "unbox", "(", "Type", ".", "getType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "// A special case since INT type represents (byte, char, short and int).", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "INT", "&&", "!", "int", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "encodeType", "=", "TypeToken", ".", "of", "(", "int", ".", "class", ")", ";", "}", "}", "else", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "STRING", "&&", "!", "String", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "// For non-string object that has a String schema, invoke toString().", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "encodeType", ".", "getRawType", "(", ")", ")", ",", "getMethod", "(", "String", ".", "class", ",", "\"toString\"", ")", ")", ";", "encodeType", "=", "TypeToken", ".", "of", "(", "String", ".", "class", ")", ";", "}", "else", "if", "(", "schema", ".", "getType", "(", ")", "==", "Schema", ".", "Type", ".", "BYTES", "&&", "UUID", ".", "class", ".", "equals", "(", "encodeType", ".", "getRawType", "(", ")", ")", ")", "{", "// Special case UUID, encode as byte array", "// ByteBuffer buf = ByteBuffer.allocate(Longs.BYTES * 2)", "// .putLong(uuid.getMostSignificantBits())", "// .putLong(uuid.getLeastSignificantBits());", "// encoder.writeBytes((ByteBuffer) buf.flip());", "Type", "byteBufferType", "=", "Type", ".", "getType", "(", "ByteBuffer", ".", "class", ")", ";", "Type", "uuidType", "=", "Type", ".", "getType", "(", "UUID", ".", "class", ")", ";", "mg", ".", "push", "(", "Longs", ".", "BYTES", "*", "2", ")", ";", "mg", ".", "invokeStatic", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"allocate\"", ",", "int", ".", "class", ")", ")", ";", "mg", ".", "swap", "(", ")", ";", "mg", ".", "invokeVirtual", "(", "uuidType", ",", "getMethod", "(", "long", ".", "class", ",", "\"getMostSignificantBits\"", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"putLong\"", ",", "long", ".", "class", ")", ")", ";", "mg", ".", "loadArg", "(", "value", ")", ";", "mg", ".", "invokeVirtual", "(", "uuidType", ",", "getMethod", "(", "long", ".", "class", ",", "\"getLeastSignificantBits\"", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "byteBufferType", ",", "getMethod", "(", "ByteBuffer", ".", "class", ",", "\"putLong\"", ",", "long", ".", "class", ")", ")", ";", "mg", ".", "invokeVirtual", "(", "Type", ".", "getType", "(", "Buffer", ".", "class", ")", ",", "getMethod", "(", "Buffer", ".", "class", ",", "\"flip\"", ")", ")", ";", "mg", ".", "checkCast", "(", "byteBufferType", ")", ";", "encodeType", "=", "TypeToken", ".", "of", "(", "ByteBuffer", ".", "class", ")", ";", "}", "mg", ".", "invokeInterface", "(", "Type", ".", "getType", "(", "Encoder", ".", "class", ")", ",", "getMethod", "(", "Encoder", ".", "class", ",", "encodeMethod", ",", "encodeType", ".", "getRawType", "(", ")", ")", ")", ";", "mg", ".", "pop", "(", ")", ";", "}" ]
Generates method body for encoding simple schema type by calling corresponding write method in Encoder. @param mg Method body generator @param type Data type to encode @param encodeMethod Name of the encode method to invoke on the given encoder. @param value Argument index of the value to encode. @param encoder Method argument index of the encoder
[ "Generates", "method", "body", "for", "encoding", "simple", "schema", "type", "by", "calling", "corresponding", "write", "method", "in", "Encoder", "." ]
train
https://github.com/cdapio/tigon/blob/5be6dffd7c79519d1211bb08f75be7dcfbbad392/tigon-yarn/src/main/java/co/cask/tigon/internal/io/DatumWriterGenerator.java#L396-L442
carewebframework/carewebframework-core
org.carewebframework.messaging-parent/org.carewebframework.messaging.jms-parent/org.carewebframework.messaging.jms.core/src/main/java/org/carewebframework/messaging/jms/JMSService.java
JMSService.produceTopicMessage
public void produceTopicMessage(String destinationName, String messageData, String recipients) { """ Produces topic message. Uses JmsTemplate to send to local broker and forwards (based on demand) to broker network. @param destinationName The destination name. @param messageData The message data. @param recipients Comma-delimited list of recipient ids. """ Message msg = createObjectMessage(messageData, "anonymous", recipients); sendMessage(destinationName, msg); }
java
public void produceTopicMessage(String destinationName, String messageData, String recipients) { Message msg = createObjectMessage(messageData, "anonymous", recipients); sendMessage(destinationName, msg); }
[ "public", "void", "produceTopicMessage", "(", "String", "destinationName", ",", "String", "messageData", ",", "String", "recipients", ")", "{", "Message", "msg", "=", "createObjectMessage", "(", "messageData", ",", "\"anonymous\"", ",", "recipients", ")", ";", "sendMessage", "(", "destinationName", ",", "msg", ")", ";", "}" ]
Produces topic message. Uses JmsTemplate to send to local broker and forwards (based on demand) to broker network. @param destinationName The destination name. @param messageData The message data. @param recipients Comma-delimited list of recipient ids.
[ "Produces", "topic", "message", ".", "Uses", "JmsTemplate", "to", "send", "to", "local", "broker", "and", "forwards", "(", "based", "on", "demand", ")", "to", "broker", "network", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.messaging-parent/org.carewebframework.messaging.jms-parent/org.carewebframework.messaging.jms.core/src/main/java/org/carewebframework/messaging/jms/JMSService.java#L175-L178
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsADEManager.java
CmsADEManager.getFavoriteList
public List<CmsContainerElementBean> getFavoriteList(CmsObject cms) throws CmsException { """ Returns the favorite list, or creates it if not available.<p> @param cms the cms context @return the favorite list @throws CmsException if something goes wrong """ CmsUser user = cms.getRequestContext().getCurrentUser(); Object obj = user.getAdditionalInfo(ADDINFO_ADE_FAVORITE_LIST); List<CmsContainerElementBean> favList = new ArrayList<CmsContainerElementBean>(); if (obj instanceof String) { try { JSONArray array = new JSONArray((String)obj); for (int i = 0; i < array.length(); i++) { try { favList.add(elementFromJson(array.getJSONObject(i))); } catch (Throwable e) { // should never happen, catches wrong or no longer existing values LOG.warn(e.getLocalizedMessage()); } } } catch (Throwable e) { // should never happen, catches json parsing LOG.warn(e.getLocalizedMessage()); } } else { // save to be better next time saveFavoriteList(cms, favList); } return favList; }
java
public List<CmsContainerElementBean> getFavoriteList(CmsObject cms) throws CmsException { CmsUser user = cms.getRequestContext().getCurrentUser(); Object obj = user.getAdditionalInfo(ADDINFO_ADE_FAVORITE_LIST); List<CmsContainerElementBean> favList = new ArrayList<CmsContainerElementBean>(); if (obj instanceof String) { try { JSONArray array = new JSONArray((String)obj); for (int i = 0; i < array.length(); i++) { try { favList.add(elementFromJson(array.getJSONObject(i))); } catch (Throwable e) { // should never happen, catches wrong or no longer existing values LOG.warn(e.getLocalizedMessage()); } } } catch (Throwable e) { // should never happen, catches json parsing LOG.warn(e.getLocalizedMessage()); } } else { // save to be better next time saveFavoriteList(cms, favList); } return favList; }
[ "public", "List", "<", "CmsContainerElementBean", ">", "getFavoriteList", "(", "CmsObject", "cms", ")", "throws", "CmsException", "{", "CmsUser", "user", "=", "cms", ".", "getRequestContext", "(", ")", ".", "getCurrentUser", "(", ")", ";", "Object", "obj", "=", "user", ".", "getAdditionalInfo", "(", "ADDINFO_ADE_FAVORITE_LIST", ")", ";", "List", "<", "CmsContainerElementBean", ">", "favList", "=", "new", "ArrayList", "<", "CmsContainerElementBean", ">", "(", ")", ";", "if", "(", "obj", "instanceof", "String", ")", "{", "try", "{", "JSONArray", "array", "=", "new", "JSONArray", "(", "(", "String", ")", "obj", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "array", ".", "length", "(", ")", ";", "i", "++", ")", "{", "try", "{", "favList", ".", "add", "(", "elementFromJson", "(", "array", ".", "getJSONObject", "(", "i", ")", ")", ")", ";", "}", "catch", "(", "Throwable", "e", ")", "{", "// should never happen, catches wrong or no longer existing values", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "}", "}", "catch", "(", "Throwable", "e", ")", "{", "// should never happen, catches json parsing", "LOG", ".", "warn", "(", "e", ".", "getLocalizedMessage", "(", ")", ")", ";", "}", "}", "else", "{", "// save to be better next time", "saveFavoriteList", "(", "cms", ",", "favList", ")", ";", "}", "return", "favList", ";", "}" ]
Returns the favorite list, or creates it if not available.<p> @param cms the cms context @return the favorite list @throws CmsException if something goes wrong
[ "Returns", "the", "favorite", "list", "or", "creates", "it", "if", "not", "available", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L568-L595
rterp/GMapsFX
GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptArray.java
JavascriptArray.lastIndexOf
public int lastIndexOf(Object obj) { """ lastIndexOf() Search the array for an element, starting at the end, and returns its position """ if (obj instanceof JavascriptObject) { return checkInteger(invokeJavascript("lastIndexOf", ((JavascriptObject) obj).getJSObject()), -1); } return checkInteger(invokeJavascript("lastIndexOf", obj), -1); }
java
public int lastIndexOf(Object obj) { if (obj instanceof JavascriptObject) { return checkInteger(invokeJavascript("lastIndexOf", ((JavascriptObject) obj).getJSObject()), -1); } return checkInteger(invokeJavascript("lastIndexOf", obj), -1); }
[ "public", "int", "lastIndexOf", "(", "Object", "obj", ")", "{", "if", "(", "obj", "instanceof", "JavascriptObject", ")", "{", "return", "checkInteger", "(", "invokeJavascript", "(", "\"lastIndexOf\"", ",", "(", "(", "JavascriptObject", ")", "obj", ")", ".", "getJSObject", "(", ")", ")", ",", "-", "1", ")", ";", "}", "return", "checkInteger", "(", "invokeJavascript", "(", "\"lastIndexOf\"", ",", "obj", ")", ",", "-", "1", ")", ";", "}" ]
lastIndexOf() Search the array for an element, starting at the end, and returns its position
[ "lastIndexOf", "()", "Search", "the", "array", "for", "an", "element", "starting", "at", "the", "end", "and", "returns", "its", "position" ]
train
https://github.com/rterp/GMapsFX/blob/4623d3f768e8ad78fc50ee32dd204d236e01059f/GMapsFX/src/main/java/com/lynden/gmapsfx/javascript/JavascriptArray.java#L62-L67
nguyenq/tess4j
src/main/java/net/sourceforge/tess4j/util/PdfGsUtilities.java
PdfGsUtilities.convertPdf2Png
public synchronized static File[] convertPdf2Png(File inputPdfFile) throws IOException { """ Converts PDF to PNG format. @param inputPdfFile input file @return an array of PNG images @throws java.io.IOException """ Path path = Files.createTempDirectory("tessimages"); File imageDir = path.toFile(); //get Ghostscript instance Ghostscript gs = Ghostscript.getInstance(); //prepare Ghostscript interpreter parameters //refer to Ghostscript documentation for parameter usage List<String> gsArgs = new ArrayList<String>(); gsArgs.add("-gs"); gsArgs.add("-dNOPAUSE"); gsArgs.add("-dQUIET"); gsArgs.add("-dBATCH"); gsArgs.add("-dSAFER"); gsArgs.add("-sDEVICE=pnggray"); gsArgs.add("-r300"); gsArgs.add("-dGraphicsAlphaBits=4"); gsArgs.add("-dTextAlphaBits=4"); gsArgs.add("-sOutputFile=" + imageDir.getPath() + "/workingimage%04d.png"); gsArgs.add(inputPdfFile.getPath()); //execute and exit interpreter try { synchronized (gs) { gs.initialize(gsArgs.toArray(new String[0])); gs.exit(); } } catch (UnsatisfiedLinkError e) { logger.error(e.getMessage()); throw new RuntimeException(getMessage(e.getMessage())); } catch (NoClassDefFoundError e) { logger.error(e.getMessage()); throw new RuntimeException(getMessage(e.getMessage())); } catch (GhostscriptException e) { logger.error(e.getMessage()); throw new RuntimeException(e.getMessage()); } finally { if (imageDir.list().length == 0) { imageDir.delete(); } //delete interpreter instance (safer) try { Ghostscript.deleteInstance(); } catch (GhostscriptException e) { //nothing } } // find working files File[] workingFiles = imageDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().matches("workingimage\\d{4}\\.png$"); } }); Arrays.sort(workingFiles, new Comparator<File>() { @Override public int compare(File f1, File f2) { return f1.getName().compareTo(f2.getName()); } }); return workingFiles; }
java
public synchronized static File[] convertPdf2Png(File inputPdfFile) throws IOException { Path path = Files.createTempDirectory("tessimages"); File imageDir = path.toFile(); //get Ghostscript instance Ghostscript gs = Ghostscript.getInstance(); //prepare Ghostscript interpreter parameters //refer to Ghostscript documentation for parameter usage List<String> gsArgs = new ArrayList<String>(); gsArgs.add("-gs"); gsArgs.add("-dNOPAUSE"); gsArgs.add("-dQUIET"); gsArgs.add("-dBATCH"); gsArgs.add("-dSAFER"); gsArgs.add("-sDEVICE=pnggray"); gsArgs.add("-r300"); gsArgs.add("-dGraphicsAlphaBits=4"); gsArgs.add("-dTextAlphaBits=4"); gsArgs.add("-sOutputFile=" + imageDir.getPath() + "/workingimage%04d.png"); gsArgs.add(inputPdfFile.getPath()); //execute and exit interpreter try { synchronized (gs) { gs.initialize(gsArgs.toArray(new String[0])); gs.exit(); } } catch (UnsatisfiedLinkError e) { logger.error(e.getMessage()); throw new RuntimeException(getMessage(e.getMessage())); } catch (NoClassDefFoundError e) { logger.error(e.getMessage()); throw new RuntimeException(getMessage(e.getMessage())); } catch (GhostscriptException e) { logger.error(e.getMessage()); throw new RuntimeException(e.getMessage()); } finally { if (imageDir.list().length == 0) { imageDir.delete(); } //delete interpreter instance (safer) try { Ghostscript.deleteInstance(); } catch (GhostscriptException e) { //nothing } } // find working files File[] workingFiles = imageDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().matches("workingimage\\d{4}\\.png$"); } }); Arrays.sort(workingFiles, new Comparator<File>() { @Override public int compare(File f1, File f2) { return f1.getName().compareTo(f2.getName()); } }); return workingFiles; }
[ "public", "synchronized", "static", "File", "[", "]", "convertPdf2Png", "(", "File", "inputPdfFile", ")", "throws", "IOException", "{", "Path", "path", "=", "Files", ".", "createTempDirectory", "(", "\"tessimages\"", ")", ";", "File", "imageDir", "=", "path", ".", "toFile", "(", ")", ";", "//get Ghostscript instance\r", "Ghostscript", "gs", "=", "Ghostscript", ".", "getInstance", "(", ")", ";", "//prepare Ghostscript interpreter parameters\r", "//refer to Ghostscript documentation for parameter usage\r", "List", "<", "String", ">", "gsArgs", "=", "new", "ArrayList", "<", "String", ">", "(", ")", ";", "gsArgs", ".", "add", "(", "\"-gs\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dNOPAUSE\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dQUIET\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dBATCH\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dSAFER\"", ")", ";", "gsArgs", ".", "add", "(", "\"-sDEVICE=pnggray\"", ")", ";", "gsArgs", ".", "add", "(", "\"-r300\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dGraphicsAlphaBits=4\"", ")", ";", "gsArgs", ".", "add", "(", "\"-dTextAlphaBits=4\"", ")", ";", "gsArgs", ".", "add", "(", "\"-sOutputFile=\"", "+", "imageDir", ".", "getPath", "(", ")", "+", "\"/workingimage%04d.png\"", ")", ";", "gsArgs", ".", "add", "(", "inputPdfFile", ".", "getPath", "(", ")", ")", ";", "//execute and exit interpreter\r", "try", "{", "synchronized", "(", "gs", ")", "{", "gs", ".", "initialize", "(", "gsArgs", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ")", ";", "gs", ".", "exit", "(", ")", ";", "}", "}", "catch", "(", "UnsatisfiedLinkError", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "new", "RuntimeException", "(", "getMessage", "(", "e", ".", "getMessage", "(", ")", ")", ")", ";", "}", "catch", "(", "NoClassDefFoundError", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "new", "RuntimeException", "(", "getMessage", "(", "e", ".", "getMessage", "(", ")", ")", ")", ";", "}", "catch", "(", "GhostscriptException", "e", ")", "{", "logger", ".", "error", "(", "e", ".", "getMessage", "(", ")", ")", ";", "throw", "new", "RuntimeException", "(", "e", ".", "getMessage", "(", ")", ")", ";", "}", "finally", "{", "if", "(", "imageDir", ".", "list", "(", ")", ".", "length", "==", "0", ")", "{", "imageDir", ".", "delete", "(", ")", ";", "}", "//delete interpreter instance (safer)\r", "try", "{", "Ghostscript", ".", "deleteInstance", "(", ")", ";", "}", "catch", "(", "GhostscriptException", "e", ")", "{", "//nothing\r", "}", "}", "// find working files\r", "File", "[", "]", "workingFiles", "=", "imageDir", ".", "listFiles", "(", "new", "FilenameFilter", "(", ")", "{", "@", "Override", "public", "boolean", "accept", "(", "File", "dir", ",", "String", "name", ")", "{", "return", "name", ".", "toLowerCase", "(", ")", ".", "matches", "(", "\"workingimage\\\\d{4}\\\\.png$\"", ")", ";", "}", "}", ")", ";", "Arrays", ".", "sort", "(", "workingFiles", ",", "new", "Comparator", "<", "File", ">", "(", ")", "{", "@", "Override", "public", "int", "compare", "(", "File", "f1", ",", "File", "f2", ")", "{", "return", "f1", ".", "getName", "(", ")", ".", "compareTo", "(", "f2", ".", "getName", "(", ")", ")", ";", "}", "}", ")", ";", "return", "workingFiles", ";", "}" ]
Converts PDF to PNG format. @param inputPdfFile input file @return an array of PNG images @throws java.io.IOException
[ "Converts", "PDF", "to", "PNG", "format", "." ]
train
https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/PdfGsUtilities.java#L80-L147
lookfirst/WePay-Java-SDK
src/main/java/com/lookfirst/wepay/WePayApi.java
WePayApi.getAuthorizationUri
public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { """ Generate URI used during oAuth authorization Redirect your user to this URI where they can grant your application permission to make API calls @see <a href="https://www.wepay.com/developer/reference/oauth2">https://www.wepay.com/developer/reference/oauth2</a> @param scopes List of scope fields for which your application wants access @param redirectUri Where user goes after logging in at WePay (domain must match application settings) @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri @return string URI to which you must redirect your user to grant access to your application """ // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; }
java
public String getAuthorizationUri(List<Scope> scopes, String redirectUri, String state, String userName, String userEmail) { // this method must use www instead of just naked domain for security reasons. String host = key.isProduction() ? "https://www.wepay.com" : "https://stage.wepay.com"; String uri = host + "/v2/oauth2/authorize?"; uri += "client_id=" + urlEncode(key.getClientId()) + "&"; uri += "redirect_uri=" + urlEncode(redirectUri) + "&"; uri += "scope=" + urlEncode(StringUtils.join(scopes, ",")); if (state != null || userName != null || userEmail != null) uri += "&"; uri += state != null ? "state=" + urlEncode(state) + "&" : ""; uri += userName != null ? "user_name=" + urlEncode(userName) + "&" : ""; uri += userEmail != null ? "user_email=" + urlEncode(userEmail) : ""; return uri; }
[ "public", "String", "getAuthorizationUri", "(", "List", "<", "Scope", ">", "scopes", ",", "String", "redirectUri", ",", "String", "state", ",", "String", "userName", ",", "String", "userEmail", ")", "{", "// this method must use www instead of just naked domain for security reasons.", "String", "host", "=", "key", ".", "isProduction", "(", ")", "?", "\"https://www.wepay.com\"", ":", "\"https://stage.wepay.com\"", ";", "String", "uri", "=", "host", "+", "\"/v2/oauth2/authorize?\"", ";", "uri", "+=", "\"client_id=\"", "+", "urlEncode", "(", "key", ".", "getClientId", "(", ")", ")", "+", "\"&\"", ";", "uri", "+=", "\"redirect_uri=\"", "+", "urlEncode", "(", "redirectUri", ")", "+", "\"&\"", ";", "uri", "+=", "\"scope=\"", "+", "urlEncode", "(", "StringUtils", ".", "join", "(", "scopes", ",", "\",\"", ")", ")", ";", "if", "(", "state", "!=", "null", "||", "userName", "!=", "null", "||", "userEmail", "!=", "null", ")", "uri", "+=", "\"&\"", ";", "uri", "+=", "state", "!=", "null", "?", "\"state=\"", "+", "urlEncode", "(", "state", ")", "+", "\"&\"", ":", "\"\"", ";", "uri", "+=", "userName", "!=", "null", "?", "\"user_name=\"", "+", "urlEncode", "(", "userName", ")", "+", "\"&\"", ":", "\"\"", ";", "uri", "+=", "userEmail", "!=", "null", "?", "\"user_email=\"", "+", "urlEncode", "(", "userEmail", ")", ":", "\"\"", ";", "return", "uri", ";", "}" ]
Generate URI used during oAuth authorization Redirect your user to this URI where they can grant your application permission to make API calls @see <a href="https://www.wepay.com/developer/reference/oauth2">https://www.wepay.com/developer/reference/oauth2</a> @param scopes List of scope fields for which your application wants access @param redirectUri Where user goes after logging in at WePay (domain must match application settings) @param userName user_name,user_email which will be pre-filled on login form, state to be returned in querystring of redirect_uri @return string URI to which you must redirect your user to grant access to your application
[ "Generate", "URI", "used", "during", "oAuth", "authorization", "Redirect", "your", "user", "to", "this", "URI", "where", "they", "can", "grant", "your", "application", "permission", "to", "make", "API", "calls" ]
train
https://github.com/lookfirst/WePay-Java-SDK/blob/3c0a47d6fa051d531c8fdbbfd54a0ef2891aa8f0/src/main/java/com/lookfirst/wepay/WePayApi.java#L176-L191
Ordinastie/MalisisCore
src/main/java/net/malisis/core/block/component/WallComponent.java
WallComponent.mergeBlock
@Override public IBlockState mergeBlock(World world, BlockPos pos, IBlockState state, ItemStack itemStack, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ) { """ Merges the {@link IBlockState} into a corner if possible. @param world the world @param pos the pos @param state the state @param itemStack the item stack @param player the player @param side the side @param hitX the hit x @param hitY the hit y @param hitZ the hit z @return the i block state """ EnumFacing direction = DirectionalComponent.getDirection(state); EnumFacing realSide = EnumFacingUtils.getRealSide(state, side); if (realSide == EnumFacing.EAST && hitX == 1) return null; if (realSide == EnumFacing.WEST && hitX == 0) return null; if (realSide == EnumFacing.UP && hitY == 1) return null; if (realSide == EnumFacing.DOWN && hitX == 0) return null; boolean rotate = false; switch (direction) { case SOUTH: rotate = hitX < 0.5F; break; case NORTH: rotate = hitX >= 0.5F; break; case WEST: rotate = hitZ < 0.5F; break; case EAST: rotate = hitZ >= 0.5F; break; default: break; } if (rotate) state = DirectionalComponent.rotate(state); return state.withProperty(getProperty(), true); }
java
@Override public IBlockState mergeBlock(World world, BlockPos pos, IBlockState state, ItemStack itemStack, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ) { EnumFacing direction = DirectionalComponent.getDirection(state); EnumFacing realSide = EnumFacingUtils.getRealSide(state, side); if (realSide == EnumFacing.EAST && hitX == 1) return null; if (realSide == EnumFacing.WEST && hitX == 0) return null; if (realSide == EnumFacing.UP && hitY == 1) return null; if (realSide == EnumFacing.DOWN && hitX == 0) return null; boolean rotate = false; switch (direction) { case SOUTH: rotate = hitX < 0.5F; break; case NORTH: rotate = hitX >= 0.5F; break; case WEST: rotate = hitZ < 0.5F; break; case EAST: rotate = hitZ >= 0.5F; break; default: break; } if (rotate) state = DirectionalComponent.rotate(state); return state.withProperty(getProperty(), true); }
[ "@", "Override", "public", "IBlockState", "mergeBlock", "(", "World", "world", ",", "BlockPos", "pos", ",", "IBlockState", "state", ",", "ItemStack", "itemStack", ",", "EntityPlayer", "player", ",", "EnumFacing", "side", ",", "float", "hitX", ",", "float", "hitY", ",", "float", "hitZ", ")", "{", "EnumFacing", "direction", "=", "DirectionalComponent", ".", "getDirection", "(", "state", ")", ";", "EnumFacing", "realSide", "=", "EnumFacingUtils", ".", "getRealSide", "(", "state", ",", "side", ")", ";", "if", "(", "realSide", "==", "EnumFacing", ".", "EAST", "&&", "hitX", "==", "1", ")", "return", "null", ";", "if", "(", "realSide", "==", "EnumFacing", ".", "WEST", "&&", "hitX", "==", "0", ")", "return", "null", ";", "if", "(", "realSide", "==", "EnumFacing", ".", "UP", "&&", "hitY", "==", "1", ")", "return", "null", ";", "if", "(", "realSide", "==", "EnumFacing", ".", "DOWN", "&&", "hitX", "==", "0", ")", "return", "null", ";", "boolean", "rotate", "=", "false", ";", "switch", "(", "direction", ")", "{", "case", "SOUTH", ":", "rotate", "=", "hitX", "<", "0.5F", ";", "break", ";", "case", "NORTH", ":", "rotate", "=", "hitX", ">=", "0.5F", ";", "break", ";", "case", "WEST", ":", "rotate", "=", "hitZ", "<", "0.5F", ";", "break", ";", "case", "EAST", ":", "rotate", "=", "hitZ", ">=", "0.5F", ";", "break", ";", "default", ":", "break", ";", "}", "if", "(", "rotate", ")", "state", "=", "DirectionalComponent", ".", "rotate", "(", "state", ")", ";", "return", "state", ".", "withProperty", "(", "getProperty", "(", ")", ",", "true", ")", ";", "}" ]
Merges the {@link IBlockState} into a corner if possible. @param world the world @param pos the pos @param state the state @param itemStack the item stack @param player the player @param side the side @param hitX the hit x @param hitY the hit y @param hitZ the hit z @return the i block state
[ "Merges", "the", "{", "@link", "IBlockState", "}", "into", "a", "corner", "if", "possible", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/block/component/WallComponent.java#L131-L169
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.getVirtualMachineScaleSetNetworkInterfaceAsync
public Observable<NetworkInterfaceInner> getVirtualMachineScaleSetNetworkInterfaceAsync(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String expand) { """ Get the specified network interface in a virtual machine scale set. @param resourceGroupName The name of the resource group. @param virtualMachineScaleSetName The name of the virtual machine scale set. @param virtualmachineIndex The virtual machine index. @param networkInterfaceName The name of the network interface. @param expand Expands referenced resources. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkInterfaceInner object """ return getVirtualMachineScaleSetNetworkInterfaceWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).map(new Func1<ServiceResponse<NetworkInterfaceInner>, NetworkInterfaceInner>() { @Override public NetworkInterfaceInner call(ServiceResponse<NetworkInterfaceInner> response) { return response.body(); } }); }
java
public Observable<NetworkInterfaceInner> getVirtualMachineScaleSetNetworkInterfaceAsync(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String expand) { return getVirtualMachineScaleSetNetworkInterfaceWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, expand).map(new Func1<ServiceResponse<NetworkInterfaceInner>, NetworkInterfaceInner>() { @Override public NetworkInterfaceInner call(ServiceResponse<NetworkInterfaceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NetworkInterfaceInner", ">", "getVirtualMachineScaleSetNetworkInterfaceAsync", "(", "String", "resourceGroupName", ",", "String", "virtualMachineScaleSetName", ",", "String", "virtualmachineIndex", ",", "String", "networkInterfaceName", ",", "String", "expand", ")", "{", "return", "getVirtualMachineScaleSetNetworkInterfaceWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualMachineScaleSetName", ",", "virtualmachineIndex", ",", "networkInterfaceName", ",", "expand", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "NetworkInterfaceInner", ">", ",", "NetworkInterfaceInner", ">", "(", ")", "{", "@", "Override", "public", "NetworkInterfaceInner", "call", "(", "ServiceResponse", "<", "NetworkInterfaceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Get the specified network interface in a virtual machine scale set. @param resourceGroupName The name of the resource group. @param virtualMachineScaleSetName The name of the virtual machine scale set. @param virtualmachineIndex The virtual machine index. @param networkInterfaceName The name of the network interface. @param expand Expands referenced resources. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkInterfaceInner object
[ "Get", "the", "specified", "network", "interface", "in", "a", "virtual", "machine", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L1872-L1879
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.beginResumeWithServiceResponseAsync
public Observable<ServiceResponse<Page<SiteInner>>> beginResumeWithServiceResponseAsync(final String resourceGroupName, final String name) { """ Resume an App Service Environment. Resume an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SiteInner&gt; object """ return beginResumeSinglePageAsync(resourceGroupName, name) .concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() { @Override public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(beginResumeNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<SiteInner>>> beginResumeWithServiceResponseAsync(final String resourceGroupName, final String name) { return beginResumeSinglePageAsync(resourceGroupName, name) .concatMap(new Func1<ServiceResponse<Page<SiteInner>>, Observable<ServiceResponse<Page<SiteInner>>>>() { @Override public Observable<ServiceResponse<Page<SiteInner>>> call(ServiceResponse<Page<SiteInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(beginResumeNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", ">", "beginResumeWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "name", ")", "{", "return", "beginResumeSinglePageAsync", "(", "resourceGroupName", ",", "name", ")", ".", "concatMap", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", ",", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", ">", ">", "(", ")", "{", "@", "Override", "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "SiteInner", ">", ">", "page", ")", "{", "String", "nextPageLink", "=", "page", ".", "body", "(", ")", ".", "nextPageLink", "(", ")", ";", "if", "(", "nextPageLink", "==", "null", ")", "{", "return", "Observable", ".", "just", "(", "page", ")", ";", "}", "return", "Observable", ".", "just", "(", "page", ")", ".", "concatWith", "(", "beginResumeNextWithServiceResponseAsync", "(", "nextPageLink", ")", ")", ";", "}", "}", ")", ";", "}" ]
Resume an App Service Environment. Resume an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SiteInner&gt; object
[ "Resume", "an", "App", "Service", "Environment", ".", "Resume", "an", "App", "Service", "Environment", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L3998-L4010
erlang/otp
lib/jinterface/java_src/com/ericsson/otp/erlang/OtpConnection.java
OtpConnection.sendBuf
public void sendBuf(final OtpErlangPid dest, final OtpOutputStream payload) throws IOException { """ Send a pre-encoded message to a process on a remote node. @param dest the Erlang PID of the remote process. @param payload the encoded message to send. @exception java.io.IOException if the connection is not active or a communication error occurs. """ super.sendBuf(self.pid(), dest, payload); }
java
public void sendBuf(final OtpErlangPid dest, final OtpOutputStream payload) throws IOException { super.sendBuf(self.pid(), dest, payload); }
[ "public", "void", "sendBuf", "(", "final", "OtpErlangPid", "dest", ",", "final", "OtpOutputStream", "payload", ")", "throws", "IOException", "{", "super", ".", "sendBuf", "(", "self", ".", "pid", "(", ")", ",", "dest", ",", "payload", ")", ";", "}" ]
Send a pre-encoded message to a process on a remote node. @param dest the Erlang PID of the remote process. @param payload the encoded message to send. @exception java.io.IOException if the connection is not active or a communication error occurs.
[ "Send", "a", "pre", "-", "encoded", "message", "to", "a", "process", "on", "a", "remote", "node", "." ]
train
https://github.com/erlang/otp/blob/ac6084fd83240355f72e94adbf303e57832d1fab/lib/jinterface/java_src/com/ericsson/otp/erlang/OtpConnection.java#L412-L415
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/PersistenceXMLLoader.java
PersistenceXMLLoader.findPersistenceUnits
public static List<PersistenceUnitMetadata> findPersistenceUnits(URL url, final String[] persistenceUnits) throws Exception { """ Find persistence units. @param url the url @return the list @throws Exception the exception """ return findPersistenceUnits(url, persistenceUnits, PersistenceUnitTransactionType.JTA); }
java
public static List<PersistenceUnitMetadata> findPersistenceUnits(URL url, final String[] persistenceUnits) throws Exception { return findPersistenceUnits(url, persistenceUnits, PersistenceUnitTransactionType.JTA); }
[ "public", "static", "List", "<", "PersistenceUnitMetadata", ">", "findPersistenceUnits", "(", "URL", "url", ",", "final", "String", "[", "]", "persistenceUnits", ")", "throws", "Exception", "{", "return", "findPersistenceUnits", "(", "url", ",", "persistenceUnits", ",", "PersistenceUnitTransactionType", ".", "JTA", ")", ";", "}" ]
Find persistence units. @param url the url @return the list @throws Exception the exception
[ "Find", "persistence", "units", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/loader/PersistenceXMLLoader.java#L247-L251
jbundle/osgi
obr/src/main/java/org/jbundle/util/osgi/obr/ObrClassFinderService.java
ObrClassFinderService.isResourceBundleMatch
public boolean isResourceBundleMatch(Object objResource, Bundle bundle) { """ Does this resource match this bundle? @param resource @param context @return """ Resource resource = (Resource)objResource; return ((bundle.getSymbolicName().equals(resource.getSymbolicName())) && (isValidVersion(bundle.getVersion(), resource.getVersion().toString()))); }
java
public boolean isResourceBundleMatch(Object objResource, Bundle bundle) { Resource resource = (Resource)objResource; return ((bundle.getSymbolicName().equals(resource.getSymbolicName())) && (isValidVersion(bundle.getVersion(), resource.getVersion().toString()))); }
[ "public", "boolean", "isResourceBundleMatch", "(", "Object", "objResource", ",", "Bundle", "bundle", ")", "{", "Resource", "resource", "=", "(", "Resource", ")", "objResource", ";", "return", "(", "(", "bundle", ".", "getSymbolicName", "(", ")", ".", "equals", "(", "resource", ".", "getSymbolicName", "(", ")", ")", ")", "&&", "(", "isValidVersion", "(", "bundle", ".", "getVersion", "(", ")", ",", "resource", ".", "getVersion", "(", ")", ".", "toString", "(", ")", ")", ")", ")", ";", "}" ]
Does this resource match this bundle? @param resource @param context @return
[ "Does", "this", "resource", "match", "this", "bundle?" ]
train
https://github.com/jbundle/osgi/blob/beb02aef78736a4f799aaac001c8f0327bf0536c/obr/src/main/java/org/jbundle/util/osgi/obr/ObrClassFinderService.java#L336-L340