repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
alkacon/opencms-core
src-gwt/org/opencms/ugc/client/CmsUgcWrapper.java
CmsUgcWrapper.uploadFields
public void uploadFields( final Set<String> fields, final Function<Map<String, String>, Void> filenameCallback, final I_CmsErrorCallback errorCallback) { disableAllFileFieldsExcept(fields); final String id = CmsJsUtils.generateRandomId(); updateFormAction(id); // Using an array here because we can only store the handler registration after it has been created , but final HandlerRegistration[] registration = {null}; registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() { @SuppressWarnings("synthetic-access") public void onSubmitComplete(SubmitCompleteEvent event) { enableAllFileFields(); registration[0].removeHandler(); CmsUUID sessionId = m_formSession.internalGetSessionId(); RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles( sessionId, fields, id, new AsyncCallback<Map<String, String>>() { public void onFailure(Throwable caught) { m_formSession.getContentFormApi().handleError(caught, errorCallback); } public void onSuccess(Map<String, String> fileNames) { filenameCallback.apply(fileNames); } }); m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder); m_formSession.getContentFormApi().getRequestCounter().decrement(); } }); m_formSession.getContentFormApi().getRequestCounter().increment(); submit(); }
java
public void uploadFields( final Set<String> fields, final Function<Map<String, String>, Void> filenameCallback, final I_CmsErrorCallback errorCallback) { disableAllFileFieldsExcept(fields); final String id = CmsJsUtils.generateRandomId(); updateFormAction(id); // Using an array here because we can only store the handler registration after it has been created , but final HandlerRegistration[] registration = {null}; registration[0] = addSubmitCompleteHandler(new SubmitCompleteHandler() { @SuppressWarnings("synthetic-access") public void onSubmitComplete(SubmitCompleteEvent event) { enableAllFileFields(); registration[0].removeHandler(); CmsUUID sessionId = m_formSession.internalGetSessionId(); RequestBuilder requestBuilder = CmsXmlContentUgcApi.SERVICE.uploadFiles( sessionId, fields, id, new AsyncCallback<Map<String, String>>() { public void onFailure(Throwable caught) { m_formSession.getContentFormApi().handleError(caught, errorCallback); } public void onSuccess(Map<String, String> fileNames) { filenameCallback.apply(fileNames); } }); m_formSession.getContentFormApi().getRpcHelper().executeRpc(requestBuilder); m_formSession.getContentFormApi().getRequestCounter().decrement(); } }); m_formSession.getContentFormApi().getRequestCounter().increment(); submit(); }
[ "public", "void", "uploadFields", "(", "final", "Set", "<", "String", ">", "fields", ",", "final", "Function", "<", "Map", "<", "String", ",", "String", ">", ",", "Void", ">", "filenameCallback", ",", "final", "I_CmsErrorCallback", "errorCallback", ")", "{",...
Uploads files from the given file input fields.<p< @param fields the set of names of fields containing the files to upload @param filenameCallback the callback to call with the resulting map from field names to file paths @param errorCallback the callback to call with an error message
[ "Uploads", "files", "from", "the", "given", "file", "input", "fields", ".", "<p<" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ugc/client/CmsUgcWrapper.java#L99-L141
lessthanoptimal/BoofCV
examples/src/main/java/boofcv/examples/stereo/ExampleFundamentalMatrix.java
ExampleFundamentalMatrix.computeMatches
public static List<AssociatedPair> computeMatches( BufferedImage left , BufferedImage right ) { DetectDescribePoint detDesc = FactoryDetectDescribe.surfStable( new ConfigFastHessian(0, 2, 400, 1, 9, 4, 4), null,null, GrayF32.class); // DetectDescribePoint detDesc = FactoryDetectDescribe.sift(null,new ConfigSiftDetector(2,0,200,5),null,null); ScoreAssociation<BrightFeature> scorer = FactoryAssociation.scoreEuclidean(BrightFeature.class,true); AssociateDescription<BrightFeature> associate = FactoryAssociation.greedy(scorer, 0.1, true); ExampleAssociatePoints<GrayF32,BrightFeature> findMatches = new ExampleAssociatePoints<>(detDesc, associate, GrayF32.class); findMatches.associate(left,right); List<AssociatedPair> matches = new ArrayList<>(); FastQueue<AssociatedIndex> matchIndexes = associate.getMatches(); for( int i = 0; i < matchIndexes.size; i++ ) { AssociatedIndex a = matchIndexes.get(i); AssociatedPair p = new AssociatedPair(findMatches.pointsA.get(a.src) , findMatches.pointsB.get(a.dst)); matches.add( p); } return matches; }
java
public static List<AssociatedPair> computeMatches( BufferedImage left , BufferedImage right ) { DetectDescribePoint detDesc = FactoryDetectDescribe.surfStable( new ConfigFastHessian(0, 2, 400, 1, 9, 4, 4), null,null, GrayF32.class); // DetectDescribePoint detDesc = FactoryDetectDescribe.sift(null,new ConfigSiftDetector(2,0,200,5),null,null); ScoreAssociation<BrightFeature> scorer = FactoryAssociation.scoreEuclidean(BrightFeature.class,true); AssociateDescription<BrightFeature> associate = FactoryAssociation.greedy(scorer, 0.1, true); ExampleAssociatePoints<GrayF32,BrightFeature> findMatches = new ExampleAssociatePoints<>(detDesc, associate, GrayF32.class); findMatches.associate(left,right); List<AssociatedPair> matches = new ArrayList<>(); FastQueue<AssociatedIndex> matchIndexes = associate.getMatches(); for( int i = 0; i < matchIndexes.size; i++ ) { AssociatedIndex a = matchIndexes.get(i); AssociatedPair p = new AssociatedPair(findMatches.pointsA.get(a.src) , findMatches.pointsB.get(a.dst)); matches.add( p); } return matches; }
[ "public", "static", "List", "<", "AssociatedPair", ">", "computeMatches", "(", "BufferedImage", "left", ",", "BufferedImage", "right", ")", "{", "DetectDescribePoint", "detDesc", "=", "FactoryDetectDescribe", ".", "surfStable", "(", "new", "ConfigFastHessian", "(", ...
Use the associate point feature example to create a list of {@link AssociatedPair} for use in computing the fundamental matrix.
[ "Use", "the", "associate", "point", "feature", "example", "to", "create", "a", "list", "of", "{" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/stereo/ExampleFundamentalMatrix.java#L131-L154
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/map/cache/TileCache.java
TileCache.calcCodesForBounds
protected List<TileCode> calcCodesForBounds(Bbox bounds) { // Calculate tile width and height for tileLevel=currentTileLevel double div = Math.pow(2, currentTileLevel); // tile level must be correct! double scale = layer.getMapModel().getMapView().getCurrentScale(); double tileWidth = Math.ceil((scale * layerBounds.getWidth()) / div) / scale; double tileHeight = Math.ceil((scale * layerBounds.getHeight()) / div) / scale; // For safety (to prevent division by 0): List<TileCode> codes = new ArrayList<TileCode>(); if (tileWidth == 0 || tileHeight == 0) { return codes; } // Calculate bounds relative to extents: Bbox clippedBounds = bounds.intersection(layerBounds); if (clippedBounds == null) { Log.logError("Map bounds outside of layer extents, check the server configuration, it is incorrect."); return codes; } double relativeBoundX = Math.abs(clippedBounds.getX() - layerBounds.getX()); double relativeBoundY = Math.abs(clippedBounds.getY() - layerBounds.getY()); currentMinX = (int) Math.floor(relativeBoundX / tileWidth); currentMinY = (int) Math.floor(relativeBoundY / tileHeight); currentMaxX = (int) Math.ceil((relativeBoundX + clippedBounds.getWidth()) / tileWidth) - 1; currentMaxY = (int) Math.ceil((relativeBoundY + clippedBounds.getHeight()) / tileHeight) - 1; // Now fill the list with the correct codes: for (int x = currentMinX; x <= currentMaxX; x++) { for (int y = currentMinY; y <= currentMaxY; y++) { codes.add(new TileCode(currentTileLevel, x, y)); } } return codes; }
java
protected List<TileCode> calcCodesForBounds(Bbox bounds) { // Calculate tile width and height for tileLevel=currentTileLevel double div = Math.pow(2, currentTileLevel); // tile level must be correct! double scale = layer.getMapModel().getMapView().getCurrentScale(); double tileWidth = Math.ceil((scale * layerBounds.getWidth()) / div) / scale; double tileHeight = Math.ceil((scale * layerBounds.getHeight()) / div) / scale; // For safety (to prevent division by 0): List<TileCode> codes = new ArrayList<TileCode>(); if (tileWidth == 0 || tileHeight == 0) { return codes; } // Calculate bounds relative to extents: Bbox clippedBounds = bounds.intersection(layerBounds); if (clippedBounds == null) { Log.logError("Map bounds outside of layer extents, check the server configuration, it is incorrect."); return codes; } double relativeBoundX = Math.abs(clippedBounds.getX() - layerBounds.getX()); double relativeBoundY = Math.abs(clippedBounds.getY() - layerBounds.getY()); currentMinX = (int) Math.floor(relativeBoundX / tileWidth); currentMinY = (int) Math.floor(relativeBoundY / tileHeight); currentMaxX = (int) Math.ceil((relativeBoundX + clippedBounds.getWidth()) / tileWidth) - 1; currentMaxY = (int) Math.ceil((relativeBoundY + clippedBounds.getHeight()) / tileHeight) - 1; // Now fill the list with the correct codes: for (int x = currentMinX; x <= currentMaxX; x++) { for (int y = currentMinY; y <= currentMaxY; y++) { codes.add(new TileCode(currentTileLevel, x, y)); } } return codes; }
[ "protected", "List", "<", "TileCode", ">", "calcCodesForBounds", "(", "Bbox", "bounds", ")", "{", "// Calculate tile width and height for tileLevel=currentTileLevel", "double", "div", "=", "Math", ".", "pow", "(", "2", ",", "currentTileLevel", ")", ";", "// tile level...
Saves the complete array of TileCode objects for the given bounds (and the current scale). @param bounds view bounds @return list of tiles in these bounds
[ "Saves", "the", "complete", "array", "of", "TileCode", "objects", "for", "the", "given", "bounds", "(", "and", "the", "current", "scale", ")", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/map/cache/TileCache.java#L316-L349
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/io/IOUtils.java
IOUtils.stringFromFile
public static String stringFromFile(String filename, String encoding) { try { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new EncodingFileReader(filename,encoding)); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append(eolChar); } in.close(); return sb.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }
java
public static String stringFromFile(String filename, String encoding) { try { StringBuilder sb = new StringBuilder(); BufferedReader in = new BufferedReader(new EncodingFileReader(filename,encoding)); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append(eolChar); } in.close(); return sb.toString(); } catch (IOException e) { e.printStackTrace(); return null; } }
[ "public", "static", "String", "stringFromFile", "(", "String", "filename", ",", "String", "encoding", ")", "{", "try", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "BufferedReader", "in", "=", "new", "BufferedReader", "(", "new", "...
Returns the contents of a file as a single string. The string may be empty, if the file is empty. If there is an IOException, it is caught and null is returned. Encoding can also be specified.
[ "Returns", "the", "contents", "of", "a", "file", "as", "a", "single", "string", ".", "The", "string", "may", "be", "empty", "if", "the", "file", "is", "empty", ".", "If", "there", "is", "an", "IOException", "it", "is", "caught", "and", "null", "is", ...
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/io/IOUtils.java#L1198-L1214
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
JdbcProjectImpl.createNewProject
@Override public synchronized Project createNewProject(final String name, final String description, final User creator) throws ProjectManagerException { final ProjectResultHandler handler = new ProjectResultHandler(); // Check if the same project name exists. try { final List<Project> projects = this.dbOperator .query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name); if (!projects.isEmpty()) { throw new ProjectManagerException( "Active project with name " + name + " already exists in db."); } } catch (final SQLException ex) { logger.error(ex); throw new ProjectManagerException("Checking for existing project failed. " + name, ex); } final String INSERT_PROJECT = "INSERT INTO projects ( name, active, modified_time, create_time, version, last_modified_by, description, enc_type, settings_blob) values (?,?,?,?,?,?,?,?,?)"; final SQLTransaction<Integer> insertProject = transOperator -> { final long time = System.currentTimeMillis(); return transOperator .update(INSERT_PROJECT, name, true, time, time, null, creator.getUserId(), description, this.defaultEncodingType.getNumVal(), null); }; // Insert project try { final int numRowsInserted = this.dbOperator.transaction(insertProject); if (numRowsInserted == 0) { throw new ProjectManagerException("No projects have been inserted."); } } catch (final SQLException ex) { logger.error(INSERT_PROJECT + " failed.", ex); throw new ProjectManagerException("Insert project" + name + " for existing project failed. ", ex); } return fetchProjectByName(name); }
java
@Override public synchronized Project createNewProject(final String name, final String description, final User creator) throws ProjectManagerException { final ProjectResultHandler handler = new ProjectResultHandler(); // Check if the same project name exists. try { final List<Project> projects = this.dbOperator .query(ProjectResultHandler.SELECT_ACTIVE_PROJECT_BY_NAME, handler, name); if (!projects.isEmpty()) { throw new ProjectManagerException( "Active project with name " + name + " already exists in db."); } } catch (final SQLException ex) { logger.error(ex); throw new ProjectManagerException("Checking for existing project failed. " + name, ex); } final String INSERT_PROJECT = "INSERT INTO projects ( name, active, modified_time, create_time, version, last_modified_by, description, enc_type, settings_blob) values (?,?,?,?,?,?,?,?,?)"; final SQLTransaction<Integer> insertProject = transOperator -> { final long time = System.currentTimeMillis(); return transOperator .update(INSERT_PROJECT, name, true, time, time, null, creator.getUserId(), description, this.defaultEncodingType.getNumVal(), null); }; // Insert project try { final int numRowsInserted = this.dbOperator.transaction(insertProject); if (numRowsInserted == 0) { throw new ProjectManagerException("No projects have been inserted."); } } catch (final SQLException ex) { logger.error(INSERT_PROJECT + " failed.", ex); throw new ProjectManagerException("Insert project" + name + " for existing project failed. ", ex); } return fetchProjectByName(name); }
[ "@", "Override", "public", "synchronized", "Project", "createNewProject", "(", "final", "String", "name", ",", "final", "String", "description", ",", "final", "User", "creator", ")", "throws", "ProjectManagerException", "{", "final", "ProjectResultHandler", "handler",...
Creates a Project in the db. It will throw an exception if it finds an active project of the same name, or the SQL fails
[ "Creates", "a", "Project", "in", "the", "db", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java#L203-L243
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/field/PropertiesField.java
PropertiesField.setProperty
public int setProperty(String strProperty, String strValue, boolean bDisplayOption, int iMoveMode) { if (m_propertiesCache == null) m_propertiesCache = this.loadProperties(); boolean bChanged = false; // If strValue == null, delete; if = '', it's okay (key='') [a blank property]! if (strValue == null) { if (m_propertiesCache.get(strProperty) != null) { m_propertiesCache.remove(strProperty); bChanged = true; } } else { if (!strValue.equals(m_propertiesCache.get(strProperty))) { m_propertiesCache.put(strProperty, strValue); // Add this param bChanged = true; } } int iErrorCode = DBConstants.NORMAL_RETURN; if (bChanged) { // Only change if there is a change of properties (not just a change in the #date line in properties) String strProperties = this.propertiesToInternalString(m_propertiesCache); Map<String,Object> propertiesSave = m_propertiesCache; iErrorCode = this.setString(strProperties, bDisplayOption, iMoveMode); m_propertiesCache = propertiesSave; // Zeroed out in set String } return iErrorCode; }
java
public int setProperty(String strProperty, String strValue, boolean bDisplayOption, int iMoveMode) { if (m_propertiesCache == null) m_propertiesCache = this.loadProperties(); boolean bChanged = false; // If strValue == null, delete; if = '', it's okay (key='') [a blank property]! if (strValue == null) { if (m_propertiesCache.get(strProperty) != null) { m_propertiesCache.remove(strProperty); bChanged = true; } } else { if (!strValue.equals(m_propertiesCache.get(strProperty))) { m_propertiesCache.put(strProperty, strValue); // Add this param bChanged = true; } } int iErrorCode = DBConstants.NORMAL_RETURN; if (bChanged) { // Only change if there is a change of properties (not just a change in the #date line in properties) String strProperties = this.propertiesToInternalString(m_propertiesCache); Map<String,Object> propertiesSave = m_propertiesCache; iErrorCode = this.setString(strProperties, bDisplayOption, iMoveMode); m_propertiesCache = propertiesSave; // Zeroed out in set String } return iErrorCode; }
[ "public", "int", "setProperty", "(", "String", "strProperty", ",", "String", "strValue", ",", "boolean", "bDisplayOption", ",", "int", "iMoveMode", ")", "{", "if", "(", "m_propertiesCache", "==", "null", ")", "m_propertiesCache", "=", "this", ".", "loadPropertie...
Set this property in the user's property area. @param strProperty The property key. @param strValue The property value. @param iDisplayOption If true, display the new field. @param iMoveMove The move mode. @return An error code (NORMAL_RETURN for success).
[ "Set", "this", "property", "in", "the", "user", "s", "property", "area", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/field/PropertiesField.java#L140-L171
fommil/matrix-toolkits-java
src/main/java/no/uib/cipr/matrix/io/MatrixVectorReader.java
MatrixVectorReader.readVectorCoordinateSize
public VectorSize readVectorCoordinateSize() throws IOException { int size = getInt(), numEntries = getInt(); return new VectorSize(size, numEntries); }
java
public VectorSize readVectorCoordinateSize() throws IOException { int size = getInt(), numEntries = getInt(); return new VectorSize(size, numEntries); }
[ "public", "VectorSize", "readVectorCoordinateSize", "(", ")", "throws", "IOException", "{", "int", "size", "=", "getInt", "(", ")", ",", "numEntries", "=", "getInt", "(", ")", ";", "return", "new", "VectorSize", "(", "size", ",", "numEntries", ")", ";", "}...
Reads in the size of a coordinate vector. Skips initial comments
[ "Reads", "in", "the", "size", "of", "a", "coordinate", "vector", ".", "Skips", "initial", "comments" ]
train
https://github.com/fommil/matrix-toolkits-java/blob/6157618bc86bcda3749af2a60bf869d8f3292960/src/main/java/no/uib/cipr/matrix/io/MatrixVectorReader.java#L318-L322
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/NotesApi.java
NotesApi.deleteMergeRequestNote
public void deleteMergeRequestNote(Object projectIdOrPath, Integer mergeRequestIid, Integer noteId) throws GitLabApiException { if (mergeRequestIid == null) { throw new RuntimeException("mergeRequestIid cannot be null"); } if (noteId == null) { throw new RuntimeException("noteId cannot be null"); } Response.Status expectedStatus = (isApiVersion(GitLabApi.ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId); }
java
public void deleteMergeRequestNote(Object projectIdOrPath, Integer mergeRequestIid, Integer noteId) throws GitLabApiException { if (mergeRequestIid == null) { throw new RuntimeException("mergeRequestIid cannot be null"); } if (noteId == null) { throw new RuntimeException("noteId cannot be null"); } Response.Status expectedStatus = (isApiVersion(GitLabApi.ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "merge_requests", mergeRequestIid, "notes", noteId); }
[ "public", "void", "deleteMergeRequestNote", "(", "Object", "projectIdOrPath", ",", "Integer", "mergeRequestIid", ",", "Integer", "noteId", ")", "throws", "GitLabApiException", "{", "if", "(", "mergeRequestIid", "==", "null", ")", "{", "throw", "new", "RuntimeExcepti...
Delete the specified merge request's note. @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param mergeRequestIid the merge request IID to delete the notes for @param noteId the ID of the node to delete @throws GitLabApiException if any exception occurs
[ "Delete", "the", "specified", "merge", "request", "s", "note", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/NotesApi.java#L419-L432
icode/ameba
src/main/java/ameba/lib/Fibers.java
Fibers.runInFiber
public static void runInFiber(FiberScheduler scheduler, SuspendableRunnable target) throws ExecutionException, InterruptedException { FiberUtil.runInFiber(scheduler, target); }
java
public static void runInFiber(FiberScheduler scheduler, SuspendableRunnable target) throws ExecutionException, InterruptedException { FiberUtil.runInFiber(scheduler, target); }
[ "public", "static", "void", "runInFiber", "(", "FiberScheduler", "scheduler", ",", "SuspendableRunnable", "target", ")", "throws", "ExecutionException", ",", "InterruptedException", "{", "FiberUtil", ".", "runInFiber", "(", "scheduler", ",", "target", ")", ";", "}" ...
Runs an action in a new fiber and awaits the fiber's termination. @param scheduler the {@link FiberScheduler} to use when scheduling the fiber. @param target the operation @throws ExecutionException @throws InterruptedException
[ "Runs", "an", "action", "in", "a", "new", "fiber", "and", "awaits", "the", "fiber", "s", "termination", "." ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/lib/Fibers.java#L287-L289
playn/playn
core/src/playn/core/GLBatch.java
GLBatch.begin
public void begin (float fbufWidth, float fbufHeight, boolean flip) { if (begun) throw new IllegalStateException(getClass().getSimpleName() + " mismatched begin()"); begun = true; }
java
public void begin (float fbufWidth, float fbufHeight, boolean flip) { if (begun) throw new IllegalStateException(getClass().getSimpleName() + " mismatched begin()"); begun = true; }
[ "public", "void", "begin", "(", "float", "fbufWidth", ",", "float", "fbufHeight", ",", "boolean", "flip", ")", "{", "if", "(", "begun", ")", "throw", "new", "IllegalStateException", "(", "getClass", "(", ")", ".", "getSimpleName", "(", ")", "+", "\" mismat...
Must be called before this batch is used to accumulate and send drawing commands. @param flip whether or not to flip the y-axis. This is generally true when rendering to the default frame buffer (the screen), and false when rendering to textures.
[ "Must", "be", "called", "before", "this", "batch", "is", "used", "to", "accumulate", "and", "send", "drawing", "commands", "." ]
train
https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/core/src/playn/core/GLBatch.java#L32-L35
airlift/slice
src/main/java/io/airlift/slice/Slices.java
Slices.wrappedShortArray
public static Slice wrappedShortArray(short[] array, int offset, int length) { if (length == 0) { return EMPTY_SLICE; } return new Slice(array, offset, length); }
java
public static Slice wrappedShortArray(short[] array, int offset, int length) { if (length == 0) { return EMPTY_SLICE; } return new Slice(array, offset, length); }
[ "public", "static", "Slice", "wrappedShortArray", "(", "short", "[", "]", "array", ",", "int", "offset", ",", "int", "length", ")", "{", "if", "(", "length", "==", "0", ")", "{", "return", "EMPTY_SLICE", ";", "}", "return", "new", "Slice", "(", "array"...
Creates a slice over the specified array range. @param offset the array position at which the slice begins @param length the number of array positions to include in the slice
[ "Creates", "a", "slice", "over", "the", "specified", "array", "range", "." ]
train
https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/Slices.java#L193-L199
jronrun/benayn
benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java
Strs.endAny
public static boolean endAny(String target, String... endWith) { return endAny(target, Arrays.asList(endWith)); }
java
public static boolean endAny(String target, String... endWith) { return endAny(target, Arrays.asList(endWith)); }
[ "public", "static", "boolean", "endAny", "(", "String", "target", ",", "String", "...", "endWith", ")", "{", "return", "endAny", "(", "target", ",", "Arrays", ".", "asList", "(", "endWith", ")", ")", ";", "}" ]
Check if target string ends with any of an array of specified strings. @param target @param endWith @return
[ "Check", "if", "target", "string", "ends", "with", "any", "of", "an", "array", "of", "specified", "strings", "." ]
train
https://github.com/jronrun/benayn/blob/7585152e10e4cac07b4274c65f1c72ad7061ae69/benayn-ustyle/src/main/java/com/benayn/ustyle/string/Strs.java#L303-L305
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java
MarkerUtil.createMarkers
public static void createMarkers(final IJavaProject javaProject, final SortedBugCollection theCollection, final ISchedulingRule rule, IProgressMonitor monitor) { if (monitor.isCanceled()) { return; } final List<MarkerParameter> bugParameters = createBugParameters(javaProject, theCollection, monitor); if (monitor.isCanceled()) { return; } WorkspaceJob wsJob = new WorkspaceJob("Creating SpotBugs markers") { @Override public IStatus runInWorkspace(IProgressMonitor monitor1) throws CoreException { IProject project = javaProject.getProject(); try { new MarkerReporter(bugParameters, theCollection, project).run(monitor1); } catch (CoreException e) { FindbugsPlugin.getDefault().logException(e, "Core exception on add marker"); return e.getStatus(); } return monitor1.isCanceled()? Status.CANCEL_STATUS : Status.OK_STATUS; } }; wsJob.setRule(rule); wsJob.setSystem(true); wsJob.setUser(false); wsJob.schedule(); }
java
public static void createMarkers(final IJavaProject javaProject, final SortedBugCollection theCollection, final ISchedulingRule rule, IProgressMonitor monitor) { if (monitor.isCanceled()) { return; } final List<MarkerParameter> bugParameters = createBugParameters(javaProject, theCollection, monitor); if (monitor.isCanceled()) { return; } WorkspaceJob wsJob = new WorkspaceJob("Creating SpotBugs markers") { @Override public IStatus runInWorkspace(IProgressMonitor monitor1) throws CoreException { IProject project = javaProject.getProject(); try { new MarkerReporter(bugParameters, theCollection, project).run(monitor1); } catch (CoreException e) { FindbugsPlugin.getDefault().logException(e, "Core exception on add marker"); return e.getStatus(); } return monitor1.isCanceled()? Status.CANCEL_STATUS : Status.OK_STATUS; } }; wsJob.setRule(rule); wsJob.setSystem(true); wsJob.setUser(false); wsJob.schedule(); }
[ "public", "static", "void", "createMarkers", "(", "final", "IJavaProject", "javaProject", ",", "final", "SortedBugCollection", "theCollection", ",", "final", "ISchedulingRule", "rule", ",", "IProgressMonitor", "monitor", ")", "{", "if", "(", "monitor", ".", "isCance...
Create an Eclipse marker for given BugInstance. @param javaProject the project @param monitor
[ "Create", "an", "Eclipse", "marker", "for", "given", "BugInstance", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java#L119-L145
lessthanoptimal/BoofCV
main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FeatureLaplacePyramid.java
FeatureLaplacePyramid.detect
@Override public void detect(PyramidFloat<T> ss) { spaceIndex = 0; foundPoints.clear(); // compute feature intensity in each level for (int i = 1; i < ss.getNumLayers()-1; i++) { // detect features in 2D space. Don't need to compute features at the tail ends of scale-space // if (i > 0 && i < ss.getNumLayers() - 1) // detectCandidateFeatures(ss.getLayer(i), ss.getSigma(i)); spaceIndex = i; detectCandidateFeatures(ss.getLayer(i), ss.getSigma(i)); // find maximum in 3xNx3 (local image and scale space) region findLocalScaleSpaceMax(ss, i); // spaceIndex++; // if (spaceIndex >= 3) // spaceIndex = 0; // // // find maximum in 3x3x3 (local image and scale space) region // if (i >= 2) { // detectCandidateFeatures(ss.getLayer(i-i), ss.getSigma(i-1)); // findLocalScaleSpaceMax(ss, i - 1); // } } }
java
@Override public void detect(PyramidFloat<T> ss) { spaceIndex = 0; foundPoints.clear(); // compute feature intensity in each level for (int i = 1; i < ss.getNumLayers()-1; i++) { // detect features in 2D space. Don't need to compute features at the tail ends of scale-space // if (i > 0 && i < ss.getNumLayers() - 1) // detectCandidateFeatures(ss.getLayer(i), ss.getSigma(i)); spaceIndex = i; detectCandidateFeatures(ss.getLayer(i), ss.getSigma(i)); // find maximum in 3xNx3 (local image and scale space) region findLocalScaleSpaceMax(ss, i); // spaceIndex++; // if (spaceIndex >= 3) // spaceIndex = 0; // // // find maximum in 3x3x3 (local image and scale space) region // if (i >= 2) { // detectCandidateFeatures(ss.getLayer(i-i), ss.getSigma(i-1)); // findLocalScaleSpaceMax(ss, i - 1); // } } }
[ "@", "Override", "public", "void", "detect", "(", "PyramidFloat", "<", "T", ">", "ss", ")", "{", "spaceIndex", "=", "0", ";", "foundPoints", ".", "clear", "(", ")", ";", "// compute feature intensity in each level", "for", "(", "int", "i", "=", "1", ";", ...
Searches for features inside the provided scale space @param ss Scale space of an image
[ "Searches", "for", "features", "inside", "the", "provided", "scale", "space" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-feature/src/main/java/boofcv/alg/feature/detect/interest/FeatureLaplacePyramid.java#L101-L127
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/EnumUtils.java
EnumUtils.getEnum
public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) { if (enumName == null) { return null; } try { return Enum.valueOf(enumClass, enumName); } catch (final IllegalArgumentException ex) { return null; } }
java
public static <E extends Enum<E>> E getEnum(final Class<E> enumClass, final String enumName) { if (enumName == null) { return null; } try { return Enum.valueOf(enumClass, enumName); } catch (final IllegalArgumentException ex) { return null; } }
[ "public", "static", "<", "E", "extends", "Enum", "<", "E", ">", ">", "E", "getEnum", "(", "final", "Class", "<", "E", ">", "enumClass", ",", "final", "String", "enumName", ")", "{", "if", "(", "enumName", "==", "null", ")", "{", "return", "null", "...
<p>Gets the enum for the class, returning {@code null} if not found.</p> <p>This method differs from {@link Enum#valueOf} in that it does not throw an exception for an invalid enum name.</p> @param <E> the type of the enumeration @param enumClass the class of the enum to query, not null @param enumName the enum name, null returns null @return the enum, null if not found
[ "<p", ">", "Gets", "the", "enum", "for", "the", "class", "returning", "{", "@code", "null", "}", "if", "not", "found", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/EnumUtils.java#L114-L123
OpenBEL/openbel-framework
org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/CacheUtil.java
CacheUtil.copyToDirectory
public static File copyToDirectory(File resource, final String resourceLocation, final File copy) throws ResourceDownloadError { copy.getParentFile().mkdirs(); return copyWithDecompression(resource, resourceLocation, copy); }
java
public static File copyToDirectory(File resource, final String resourceLocation, final File copy) throws ResourceDownloadError { copy.getParentFile().mkdirs(); return copyWithDecompression(resource, resourceLocation, copy); }
[ "public", "static", "File", "copyToDirectory", "(", "File", "resource", ",", "final", "String", "resourceLocation", ",", "final", "File", "copy", ")", "throws", "ResourceDownloadError", "{", "copy", ".", "getParentFile", "(", ")", ".", "mkdirs", "(", ")", ";",...
Copies the resolved resource to the system's temporary directory pointed to by the system property <tt>java.io.tmpdir</tt>. <p> GZIP Decompression occur on the file if the cached resource is found to contain the {@link #GZIP_MAGIC_NUMBER}. See {@link CacheUtil#copyWithDecompression(File, String, File)}. </p> @param resource {@link File}, the resource file to copy from @param resourceLocation {@link String}, the resource location url @param copy {@link File}, the resource file to copy to @return {@link File}, the resource file in the system's temp directory @throws ResourceDownloadError Thrown if an IO error copying the resource
[ "Copies", "the", "resolved", "resource", "to", "the", "system", "s", "temporary", "directory", "pointed", "to", "by", "the", "system", "property", "<tt", ">", "java", ".", "io", ".", "tmpdir<", "/", "tt", ">", ".", "<p", ">", "GZIP", "Decompression", "oc...
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.core/src/main/java/org/openbel/framework/core/df/cache/CacheUtil.java#L280-L285
google/auto
service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java
ServicesFiles.writeServiceFile
static void writeServiceFile(Collection<String> services, OutputStream output) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8)); for (String service : services) { writer.write(service); writer.newLine(); } writer.flush(); }
java
static void writeServiceFile(Collection<String> services, OutputStream output) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, UTF_8)); for (String service : services) { writer.write(service); writer.newLine(); } writer.flush(); }
[ "static", "void", "writeServiceFile", "(", "Collection", "<", "String", ">", "services", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "BufferedWriter", "writer", "=", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "output", ",...
Writes the set of service class names to a service file. @param output not {@code null}. Not closed after use. @param services a not {@code null Collection} of service class names. @throws IOException
[ "Writes", "the", "set", "of", "service", "class", "names", "to", "a", "service", "file", "." ]
train
https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java#L90-L98
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java
SerializationUtils.toJson
public static JsonNode toJson(Object obj, ClassLoader classLoader) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { if (obj == null) { return NullNode.instance; } ObjectMapper mapper = poolMapper.borrowObject(); if (mapper != null) { try { return mapper.valueToTree(obj); } finally { poolMapper.returnObject(mapper); } } throw new SerializationException("No ObjectMapper instance avaialble!"); } catch (Exception e) { throw e instanceof SerializationException ? (SerializationException) e : new SerializationException(e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
java
public static JsonNode toJson(Object obj, ClassLoader classLoader) { ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { Thread.currentThread().setContextClassLoader(classLoader); } try { if (obj == null) { return NullNode.instance; } ObjectMapper mapper = poolMapper.borrowObject(); if (mapper != null) { try { return mapper.valueToTree(obj); } finally { poolMapper.returnObject(mapper); } } throw new SerializationException("No ObjectMapper instance avaialble!"); } catch (Exception e) { throw e instanceof SerializationException ? (SerializationException) e : new SerializationException(e); } finally { Thread.currentThread().setContextClassLoader(oldClassLoader); } }
[ "public", "static", "JsonNode", "toJson", "(", "Object", "obj", ",", "ClassLoader", "classLoader", ")", "{", "ClassLoader", "oldClassLoader", "=", "Thread", ".", "currentThread", "(", ")", ".", "getContextClassLoader", "(", ")", ";", "if", "(", "classLoader", ...
Serialize an object to {@link JsonNode}, with a custom class loader. @param obj @param classLoader @return @since 0.6.2
[ "Serialize", "an", "object", "to", "{", "@link", "JsonNode", "}", "with", "a", "custom", "class", "loader", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/SerializationUtils.java#L412-L436
netty/netty
resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java
DnsNameResolver.newRedirectDnsServerStream
protected DnsServerAddressStream newRedirectDnsServerStream( @SuppressWarnings("unused") String hostname, List<InetSocketAddress> nameservers) { DnsServerAddressStream cached = authoritativeDnsServerCache().get(hostname); if (cached == null || cached.size() == 0) { // If there is no cache hit (which may be the case for example when a NoopAuthoritativeDnsServerCache // is used), we will just directly use the provided nameservers. Collections.sort(nameservers, nameServerComparator); return new SequentialDnsServerAddressStream(nameservers, 0); } return cached; }
java
protected DnsServerAddressStream newRedirectDnsServerStream( @SuppressWarnings("unused") String hostname, List<InetSocketAddress> nameservers) { DnsServerAddressStream cached = authoritativeDnsServerCache().get(hostname); if (cached == null || cached.size() == 0) { // If there is no cache hit (which may be the case for example when a NoopAuthoritativeDnsServerCache // is used), we will just directly use the provided nameservers. Collections.sort(nameservers, nameServerComparator); return new SequentialDnsServerAddressStream(nameservers, 0); } return cached; }
[ "protected", "DnsServerAddressStream", "newRedirectDnsServerStream", "(", "@", "SuppressWarnings", "(", "\"unused\"", ")", "String", "hostname", ",", "List", "<", "InetSocketAddress", ">", "nameservers", ")", "{", "DnsServerAddressStream", "cached", "=", "authoritativeDns...
Creates a new {@link DnsServerAddressStream} to following a redirected DNS query. By overriding this it provides the opportunity to sort the name servers before following a redirected DNS query. @param hostname the hostname. @param nameservers The addresses of the DNS servers which are used in the event of a redirect. This may contain resolved and unresolved addresses so the used {@link DnsServerAddressStream} must allow unresolved addresses if you want to include these as well. @return A {@link DnsServerAddressStream} which will be used to follow the DNS redirect or {@code null} if none should be followed.
[ "Creates", "a", "new", "{", "@link", "DnsServerAddressStream", "}", "to", "following", "a", "redirected", "DNS", "query", ".", "By", "overriding", "this", "it", "provides", "the", "opportunity", "to", "sort", "the", "name", "servers", "before", "following", "a...
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/resolver-dns/src/main/java/io/netty/resolver/dns/DnsNameResolver.java#L477-L487
wso2/transport-http
components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/Http2PushPromise.java
Http2PushPromise.addHeader
public void addHeader(String name, String value) { httpRequest.headers().add(name, value); }
java
public void addHeader(String name, String value) { httpRequest.headers().add(name, value); }
[ "public", "void", "addHeader", "(", "String", "name", ",", "String", "value", ")", "{", "httpRequest", ".", "headers", "(", ")", ".", "add", "(", "name", ",", "value", ")", ";", "}" ]
Adds a header to the push promise. This will not replace the value of an already exists header. @param name the header name @param value value of the header
[ "Adds", "a", "header", "to", "the", "push", "promise", ".", "This", "will", "not", "replace", "the", "value", "of", "an", "already", "exists", "header", "." ]
train
https://github.com/wso2/transport-http/blob/c51aa715b473db6c1b82a7d7b22f6e65f74df4c9/components/org.wso2.transport.http.netty/src/main/java/org/wso2/transport/http/netty/message/Http2PushPromise.java#L98-L100
blackdoor/blackdoor
src/main/java/black/door/json/Derulo.java
Derulo.toJSON
public static String toJSON(int indent, Object object) { return toJSON(indent, 1, object, true).toString(); }
java
public static String toJSON(int indent, Object object) { return toJSON(indent, 1, object, true).toString(); }
[ "public", "static", "String", "toJSON", "(", "int", "indent", ",", "Object", "object", ")", "{", "return", "toJSON", "(", "indent", ",", "1", ",", "object", ",", "true", ")", ".", "toString", "(", ")", ";", "}" ]
Serializes object as a JSON string. Map objects are serialized as JSON objects, List objects are serialized as JSON arrays. Numbers, Booleans, and null are all serialized to their respective JSON types. Other classes will be serialised using object.toJSONString if they have it, otherwise they will be serialized using String.valueOf(object). @param indent the number of spaces to indent the output between elements @param object the object to serialize @return the JSON string representation of object
[ "Serializes", "object", "as", "a", "JSON", "string", ".", "Map", "objects", "are", "serialized", "as", "JSON", "objects", "List", "objects", "are", "serialized", "as", "JSON", "arrays", ".", "Numbers", "Booleans", "and", "null", "are", "all", "serialized", "...
train
https://github.com/blackdoor/blackdoor/blob/060c7a71dfafb85e10e8717736e6d3160262e96b/src/main/java/black/door/json/Derulo.java#L185-L187
tipsy/javalin
src/main/java/io/javalin/Javalin.java
Javalin.sse
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client) { return sse(path, client, new HashSet<>()); }
java
public Javalin sse(@NotNull String path, @NotNull Consumer<SseClient> client) { return sse(path, client, new HashSet<>()); }
[ "public", "Javalin", "sse", "(", "@", "NotNull", "String", "path", ",", "@", "NotNull", "Consumer", "<", "SseClient", ">", "client", ")", "{", "return", "sse", "(", "path", ",", "client", ",", "new", "HashSet", "<>", "(", ")", ")", ";", "}" ]
Adds a lambda handler for a Server Sent Event connection on the specified path.
[ "Adds", "a", "lambda", "handler", "for", "a", "Server", "Sent", "Event", "connection", "on", "the", "specified", "path", "." ]
train
https://github.com/tipsy/javalin/blob/68b2f7592f237db1c2b597e645697eb75fdaee53/src/main/java/io/javalin/Javalin.java#L435-L437
beanshell/beanshell
src/main/java/bsh/engine/BshScriptEngine.java
BshScriptEngine.evalSource
private Object evalSource(Object source, ScriptContext scriptContext) throws ScriptException { try { Interpreter bsh = getInterpreter(); NameSpace contextNameSpace = getEngineNameSpace(scriptContext); bsh.setNameSpace(contextNameSpace); bsh.setOut(toPrintStream(scriptContext.getWriter())); bsh.setErr(toPrintStream(scriptContext.getErrorWriter())); if (source instanceof Reader) { return bsh.eval((Reader) source); } else { return bsh.eval((String) source); } } catch (ParseException e) { // explicit parsing error throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); } catch (TargetError e) { // The script threw an application level exception ScriptException se = new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); se.initCause(e.getTarget()); throw se; } catch (EvalError e) { // The script couldn't be evaluated properly throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); } catch (IOException e) { throw new ScriptException(e.toString()); } }
java
private Object evalSource(Object source, ScriptContext scriptContext) throws ScriptException { try { Interpreter bsh = getInterpreter(); NameSpace contextNameSpace = getEngineNameSpace(scriptContext); bsh.setNameSpace(contextNameSpace); bsh.setOut(toPrintStream(scriptContext.getWriter())); bsh.setErr(toPrintStream(scriptContext.getErrorWriter())); if (source instanceof Reader) { return bsh.eval((Reader) source); } else { return bsh.eval((String) source); } } catch (ParseException e) { // explicit parsing error throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); } catch (TargetError e) { // The script threw an application level exception ScriptException se = new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); se.initCause(e.getTarget()); throw se; } catch (EvalError e) { // The script couldn't be evaluated properly throw new ScriptException(e.toString(), e.getErrorSourceFile(), e.getErrorLineNumber()); } catch (IOException e) { throw new ScriptException(e.toString()); } }
[ "private", "Object", "evalSource", "(", "Object", "source", ",", "ScriptContext", "scriptContext", ")", "throws", "ScriptException", "{", "try", "{", "Interpreter", "bsh", "=", "getInterpreter", "(", ")", ";", "NameSpace", "contextNameSpace", "=", "getEngineNameSpac...
/* This is the primary implementation method. We respect the String/Reader difference here in BeanShell because BeanShell will do a few extra things in the string case... e.g. tack on a trailing ";" semicolon if necessary.
[ "/", "*", "This", "is", "the", "primary", "implementation", "method", ".", "We", "respect", "the", "String", "/", "Reader", "difference", "here", "in", "BeanShell", "because", "BeanShell", "will", "do", "a", "few", "extra", "things", "in", "the", "string", ...
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/engine/BshScriptEngine.java#L90-L119
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java
BitsUtil.nextClearBit
public static int nextClearBit(long[] v, int start) { start = start < 0 ? 0 : start; int wordindex = start >>> LONG_LOG2_SIZE; if(wordindex >= v.length) { return -1; } // Initial word long cur = ~v[wordindex] & (LONG_ALL_BITS << start); for(;;) { if(cur != 0) { return (wordindex * Long.SIZE) + Long.numberOfTrailingZeros(cur); } if(++wordindex == v.length) { return -1; } cur = ~v[wordindex]; } }
java
public static int nextClearBit(long[] v, int start) { start = start < 0 ? 0 : start; int wordindex = start >>> LONG_LOG2_SIZE; if(wordindex >= v.length) { return -1; } // Initial word long cur = ~v[wordindex] & (LONG_ALL_BITS << start); for(;;) { if(cur != 0) { return (wordindex * Long.SIZE) + Long.numberOfTrailingZeros(cur); } if(++wordindex == v.length) { return -1; } cur = ~v[wordindex]; } }
[ "public", "static", "int", "nextClearBit", "(", "long", "[", "]", "v", ",", "int", "start", ")", "{", "start", "=", "start", "<", "0", "?", "0", ":", "start", ";", "int", "wordindex", "=", "start", ">>>", "LONG_LOG2_SIZE", ";", "if", "(", "wordindex"...
Find the next clear bit. @param v Value to process @param start Start position (inclusive) @return Position of next clear bit, or -1.
[ "Find", "the", "next", "clear", "bit", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java#L1366-L1384
FasterXML/woodstox
src/main/java/com/ctc/wstx/dtd/DTDElement.java
DTDElement.addNsDefault
public DTDAttribute addNsDefault (InputProblemReporter rep, PrefixedName attrName, int valueType, DefaultAttrValue defValue, boolean fullyValidate) throws XMLStreamException { /* Let's simplify handling a bit: although theoretically all * combinations of value can be used, let's really only differentiate * between CDATA and 'other' (for which let's use NMTOKEN) */ DTDAttribute nsAttr; switch (valueType) { case DTDAttribute.TYPE_CDATA: nsAttr = new DTDCdataAttr(attrName, defValue, -1, mNsAware, mXml11); break; default: // something else, default to NMTOKEN then nsAttr = new DTDNmTokenAttr(attrName, defValue, -1, mNsAware, mXml11); break; } // Ok. So which prefix are we to bind? Need to access by prefix... String prefix = attrName.getPrefix(); if (prefix == null || prefix.length() == 0) { // defult NS -> "" prefix = ""; } else { // non-default, use the local name prefix = attrName.getLocalName(); } if (mNsDefaults == null) { mNsDefaults = new HashMap<String,DTDAttribute>(); } else { if (mNsDefaults.containsKey(prefix)) { return null; } } mNsDefaults.put(prefix, nsAttr); return nsAttr; }
java
public DTDAttribute addNsDefault (InputProblemReporter rep, PrefixedName attrName, int valueType, DefaultAttrValue defValue, boolean fullyValidate) throws XMLStreamException { /* Let's simplify handling a bit: although theoretically all * combinations of value can be used, let's really only differentiate * between CDATA and 'other' (for which let's use NMTOKEN) */ DTDAttribute nsAttr; switch (valueType) { case DTDAttribute.TYPE_CDATA: nsAttr = new DTDCdataAttr(attrName, defValue, -1, mNsAware, mXml11); break; default: // something else, default to NMTOKEN then nsAttr = new DTDNmTokenAttr(attrName, defValue, -1, mNsAware, mXml11); break; } // Ok. So which prefix are we to bind? Need to access by prefix... String prefix = attrName.getPrefix(); if (prefix == null || prefix.length() == 0) { // defult NS -> "" prefix = ""; } else { // non-default, use the local name prefix = attrName.getLocalName(); } if (mNsDefaults == null) { mNsDefaults = new HashMap<String,DTDAttribute>(); } else { if (mNsDefaults.containsKey(prefix)) { return null; } } mNsDefaults.put(prefix, nsAttr); return nsAttr; }
[ "public", "DTDAttribute", "addNsDefault", "(", "InputProblemReporter", "rep", ",", "PrefixedName", "attrName", ",", "int", "valueType", ",", "DefaultAttrValue", "defValue", ",", "boolean", "fullyValidate", ")", "throws", "XMLStreamException", "{", "/* Let's simplify handl...
Method called to add a definition of a namespace-declaration pseudo-attribute with a default value. @param rep Reporter to use to report non-fatal problems @param fullyValidate Whether this is being invoked for actual DTD validation, or just the "typing non-validator" @return Attribute that acts as the placeholder, if the declaration was added; null to indicate it was a dup (there was an earlier declaration)
[ "Method", "called", "to", "add", "a", "definition", "of", "a", "namespace", "-", "declaration", "pseudo", "-", "attribute", "with", "a", "default", "value", "." ]
train
https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/dtd/DTDElement.java#L322-L359
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/DigitalOption.java
DigitalOption.getValue
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { // Get underlying and numeraire // Get S(T) RandomVariable underlyingAtMaturity = model.getAssetValue(maturity, underlyingIndex); // The payoff: values = indicator(underlying - strike, 0) = V(T) = max(S(T)-K,0) RandomVariable values = underlyingAtMaturity.sub(strike).choose(new Scalar(1.0), new Scalar(0.0)); // Discounting... RandomVariable numeraireAtMaturity = model.getNumeraire(maturity); RandomVariable monteCarloWeights = model.getMonteCarloWeights(maturity); values = values.div(numeraireAtMaturity).mult(monteCarloWeights); // ...to evaluation time. RandomVariable numeraireAtEvalTime = model.getNumeraire(evaluationTime); RandomVariable monteCarloProbabilitiesAtEvalTime = model.getMonteCarloWeights(evaluationTime); values = values.mult(numeraireAtEvalTime).div(monteCarloProbabilitiesAtEvalTime); return values; }
java
@Override public RandomVariable getValue(double evaluationTime, AssetModelMonteCarloSimulationModel model) throws CalculationException { // Get underlying and numeraire // Get S(T) RandomVariable underlyingAtMaturity = model.getAssetValue(maturity, underlyingIndex); // The payoff: values = indicator(underlying - strike, 0) = V(T) = max(S(T)-K,0) RandomVariable values = underlyingAtMaturity.sub(strike).choose(new Scalar(1.0), new Scalar(0.0)); // Discounting... RandomVariable numeraireAtMaturity = model.getNumeraire(maturity); RandomVariable monteCarloWeights = model.getMonteCarloWeights(maturity); values = values.div(numeraireAtMaturity).mult(monteCarloWeights); // ...to evaluation time. RandomVariable numeraireAtEvalTime = model.getNumeraire(evaluationTime); RandomVariable monteCarloProbabilitiesAtEvalTime = model.getMonteCarloWeights(evaluationTime); values = values.mult(numeraireAtEvalTime).div(monteCarloProbabilitiesAtEvalTime); return values; }
[ "@", "Override", "public", "RandomVariable", "getValue", "(", "double", "evaluationTime", ",", "AssetModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "// Get underlying and numeraire", "// Get S(T)", "RandomVariable", "underlyingAtMaturity", ...
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. Cashflows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Note", ":", "For", "a", "lattice", "this", "is", "often", "the", "valu...
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/assetderivativevaluation/products/DigitalOption.java#L79-L100
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.declareType
public boolean declareType(StaticScope scope, String name, JSType type) { checkState(!name.isEmpty()); if (getTypeForScopeInternal(getCreationScope(scope, name), name) != null) { return false; } register(scope, type, name); return true; }
java
public boolean declareType(StaticScope scope, String name, JSType type) { checkState(!name.isEmpty()); if (getTypeForScopeInternal(getCreationScope(scope, name), name) != null) { return false; } register(scope, type, name); return true; }
[ "public", "boolean", "declareType", "(", "StaticScope", "scope", ",", "String", "name", ",", "JSType", "type", ")", "{", "checkState", "(", "!", "name", ".", "isEmpty", "(", ")", ")", ";", "if", "(", "getTypeForScopeInternal", "(", "getCreationScope", "(", ...
Records declared global type names. This makes resolution faster and more robust in the common case. @param name The name of the type to be recorded. @param type The actual type being associated with the name. @return True if this name is not already defined, false otherwise.
[ "Records", "declared", "global", "type", "names", ".", "This", "makes", "resolution", "faster", "and", "more", "robust", "in", "the", "common", "case", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1139-L1147
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/RobotiumWebClient.java
RobotiumWebClient.onJsPrompt
@Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult r) { if(message != null && (message.contains(";,") || message.contains("robotium-finished"))){ if(message.equals("robotium-finished")){ webElementCreator.setFinished(true); } else{ webElementCreator.createWebElementAndAddInList(message, view); } r.confirm(); return true; } else { if(originalWebChromeClient != null) { return originalWebChromeClient.onJsPrompt(view, url, message, defaultValue, r); } return true; } }
java
@Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult r) { if(message != null && (message.contains(";,") || message.contains("robotium-finished"))){ if(message.equals("robotium-finished")){ webElementCreator.setFinished(true); } else{ webElementCreator.createWebElementAndAddInList(message, view); } r.confirm(); return true; } else { if(originalWebChromeClient != null) { return originalWebChromeClient.onJsPrompt(view, url, message, defaultValue, r); } return true; } }
[ "@", "Override", "public", "boolean", "onJsPrompt", "(", "WebView", "view", ",", "String", "url", ",", "String", "message", ",", "String", "defaultValue", ",", "JsPromptResult", "r", ")", "{", "if", "(", "message", "!=", "null", "&&", "(", "message", ".", ...
Overrides onJsPrompt in order to create {@code WebElement} objects based on the web elements attributes prompted by the injections of JavaScript
[ "Overrides", "onJsPrompt", "in", "order", "to", "create", "{" ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/RobotiumWebClient.java#L68-L89
jhipster/jhipster
jhipster-framework/src/main/java/io/github/jhipster/service/QueryService.java
QueryService.buildSpecification
protected <X> Specification<ENTITY> buildSpecification(Filter<X> filter, SingularAttribute<? super ENTITY, X> field) { return buildSpecification(filter, root -> root.get(field)); }
java
protected <X> Specification<ENTITY> buildSpecification(Filter<X> filter, SingularAttribute<? super ENTITY, X> field) { return buildSpecification(filter, root -> root.get(field)); }
[ "protected", "<", "X", ">", "Specification", "<", "ENTITY", ">", "buildSpecification", "(", "Filter", "<", "X", ">", "filter", ",", "SingularAttribute", "<", "?", "super", "ENTITY", ",", "X", ">", "field", ")", "{", "return", "buildSpecification", "(", "fi...
Helper function to return a specification for filtering on a single field, where equality, and null/non-null conditions are supported. @param filter the individual attribute filter coming from the frontend. @param field the JPA static metamodel representing the field. @param <X> The type of the attribute which is filtered. @return a Specification
[ "Helper", "function", "to", "return", "a", "specification", "for", "filtering", "on", "a", "single", "field", "where", "equality", "and", "null", "/", "non", "-", "null", "conditions", "are", "supported", "." ]
train
https://github.com/jhipster/jhipster/blob/5dcf4239c7cc035e188ef02447d3c628fac5c5d9/jhipster-framework/src/main/java/io/github/jhipster/service/QueryService.java#L55-L58
apache/reef
lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/evaluator/AggregateContainer.java
AggregateContainer.aggregateTasklets
private void aggregateTasklets(final AggregateTriggerType type) { final List<WorkerToMasterReport> workerToMasterReports = new ArrayList<>(); final List<Object> results = new ArrayList<>(); final List<Integer> aggregatedTasklets = new ArrayList<>(); // Synchronization to prevent duplication of work on the same aggregation function on the same worker. synchronized (stateLock) { switch(type) { case ALARM: aggregateTasklets(workerToMasterReports, results, aggregatedTasklets); break; case COUNT: if (!aggregateOnCount()) { return; } aggregateTasklets(workerToMasterReports, results, aggregatedTasklets); break; default: throw new RuntimeException("Unexpected aggregate type."); } } if (!results.isEmpty()) { // Run the aggregation function. try { final Object aggregationResult = taskletAggregationRequest.executeAggregation(results); workerToMasterReports.add(new TaskletAggregationResultReport(aggregatedTasklets, aggregationResult)); } catch (final Exception e) { workerToMasterReports.add(new TaskletAggregationFailureReport(aggregatedTasklets, e)); } } // Add to worker report only if there is something to report back. if (!workerToMasterReports.isEmpty()) { workerReportsQueue.addLast(kryoUtils.serialize(new WorkerToMasterReports(workerToMasterReports))); heartBeatTriggerManager.triggerHeartBeat(); } }
java
private void aggregateTasklets(final AggregateTriggerType type) { final List<WorkerToMasterReport> workerToMasterReports = new ArrayList<>(); final List<Object> results = new ArrayList<>(); final List<Integer> aggregatedTasklets = new ArrayList<>(); // Synchronization to prevent duplication of work on the same aggregation function on the same worker. synchronized (stateLock) { switch(type) { case ALARM: aggregateTasklets(workerToMasterReports, results, aggregatedTasklets); break; case COUNT: if (!aggregateOnCount()) { return; } aggregateTasklets(workerToMasterReports, results, aggregatedTasklets); break; default: throw new RuntimeException("Unexpected aggregate type."); } } if (!results.isEmpty()) { // Run the aggregation function. try { final Object aggregationResult = taskletAggregationRequest.executeAggregation(results); workerToMasterReports.add(new TaskletAggregationResultReport(aggregatedTasklets, aggregationResult)); } catch (final Exception e) { workerToMasterReports.add(new TaskletAggregationFailureReport(aggregatedTasklets, e)); } } // Add to worker report only if there is something to report back. if (!workerToMasterReports.isEmpty()) { workerReportsQueue.addLast(kryoUtils.serialize(new WorkerToMasterReports(workerToMasterReports))); heartBeatTriggerManager.triggerHeartBeat(); } }
[ "private", "void", "aggregateTasklets", "(", "final", "AggregateTriggerType", "type", ")", "{", "final", "List", "<", "WorkerToMasterReport", ">", "workerToMasterReports", "=", "new", "ArrayList", "<>", "(", ")", ";", "final", "List", "<", "Object", ">", "result...
Performs the output aggregation and generates the {@link WorkerToMasterReports} to report back to the {@link org.apache.reef.vortex.driver.VortexDriver}.
[ "Performs", "the", "output", "aggregation", "and", "generates", "the", "{" ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-applications/reef-vortex/src/main/java/org/apache/reef/vortex/evaluator/AggregateContainer.java#L104-L142
wisdom-framework/wisdom
extensions/wisdom-raml/wisdom-raml-maven-plugin/src/main/java/org/wisdom/raml/mojo/RamlCompilerMojo.java
RamlCompilerMojo.getRamlOutputFile
private File getRamlOutputFile(File input) { String ramlFileName = input.getName().substring(0, input.getName().length() - 4) + "raml"; File outDir; if (outputDirectory == null) { outDir = new File(WatcherUtils.getExternalAssetsDestination(basedir), "raml"); } else { outDir = new File(basedir, outputDirectory); } return new File(outDir, ramlFileName); }
java
private File getRamlOutputFile(File input) { String ramlFileName = input.getName().substring(0, input.getName().length() - 4) + "raml"; File outDir; if (outputDirectory == null) { outDir = new File(WatcherUtils.getExternalAssetsDestination(basedir), "raml"); } else { outDir = new File(basedir, outputDirectory); } return new File(outDir, ramlFileName); }
[ "private", "File", "getRamlOutputFile", "(", "File", "input", ")", "{", "String", "ramlFileName", "=", "input", ".", "getName", "(", ")", ".", "substring", "(", "0", ",", "input", ".", "getName", "(", ")", ".", "length", "(", ")", "-", "4", ")", "+",...
Create the .raml file from the java source file. @param input The java source file. @return The File where the raml spec, for the given input, will be written.
[ "Create", "the", ".", "raml", "file", "from", "the", "java", "source", "file", "." ]
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/extensions/wisdom-raml/wisdom-raml-maven-plugin/src/main/java/org/wisdom/raml/mojo/RamlCompilerMojo.java#L124-L135
apiman/apiman
manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java
EsMarshalling.unmarshallApiSummary
public static ApiSummaryBean unmarshallApiSummary(Map<String, Object> source) { if (source == null) { return null; } ApiSummaryBean bean = new ApiSummaryBean(); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); bean.setCreatedOn(asDate(source.get("createdOn"))); postMarshall(bean); return bean; }
java
public static ApiSummaryBean unmarshallApiSummary(Map<String, Object> source) { if (source == null) { return null; } ApiSummaryBean bean = new ApiSummaryBean(); bean.setOrganizationId(asString(source.get("organizationId"))); bean.setOrganizationName(asString(source.get("organizationName"))); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); bean.setCreatedOn(asDate(source.get("createdOn"))); postMarshall(bean); return bean; }
[ "public", "static", "ApiSummaryBean", "unmarshallApiSummary", "(", "Map", "<", "String", ",", "Object", ">", "source", ")", "{", "if", "(", "source", "==", "null", ")", "{", "return", "null", ";", "}", "ApiSummaryBean", "bean", "=", "new", "ApiSummaryBean", ...
Unmarshals the given map source into a bean. @param source the source @return the API summary
[ "Unmarshals", "the", "given", "map", "source", "into", "a", "bean", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L926-L939
kiswanij/jk-util
src/main/java/com/jk/util/JKStringUtil.java
JKStringUtil.setParameters
public static String setParameters(String value, final Object[] params) { if (params != null) { for (int i = 0; i < params.length; i++) { value = value.replaceAll("\\{" + i + "\\}", params[i].toString()); } } return value; }
java
public static String setParameters(String value, final Object[] params) { if (params != null) { for (int i = 0; i < params.length; i++) { value = value.replaceAll("\\{" + i + "\\}", params[i].toString()); } } return value; }
[ "public", "static", "String", "setParameters", "(", "String", "value", ",", "final", "Object", "[", "]", "params", ")", "{", "if", "(", "params", "!=", "null", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "params", ".", "length", ";",...
replace params in string with the using index , for example "Hello {1} {2}" with Jalal , Kiswani as aparamters will generate Hello Jalal Kiswani . @param value the value @param params the params @return the string
[ "replace", "params", "in", "string", "with", "the", "using", "index", "for", "example", "Hello", "{", "1", "}", "{", "2", "}", "with", "Jalal", "Kiswani", "as", "aparamters", "will", "generate", "Hello", "Jalal", "Kiswani", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/JKStringUtil.java#L81-L88
aws/aws-sdk-java
aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/SetCognitoEventsRequest.java
SetCognitoEventsRequest.withEvents
public SetCognitoEventsRequest withEvents(java.util.Map<String, String> events) { setEvents(events); return this; }
java
public SetCognitoEventsRequest withEvents(java.util.Map<String, String> events) { setEvents(events); return this; }
[ "public", "SetCognitoEventsRequest", "withEvents", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "events", ")", "{", "setEvents", "(", "events", ")", ";", "return", "this", ";", "}" ]
<p> The events to configure </p> @param events The events to configure @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "events", "to", "configure", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitosync/src/main/java/com/amazonaws/services/cognitosync/model/SetCognitoEventsRequest.java#L123-L126
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/util/ReferenceMap.java
ReferenceMap.toReference
private Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, queue); case WEAK: return new WeakRef(hash, referent, queue); default: throw new Error(); } }
java
private Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, queue); case WEAK: return new WeakRef(hash, referent, queue); default: throw new Error(); } }
[ "private", "Object", "toReference", "(", "int", "type", ",", "Object", "referent", ",", "int", "hash", ")", "{", "switch", "(", "type", ")", "{", "case", "HARD", ":", "return", "referent", ";", "case", "SOFT", ":", "return", "new", "SoftRef", "(", "has...
Constructs a reference of the given type to the given referent. The reference is registered with the queue for later purging. @param type HARD, SOFT or WEAK @param referent the object to refer to @param hash the hash code of the <I>key</I> of the mapping; this number might be different from referent.hashCode() if the referent represents a value and not a key
[ "Constructs", "a", "reference", "of", "the", "given", "type", "to", "the", "given", "referent", ".", "The", "reference", "is", "registered", "with", "the", "queue", "for", "later", "purging", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/util/ReferenceMap.java#L343-L356
b3log/latke
latke-core/src/main/java/org/b3log/latke/util/Callstacks.java
Callstacks.isCaller
public static boolean isCaller(final String className, final String methodName) { final Throwable throwable = new Throwable(); final StackTraceElement[] stackElements = throwable.getStackTrace(); if (null == stackElements) { LOGGER.log(Level.WARN, "Empty call stack"); return false; } final boolean matchAllMethod = "*".equals(methodName); for (int i = 1; i < stackElements.length; i++) { if (stackElements[i].getClassName().equals(className)) { return matchAllMethod ? true : stackElements[i].getMethodName().equals(methodName); } } return false; }
java
public static boolean isCaller(final String className, final String methodName) { final Throwable throwable = new Throwable(); final StackTraceElement[] stackElements = throwable.getStackTrace(); if (null == stackElements) { LOGGER.log(Level.WARN, "Empty call stack"); return false; } final boolean matchAllMethod = "*".equals(methodName); for (int i = 1; i < stackElements.length; i++) { if (stackElements[i].getClassName().equals(className)) { return matchAllMethod ? true : stackElements[i].getMethodName().equals(methodName); } } return false; }
[ "public", "static", "boolean", "isCaller", "(", "final", "String", "className", ",", "final", "String", "methodName", ")", "{", "final", "Throwable", "throwable", "=", "new", "Throwable", "(", ")", ";", "final", "StackTraceElement", "[", "]", "stackElements", ...
Checks the current method is whether invoked by a caller specified by the given class name and method name. @param className the given class name @param methodName the given method name, "*" for matching all methods @return {@code true} if it is invoked by the specified caller, returns {@code false} otherwise
[ "Checks", "the", "current", "method", "is", "whether", "invoked", "by", "a", "caller", "specified", "by", "the", "given", "class", "name", "and", "method", "name", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/b3log/latke/util/Callstacks.java#L42-L61
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java
StringSupport.split
public static List<String> split(String input, String punctuationChars, String quoteChars) { return split(input, punctuationChars, quoteChars, false, false, false); }
java
public static List<String> split(String input, String punctuationChars, String quoteChars) { return split(input, punctuationChars, quoteChars, false, false, false); }
[ "public", "static", "List", "<", "String", ">", "split", "(", "String", "input", ",", "String", "punctuationChars", ",", "String", "quoteChars", ")", "{", "return", "split", "(", "input", ",", "punctuationChars", ",", "quoteChars", ",", "false", ",", "false"...
reads all words in a text and converts them to lower case @param input @param punctuationChars characters that can not belong to words and are therefore separators @return a collection of uniquely identified words
[ "reads", "all", "words", "in", "a", "text", "and", "converts", "them", "to", "lower", "case" ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/misc/StringSupport.java#L540-L542
craftercms/commons
utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java
HttpUtils.getFullUrl
public static String getFullUrl(HttpServletRequest request, String relativeUrl) { StringBuilder baseUrl = getBaseRequestUrl(request, false); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); if (contextPath.equals("/")) { contextPath = ""; } if (servletPath.equals("/")) { servletPath = ""; } return baseUrl.append(contextPath).append(servletPath).append(relativeUrl).toString(); }
java
public static String getFullUrl(HttpServletRequest request, String relativeUrl) { StringBuilder baseUrl = getBaseRequestUrl(request, false); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); if (contextPath.equals("/")) { contextPath = ""; } if (servletPath.equals("/")) { servletPath = ""; } return baseUrl.append(contextPath).append(servletPath).append(relativeUrl).toString(); }
[ "public", "static", "String", "getFullUrl", "(", "HttpServletRequest", "request", ",", "String", "relativeUrl", ")", "{", "StringBuilder", "baseUrl", "=", "getBaseRequestUrl", "(", "request", ",", "false", ")", ";", "String", "contextPath", "=", "request", ".", ...
Returns the full URL for the relative URL based in the specified request. The full URL includes the scheme, server name, port number, context path and server path. @param request the request object used to build the base URL @param relativeUrl the relative URL @return the full URL
[ "Returns", "the", "full", "URL", "for", "the", "relative", "URL", "based", "in", "the", "specified", "request", ".", "The", "full", "URL", "includes", "the", "scheme", "server", "name", "port", "number", "context", "path", "and", "server", "path", "." ]
train
https://github.com/craftercms/commons/blob/3074fe49e56c2a4aae0832f40b17ae563335dc83/utilities/src/main/java/org/craftercms/commons/http/HttpUtils.java#L89-L102
jOOQ/jOOL
jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java
Unchecked.doubleConsumer
public static DoubleConsumer doubleConsumer(CheckedDoubleConsumer consumer, Consumer<Throwable> handler) { return d -> { try { consumer.accept(d); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
java
public static DoubleConsumer doubleConsumer(CheckedDoubleConsumer consumer, Consumer<Throwable> handler) { return d -> { try { consumer.accept(d); } catch (Throwable e) { handler.accept(e); throw new IllegalStateException("Exception handler must throw a RuntimeException", e); } }; }
[ "public", "static", "DoubleConsumer", "doubleConsumer", "(", "CheckedDoubleConsumer", "consumer", ",", "Consumer", "<", "Throwable", ">", "handler", ")", "{", "return", "d", "->", "{", "try", "{", "consumer", ".", "accept", "(", "d", ")", ";", "}", "catch", ...
Wrap a {@link CheckedDoubleConsumer} in a {@link DoubleConsumer} with a custom handler for checked exceptions. <p> Example: <code><pre> Arrays.stream(new double[] { 1.0, 2.0 }).forEach(Unchecked.doubleConsumer( d -> { if (d &lt; 0.0) throw new Exception("Only positive numbers allowed"); }, e -> { throw new IllegalStateException(e); } )); </pre></code>
[ "Wrap", "a", "{" ]
train
https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L823-L834
igniterealtime/Smack
smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferNegotiator.java
FileTransferNegotiator.negotiateOutgoingTransfer
public StreamNegotiator negotiateOutgoingTransfer(final Jid userID, final String streamID, final String fileName, final long size, final String desc, int responseTimeout) throws XMPPErrorException, NotConnectedException, NoResponseException, NoAcceptableTransferMechanisms, InterruptedException { StreamInitiation si = new StreamInitiation(); si.setSessionID(streamID); si.setMimeType(URLConnection.guessContentTypeFromName(fileName)); StreamInitiation.File siFile = new StreamInitiation.File(fileName, size); siFile.setDesc(desc); si.setFile(siFile); si.setFeatureNegotiationForm(createDefaultInitiationForm()); si.setFrom(connection().getUser()); si.setTo(userID); si.setType(IQ.Type.set); Stanza siResponse = connection().createStanzaCollectorAndSend(si).nextResultOrThrow( responseTimeout); if (siResponse instanceof IQ) { IQ iqResponse = (IQ) siResponse; if (iqResponse.getType().equals(IQ.Type.result)) { StreamInitiation response = (StreamInitiation) siResponse; return getOutgoingNegotiator(getStreamMethodField(response .getFeatureNegotiationForm())); } else { throw new XMPPErrorException(iqResponse, iqResponse.getError()); } } else { return null; } }
java
public StreamNegotiator negotiateOutgoingTransfer(final Jid userID, final String streamID, final String fileName, final long size, final String desc, int responseTimeout) throws XMPPErrorException, NotConnectedException, NoResponseException, NoAcceptableTransferMechanisms, InterruptedException { StreamInitiation si = new StreamInitiation(); si.setSessionID(streamID); si.setMimeType(URLConnection.guessContentTypeFromName(fileName)); StreamInitiation.File siFile = new StreamInitiation.File(fileName, size); siFile.setDesc(desc); si.setFile(siFile); si.setFeatureNegotiationForm(createDefaultInitiationForm()); si.setFrom(connection().getUser()); si.setTo(userID); si.setType(IQ.Type.set); Stanza siResponse = connection().createStanzaCollectorAndSend(si).nextResultOrThrow( responseTimeout); if (siResponse instanceof IQ) { IQ iqResponse = (IQ) siResponse; if (iqResponse.getType().equals(IQ.Type.result)) { StreamInitiation response = (StreamInitiation) siResponse; return getOutgoingNegotiator(getStreamMethodField(response .getFeatureNegotiationForm())); } else { throw new XMPPErrorException(iqResponse, iqResponse.getError()); } } else { return null; } }
[ "public", "StreamNegotiator", "negotiateOutgoingTransfer", "(", "final", "Jid", "userID", ",", "final", "String", "streamID", ",", "final", "String", "fileName", ",", "final", "long", "size", ",", "final", "String", "desc", ",", "int", "responseTimeout", ")", "t...
Send a request to another user to send them a file. The other user has the option of, accepting, rejecting, or not responding to a received file transfer request. <p> If they accept, the stanza will contain the other user's chosen stream type to send the file across. The two choices this implementation provides to the other user for file transfer are <a href="http://www.xmpp.org/extensions/jep-0065.html">SOCKS5 Bytestreams</a>, which is the preferred method of transfer, and <a href="http://www.xmpp.org/extensions/jep-0047.html">In-Band Bytestreams</a>, which is the fallback mechanism. </p> <p> The other user may choose to decline the file request if they do not desire the file, their client does not support XEP-0096, or if there are no acceptable means to transfer the file. </p> Finally, if the other user does not respond this method will return null after the specified timeout. @param userID The userID of the user to whom the file will be sent. @param streamID The unique identifier for this file transfer. @param fileName The name of this file. Preferably it should include an extension as it is used to determine what type of file it is. @param size The size, in bytes, of the file. @param desc A description of the file. @param responseTimeout The amount of time, in milliseconds, to wait for the remote user to respond. If they do not respond in time, this @return Returns the stream negotiator selected by the peer. @throws XMPPErrorException Thrown if there is an error negotiating the file transfer. @throws NotConnectedException @throws NoResponseException @throws NoAcceptableTransferMechanisms @throws InterruptedException
[ "Send", "a", "request", "to", "another", "user", "to", "send", "them", "a", "file", ".", "The", "other", "user", "has", "the", "option", "of", "accepting", "rejecting", "or", "not", "responding", "to", "a", "received", "file", "transfer", "request", ".", ...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/filetransfer/FileTransferNegotiator.java#L304-L339
jnidzwetzki/bitfinex-v2-wss-api-java
src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java
BitfinexSymbols.candlesticks
public static BitfinexCandlestickSymbol candlesticks(final String currency, final String profitCurrency, final BitfinexCandleTimeFrame timeframe) { final String currencyNonNull = Objects.requireNonNull(currency).toUpperCase(); final String profitCurrencyNonNull = Objects.requireNonNull(profitCurrency).toUpperCase(); return candlesticks(BitfinexCurrencyPair.of(currencyNonNull, profitCurrencyNonNull), timeframe); }
java
public static BitfinexCandlestickSymbol candlesticks(final String currency, final String profitCurrency, final BitfinexCandleTimeFrame timeframe) { final String currencyNonNull = Objects.requireNonNull(currency).toUpperCase(); final String profitCurrencyNonNull = Objects.requireNonNull(profitCurrency).toUpperCase(); return candlesticks(BitfinexCurrencyPair.of(currencyNonNull, profitCurrencyNonNull), timeframe); }
[ "public", "static", "BitfinexCandlestickSymbol", "candlesticks", "(", "final", "String", "currency", ",", "final", "String", "profitCurrency", ",", "final", "BitfinexCandleTimeFrame", "timeframe", ")", "{", "final", "String", "currencyNonNull", "=", "Objects", ".", "r...
Returns symbol for candlestick channel @param currency of candles @param profitCurrency of candles @param timeframe configuration of candles @return symbol
[ "Returns", "symbol", "for", "candlestick", "channel" ]
train
https://github.com/jnidzwetzki/bitfinex-v2-wss-api-java/blob/2e6adf1eb6f8cd4c8722f1619f78ab2cc3c600ee/src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java#L66-L73
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java
PhotosApi.getCounts
public Photocounts getCounts(List<Date> dates, List<Date> takenDates) throws JinxException { Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.getCounts"); if (!JinxUtils.isNullOrEmpty(dates)) { Collections.sort(dates); List<String> formattedDates = new ArrayList<String>(); for (Date date : dates) { formattedDates.add(JinxUtils.formatDateAsUnixTimestamp(date)); } params.put("dates", JinxUtils.buildCommaDelimitedList(formattedDates)); } if (!JinxUtils.isNullOrEmpty(takenDates)) { List<String> formattedDates = new ArrayList<String>(); for (Date date : takenDates) { formattedDates.add(JinxUtils.formatDateAsMySqlTimestamp(date)); } params.put("taken_dates", JinxUtils.buildCommaDelimitedList(formattedDates)); } return jinx.flickrGet(params, Photocounts.class); }
java
public Photocounts getCounts(List<Date> dates, List<Date> takenDates) throws JinxException { Map<String, String> params = new TreeMap<>(); params.put("method", "flickr.photos.getCounts"); if (!JinxUtils.isNullOrEmpty(dates)) { Collections.sort(dates); List<String> formattedDates = new ArrayList<String>(); for (Date date : dates) { formattedDates.add(JinxUtils.formatDateAsUnixTimestamp(date)); } params.put("dates", JinxUtils.buildCommaDelimitedList(formattedDates)); } if (!JinxUtils.isNullOrEmpty(takenDates)) { List<String> formattedDates = new ArrayList<String>(); for (Date date : takenDates) { formattedDates.add(JinxUtils.formatDateAsMySqlTimestamp(date)); } params.put("taken_dates", JinxUtils.buildCommaDelimitedList(formattedDates)); } return jinx.flickrGet(params, Photocounts.class); }
[ "public", "Photocounts", "getCounts", "(", "List", "<", "Date", ">", "dates", ",", "List", "<", "Date", ">", "takenDates", ")", "throws", "JinxException", "{", "Map", "<", "String", ",", "String", ">", "params", "=", "new", "TreeMap", "<>", "(", ")", "...
Gets a list of photo counts for the given date ranges for the calling user. <br> This method requires authentication with 'read' permission. <br> You must provide either dates or takenDates parameters. Flickr may not return correct results if you specify both. @param dates a list of dates denoting the periods to return counts for. They should be specified smallest first. @param takenDates a list of dates denoting the periods to return counts for. They should be specified smallest first. @return object containing a list of counts for the specified dates. @throws JinxException if there are any errors. @see <a href="https://www.flickr.com/services/api/flickr.photos.getCounts.html">flickr.photos.getCounts</a>
[ "Gets", "a", "list", "of", "photo", "counts", "for", "the", "given", "date", "ranges", "for", "the", "calling", "user", ".", "<br", ">", "This", "method", "requires", "authentication", "with", "read", "permission", ".", "<br", ">", "You", "must", "provide"...
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/PhotosApi.java#L246-L265
biojava/biojava
biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java
Utils.checkSequence
public static final String checkSequence(String sequence, Set<Character> cSet){ boolean containInvalid = false; if(cSet != null){ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, cSet); }else{ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, PeptideProperties.standardAASet); } if(containInvalid){ String cSeq = cleanSequence(sequence, cSet); logger.warn("There exists invalid characters in the sequence. Computed results might not be precise."); logger.warn("To remove this warning: Please use org.biojava.nbio.aaproperties.Utils.cleanSequence to clean sequence."); return cSeq; } else{ return sequence; } }
java
public static final String checkSequence(String sequence, Set<Character> cSet){ boolean containInvalid = false; if(cSet != null){ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, cSet); }else{ containInvalid = sequence != null && doesSequenceContainInvalidChar(sequence, PeptideProperties.standardAASet); } if(containInvalid){ String cSeq = cleanSequence(sequence, cSet); logger.warn("There exists invalid characters in the sequence. Computed results might not be precise."); logger.warn("To remove this warning: Please use org.biojava.nbio.aaproperties.Utils.cleanSequence to clean sequence."); return cSeq; } else{ return sequence; } }
[ "public", "static", "final", "String", "checkSequence", "(", "String", "sequence", ",", "Set", "<", "Character", ">", "cSet", ")", "{", "boolean", "containInvalid", "=", "false", ";", "if", "(", "cSet", "!=", "null", ")", "{", "containInvalid", "=", "seque...
Checks if the sequence contains invalid characters. Note that any character outside of the 20 standard protein amino acid codes are considered as invalid. If yes, it will return a new sequence where invalid characters are replaced with '-'. If no, it will simply return the input sequence. @param sequence protein sequence to be check for invalid characters. @param cSet character set which define the valid characters. @return a sequence with no invalid characters.
[ "Checks", "if", "the", "sequence", "contains", "invalid", "characters", ".", "Note", "that", "any", "character", "outside", "of", "the", "20", "standard", "protein", "amino", "acid", "codes", "are", "considered", "as", "invalid", ".", "If", "yes", "it", "wil...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-aa-prop/src/main/java/org/biojava/nbio/aaproperties/Utils.java#L165-L182
elki-project/elki
elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/PrimsMinimumSpanningTree.java
PrimsMinimumSpanningTree.processDense
public static <T> void processDense(T data, Adapter<T> adapter, Collector collector) { // Number of nodes final int n = adapter.size(data); // Best distance for each node double[] best = new double[n]; Arrays.fill(best, Double.POSITIVE_INFINITY); // Best previous node int[] src = new int[n]; // Nodes already handled // byte[] uses more memory, but it will be faster. byte[] connected = new byte[n]; // We always start at "random" node 0 // Note: we use this below in the "j" loop! int current = 0; connected[current] = 1; best[current] = 0; // Search for(int i = n - 2; i >= 0; i--) { // Update best and src from current: int newbesti = -1; double newbestd = Double.POSITIVE_INFINITY; // Note: we assume we started with 0, and can thus skip it for(int j = 0; j < n; ++j) { if(connected[j] == 1) { continue; } final double dist = adapter.distance(data, current, j); if(dist < best[j]) { best[j] = dist; src[j] = current; } if(best[j] < newbestd || newbesti == -1) { newbestd = best[j]; newbesti = j; } } assert (newbesti >= 0); // Flag connected[newbesti] = 1; // Store edge collector.addEdge(newbestd, src[newbesti], newbesti); // Continue current = newbesti; } }
java
public static <T> void processDense(T data, Adapter<T> adapter, Collector collector) { // Number of nodes final int n = adapter.size(data); // Best distance for each node double[] best = new double[n]; Arrays.fill(best, Double.POSITIVE_INFINITY); // Best previous node int[] src = new int[n]; // Nodes already handled // byte[] uses more memory, but it will be faster. byte[] connected = new byte[n]; // We always start at "random" node 0 // Note: we use this below in the "j" loop! int current = 0; connected[current] = 1; best[current] = 0; // Search for(int i = n - 2; i >= 0; i--) { // Update best and src from current: int newbesti = -1; double newbestd = Double.POSITIVE_INFINITY; // Note: we assume we started with 0, and can thus skip it for(int j = 0; j < n; ++j) { if(connected[j] == 1) { continue; } final double dist = adapter.distance(data, current, j); if(dist < best[j]) { best[j] = dist; src[j] = current; } if(best[j] < newbestd || newbesti == -1) { newbestd = best[j]; newbesti = j; } } assert (newbesti >= 0); // Flag connected[newbesti] = 1; // Store edge collector.addEdge(newbestd, src[newbesti], newbesti); // Continue current = newbesti; } }
[ "public", "static", "<", "T", ">", "void", "processDense", "(", "T", "data", ",", "Adapter", "<", "T", ">", "adapter", ",", "Collector", "collector", ")", "{", "// Number of nodes", "final", "int", "n", "=", "adapter", ".", "size", "(", "data", ")", ";...
Run Prim's algorithm on a dense graph. @param data Data set @param adapter Adapter instance @param collector Edge collector
[ "Run", "Prim", "s", "algorithm", "on", "a", "dense", "graph", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/geometry/PrimsMinimumSpanningTree.java#L131-L177
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/aaa/aaauser_binding.java
aaauser_binding.get
public static aaauser_binding get(nitro_service service, String username) throws Exception{ aaauser_binding obj = new aaauser_binding(); obj.set_username(username); aaauser_binding response = (aaauser_binding) obj.get_resource(service); return response; }
java
public static aaauser_binding get(nitro_service service, String username) throws Exception{ aaauser_binding obj = new aaauser_binding(); obj.set_username(username); aaauser_binding response = (aaauser_binding) obj.get_resource(service); return response; }
[ "public", "static", "aaauser_binding", "get", "(", "nitro_service", "service", ",", "String", "username", ")", "throws", "Exception", "{", "aaauser_binding", "obj", "=", "new", "aaauser_binding", "(", ")", ";", "obj", ".", "set_username", "(", "username", ")", ...
Use this API to fetch aaauser_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "aaauser_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/aaa/aaauser_binding.java#L202-L207
MGunlogson/CuckooFilter4J
src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java
SegmentedBucketLocker.unlockBucketsWrite
void unlockBucketsWrite(long i1, long i2) { int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always unlock segments in same order to avoid deadlocks if (bucket1LockIdx == bucket2LockIdx) { lockAry[bucket1LockIdx].tryUnlockWrite(); return; } lockAry[bucket1LockIdx].tryUnlockWrite(); lockAry[bucket2LockIdx].tryUnlockWrite(); }
java
void unlockBucketsWrite(long i1, long i2) { int bucket1LockIdx = getBucketLock(i1); int bucket2LockIdx = getBucketLock(i2); // always unlock segments in same order to avoid deadlocks if (bucket1LockIdx == bucket2LockIdx) { lockAry[bucket1LockIdx].tryUnlockWrite(); return; } lockAry[bucket1LockIdx].tryUnlockWrite(); lockAry[bucket2LockIdx].tryUnlockWrite(); }
[ "void", "unlockBucketsWrite", "(", "long", "i1", ",", "long", "i2", ")", "{", "int", "bucket1LockIdx", "=", "getBucketLock", "(", "i1", ")", ";", "int", "bucket2LockIdx", "=", "getBucketLock", "(", "i2", ")", ";", "// always unlock segments in same order to avoid ...
Unlocks segments corresponding to bucket indexes in specific order to prevent deadlocks
[ "Unlocks", "segments", "corresponding", "to", "bucket", "indexes", "in", "specific", "order", "to", "prevent", "deadlocks" ]
train
https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/SegmentedBucketLocker.java#L103-L113
JOML-CI/JOML
src/org/joml/Intersectionf.java
Intersectionf.distancePointLine
public static float distancePointLine(float pX, float pY, float pZ, float x0, float y0, float z0, float x1, float y1, float z1) { float d21x = x1 - x0, d21y = y1 - y0, d21z = z1 - z0; float d10x = x0 - pX, d10y = y0 - pY, d10z = z0 - pZ; float cx = d21y * d10z - d21z * d10y, cy = d21z * d10x - d21x * d10z, cz = d21x * d10y - d21y * d10x; return (float) Math.sqrt((cx*cx + cy*cy + cz*cz) / (d21x*d21x + d21y*d21y + d21z*d21z)); }
java
public static float distancePointLine(float pX, float pY, float pZ, float x0, float y0, float z0, float x1, float y1, float z1) { float d21x = x1 - x0, d21y = y1 - y0, d21z = z1 - z0; float d10x = x0 - pX, d10y = y0 - pY, d10z = z0 - pZ; float cx = d21y * d10z - d21z * d10y, cy = d21z * d10x - d21x * d10z, cz = d21x * d10y - d21y * d10x; return (float) Math.sqrt((cx*cx + cy*cy + cz*cz) / (d21x*d21x + d21y*d21y + d21z*d21z)); }
[ "public", "static", "float", "distancePointLine", "(", "float", "pX", ",", "float", "pY", ",", "float", "pZ", ",", "float", "x0", ",", "float", "y0", ",", "float", "z0", ",", "float", "x1", ",", "float", "y1", ",", "float", "z1", ")", "{", "float", ...
Compute the distance of the given point <code>(pX, pY, pZ)</code> to the line defined by the two points <code>(x0, y0, z0)</code> and <code>(x1, y1, z1)</code>. <p> Reference: <a href="http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html">http://mathworld.wolfram.com</a> @param pX the x coordinate of the point @param pY the y coordinate of the point @param pZ the z coordinate of the point @param x0 the x coordinate of the first point on the line @param y0 the y coordinate of the first point on the line @param z0 the z coordinate of the first point on the line @param x1 the x coordinate of the second point on the line @param y1 the y coordinate of the second point on the line @param z1 the z coordinate of the second point on the line @return the distance between the point and the line
[ "Compute", "the", "distance", "of", "the", "given", "point", "<code", ">", "(", "pX", "pY", "pZ", ")", "<", "/", "code", ">", "to", "the", "line", "defined", "by", "the", "two", "points", "<code", ">", "(", "x0", "y0", "z0", ")", "<", "/", "code"...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Intersectionf.java#L3882-L3888
Mozu/mozu-java
mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/PaymentUrl.java
PaymentUrl.getAvailablePaymentActionsUrl
public static MozuUrl getAvailablePaymentActionsUrl(String orderId, String paymentId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/payments/{paymentId}/actions"); formatter.formatUrl("orderId", orderId); formatter.formatUrl("paymentId", paymentId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
java
public static MozuUrl getAvailablePaymentActionsUrl(String orderId, String paymentId) { UrlFormatter formatter = new UrlFormatter("/api/commerce/orders/{orderId}/payments/{paymentId}/actions"); formatter.formatUrl("orderId", orderId); formatter.formatUrl("paymentId", paymentId); return new MozuUrl(formatter.getResourceUrl(), MozuUrl.UrlLocation.TENANT_POD) ; }
[ "public", "static", "MozuUrl", "getAvailablePaymentActionsUrl", "(", "String", "orderId", ",", "String", "paymentId", ")", "{", "UrlFormatter", "formatter", "=", "new", "UrlFormatter", "(", "\"/api/commerce/orders/{orderId}/payments/{paymentId}/actions\"", ")", ";", "format...
Get Resource Url for GetAvailablePaymentActions @param orderId Unique identifier of the order. @param paymentId Unique identifier of the payment for which to perform the action. @return String Resource Url
[ "Get", "Resource", "Url", "for", "GetAvailablePaymentActions" ]
train
https://github.com/Mozu/mozu-java/blob/5beadde73601a859f845e3e2fc1077b39c8bea83/mozu-java-core/src/main/java/com/mozu/api/urls/commerce/orders/PaymentUrl.java#L36-L42
vipshop/vjtools
vjkit/src/main/java/com/vip/vjtools/vjkit/security/CryptoUtil.java
CryptoUtil.isMacValid
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) { byte[] actual = hmacSha1(input, key); return Arrays.equals(expected, actual); }
java
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) { byte[] actual = hmacSha1(input, key); return Arrays.equals(expected, actual); }
[ "public", "static", "boolean", "isMacValid", "(", "byte", "[", "]", "expected", ",", "byte", "[", "]", "input", ",", "byte", "[", "]", "key", ")", "{", "byte", "[", "]", "actual", "=", "hmacSha1", "(", "input", ",", "key", ")", ";", "return", "Arra...
校验HMAC-SHA1签名是否正确. @param expected 已存在的签名 @param input 原始输入字符串 @param key 密钥
[ "校验HMAC", "-", "SHA1签名是否正确", "." ]
train
https://github.com/vipshop/vjtools/blob/60c743da35913d72f37f2d79afa90ad2bf73cb89/vjkit/src/main/java/com/vip/vjtools/vjkit/security/CryptoUtil.java#L60-L63
moparisthebest/beehive
beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java
FlowController.create
public synchronized void create( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext ) { PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, null ) ); try { try { // we start the context on the bean so user control can run against Controls in the onCreate() method super.create( request, response, servletContext ); } catch ( Throwable th ) { try { _log.info( "Handling exception in onCreate(), FlowController " + this, th ); reinitialize(request, response, servletContext); ActionForward fwd = handleException( th, null, null, request, response ); if ( fwd == null ) fwd = NULL_ACTION_FORWARD; request.setAttribute( ONCREATE_EXCEPTION_FORWARD, fwd ); } catch ( Exception e ) { _log.error( "Exception thrown while handling exception in onCreate(): " + e.getMessage(), th ); } } } finally { if(prevState != null) setPerRequestState( prevState ); PageFlowControlContainer pfcc = PageFlowControlContainerFactory.getControlContainer(request,getServletContext()); pfcc.endContextOnPageFlow(this); } PageFlowEventReporter er = AdapterManager.getServletContainerAdapter( servletContext ).getEventReporter(); RequestContext requestContext = new RequestContext( request, response ); er.flowControllerCreated( requestContext, this ); }
java
public synchronized void create( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext ) { PerRequestState prevState = setPerRequestState( new PerRequestState( request, response, null ) ); try { try { // we start the context on the bean so user control can run against Controls in the onCreate() method super.create( request, response, servletContext ); } catch ( Throwable th ) { try { _log.info( "Handling exception in onCreate(), FlowController " + this, th ); reinitialize(request, response, servletContext); ActionForward fwd = handleException( th, null, null, request, response ); if ( fwd == null ) fwd = NULL_ACTION_FORWARD; request.setAttribute( ONCREATE_EXCEPTION_FORWARD, fwd ); } catch ( Exception e ) { _log.error( "Exception thrown while handling exception in onCreate(): " + e.getMessage(), th ); } } } finally { if(prevState != null) setPerRequestState( prevState ); PageFlowControlContainer pfcc = PageFlowControlContainerFactory.getControlContainer(request,getServletContext()); pfcc.endContextOnPageFlow(this); } PageFlowEventReporter er = AdapterManager.getServletContainerAdapter( servletContext ).getEventReporter(); RequestContext requestContext = new RequestContext( request, response ); er.flowControllerCreated( requestContext, this ); }
[ "public", "synchronized", "void", "create", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ",", "ServletContext", "servletContext", ")", "{", "PerRequestState", "prevState", "=", "setPerRequestState", "(", "new", "PerRequestState", "(", "r...
Initialize after object creation. This is a framework-invoked method; it should not normally be called directly.
[ "Initialize", "after", "object", "creation", ".", "This", "is", "a", "framework", "-", "invoked", "method", ";", "it", "should", "not", "normally", "be", "called", "directly", "." ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowController.java#L561-L602
jaxio/javaee-lab
javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java
GenericRepository.isPropertyNull
@Transactional public boolean isPropertyNull(PK id, SingularAttribute<E, ?> property) { checkNotNull(id, "The id cannot be null"); checkNotNull(property, "The property cannot be null"); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class); Root<E> root = criteriaQuery.from(type); criteriaQuery = criteriaQuery.select(builder.count(root)); // predicate Predicate idPredicate = builder.equal(root.get("id"), id); Predicate isNullPredicate = builder.isNull(root.get(property)); criteriaQuery = criteriaQuery.where(jpaUtil.andPredicate(builder, idPredicate, isNullPredicate)); TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery); return typedQuery.getSingleResult().intValue() == 1; }
java
@Transactional public boolean isPropertyNull(PK id, SingularAttribute<E, ?> property) { checkNotNull(id, "The id cannot be null"); checkNotNull(property, "The property cannot be null"); CriteriaBuilder builder = entityManager.getCriteriaBuilder(); CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class); Root<E> root = criteriaQuery.from(type); criteriaQuery = criteriaQuery.select(builder.count(root)); // predicate Predicate idPredicate = builder.equal(root.get("id"), id); Predicate isNullPredicate = builder.isNull(root.get(property)); criteriaQuery = criteriaQuery.where(jpaUtil.andPredicate(builder, idPredicate, isNullPredicate)); TypedQuery<Long> typedQuery = entityManager.createQuery(criteriaQuery); return typedQuery.getSingleResult().intValue() == 1; }
[ "@", "Transactional", "public", "boolean", "isPropertyNull", "(", "PK", "id", ",", "SingularAttribute", "<", "E", ",", "?", ">", "property", ")", "{", "checkNotNull", "(", "id", ",", "\"The id cannot be null\"", ")", ";", "checkNotNull", "(", "property", ",", ...
/* Helper to determine if the passed given property is null. Used mainly on binary lazy loaded property. @param id the entity id @param property the property to check
[ "/", "*", "Helper", "to", "determine", "if", "the", "passed", "given", "property", "is", "null", ".", "Used", "mainly", "on", "binary", "lazy", "loaded", "property", "." ]
train
https://github.com/jaxio/javaee-lab/blob/61238b967952446d81cc68424a4e809093a77fcf/javaee7-jpa-query-by-example/src/main/java/com/jaxio/jpa/querybyexample/GenericRepository.java#L643-L659
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java
HttpUtil.getContentLength
public static int getContentLength(HttpMessage message, int defaultValue) { return (int) Math.min(Integer.MAX_VALUE, getContentLength(message, (long) defaultValue)); }
java
public static int getContentLength(HttpMessage message, int defaultValue) { return (int) Math.min(Integer.MAX_VALUE, getContentLength(message, (long) defaultValue)); }
[ "public", "static", "int", "getContentLength", "(", "HttpMessage", "message", ",", "int", "defaultValue", ")", "{", "return", "(", "int", ")", "Math", ".", "min", "(", "Integer", ".", "MAX_VALUE", ",", "getContentLength", "(", "message", ",", "(", "long", ...
Get an {@code int} representation of {@link #getContentLength(HttpMessage, long)}. @return the content length or {@code defaultValue} if this message does not have the {@code "Content-Length"} header or its value is not a number. Not to exceed the boundaries of integer.
[ "Get", "an", "{", "@code", "int", "}", "representation", "of", "{", "@link", "#getContentLength", "(", "HttpMessage", "long", ")", "}", "." ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpUtil.java#L195-L197
OpenLiberty/open-liberty
dev/com.ibm.ws.clientcontainer/src/com/ibm/ws/clientcontainer/internal/LifecycleCallbackHelper.java
LifecycleCallbackHelper.getAnnotatedMethod
@SuppressWarnings("rawtypes") public Method getAnnotatedMethod(Class clazz, Class<? extends Annotation> annotationClass) { Method m = null; Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Annotation[] a = methods[i].getAnnotations(); if (a != null) { for (int j = 0; j < a.length; j++) { if (a[j].annotationType() == annotationClass) { if (m == null) { m = methods[i]; } else { Tr.warning(tc, "DUPLICATE_CALLBACK_METHOD_CWWKC2454W", new Object[] { methods[i].getName(), clazz.getName() }); } } } } } return m; }
java
@SuppressWarnings("rawtypes") public Method getAnnotatedMethod(Class clazz, Class<? extends Annotation> annotationClass) { Method m = null; Method[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { Annotation[] a = methods[i].getAnnotations(); if (a != null) { for (int j = 0; j < a.length; j++) { if (a[j].annotationType() == annotationClass) { if (m == null) { m = methods[i]; } else { Tr.warning(tc, "DUPLICATE_CALLBACK_METHOD_CWWKC2454W", new Object[] { methods[i].getName(), clazz.getName() }); } } } } } return m; }
[ "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "public", "Method", "getAnnotatedMethod", "(", "Class", "clazz", ",", "Class", "<", "?", "extends", "Annotation", ">", "annotationClass", ")", "{", "Method", "m", "=", "null", ";", "Method", "[", "]", "metho...
Gets the annotated method from the class object. @param clazz the Class to be inspected. @param annotationClass the annotation class object @return a Method object or null if there is no annotated method.
[ "Gets", "the", "annotated", "method", "from", "the", "class", "object", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.clientcontainer/src/com/ibm/ws/clientcontainer/internal/LifecycleCallbackHelper.java#L156-L177
JOML-CI/JOML
src/org/joml/RayAabIntersection.java
RayAabIntersection.set
public void set(float originX, float originY, float originZ, float dirX, float dirY, float dirZ) { this.originX = originX; this.originY = originY; this.originZ = originZ; this.dirX = dirX; this.dirY = dirY; this.dirZ = dirZ; precomputeSlope(); }
java
public void set(float originX, float originY, float originZ, float dirX, float dirY, float dirZ) { this.originX = originX; this.originY = originY; this.originZ = originZ; this.dirX = dirX; this.dirY = dirY; this.dirZ = dirZ; precomputeSlope(); }
[ "public", "void", "set", "(", "float", "originX", ",", "float", "originY", ",", "float", "originZ", ",", "float", "dirX", ",", "float", "dirY", ",", "float", "dirZ", ")", "{", "this", ".", "originX", "=", "originX", ";", "this", ".", "originY", "=", ...
Update the ray stored by this {@link RayAabIntersection} with the new origin <code>(originX, originY, originZ)</code> and direction <code>(dirX, dirY, dirZ)</code>. @param originX the x coordinate of the ray origin @param originY the y coordinate of the ray origin @param originZ the z coordinate of the ray origin @param dirX the x coordinate of the ray direction @param dirY the y coordinate of the ray direction @param dirZ the z coordinate of the ray direction
[ "Update", "the", "ray", "stored", "by", "this", "{", "@link", "RayAabIntersection", "}", "with", "the", "new", "origin", "<code", ">", "(", "originX", "originY", "originZ", ")", "<", "/", "code", ">", "and", "direction", "<code", ">", "(", "dirX", "dirY"...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/RayAabIntersection.java#L100-L108
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.debtAccount_debt_debtId_GET
public OvhDebt debtAccount_debt_debtId_GET(Long debtId) throws IOException { String qPath = "/me/debtAccount/debt/{debtId}"; StringBuilder sb = path(qPath, debtId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDebt.class); }
java
public OvhDebt debtAccount_debt_debtId_GET(Long debtId) throws IOException { String qPath = "/me/debtAccount/debt/{debtId}"; StringBuilder sb = path(qPath, debtId); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhDebt.class); }
[ "public", "OvhDebt", "debtAccount_debt_debtId_GET", "(", "Long", "debtId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/debtAccount/debt/{debtId}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "debtId", ")", ";", "String", "re...
Get this object properties REST: GET /me/debtAccount/debt/{debtId} @param debtId [required]
[ "Get", "this", "object", "properties" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2745-L2750
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java
AmazonS3Client.resolveRequestEndpoint
private void resolveRequestEndpoint(Request<?> request, String bucketName, String key, URI endpoint) { ServiceEndpointBuilder builder = getBuilder(endpoint, endpoint.getScheme(), false); buildEndpointResolver(builder, bucketName, key).resolveRequestEndpoint(request); }
java
private void resolveRequestEndpoint(Request<?> request, String bucketName, String key, URI endpoint) { ServiceEndpointBuilder builder = getBuilder(endpoint, endpoint.getScheme(), false); buildEndpointResolver(builder, bucketName, key).resolveRequestEndpoint(request); }
[ "private", "void", "resolveRequestEndpoint", "(", "Request", "<", "?", ">", "request", ",", "String", "bucketName", ",", "String", "key", ",", "URI", "endpoint", ")", "{", "ServiceEndpointBuilder", "builder", "=", "getBuilder", "(", "endpoint", ",", "endpoint", ...
Configure the given request with an endpoint and resource path based on the bucket name and key provided
[ "Configure", "the", "given", "request", "with", "an", "endpoint", "and", "resource", "path", "based", "on", "the", "bucket", "name", "and", "key", "provided" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3Client.java#L4663-L4666
skyscreamer/JSONassert
src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
JSONAssert.assertNotEquals
public static void assertNotEquals(String expectedStr, String actualStr, JSONCompareMode compareMode) throws JSONException { assertNotEquals("", expectedStr, actualStr, compareMode); }
java
public static void assertNotEquals(String expectedStr, String actualStr, JSONCompareMode compareMode) throws JSONException { assertNotEquals("", expectedStr, actualStr, compareMode); }
[ "public", "static", "void", "assertNotEquals", "(", "String", "expectedStr", ",", "String", "actualStr", ",", "JSONCompareMode", "compareMode", ")", "throws", "JSONException", "{", "assertNotEquals", "(", "\"\"", ",", "expectedStr", ",", "actualStr", ",", "compareMo...
Asserts that the JSONArray provided does not match the expected string. If it is it throws an {@link AssertionError}. @param expectedStr Expected JSON string @param actualStr String to compare @param compareMode Specifies which comparison mode to use @throws JSONException JSON parsing error
[ "Asserts", "that", "the", "JSONArray", "provided", "does", "not", "match", "the", "expected", "string", ".", "If", "it", "is", "it", "throws", "an", "{", "@link", "AssertionError", "}", "." ]
train
https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L430-L433
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.newPoolInstance
public void newPoolInstance(CmsParameterConfiguration configuration, String poolName) throws CmsInitException { CmsDbPoolV11 pool; try { pool = new CmsDbPoolV11(configuration, poolName); } catch (Exception e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_INIT_CONN_POOL_1, poolName); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsInitException(message, e); } addPool(pool); }
java
public void newPoolInstance(CmsParameterConfiguration configuration, String poolName) throws CmsInitException { CmsDbPoolV11 pool; try { pool = new CmsDbPoolV11(configuration, poolName); } catch (Exception e) { CmsMessageContainer message = Messages.get().container(Messages.ERR_INIT_CONN_POOL_1, poolName); if (LOG.isErrorEnabled()) { LOG.error(message.key(), e); } throw new CmsInitException(message, e); } addPool(pool); }
[ "public", "void", "newPoolInstance", "(", "CmsParameterConfiguration", "configuration", ",", "String", "poolName", ")", "throws", "CmsInitException", "{", "CmsDbPoolV11", "pool", ";", "try", "{", "pool", "=", "new", "CmsDbPoolV11", "(", "configuration", ",", "poolNa...
Method to create a new instance of a pool.<p> @param configuration the configurations from the propertyfile @param poolName the configuration name of the pool @throws CmsInitException if the pools could not be initialized
[ "Method", "to", "create", "a", "new", "instance", "of", "a", "pool", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L6019-L6034
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java
MultiViewOps.createFundamental
public static DMatrixRMaj createFundamental(DMatrixRMaj R, Vector3D_F64 T, DMatrixRMaj K1, DMatrixRMaj K2, @Nullable DMatrixRMaj F ) { if( F == null ) F = new DMatrixRMaj(3,3); else F.reshape(3,3); createEssential(R,T,F); F.set(createFundamental(F,K1,K2)); return F; }
java
public static DMatrixRMaj createFundamental(DMatrixRMaj R, Vector3D_F64 T, DMatrixRMaj K1, DMatrixRMaj K2, @Nullable DMatrixRMaj F ) { if( F == null ) F = new DMatrixRMaj(3,3); else F.reshape(3,3); createEssential(R,T,F); F.set(createFundamental(F,K1,K2)); return F; }
[ "public", "static", "DMatrixRMaj", "createFundamental", "(", "DMatrixRMaj", "R", ",", "Vector3D_F64", "T", ",", "DMatrixRMaj", "K1", ",", "DMatrixRMaj", "K2", ",", "@", "Nullable", "DMatrixRMaj", "F", ")", "{", "if", "(", "F", "==", "null", ")", "F", "=", ...
<p> Computes an fudamental matrix from a rotation, translation, and calibration matrix. Motion is from the first camera frame into the second camera frame. </p> @param R Rotation matrix. first to second @param T Translation vector. first to second @param K1 Intrinsic camera calibration matrix for camera 1 @param K2 Intrinsic camera calibration matrix for camera 2 @param F (Output) Storage for essential matrix. 3x3 matrix @return Essential matrix
[ "<p", ">", "Computes", "an", "fudamental", "matrix", "from", "a", "rotation", "translation", "and", "calibration", "matrix", ".", "Motion", "is", "from", "the", "first", "camera", "frame", "into", "the", "second", "camera", "frame", ".", "<", "/", "p", ">"...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/MultiViewOps.java#L751-L762
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.setFeatureStyle
public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyleExtension featureStyleExtension, FeatureRow featureRow, float density) { return setFeatureStyle(markerOptions, featureStyleExtension, featureRow, density, null); }
java
public static boolean setFeatureStyle(MarkerOptions markerOptions, FeatureStyleExtension featureStyleExtension, FeatureRow featureRow, float density) { return setFeatureStyle(markerOptions, featureStyleExtension, featureRow, density, null); }
[ "public", "static", "boolean", "setFeatureStyle", "(", "MarkerOptions", "markerOptions", ",", "FeatureStyleExtension", "featureStyleExtension", ",", "FeatureRow", "featureRow", ",", "float", "density", ")", "{", "return", "setFeatureStyle", "(", "markerOptions", ",", "f...
Set the feature row style (icon or style) into the marker options @param markerOptions marker options @param featureStyleExtension feature style extension @param featureRow feature row @param density display density: {@link android.util.DisplayMetrics#density} @return true if icon or style was set into the marker options
[ "Set", "the", "feature", "row", "style", "(", "icon", "or", "style", ")", "into", "the", "marker", "options" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L111-L113
apache/flink
flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/AbstractFetcher.java
AbstractFetcher.registerOffsetMetrics
private void registerOffsetMetrics( MetricGroup consumerMetricGroup, List<KafkaTopicPartitionState<KPH>> partitionOffsetStates) { for (KafkaTopicPartitionState<KPH> ktp : partitionOffsetStates) { MetricGroup topicPartitionGroup = consumerMetricGroup .addGroup(OFFSETS_BY_TOPIC_METRICS_GROUP, ktp.getTopic()) .addGroup(OFFSETS_BY_PARTITION_METRICS_GROUP, Integer.toString(ktp.getPartition())); topicPartitionGroup.gauge(CURRENT_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); topicPartitionGroup.gauge(COMMITTED_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); legacyCurrentOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); legacyCommittedOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); } }
java
private void registerOffsetMetrics( MetricGroup consumerMetricGroup, List<KafkaTopicPartitionState<KPH>> partitionOffsetStates) { for (KafkaTopicPartitionState<KPH> ktp : partitionOffsetStates) { MetricGroup topicPartitionGroup = consumerMetricGroup .addGroup(OFFSETS_BY_TOPIC_METRICS_GROUP, ktp.getTopic()) .addGroup(OFFSETS_BY_PARTITION_METRICS_GROUP, Integer.toString(ktp.getPartition())); topicPartitionGroup.gauge(CURRENT_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); topicPartitionGroup.gauge(COMMITTED_OFFSETS_METRICS_GAUGE, new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); legacyCurrentOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.CURRENT_OFFSET)); legacyCommittedOffsetsMetricGroup.gauge(getLegacyOffsetsMetricsGaugeName(ktp), new OffsetGauge(ktp, OffsetGaugeType.COMMITTED_OFFSET)); } }
[ "private", "void", "registerOffsetMetrics", "(", "MetricGroup", "consumerMetricGroup", ",", "List", "<", "KafkaTopicPartitionState", "<", "KPH", ">", ">", "partitionOffsetStates", ")", "{", "for", "(", "KafkaTopicPartitionState", "<", "KPH", ">", "ktp", ":", "partit...
For each partition, register a new metric group to expose current offsets and committed offsets. Per-partition metric groups can be scoped by user variables {@link KafkaConsumerMetricConstants#OFFSETS_BY_TOPIC_METRICS_GROUP} and {@link KafkaConsumerMetricConstants#OFFSETS_BY_PARTITION_METRICS_GROUP}. <p>Note: this method also registers gauges for deprecated offset metrics, to maintain backwards compatibility. @param consumerMetricGroup The consumer metric group @param partitionOffsetStates The partition offset state holders, whose values will be used to update metrics
[ "For", "each", "partition", "register", "a", "new", "metric", "group", "to", "expose", "current", "offsets", "and", "committed", "offsets", ".", "Per", "-", "partition", "metric", "groups", "can", "be", "scoped", "by", "user", "variables", "{", "@link", "Kaf...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/streaming/connectors/kafka/internals/AbstractFetcher.java#L616-L631
stratosphere/stratosphere
stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java
Configuration.setBytes
public void setBytes(String key, byte[] bytes) { String encoded = new String(Base64.encodeBase64(bytes)); setStringInternal(key, encoded); }
java
public void setBytes(String key, byte[] bytes) { String encoded = new String(Base64.encodeBase64(bytes)); setStringInternal(key, encoded); }
[ "public", "void", "setBytes", "(", "String", "key", ",", "byte", "[", "]", "bytes", ")", "{", "String", "encoded", "=", "new", "String", "(", "Base64", ".", "encodeBase64", "(", "bytes", ")", ")", ";", "setStringInternal", "(", "key", ",", "encoded", "...
Adds the given byte array to the configuration object. If key is <code>null</code> then nothing is added. @param key The key under which the bytes are added. @param bytes The bytes to be added.
[ "Adds", "the", "given", "byte", "array", "to", "the", "configuration", "object", ".", "If", "key", "is", "<code", ">", "null<", "/", "code", ">", "then", "nothing", "is", "added", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-core/src/main/java/eu/stratosphere/configuration/Configuration.java#L349-L352
Scout24/appmon4j
core/src/main/java/de/is24/util/monitoring/InApplicationMonitor.java
InApplicationMonitor.registerVersion
public void registerVersion(String name, String version) { Version versionToAdd = new Version(keyHandler.handle(name), version); getCorePlugin().registerVersion(versionToAdd); }
java
public void registerVersion(String name, String version) { Version versionToAdd = new Version(keyHandler.handle(name), version); getCorePlugin().registerVersion(versionToAdd); }
[ "public", "void", "registerVersion", "(", "String", "name", ",", "String", "version", ")", "{", "Version", "versionToAdd", "=", "new", "Version", "(", "keyHandler", ".", "handle", "(", "name", ")", ",", "version", ")", ";", "getCorePlugin", "(", ")", ".", ...
This method was intended to register module names with their current version identifier. This could / should actually be generalized into an non numeric state value @param name name of the versionized "thing" (class, module etc.) @param version identifier of the version
[ "This", "method", "was", "intended", "to", "register", "module", "names", "with", "their", "current", "version", "identifier", ".", "This", "could", "/", "should", "actually", "be", "generalized", "into", "an", "non", "numeric", "state", "value" ]
train
https://github.com/Scout24/appmon4j/blob/a662e5123805ea455cfd01e1b9ae5d808f83529c/core/src/main/java/de/is24/util/monitoring/InApplicationMonitor.java#L335-L338
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java
DiscreteDistributions.hypergeometric
public static double hypergeometric(int k, int n, int Kp, int Np) { if(k<0 || n<0 || Kp<0 || Np<0) { throw new IllegalArgumentException("All the parameters must be positive."); } Kp = Math.max(k, Kp); Np = Math.max(n, Np); /* //slow! $probability=StatsUtilities::combination($Kp,$k)*StatsUtilities::combination($Np-$Kp,$n-$k)/StatsUtilities::combination($Np,$n); */ //fast and can handle large numbers //Cdf(k)-Cdf(k-1) double probability = approxHypergeometricCdf(k,n,Kp,Np); if(k>0) { probability -= approxHypergeometricCdf(k-1,n,Kp,Np); } return probability; }
java
public static double hypergeometric(int k, int n, int Kp, int Np) { if(k<0 || n<0 || Kp<0 || Np<0) { throw new IllegalArgumentException("All the parameters must be positive."); } Kp = Math.max(k, Kp); Np = Math.max(n, Np); /* //slow! $probability=StatsUtilities::combination($Kp,$k)*StatsUtilities::combination($Np-$Kp,$n-$k)/StatsUtilities::combination($Np,$n); */ //fast and can handle large numbers //Cdf(k)-Cdf(k-1) double probability = approxHypergeometricCdf(k,n,Kp,Np); if(k>0) { probability -= approxHypergeometricCdf(k-1,n,Kp,Np); } return probability; }
[ "public", "static", "double", "hypergeometric", "(", "int", "k", ",", "int", "n", ",", "int", "Kp", ",", "int", "Np", ")", "{", "if", "(", "k", "<", "0", "||", "n", "<", "0", "||", "Kp", "<", "0", "||", "Np", "<", "0", ")", "{", "throw", "n...
Returns the probability of finding k successes on a sample of n, from a population with Kp successes and size Np @param k @param n @param Kp @param Np @return
[ "Returns", "the", "probability", "of", "finding", "k", "successes", "on", "a", "sample", "of", "n", "from", "a", "population", "with", "Kp", "successes", "and", "size", "Np" ]
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/DiscreteDistributions.java#L268-L289
LearnLib/learnlib
oracles/filters/cache/src/main/java/de/learnlib/filter/cache/dfa/DFACaches.java
DFACaches.createCache
public static <I> DFACacheOracle<I> createCache(Alphabet<I> alphabet, MembershipOracle<I, Boolean> mqOracle) { return createDAGCache(alphabet, mqOracle); }
java
public static <I> DFACacheOracle<I> createCache(Alphabet<I> alphabet, MembershipOracle<I, Boolean> mqOracle) { return createDAGCache(alphabet, mqOracle); }
[ "public", "static", "<", "I", ">", "DFACacheOracle", "<", "I", ">", "createCache", "(", "Alphabet", "<", "I", ">", "alphabet", ",", "MembershipOracle", "<", "I", ",", "Boolean", ">", "mqOracle", ")", "{", "return", "createDAGCache", "(", "alphabet", ",", ...
Creates a cache oracle for a DFA learning setup. <p> Note that this method does not specify the implementation to use for the cache. Currently, a DAG ({@link IncrementalDFABuilder}) is used; however, this may change in the future. @param alphabet the input alphabet @param mqOracle the membership oracle @return a Mealy learning cache with a default implementation
[ "Creates", "a", "cache", "oracle", "for", "a", "DFA", "learning", "setup", ".", "<p", ">", "Note", "that", "this", "method", "does", "not", "specify", "the", "implementation", "to", "use", "for", "the", "cache", ".", "Currently", "a", "DAG", "(", "{", ...
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/oracles/filters/cache/src/main/java/de/learnlib/filter/cache/dfa/DFACaches.java#L106-L108
apptik/JustJson
json-core/src/main/java/io/apptik/json/JsonObject.java
JsonObject.getInt
public Integer getInt(String name, boolean strict) throws JsonException { JsonElement el = get(name); Integer res = null; if (strict && !el.isNumber()) { throw Util.typeMismatch(name, el, "int", true); } if (el.isNumber()) { res = el.asInt(); } if (el.isString()) { res = Util.toInteger(el.asString()); } if (res == null) throw Util.typeMismatch(name, el, "int", strict); return res; }
java
public Integer getInt(String name, boolean strict) throws JsonException { JsonElement el = get(name); Integer res = null; if (strict && !el.isNumber()) { throw Util.typeMismatch(name, el, "int", true); } if (el.isNumber()) { res = el.asInt(); } if (el.isString()) { res = Util.toInteger(el.asString()); } if (res == null) throw Util.typeMismatch(name, el, "int", strict); return res; }
[ "public", "Integer", "getInt", "(", "String", "name", ",", "boolean", "strict", ")", "throws", "JsonException", "{", "JsonElement", "el", "=", "get", "(", "name", ")", ";", "Integer", "res", "=", "null", ";", "if", "(", "strict", "&&", "!", "el", ".", ...
Returns the value mapped by {@code name} if it exists and is an int or can be coerced to an int, or throws otherwise. @throws JsonException if the mapping doesn't exist or cannot be coerced to an int.
[ "Returns", "the", "value", "mapped", "by", "{", "@code", "name", "}", "if", "it", "exists", "and", "is", "an", "int", "or", "can", "be", "coerced", "to", "an", "int", "or", "throws", "otherwise", "." ]
train
https://github.com/apptik/JustJson/blob/c90f0dd7f84df26da4749be8cd9b026fff499a79/json-core/src/main/java/io/apptik/json/JsonObject.java#L466-L481
couchbase/couchbase-java-client
src/main/java/com/couchbase/client/java/analytics/AnalyticsQuery.java
AnalyticsQuery.parameterized
public static ParameterizedAnalyticsQuery parameterized(final String statement, final JsonObject namedParams) { return new ParameterizedAnalyticsQuery(statement, null, namedParams, null); }
java
public static ParameterizedAnalyticsQuery parameterized(final String statement, final JsonObject namedParams) { return new ParameterizedAnalyticsQuery(statement, null, namedParams, null); }
[ "public", "static", "ParameterizedAnalyticsQuery", "parameterized", "(", "final", "String", "statement", ",", "final", "JsonObject", "namedParams", ")", "{", "return", "new", "ParameterizedAnalyticsQuery", "(", "statement", ",", "null", ",", "namedParams", ",", "null"...
Creates an {@link AnalyticsQuery} with named parameters as part of the query. @param statement the statement to send. @param namedParams the named parameters which will be put in for the placeholders. @return a {@link AnalyticsQuery}.
[ "Creates", "an", "{", "@link", "AnalyticsQuery", "}", "with", "named", "parameters", "as", "part", "of", "the", "query", "." ]
train
https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/analytics/AnalyticsQuery.java#L105-L108
jboss/jboss-jstl-api_spec
src/main/java/org/apache/taglibs/standard/util/XmlUtil.java
XmlUtil.newSAXSource
public static SAXSource newSAXSource(Reader reader, String systemId, JstlEntityResolver entityResolver) throws ParserConfigurationException, SAXException { SAXSource source = new SAXSource(newXMLReader(entityResolver), new InputSource(reader)); source.setSystemId(wrapSystemId(systemId)); return source; }
java
public static SAXSource newSAXSource(Reader reader, String systemId, JstlEntityResolver entityResolver) throws ParserConfigurationException, SAXException { SAXSource source = new SAXSource(newXMLReader(entityResolver), new InputSource(reader)); source.setSystemId(wrapSystemId(systemId)); return source; }
[ "public", "static", "SAXSource", "newSAXSource", "(", "Reader", "reader", ",", "String", "systemId", ",", "JstlEntityResolver", "entityResolver", ")", "throws", "ParserConfigurationException", ",", "SAXException", "{", "SAXSource", "source", "=", "new", "SAXSource", "...
Create a SAXSource from a Reader. Any entities will be resolved using JSTL semantics. @param reader the source of the XML @param systemId the system id @param entityResolver for resolving using JSTL semamtics @return a new SAXSource @throws ParserConfigurationException if there was a configuration problem creating the source @throws SAXException if there was a problem creating the source
[ "Create", "a", "SAXSource", "from", "a", "Reader", ".", "Any", "entities", "will", "be", "resolved", "using", "JSTL", "semantics", "." ]
train
https://github.com/jboss/jboss-jstl-api_spec/blob/4ad412ae5be1ae606b8d33c188cb3d98bfcbe84c/src/main/java/org/apache/taglibs/standard/util/XmlUtil.java#L245-L250
dlew/joda-time-android
library/src/main/java/net/danlew/android/joda/ResUtils.java
ResUtils.getIdentifier
public static int getIdentifier(Class<?> type, String name) { // See if the cache already contains this identifier Map<String, Integer> typeCache; if (!sIdentifierCache.containsKey(type)) { typeCache = new ConcurrentHashMap<String, Integer>(); sIdentifierCache.put(type, typeCache); } else { typeCache = sIdentifierCache.get(type); } if (typeCache.containsKey(name)) { return typeCache.get(name); } // Retrieve the identifier try { Field field = type.getField(name); int resId = field.getInt(null); if (resId != 0) { typeCache.put(name, resId); } return resId; } catch (Exception e) { Log.e("JodaTimeAndroid", "Failed to retrieve identifier: type=" + type + " name=" + name, e); return 0; } }
java
public static int getIdentifier(Class<?> type, String name) { // See if the cache already contains this identifier Map<String, Integer> typeCache; if (!sIdentifierCache.containsKey(type)) { typeCache = new ConcurrentHashMap<String, Integer>(); sIdentifierCache.put(type, typeCache); } else { typeCache = sIdentifierCache.get(type); } if (typeCache.containsKey(name)) { return typeCache.get(name); } // Retrieve the identifier try { Field field = type.getField(name); int resId = field.getInt(null); if (resId != 0) { typeCache.put(name, resId); } return resId; } catch (Exception e) { Log.e("JodaTimeAndroid", "Failed to retrieve identifier: type=" + type + " name=" + name, e); return 0; } }
[ "public", "static", "int", "getIdentifier", "(", "Class", "<", "?", ">", "type", ",", "String", "name", ")", "{", "// See if the cache already contains this identifier", "Map", "<", "String", ",", "Integer", ">", "typeCache", ";", "if", "(", "!", "sIdentifierCac...
Retrieves a resource id dynamically, via reflection. It's much faster than Resources.getIdentifier(), however it only allows you to get identifiers from your own package. Note that this method is still slower than retrieving resources directly (e.g., R.drawable.MyResource) - it should only be used when dynamically retrieving ids. Originally sourced from https://github.com/dlew/android-utils/ @param type the type of resource (e.g. R.drawable.class, R.layout.class, etc.) @param name the name of the resource @return the resource id, or 0 if not found
[ "Retrieves", "a", "resource", "id", "dynamically", "via", "reflection", ".", "It", "s", "much", "faster", "than", "Resources", ".", "getIdentifier", "()", "however", "it", "only", "allows", "you", "to", "get", "identifiers", "from", "your", "own", "package", ...
train
https://github.com/dlew/joda-time-android/blob/5bf96f6ef4ea63ee91e73e1e528896fa00108dec/library/src/main/java/net/danlew/android/joda/ResUtils.java#L88-L118
alkacon/opencms-core
src/org/opencms/xml/containerpage/CmsXmlContainerPage.java
CmsXmlContainerPage.fillResource
protected CmsResource fillResource(CmsObject cms, Element element, CmsUUID resourceId) throws CmsException { String xpath = element.getPath(); int pos = xpath.lastIndexOf("/" + XmlNode.Containers.name() + "/"); if (pos > 0) { xpath = xpath.substring(pos + 1); } CmsRelationType type = getHandler().getRelationType(xpath); CmsResource res = cms.readResource(resourceId, CmsResourceFilter.IGNORE_EXPIRATION); CmsXmlVfsFileValue.fillEntry(element, res.getStructureId(), res.getRootPath(), type); return res; }
java
protected CmsResource fillResource(CmsObject cms, Element element, CmsUUID resourceId) throws CmsException { String xpath = element.getPath(); int pos = xpath.lastIndexOf("/" + XmlNode.Containers.name() + "/"); if (pos > 0) { xpath = xpath.substring(pos + 1); } CmsRelationType type = getHandler().getRelationType(xpath); CmsResource res = cms.readResource(resourceId, CmsResourceFilter.IGNORE_EXPIRATION); CmsXmlVfsFileValue.fillEntry(element, res.getStructureId(), res.getRootPath(), type); return res; }
[ "protected", "CmsResource", "fillResource", "(", "CmsObject", "cms", ",", "Element", "element", ",", "CmsUUID", "resourceId", ")", "throws", "CmsException", "{", "String", "xpath", "=", "element", ".", "getPath", "(", ")", ";", "int", "pos", "=", "xpath", "....
Fills a {@link CmsXmlVfsFileValue} with the resource identified by the given id.<p> @param cms the current CMS context @param element the XML element to fill @param resourceId the ID identifying the resource to use @return the resource @throws CmsException if the resource can not be read
[ "Fills", "a", "{", "@link", "CmsXmlVfsFileValue", "}", "with", "the", "resource", "identified", "by", "the", "given", "id", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsXmlContainerPage.java#L445-L456
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java
DoubleIntIndex.addSorted
public synchronized boolean addSorted(int key, int value) { if (count == capacity) { if (fixedSize) { return false; } else { doubleCapacity(); } } if (count != 0 && value < values[count - 1]) { return false; } hasChanged = true; keys[count] = key; values[count] = value; count++; return true; }
java
public synchronized boolean addSorted(int key, int value) { if (count == capacity) { if (fixedSize) { return false; } else { doubleCapacity(); } } if (count != 0 && value < values[count - 1]) { return false; } hasChanged = true; keys[count] = key; values[count] = value; count++; return true; }
[ "public", "synchronized", "boolean", "addSorted", "(", "int", "key", ",", "int", "value", ")", "{", "if", "(", "count", "==", "capacity", ")", "{", "if", "(", "fixedSize", ")", "{", "return", "false", ";", "}", "else", "{", "doubleCapacity", "(", ")", ...
Adds a key, value pair into the table with the guarantee that the key is equal or larger than the largest existing key. This prevents a sort from taking place on next call to find() @param key the key @param value the value @return true or false depending on success
[ "Adds", "a", "key", "value", "pair", "into", "the", "table", "with", "the", "guarantee", "that", "the", "key", "is", "equal", "or", "larger", "than", "the", "largest", "existing", "key", ".", "This", "prevents", "a", "sort", "from", "taking", "place", "o...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/lib/DoubleIntIndex.java#L185-L206
beanshell/beanshell
src/main/java/bsh/Reflect.java
Reflect.getDeclaredMethod
public static BshMethod getDeclaredMethod(Class<?> type, String name, Class<?>[] sig) { if (!isGeneratedClass(type)) return null; BshMethod meth = getMethod(type, name, sig); if (null == meth && !type.isInterface()) return getMethod(getNewInstance(type), name, sig); return meth; }
java
public static BshMethod getDeclaredMethod(Class<?> type, String name, Class<?>[] sig) { if (!isGeneratedClass(type)) return null; BshMethod meth = getMethod(type, name, sig); if (null == meth && !type.isInterface()) return getMethod(getNewInstance(type), name, sig); return meth; }
[ "public", "static", "BshMethod", "getDeclaredMethod", "(", "Class", "<", "?", ">", "type", ",", "String", "name", ",", "Class", "<", "?", ">", "[", "]", "sig", ")", "{", "if", "(", "!", "isGeneratedClass", "(", "type", ")", ")", "return", "null", ";"...
/* Get method from either class static or object instance namespaces
[ "/", "*", "Get", "method", "from", "either", "class", "static", "or", "object", "instance", "namespaces" ]
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Reflect.java#L833-L840
elki-project/elki
elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/VAFile.java
VAFile.calculateApproximation
public VectorApproximation calculateApproximation(DBID id, V dv) { int[] approximation = new int[dv.getDimensionality()]; for(int d = 0; d < splitPositions.length; d++) { final double val = dv.doubleValue(d); final int lastBorderIndex = splitPositions[d].length - 1; // Value is below data grid if(val < splitPositions[d][0]) { approximation[d] = 0; if(id != null) { LOG.warning("Vector outside of VAFile grid!"); } } // Value is above data grid else if(val > splitPositions[d][lastBorderIndex]) { approximation[d] = lastBorderIndex - 1; if(id != null) { LOG.warning("Vector outside of VAFile grid!"); } } // normal case else { // Search grid position int pos = Arrays.binarySearch(splitPositions[d], val); pos = (pos >= 0) ? pos : ((-pos) - 2); approximation[d] = pos; } } return new VectorApproximation(id, approximation); }
java
public VectorApproximation calculateApproximation(DBID id, V dv) { int[] approximation = new int[dv.getDimensionality()]; for(int d = 0; d < splitPositions.length; d++) { final double val = dv.doubleValue(d); final int lastBorderIndex = splitPositions[d].length - 1; // Value is below data grid if(val < splitPositions[d][0]) { approximation[d] = 0; if(id != null) { LOG.warning("Vector outside of VAFile grid!"); } } // Value is above data grid else if(val > splitPositions[d][lastBorderIndex]) { approximation[d] = lastBorderIndex - 1; if(id != null) { LOG.warning("Vector outside of VAFile grid!"); } } // normal case else { // Search grid position int pos = Arrays.binarySearch(splitPositions[d], val); pos = (pos >= 0) ? pos : ((-pos) - 2); approximation[d] = pos; } } return new VectorApproximation(id, approximation); }
[ "public", "VectorApproximation", "calculateApproximation", "(", "DBID", "id", ",", "V", "dv", ")", "{", "int", "[", "]", "approximation", "=", "new", "int", "[", "dv", ".", "getDimensionality", "(", ")", "]", ";", "for", "(", "int", "d", "=", "0", ";",...
Calculate the VA file position given the existing borders. @param id Object ID @param dv Data vector @return Vector approximation
[ "Calculate", "the", "VA", "file", "position", "given", "the", "existing", "borders", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-various/src/main/java/de/lmu/ifi/dbs/elki/index/vafile/VAFile.java#L178-L205
graphql-java/graphql-java
src/main/java/graphql/schema/idl/SchemaTypeChecker.java
SchemaTypeChecker.checkDeprecatedDirective
static void checkDeprecatedDirective(List<GraphQLError> errors, Directive directive, Supplier<InvalidDeprecationDirectiveError> errorSupplier) { if ("deprecated".equals(directive.getName())) { // it can have zero args List<Argument> arguments = directive.getArguments(); if (arguments.size() == 0) { return; } // but if has more than it must have 1 called "reason" of type StringValue if (arguments.size() == 1) { Argument arg = arguments.get(0); if ("reason".equals(arg.getName()) && arg.getValue() instanceof StringValue) { return; } } // not valid errors.add(errorSupplier.get()); } }
java
static void checkDeprecatedDirective(List<GraphQLError> errors, Directive directive, Supplier<InvalidDeprecationDirectiveError> errorSupplier) { if ("deprecated".equals(directive.getName())) { // it can have zero args List<Argument> arguments = directive.getArguments(); if (arguments.size() == 0) { return; } // but if has more than it must have 1 called "reason" of type StringValue if (arguments.size() == 1) { Argument arg = arguments.get(0); if ("reason".equals(arg.getName()) && arg.getValue() instanceof StringValue) { return; } } // not valid errors.add(errorSupplier.get()); } }
[ "static", "void", "checkDeprecatedDirective", "(", "List", "<", "GraphQLError", ">", "errors", ",", "Directive", "directive", ",", "Supplier", "<", "InvalidDeprecationDirectiveError", ">", "errorSupplier", ")", "{", "if", "(", "\"deprecated\"", ".", "equals", "(", ...
A special check for the magic @deprecated directive @param errors the list of errors @param directive the directive to check @param errorSupplier the error supplier function
[ "A", "special", "check", "for", "the", "magic", "@deprecated", "directive" ]
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/schema/idl/SchemaTypeChecker.java#L347-L364
googleads/googleads-java-lib
examples/admanager_axis/src/main/java/admanager/axis/v201811/inventoryservice/GetTopLevelAdUnits.java
GetTopLevelAdUnits.runExample
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the InventoryService. InventoryServiceInterface inventoryService = adManagerServices.get(session, InventoryServiceInterface.class); // Get the NetworkService. NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class); // Set the parent ad unit's ID for all children ad units to be fetched from. String parentAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId(); // Create a statement to select ad units under the parent ad unit. StatementBuilder statementBuilder = new StatementBuilder() .where("parentId = :parentId") .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .withBindVariableValue("parentId", parentAdUnitId); // Default for total result set size. int totalResultSetSize = 0; do { // Get ad units by statement. AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (AdUnit adUnit : page.getResults()) { System.out.printf( "%d) Ad unit with ID '%s' and name '%s' was found.%n", i++, adUnit.getId(), adUnit.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
java
public static void runExample(AdManagerServices adManagerServices, AdManagerSession session) throws RemoteException { // Get the InventoryService. InventoryServiceInterface inventoryService = adManagerServices.get(session, InventoryServiceInterface.class); // Get the NetworkService. NetworkServiceInterface networkService = adManagerServices.get(session, NetworkServiceInterface.class); // Set the parent ad unit's ID for all children ad units to be fetched from. String parentAdUnitId = networkService.getCurrentNetwork().getEffectiveRootAdUnitId(); // Create a statement to select ad units under the parent ad unit. StatementBuilder statementBuilder = new StatementBuilder() .where("parentId = :parentId") .orderBy("id ASC") .limit(StatementBuilder.SUGGESTED_PAGE_LIMIT) .withBindVariableValue("parentId", parentAdUnitId); // Default for total result set size. int totalResultSetSize = 0; do { // Get ad units by statement. AdUnitPage page = inventoryService.getAdUnitsByStatement(statementBuilder.toStatement()); if (page.getResults() != null) { totalResultSetSize = page.getTotalResultSetSize(); int i = page.getStartIndex(); for (AdUnit adUnit : page.getResults()) { System.out.printf( "%d) Ad unit with ID '%s' and name '%s' was found.%n", i++, adUnit.getId(), adUnit.getName()); } } statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT); } while (statementBuilder.getOffset() < totalResultSetSize); System.out.printf("Number of results found: %d%n", totalResultSetSize); }
[ "public", "static", "void", "runExample", "(", "AdManagerServices", "adManagerServices", ",", "AdManagerSession", "session", ")", "throws", "RemoteException", "{", "// Get the InventoryService.", "InventoryServiceInterface", "inventoryService", "=", "adManagerServices", ".", ...
Runs the example. @param adManagerServices the services factory. @param session the session. @throws ApiException if the API request failed with one or more service errors. @throws RemoteException if the API request failed due to other errors.
[ "Runs", "the", "example", "." ]
train
https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201811/inventoryservice/GetTopLevelAdUnits.java#L53-L95
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/formats/html/AllClassesFrameWriter.java
AllClassesFrameWriter.addContents
protected void addContents(List<Doc> classlist, boolean wantFrames, Content content) { for (int i = 0; i < classlist.size(); i++) { ClassDoc cd = (ClassDoc)classlist.get(i); if (!Util.isCoreClass(cd)) { continue; } Content label = italicsClassName(cd, false); Content linkContent; if (wantFrames) { linkContent = getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.ALL_CLASSES_FRAME, cd).label(label).target("classFrame")); } else { linkContent = getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.DEFAULT, cd).label(label)); } Content li = HtmlTree.LI(linkContent); content.addContent(li); } }
java
protected void addContents(List<Doc> classlist, boolean wantFrames, Content content) { for (int i = 0; i < classlist.size(); i++) { ClassDoc cd = (ClassDoc)classlist.get(i); if (!Util.isCoreClass(cd)) { continue; } Content label = italicsClassName(cd, false); Content linkContent; if (wantFrames) { linkContent = getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.ALL_CLASSES_FRAME, cd).label(label).target("classFrame")); } else { linkContent = getLink(new LinkInfoImpl(configuration, LinkInfoImpl.Kind.DEFAULT, cd).label(label)); } Content li = HtmlTree.LI(linkContent); content.addContent(li); } }
[ "protected", "void", "addContents", "(", "List", "<", "Doc", ">", "classlist", ",", "boolean", "wantFrames", ",", "Content", "content", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "classlist", ".", "size", "(", ")", ";", "i", "++", "...
Given a list of classes, generate links for each class or interface. If the class kind is interface, print it in the italics font. Also all links should target the right-hand frame. If clicked on any class name in this page, appropriate class page should get opened in the right-hand frame. @param classlist Sorted list of classes. @param wantFrames True if we want frames. @param content HtmlTree content to which the links will be added
[ "Given", "a", "list", "of", "classes", "generate", "links", "for", "each", "class", "or", "interface", ".", "If", "the", "class", "kind", "is", "interface", "print", "it", "in", "the", "italics", "font", ".", "Also", "all", "links", "should", "target", "...
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/formats/html/AllClassesFrameWriter.java#L152-L170
SeleniumHQ/selenium
java/client/src/org/openqa/selenium/interactions/Actions.java
Actions.dragAndDrop
public Actions dragAndDrop(WebElement source, WebElement target) { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, (Locatable) source)); action.addAction(new MoveMouseAction(jsonMouse, (Locatable) target)); action.addAction(new ButtonReleaseAction(jsonMouse, (Locatable) target)); } return moveInTicks(source, 0, 0) .tick(defaultMouse.createPointerDown(LEFT.asArg())) .moveInTicks(target, 0, 0) .tick(defaultMouse.createPointerUp(LEFT.asArg())); }
java
public Actions dragAndDrop(WebElement source, WebElement target) { if (isBuildingActions()) { action.addAction(new ClickAndHoldAction(jsonMouse, (Locatable) source)); action.addAction(new MoveMouseAction(jsonMouse, (Locatable) target)); action.addAction(new ButtonReleaseAction(jsonMouse, (Locatable) target)); } return moveInTicks(source, 0, 0) .tick(defaultMouse.createPointerDown(LEFT.asArg())) .moveInTicks(target, 0, 0) .tick(defaultMouse.createPointerUp(LEFT.asArg())); }
[ "public", "Actions", "dragAndDrop", "(", "WebElement", "source", ",", "WebElement", "target", ")", "{", "if", "(", "isBuildingActions", "(", ")", ")", "{", "action", ".", "addAction", "(", "new", "ClickAndHoldAction", "(", "jsonMouse", ",", "(", "Locatable", ...
A convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse. @param source element to emulate button down at. @param target element to move to and release the mouse at. @return A self reference.
[ "A", "convenience", "method", "that", "performs", "click", "-", "and", "-", "hold", "at", "the", "location", "of", "the", "source", "element", "moves", "to", "the", "location", "of", "the", "target", "element", "then", "releases", "the", "mouse", "." ]
train
https://github.com/SeleniumHQ/selenium/blob/7af172729f17b20269c8ca4ea6f788db48616535/java/client/src/org/openqa/selenium/interactions/Actions.java#L448-L459
cdk/cdk
tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java
MolecularFormulaManipulator.getMolecularFormula
public static IMolecularFormula getMolecularFormula(String stringMF, IMolecularFormula formula) { return getMolecularFormula(stringMF, formula, false); }
java
public static IMolecularFormula getMolecularFormula(String stringMF, IMolecularFormula formula) { return getMolecularFormula(stringMF, formula, false); }
[ "public", "static", "IMolecularFormula", "getMolecularFormula", "(", "String", "stringMF", ",", "IMolecularFormula", "formula", ")", "{", "return", "getMolecularFormula", "(", "stringMF", ",", "formula", ",", "false", ")", ";", "}" ]
add in a instance of IMolecularFormula the elements extracts form molecular formula string. The string is immediately analyzed and a set of Nodes is built based on this analysis <p> The hydrogens must be implicit. @param stringMF The molecularFormula string @return The filled IMolecularFormula @see #getMolecularFormula(String, IChemObjectBuilder)
[ "add", "in", "a", "instance", "of", "IMolecularFormula", "the", "elements", "extracts", "form", "molecular", "formula", "string", ".", "The", "string", "is", "immediately", "analyzed", "and", "a", "set", "of", "Nodes", "is", "built", "based", "on", "this", "...
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/formula/src/main/java/org/openscience/cdk/tools/manipulator/MolecularFormulaManipulator.java#L617-L619
couchbase/java-dcp-client
src/main/java/com/couchbase/client/dcp/util/Version.java
Version.parseVersion
public static Version parseVersion(String versionString) { requireNonNull(versionString, "versionString"); Matcher matcher = VERSION_PATTERN.matcher(versionString); if (matcher.matches() && matcher.groupCount() == 3) { int major = Integer.parseInt(matcher.group(1)); int minor = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0; int patch = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0; return new Version(major, minor, patch); } else { throw new IllegalArgumentException( "Expected a version string starting with X[.Y[.Z]], was " + versionString); } }
java
public static Version parseVersion(String versionString) { requireNonNull(versionString, "versionString"); Matcher matcher = VERSION_PATTERN.matcher(versionString); if (matcher.matches() && matcher.groupCount() == 3) { int major = Integer.parseInt(matcher.group(1)); int minor = matcher.group(2) != null ? Integer.parseInt(matcher.group(2)) : 0; int patch = matcher.group(3) != null ? Integer.parseInt(matcher.group(3)) : 0; return new Version(major, minor, patch); } else { throw new IllegalArgumentException( "Expected a version string starting with X[.Y[.Z]], was " + versionString); } }
[ "public", "static", "Version", "parseVersion", "(", "String", "versionString", ")", "{", "requireNonNull", "(", "versionString", ",", "\"versionString\"", ")", ";", "Matcher", "matcher", "=", "VERSION_PATTERN", ".", "matcher", "(", "versionString", ")", ";", "if",...
Parses a {@link String} into a {@link Version}. This expects a version string in the form of "X[.Y[.Z]][anything]". That is a major number, followed optionally by a minor only or a minor + a patch revision, everything after that being completely ignored. <p> The parsing is extremely lenient, accepting any input string whose first character is a decimal digit. <p> For example, the following version strings are valid: <pre> - "3.a.2" (3.0.0) considered only a major version since there's a char where minor number should be - "2" (2.0.0) - "3.11" (3.11.0) - "3.14.15" (3.14.15) - "1.2.3-SNAPSHOT-12.10.2014" (1.2.3) </pre> <p> Bad version strings cause an {@link IllegalArgumentException}, whereas a null one will cause a {@link NullPointerException}. @param versionString the string to parse into a Version. @return the major.minor.patch Version corresponding to the string. @throws IllegalArgumentException if the string cannot be correctly parsed into a Version. This happens if the input is empty, the first character is not a decimal digit, or if any version component is greater than Integer.MAX_VALUE. @throws NullPointerException if the string is null.
[ "Parses", "a", "{", "@link", "String", "}", "into", "a", "{", "@link", "Version", "}", ".", "This", "expects", "a", "version", "string", "in", "the", "form", "of", "X", "[", ".", "Y", "[", ".", "Z", "]]", "[", "anything", "]", ".", "That", "is", ...
train
https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/util/Version.java#L122-L135
b3dgs/lionengine
lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java
UtilMath.curveValue
public static double curveValue(double value, double dest, double speed) { Check.different(speed, 0.0); final double reciprocal = 1.0 / speed; final double invReciprocal = 1.0 - reciprocal; return value * invReciprocal + dest * reciprocal; }
java
public static double curveValue(double value, double dest, double speed) { Check.different(speed, 0.0); final double reciprocal = 1.0 / speed; final double invReciprocal = 1.0 - reciprocal; return value * invReciprocal + dest * reciprocal; }
[ "public", "static", "double", "curveValue", "(", "double", "value", ",", "double", "dest", ",", "double", "speed", ")", "{", "Check", ".", "different", "(", "speed", ",", "0.0", ")", ";", "final", "double", "reciprocal", "=", "1.0", "/", "speed", ";", ...
Apply progressive modifications to a value. @param value The value. @param dest The value to reach. @param speed The effect speed (must not be equal to 0.0). @return The modified value. @throws LionEngineException If invalid argument.
[ "Apply", "progressive", "modifications", "to", "a", "value", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/UtilMath.java#L157-L165
daimajia/AndroidImageSlider
library/src/main/java/com/daimajia/slider/library/Tricks/ViewPagerEx.java
ViewPagerEx.executeKeyEvent
public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; }
java
public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; }
[ "public", "boolean", "executeKeyEvent", "(", "KeyEvent", "event", ")", "{", "boolean", "handled", "=", "false", ";", "if", "(", "event", ".", "getAction", "(", ")", "==", "KeyEvent", ".", "ACTION_DOWN", ")", "{", "switch", "(", "event", ".", "getKeyCode", ...
You can call this function yourself to have the scroll view perform scrolling from a key event, just as if the event had been dispatched to it by the view hierarchy. @param event The key event to execute. @return Return true if the event was handled, else false.
[ "You", "can", "call", "this", "function", "yourself", "to", "have", "the", "scroll", "view", "perform", "scrolling", "from", "a", "key", "event", "just", "as", "if", "the", "event", "had", "been", "dispatched", "to", "it", "by", "the", "view", "hierarchy",...
train
https://github.com/daimajia/AndroidImageSlider/blob/e318cabdef668de985efdcc45ca304e2ac6f58b5/library/src/main/java/com/daimajia/slider/library/Tricks/ViewPagerEx.java#L2505-L2529
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/PROCLUS.java
PROCLUS.manhattanSegmentalDistance
private double manhattanSegmentalDistance(NumberVector o1, double[] o2, long[] dimensions) { double result = 0; int card = 0; for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) { result += Math.abs(o1.doubleValue(d) - o2[d]); ++card; } return result / card; }
java
private double manhattanSegmentalDistance(NumberVector o1, double[] o2, long[] dimensions) { double result = 0; int card = 0; for(int d = BitsUtil.nextSetBit(dimensions, 0); d >= 0; d = BitsUtil.nextSetBit(dimensions, d + 1)) { result += Math.abs(o1.doubleValue(d) - o2[d]); ++card; } return result / card; }
[ "private", "double", "manhattanSegmentalDistance", "(", "NumberVector", "o1", ",", "double", "[", "]", "o2", ",", "long", "[", "]", "dimensions", ")", "{", "double", "result", "=", "0", ";", "int", "card", "=", "0", ";", "for", "(", "int", "d", "=", ...
Returns the Manhattan segmental distance between o1 and o2 relative to the specified dimensions. @param o1 the first object @param o2 the second object @param dimensions the dimensions to be considered @return the Manhattan segmental distance between o1 and o2 relative to the specified dimensions
[ "Returns", "the", "Manhattan", "segmental", "distance", "between", "o1", "and", "o2", "relative", "to", "the", "specified", "dimensions", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/PROCLUS.java#L641-L649
citrusframework/citrus
modules/citrus-ws/src/main/java/com/consol/citrus/ws/addressing/WsAddressingHeaders.java
WsAddressingHeaders.setFrom
public void setFrom(String from) { try { this.from = new EndpointReference(new URI(from)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid from uri", e); } }
java
public void setFrom(String from) { try { this.from = new EndpointReference(new URI(from)); } catch (URISyntaxException e) { throw new CitrusRuntimeException("Invalid from uri", e); } }
[ "public", "void", "setFrom", "(", "String", "from", ")", "{", "try", "{", "this", ".", "from", "=", "new", "EndpointReference", "(", "new", "URI", "(", "from", ")", ")", ";", "}", "catch", "(", "URISyntaxException", "e", ")", "{", "throw", "new", "Ci...
Sets the from endpoint reference by string. @param from the from to set
[ "Sets", "the", "from", "endpoint", "reference", "by", "string", "." ]
train
https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ws/src/main/java/com/consol/citrus/ws/addressing/WsAddressingHeaders.java#L174-L180
google/closure-compiler
src/com/google/javascript/jscomp/AbstractCommandLineRunner.java
AbstractCommandLineRunner.createJsonFile
@GwtIncompatible("Unnecessary") JsonFileSpec createJsonFile(B options, String outputMarker, Function<String, String> escaper) throws IOException { Appendable jsOutput = new StringBuilder(); writeOutput( jsOutput, compiler, (JSModule) null, config.outputWrapper, outputMarker, escaper); JsonFileSpec jsonOutput = new JsonFileSpec(jsOutput.toString(), Strings.isNullOrEmpty(config.jsOutputFile) ? "compiled.js" : config.jsOutputFile); if (!Strings.isNullOrEmpty(options.sourceMapOutputPath)) { StringBuilder sourcemap = new StringBuilder(); compiler.getSourceMap().appendTo(sourcemap, jsonOutput.getPath()); jsonOutput.setSourceMap(sourcemap.toString()); } return jsonOutput; }
java
@GwtIncompatible("Unnecessary") JsonFileSpec createJsonFile(B options, String outputMarker, Function<String, String> escaper) throws IOException { Appendable jsOutput = new StringBuilder(); writeOutput( jsOutput, compiler, (JSModule) null, config.outputWrapper, outputMarker, escaper); JsonFileSpec jsonOutput = new JsonFileSpec(jsOutput.toString(), Strings.isNullOrEmpty(config.jsOutputFile) ? "compiled.js" : config.jsOutputFile); if (!Strings.isNullOrEmpty(options.sourceMapOutputPath)) { StringBuilder sourcemap = new StringBuilder(); compiler.getSourceMap().appendTo(sourcemap, jsonOutput.getPath()); jsonOutput.setSourceMap(sourcemap.toString()); } return jsonOutput; }
[ "@", "GwtIncompatible", "(", "\"Unnecessary\"", ")", "JsonFileSpec", "createJsonFile", "(", "B", "options", ",", "String", "outputMarker", ",", "Function", "<", "String", ",", "String", ">", "escaper", ")", "throws", "IOException", "{", "Appendable", "jsOutput", ...
Save the compiler output to a JsonFileSpec to be later written to stdout
[ "Save", "the", "compiler", "output", "to", "a", "JsonFileSpec", "to", "be", "later", "written", "to", "stdout" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/AbstractCommandLineRunner.java#L1463-L1482
Impetus/Kundera
src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/HBaseDataHandler.java
HBaseDataHandler.getExtPropertyFilters
private FilterList getExtPropertyFilters(EntityMetadata m, FilterList filterList) { Filter filter = getFilter(m.getTableName()); if (filter != null) { if (filterList == null) { filterList = new FilterList(); } filterList.addFilter(filter); } return filterList; }
java
private FilterList getExtPropertyFilters(EntityMetadata m, FilterList filterList) { Filter filter = getFilter(m.getTableName()); if (filter != null) { if (filterList == null) { filterList = new FilterList(); } filterList.addFilter(filter); } return filterList; }
[ "private", "FilterList", "getExtPropertyFilters", "(", "EntityMetadata", "m", ",", "FilterList", "filterList", ")", "{", "Filter", "filter", "=", "getFilter", "(", "m", ".", "getTableName", "(", ")", ")", ";", "if", "(", "filter", "!=", "null", ")", "{", "...
Gets the ext property filters. @param m the m @param filterList the filter list @return the ext property filters
[ "Gets", "the", "ext", "property", "filters", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-hbase/kundera-hbase-v2/src/main/java/com/impetus/client/hbase/admin/HBaseDataHandler.java#L206-L218
spacecowboy/NoNonsense-FilePicker
library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java
AbstractFilePickerFragment.onClickDir
public void onClickDir(@NonNull View view, @NonNull DirViewHolder viewHolder) { if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } }
java
public void onClickDir(@NonNull View view, @NonNull DirViewHolder viewHolder) { if (isDir(viewHolder.file)) { goToDir(viewHolder.file); } }
[ "public", "void", "onClickDir", "(", "@", "NonNull", "View", "view", ",", "@", "NonNull", "DirViewHolder", "viewHolder", ")", "{", "if", "(", "isDir", "(", "viewHolder", ".", "file", ")", ")", "{", "goToDir", "(", "viewHolder", ".", "file", ")", ";", "...
Called when a non-selectable item, typically a directory, is clicked. @param view that was clicked. Not used in default implementation. @param viewHolder for the clicked view
[ "Called", "when", "a", "non", "-", "selectable", "item", "typically", "a", "directory", "is", "clicked", "." ]
train
https://github.com/spacecowboy/NoNonsense-FilePicker/blob/396ef7fa5e87791170791f9d94c78f6e42a7679a/library/src/main/java/com/nononsenseapps/filepicker/AbstractFilePickerFragment.java#L710-L714
GenesysPureEngage/workspace-client-java
src/main/java/com/genesys/internal/workspace/api/MediaApi.java
MediaApi.placeInQueue
public ApiSuccessResponse placeInQueue(String mediatype, String id, PlaceInQueueData placeInQueueData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = placeInQueueWithHttpInfo(mediatype, id, placeInQueueData); return resp.getData(); }
java
public ApiSuccessResponse placeInQueue(String mediatype, String id, PlaceInQueueData placeInQueueData) throws ApiException { ApiResponse<ApiSuccessResponse> resp = placeInQueueWithHttpInfo(mediatype, id, placeInQueueData); return resp.getData(); }
[ "public", "ApiSuccessResponse", "placeInQueue", "(", "String", "mediatype", ",", "String", "id", ",", "PlaceInQueueData", "placeInQueueData", ")", "throws", "ApiException", "{", "ApiResponse", "<", "ApiSuccessResponse", ">", "resp", "=", "placeInQueueWithHttpInfo", "(",...
Place an interaction in a queue Place the interaction in the specified queue. @param mediatype The media channel. (required) @param id The ID of the interaction. (required) @param placeInQueueData (required) @return ApiSuccessResponse @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Place", "an", "interaction", "in", "a", "queue", "Place", "the", "interaction", "in", "the", "specified", "queue", "." ]
train
https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/MediaApi.java#L3118-L3121
foundation-runtime/service-directory
2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java
DirectoryConnection.onConnected
public void onConnected(int serverSessionTimeout, String sessionId, byte[] sessionPassword, int serverId) { if (serverSessionTimeout <= 0) { closeSession(); LOGGER.error("Unable to reconnect to Directory Server, session 0x" + sessionId + " has expired"); return; } boolean reopen = session.id == null || session.id.equals("") ? false : true; session.timeOut = serverSessionTimeout; session.id = sessionId; session.password = sessionPassword; session.serverId = serverId; if(getStatus().isAlive()){ setStatus(ConnectionStatus.CONNECTED); } if(reopen){ eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.REOPEN)); } else { eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.CREATED)); } LOGGER.info("Session establishment complete on server " + this.clientSocket.getRemoteSocketAddress() + ", sessionid = 0x" + sessionId + ", session timeout = " + session.timeOut + ", serverId=" + session.serverId); }
java
public void onConnected(int serverSessionTimeout, String sessionId, byte[] sessionPassword, int serverId) { if (serverSessionTimeout <= 0) { closeSession(); LOGGER.error("Unable to reconnect to Directory Server, session 0x" + sessionId + " has expired"); return; } boolean reopen = session.id == null || session.id.equals("") ? false : true; session.timeOut = serverSessionTimeout; session.id = sessionId; session.password = sessionPassword; session.serverId = serverId; if(getStatus().isAlive()){ setStatus(ConnectionStatus.CONNECTED); } if(reopen){ eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.REOPEN)); } else { eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.CREATED)); } LOGGER.info("Session establishment complete on server " + this.clientSocket.getRemoteSocketAddress() + ", sessionid = 0x" + sessionId + ", session timeout = " + session.timeOut + ", serverId=" + session.serverId); }
[ "public", "void", "onConnected", "(", "int", "serverSessionTimeout", ",", "String", "sessionId", ",", "byte", "[", "]", "sessionPassword", ",", "int", "serverId", ")", "{", "if", "(", "serverSessionTimeout", "<=", "0", ")", "{", "closeSession", "(", ")", ";"...
On the DirectoryConnection setup connection to DirectoryServer. @param serverSessionTimeout the session timeout. @param sessionId the session id. @param sessionPassword the session password. @param serverId the remote server id.
[ "On", "the", "DirectoryConnection", "setup", "connection", "to", "DirectoryServer", "." ]
train
https://github.com/foundation-runtime/service-directory/blob/a7bdefe173dc99e75eff4a24e07e6407e62f2ed4/2.0/sd-api/src/main/java/com/cisco/oss/foundation/directory/connect/DirectoryConnection.java#L673-L699
knowm/Sundial
src/main/java/org/knowm/sundial/SundialJobScheduler.java
SundialJobScheduler.removeTrigger
public static void removeTrigger(String triggerName) throws SundialSchedulerException { try { getScheduler().unscheduleJob(triggerName); } catch (SchedulerException e) { throw new SundialSchedulerException("ERROR REMOVING TRIGGER!!!", e); } }
java
public static void removeTrigger(String triggerName) throws SundialSchedulerException { try { getScheduler().unscheduleJob(triggerName); } catch (SchedulerException e) { throw new SundialSchedulerException("ERROR REMOVING TRIGGER!!!", e); } }
[ "public", "static", "void", "removeTrigger", "(", "String", "triggerName", ")", "throws", "SundialSchedulerException", "{", "try", "{", "getScheduler", "(", ")", ".", "unscheduleJob", "(", "triggerName", ")", ";", "}", "catch", "(", "SchedulerException", "e", ")...
Removes a Trigger matching the the given Trigger Name @param triggerName
[ "Removes", "a", "Trigger", "matching", "the", "the", "given", "Trigger", "Name" ]
train
https://github.com/knowm/Sundial/blob/0d61549fdfb8d6f884a1f2eed7e32ad39e2f4c62/src/main/java/org/knowm/sundial/SundialJobScheduler.java#L490-L497
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/override/RawResolvedFeatures.java
RawResolvedFeatures.requestNotificationOnChange
protected static void requestNotificationOnChange(JvmType type, Runnable listener) { Resource resource = type.eResource(); if (resource instanceof TypeResource) { IMirror mirror = ((TypeResource) resource).getMirror(); if (mirror instanceof IMirrorExtension) { if (((IMirrorExtension) mirror).isSealed()) return; } } Notifier notifier = type; if (resource != null) { if (resource.getResourceSet() != null) notifier = resource.getResourceSet(); else notifier = resource; } JvmTypeChangeDispatcher dispatcher = JvmTypeChangeDispatcher.findResourceChangeDispatcher(notifier); dispatcher.requestNotificationOnChange(type, listener); }
java
protected static void requestNotificationOnChange(JvmType type, Runnable listener) { Resource resource = type.eResource(); if (resource instanceof TypeResource) { IMirror mirror = ((TypeResource) resource).getMirror(); if (mirror instanceof IMirrorExtension) { if (((IMirrorExtension) mirror).isSealed()) return; } } Notifier notifier = type; if (resource != null) { if (resource.getResourceSet() != null) notifier = resource.getResourceSet(); else notifier = resource; } JvmTypeChangeDispatcher dispatcher = JvmTypeChangeDispatcher.findResourceChangeDispatcher(notifier); dispatcher.requestNotificationOnChange(type, listener); }
[ "protected", "static", "void", "requestNotificationOnChange", "(", "JvmType", "type", ",", "Runnable", "listener", ")", "{", "Resource", "resource", "=", "type", ".", "eResource", "(", ")", ";", "if", "(", "resource", "instanceof", "TypeResource", ")", "{", "I...
Registers the given listener to be notified on type changes, if (and only if) the type if expected to be changeable. @see IMirrorExtension#isSealed()
[ "Registers", "the", "given", "listener", "to", "be", "notified", "on", "type", "changes", "if", "(", "and", "only", "if", ")", "the", "type", "if", "expected", "to", "be", "changeable", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/typesystem/override/RawResolvedFeatures.java#L87-L105
jenetics/jpx
jpx/src/main/java/io/jenetics/jpx/IO.java
IO.writeInt
static void writeInt(final int value, final DataOutput out) throws IOException { // Zig-zag encoding. int n = (value << 1)^(value >> 31); if ((n & ~0x7F) != 0) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; } } } } out.write((byte)n); }
java
static void writeInt(final int value, final DataOutput out) throws IOException { // Zig-zag encoding. int n = (value << 1)^(value >> 31); if ((n & ~0x7F) != 0) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; if (n > 0x7F) { out.write((byte)((n | 0x80) & 0xFF)); n >>>= 7; } } } } out.write((byte)n); }
[ "static", "void", "writeInt", "(", "final", "int", "value", ",", "final", "DataOutput", "out", ")", "throws", "IOException", "{", "// Zig-zag encoding.", "int", "n", "=", "(", "value", "<<", "1", ")", "^", "(", "value", ">>", "31", ")", ";", "if", "(",...
Writes an int value to a series of bytes. The values are written using <a href="http://lucene.apache.org/core/3_5_0/fileformats.html#VInt">variable-length</a> <a href="https://developers.google.com/protocol-buffers/docs/encoding?csw=1#types">zig-zag</a> coding. Each {@code int} value is written in 1 to 5 bytes. @see #readInt(DataInput) @param value the integer value to write @param out the data output the integer value is written to @throws NullPointerException if the given data output is {@code null} @throws IOException if an I/O error occurs
[ "Writes", "an", "int", "value", "to", "a", "series", "of", "bytes", ".", "The", "values", "are", "written", "using", "<a", "href", "=", "http", ":", "//", "lucene", ".", "apache", ".", "org", "/", "core", "/", "3_5_0", "/", "fileformats", ".", "html#...
train
https://github.com/jenetics/jpx/blob/58fefc10580602d07f1480d6a5886d13a553ff8f/jpx/src/main/java/io/jenetics/jpx/IO.java#L222-L242
facebook/fresco
samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/DraweeUtil.java
DraweeUtil.setBgColor
public static void setBgColor(View view, final Config config) { int[] colors = view.getContext().getResources().getIntArray(R.array.bg_colors); final int bgColor = colors[config.bgColor]; view.setBackgroundColor(bgColor); }
java
public static void setBgColor(View view, final Config config) { int[] colors = view.getContext().getResources().getIntArray(R.array.bg_colors); final int bgColor = colors[config.bgColor]; view.setBackgroundColor(bgColor); }
[ "public", "static", "void", "setBgColor", "(", "View", "view", ",", "final", "Config", "config", ")", "{", "int", "[", "]", "colors", "=", "view", ".", "getContext", "(", ")", ".", "getResources", "(", ")", ".", "getIntArray", "(", "R", ".", "array", ...
Utility method which set the bgColor based on configuration values @param view The View to change the bgColor to @param config The Config object
[ "Utility", "method", "which", "set", "the", "bgColor", "based", "on", "configuration", "values" ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/samples/scrollperf/src/main/java/com/facebook/samples/scrollperf/util/DraweeUtil.java#L107-L111
xebia-france/xebia-servlet-extras
src/main/java/fr/xebia/servlet/filter/SecuredRemoteAddressFilter.java
SecuredRemoteAddressFilter.doFilter
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletRequest xRequest; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { if (!request.isSecure() && matchesOne(request.getRemoteAddr(), securedRemoteAddresses)) { xRequest = new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public boolean isSecure() { return true; } }; } else { xRequest = request; } if (logger.isDebugEnabled()) { logger.debug("Incoming request uri=" + ((HttpServletRequest) request).getRequestURI() + " with originalSecure='" + request.isSecure() + "', remoteAddr='" + request.getRemoteAddr() + "' will be seen with newSecure='" + xRequest.isSecure() + "'"); } } else { xRequest = request; } chain.doFilter(xRequest, response); }
java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { ServletRequest xRequest; if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { if (!request.isSecure() && matchesOne(request.getRemoteAddr(), securedRemoteAddresses)) { xRequest = new HttpServletRequestWrapper((HttpServletRequest) request) { @Override public boolean isSecure() { return true; } }; } else { xRequest = request; } if (logger.isDebugEnabled()) { logger.debug("Incoming request uri=" + ((HttpServletRequest) request).getRequestURI() + " with originalSecure='" + request.isSecure() + "', remoteAddr='" + request.getRemoteAddr() + "' will be seen with newSecure='" + xRequest.isSecure() + "'"); } } else { xRequest = request; } chain.doFilter(xRequest, response); }
[ "public", "void", "doFilter", "(", "ServletRequest", "request", ",", "ServletResponse", "response", ",", "FilterChain", "chain", ")", "throws", "IOException", ",", "ServletException", "{", "ServletRequest", "xRequest", ";", "if", "(", "request", "instanceof", "HttpS...
If incoming remote address matches one of the declared IP pattern, wraps the incoming {@link HttpServletRequest} to override {@link HttpServletRequest#isSecure()} to set it to <code>true</code>.
[ "If", "incoming", "remote", "address", "matches", "one", "of", "the", "declared", "IP", "pattern", "wraps", "the", "incoming", "{" ]
train
https://github.com/xebia-france/xebia-servlet-extras/blob/b263636fc78f8794dde57d92b835edb5e95ce379/src/main/java/fr/xebia/servlet/filter/SecuredRemoteAddressFilter.java#L177-L200
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
Dynamic.ofInvocation
public static Dynamic ofInvocation(Constructor<?> constructor, List<?> rawArguments) { return ofInvocation(new MethodDescription.ForLoadedConstructor(constructor), rawArguments); }
java
public static Dynamic ofInvocation(Constructor<?> constructor, List<?> rawArguments) { return ofInvocation(new MethodDescription.ForLoadedConstructor(constructor), rawArguments); }
[ "public", "static", "Dynamic", "ofInvocation", "(", "Constructor", "<", "?", ">", "constructor", ",", "List", "<", "?", ">", "rawArguments", ")", "{", "return", "ofInvocation", "(", "new", "MethodDescription", ".", "ForLoadedConstructor", "(", "constructor", ")"...
Represents a constant that is resolved by invoking a constructor. @param constructor The constructor to invoke to create the represented constant value. @param rawArguments The constructor's constant arguments. @return A dynamic constant that is resolved by the supplied constuctor.
[ "Represents", "a", "constant", "that", "is", "resolved", "by", "invoking", "a", "constructor", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1553-L1555
allure-framework/allure1
allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java
AllureResultsUtils.writeAttachment
public static Attachment writeAttachment(byte[] attachment, String title, String type) throws IOException { String name = generateAttachmentName(); String extension = getExtensionByMimeType(type); String source = name + extension; File file = new File(getResultsDirectory(), source); synchronized (ATTACHMENTS_LOCK) { if (!file.exists()) { try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(attachment); } } } return new Attachment().withTitle(title).withSource(source).withType(type); }
java
public static Attachment writeAttachment(byte[] attachment, String title, String type) throws IOException { String name = generateAttachmentName(); String extension = getExtensionByMimeType(type); String source = name + extension; File file = new File(getResultsDirectory(), source); synchronized (ATTACHMENTS_LOCK) { if (!file.exists()) { try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(attachment); } } } return new Attachment().withTitle(title).withSource(source).withType(type); }
[ "public", "static", "Attachment", "writeAttachment", "(", "byte", "[", "]", "attachment", ",", "String", "title", ",", "String", "type", ")", "throws", "IOException", "{", "String", "name", "=", "generateAttachmentName", "(", ")", ";", "String", "extension", "...
Write attachment with specified type. Generate attachment name uses {@link #generateAttachmentName()}, attachment extension uses {@link #getExtensionByMimeType(String)} @param attachment byte array with attachment @param title attachment title @param type valid mime-type of attachment @return Created {@link ru.yandex.qatools.allure.model.Attachment} @throws IOException if can't write attachment
[ "Write", "attachment", "with", "specified", "type", ".", "Generate", "attachment", "name", "uses", "{", "@link", "#generateAttachmentName", "()", "}", "attachment", "extension", "uses", "{", "@link", "#getExtensionByMimeType", "(", "String", ")", "}" ]
train
https://github.com/allure-framework/allure1/blob/9a816fa05d8b894a917b7ebb7fd1a4056dee4693/allure-java-adaptor-api/src/main/java/ru/yandex/qatools/allure/utils/AllureResultsUtils.java#L265-L279
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
Dynamic.ofInvocation
public static Dynamic ofInvocation(Constructor<?> constructor, Object... rawArgument) { return ofInvocation(constructor, Arrays.asList(rawArgument)); }
java
public static Dynamic ofInvocation(Constructor<?> constructor, Object... rawArgument) { return ofInvocation(constructor, Arrays.asList(rawArgument)); }
[ "public", "static", "Dynamic", "ofInvocation", "(", "Constructor", "<", "?", ">", "constructor", ",", "Object", "...", "rawArgument", ")", "{", "return", "ofInvocation", "(", "constructor", ",", "Arrays", ".", "asList", "(", "rawArgument", ")", ")", ";", "}"...
Represents a constant that is resolved by invoking a constructor. @param constructor The constructor to invoke to create the represented constant value. @param rawArgument The constructor's constant arguments. @return A dynamic constant that is resolved by the supplied constuctor.
[ "Represents", "a", "constant", "that", "is", "resolved", "by", "invoking", "a", "constructor", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1542-L1544
javalite/activejdbc
activejdbc/src/main/java/org/javalite/activejdbc/Base.java
Base.firstCell
public static Object firstCell(String query, Object... params) { return new DB(DB.DEFAULT_NAME).firstCell(query, params); }
java
public static Object firstCell(String query, Object... params) { return new DB(DB.DEFAULT_NAME).firstCell(query, params); }
[ "public", "static", "Object", "firstCell", "(", "String", "query", ",", "Object", "...", "params", ")", "{", "return", "new", "DB", "(", "DB", ".", "DEFAULT_NAME", ")", ".", "firstCell", "(", "query", ",", "params", ")", ";", "}" ]
Returns a value of the first column of the first row. This query expects only one column selected in the select statement. If more than one column returned, it will throw {@link IllegalArgumentException}. @param query query @param params parameters @return fetched value, or null if query did not fetch anything.
[ "Returns", "a", "value", "of", "the", "first", "column", "of", "the", "first", "row", ".", "This", "query", "expects", "only", "one", "column", "selected", "in", "the", "select", "statement", ".", "If", "more", "than", "one", "column", "returned", "it", ...
train
https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/activejdbc/src/main/java/org/javalite/activejdbc/Base.java#L178-L180
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/lib/MultipleOutputs.java
MultipleOutputs.isMultiNamedOutput
public static boolean isMultiNamedOutput(JobConf conf, String namedOutput) { checkNamedOutput(conf, namedOutput, false); return conf.getBoolean(MO_PREFIX + namedOutput + MULTI, false); }
java
public static boolean isMultiNamedOutput(JobConf conf, String namedOutput) { checkNamedOutput(conf, namedOutput, false); return conf.getBoolean(MO_PREFIX + namedOutput + MULTI, false); }
[ "public", "static", "boolean", "isMultiNamedOutput", "(", "JobConf", "conf", ",", "String", "namedOutput", ")", "{", "checkNamedOutput", "(", "conf", ",", "namedOutput", ",", "false", ")", ";", "return", "conf", ".", "getBoolean", "(", "MO_PREFIX", "+", "named...
Returns if a named output is multiple. @param conf job conf @param namedOutput named output @return <code>true</code> if the name output is multi, <code>false</code> if it is single. If the name output is not defined it returns <code>false</code>
[ "Returns", "if", "a", "named", "output", "is", "multiple", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/lib/MultipleOutputs.java#L223-L226
dmerkushov/os-helper
src/main/java/ru/dmerkushov/oshelper/OSHelper.java
OSHelper.sendEmail_Unix
public static ProcessReturn sendEmail_Unix (String target, String topic, String text) throws OSHelperException { topic = topic.replaceAll ("\"", "\\\""); String emailCommandAsString = "mail -s \"" + topic + "\" -S sendcharsets=utf-8 " + target; List<String> emailCommandAsList = OSHelper.constructCommandAsList_Unix_sh (emailCommandAsString); Process process = OSHelper.runCommand (emailCommandAsList); OutputStream processStdin = process.getOutputStream (); try { processStdin.write (text.getBytes ()); } catch (IOException ex) { throw new OSHelperException (ex); } try { processStdin.close (); } catch (IOException ex) { throw new OSHelperException (ex); } ProcessReturn processReturn = OSHelper.procWaitWithProcessReturn (process, 10000); return processReturn; }
java
public static ProcessReturn sendEmail_Unix (String target, String topic, String text) throws OSHelperException { topic = topic.replaceAll ("\"", "\\\""); String emailCommandAsString = "mail -s \"" + topic + "\" -S sendcharsets=utf-8 " + target; List<String> emailCommandAsList = OSHelper.constructCommandAsList_Unix_sh (emailCommandAsString); Process process = OSHelper.runCommand (emailCommandAsList); OutputStream processStdin = process.getOutputStream (); try { processStdin.write (text.getBytes ()); } catch (IOException ex) { throw new OSHelperException (ex); } try { processStdin.close (); } catch (IOException ex) { throw new OSHelperException (ex); } ProcessReturn processReturn = OSHelper.procWaitWithProcessReturn (process, 10000); return processReturn; }
[ "public", "static", "ProcessReturn", "sendEmail_Unix", "(", "String", "target", ",", "String", "topic", ",", "String", "text", ")", "throws", "OSHelperException", "{", "topic", "=", "topic", ".", "replaceAll", "(", "\"\\\"\"", ",", "\"\\\\\\\"\"", ")", ";", "S...
Send a simple email @param target @param topic @param text @return The ProcessReturn structure of the mailing process. Normal are empty <code>stdout</code> and <code>stderr</code>, 0 * for <code>exitCode</code> and <code>osh_PROCESS_EXITED_BY_ITSELF</code> for <code>exitStatus</code> @see ProcessReturn
[ "Send", "a", "simple", "email" ]
train
https://github.com/dmerkushov/os-helper/blob/a7c2b72d289d9bc23ae106d1c5e11769cf3463d6/src/main/java/ru/dmerkushov/oshelper/OSHelper.java#L362-L380
ZieIony/Carbon
carbon/src/main/java/carbon/shadow/ShadowRenderer.java
ShadowRenderer.drawEdgeShadow
public void drawEdgeShadow(Canvas canvas, Matrix transform, RectF bounds, int elevation) { bounds.bottom += elevation; bounds.offset(0, -elevation); edgeColors[0] = shadowEndColor; edgeColors[1] = shadowMiddleColor; edgeColors[2] = shadowStartColor; edgeShadowPaint.setShader( new LinearGradient( bounds.left, bounds.top, bounds.left, bounds.bottom, edgeColors, edgePositions, Shader.TileMode.CLAMP)); canvas.save(); canvas.concat(transform); canvas.drawRect(bounds, edgeShadowPaint); canvas.restore(); }
java
public void drawEdgeShadow(Canvas canvas, Matrix transform, RectF bounds, int elevation) { bounds.bottom += elevation; bounds.offset(0, -elevation); edgeColors[0] = shadowEndColor; edgeColors[1] = shadowMiddleColor; edgeColors[2] = shadowStartColor; edgeShadowPaint.setShader( new LinearGradient( bounds.left, bounds.top, bounds.left, bounds.bottom, edgeColors, edgePositions, Shader.TileMode.CLAMP)); canvas.save(); canvas.concat(transform); canvas.drawRect(bounds, edgeShadowPaint); canvas.restore(); }
[ "public", "void", "drawEdgeShadow", "(", "Canvas", "canvas", ",", "Matrix", "transform", ",", "RectF", "bounds", ",", "int", "elevation", ")", "{", "bounds", ".", "bottom", "+=", "elevation", ";", "bounds", ".", "offset", "(", "0", ",", "-", "elevation", ...
Draws an edge shadow on the canvas in the current bounds with the matrix transform applied.
[ "Draws", "an", "edge", "shadow", "on", "the", "canvas", "in", "the", "current", "bounds", "with", "the", "matrix", "transform", "applied", "." ]
train
https://github.com/ZieIony/Carbon/blob/78b0a432bd49edc7a6a13ce111cab274085d1693/carbon/src/main/java/carbon/shadow/ShadowRenderer.java#L100-L122