repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
m-m-m/util
gwt/src/main/resources/net/sf/mmm/util/gwt/supersource/net/sf/mmm/util/exception/api/NlsRuntimeException.java
NlsRuntimeException.printStackTrace
static void printStackTrace(NlsThrowable throwable, Locale locale, Appendable buffer) { """ @see NlsThrowable#printStackTrace(Locale, Appendable) @param throwable is the {@link NlsThrowable} to print. @param locale is the {@link Locale} to translate to. @param buffer is where to write the stack trace to. """ try { synchronized (buffer) { buffer.append(throwable.getClass().getName()); buffer.append(": "); throwable.getLocalizedMessage(locale, buffer); buffer.append('\n'); UUID uuid = throwable.getUuid(); if (uuid != null) { buffer.append(uuid.toString()); buffer.append('\n'); } StackTraceElement[] trace = throwable.getStackTrace(); for (int i = 0; i < trace.length; i++) { buffer.append("\tat "); buffer.append(trace[i].toString()); buffer.append('\n'); } for (Throwable suppressed : ((Throwable) throwable).getSuppressed()) { buffer.append("Suppressed: "); buffer.append('\n'); printStackTraceCause(suppressed, locale, buffer); } Throwable cause = throwable.getCause(); if (cause != null) { buffer.append("Caused by: "); buffer.append('\n'); printStackTraceCause(cause, locale, buffer); } } } catch (IOException e) { throw new IllegalStateException(e); } }
java
static void printStackTrace(NlsThrowable throwable, Locale locale, Appendable buffer) { try { synchronized (buffer) { buffer.append(throwable.getClass().getName()); buffer.append(": "); throwable.getLocalizedMessage(locale, buffer); buffer.append('\n'); UUID uuid = throwable.getUuid(); if (uuid != null) { buffer.append(uuid.toString()); buffer.append('\n'); } StackTraceElement[] trace = throwable.getStackTrace(); for (int i = 0; i < trace.length; i++) { buffer.append("\tat "); buffer.append(trace[i].toString()); buffer.append('\n'); } for (Throwable suppressed : ((Throwable) throwable).getSuppressed()) { buffer.append("Suppressed: "); buffer.append('\n'); printStackTraceCause(suppressed, locale, buffer); } Throwable cause = throwable.getCause(); if (cause != null) { buffer.append("Caused by: "); buffer.append('\n'); printStackTraceCause(cause, locale, buffer); } } } catch (IOException e) { throw new IllegalStateException(e); } }
[ "static", "void", "printStackTrace", "(", "NlsThrowable", "throwable", ",", "Locale", "locale", ",", "Appendable", "buffer", ")", "{", "try", "{", "synchronized", "(", "buffer", ")", "{", "buffer", ".", "append", "(", "throwable", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "buffer", ".", "append", "(", "\": \"", ")", ";", "throwable", ".", "getLocalizedMessage", "(", "locale", ",", "buffer", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "UUID", "uuid", "=", "throwable", ".", "getUuid", "(", ")", ";", "if", "(", "uuid", "!=", "null", ")", "{", "buffer", ".", "append", "(", "uuid", ".", "toString", "(", ")", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "}", "StackTraceElement", "[", "]", "trace", "=", "throwable", ".", "getStackTrace", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "trace", ".", "length", ";", "i", "++", ")", "{", "buffer", ".", "append", "(", "\"\\tat \"", ")", ";", "buffer", ".", "append", "(", "trace", "[", "i", "]", ".", "toString", "(", ")", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "}", "for", "(", "Throwable", "suppressed", ":", "(", "(", "Throwable", ")", "throwable", ")", ".", "getSuppressed", "(", ")", ")", "{", "buffer", ".", "append", "(", "\"Suppressed: \"", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "printStackTraceCause", "(", "suppressed", ",", "locale", ",", "buffer", ")", ";", "}", "Throwable", "cause", "=", "throwable", ".", "getCause", "(", ")", ";", "if", "(", "cause", "!=", "null", ")", "{", "buffer", ".", "append", "(", "\"Caused by: \"", ")", ";", "buffer", ".", "append", "(", "'", "'", ")", ";", "printStackTraceCause", "(", "cause", ",", "locale", ",", "buffer", ")", ";", "}", "}", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "IllegalStateException", "(", "e", ")", ";", "}", "}" ]
@see NlsThrowable#printStackTrace(Locale, Appendable) @param throwable is the {@link NlsThrowable} to print. @param locale is the {@link Locale} to translate to. @param buffer is where to write the stack trace to.
[ "@see", "NlsThrowable#printStackTrace", "(", "Locale", "Appendable", ")" ]
train
https://github.com/m-m-m/util/blob/f0e4e084448f8dfc83ca682a9e1618034a094ce6/gwt/src/main/resources/net/sf/mmm/util/gwt/supersource/net/sf/mmm/util/exception/api/NlsRuntimeException.java#L139-L174
alkacon/opencms-core
src/org/opencms/relations/CmsCategoryService.java
CmsCategoryService.localizeCategory
public CmsCategory localizeCategory(CmsObject cms, CmsCategory category, Locale locale) { """ Localizes a single category by reading its locale-specific properties for title and description, if possible.<p> @param cms the CMS context to use for reading resources @param category the category to localize @param locale the locale to use @return the localized category """ try { CmsUUID id = category.getId(); CmsResource categoryRes = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION); String title = cms.readPropertyObject( categoryRes, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); String description = cms.readPropertyObject( categoryRes, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false, locale).getValue(); return new CmsCategory(category, title, description); } catch (Exception e) { LOG.error("Could not read localized category: " + e.getLocalizedMessage(), e); return category; } }
java
public CmsCategory localizeCategory(CmsObject cms, CmsCategory category, Locale locale) { try { CmsUUID id = category.getId(); CmsResource categoryRes = cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION); String title = cms.readPropertyObject( categoryRes, CmsPropertyDefinition.PROPERTY_TITLE, false, locale).getValue(); String description = cms.readPropertyObject( categoryRes, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false, locale).getValue(); return new CmsCategory(category, title, description); } catch (Exception e) { LOG.error("Could not read localized category: " + e.getLocalizedMessage(), e); return category; } }
[ "public", "CmsCategory", "localizeCategory", "(", "CmsObject", "cms", ",", "CmsCategory", "category", ",", "Locale", "locale", ")", "{", "try", "{", "CmsUUID", "id", "=", "category", ".", "getId", "(", ")", ";", "CmsResource", "categoryRes", "=", "cms", ".", "readResource", "(", "id", ",", "CmsResourceFilter", ".", "IGNORE_EXPIRATION", ")", ";", "String", "title", "=", "cms", ".", "readPropertyObject", "(", "categoryRes", ",", "CmsPropertyDefinition", ".", "PROPERTY_TITLE", ",", "false", ",", "locale", ")", ".", "getValue", "(", ")", ";", "String", "description", "=", "cms", ".", "readPropertyObject", "(", "categoryRes", ",", "CmsPropertyDefinition", ".", "PROPERTY_DESCRIPTION", ",", "false", ",", "locale", ")", ".", "getValue", "(", ")", ";", "return", "new", "CmsCategory", "(", "category", ",", "title", ",", "description", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "LOG", ".", "error", "(", "\"Could not read localized category: \"", "+", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "return", "category", ";", "}", "}" ]
Localizes a single category by reading its locale-specific properties for title and description, if possible.<p> @param cms the CMS context to use for reading resources @param category the category to localize @param locale the locale to use @return the localized category
[ "Localizes", "a", "single", "category", "by", "reading", "its", "locale", "-", "specific", "properties", "for", "title", "and", "description", "if", "possible", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L399-L419
google/closure-compiler
src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java
TypeTransformationParser.validRecordTypeExpression
private boolean validRecordTypeExpression(Node expr) { """ A record type expression must be of the form: record(RecordExp, RecordExp, ...) """ // The expression must have at least two children. The record keyword and // a record expression if (!checkParameterCount(expr, Keywords.RECORD)) { return false; } // Each child must be a valid record for (int i = 0; i < getCallParamCount(expr); i++) { if (!validRecordParam(getCallArgument(expr, i))) { warnInvalidInside(Keywords.RECORD.name, expr); return false; } } return true; }
java
private boolean validRecordTypeExpression(Node expr) { // The expression must have at least two children. The record keyword and // a record expression if (!checkParameterCount(expr, Keywords.RECORD)) { return false; } // Each child must be a valid record for (int i = 0; i < getCallParamCount(expr); i++) { if (!validRecordParam(getCallArgument(expr, i))) { warnInvalidInside(Keywords.RECORD.name, expr); return false; } } return true; }
[ "private", "boolean", "validRecordTypeExpression", "(", "Node", "expr", ")", "{", "// The expression must have at least two children. The record keyword and", "// a record expression", "if", "(", "!", "checkParameterCount", "(", "expr", ",", "Keywords", ".", "RECORD", ")", ")", "{", "return", "false", ";", "}", "// Each child must be a valid record", "for", "(", "int", "i", "=", "0", ";", "i", "<", "getCallParamCount", "(", "expr", ")", ";", "i", "++", ")", "{", "if", "(", "!", "validRecordParam", "(", "getCallArgument", "(", "expr", ",", "i", ")", ")", ")", "{", "warnInvalidInside", "(", "Keywords", ".", "RECORD", ".", "name", ",", "expr", ")", ";", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
A record type expression must be of the form: record(RecordExp, RecordExp, ...)
[ "A", "record", "type", "expression", "must", "be", "of", "the", "form", ":", "record", "(", "RecordExp", "RecordExp", "...", ")" ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/parsing/TypeTransformationParser.java#L434-L448
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nslimitselector.java
nslimitselector.get
public static nslimitselector get(nitro_service service, String selectorname) throws Exception { """ Use this API to fetch nslimitselector resource of given name . """ nslimitselector obj = new nslimitselector(); obj.set_selectorname(selectorname); nslimitselector response = (nslimitselector) obj.get_resource(service); return response; }
java
public static nslimitselector get(nitro_service service, String selectorname) throws Exception{ nslimitselector obj = new nslimitselector(); obj.set_selectorname(selectorname); nslimitselector response = (nslimitselector) obj.get_resource(service); return response; }
[ "public", "static", "nslimitselector", "get", "(", "nitro_service", "service", ",", "String", "selectorname", ")", "throws", "Exception", "{", "nslimitselector", "obj", "=", "new", "nslimitselector", "(", ")", ";", "obj", ".", "set_selectorname", "(", "selectorname", ")", ";", "nslimitselector", "response", "=", "(", "nslimitselector", ")", "obj", ".", "get_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch nslimitselector resource of given name .
[ "Use", "this", "API", "to", "fetch", "nslimitselector", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ns/nslimitselector.java#L276-L281
zaproxy/zaproxy
src/org/zaproxy/zap/utils/TimeStampUtils.java
TimeStampUtils.getTimeStampedMessage
public static String getTimeStampedMessage(String message, String format) { """ Returns the provided {@code message} along with a date/time based on the provided {@code format} which is a SimpleDateFormat string. If application of the provided {@code format} fails a default format is used. The DEFAULT format is defined in Messages.properties. @param message the message to be time stamped @param format the format to be used in creating the time stamp @return a time stamp in the designated format along with the original message @see SimpleDateFormat """ StringBuilder timeStampedMessage = new StringBuilder(format.length()+TIME_STAMP_DELIMITER.length()+message.length()+2); timeStampedMessage.append(currentFormattedTimeStamp(format)); //Timestamp timeStampedMessage.append(' ').append(TIME_STAMP_DELIMITER).append(' '); //Padded Delimiter timeStampedMessage.append(message); //Original message return timeStampedMessage.toString(); }
java
public static String getTimeStampedMessage(String message, String format){ StringBuilder timeStampedMessage = new StringBuilder(format.length()+TIME_STAMP_DELIMITER.length()+message.length()+2); timeStampedMessage.append(currentFormattedTimeStamp(format)); //Timestamp timeStampedMessage.append(' ').append(TIME_STAMP_DELIMITER).append(' '); //Padded Delimiter timeStampedMessage.append(message); //Original message return timeStampedMessage.toString(); }
[ "public", "static", "String", "getTimeStampedMessage", "(", "String", "message", ",", "String", "format", ")", "{", "StringBuilder", "timeStampedMessage", "=", "new", "StringBuilder", "(", "format", ".", "length", "(", ")", "+", "TIME_STAMP_DELIMITER", ".", "length", "(", ")", "+", "message", ".", "length", "(", ")", "+", "2", ")", ";", "timeStampedMessage", ".", "append", "(", "currentFormattedTimeStamp", "(", "format", ")", ")", ";", "//Timestamp\r", "timeStampedMessage", ".", "append", "(", "'", "'", ")", ".", "append", "(", "TIME_STAMP_DELIMITER", ")", ".", "append", "(", "'", "'", ")", ";", "//Padded Delimiter\r", "timeStampedMessage", ".", "append", "(", "message", ")", ";", "//Original message\r", "return", "timeStampedMessage", ".", "toString", "(", ")", ";", "}" ]
Returns the provided {@code message} along with a date/time based on the provided {@code format} which is a SimpleDateFormat string. If application of the provided {@code format} fails a default format is used. The DEFAULT format is defined in Messages.properties. @param message the message to be time stamped @param format the format to be used in creating the time stamp @return a time stamp in the designated format along with the original message @see SimpleDateFormat
[ "Returns", "the", "provided", "{", "@code", "message", "}", "along", "with", "a", "date", "/", "time", "based", "on", "the", "provided", "{", "@code", "format", "}", "which", "is", "a", "SimpleDateFormat", "string", ".", "If", "application", "of", "the", "provided", "{", "@code", "format", "}", "fails", "a", "default", "format", "is", "used", ".", "The", "DEFAULT", "format", "is", "defined", "in", "Messages", ".", "properties", ".", "@param", "message", "the", "message", "to", "be", "time", "stamped", "@param", "format", "the", "format", "to", "be", "used", "in", "creating", "the", "time", "stamp", "@return", "a", "time", "stamp", "in", "the", "designated", "format", "along", "with", "the", "original", "message" ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/utils/TimeStampUtils.java#L91-L99
bazaarvoice/emodb
common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java
AdaptiveResultSet.executeAdaptiveQuery
public static ResultSet executeAdaptiveQuery(Session session, Statement statement, int fetchSize) { """ Executes a query sychronously, dynamically adjusting the fetch size down if necessary. """ int remainingAdaptations = MAX_ADAPTATIONS; while (true) { try { statement.setFetchSize(fetchSize); ResultSet resultSet = session.execute(statement); return new AdaptiveResultSet(session, resultSet, remainingAdaptations); } catch (Throwable t) { if (isAdaptiveException(t) && --remainingAdaptations != 0 && fetchSize > MIN_FETCH_SIZE) { // Try again with half the fetch size fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Repeating previous query with fetch size {} due to {}", fetchSize, t.getMessage()); } else { throw Throwables.propagate(t); } } } }
java
public static ResultSet executeAdaptiveQuery(Session session, Statement statement, int fetchSize) { int remainingAdaptations = MAX_ADAPTATIONS; while (true) { try { statement.setFetchSize(fetchSize); ResultSet resultSet = session.execute(statement); return new AdaptiveResultSet(session, resultSet, remainingAdaptations); } catch (Throwable t) { if (isAdaptiveException(t) && --remainingAdaptations != 0 && fetchSize > MIN_FETCH_SIZE) { // Try again with half the fetch size fetchSize = Math.max(fetchSize / 2, MIN_FETCH_SIZE); _log.debug("Repeating previous query with fetch size {} due to {}", fetchSize, t.getMessage()); } else { throw Throwables.propagate(t); } } } }
[ "public", "static", "ResultSet", "executeAdaptiveQuery", "(", "Session", "session", ",", "Statement", "statement", ",", "int", "fetchSize", ")", "{", "int", "remainingAdaptations", "=", "MAX_ADAPTATIONS", ";", "while", "(", "true", ")", "{", "try", "{", "statement", ".", "setFetchSize", "(", "fetchSize", ")", ";", "ResultSet", "resultSet", "=", "session", ".", "execute", "(", "statement", ")", ";", "return", "new", "AdaptiveResultSet", "(", "session", ",", "resultSet", ",", "remainingAdaptations", ")", ";", "}", "catch", "(", "Throwable", "t", ")", "{", "if", "(", "isAdaptiveException", "(", "t", ")", "&&", "--", "remainingAdaptations", "!=", "0", "&&", "fetchSize", ">", "MIN_FETCH_SIZE", ")", "{", "// Try again with half the fetch size", "fetchSize", "=", "Math", ".", "max", "(", "fetchSize", "/", "2", ",", "MIN_FETCH_SIZE", ")", ";", "_log", ".", "debug", "(", "\"Repeating previous query with fetch size {} due to {}\"", ",", "fetchSize", ",", "t", ".", "getMessage", "(", ")", ")", ";", "}", "else", "{", "throw", "Throwables", ".", "propagate", "(", "t", ")", ";", "}", "}", "}", "}" ]
Executes a query sychronously, dynamically adjusting the fetch size down if necessary.
[ "Executes", "a", "query", "sychronously", "dynamically", "adjusting", "the", "fetch", "size", "down", "if", "necessary", "." ]
train
https://github.com/bazaarvoice/emodb/blob/97ec7671bc78b47fc2a1c11298c0c872bd5ec7fb/common/astyanax/src/main/java/com/bazaarvoice/emodb/common/cassandra/cqldriver/AdaptiveResultSet.java#L84-L101
real-logic/agrona
agrona/src/main/java/org/agrona/concurrent/AgentRunner.java
AgentRunner.startOnThread
public static Thread startOnThread(final AgentRunner runner, final ThreadFactory threadFactory) { """ Start the given agent runner on a new thread. @param runner the agent runner to start. @param threadFactory the factory to use to create the thread. @return the new thread that has been started. """ final Thread thread = threadFactory.newThread(runner); thread.setName(runner.agent().roleName()); thread.start(); return thread; }
java
public static Thread startOnThread(final AgentRunner runner, final ThreadFactory threadFactory) { final Thread thread = threadFactory.newThread(runner); thread.setName(runner.agent().roleName()); thread.start(); return thread; }
[ "public", "static", "Thread", "startOnThread", "(", "final", "AgentRunner", "runner", ",", "final", "ThreadFactory", "threadFactory", ")", "{", "final", "Thread", "thread", "=", "threadFactory", ".", "newThread", "(", "runner", ")", ";", "thread", ".", "setName", "(", "runner", ".", "agent", "(", ")", ".", "roleName", "(", ")", ")", ";", "thread", ".", "start", "(", ")", ";", "return", "thread", ";", "}" ]
Start the given agent runner on a new thread. @param runner the agent runner to start. @param threadFactory the factory to use to create the thread. @return the new thread that has been started.
[ "Start", "the", "given", "agent", "runner", "on", "a", "new", "thread", "." ]
train
https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/concurrent/AgentRunner.java#L95-L102
lessthanoptimal/BoofCV
integration/boofcv-swing/src/main/java/boofcv/gui/fiducial/VisualizeFiducial.java
VisualizeFiducial.drawChessboard
public static void drawChessboard( Graphics2D g2 , WorldToCameraToPixel fiducialToPixel , int numRows , int numCols , double squareWidth ) { """ Renders a translucent chessboard pattern @param g2 Graphics object it's drawn in @param fiducialToPixel Coverts a coordinate from fiducial into pixel @param numRows Number of rows in the calibration grid @param numCols Number of columns in the calibration grid @param squareWidth Width of each square """ Point3D_F64 fidPt = new Point3D_F64(); Point2D_F64 pixel0 = new Point2D_F64(); Point2D_F64 pixel1 = new Point2D_F64(); Point2D_F64 pixel2 = new Point2D_F64(); Point2D_F64 pixel3 = new Point2D_F64(); Line2D.Double l = new Line2D.Double(); int polyX[] = new int[4]; int polyY[] = new int[4]; int alpha = 100; Color red = new Color(255,0,0,alpha); Color black = new Color(0,0,0,alpha); for( int row = 0; row < numRows; row++ ) { double y0 = -numRows*squareWidth/2 + row*squareWidth; for (int col = row%2; col < numCols; col += 2) { double x0 = -numCols*squareWidth/2 + col*squareWidth; fidPt.set(x0,y0, 0); fiducialToPixel.transform(fidPt, pixel0); fidPt.set(x0 + squareWidth, y0, 0); fiducialToPixel.transform(fidPt, pixel1); fidPt.set(x0 + squareWidth, y0 + squareWidth, 0); fiducialToPixel.transform(fidPt, pixel2); fidPt.set(x0, y0 + squareWidth, 0); fiducialToPixel.transform(fidPt, pixel3); polyX[0] = (int)(pixel0.x+0.5); polyX[1] = (int)(pixel1.x+0.5); polyX[2] = (int)(pixel2.x+0.5); polyX[3] = (int)(pixel3.x+0.5); polyY[0] = (int)(pixel0.y+0.5); polyY[1] = (int)(pixel1.y+0.5); polyY[2] = (int)(pixel2.y+0.5); polyY[3] = (int)(pixel3.y+0.5); g2.setColor(black); g2.fillPolygon(polyX,polyY,4); g2.setColor(red); drawLine(g2, l, pixel0.x, pixel0.y, pixel1.x, pixel1.y); drawLine(g2, l, pixel1.x, pixel1.y, pixel2.x, pixel2.y); drawLine(g2, l, pixel2.x, pixel2.y, pixel3.x, pixel3.y); drawLine(g2, l, pixel3.x, pixel3.y, pixel0.x, pixel0.y); } } }
java
public static void drawChessboard( Graphics2D g2 , WorldToCameraToPixel fiducialToPixel , int numRows , int numCols , double squareWidth ) { Point3D_F64 fidPt = new Point3D_F64(); Point2D_F64 pixel0 = new Point2D_F64(); Point2D_F64 pixel1 = new Point2D_F64(); Point2D_F64 pixel2 = new Point2D_F64(); Point2D_F64 pixel3 = new Point2D_F64(); Line2D.Double l = new Line2D.Double(); int polyX[] = new int[4]; int polyY[] = new int[4]; int alpha = 100; Color red = new Color(255,0,0,alpha); Color black = new Color(0,0,0,alpha); for( int row = 0; row < numRows; row++ ) { double y0 = -numRows*squareWidth/2 + row*squareWidth; for (int col = row%2; col < numCols; col += 2) { double x0 = -numCols*squareWidth/2 + col*squareWidth; fidPt.set(x0,y0, 0); fiducialToPixel.transform(fidPt, pixel0); fidPt.set(x0 + squareWidth, y0, 0); fiducialToPixel.transform(fidPt, pixel1); fidPt.set(x0 + squareWidth, y0 + squareWidth, 0); fiducialToPixel.transform(fidPt, pixel2); fidPt.set(x0, y0 + squareWidth, 0); fiducialToPixel.transform(fidPt, pixel3); polyX[0] = (int)(pixel0.x+0.5); polyX[1] = (int)(pixel1.x+0.5); polyX[2] = (int)(pixel2.x+0.5); polyX[3] = (int)(pixel3.x+0.5); polyY[0] = (int)(pixel0.y+0.5); polyY[1] = (int)(pixel1.y+0.5); polyY[2] = (int)(pixel2.y+0.5); polyY[3] = (int)(pixel3.y+0.5); g2.setColor(black); g2.fillPolygon(polyX,polyY,4); g2.setColor(red); drawLine(g2, l, pixel0.x, pixel0.y, pixel1.x, pixel1.y); drawLine(g2, l, pixel1.x, pixel1.y, pixel2.x, pixel2.y); drawLine(g2, l, pixel2.x, pixel2.y, pixel3.x, pixel3.y); drawLine(g2, l, pixel3.x, pixel3.y, pixel0.x, pixel0.y); } } }
[ "public", "static", "void", "drawChessboard", "(", "Graphics2D", "g2", ",", "WorldToCameraToPixel", "fiducialToPixel", ",", "int", "numRows", ",", "int", "numCols", ",", "double", "squareWidth", ")", "{", "Point3D_F64", "fidPt", "=", "new", "Point3D_F64", "(", ")", ";", "Point2D_F64", "pixel0", "=", "new", "Point2D_F64", "(", ")", ";", "Point2D_F64", "pixel1", "=", "new", "Point2D_F64", "(", ")", ";", "Point2D_F64", "pixel2", "=", "new", "Point2D_F64", "(", ")", ";", "Point2D_F64", "pixel3", "=", "new", "Point2D_F64", "(", ")", ";", "Line2D", ".", "Double", "l", "=", "new", "Line2D", ".", "Double", "(", ")", ";", "int", "polyX", "[", "]", "=", "new", "int", "[", "4", "]", ";", "int", "polyY", "[", "]", "=", "new", "int", "[", "4", "]", ";", "int", "alpha", "=", "100", ";", "Color", "red", "=", "new", "Color", "(", "255", ",", "0", ",", "0", ",", "alpha", ")", ";", "Color", "black", "=", "new", "Color", "(", "0", ",", "0", ",", "0", ",", "alpha", ")", ";", "for", "(", "int", "row", "=", "0", ";", "row", "<", "numRows", ";", "row", "++", ")", "{", "double", "y0", "=", "-", "numRows", "*", "squareWidth", "/", "2", "+", "row", "*", "squareWidth", ";", "for", "(", "int", "col", "=", "row", "%", "2", ";", "col", "<", "numCols", ";", "col", "+=", "2", ")", "{", "double", "x0", "=", "-", "numCols", "*", "squareWidth", "/", "2", "+", "col", "*", "squareWidth", ";", "fidPt", ".", "set", "(", "x0", ",", "y0", ",", "0", ")", ";", "fiducialToPixel", ".", "transform", "(", "fidPt", ",", "pixel0", ")", ";", "fidPt", ".", "set", "(", "x0", "+", "squareWidth", ",", "y0", ",", "0", ")", ";", "fiducialToPixel", ".", "transform", "(", "fidPt", ",", "pixel1", ")", ";", "fidPt", ".", "set", "(", "x0", "+", "squareWidth", ",", "y0", "+", "squareWidth", ",", "0", ")", ";", "fiducialToPixel", ".", "transform", "(", "fidPt", ",", "pixel2", ")", ";", "fidPt", ".", "set", "(", "x0", ",", "y0", "+", "squareWidth", ",", "0", ")", ";", "fiducialToPixel", ".", "transform", "(", "fidPt", ",", "pixel3", ")", ";", "polyX", "[", "0", "]", "=", "(", "int", ")", "(", "pixel0", ".", "x", "+", "0.5", ")", ";", "polyX", "[", "1", "]", "=", "(", "int", ")", "(", "pixel1", ".", "x", "+", "0.5", ")", ";", "polyX", "[", "2", "]", "=", "(", "int", ")", "(", "pixel2", ".", "x", "+", "0.5", ")", ";", "polyX", "[", "3", "]", "=", "(", "int", ")", "(", "pixel3", ".", "x", "+", "0.5", ")", ";", "polyY", "[", "0", "]", "=", "(", "int", ")", "(", "pixel0", ".", "y", "+", "0.5", ")", ";", "polyY", "[", "1", "]", "=", "(", "int", ")", "(", "pixel1", ".", "y", "+", "0.5", ")", ";", "polyY", "[", "2", "]", "=", "(", "int", ")", "(", "pixel2", ".", "y", "+", "0.5", ")", ";", "polyY", "[", "3", "]", "=", "(", "int", ")", "(", "pixel3", ".", "y", "+", "0.5", ")", ";", "g2", ".", "setColor", "(", "black", ")", ";", "g2", ".", "fillPolygon", "(", "polyX", ",", "polyY", ",", "4", ")", ";", "g2", ".", "setColor", "(", "red", ")", ";", "drawLine", "(", "g2", ",", "l", ",", "pixel0", ".", "x", ",", "pixel0", ".", "y", ",", "pixel1", ".", "x", ",", "pixel1", ".", "y", ")", ";", "drawLine", "(", "g2", ",", "l", ",", "pixel1", ".", "x", ",", "pixel1", ".", "y", ",", "pixel2", ".", "x", ",", "pixel2", ".", "y", ")", ";", "drawLine", "(", "g2", ",", "l", ",", "pixel2", ".", "x", ",", "pixel2", ".", "y", ",", "pixel3", ".", "x", ",", "pixel3", ".", "y", ")", ";", "drawLine", "(", "g2", ",", "l", ",", "pixel3", ".", "x", ",", "pixel3", ".", "y", ",", "pixel0", ".", "x", ",", "pixel0", ".", "y", ")", ";", "}", "}", "}" ]
Renders a translucent chessboard pattern @param g2 Graphics object it's drawn in @param fiducialToPixel Coverts a coordinate from fiducial into pixel @param numRows Number of rows in the calibration grid @param numCols Number of columns in the calibration grid @param squareWidth Width of each square
[ "Renders", "a", "translucent", "chessboard", "pattern" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-swing/src/main/java/boofcv/gui/fiducial/VisualizeFiducial.java#L160-L211
Azure/azure-sdk-for-java
appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java
AppServiceCertificateOrdersInner.reissueAsync
public Observable<Void> reissueAsync(String resourceGroupName, String certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest) { """ Reissue an existing certificate order. Reissue an existing certificate order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @param reissueCertificateOrderRequest Parameters for the reissue. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return reissueWithServiceResponseAsync(resourceGroupName, certificateOrderName, reissueCertificateOrderRequest).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> reissueAsync(String resourceGroupName, String certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest) { return reissueWithServiceResponseAsync(resourceGroupName, certificateOrderName, reissueCertificateOrderRequest).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "reissueAsync", "(", "String", "resourceGroupName", ",", "String", "certificateOrderName", ",", "ReissueCertificateOrderRequest", "reissueCertificateOrderRequest", ")", "{", "return", "reissueWithServiceResponseAsync", "(", "resourceGroupName", ",", "certificateOrderName", ",", "reissueCertificateOrderRequest", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Reissue an existing certificate order. Reissue an existing certificate order. @param resourceGroupName Name of the resource group to which the resource belongs. @param certificateOrderName Name of the certificate order. @param reissueCertificateOrderRequest Parameters for the reissue. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "Reissue", "an", "existing", "certificate", "order", ".", "Reissue", "an", "existing", "certificate", "order", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L1613-L1620
wcm-io/wcm-io-handler
url/src/main/java/io/wcm/handler/url/suffix/SuffixParser.java
SuffixParser.get
@SuppressWarnings("unchecked") public <T> @Nullable T get(@NotNull String key, @Nullable T defaultValue) { """ Extract the value of a named suffix part from this request's suffix @param key key of the suffix part @param defaultValue the default value to return if suffix part not set. Only String, Boolean, Integer, Long are supported. @param <T> Parameter type. @return the value of that named parameter (or the default value if not used) """ if (defaultValue instanceof String || defaultValue == null) { return (T)getString(key, (String)defaultValue); } if (defaultValue instanceof Boolean) { return (T)(Boolean)getBoolean(key, (Boolean)defaultValue); } if (defaultValue instanceof Integer) { return (T)(Integer)getInt(key, (Integer)defaultValue); } if (defaultValue instanceof Long) { return (T)(Long)getLong(key, (Long)defaultValue); } throw new IllegalArgumentException("Unsupported type: " + defaultValue.getClass().getName()); }
java
@SuppressWarnings("unchecked") public <T> @Nullable T get(@NotNull String key, @Nullable T defaultValue) { if (defaultValue instanceof String || defaultValue == null) { return (T)getString(key, (String)defaultValue); } if (defaultValue instanceof Boolean) { return (T)(Boolean)getBoolean(key, (Boolean)defaultValue); } if (defaultValue instanceof Integer) { return (T)(Integer)getInt(key, (Integer)defaultValue); } if (defaultValue instanceof Long) { return (T)(Long)getLong(key, (Long)defaultValue); } throw new IllegalArgumentException("Unsupported type: " + defaultValue.getClass().getName()); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "@", "Nullable", "T", "get", "(", "@", "NotNull", "String", "key", ",", "@", "Nullable", "T", "defaultValue", ")", "{", "if", "(", "defaultValue", "instanceof", "String", "||", "defaultValue", "==", "null", ")", "{", "return", "(", "T", ")", "getString", "(", "key", ",", "(", "String", ")", "defaultValue", ")", ";", "}", "if", "(", "defaultValue", "instanceof", "Boolean", ")", "{", "return", "(", "T", ")", "(", "Boolean", ")", "getBoolean", "(", "key", ",", "(", "Boolean", ")", "defaultValue", ")", ";", "}", "if", "(", "defaultValue", "instanceof", "Integer", ")", "{", "return", "(", "T", ")", "(", "Integer", ")", "getInt", "(", "key", ",", "(", "Integer", ")", "defaultValue", ")", ";", "}", "if", "(", "defaultValue", "instanceof", "Long", ")", "{", "return", "(", "T", ")", "(", "Long", ")", "getLong", "(", "key", ",", "(", "Long", ")", "defaultValue", ")", ";", "}", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported type: \"", "+", "defaultValue", ".", "getClass", "(", ")", ".", "getName", "(", ")", ")", ";", "}" ]
Extract the value of a named suffix part from this request's suffix @param key key of the suffix part @param defaultValue the default value to return if suffix part not set. Only String, Boolean, Integer, Long are supported. @param <T> Parameter type. @return the value of that named parameter (or the default value if not used)
[ "Extract", "the", "value", "of", "a", "named", "suffix", "part", "from", "this", "request", "s", "suffix" ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/suffix/SuffixParser.java#L107-L122
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/FormSupport.java
FormSupport.setPlaceholderText
public <B extends TextBoxBase> B setPlaceholderText (B box, String placeholder) { """ Set the placeholder text to use on the specified form field. This text will be shown when the field is blank and unfocused. """ box.getElement().setAttribute("placeholder", placeholder); return box; }
java
public <B extends TextBoxBase> B setPlaceholderText (B box, String placeholder) { box.getElement().setAttribute("placeholder", placeholder); return box; }
[ "public", "<", "B", "extends", "TextBoxBase", ">", "B", "setPlaceholderText", "(", "B", "box", ",", "String", "placeholder", ")", "{", "box", ".", "getElement", "(", ")", ".", "setAttribute", "(", "\"placeholder\"", ",", "placeholder", ")", ";", "return", "box", ";", "}" ]
Set the placeholder text to use on the specified form field. This text will be shown when the field is blank and unfocused.
[ "Set", "the", "placeholder", "text", "to", "use", "on", "the", "specified", "form", "field", ".", "This", "text", "will", "be", "shown", "when", "the", "field", "is", "blank", "and", "unfocused", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/FormSupport.java#L35-L39
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java
ExpressRoutePortsInner.beginCreateOrUpdate
public ExpressRoutePortInner beginCreateOrUpdate(String resourceGroupName, String expressRoutePortName, ExpressRoutePortInner parameters) { """ Creates or updates the specified ExpressRoutePort resource. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @param parameters Parameters supplied to the create ExpressRoutePort operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ExpressRoutePortInner object if successful. """ return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, expressRoutePortName, parameters).toBlocking().single().body(); }
java
public ExpressRoutePortInner beginCreateOrUpdate(String resourceGroupName, String expressRoutePortName, ExpressRoutePortInner parameters) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, expressRoutePortName, parameters).toBlocking().single().body(); }
[ "public", "ExpressRoutePortInner", "beginCreateOrUpdate", "(", "String", "resourceGroupName", ",", "String", "expressRoutePortName", ",", "ExpressRoutePortInner", "parameters", ")", "{", "return", "beginCreateOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "expressRoutePortName", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates or updates the specified ExpressRoutePort resource. @param resourceGroupName The name of the resource group. @param expressRoutePortName The name of the ExpressRoutePort resource. @param parameters Parameters supplied to the create ExpressRoutePort operation. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the ExpressRoutePortInner object if successful.
[ "Creates", "or", "updates", "the", "specified", "ExpressRoutePort", "resource", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/ExpressRoutePortsInner.java#L437-L439
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/cache/disc/impl/ext/DiskLruCache.java
DiskLruCache.rebuildJournal
private synchronized void rebuildJournal() throws IOException { """ Creates a new journal that omits redundant information. This replaces the current journal if it exists. """ if (journalWriter != null) { journalWriter.close(); } Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII)); try { writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(appVersion)); writer.write("\n"); writer.write(Integer.toString(valueCount)); writer.write("\n"); writer.write("\n"); for (Entry entry : lruEntries.values()) { if (entry.currentEditor != null) { writer.write(DIRTY + ' ' + entry.key + '\n'); } else { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } } finally { writer.close(); } if (journalFile.exists()) { renameTo(journalFile, journalFileBackup, true); } renameTo(journalFileTmp, journalFile, false); journalFileBackup.delete(); journalWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII)); }
java
private synchronized void rebuildJournal() throws IOException { if (journalWriter != null) { journalWriter.close(); } Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(journalFileTmp), Util.US_ASCII)); try { writer.write(MAGIC); writer.write("\n"); writer.write(VERSION_1); writer.write("\n"); writer.write(Integer.toString(appVersion)); writer.write("\n"); writer.write(Integer.toString(valueCount)); writer.write("\n"); writer.write("\n"); for (Entry entry : lruEntries.values()) { if (entry.currentEditor != null) { writer.write(DIRTY + ' ' + entry.key + '\n'); } else { writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n'); } } } finally { writer.close(); } if (journalFile.exists()) { renameTo(journalFile, journalFileBackup, true); } renameTo(journalFileTmp, journalFile, false); journalFileBackup.delete(); journalWriter = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(journalFile, true), Util.US_ASCII)); }
[ "private", "synchronized", "void", "rebuildJournal", "(", ")", "throws", "IOException", "{", "if", "(", "journalWriter", "!=", "null", ")", "{", "journalWriter", ".", "close", "(", ")", ";", "}", "Writer", "writer", "=", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "journalFileTmp", ")", ",", "Util", ".", "US_ASCII", ")", ")", ";", "try", "{", "writer", ".", "write", "(", "MAGIC", ")", ";", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "writer", ".", "write", "(", "VERSION_1", ")", ";", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "writer", ".", "write", "(", "Integer", ".", "toString", "(", "appVersion", ")", ")", ";", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "writer", ".", "write", "(", "Integer", ".", "toString", "(", "valueCount", ")", ")", ";", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "writer", ".", "write", "(", "\"\\n\"", ")", ";", "for", "(", "Entry", "entry", ":", "lruEntries", ".", "values", "(", ")", ")", "{", "if", "(", "entry", ".", "currentEditor", "!=", "null", ")", "{", "writer", ".", "write", "(", "DIRTY", "+", "'", "'", "+", "entry", ".", "key", "+", "'", "'", ")", ";", "}", "else", "{", "writer", ".", "write", "(", "CLEAN", "+", "'", "'", "+", "entry", ".", "key", "+", "entry", ".", "getLengths", "(", ")", "+", "'", "'", ")", ";", "}", "}", "}", "finally", "{", "writer", ".", "close", "(", ")", ";", "}", "if", "(", "journalFile", ".", "exists", "(", ")", ")", "{", "renameTo", "(", "journalFile", ",", "journalFileBackup", ",", "true", ")", ";", "}", "renameTo", "(", "journalFileTmp", ",", "journalFile", ",", "false", ")", ";", "journalFileBackup", ".", "delete", "(", ")", ";", "journalWriter", "=", "new", "BufferedWriter", "(", "new", "OutputStreamWriter", "(", "new", "FileOutputStream", "(", "journalFile", ",", "true", ")", ",", "Util", ".", "US_ASCII", ")", ")", ";", "}" ]
Creates a new journal that omits redundant information. This replaces the current journal if it exists.
[ "Creates", "a", "new", "journal", "that", "omits", "redundant", "information", ".", "This", "replaces", "the", "current", "journal", "if", "it", "exists", "." ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/cache/disc/impl/ext/DiskLruCache.java#L353-L390
RestComm/media-core
ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java
HostCandidateHarvester.openUdpChannel
private DatagramChannel openUdpChannel(InetAddress localAddress, int port, Selector selector) throws IOException { """ Opens a datagram channel and binds it to an address. @param localAddress The address to bind the channel to. @param port The port to use @return The bound datagram channel @throws IOException When an error occurs while binding the datagram channel. """ DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); // Register selector for reading operations channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); channel.bind(new InetSocketAddress(localAddress, port)); return channel; }
java
private DatagramChannel openUdpChannel(InetAddress localAddress, int port, Selector selector) throws IOException { DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); // Register selector for reading operations channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE); channel.bind(new InetSocketAddress(localAddress, port)); return channel; }
[ "private", "DatagramChannel", "openUdpChannel", "(", "InetAddress", "localAddress", ",", "int", "port", ",", "Selector", "selector", ")", "throws", "IOException", "{", "DatagramChannel", "channel", "=", "DatagramChannel", ".", "open", "(", ")", ";", "channel", ".", "configureBlocking", "(", "false", ")", ";", "// Register selector for reading operations", "channel", ".", "register", "(", "selector", ",", "SelectionKey", ".", "OP_READ", "|", "SelectionKey", ".", "OP_WRITE", ")", ";", "channel", ".", "bind", "(", "new", "InetSocketAddress", "(", "localAddress", ",", "port", ")", ")", ";", "return", "channel", ";", "}" ]
Opens a datagram channel and binds it to an address. @param localAddress The address to bind the channel to. @param port The port to use @return The bound datagram channel @throws IOException When an error occurs while binding the datagram channel.
[ "Opens", "a", "datagram", "channel", "and", "binds", "it", "to", "an", "address", "." ]
train
https://github.com/RestComm/media-core/blob/07b8703343708599f60af66bae62aded77ee81b5/ice/src/main/java/org/restcomm/media/core/ice/harvest/HostCandidateHarvester.java#L150-L157
kiegroup/drools
drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java
DefaultAgenda.addItemToActivationGroup
public void addItemToActivationGroup(final AgendaItem item) { """ If the item belongs to an activation group, add it @param item """ if ( item.isRuleAgendaItem() ) { throw new UnsupportedOperationException("defensive programming, making sure this isn't called, before removing"); } String group = item.getRule().getActivationGroup(); if ( group != null && group.length() > 0 ) { InternalActivationGroup actgroup = getActivationGroup( group ); // Don't allow lazy activations to activate, from before it's last trigger point if ( actgroup.getTriggeredForRecency() != 0 && actgroup.getTriggeredForRecency() >= item.getPropagationContext().getFactHandle().getRecency() ) { return; } actgroup.addActivation( item ); } }
java
public void addItemToActivationGroup(final AgendaItem item) { if ( item.isRuleAgendaItem() ) { throw new UnsupportedOperationException("defensive programming, making sure this isn't called, before removing"); } String group = item.getRule().getActivationGroup(); if ( group != null && group.length() > 0 ) { InternalActivationGroup actgroup = getActivationGroup( group ); // Don't allow lazy activations to activate, from before it's last trigger point if ( actgroup.getTriggeredForRecency() != 0 && actgroup.getTriggeredForRecency() >= item.getPropagationContext().getFactHandle().getRecency() ) { return; } actgroup.addActivation( item ); } }
[ "public", "void", "addItemToActivationGroup", "(", "final", "AgendaItem", "item", ")", "{", "if", "(", "item", ".", "isRuleAgendaItem", "(", ")", ")", "{", "throw", "new", "UnsupportedOperationException", "(", "\"defensive programming, making sure this isn't called, before removing\"", ")", ";", "}", "String", "group", "=", "item", ".", "getRule", "(", ")", ".", "getActivationGroup", "(", ")", ";", "if", "(", "group", "!=", "null", "&&", "group", ".", "length", "(", ")", ">", "0", ")", "{", "InternalActivationGroup", "actgroup", "=", "getActivationGroup", "(", "group", ")", ";", "// Don't allow lazy activations to activate, from before it's last trigger point", "if", "(", "actgroup", ".", "getTriggeredForRecency", "(", ")", "!=", "0", "&&", "actgroup", ".", "getTriggeredForRecency", "(", ")", ">=", "item", ".", "getPropagationContext", "(", ")", ".", "getFactHandle", "(", ")", ".", "getRecency", "(", ")", ")", "{", "return", ";", "}", "actgroup", ".", "addActivation", "(", "item", ")", ";", "}", "}" ]
If the item belongs to an activation group, add it @param item
[ "If", "the", "item", "belongs", "to", "an", "activation", "group", "add", "it" ]
train
https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-core/src/main/java/org/drools/core/common/DefaultAgenda.java#L319-L335
Teddy-Zhu/SilentGo
utils/src/main/java/com/silentgo/utils/asm/Label.java
Label.addToSubroutine
void addToSubroutine(final long id, final int nbSubroutines) { """ Marks this basic block as belonging to the given subroutine. @param id a subroutine id. @param nbSubroutines the total number of subroutines in the method. """ if ((status & VISITED) == 0) { status |= VISITED; srcAndRefPositions = new int[nbSubroutines / 32 + 1]; } srcAndRefPositions[(int) (id >>> 32)] |= (int) id; }
java
void addToSubroutine(final long id, final int nbSubroutines) { if ((status & VISITED) == 0) { status |= VISITED; srcAndRefPositions = new int[nbSubroutines / 32 + 1]; } srcAndRefPositions[(int) (id >>> 32)] |= (int) id; }
[ "void", "addToSubroutine", "(", "final", "long", "id", ",", "final", "int", "nbSubroutines", ")", "{", "if", "(", "(", "status", "&", "VISITED", ")", "==", "0", ")", "{", "status", "|=", "VISITED", ";", "srcAndRefPositions", "=", "new", "int", "[", "nbSubroutines", "/", "32", "+", "1", "]", ";", "}", "srcAndRefPositions", "[", "(", "int", ")", "(", "id", ">>>", "32", ")", "]", "|=", "(", "int", ")", "id", ";", "}" ]
Marks this basic block as belonging to the given subroutine. @param id a subroutine id. @param nbSubroutines the total number of subroutines in the method.
[ "Marks", "this", "basic", "block", "as", "belonging", "to", "the", "given", "subroutine", "." ]
train
https://github.com/Teddy-Zhu/SilentGo/blob/27f58b0cafe56b2eb9fc6993efa9ca2b529661e1/utils/src/main/java/com/silentgo/utils/asm/Label.java#L477-L483
synchronoss/cpo-api
cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java
CassandraCpoAdapter.retrieveBean
@Override public <T, C> T retrieveBean(String name, C criteria, T result, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { """ Retrieves the bean from the datasource. The assumption is that the bean exists in the datasource. If the retrieve function defined for this beans returns more than one row, an exception will be thrown. @param name The filter name which tells the datasource which beans should be returned. The name also signifies what data in the bean will be populated. @param criteria This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the arguments used to retrieve the collection of beans. @param result This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the bean type that will be returned in the collection. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return An bean of the same type as the result argument that is filled in as specified the metadata for the retireve. @throws CpoException Thrown if there are errors accessing the datasource """ Iterator<T> it = processSelectGroup(name, criteria, result, wheres, orderBy, nativeExpressions, true).iterator(); if (it.hasNext()) { return it.next(); } else { return null; } }
java
@Override public <T, C> T retrieveBean(String name, C criteria, T result, Collection<CpoWhere> wheres, Collection<CpoOrderBy> orderBy, Collection<CpoNativeFunction> nativeExpressions) throws CpoException { Iterator<T> it = processSelectGroup(name, criteria, result, wheres, orderBy, nativeExpressions, true).iterator(); if (it.hasNext()) { return it.next(); } else { return null; } }
[ "@", "Override", "public", "<", "T", ",", "C", ">", "T", "retrieveBean", "(", "String", "name", ",", "C", "criteria", ",", "T", "result", ",", "Collection", "<", "CpoWhere", ">", "wheres", ",", "Collection", "<", "CpoOrderBy", ">", "orderBy", ",", "Collection", "<", "CpoNativeFunction", ">", "nativeExpressions", ")", "throws", "CpoException", "{", "Iterator", "<", "T", ">", "it", "=", "processSelectGroup", "(", "name", ",", "criteria", ",", "result", ",", "wheres", ",", "orderBy", ",", "nativeExpressions", ",", "true", ")", ".", "iterator", "(", ")", ";", "if", "(", "it", ".", "hasNext", "(", ")", ")", "{", "return", "it", ".", "next", "(", ")", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Retrieves the bean from the datasource. The assumption is that the bean exists in the datasource. If the retrieve function defined for this beans returns more than one row, an exception will be thrown. @param name The filter name which tells the datasource which beans should be returned. The name also signifies what data in the bean will be populated. @param criteria This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the arguments used to retrieve the collection of beans. @param result This is an bean that has been defined within the metadata of the datasource. If the class is not defined an exception will be thrown. If the bean does not exist in the datasource, an exception will be thrown. This bean is used to specify the bean type that will be returned in the collection. @param wheres A collection of CpoWhere beans that define the constraints that should be used when retrieving beans @param orderBy The CpoOrderBy bean that defines the order in which beans should be returned @param nativeExpressions Native expression that will be used to augment the expression stored in the meta data. This text will be embedded at run-time @return An bean of the same type as the result argument that is filled in as specified the metadata for the retireve. @throws CpoException Thrown if there are errors accessing the datasource
[ "Retrieves", "the", "bean", "from", "the", "datasource", ".", "The", "assumption", "is", "that", "the", "bean", "exists", "in", "the", "datasource", ".", "If", "the", "retrieve", "function", "defined", "for", "this", "beans", "returns", "more", "than", "one", "row", "an", "exception", "will", "be", "thrown", "." ]
train
https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1428-L1436
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/cdn/CdnClient.java
CdnClient.setDomainRefererACL
public SetDomainRefererACLResponse setDomainRefererACL(SetDomainRefererACLRequest request) { """ Update RefererACL rules of specified domain acceleration. @param request The request containing all of the options related to the update request. @return Result of the setDomainRefererACL operation returned by the service. """ checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config"); internalRequest.addParameter("refererACL",""); this.attachRequestToBody(request, internalRequest); return invokeHttpClient(internalRequest, SetDomainRefererACLResponse.class); }
java
public SetDomainRefererACLResponse setDomainRefererACL(SetDomainRefererACLRequest request) { checkNotNull(request, "The parameter request should NOT be null."); InternalRequest internalRequest = createRequest(request, HttpMethodName.PUT, DOMAIN, request.getDomain(), "config"); internalRequest.addParameter("refererACL",""); this.attachRequestToBody(request, internalRequest); return invokeHttpClient(internalRequest, SetDomainRefererACLResponse.class); }
[ "public", "SetDomainRefererACLResponse", "setDomainRefererACL", "(", "SetDomainRefererACLRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"The parameter request should NOT be null.\"", ")", ";", "InternalRequest", "internalRequest", "=", "createRequest", "(", "request", ",", "HttpMethodName", ".", "PUT", ",", "DOMAIN", ",", "request", ".", "getDomain", "(", ")", ",", "\"config\"", ")", ";", "internalRequest", ".", "addParameter", "(", "\"refererACL\"", ",", "\"\"", ")", ";", "this", ".", "attachRequestToBody", "(", "request", ",", "internalRequest", ")", ";", "return", "invokeHttpClient", "(", "internalRequest", ",", "SetDomainRefererACLResponse", ".", "class", ")", ";", "}" ]
Update RefererACL rules of specified domain acceleration. @param request The request containing all of the options related to the update request. @return Result of the setDomainRefererACL operation returned by the service.
[ "Update", "RefererACL", "rules", "of", "specified", "domain", "acceleration", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/cdn/CdnClient.java#L398-L404
peterbencze/serritor
src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java
BaseCrawler.downloadFile
protected final void downloadFile(final URI source, final File destination) throws IOException { """ Downloads the file specified by the URL. @param source the source URL @param destination the destination file @throws IOException if an I/O error occurs while downloading the file """ Validate.validState(!isStopped, "Cannot download file when the crawler is not started."); Validate.validState(!isStopping, "Cannot download file when the crawler is stopping."); Validate.notNull(source, "The source URL cannot be null."); Validate.notNull(destination, "The destination file cannot be null."); HttpGet request = new HttpGet(source); try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { FileUtils.copyInputStreamToFile(entity.getContent(), destination); } } }
java
protected final void downloadFile(final URI source, final File destination) throws IOException { Validate.validState(!isStopped, "Cannot download file when the crawler is not started."); Validate.validState(!isStopping, "Cannot download file when the crawler is stopping."); Validate.notNull(source, "The source URL cannot be null."); Validate.notNull(destination, "The destination file cannot be null."); HttpGet request = new HttpGet(source); try (CloseableHttpResponse response = httpClient.execute(request)) { HttpEntity entity = response.getEntity(); if (entity != null) { FileUtils.copyInputStreamToFile(entity.getContent(), destination); } } }
[ "protected", "final", "void", "downloadFile", "(", "final", "URI", "source", ",", "final", "File", "destination", ")", "throws", "IOException", "{", "Validate", ".", "validState", "(", "!", "isStopped", ",", "\"Cannot download file when the crawler is not started.\"", ")", ";", "Validate", ".", "validState", "(", "!", "isStopping", ",", "\"Cannot download file when the crawler is stopping.\"", ")", ";", "Validate", ".", "notNull", "(", "source", ",", "\"The source URL cannot be null.\"", ")", ";", "Validate", ".", "notNull", "(", "destination", ",", "\"The destination file cannot be null.\"", ")", ";", "HttpGet", "request", "=", "new", "HttpGet", "(", "source", ")", ";", "try", "(", "CloseableHttpResponse", "response", "=", "httpClient", ".", "execute", "(", "request", ")", ")", "{", "HttpEntity", "entity", "=", "response", ".", "getEntity", "(", ")", ";", "if", "(", "entity", "!=", "null", ")", "{", "FileUtils", ".", "copyInputStreamToFile", "(", "entity", ".", "getContent", "(", ")", ",", "destination", ")", ";", "}", "}", "}" ]
Downloads the file specified by the URL. @param source the source URL @param destination the destination file @throws IOException if an I/O error occurs while downloading the file
[ "Downloads", "the", "file", "specified", "by", "the", "URL", "." ]
train
https://github.com/peterbencze/serritor/blob/10ed6f82c90fa1dccd684382b68b5d77a37652c0/src/main/java/com/github/peterbencze/serritor/api/BaseCrawler.java#L284-L297
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/Plugin.java
Plugin.loadCustomPlugin
public static Plugin loadCustomPlugin(File f, @CheckForNull Project project) throws PluginException { """ Loads the given plugin and enables it for the given project. @param f A non-null jar file of custom plugin. @param project A nullable target project """ URL urlString; try { urlString = f.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } return loadCustomPlugin(urlString, project); }
java
public static Plugin loadCustomPlugin(File f, @CheckForNull Project project) throws PluginException { URL urlString; try { urlString = f.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } return loadCustomPlugin(urlString, project); }
[ "public", "static", "Plugin", "loadCustomPlugin", "(", "File", "f", ",", "@", "CheckForNull", "Project", "project", ")", "throws", "PluginException", "{", "URL", "urlString", ";", "try", "{", "urlString", "=", "f", ".", "toURI", "(", ")", ".", "toURL", "(", ")", ";", "}", "catch", "(", "MalformedURLException", "e", ")", "{", "throw", "new", "IllegalArgumentException", "(", "e", ")", ";", "}", "return", "loadCustomPlugin", "(", "urlString", ",", "project", ")", ";", "}" ]
Loads the given plugin and enables it for the given project. @param f A non-null jar file of custom plugin. @param project A nullable target project
[ "Loads", "the", "given", "plugin", "and", "enables", "it", "for", "the", "given", "project", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/Plugin.java#L636-L645
aboutsip/pkts
pkts-sip/src/main/java/io/pkts/packet/sip/impl/PreConditions.java
PreConditions.ifNull
public static <T> T ifNull(final T reference, final T defaultValue) { """ If our reference is null then return a default value instead. @param reference the thing to check. @param defaultValue the default value to return if the above reference is null. @return the reference if not null, otherwise the default value. Note, if your default value is null as well then you will get back null, since that is what you asked. Chain with {@link #assertNotNull(Object, String)} if you want to make sure you have a non-null value for the default value. """ if (reference == null) { return defaultValue; } return reference; }
java
public static <T> T ifNull(final T reference, final T defaultValue) { if (reference == null) { return defaultValue; } return reference; }
[ "public", "static", "<", "T", ">", "T", "ifNull", "(", "final", "T", "reference", ",", "final", "T", "defaultValue", ")", "{", "if", "(", "reference", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "return", "reference", ";", "}" ]
If our reference is null then return a default value instead. @param reference the thing to check. @param defaultValue the default value to return if the above reference is null. @return the reference if not null, otherwise the default value. Note, if your default value is null as well then you will get back null, since that is what you asked. Chain with {@link #assertNotNull(Object, String)} if you want to make sure you have a non-null value for the default value.
[ "If", "our", "reference", "is", "null", "then", "return", "a", "default", "value", "instead", "." ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/PreConditions.java#L132-L137
drewnoakes/metadata-extractor
Source/com/drew/metadata/Directory.java
Directory.setString
@java.lang.SuppressWarnings( { """ Sets a <code>String</code> value for the specified tag. @param tagType the tag's value as an int @param value the value for the specified tag as a String """ "ConstantConditions" }) public void setString(int tagType, @NotNull String value) { if (value == null) throw new NullPointerException("cannot set a null String"); setObject(tagType, value); }
java
@java.lang.SuppressWarnings({ "ConstantConditions" }) public void setString(int tagType, @NotNull String value) { if (value == null) throw new NullPointerException("cannot set a null String"); setObject(tagType, value); }
[ "@", "java", ".", "lang", ".", "SuppressWarnings", "(", "{", "\"ConstantConditions\"", "}", ")", "public", "void", "setString", "(", "int", "tagType", ",", "@", "NotNull", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"cannot set a null String\"", ")", ";", "setObject", "(", "tagType", ",", "value", ")", ";", "}" ]
Sets a <code>String</code> value for the specified tag. @param tagType the tag's value as an int @param value the value for the specified tag as a String
[ "Sets", "a", "<code", ">", "String<", "/", "code", ">", "value", "for", "the", "specified", "tag", "." ]
train
https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/metadata/Directory.java#L283-L289
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/io/FileSupport.java
FileSupport.getFilesAndDirectoriesInDirectoryTree
public static ArrayList<File> getFilesAndDirectoriesInDirectoryTree(String path, String includeMask) { """ Retrieves all files from a directory and its subdirectories. @param path path to directory @param includeMask file name to match @return a list containing the found files """ File file = new File(path); return getContentsInDirectoryTree(file, includeMask, true, true); }
java
public static ArrayList<File> getFilesAndDirectoriesInDirectoryTree(String path, String includeMask) { File file = new File(path); return getContentsInDirectoryTree(file, includeMask, true, true); }
[ "public", "static", "ArrayList", "<", "File", ">", "getFilesAndDirectoriesInDirectoryTree", "(", "String", "path", ",", "String", "includeMask", ")", "{", "File", "file", "=", "new", "File", "(", "path", ")", ";", "return", "getContentsInDirectoryTree", "(", "file", ",", "includeMask", ",", "true", ",", "true", ")", ";", "}" ]
Retrieves all files from a directory and its subdirectories. @param path path to directory @param includeMask file name to match @return a list containing the found files
[ "Retrieves", "all", "files", "from", "a", "directory", "and", "its", "subdirectories", "." ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/io/FileSupport.java#L196-L199
UrielCh/ovh-java-sdk
ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java
ApiOvhDedicatedserver.serviceName_virtualNetworkInterface_GET
public ArrayList<String> serviceName_virtualNetworkInterface_GET(String serviceName, OvhVirtualNetworkInterfaceModeEnum mode, String name, String vrack) throws IOException { """ List server VirtualNetworkInterfaces REST: GET /dedicated/server/{serviceName}/virtualNetworkInterface @param name [required] Filter the value of name property (=) @param vrack [required] Filter the value of vrack property (=) @param mode [required] Filter the value of mode property (=) @param serviceName [required] The internal name of your dedicated server API beta """ String qPath = "/dedicated/server/{serviceName}/virtualNetworkInterface"; StringBuilder sb = path(qPath, serviceName); query(sb, "mode", mode); query(sb, "name", name); query(sb, "vrack", vrack); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
java
public ArrayList<String> serviceName_virtualNetworkInterface_GET(String serviceName, OvhVirtualNetworkInterfaceModeEnum mode, String name, String vrack) throws IOException { String qPath = "/dedicated/server/{serviceName}/virtualNetworkInterface"; StringBuilder sb = path(qPath, serviceName); query(sb, "mode", mode); query(sb, "name", name); query(sb, "vrack", vrack); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, t1); }
[ "public", "ArrayList", "<", "String", ">", "serviceName_virtualNetworkInterface_GET", "(", "String", "serviceName", ",", "OvhVirtualNetworkInterfaceModeEnum", "mode", ",", "String", "name", ",", "String", "vrack", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/dedicated/server/{serviceName}/virtualNetworkInterface\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ")", ";", "query", "(", "sb", ",", "\"mode\"", ",", "mode", ")", ";", "query", "(", "sb", ",", "\"name\"", ",", "name", ")", ";", "query", "(", "sb", ",", "\"vrack\"", ",", "vrack", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "t1", ")", ";", "}" ]
List server VirtualNetworkInterfaces REST: GET /dedicated/server/{serviceName}/virtualNetworkInterface @param name [required] Filter the value of name property (=) @param vrack [required] Filter the value of vrack property (=) @param mode [required] Filter the value of mode property (=) @param serviceName [required] The internal name of your dedicated server API beta
[ "List", "server", "VirtualNetworkInterfaces" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dedicatedserver/src/main/java/net/minidev/ovh/api/ApiOvhDedicatedserver.java#L185-L193
OpenLiberty/open-liberty
dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/utils/PromptX509TrustManager.java
PromptX509TrustManager.generateDigest
private String generateDigest(String algorithmName, X509Certificate cert) { """ This method is used to create a "SHA-1" or "MD5" digest on an X509Certificate as the "fingerprint". @param algorithmName @param cert @return String """ try { MessageDigest md = MessageDigest.getInstance(algorithmName); md.update(cert.getEncoded()); byte data[] = md.digest(); StringBuilder buffer = new StringBuilder(3 * data.length); int i = 0; buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]); buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]); for (++i; i < data.length; i++) { buffer.append(':'); buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]); buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]); } return buffer.toString(); } catch (NoClassDefFoundError e) { return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage()); } catch (Exception e) { return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage()); } }
java
private String generateDigest(String algorithmName, X509Certificate cert) { try { MessageDigest md = MessageDigest.getInstance(algorithmName); md.update(cert.getEncoded()); byte data[] = md.digest(); StringBuilder buffer = new StringBuilder(3 * data.length); int i = 0; buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]); buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]); for (++i; i < data.length; i++) { buffer.append(':'); buffer.append(HEX_CHARS[(data[i] >> 4) & 0xF]); buffer.append(HEX_CHARS[(data[i] % 16) & 0xF]); } return buffer.toString(); } catch (NoClassDefFoundError e) { return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage()); } catch (Exception e) { return getMessage("sslTrust.genDigestError", algorithmName, e.getMessage()); } }
[ "private", "String", "generateDigest", "(", "String", "algorithmName", ",", "X509Certificate", "cert", ")", "{", "try", "{", "MessageDigest", "md", "=", "MessageDigest", ".", "getInstance", "(", "algorithmName", ")", ";", "md", ".", "update", "(", "cert", ".", "getEncoded", "(", ")", ")", ";", "byte", "data", "[", "]", "=", "md", ".", "digest", "(", ")", ";", "StringBuilder", "buffer", "=", "new", "StringBuilder", "(", "3", "*", "data", ".", "length", ")", ";", "int", "i", "=", "0", ";", "buffer", ".", "append", "(", "HEX_CHARS", "[", "(", "data", "[", "i", "]", ">>", "4", ")", "&", "0xF", "]", ")", ";", "buffer", ".", "append", "(", "HEX_CHARS", "[", "(", "data", "[", "i", "]", "%", "16", ")", "&", "0xF", "]", ")", ";", "for", "(", "++", "i", ";", "i", "<", "data", ".", "length", ";", "i", "++", ")", "{", "buffer", ".", "append", "(", "'", "'", ")", ";", "buffer", ".", "append", "(", "HEX_CHARS", "[", "(", "data", "[", "i", "]", ">>", "4", ")", "&", "0xF", "]", ")", ";", "buffer", ".", "append", "(", "HEX_CHARS", "[", "(", "data", "[", "i", "]", "%", "16", ")", "&", "0xF", "]", ")", ";", "}", "return", "buffer", ".", "toString", "(", ")", ";", "}", "catch", "(", "NoClassDefFoundError", "e", ")", "{", "return", "getMessage", "(", "\"sslTrust.genDigestError\"", ",", "algorithmName", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "return", "getMessage", "(", "\"sslTrust.genDigestError\"", ",", "algorithmName", ",", "e", ".", "getMessage", "(", ")", ")", ";", "}", "}" ]
This method is used to create a "SHA-1" or "MD5" digest on an X509Certificate as the "fingerprint". @param algorithmName @param cert @return String
[ "This", "method", "is", "used", "to", "create", "a", "SHA", "-", "1", "or", "MD5", "digest", "on", "an", "X509Certificate", "as", "the", "fingerprint", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webserver.plugin.utility/src/com/ibm/ws/webserver/plugin/utility/utils/PromptX509TrustManager.java#L72-L94
Viascom/groundwork
foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/authorization/DefaultAuthorizationStrategy.java
DefaultAuthorizationStrategy.addAuthorization
@Override public void addAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { """ Add a new FoxHttpAuthorization to the AuthorizationStrategy @param foxHttpAuthorizationScope scope in which the authorization is used @param foxHttpAuthorization authorization itself """ if (foxHttpAuthorizations.containsKey(foxHttpAuthorizationScope.toString())) { foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()).add(foxHttpAuthorization); } else { foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), new ArrayList<>(Collections.singletonList(foxHttpAuthorization))); } }
java
@Override public void addAuthorization(FoxHttpAuthorizationScope foxHttpAuthorizationScope, FoxHttpAuthorization foxHttpAuthorization) { if (foxHttpAuthorizations.containsKey(foxHttpAuthorizationScope.toString())) { foxHttpAuthorizations.get(foxHttpAuthorizationScope.toString()).add(foxHttpAuthorization); } else { foxHttpAuthorizations.put(foxHttpAuthorizationScope.toString(), new ArrayList<>(Collections.singletonList(foxHttpAuthorization))); } }
[ "@", "Override", "public", "void", "addAuthorization", "(", "FoxHttpAuthorizationScope", "foxHttpAuthorizationScope", ",", "FoxHttpAuthorization", "foxHttpAuthorization", ")", "{", "if", "(", "foxHttpAuthorizations", ".", "containsKey", "(", "foxHttpAuthorizationScope", ".", "toString", "(", ")", ")", ")", "{", "foxHttpAuthorizations", ".", "get", "(", "foxHttpAuthorizationScope", ".", "toString", "(", ")", ")", ".", "add", "(", "foxHttpAuthorization", ")", ";", "}", "else", "{", "foxHttpAuthorizations", ".", "put", "(", "foxHttpAuthorizationScope", ".", "toString", "(", ")", ",", "new", "ArrayList", "<>", "(", "Collections", ".", "singletonList", "(", "foxHttpAuthorization", ")", ")", ")", ";", "}", "}" ]
Add a new FoxHttpAuthorization to the AuthorizationStrategy @param foxHttpAuthorizationScope scope in which the authorization is used @param foxHttpAuthorization authorization itself
[ "Add", "a", "new", "FoxHttpAuthorization", "to", "the", "AuthorizationStrategy" ]
train
https://github.com/Viascom/groundwork/blob/d3f7d0df65e2e75861fc7db938090683f2cdf919/foxhttp/src/main/java/ch/viascom/groundwork/foxhttp/authorization/DefaultAuthorizationStrategy.java#L59-L67
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java
AtomicAllocator.seekUnusedZero
protected synchronized long seekUnusedZero(Long bucketId, Aggressiveness aggressiveness) { """ This method seeks for unused zero-copy memory allocations @param bucketId Id of the bucket, serving allocations @return size of memory that was deallocated """ AtomicLong freeSpace = new AtomicLong(0); int totalElements = (int) memoryHandler.getAllocatedHostObjects(bucketId); // these 2 variables will contain jvm-wise memory access frequencies float shortAverage = zeroShort.getAverage(); float longAverage = zeroLong.getAverage(); // threshold is calculated based on agressiveness specified via configuration float shortThreshold = shortAverage / (Aggressiveness.values().length - aggressiveness.ordinal()); float longThreshold = longAverage / (Aggressiveness.values().length - aggressiveness.ordinal()); // simple counter for dereferenced objects AtomicInteger elementsDropped = new AtomicInteger(0); AtomicInteger elementsSurvived = new AtomicInteger(0); for (Long object : memoryHandler.getHostTrackingPoints(bucketId)) { AllocationPoint point = getAllocationPoint(object); // point can be null, if memory was promoted to device and was deleted there if (point == null) continue; if (point.getAllocationStatus() == AllocationStatus.HOST) { //point.getAccessState().isToeAvailable() //point.getAccessState().requestToe(); /* Check if memory points to non-existant buffer, using externals. If externals don't have specified buffer - delete reference. */ if (point.getBuffer() == null) { purgeZeroObject(bucketId, object, point, false); freeSpace.addAndGet(AllocationUtils.getRequiredMemory(point.getShape())); elementsDropped.incrementAndGet(); continue; } else { elementsSurvived.incrementAndGet(); } //point.getAccessState().releaseToe(); } else { // log.warn("SKIPPING :("); } } //log.debug("Short average: ["+shortAverage+"], Long average: [" + longAverage + "]"); //log.debug("Aggressiveness: ["+ aggressiveness+"]; Short threshold: ["+shortThreshold+"]; Long threshold: [" + longThreshold + "]"); log.debug("Zero {} elements checked: [{}], deleted: {}, survived: {}", bucketId, totalElements, elementsDropped.get(), elementsSurvived.get()); return freeSpace.get(); }
java
protected synchronized long seekUnusedZero(Long bucketId, Aggressiveness aggressiveness) { AtomicLong freeSpace = new AtomicLong(0); int totalElements = (int) memoryHandler.getAllocatedHostObjects(bucketId); // these 2 variables will contain jvm-wise memory access frequencies float shortAverage = zeroShort.getAverage(); float longAverage = zeroLong.getAverage(); // threshold is calculated based on agressiveness specified via configuration float shortThreshold = shortAverage / (Aggressiveness.values().length - aggressiveness.ordinal()); float longThreshold = longAverage / (Aggressiveness.values().length - aggressiveness.ordinal()); // simple counter for dereferenced objects AtomicInteger elementsDropped = new AtomicInteger(0); AtomicInteger elementsSurvived = new AtomicInteger(0); for (Long object : memoryHandler.getHostTrackingPoints(bucketId)) { AllocationPoint point = getAllocationPoint(object); // point can be null, if memory was promoted to device and was deleted there if (point == null) continue; if (point.getAllocationStatus() == AllocationStatus.HOST) { //point.getAccessState().isToeAvailable() //point.getAccessState().requestToe(); /* Check if memory points to non-existant buffer, using externals. If externals don't have specified buffer - delete reference. */ if (point.getBuffer() == null) { purgeZeroObject(bucketId, object, point, false); freeSpace.addAndGet(AllocationUtils.getRequiredMemory(point.getShape())); elementsDropped.incrementAndGet(); continue; } else { elementsSurvived.incrementAndGet(); } //point.getAccessState().releaseToe(); } else { // log.warn("SKIPPING :("); } } //log.debug("Short average: ["+shortAverage+"], Long average: [" + longAverage + "]"); //log.debug("Aggressiveness: ["+ aggressiveness+"]; Short threshold: ["+shortThreshold+"]; Long threshold: [" + longThreshold + "]"); log.debug("Zero {} elements checked: [{}], deleted: {}, survived: {}", bucketId, totalElements, elementsDropped.get(), elementsSurvived.get()); return freeSpace.get(); }
[ "protected", "synchronized", "long", "seekUnusedZero", "(", "Long", "bucketId", ",", "Aggressiveness", "aggressiveness", ")", "{", "AtomicLong", "freeSpace", "=", "new", "AtomicLong", "(", "0", ")", ";", "int", "totalElements", "=", "(", "int", ")", "memoryHandler", ".", "getAllocatedHostObjects", "(", "bucketId", ")", ";", "// these 2 variables will contain jvm-wise memory access frequencies", "float", "shortAverage", "=", "zeroShort", ".", "getAverage", "(", ")", ";", "float", "longAverage", "=", "zeroLong", ".", "getAverage", "(", ")", ";", "// threshold is calculated based on agressiveness specified via configuration", "float", "shortThreshold", "=", "shortAverage", "/", "(", "Aggressiveness", ".", "values", "(", ")", ".", "length", "-", "aggressiveness", ".", "ordinal", "(", ")", ")", ";", "float", "longThreshold", "=", "longAverage", "/", "(", "Aggressiveness", ".", "values", "(", ")", ".", "length", "-", "aggressiveness", ".", "ordinal", "(", ")", ")", ";", "// simple counter for dereferenced objects", "AtomicInteger", "elementsDropped", "=", "new", "AtomicInteger", "(", "0", ")", ";", "AtomicInteger", "elementsSurvived", "=", "new", "AtomicInteger", "(", "0", ")", ";", "for", "(", "Long", "object", ":", "memoryHandler", ".", "getHostTrackingPoints", "(", "bucketId", ")", ")", "{", "AllocationPoint", "point", "=", "getAllocationPoint", "(", "object", ")", ";", "// point can be null, if memory was promoted to device and was deleted there", "if", "(", "point", "==", "null", ")", "continue", ";", "if", "(", "point", ".", "getAllocationStatus", "(", ")", "==", "AllocationStatus", ".", "HOST", ")", "{", "//point.getAccessState().isToeAvailable()", "//point.getAccessState().requestToe();", "/*\n Check if memory points to non-existant buffer, using externals.\n If externals don't have specified buffer - delete reference.\n */", "if", "(", "point", ".", "getBuffer", "(", ")", "==", "null", ")", "{", "purgeZeroObject", "(", "bucketId", ",", "object", ",", "point", ",", "false", ")", ";", "freeSpace", ".", "addAndGet", "(", "AllocationUtils", ".", "getRequiredMemory", "(", "point", ".", "getShape", "(", ")", ")", ")", ";", "elementsDropped", ".", "incrementAndGet", "(", ")", ";", "continue", ";", "}", "else", "{", "elementsSurvived", ".", "incrementAndGet", "(", ")", ";", "}", "//point.getAccessState().releaseToe();", "}", "else", "{", "// log.warn(\"SKIPPING :(\");", "}", "}", "//log.debug(\"Short average: [\"+shortAverage+\"], Long average: [\" + longAverage + \"]\");", "//log.debug(\"Aggressiveness: [\"+ aggressiveness+\"]; Short threshold: [\"+shortThreshold+\"]; Long threshold: [\" + longThreshold + \"]\");", "log", ".", "debug", "(", "\"Zero {} elements checked: [{}], deleted: {}, survived: {}\"", ",", "bucketId", ",", "totalElements", ",", "elementsDropped", ".", "get", "(", ")", ",", "elementsSurvived", ".", "get", "(", ")", ")", ";", "return", "freeSpace", ".", "get", "(", ")", ";", "}" ]
This method seeks for unused zero-copy memory allocations @param bucketId Id of the bucket, serving allocations @return size of memory that was deallocated
[ "This", "method", "seeks", "for", "unused", "zero", "-", "copy", "memory", "allocations" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-backend-impls/nd4j-cuda/src/main/java/org/nd4j/jita/allocator/impl/AtomicAllocator.java#L563-L619
aboutsip/pkts
pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageStreamBuilder.java
SipMessageStreamBuilder.onPayload
private final State onPayload(final Buffer buffer) { """ We may or may not have a payload, which depends on whether there is a Content-length header available or not. If yes, then we will just slice out that entire thing once we have enough readable bytes in the buffer. @param buffer @return """ if (contentLength == 0) { return State.DONE; } if (buffer.getReadableBytes() >= contentLength) { try { payload = buffer.readBytes(contentLength); } catch (final IOException e) { throw new RuntimeException("Unable to read from stream due to IOException", e); } return State.DONE; } return State.GET_PAYLOAD; }
java
private final State onPayload(final Buffer buffer) { if (contentLength == 0) { return State.DONE; } if (buffer.getReadableBytes() >= contentLength) { try { payload = buffer.readBytes(contentLength); } catch (final IOException e) { throw new RuntimeException("Unable to read from stream due to IOException", e); } return State.DONE; } return State.GET_PAYLOAD; }
[ "private", "final", "State", "onPayload", "(", "final", "Buffer", "buffer", ")", "{", "if", "(", "contentLength", "==", "0", ")", "{", "return", "State", ".", "DONE", ";", "}", "if", "(", "buffer", ".", "getReadableBytes", "(", ")", ">=", "contentLength", ")", "{", "try", "{", "payload", "=", "buffer", ".", "readBytes", "(", "contentLength", ")", ";", "}", "catch", "(", "final", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Unable to read from stream due to IOException\"", ",", "e", ")", ";", "}", "return", "State", ".", "DONE", ";", "}", "return", "State", ".", "GET_PAYLOAD", ";", "}" ]
We may or may not have a payload, which depends on whether there is a Content-length header available or not. If yes, then we will just slice out that entire thing once we have enough readable bytes in the buffer. @param buffer @return
[ "We", "may", "or", "may", "not", "have", "a", "payload", "which", "depends", "on", "whether", "there", "is", "a", "Content", "-", "length", "header", "available", "or", "not", ".", "If", "yes", "then", "we", "will", "just", "slice", "out", "that", "entire", "thing", "once", "we", "have", "enough", "readable", "bytes", "in", "the", "buffer", "." ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-sip/src/main/java/io/pkts/packet/sip/impl/SipMessageStreamBuilder.java#L432-L447
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java
SuperPositionQCP.weightedSuperpose
public Matrix4d weightedSuperpose(Point3d[] fixed, Point3d[] moved, double[] weight) { """ Weighted superposition. @param fixed @param moved @param weight array of weigths for each equivalent point position @return """ set(moved, fixed, weight); getRotationMatrix(); if (!centered) { calcTransformation(); } else { transformation.set(rotmat); } return transformation; }
java
public Matrix4d weightedSuperpose(Point3d[] fixed, Point3d[] moved, double[] weight) { set(moved, fixed, weight); getRotationMatrix(); if (!centered) { calcTransformation(); } else { transformation.set(rotmat); } return transformation; }
[ "public", "Matrix4d", "weightedSuperpose", "(", "Point3d", "[", "]", "fixed", ",", "Point3d", "[", "]", "moved", ",", "double", "[", "]", "weight", ")", "{", "set", "(", "moved", ",", "fixed", ",", "weight", ")", ";", "getRotationMatrix", "(", ")", ";", "if", "(", "!", "centered", ")", "{", "calcTransformation", "(", ")", ";", "}", "else", "{", "transformation", ".", "set", "(", "rotmat", ")", ";", "}", "return", "transformation", ";", "}" ]
Weighted superposition. @param fixed @param moved @param weight array of weigths for each equivalent point position @return
[ "Weighted", "superposition", "." ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/geometry/SuperPositionQCP.java#L228-L237
agmip/ace-lookup
src/main/java/org/agmip/ace/util/AcePathfinderUtil.java
AcePathfinderUtil.buildNestedBuckets
private static void buildNestedBuckets(HashMap m, String p) { """ A helper method to created the nested bucket structure. @param m The map in which to build the nested structure. @param p The nested bucket structure to create """ String[] components = p.split(":"); int cl = components.length; if(cl == 1) { if( ! m.containsKey(components[0]) ) m.put(components[0], new HashMap()); } else { HashMap temp = m; for(int i=0; i < cl; i++) { if( ! temp.containsKey(components[i]) ) temp.put(components[i], new HashMap()); temp = (HashMap) temp.get(components[i]); } } }
java
private static void buildNestedBuckets(HashMap m, String p) { String[] components = p.split(":"); int cl = components.length; if(cl == 1) { if( ! m.containsKey(components[0]) ) m.put(components[0], new HashMap()); } else { HashMap temp = m; for(int i=0; i < cl; i++) { if( ! temp.containsKey(components[i]) ) temp.put(components[i], new HashMap()); temp = (HashMap) temp.get(components[i]); } } }
[ "private", "static", "void", "buildNestedBuckets", "(", "HashMap", "m", ",", "String", "p", ")", "{", "String", "[", "]", "components", "=", "p", ".", "split", "(", "\":\"", ")", ";", "int", "cl", "=", "components", ".", "length", ";", "if", "(", "cl", "==", "1", ")", "{", "if", "(", "!", "m", ".", "containsKey", "(", "components", "[", "0", "]", ")", ")", "m", ".", "put", "(", "components", "[", "0", "]", ",", "new", "HashMap", "(", ")", ")", ";", "}", "else", "{", "HashMap", "temp", "=", "m", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "cl", ";", "i", "++", ")", "{", "if", "(", "!", "temp", ".", "containsKey", "(", "components", "[", "i", "]", ")", ")", "temp", ".", "put", "(", "components", "[", "i", "]", ",", "new", "HashMap", "(", ")", ")", ";", "temp", "=", "(", "HashMap", ")", "temp", ".", "get", "(", "components", "[", "i", "]", ")", ";", "}", "}", "}" ]
A helper method to created the nested bucket structure. @param m The map in which to build the nested structure. @param p The nested bucket structure to create
[ "A", "helper", "method", "to", "created", "the", "nested", "bucket", "structure", "." ]
train
https://github.com/agmip/ace-lookup/blob/d8224a231cb8c01729e63010916a2a85517ce4c1/src/main/java/org/agmip/ace/util/AcePathfinderUtil.java#L260-L274
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/BasicTimeZone.java
BasicTimeZone.hasEquivalentTransitions
public boolean hasEquivalentTransitions(TimeZone tz, long start, long end) { """ <strong>[icu]</strong> Checks if the time zone has equivalent transitions in the time range. This method returns true when all of transition times, from/to standard offsets and DST savings used by this time zone match the other in the time range. <p>Example code:{{@literal @}.jcite android.icu.samples.util.timezone.BasicTimeZoneExample:---hasEquivalentTransitionsExample} @param tz The instance of <code>TimeZone</code> @param start The start time of the evaluated time range (inclusive) @param end The end time of the evaluated time range (inclusive) @return true if the other time zone has the equivalent transitions in the time range. When tz is not a <code>BasicTimeZone</code>, this method returns false. """ return hasEquivalentTransitions(tz, start, end, false); }
java
public boolean hasEquivalentTransitions(TimeZone tz, long start, long end) { return hasEquivalentTransitions(tz, start, end, false); }
[ "public", "boolean", "hasEquivalentTransitions", "(", "TimeZone", "tz", ",", "long", "start", ",", "long", "end", ")", "{", "return", "hasEquivalentTransitions", "(", "tz", ",", "start", ",", "end", ",", "false", ")", ";", "}" ]
<strong>[icu]</strong> Checks if the time zone has equivalent transitions in the time range. This method returns true when all of transition times, from/to standard offsets and DST savings used by this time zone match the other in the time range. <p>Example code:{{@literal @}.jcite android.icu.samples.util.timezone.BasicTimeZoneExample:---hasEquivalentTransitionsExample} @param tz The instance of <code>TimeZone</code> @param start The start time of the evaluated time range (inclusive) @param end The end time of the evaluated time range (inclusive) @return true if the other time zone has the equivalent transitions in the time range. When tz is not a <code>BasicTimeZone</code>, this method returns false.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Checks", "if", "the", "time", "zone", "has", "equivalent", "transitions", "in", "the", "time", "range", ".", "This", "method", "returns", "true", "when", "all", "of", "transition", "times", "from", "/", "to", "standard", "offsets", "and", "DST", "savings", "used", "by", "this", "time", "zone", "match", "the", "other", "in", "the", "time", "range", ".", "<p", ">", "Example", "code", ":", "{{", "@literal", "@", "}", ".", "jcite", "android", ".", "icu", ".", "samples", ".", "util", ".", "timezone", ".", "BasicTimeZoneExample", ":", "---", "hasEquivalentTransitionsExample", "}" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/util/BasicTimeZone.java#L78-L80
infinispan/infinispan
core/src/main/java/org/infinispan/container/offheap/OffHeapEntryFactoryImpl.java
OffHeapEntryFactoryImpl.equalsKey
@Override public boolean equalsKey(long address, WrappedBytes wrappedBytes) { """ Assumes the address points to the entry excluding the pointer reference at the beginning @param address the address of an entry to read @param wrappedBytes the key to check if it equals @return whether the key and address are equal """ // 16 bytes for eviction if needed (optional) // 8 bytes for linked pointer int headerOffset = evictionEnabled ? 24 : 8; byte type = MEMORY.getByte(address, headerOffset); headerOffset++; // First if hashCode doesn't match then the key can't be equal int hashCode = wrappedBytes.hashCode(); if (hashCode != MEMORY.getInt(address, headerOffset)) { return false; } headerOffset += 4; // If the length of the key is not the same it can't match either! int keyLength = MEMORY.getInt(address, headerOffset); if (keyLength != wrappedBytes.getLength()) { return false; } headerOffset += 4; if (requiresMetadataSize(type)) { headerOffset += 4; } // This is for the value size which we don't need to read headerOffset += 4; // Finally read each byte individually so we don't have to copy them into a byte[] for (int i = 0; i < keyLength; i++) { byte b = MEMORY.getByte(address, headerOffset + i); if (b != wrappedBytes.getByte(i)) return false; } return true; }
java
@Override public boolean equalsKey(long address, WrappedBytes wrappedBytes) { // 16 bytes for eviction if needed (optional) // 8 bytes for linked pointer int headerOffset = evictionEnabled ? 24 : 8; byte type = MEMORY.getByte(address, headerOffset); headerOffset++; // First if hashCode doesn't match then the key can't be equal int hashCode = wrappedBytes.hashCode(); if (hashCode != MEMORY.getInt(address, headerOffset)) { return false; } headerOffset += 4; // If the length of the key is not the same it can't match either! int keyLength = MEMORY.getInt(address, headerOffset); if (keyLength != wrappedBytes.getLength()) { return false; } headerOffset += 4; if (requiresMetadataSize(type)) { headerOffset += 4; } // This is for the value size which we don't need to read headerOffset += 4; // Finally read each byte individually so we don't have to copy them into a byte[] for (int i = 0; i < keyLength; i++) { byte b = MEMORY.getByte(address, headerOffset + i); if (b != wrappedBytes.getByte(i)) return false; } return true; }
[ "@", "Override", "public", "boolean", "equalsKey", "(", "long", "address", ",", "WrappedBytes", "wrappedBytes", ")", "{", "// 16 bytes for eviction if needed (optional)", "// 8 bytes for linked pointer", "int", "headerOffset", "=", "evictionEnabled", "?", "24", ":", "8", ";", "byte", "type", "=", "MEMORY", ".", "getByte", "(", "address", ",", "headerOffset", ")", ";", "headerOffset", "++", ";", "// First if hashCode doesn't match then the key can't be equal", "int", "hashCode", "=", "wrappedBytes", ".", "hashCode", "(", ")", ";", "if", "(", "hashCode", "!=", "MEMORY", ".", "getInt", "(", "address", ",", "headerOffset", ")", ")", "{", "return", "false", ";", "}", "headerOffset", "+=", "4", ";", "// If the length of the key is not the same it can't match either!", "int", "keyLength", "=", "MEMORY", ".", "getInt", "(", "address", ",", "headerOffset", ")", ";", "if", "(", "keyLength", "!=", "wrappedBytes", ".", "getLength", "(", ")", ")", "{", "return", "false", ";", "}", "headerOffset", "+=", "4", ";", "if", "(", "requiresMetadataSize", "(", "type", ")", ")", "{", "headerOffset", "+=", "4", ";", "}", "// This is for the value size which we don't need to read", "headerOffset", "+=", "4", ";", "// Finally read each byte individually so we don't have to copy them into a byte[]", "for", "(", "int", "i", "=", "0", ";", "i", "<", "keyLength", ";", "i", "++", ")", "{", "byte", "b", "=", "MEMORY", ".", "getByte", "(", "address", ",", "headerOffset", "+", "i", ")", ";", "if", "(", "b", "!=", "wrappedBytes", ".", "getByte", "(", "i", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Assumes the address points to the entry excluding the pointer reference at the beginning @param address the address of an entry to read @param wrappedBytes the key to check if it equals @return whether the key and address are equal
[ "Assumes", "the", "address", "points", "to", "the", "entry", "excluding", "the", "pointer", "reference", "at", "the", "beginning" ]
train
https://github.com/infinispan/infinispan/blob/7c62b94886c3febb4774ae8376acf2baa0265ab5/core/src/main/java/org/infinispan/container/offheap/OffHeapEntryFactoryImpl.java#L367-L399
apache/incubator-atlas
client/src/main/java/org/apache/atlas/AtlasClient.java
AtlasClient.getTraitDefinition
public Struct getTraitDefinition(final String guid, final String traitName) throws AtlasServiceException { """ Get trait definition for a given entity and traitname @param guid GUID of the entity @param traitName @return trait definition @throws AtlasServiceException """ JSONObject jsonResponse = callAPIWithBodyAndParams(API.GET_TRAIT_DEFINITION, null, guid, TRAIT_DEFINITIONS, traitName); try { return InstanceSerialization.fromJsonStruct(jsonResponse.getString(AtlasClient.RESULTS), false); }catch (JSONException e){ throw new AtlasServiceException(API.GET_TRAIT_DEFINITION, e); } }
java
public Struct getTraitDefinition(final String guid, final String traitName) throws AtlasServiceException{ JSONObject jsonResponse = callAPIWithBodyAndParams(API.GET_TRAIT_DEFINITION, null, guid, TRAIT_DEFINITIONS, traitName); try { return InstanceSerialization.fromJsonStruct(jsonResponse.getString(AtlasClient.RESULTS), false); }catch (JSONException e){ throw new AtlasServiceException(API.GET_TRAIT_DEFINITION, e); } }
[ "public", "Struct", "getTraitDefinition", "(", "final", "String", "guid", ",", "final", "String", "traitName", ")", "throws", "AtlasServiceException", "{", "JSONObject", "jsonResponse", "=", "callAPIWithBodyAndParams", "(", "API", ".", "GET_TRAIT_DEFINITION", ",", "null", ",", "guid", ",", "TRAIT_DEFINITIONS", ",", "traitName", ")", ";", "try", "{", "return", "InstanceSerialization", ".", "fromJsonStruct", "(", "jsonResponse", ".", "getString", "(", "AtlasClient", ".", "RESULTS", ")", ",", "false", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "throw", "new", "AtlasServiceException", "(", "API", ".", "GET_TRAIT_DEFINITION", ",", "e", ")", ";", "}", "}" ]
Get trait definition for a given entity and traitname @param guid GUID of the entity @param traitName @return trait definition @throws AtlasServiceException
[ "Get", "trait", "definition", "for", "a", "given", "entity", "and", "traitname" ]
train
https://github.com/apache/incubator-atlas/blob/e0d2cdc27c32742ebecd24db4cca62dc04dcdf4b/client/src/main/java/org/apache/atlas/AtlasClient.java#L736-L744
apereo/cas
support/cas-server-support-shell/src/main/java/org/apereo/cas/shell/commands/util/ValidateLdapConnectionCommand.java
ValidateLdapConnectionCommand.validateLdap
@ShellMethod(key = "validate-ldap", value = "Test connections to an LDAP server to verify connectivity, SSL, etc") public static void validateLdap( @ShellOption(value = { """ Validate endpoint. @param url the url @param bindDn the bind dn @param bindCredential the bind credential @param baseDn the base dn @param searchFilter the search filter @param userPassword the user password @param userAttributes the user attributes """"url"}, help = "LDAP URL to test, comma-separated.") final String url, @ShellOption(value = {"bindDn"}, help = "bindDn to use when testing the LDAP server") final String bindDn, @ShellOption(value = {"bindCredential"}, help = "bindCredential to use when testing the LDAP server") final String bindCredential, @ShellOption(value = {"baseDn"}, help = "baseDn to use when testing the LDAP server, searching for accounts (i.e. OU=some,DC=org,DC=edu)") final String baseDn, @ShellOption(value = {"searchFilter"}, help = "Filter to use when searching for accounts (i.e. (&(objectClass=*) (sAMAccountName=user)))") final String searchFilter, @ShellOption(value = {"userPassword"}, help = "Password for the user found in the search result, to attempt authentication") final String userPassword, @ShellOption(value = {"userAttributes"}, help = "User attributes, comma-separated, to fetch for the user found in the search result") final String userAttributes) { try { connect(url, bindDn, bindCredential, baseDn, searchFilter, userAttributes, userPassword); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }
java
@ShellMethod(key = "validate-ldap", value = "Test connections to an LDAP server to verify connectivity, SSL, etc") public static void validateLdap( @ShellOption(value = {"url"}, help = "LDAP URL to test, comma-separated.") final String url, @ShellOption(value = {"bindDn"}, help = "bindDn to use when testing the LDAP server") final String bindDn, @ShellOption(value = {"bindCredential"}, help = "bindCredential to use when testing the LDAP server") final String bindCredential, @ShellOption(value = {"baseDn"}, help = "baseDn to use when testing the LDAP server, searching for accounts (i.e. OU=some,DC=org,DC=edu)") final String baseDn, @ShellOption(value = {"searchFilter"}, help = "Filter to use when searching for accounts (i.e. (&(objectClass=*) (sAMAccountName=user)))") final String searchFilter, @ShellOption(value = {"userPassword"}, help = "Password for the user found in the search result, to attempt authentication") final String userPassword, @ShellOption(value = {"userAttributes"}, help = "User attributes, comma-separated, to fetch for the user found in the search result") final String userAttributes) { try { connect(url, bindDn, bindCredential, baseDn, searchFilter, userAttributes, userPassword); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }
[ "@", "ShellMethod", "(", "key", "=", "\"validate-ldap\"", ",", "value", "=", "\"Test connections to an LDAP server to verify connectivity, SSL, etc\"", ")", "public", "static", "void", "validateLdap", "(", "@", "ShellOption", "(", "value", "=", "{", "\"url\"", "}", ",", "help", "=", "\"LDAP URL to test, comma-separated.\"", ")", "final", "String", "url", ",", "@", "ShellOption", "(", "value", "=", "{", "\"bindDn\"", "}", ",", "help", "=", "\"bindDn to use when testing the LDAP server\"", ")", "final", "String", "bindDn", ",", "@", "ShellOption", "(", "value", "=", "{", "\"bindCredential\"", "}", ",", "help", "=", "\"bindCredential to use when testing the LDAP server\"", ")", "final", "String", "bindCredential", ",", "@", "ShellOption", "(", "value", "=", "{", "\"baseDn\"", "}", ",", "help", "=", "\"baseDn to use when testing the LDAP server, searching for accounts (i.e. OU=some,DC=org,DC=edu)\"", ")", "final", "String", "baseDn", ",", "@", "ShellOption", "(", "value", "=", "{", "\"searchFilter\"", "}", ",", "help", "=", "\"Filter to use when searching for accounts (i.e. (&(objectClass=*) (sAMAccountName=user)))\"", ")", "final", "String", "searchFilter", ",", "@", "ShellOption", "(", "value", "=", "{", "\"userPassword\"", "}", ",", "help", "=", "\"Password for the user found in the search result, to attempt authentication\"", ")", "final", "String", "userPassword", ",", "@", "ShellOption", "(", "value", "=", "{", "\"userAttributes\"", "}", ",", "help", "=", "\"User attributes, comma-separated, to fetch for the user found in the search result\"", ")", "final", "String", "userAttributes", ")", "{", "try", "{", "connect", "(", "url", ",", "bindDn", ",", "bindCredential", ",", "baseDn", ",", "searchFilter", ",", "userAttributes", ",", "userPassword", ")", ";", "}", "catch", "(", "final", "Exception", "e", ")", "{", "LOGGER", ".", "error", "(", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "}", "}" ]
Validate endpoint. @param url the url @param bindDn the bind dn @param bindCredential the bind credential @param baseDn the base dn @param searchFilter the search filter @param userPassword the user password @param userAttributes the user attributes
[ "Validate", "endpoint", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-shell/src/main/java/org/apereo/cas/shell/commands/util/ValidateLdapConnectionCommand.java#L42-L63
hal/core
flow/core/src/main/java/org/jboss/gwt/flow/client/Async.java
Async.whilst
public void whilst(Precondition condition, final Outcome outcome, final Function function) { """ Repeatedly call function, while condition is met. Calls the callback when stopped, or an error occurs. """ whilst(condition, outcome, function, -1); }
java
public void whilst(Precondition condition, final Outcome outcome, final Function function) { whilst(condition, outcome, function, -1); }
[ "public", "void", "whilst", "(", "Precondition", "condition", ",", "final", "Outcome", "outcome", ",", "final", "Function", "function", ")", "{", "whilst", "(", "condition", ",", "outcome", ",", "function", ",", "-", "1", ")", ";", "}" ]
Repeatedly call function, while condition is met. Calls the callback when stopped, or an error occurs.
[ "Repeatedly", "call", "function", "while", "condition", "is", "met", ".", "Calls", "the", "callback", "when", "stopped", "or", "an", "error", "occurs", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/flow/core/src/main/java/org/jboss/gwt/flow/client/Async.java#L157-L159
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/LossLayer.java
LossLayer.f1Score
@Override public double f1Score(INDArray examples, INDArray labels) { """ Returns the f1 score for the given examples. Think of this to be like a percentage right. The higher the number the more it got right. This is on a scale from 0 to 1. @param examples te the examples to classify (one example in each row) @param labels the true labels @return the scores for each ndarray """ Evaluation eval = new Evaluation(); eval.eval(labels, activate(examples, false, LayerWorkspaceMgr.noWorkspacesImmutable())); return eval.f1(); }
java
@Override public double f1Score(INDArray examples, INDArray labels) { Evaluation eval = new Evaluation(); eval.eval(labels, activate(examples, false, LayerWorkspaceMgr.noWorkspacesImmutable())); return eval.f1(); }
[ "@", "Override", "public", "double", "f1Score", "(", "INDArray", "examples", ",", "INDArray", "labels", ")", "{", "Evaluation", "eval", "=", "new", "Evaluation", "(", ")", ";", "eval", ".", "eval", "(", "labels", ",", "activate", "(", "examples", ",", "false", ",", "LayerWorkspaceMgr", ".", "noWorkspacesImmutable", "(", ")", ")", ")", ";", "return", "eval", ".", "f1", "(", ")", ";", "}" ]
Returns the f1 score for the given examples. Think of this to be like a percentage right. The higher the number the more it got right. This is on a scale from 0 to 1. @param examples te the examples to classify (one example in each row) @param labels the true labels @return the scores for each ndarray
[ "Returns", "the", "f1", "score", "for", "the", "given", "examples", ".", "Think", "of", "this", "to", "be", "like", "a", "percentage", "right", ".", "The", "higher", "the", "number", "the", "more", "it", "got", "right", ".", "This", "is", "on", "a", "scale", "from", "0", "to", "1", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/LossLayer.java#L225-L230
i-net-software/jlessc
src/com/inet/lib/less/FunctionExpression.java
FunctionExpression.evalParam
private void evalParam( int idx, CssFormatter formatter ) { """ Evaluate a parameter as this function. @param idx the index of the parameter starting with 0 @param formatter the current formation context """ Expression expr = get( idx ); type = expr.getDataType( formatter ); switch( type ) { case BOOLEAN: booleanValue = expr.booleanValue( formatter ); break; case STRING: break; default: doubleValue = expr.doubleValue( formatter ); } }
java
private void evalParam( int idx, CssFormatter formatter ) { Expression expr = get( idx ); type = expr.getDataType( formatter ); switch( type ) { case BOOLEAN: booleanValue = expr.booleanValue( formatter ); break; case STRING: break; default: doubleValue = expr.doubleValue( formatter ); } }
[ "private", "void", "evalParam", "(", "int", "idx", ",", "CssFormatter", "formatter", ")", "{", "Expression", "expr", "=", "get", "(", "idx", ")", ";", "type", "=", "expr", ".", "getDataType", "(", "formatter", ")", ";", "switch", "(", "type", ")", "{", "case", "BOOLEAN", ":", "booleanValue", "=", "expr", ".", "booleanValue", "(", "formatter", ")", ";", "break", ";", "case", "STRING", ":", "break", ";", "default", ":", "doubleValue", "=", "expr", ".", "doubleValue", "(", "formatter", ")", ";", "}", "}" ]
Evaluate a parameter as this function. @param idx the index of the parameter starting with 0 @param formatter the current formation context
[ "Evaluate", "a", "parameter", "as", "this", "function", "." ]
train
https://github.com/i-net-software/jlessc/blob/15b13e1637f6cc2e4d72df021e23ee0ca8d5e629/src/com/inet/lib/less/FunctionExpression.java#L748-L760
pmwmedia/tinylog
tinylog-api/src/main/java/org/tinylog/runtime/AndroidRuntime.java
AndroidRuntime.findStackTraceElement
private static StackTraceElement findStackTraceElement(final String loggerClassName, final StackTraceElement[] trace) { """ Gets the stack trace element that appears before the passed logger class name. @param loggerClassName Logger class name that should appear before the expected stack trace element @param trace Source stack trace @return Found stack trace element or {@code null} """ int index = 0; while (index < trace.length && !loggerClassName.equals(trace[index].getClassName())) { index = index + 1; } while (index < trace.length && loggerClassName.equals(trace[index].getClassName())) { index = index + 1; } if (index < trace.length) { return trace[index]; } else { return null; } }
java
private static StackTraceElement findStackTraceElement(final String loggerClassName, final StackTraceElement[] trace) { int index = 0; while (index < trace.length && !loggerClassName.equals(trace[index].getClassName())) { index = index + 1; } while (index < trace.length && loggerClassName.equals(trace[index].getClassName())) { index = index + 1; } if (index < trace.length) { return trace[index]; } else { return null; } }
[ "private", "static", "StackTraceElement", "findStackTraceElement", "(", "final", "String", "loggerClassName", ",", "final", "StackTraceElement", "[", "]", "trace", ")", "{", "int", "index", "=", "0", ";", "while", "(", "index", "<", "trace", ".", "length", "&&", "!", "loggerClassName", ".", "equals", "(", "trace", "[", "index", "]", ".", "getClassName", "(", ")", ")", ")", "{", "index", "=", "index", "+", "1", ";", "}", "while", "(", "index", "<", "trace", ".", "length", "&&", "loggerClassName", ".", "equals", "(", "trace", "[", "index", "]", ".", "getClassName", "(", ")", ")", ")", "{", "index", "=", "index", "+", "1", ";", "}", "if", "(", "index", "<", "trace", ".", "length", ")", "{", "return", "trace", "[", "index", "]", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
Gets the stack trace element that appears before the passed logger class name. @param loggerClassName Logger class name that should appear before the expected stack trace element @param trace Source stack trace @return Found stack trace element or {@code null}
[ "Gets", "the", "stack", "trace", "element", "that", "appears", "before", "the", "passed", "logger", "class", "name", "." ]
train
https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-api/src/main/java/org/tinylog/runtime/AndroidRuntime.java#L134-L150
tango-controls/JTango
server/src/main/java/org/tango/server/servant/DeviceImpl.java
DeviceImpl.initDevice
public synchronized void initDevice() { """ Initializes the device: <br> <ul> <li>reloads device and class properties</li> <li>applies memorized value to attributes</li> <li>restarts polling</li> <li>calls delete method {@link Delete} <li> <li>calls init method {@link Init} <li> </ul> """ MDC.setContextMap(contextMap); xlogger.entry(); if (stateImpl == null) { stateImpl = new StateImpl(businessObject, null, null); } if (statusImpl == null) { statusImpl = new StatusImpl(businessObject, null, null); } if (initImpl == null) { buildInit(null, false); } doInit(); try { pushInterfaceChangeEvent(true); } catch (final DevFailed e) { // ignore logger.error("error pushing event", e); } logger.debug("device init done"); xlogger.exit(); }
java
public synchronized void initDevice() { MDC.setContextMap(contextMap); xlogger.entry(); if (stateImpl == null) { stateImpl = new StateImpl(businessObject, null, null); } if (statusImpl == null) { statusImpl = new StatusImpl(businessObject, null, null); } if (initImpl == null) { buildInit(null, false); } doInit(); try { pushInterfaceChangeEvent(true); } catch (final DevFailed e) { // ignore logger.error("error pushing event", e); } logger.debug("device init done"); xlogger.exit(); }
[ "public", "synchronized", "void", "initDevice", "(", ")", "{", "MDC", ".", "setContextMap", "(", "contextMap", ")", ";", "xlogger", ".", "entry", "(", ")", ";", "if", "(", "stateImpl", "==", "null", ")", "{", "stateImpl", "=", "new", "StateImpl", "(", "businessObject", ",", "null", ",", "null", ")", ";", "}", "if", "(", "statusImpl", "==", "null", ")", "{", "statusImpl", "=", "new", "StatusImpl", "(", "businessObject", ",", "null", ",", "null", ")", ";", "}", "if", "(", "initImpl", "==", "null", ")", "{", "buildInit", "(", "null", ",", "false", ")", ";", "}", "doInit", "(", ")", ";", "try", "{", "pushInterfaceChangeEvent", "(", "true", ")", ";", "}", "catch", "(", "final", "DevFailed", "e", ")", "{", "// ignore", "logger", ".", "error", "(", "\"error pushing event\"", ",", "e", ")", ";", "}", "logger", ".", "debug", "(", "\"device init done\"", ")", ";", "xlogger", ".", "exit", "(", ")", ";", "}" ]
Initializes the device: <br> <ul> <li>reloads device and class properties</li> <li>applies memorized value to attributes</li> <li>restarts polling</li> <li>calls delete method {@link Delete} <li> <li>calls init method {@link Init} <li> </ul>
[ "Initializes", "the", "device", ":", "<br", ">", "<ul", ">", "<li", ">", "reloads", "device", "and", "class", "properties<", "/", "li", ">", "<li", ">", "applies", "memorized", "value", "to", "attributes<", "/", "li", ">", "<li", ">", "restarts", "polling<", "/", "li", ">", "<li", ">", "calls", "delete", "method", "{" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/servant/DeviceImpl.java#L710-L731
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/MethodDesc.java
MethodDesc.forArguments
public static MethodDesc forArguments(TypeDesc ret, TypeDesc... params) { """ Acquire a MethodDesc from a set of arguments. @param ret return type of method; null implies void @param params parameters to method; null implies none """ final String[] paramNames = createGenericParameterNames(params); return forArguments(ret, params, paramNames); }
java
public static MethodDesc forArguments(TypeDesc ret, TypeDesc... params) { final String[] paramNames = createGenericParameterNames(params); return forArguments(ret, params, paramNames); }
[ "public", "static", "MethodDesc", "forArguments", "(", "TypeDesc", "ret", ",", "TypeDesc", "...", "params", ")", "{", "final", "String", "[", "]", "paramNames", "=", "createGenericParameterNames", "(", "params", ")", ";", "return", "forArguments", "(", "ret", ",", "params", ",", "paramNames", ")", ";", "}" ]
Acquire a MethodDesc from a set of arguments. @param ret return type of method; null implies void @param params parameters to method; null implies none
[ "Acquire", "a", "MethodDesc", "from", "a", "set", "of", "arguments", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/MethodDesc.java#L48-L51
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java
ConsoleMenu.getInt
public static int getInt(final String title, final int defaultValue) { """ Gets an int from the System.in @param title for the command line @param defaultValue defaultValue if title not found @return int as entered by the user of the console app """ int opt; do { try { final String val = ConsoleMenu.getString(title + DEFAULT_TITLE + defaultValue + ")"); if (val.length() == 0) { opt = defaultValue; } else { opt = Integer.parseInt(val); } } catch (final NumberFormatException e) { opt = -1; } } while (opt == -1); return opt; }
java
public static int getInt(final String title, final int defaultValue) { int opt; do { try { final String val = ConsoleMenu.getString(title + DEFAULT_TITLE + defaultValue + ")"); if (val.length() == 0) { opt = defaultValue; } else { opt = Integer.parseInt(val); } } catch (final NumberFormatException e) { opt = -1; } } while (opt == -1); return opt; }
[ "public", "static", "int", "getInt", "(", "final", "String", "title", ",", "final", "int", "defaultValue", ")", "{", "int", "opt", ";", "do", "{", "try", "{", "final", "String", "val", "=", "ConsoleMenu", ".", "getString", "(", "title", "+", "DEFAULT_TITLE", "+", "defaultValue", "+", "\")\"", ")", ";", "if", "(", "val", ".", "length", "(", ")", "==", "0", ")", "{", "opt", "=", "defaultValue", ";", "}", "else", "{", "opt", "=", "Integer", ".", "parseInt", "(", "val", ")", ";", "}", "}", "catch", "(", "final", "NumberFormatException", "e", ")", "{", "opt", "=", "-", "1", ";", "}", "}", "while", "(", "opt", "==", "-", "1", ")", ";", "return", "opt", ";", "}" ]
Gets an int from the System.in @param title for the command line @param defaultValue defaultValue if title not found @return int as entered by the user of the console app
[ "Gets", "an", "int", "from", "the", "System", ".", "in" ]
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java#L218-L235
VoltDB/voltdb
src/frontend/org/voltdb/largequery/LargeBlockTask.java
LargeBlockTask.getLoadTask
public static LargeBlockTask getLoadTask(BlockId blockId, ByteBuffer block) { """ Get a new "load" task @param blockId The block id of the block to load @param block A ByteBuffer to write data intox @return An instance of LargeBlockTask that will load a block """ return new LargeBlockTask() { @Override public LargeBlockResponse call() throws Exception { Exception theException = null; try { LargeBlockManager.getInstance().loadBlock(blockId, block); } catch (Exception exc) { theException = exc; } return new LargeBlockResponse(theException); } }; }
java
public static LargeBlockTask getLoadTask(BlockId blockId, ByteBuffer block) { return new LargeBlockTask() { @Override public LargeBlockResponse call() throws Exception { Exception theException = null; try { LargeBlockManager.getInstance().loadBlock(blockId, block); } catch (Exception exc) { theException = exc; } return new LargeBlockResponse(theException); } }; }
[ "public", "static", "LargeBlockTask", "getLoadTask", "(", "BlockId", "blockId", ",", "ByteBuffer", "block", ")", "{", "return", "new", "LargeBlockTask", "(", ")", "{", "@", "Override", "public", "LargeBlockResponse", "call", "(", ")", "throws", "Exception", "{", "Exception", "theException", "=", "null", ";", "try", "{", "LargeBlockManager", ".", "getInstance", "(", ")", ".", "loadBlock", "(", "blockId", ",", "block", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "theException", "=", "exc", ";", "}", "return", "new", "LargeBlockResponse", "(", "theException", ")", ";", "}", "}", ";", "}" ]
Get a new "load" task @param blockId The block id of the block to load @param block A ByteBuffer to write data intox @return An instance of LargeBlockTask that will load a block
[ "Get", "a", "new", "load", "task" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/largequery/LargeBlockTask.java#L83-L98
wildfly/wildfly-core
deployment-repository/src/main/java/org/jboss/as/repository/PathUtil.java
PathUtil.deleteRecursively
public static void deleteRecursively(final Path path) throws IOException { """ Delete a path recursively. @param path a Path pointing to a file or a directory that may not exists anymore. @throws IOException """ DeploymentRepositoryLogger.ROOT_LOGGER.debugf("Deleting %s recursively", path); if (Files.exists(path)) { Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path); throw exc; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } }
java
public static void deleteRecursively(final Path path) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.debugf("Deleting %s recursively", path); if (Files.exists(path)) { Files.walkFileTree(path, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { DeploymentRepositoryLogger.ROOT_LOGGER.cannotDeleteFile(exc, path); throw exc; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } }
[ "public", "static", "void", "deleteRecursively", "(", "final", "Path", "path", ")", "throws", "IOException", "{", "DeploymentRepositoryLogger", ".", "ROOT_LOGGER", ".", "debugf", "(", "\"Deleting %s recursively\"", ",", "path", ")", ";", "if", "(", "Files", ".", "exists", "(", "path", ")", ")", "{", "Files", ".", "walkFileTree", "(", "path", ",", "new", "FileVisitor", "<", "Path", ">", "(", ")", "{", "@", "Override", "public", "FileVisitResult", "preVisitDirectory", "(", "Path", "dir", ",", "BasicFileAttributes", "attrs", ")", "throws", "IOException", "{", "return", "FileVisitResult", ".", "CONTINUE", ";", "}", "@", "Override", "public", "FileVisitResult", "visitFile", "(", "Path", "file", ",", "BasicFileAttributes", "attrs", ")", "throws", "IOException", "{", "Files", ".", "delete", "(", "file", ")", ";", "return", "FileVisitResult", ".", "CONTINUE", ";", "}", "@", "Override", "public", "FileVisitResult", "visitFileFailed", "(", "Path", "file", ",", "IOException", "exc", ")", "throws", "IOException", "{", "DeploymentRepositoryLogger", ".", "ROOT_LOGGER", ".", "cannotDeleteFile", "(", "exc", ",", "path", ")", ";", "throw", "exc", ";", "}", "@", "Override", "public", "FileVisitResult", "postVisitDirectory", "(", "Path", "dir", ",", "IOException", "exc", ")", "throws", "IOException", "{", "Files", ".", "delete", "(", "dir", ")", ";", "return", "FileVisitResult", ".", "CONTINUE", ";", "}", "}", ")", ";", "}", "}" ]
Delete a path recursively. @param path a Path pointing to a file or a directory that may not exists anymore. @throws IOException
[ "Delete", "a", "path", "recursively", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/deployment-repository/src/main/java/org/jboss/as/repository/PathUtil.java#L105-L133
fcrepo4/fcrepo4
fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/ContainerServiceImpl.java
ContainerServiceImpl.find
@Override public Container find(final FedoraSession session, final String path) { """ Retrieve a {@link org.fcrepo.kernel.api.models.Container} instance by pid and dsid @param path the path @param session the session @return A {@link org.fcrepo.kernel.api.models.Container} with the proffered PID """ final Node node = findNode(session, path); return cast(node); }
java
@Override public Container find(final FedoraSession session, final String path) { final Node node = findNode(session, path); return cast(node); }
[ "@", "Override", "public", "Container", "find", "(", "final", "FedoraSession", "session", ",", "final", "String", "path", ")", "{", "final", "Node", "node", "=", "findNode", "(", "session", ",", "path", ")", ";", "return", "cast", "(", "node", ")", ";", "}" ]
Retrieve a {@link org.fcrepo.kernel.api.models.Container} instance by pid and dsid @param path the path @param session the session @return A {@link org.fcrepo.kernel.api.models.Container} with the proffered PID
[ "Retrieve", "a", "{", "@link", "org", ".", "fcrepo", ".", "kernel", ".", "api", ".", "models", ".", "Container", "}", "instance", "by", "pid", "and", "dsid" ]
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-kernel-modeshape/src/main/java/org/fcrepo/kernel/modeshape/services/ContainerServiceImpl.java#L119-L124
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/SLINKHDBSCANLinearMemory.java
SLINKHDBSCANLinearMemory.step2
private void step2(DBIDRef id, DBIDs processedIDs, DistanceQuery<? super O> distQuery, DoubleDataStore coredists, WritableDoubleDataStore m) { """ Second step: Determine the pairwise distances from all objects in the pointer representation to the new object with the specified id. @param id the id of the object to be inserted into the pointer representation @param processedIDs the already processed ids @param distQuery Distance query @param m Data store """ double coreP = coredists.doubleValue(id); for(DBIDIter it = processedIDs.iter(); it.valid(); it.advance()) { // M(i) = dist(i, n+1) double coreQ = coredists.doubleValue(it); double dist = MathUtil.max(coreP, coreQ, distQuery.distance(id, it)); m.putDouble(it, dist); } }
java
private void step2(DBIDRef id, DBIDs processedIDs, DistanceQuery<? super O> distQuery, DoubleDataStore coredists, WritableDoubleDataStore m) { double coreP = coredists.doubleValue(id); for(DBIDIter it = processedIDs.iter(); it.valid(); it.advance()) { // M(i) = dist(i, n+1) double coreQ = coredists.doubleValue(it); double dist = MathUtil.max(coreP, coreQ, distQuery.distance(id, it)); m.putDouble(it, dist); } }
[ "private", "void", "step2", "(", "DBIDRef", "id", ",", "DBIDs", "processedIDs", ",", "DistanceQuery", "<", "?", "super", "O", ">", "distQuery", ",", "DoubleDataStore", "coredists", ",", "WritableDoubleDataStore", "m", ")", "{", "double", "coreP", "=", "coredists", ".", "doubleValue", "(", "id", ")", ";", "for", "(", "DBIDIter", "it", "=", "processedIDs", ".", "iter", "(", ")", ";", "it", ".", "valid", "(", ")", ";", "it", ".", "advance", "(", ")", ")", "{", "// M(i) = dist(i, n+1)", "double", "coreQ", "=", "coredists", ".", "doubleValue", "(", "it", ")", ";", "double", "dist", "=", "MathUtil", ".", "max", "(", "coreP", ",", "coreQ", ",", "distQuery", ".", "distance", "(", "id", ",", "it", ")", ")", ";", "m", ".", "putDouble", "(", "it", ",", "dist", ")", ";", "}", "}" ]
Second step: Determine the pairwise distances from all objects in the pointer representation to the new object with the specified id. @param id the id of the object to be inserted into the pointer representation @param processedIDs the already processed ids @param distQuery Distance query @param m Data store
[ "Second", "step", ":", "Determine", "the", "pairwise", "distances", "from", "all", "objects", "in", "the", "pointer", "representation", "to", "the", "new", "object", "with", "the", "specified", "id", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/SLINKHDBSCANLinearMemory.java#L156-L164
respoke/respoke-sdk-android
respokeSDK/src/main/java/com/digium/respokesdk/RespokeEndpoint.java
RespokeEndpoint.sendMessage
public void sendMessage(String message, boolean push, boolean ccSelf, final Respoke.TaskCompletionListener completionListener) { """ Send a message to the endpoint through the infrastructure. @param message The message to send @param push A flag indicating if a push notification should be sent for this message @param ccSelf A flag indicating if the message should be copied to other devices the client might be logged into @param completionListener A listener to receive a notification on the success of the asynchronous operation """ if ((null != signalingChannel) && (signalingChannel.connected)) { try { JSONObject data = new JSONObject(); data.put("to", endpointID); data.put("message", message); data.put("push", push); data.put("ccSelf", ccSelf); signalingChannel.sendRESTMessage("post", "/v1/messages", data, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { Respoke.postTaskSuccess(completionListener); } @Override public void onError(final String errorMessage) { Respoke.postTaskError(completionListener, errorMessage); } }); } catch (JSONException e) { Respoke.postTaskError(completionListener, "Error encoding message"); } } else { Respoke.postTaskError(completionListener, "Can't complete request when not connected. Please reconnect!"); } }
java
public void sendMessage(String message, boolean push, boolean ccSelf, final Respoke.TaskCompletionListener completionListener) { if ((null != signalingChannel) && (signalingChannel.connected)) { try { JSONObject data = new JSONObject(); data.put("to", endpointID); data.put("message", message); data.put("push", push); data.put("ccSelf", ccSelf); signalingChannel.sendRESTMessage("post", "/v1/messages", data, new RespokeSignalingChannel.RESTListener() { @Override public void onSuccess(Object response) { Respoke.postTaskSuccess(completionListener); } @Override public void onError(final String errorMessage) { Respoke.postTaskError(completionListener, errorMessage); } }); } catch (JSONException e) { Respoke.postTaskError(completionListener, "Error encoding message"); } } else { Respoke.postTaskError(completionListener, "Can't complete request when not connected. Please reconnect!"); } }
[ "public", "void", "sendMessage", "(", "String", "message", ",", "boolean", "push", ",", "boolean", "ccSelf", ",", "final", "Respoke", ".", "TaskCompletionListener", "completionListener", ")", "{", "if", "(", "(", "null", "!=", "signalingChannel", ")", "&&", "(", "signalingChannel", ".", "connected", ")", ")", "{", "try", "{", "JSONObject", "data", "=", "new", "JSONObject", "(", ")", ";", "data", ".", "put", "(", "\"to\"", ",", "endpointID", ")", ";", "data", ".", "put", "(", "\"message\"", ",", "message", ")", ";", "data", ".", "put", "(", "\"push\"", ",", "push", ")", ";", "data", ".", "put", "(", "\"ccSelf\"", ",", "ccSelf", ")", ";", "signalingChannel", ".", "sendRESTMessage", "(", "\"post\"", ",", "\"/v1/messages\"", ",", "data", ",", "new", "RespokeSignalingChannel", ".", "RESTListener", "(", ")", "{", "@", "Override", "public", "void", "onSuccess", "(", "Object", "response", ")", "{", "Respoke", ".", "postTaskSuccess", "(", "completionListener", ")", ";", "}", "@", "Override", "public", "void", "onError", "(", "final", "String", "errorMessage", ")", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "errorMessage", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "JSONException", "e", ")", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "\"Error encoding message\"", ")", ";", "}", "}", "else", "{", "Respoke", ".", "postTaskError", "(", "completionListener", ",", "\"Can't complete request when not connected. Please reconnect!\"", ")", ";", "}", "}" ]
Send a message to the endpoint through the infrastructure. @param message The message to send @param push A flag indicating if a push notification should be sent for this message @param ccSelf A flag indicating if the message should be copied to other devices the client might be logged into @param completionListener A listener to receive a notification on the success of the asynchronous operation
[ "Send", "a", "message", "to", "the", "endpoint", "through", "the", "infrastructure", "." ]
train
https://github.com/respoke/respoke-sdk-android/blob/34a15f0558d29b1f1bc8481bbc5c505e855e05ef/respokeSDK/src/main/java/com/digium/respokesdk/RespokeEndpoint.java#L106-L132
xfcjscn/sudoor-server-lib
src/main/java/net/gplatform/sudoor/server/security/model/DefaultPermissionEvaluator.java
DefaultPermissionEvaluator.getExpressionString
public String getExpressionString(String name, Object permission) { """ Find the expression string recursively from the config file @param name @param permission @return """ String expression = properties.getProperty(CONFIG_EXPRESSION_PREFIX + name + "." + permission); //Get generic permit if (expression == null) { expression = properties.getProperty(CONFIG_EXPRESSION_PREFIX + name); } //Get parent permit if (expression == null && StringUtils.contains(name, ".")) { String parent = StringUtils.substringBeforeLast(name, "."); expression = getExpressionString(parent, permission); } LOG.debug("Get Expression String: [{}] for name: [{}] permission: [{}]", expression, name, permission); return expression; }
java
public String getExpressionString(String name, Object permission) { String expression = properties.getProperty(CONFIG_EXPRESSION_PREFIX + name + "." + permission); //Get generic permit if (expression == null) { expression = properties.getProperty(CONFIG_EXPRESSION_PREFIX + name); } //Get parent permit if (expression == null && StringUtils.contains(name, ".")) { String parent = StringUtils.substringBeforeLast(name, "."); expression = getExpressionString(parent, permission); } LOG.debug("Get Expression String: [{}] for name: [{}] permission: [{}]", expression, name, permission); return expression; }
[ "public", "String", "getExpressionString", "(", "String", "name", ",", "Object", "permission", ")", "{", "String", "expression", "=", "properties", ".", "getProperty", "(", "CONFIG_EXPRESSION_PREFIX", "+", "name", "+", "\".\"", "+", "permission", ")", ";", "//Get generic permit", "if", "(", "expression", "==", "null", ")", "{", "expression", "=", "properties", ".", "getProperty", "(", "CONFIG_EXPRESSION_PREFIX", "+", "name", ")", ";", "}", "//Get parent permit", "if", "(", "expression", "==", "null", "&&", "StringUtils", ".", "contains", "(", "name", ",", "\".\"", ")", ")", "{", "String", "parent", "=", "StringUtils", ".", "substringBeforeLast", "(", "name", ",", "\".\"", ")", ";", "expression", "=", "getExpressionString", "(", "parent", ",", "permission", ")", ";", "}", "LOG", ".", "debug", "(", "\"Get Expression String: [{}] for name: [{}] permission: [{}]\"", ",", "expression", ",", "name", ",", "permission", ")", ";", "return", "expression", ";", "}" ]
Find the expression string recursively from the config file @param name @param permission @return
[ "Find", "the", "expression", "string", "recursively", "from", "the", "config", "file" ]
train
https://github.com/xfcjscn/sudoor-server-lib/blob/37dc1996eaa9cad25c82abd1de315ba565e32097/src/main/java/net/gplatform/sudoor/server/security/model/DefaultPermissionEvaluator.java#L75-L91
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/input/named/AbstractNamedInputHandler.java
AbstractNamedInputHandler.updateProperties
private void updateProperties(T target, Map<String, Object> source) { """ Updates bean by using PropertyDescriptors. Values are read from source. Is used by {@link #updateBean(Object, java.util.Map)} @param target target Bean @param source source Map """ Map<String, PropertyDescriptor> mapTargetProps = MappingUtils.mapPropertyDescriptors(target.getClass()); for (String sourceKey : source.keySet()) { if (mapTargetProps.containsKey(sourceKey) == true) { MappingUtils.callSetter(target, mapTargetProps.get(sourceKey), source.get(sourceKey)); } } }
java
private void updateProperties(T target, Map<String, Object> source) { Map<String, PropertyDescriptor> mapTargetProps = MappingUtils.mapPropertyDescriptors(target.getClass()); for (String sourceKey : source.keySet()) { if (mapTargetProps.containsKey(sourceKey) == true) { MappingUtils.callSetter(target, mapTargetProps.get(sourceKey), source.get(sourceKey)); } } }
[ "private", "void", "updateProperties", "(", "T", "target", ",", "Map", "<", "String", ",", "Object", ">", "source", ")", "{", "Map", "<", "String", ",", "PropertyDescriptor", ">", "mapTargetProps", "=", "MappingUtils", ".", "mapPropertyDescriptors", "(", "target", ".", "getClass", "(", ")", ")", ";", "for", "(", "String", "sourceKey", ":", "source", ".", "keySet", "(", ")", ")", "{", "if", "(", "mapTargetProps", ".", "containsKey", "(", "sourceKey", ")", "==", "true", ")", "{", "MappingUtils", ".", "callSetter", "(", "target", ",", "mapTargetProps", ".", "get", "(", "sourceKey", ")", ",", "source", ".", "get", "(", "sourceKey", ")", ")", ";", "}", "}", "}" ]
Updates bean by using PropertyDescriptors. Values are read from source. Is used by {@link #updateBean(Object, java.util.Map)} @param target target Bean @param source source Map
[ "Updates", "bean", "by", "using", "PropertyDescriptors", ".", "Values", "are", "read", "from", "source", ".", "Is", "used", "by", "{", "@link", "#updateBean", "(", "Object", "java", ".", "util", ".", "Map", ")", "}" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/input/named/AbstractNamedInputHandler.java#L104-L112
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.readDefaultFile
public CmsResource readDefaultFile( CmsRequestContext context, CmsResource resource, CmsResourceFilter resourceFilter) throws CmsSecurityException { """ Returns the default file for the given folder.<p> If the given resource is a file, then this file is returned.<p> Otherwise, in case of a folder:<br> <ol> <li>the {@link CmsPropertyDefinition#PROPERTY_DEFAULT_FILE} is checked, and <li>if still no file could be found, the configured default files in the <code>opencms-vfs.xml</code> configuration are iterated until a match is found, and <li>if still no file could be found, <code>null</code> is returned </ol><p> @param context the request context @param resource the folder to get the default file for @param resourceFilter the resource filter @return the default file for the given folder @throws CmsSecurityException if the user has no permissions to read the resulting file @see CmsObject#readDefaultFile(String) """ CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsResource tempResult = m_driverManager.readDefaultFile(dbc, resource, resourceFilter); if (tempResult != null) { // check if the user has read access to the resource checkPermissions(dbc, tempResult, CmsPermissionSet.ACCESS_READ, true, resourceFilter); result = tempResult; } } catch (CmsSecurityException se) { // permissions deny access to the resource throw se; } catch (CmsException e) { // ignore all other exceptions LOG.debug(e.getLocalizedMessage(), e); } finally { dbc.clear(); } return result; }
java
public CmsResource readDefaultFile( CmsRequestContext context, CmsResource resource, CmsResourceFilter resourceFilter) throws CmsSecurityException { CmsResource result = null; CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsResource tempResult = m_driverManager.readDefaultFile(dbc, resource, resourceFilter); if (tempResult != null) { // check if the user has read access to the resource checkPermissions(dbc, tempResult, CmsPermissionSet.ACCESS_READ, true, resourceFilter); result = tempResult; } } catch (CmsSecurityException se) { // permissions deny access to the resource throw se; } catch (CmsException e) { // ignore all other exceptions LOG.debug(e.getLocalizedMessage(), e); } finally { dbc.clear(); } return result; }
[ "public", "CmsResource", "readDefaultFile", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "CmsResourceFilter", "resourceFilter", ")", "throws", "CmsSecurityException", "{", "CmsResource", "result", "=", "null", ";", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(", "context", ")", ";", "try", "{", "CmsResource", "tempResult", "=", "m_driverManager", ".", "readDefaultFile", "(", "dbc", ",", "resource", ",", "resourceFilter", ")", ";", "if", "(", "tempResult", "!=", "null", ")", "{", "// check if the user has read access to the resource", "checkPermissions", "(", "dbc", ",", "tempResult", ",", "CmsPermissionSet", ".", "ACCESS_READ", ",", "true", ",", "resourceFilter", ")", ";", "result", "=", "tempResult", ";", "}", "}", "catch", "(", "CmsSecurityException", "se", ")", "{", "// permissions deny access to the resource", "throw", "se", ";", "}", "catch", "(", "CmsException", "e", ")", "{", "// ignore all other exceptions", "LOG", ".", "debug", "(", "e", ".", "getLocalizedMessage", "(", ")", ",", "e", ")", ";", "}", "finally", "{", "dbc", ".", "clear", "(", ")", ";", "}", "return", "result", ";", "}" ]
Returns the default file for the given folder.<p> If the given resource is a file, then this file is returned.<p> Otherwise, in case of a folder:<br> <ol> <li>the {@link CmsPropertyDefinition#PROPERTY_DEFAULT_FILE} is checked, and <li>if still no file could be found, the configured default files in the <code>opencms-vfs.xml</code> configuration are iterated until a match is found, and <li>if still no file could be found, <code>null</code> is returned </ol><p> @param context the request context @param resource the folder to get the default file for @param resourceFilter the resource filter @return the default file for the given folder @throws CmsSecurityException if the user has no permissions to read the resulting file @see CmsObject#readDefaultFile(String)
[ "Returns", "the", "default", "file", "for", "the", "given", "folder", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L4183-L4208
aws/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/util/XpathUtils.java
XpathUtils.asLong
public static Long asLong(String expression, Node node) throws XPathExpressionException { """ Evaluates the specified XPath expression and returns the result as a Long. <p> This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { {@link #asDouble(String, Node, XPath)} instead. Note {@link XPath} is not thread-safe and not reentrant. @param expression The XPath expression to evaluate. @param node The node to run the expression on. @return The Long result. @throws XPathExpressionException If there was a problem processing the specified XPath expression. """ return asLong(expression, node, xpath()); }
java
public static Long asLong(String expression, Node node) throws XPathExpressionException { return asLong(expression, node, xpath()); }
[ "public", "static", "Long", "asLong", "(", "String", "expression", ",", "Node", "node", ")", "throws", "XPathExpressionException", "{", "return", "asLong", "(", "expression", ",", "node", ",", "xpath", "(", ")", ")", ";", "}" ]
Evaluates the specified XPath expression and returns the result as a Long. <p> This method can be expensive as a new xpath is instantiated per invocation. Consider passing in the xpath explicitly via { {@link #asDouble(String, Node, XPath)} instead. Note {@link XPath} is not thread-safe and not reentrant. @param expression The XPath expression to evaluate. @param node The node to run the expression on. @return The Long result. @throws XPathExpressionException If there was a problem processing the specified XPath expression.
[ "Evaluates", "the", "specified", "XPath", "expression", "and", "returns", "the", "result", "as", "a", "Long", ".", "<p", ">", "This", "method", "can", "be", "expensive", "as", "a", "new", "xpath", "is", "instantiated", "per", "invocation", ".", "Consider", "passing", "in", "the", "xpath", "explicitly", "via", "{", "{", "@link", "#asDouble", "(", "String", "Node", "XPath", ")", "}", "instead", ".", "Note", "{", "@link", "XPath", "}", "is", "not", "thread", "-", "safe", "and", "not", "reentrant", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/XpathUtils.java#L382-L385
threerings/nenya
core/src/main/java/com/threerings/miso/util/MisoUtil.java
MisoUtil.screenToFull
public static Point screenToFull ( MisoSceneMetrics metrics, int sx, int sy, Point fpos) { """ Convert the given screen-based pixel coordinates to full scene-based coordinates that include both the tile coordinates and the fine coordinates in each dimension. Converted coordinates are placed in the given point object. @param sx the screen x-position pixel coordinate. @param sy the screen y-position pixel coordinate. @param fpos the point object to place coordinates in. @return the point passed in to receive the coordinates. """ // get the tile coordinates Point tpos = new Point(); screenToTile(metrics, sx, sy, tpos); // get the screen coordinates for the containing tile Point spos = tileToScreen(metrics, tpos.x, tpos.y, new Point()); // Log.info("Screen to full " + // "[screen=" + StringUtil.coordsToString(sx, sy) + // ", tpos=" + StringUtil.toString(tpos) + // ", spos=" + StringUtil.toString(spos) + // ", fpix=" + StringUtil.coordsToString( // sx-spos.x, sy-spos.y) + "]."); // get the fine coordinates within the containing tile pixelToFine(metrics, sx - spos.x, sy - spos.y, fpos); // toss in the tile coordinates for good measure fpos.x += (tpos.x * FULL_TILE_FACTOR); fpos.y += (tpos.y * FULL_TILE_FACTOR); return fpos; }
java
public static Point screenToFull ( MisoSceneMetrics metrics, int sx, int sy, Point fpos) { // get the tile coordinates Point tpos = new Point(); screenToTile(metrics, sx, sy, tpos); // get the screen coordinates for the containing tile Point spos = tileToScreen(metrics, tpos.x, tpos.y, new Point()); // Log.info("Screen to full " + // "[screen=" + StringUtil.coordsToString(sx, sy) + // ", tpos=" + StringUtil.toString(tpos) + // ", spos=" + StringUtil.toString(spos) + // ", fpix=" + StringUtil.coordsToString( // sx-spos.x, sy-spos.y) + "]."); // get the fine coordinates within the containing tile pixelToFine(metrics, sx - spos.x, sy - spos.y, fpos); // toss in the tile coordinates for good measure fpos.x += (tpos.x * FULL_TILE_FACTOR); fpos.y += (tpos.y * FULL_TILE_FACTOR); return fpos; }
[ "public", "static", "Point", "screenToFull", "(", "MisoSceneMetrics", "metrics", ",", "int", "sx", ",", "int", "sy", ",", "Point", "fpos", ")", "{", "// get the tile coordinates", "Point", "tpos", "=", "new", "Point", "(", ")", ";", "screenToTile", "(", "metrics", ",", "sx", ",", "sy", ",", "tpos", ")", ";", "// get the screen coordinates for the containing tile", "Point", "spos", "=", "tileToScreen", "(", "metrics", ",", "tpos", ".", "x", ",", "tpos", ".", "y", ",", "new", "Point", "(", ")", ")", ";", "// Log.info(\"Screen to full \" +", "// \"[screen=\" + StringUtil.coordsToString(sx, sy) +", "// \", tpos=\" + StringUtil.toString(tpos) +", "// \", spos=\" + StringUtil.toString(spos) +", "// \", fpix=\" + StringUtil.coordsToString(", "// sx-spos.x, sy-spos.y) + \"].\");", "// get the fine coordinates within the containing tile", "pixelToFine", "(", "metrics", ",", "sx", "-", "spos", ".", "x", ",", "sy", "-", "spos", ".", "y", ",", "fpos", ")", ";", "// toss in the tile coordinates for good measure", "fpos", ".", "x", "+=", "(", "tpos", ".", "x", "*", "FULL_TILE_FACTOR", ")", ";", "fpos", ".", "y", "+=", "(", "tpos", ".", "y", "*", "FULL_TILE_FACTOR", ")", ";", "return", "fpos", ";", "}" ]
Convert the given screen-based pixel coordinates to full scene-based coordinates that include both the tile coordinates and the fine coordinates in each dimension. Converted coordinates are placed in the given point object. @param sx the screen x-position pixel coordinate. @param sy the screen y-position pixel coordinate. @param fpos the point object to place coordinates in. @return the point passed in to receive the coordinates.
[ "Convert", "the", "given", "screen", "-", "based", "pixel", "coordinates", "to", "full", "scene", "-", "based", "coordinates", "that", "include", "both", "the", "tile", "coordinates", "and", "the", "fine", "coordinates", "in", "each", "dimension", ".", "Converted", "coordinates", "are", "placed", "in", "the", "given", "point", "object", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/miso/util/MisoUtil.java#L317-L342
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.update_child_account
public String update_child_account(Object data) { """ /* Update Child Account. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} auth_key: 16 character authorization key of Reseller child to be modified [Mandatory] @options data {String} company_org: Name of Reseller child’s company [Optional] @options data {String} first_name: First name of Reseller child [Optional] @options data {String} last_name: Last name of Reseller child [Optional] @options data {String} password: Password of Reseller child to login [Optional] @options data {Array} associate_ip: Associate dedicated IPs to reseller child. You can use commas to separate multiple IPs [Optional] @options data {Array} disassociate_ip: Disassociate dedicated IPs from reseller child. You can use commas to separate multiple IPs [Optional] """ Gson gson = new Gson(); String json = gson.toJson(data); return put("account", json); }
java
public String update_child_account(Object data) { Gson gson = new Gson(); String json = gson.toJson(data); return put("account", json); }
[ "public", "String", "update_child_account", "(", "Object", "data", ")", "{", "Gson", "gson", "=", "new", "Gson", "(", ")", ";", "String", "json", "=", "gson", ".", "toJson", "(", "data", ")", ";", "return", "put", "(", "\"account\"", ",", "json", ")", ";", "}" ]
/* Update Child Account. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} auth_key: 16 character authorization key of Reseller child to be modified [Mandatory] @options data {String} company_org: Name of Reseller child’s company [Optional] @options data {String} first_name: First name of Reseller child [Optional] @options data {String} last_name: Last name of Reseller child [Optional] @options data {String} password: Password of Reseller child to login [Optional] @options data {Array} associate_ip: Associate dedicated IPs to reseller child. You can use commas to separate multiple IPs [Optional] @options data {Array} disassociate_ip: Disassociate dedicated IPs from reseller child. You can use commas to separate multiple IPs [Optional]
[ "/", "*", "Update", "Child", "Account", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L212-L216
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/word2vec/wordstore/inmemory/AbstractCache.java
AbstractCache.incrementDocCount
@Override public void incrementDocCount(String word, long howMuch) { """ Increment number of documents the label was observed in Please note: this method is NOT thread-safe @param word the word to increment by @param howMuch """ T element = extendedVocabulary.get(word); if (element != null) { element.incrementSequencesCount(); } }
java
@Override public void incrementDocCount(String word, long howMuch) { T element = extendedVocabulary.get(word); if (element != null) { element.incrementSequencesCount(); } }
[ "@", "Override", "public", "void", "incrementDocCount", "(", "String", "word", ",", "long", "howMuch", ")", "{", "T", "element", "=", "extendedVocabulary", ".", "get", "(", "word", ")", ";", "if", "(", "element", "!=", "null", ")", "{", "element", ".", "incrementSequencesCount", "(", ")", ";", "}", "}" ]
Increment number of documents the label was observed in Please note: this method is NOT thread-safe @param word the word to increment by @param howMuch
[ "Increment", "number", "of", "documents", "the", "label", "was", "observed", "in" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/word2vec/wordstore/inmemory/AbstractCache.java#L334-L340
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java
PerspectiveOps.projectionSplit
public static void projectionSplit( DMatrixRMaj P , DMatrixRMaj M , Vector3D_F64 T ) { """ Splits the projection matrix into a 3x3 matrix and 3x1 vector. @param P (Input) 3x4 projection matirx @param M (Output) M = P(:,0:2) @param T (Output) T = P(:,3) """ CommonOps_DDRM.extract(P,0,3,0,3,M,0,0); T.x = P.get(0,3); T.y = P.get(1,3); T.z = P.get(2,3); }
java
public static void projectionSplit( DMatrixRMaj P , DMatrixRMaj M , Vector3D_F64 T ) { CommonOps_DDRM.extract(P,0,3,0,3,M,0,0); T.x = P.get(0,3); T.y = P.get(1,3); T.z = P.get(2,3); }
[ "public", "static", "void", "projectionSplit", "(", "DMatrixRMaj", "P", ",", "DMatrixRMaj", "M", ",", "Vector3D_F64", "T", ")", "{", "CommonOps_DDRM", ".", "extract", "(", "P", ",", "0", ",", "3", ",", "0", ",", "3", ",", "M", ",", "0", ",", "0", ")", ";", "T", ".", "x", "=", "P", ".", "get", "(", "0", ",", "3", ")", ";", "T", ".", "y", "=", "P", ".", "get", "(", "1", ",", "3", ")", ";", "T", ".", "z", "=", "P", ".", "get", "(", "2", ",", "3", ")", ";", "}" ]
Splits the projection matrix into a 3x3 matrix and 3x1 vector. @param P (Input) 3x4 projection matirx @param M (Output) M = P(:,0:2) @param T (Output) T = P(:,3)
[ "Splits", "the", "projection", "matrix", "into", "a", "3x3", "matrix", "and", "3x1", "vector", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/PerspectiveOps.java#L650-L655
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/HashUtils.java
HashUtils.getMD5String
public static String getMD5String(String str) { """ Calculate MD5 hash of a String @param str - the String to hash @return the MD5 hash value """ MessageDigest messageDigest = getMessageDigest(MD5); return getHashString(str, messageDigest); }
java
public static String getMD5String(String str) { MessageDigest messageDigest = getMessageDigest(MD5); return getHashString(str, messageDigest); }
[ "public", "static", "String", "getMD5String", "(", "String", "str", ")", "{", "MessageDigest", "messageDigest", "=", "getMessageDigest", "(", "MD5", ")", ";", "return", "getHashString", "(", "str", ",", "messageDigest", ")", ";", "}" ]
Calculate MD5 hash of a String @param str - the String to hash @return the MD5 hash value
[ "Calculate", "MD5", "hash", "of", "a", "String" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.feature.core/src/com/ibm/ws/kernel/feature/internal/HashUtils.java#L35-L38
ngageoint/geopackage-android-map
geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java
StyleUtils.createMarkerOptions
public static MarkerOptions createMarkerOptions(GeoPackage geoPackage, FeatureRow featureRow, float density, IconCache iconCache) { """ Create new marker options populated with the feature row style (icon or style) @param geoPackage GeoPackage @param featureRow feature row @param density display density: {@link android.util.DisplayMetrics#density} @param iconCache icon cache @return marker options populated with the feature style """ MarkerOptions markerOptions = new MarkerOptions(); setFeatureStyle(markerOptions, geoPackage, featureRow, density, iconCache); return markerOptions; }
java
public static MarkerOptions createMarkerOptions(GeoPackage geoPackage, FeatureRow featureRow, float density, IconCache iconCache) { MarkerOptions markerOptions = new MarkerOptions(); setFeatureStyle(markerOptions, geoPackage, featureRow, density, iconCache); return markerOptions; }
[ "public", "static", "MarkerOptions", "createMarkerOptions", "(", "GeoPackage", "geoPackage", ",", "FeatureRow", "featureRow", ",", "float", "density", ",", "IconCache", "iconCache", ")", "{", "MarkerOptions", "markerOptions", "=", "new", "MarkerOptions", "(", ")", ";", "setFeatureStyle", "(", "markerOptions", ",", "geoPackage", ",", "featureRow", ",", "density", ",", "iconCache", ")", ";", "return", "markerOptions", ";", "}" ]
Create new marker options populated with the feature row style (icon or style) @param geoPackage GeoPackage @param featureRow feature row @param density display density: {@link android.util.DisplayMetrics#density} @param iconCache icon cache @return marker options populated with the feature style
[ "Create", "new", "marker", "options", "populated", "with", "the", "feature", "row", "style", "(", "icon", "or", "style", ")" ]
train
https://github.com/ngageoint/geopackage-android-map/blob/634d78468a5c52d2bc98791cc7ff03981ebf573b/geopackage-map/src/main/java/mil/nga/geopackage/map/features/StyleUtils.java#L48-L54
greenmail-mail-test/greenmail
greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java
GreenMailUtil.setQuota
public static void setQuota(final GreenMailUser user, final Quota quota) { """ Sets a quota for a users. @param user the user. @param quota the quota. """ Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP); try { Store store = session.getStore("imap"); store.connect(user.getEmail(), user.getPassword()); try { ((QuotaAwareStore) store).setQuota(quota); } finally { store.close(); } } catch (Exception ex) { throw new IllegalStateException("Can not set quota " + quota + " for user " + user, ex); } }
java
public static void setQuota(final GreenMailUser user, final Quota quota) { Session session = GreenMailUtil.getSession(ServerSetupTest.IMAP); try { Store store = session.getStore("imap"); store.connect(user.getEmail(), user.getPassword()); try { ((QuotaAwareStore) store).setQuota(quota); } finally { store.close(); } } catch (Exception ex) { throw new IllegalStateException("Can not set quota " + quota + " for user " + user, ex); } }
[ "public", "static", "void", "setQuota", "(", "final", "GreenMailUser", "user", ",", "final", "Quota", "quota", ")", "{", "Session", "session", "=", "GreenMailUtil", ".", "getSession", "(", "ServerSetupTest", ".", "IMAP", ")", ";", "try", "{", "Store", "store", "=", "session", ".", "getStore", "(", "\"imap\"", ")", ";", "store", ".", "connect", "(", "user", ".", "getEmail", "(", ")", ",", "user", ".", "getPassword", "(", ")", ")", ";", "try", "{", "(", "(", "QuotaAwareStore", ")", "store", ")", ".", "setQuota", "(", "quota", ")", ";", "}", "finally", "{", "store", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Can not set quota \"", "+", "quota", "+", "\" for user \"", "+", "user", ",", "ex", ")", ";", "}", "}" ]
Sets a quota for a users. @param user the user. @param quota the quota.
[ "Sets", "a", "quota", "for", "a", "users", "." ]
train
https://github.com/greenmail-mail-test/greenmail/blob/6d19a62233d1ef6fedbbd1f6fdde2d28e713834a/greenmail-core/src/main/java/com/icegreen/greenmail/util/GreenMailUtil.java#L391-L405
eserating/siren4j
src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java
ReflectingConverter.resolveUri
private String resolveUri(String rawUri, EntityContext context, boolean handleURIOverride) throws Siren4JException { """ Resolves the raw uri by replacing field tokens with the actual data. @param rawUri assumed not <code>null</code> or . @param context @return uri with tokens resolved. @throws Siren4JException """ String resolvedUri = rawUri; String baseUri = null; boolean fullyQualified = false; if (context.getCurrentObject() instanceof Resource) { Resource resource = (Resource) context.getCurrentObject(); baseUri = resource.getBaseUri(); fullyQualified = resource.isFullyQualifiedLinks() == null ? false : resource.isFullyQualifiedLinks(); String override = resource.getOverrideUri(); if (handleURIOverride && StringUtils.isNotBlank(override)) { resolvedUri = override; } } resolvedUri = handleTokenReplacement(resolvedUri, context); if (fullyQualified && StringUtils.isNotBlank(baseUri) && !isAbsoluteUri(resolvedUri)) { StringBuffer sb = new StringBuffer(); sb.append(baseUri.endsWith("/") ? baseUri.substring(0, baseUri.length() - 1) : baseUri); sb.append(resolvedUri.startsWith("/") ? resolvedUri : "/" + resolvedUri); resolvedUri = sb.toString(); } return resolvedUri; }
java
private String resolveUri(String rawUri, EntityContext context, boolean handleURIOverride) throws Siren4JException { String resolvedUri = rawUri; String baseUri = null; boolean fullyQualified = false; if (context.getCurrentObject() instanceof Resource) { Resource resource = (Resource) context.getCurrentObject(); baseUri = resource.getBaseUri(); fullyQualified = resource.isFullyQualifiedLinks() == null ? false : resource.isFullyQualifiedLinks(); String override = resource.getOverrideUri(); if (handleURIOverride && StringUtils.isNotBlank(override)) { resolvedUri = override; } } resolvedUri = handleTokenReplacement(resolvedUri, context); if (fullyQualified && StringUtils.isNotBlank(baseUri) && !isAbsoluteUri(resolvedUri)) { StringBuffer sb = new StringBuffer(); sb.append(baseUri.endsWith("/") ? baseUri.substring(0, baseUri.length() - 1) : baseUri); sb.append(resolvedUri.startsWith("/") ? resolvedUri : "/" + resolvedUri); resolvedUri = sb.toString(); } return resolvedUri; }
[ "private", "String", "resolveUri", "(", "String", "rawUri", ",", "EntityContext", "context", ",", "boolean", "handleURIOverride", ")", "throws", "Siren4JException", "{", "String", "resolvedUri", "=", "rawUri", ";", "String", "baseUri", "=", "null", ";", "boolean", "fullyQualified", "=", "false", ";", "if", "(", "context", ".", "getCurrentObject", "(", ")", "instanceof", "Resource", ")", "{", "Resource", "resource", "=", "(", "Resource", ")", "context", ".", "getCurrentObject", "(", ")", ";", "baseUri", "=", "resource", ".", "getBaseUri", "(", ")", ";", "fullyQualified", "=", "resource", ".", "isFullyQualifiedLinks", "(", ")", "==", "null", "?", "false", ":", "resource", ".", "isFullyQualifiedLinks", "(", ")", ";", "String", "override", "=", "resource", ".", "getOverrideUri", "(", ")", ";", "if", "(", "handleURIOverride", "&&", "StringUtils", ".", "isNotBlank", "(", "override", ")", ")", "{", "resolvedUri", "=", "override", ";", "}", "}", "resolvedUri", "=", "handleTokenReplacement", "(", "resolvedUri", ",", "context", ")", ";", "if", "(", "fullyQualified", "&&", "StringUtils", ".", "isNotBlank", "(", "baseUri", ")", "&&", "!", "isAbsoluteUri", "(", "resolvedUri", ")", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "sb", ".", "append", "(", "baseUri", ".", "endsWith", "(", "\"/\"", ")", "?", "baseUri", ".", "substring", "(", "0", ",", "baseUri", ".", "length", "(", ")", "-", "1", ")", ":", "baseUri", ")", ";", "sb", ".", "append", "(", "resolvedUri", ".", "startsWith", "(", "\"/\"", ")", "?", "resolvedUri", ":", "\"/\"", "+", "resolvedUri", ")", ";", "resolvedUri", "=", "sb", ".", "toString", "(", ")", ";", "}", "return", "resolvedUri", ";", "}" ]
Resolves the raw uri by replacing field tokens with the actual data. @param rawUri assumed not <code>null</code> or . @param context @return uri with tokens resolved. @throws Siren4JException
[ "Resolves", "the", "raw", "uri", "by", "replacing", "field", "tokens", "with", "the", "actual", "data", "." ]
train
https://github.com/eserating/siren4j/blob/f12e3185076ad920352ec4f6eb2a071a3683505f/src/main/java/com/google/code/siren4j/converter/ReflectingConverter.java#L504-L527
TrueNight/Utils
utils/src/main/java/xyz/truenight/utils/Palazzo.java
Palazzo.submitSafe
public void submitSafe(Object tag, Object subTag, Runnable runnable) { """ Same as submit(String tag, String subTag, Runnable runnable) but task will NOT be added to queue IF there is same task in queue @param tag queue tag @param subTag task tag @param runnable task """ submitSafe(tag, subTag, false, runnable); }
java
public void submitSafe(Object tag, Object subTag, Runnable runnable) { submitSafe(tag, subTag, false, runnable); }
[ "public", "void", "submitSafe", "(", "Object", "tag", ",", "Object", "subTag", ",", "Runnable", "runnable", ")", "{", "submitSafe", "(", "tag", ",", "subTag", ",", "false", ",", "runnable", ")", ";", "}" ]
Same as submit(String tag, String subTag, Runnable runnable) but task will NOT be added to queue IF there is same task in queue @param tag queue tag @param subTag task tag @param runnable task
[ "Same", "as", "submit", "(", "String", "tag", "String", "subTag", "Runnable", "runnable", ")", "but", "task", "will", "NOT", "be", "added", "to", "queue", "IF", "there", "is", "same", "task", "in", "queue" ]
train
https://github.com/TrueNight/Utils/blob/78a11faa16258b09f08826797370310ab650530c/utils/src/main/java/xyz/truenight/utils/Palazzo.java#L99-L101
Alluxio/alluxio
core/common/src/main/java/alluxio/util/io/ByteIOUtils.java
ByteIOUtils.writeShort
public static void writeShort(OutputStream out, short v) throws IOException { """ Writes a specific short value (2 bytes) to the output stream. @param out output stream @param v short value to write """ out.write((byte) (0xff & (v >> 8))); out.write((byte) (0xff & v)); }
java
public static void writeShort(OutputStream out, short v) throws IOException { out.write((byte) (0xff & (v >> 8))); out.write((byte) (0xff & v)); }
[ "public", "static", "void", "writeShort", "(", "OutputStream", "out", ",", "short", "v", ")", "throws", "IOException", "{", "out", ".", "write", "(", "(", "byte", ")", "(", "0xff", "&", "(", "v", ">>", "8", ")", ")", ")", ";", "out", ".", "write", "(", "(", "byte", ")", "(", "0xff", "&", "v", ")", ")", ";", "}" ]
Writes a specific short value (2 bytes) to the output stream. @param out output stream @param v short value to write
[ "Writes", "a", "specific", "short", "value", "(", "2", "bytes", ")", "to", "the", "output", "stream", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/io/ByteIOUtils.java#L156-L159
shrinkwrap/shrinkwrap
impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarBuffer.java
TarBuffer.writeRecord
public void writeRecord(byte[] buf, int offset) throws IOException { """ Write an archive record to the archive, where the record may be inside of a larger array buffer. The buffer must be "offset plus record size" long. @param buf The buffer containing the record data to write. @param offset The offset of the record data within buf. """ if (this.debug) { System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); } if ((offset + this.recordSize) > buf.length) { throw new IOException("record has length '" + buf.length + "' with offset '" + offset + "' which is less than the record size of '" + this.recordSize + "'"); } if (this.currRecIdx >= this.recsPerBlock) { this.writeBlock(); } System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize), this.recordSize); this.currRecIdx++; }
java
public void writeRecord(byte[] buf, int offset) throws IOException { if (this.debug) { System.err.println("WriteRecord: recIdx = " + this.currRecIdx + " blkIdx = " + this.currBlkIdx); } if (this.outStream == null) { throw new IOException("writing to an input buffer"); } if ((offset + this.recordSize) > buf.length) { throw new IOException("record has length '" + buf.length + "' with offset '" + offset + "' which is less than the record size of '" + this.recordSize + "'"); } if (this.currRecIdx >= this.recsPerBlock) { this.writeBlock(); } System.arraycopy(buf, offset, this.blockBuffer, (this.currRecIdx * this.recordSize), this.recordSize); this.currRecIdx++; }
[ "public", "void", "writeRecord", "(", "byte", "[", "]", "buf", ",", "int", "offset", ")", "throws", "IOException", "{", "if", "(", "this", ".", "debug", ")", "{", "System", ".", "err", ".", "println", "(", "\"WriteRecord: recIdx = \"", "+", "this", ".", "currRecIdx", "+", "\" blkIdx = \"", "+", "this", ".", "currBlkIdx", ")", ";", "}", "if", "(", "this", ".", "outStream", "==", "null", ")", "{", "throw", "new", "IOException", "(", "\"writing to an input buffer\"", ")", ";", "}", "if", "(", "(", "offset", "+", "this", ".", "recordSize", ")", ">", "buf", ".", "length", ")", "{", "throw", "new", "IOException", "(", "\"record has length '\"", "+", "buf", ".", "length", "+", "\"' with offset '\"", "+", "offset", "+", "\"' which is less than the record size of '\"", "+", "this", ".", "recordSize", "+", "\"'\"", ")", ";", "}", "if", "(", "this", ".", "currRecIdx", ">=", "this", ".", "recsPerBlock", ")", "{", "this", ".", "writeBlock", "(", ")", ";", "}", "System", ".", "arraycopy", "(", "buf", ",", "offset", ",", "this", ".", "blockBuffer", ",", "(", "this", ".", "currRecIdx", "*", "this", ".", "recordSize", ")", ",", "this", ".", "recordSize", ")", ";", "this", ".", "currRecIdx", "++", ";", "}" ]
Write an archive record to the archive, where the record may be inside of a larger array buffer. The buffer must be "offset plus record size" long. @param buf The buffer containing the record data to write. @param offset The offset of the record data within buf.
[ "Write", "an", "archive", "record", "to", "the", "archive", "where", "the", "record", "may", "be", "inside", "of", "a", "larger", "array", "buffer", ".", "The", "buffer", "must", "be", "offset", "plus", "record", "size", "long", "." ]
train
https://github.com/shrinkwrap/shrinkwrap/blob/3f8a1a6d344651428c709a63ebb52d35343c5387/impl-base/src/main/java/org/jboss/shrinkwrap/impl/base/io/tar/TarBuffer.java#L302-L323
lightblueseas/swing-components
src/main/java/de/alpharogroup/layout/LayoutExtensions.java
LayoutExtensions.addComponent
public static void addComponent(final GridBagLayout gbl, final GridBagConstraints gbc, final int gridx, final int gridy, final Component component, final Container panelToAdd) { """ Adds the component. @param gbl the gbl @param gbc the gbc @param gridx the gridx @param gridy the gridy @param component the component @param panelToAdd the panel to add """ gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(5, 5, 5, 5); gbc.gridx = gridx; gbc.gridy = gridy; gbl.setConstraints(component, gbc); panelToAdd.add(component); }
java
public static void addComponent(final GridBagLayout gbl, final GridBagConstraints gbc, final int gridx, final int gridy, final Component component, final Container panelToAdd) { gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(5, 5, 5, 5); gbc.gridx = gridx; gbc.gridy = gridy; gbl.setConstraints(component, gbc); panelToAdd.add(component); }
[ "public", "static", "void", "addComponent", "(", "final", "GridBagLayout", "gbl", ",", "final", "GridBagConstraints", "gbc", ",", "final", "int", "gridx", ",", "final", "int", "gridy", ",", "final", "Component", "component", ",", "final", "Container", "panelToAdd", ")", "{", "gbc", ".", "anchor", "=", "GridBagConstraints", ".", "CENTER", ";", "gbc", ".", "fill", "=", "GridBagConstraints", ".", "BOTH", ";", "gbc", ".", "insets", "=", "new", "Insets", "(", "5", ",", "5", ",", "5", ",", "5", ")", ";", "gbc", ".", "gridx", "=", "gridx", ";", "gbc", ".", "gridy", "=", "gridy", ";", "gbl", ".", "setConstraints", "(", "component", ",", "gbc", ")", ";", "panelToAdd", ".", "add", "(", "component", ")", ";", "}" ]
Adds the component. @param gbl the gbl @param gbc the gbc @param gridx the gridx @param gridy the gridy @param component the component @param panelToAdd the panel to add
[ "Adds", "the", "component", "." ]
train
https://github.com/lightblueseas/swing-components/blob/4045e85cabd8f0ce985cbfff134c3c9873930c79/src/main/java/de/alpharogroup/layout/LayoutExtensions.java#L91-L101
openbase/jul
visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java
SVGIcon.setForegroundIcon
public void setForegroundIcon(final PROVIDER iconProvider, final Color color) { """ Changes the foregroundIcon icon. <p> Note: previous color setup and animations are reset as well. @param iconProvider the icon which should be set as the new icon. @param color the color of the new icon. """ // copy old images to replace later. final Shape oldForegroundIcon = foregroundIcon; final Shape oldForegroundFadeIcon = foregroundFadeIcon; // create new images. this.foregroundIcon = createIcon(iconProvider, Layer.FOREGROUND); this.foregroundFadeIcon = createColorFadeIcon(iconProvider, Layer.FOREGROUND); // setup icon color if (color != null) { setForegroundIconColor(color); } // replace old icons with new ones. getChildren().replaceAll((node) -> { if (node.equals(oldForegroundIcon)) { return foregroundIcon; } else if (node.equals(oldForegroundFadeIcon)) { return foregroundFadeIcon; } else { return node; } }
java
public void setForegroundIcon(final PROVIDER iconProvider, final Color color) { // copy old images to replace later. final Shape oldForegroundIcon = foregroundIcon; final Shape oldForegroundFadeIcon = foregroundFadeIcon; // create new images. this.foregroundIcon = createIcon(iconProvider, Layer.FOREGROUND); this.foregroundFadeIcon = createColorFadeIcon(iconProvider, Layer.FOREGROUND); // setup icon color if (color != null) { setForegroundIconColor(color); } // replace old icons with new ones. getChildren().replaceAll((node) -> { if (node.equals(oldForegroundIcon)) { return foregroundIcon; } else if (node.equals(oldForegroundFadeIcon)) { return foregroundFadeIcon; } else { return node; } }
[ "public", "void", "setForegroundIcon", "(", "final", "PROVIDER", "iconProvider", ",", "final", "Color", "color", ")", "{", "// copy old images to replace later.", "final", "Shape", "oldForegroundIcon", "=", "foregroundIcon", ";", "final", "Shape", "oldForegroundFadeIcon", "=", "foregroundFadeIcon", ";", "// create new images.", "this", ".", "foregroundIcon", "=", "createIcon", "(", "iconProvider", ",", "Layer", ".", "FOREGROUND", ")", ";", "this", ".", "foregroundFadeIcon", "=", "createColorFadeIcon", "(", "iconProvider", ",", "Layer", ".", "FOREGROUND", ")", ";", "// setup icon color", "if", "(", "color", "!=", "null", ")", "{", "setForegroundIconColor", "(", "color", ")", ";", "}", "// replace old icons with new ones.", "getChildren", "(", ")", ".", "replaceAll", "(", "(", "node", ")", "-", ">", "{", "if", "(", "node", ".", "equals", "(", "oldForegroundIcon", ")", ")", "{", "return", "foregroundIcon", ";", "}", "else", "if", "", "(", "node", ".", "equals", "(", "oldForegroundFadeIcon", ")", ")", "", "{", "return", "foregroundFadeIcon", ";", "}", "else", "", "{", "return", "node", ";", "}", "}" ]
Changes the foregroundIcon icon. <p> Note: previous color setup and animations are reset as well. @param iconProvider the icon which should be set as the new icon. @param color the color of the new icon.
[ "Changes", "the", "foregroundIcon", "icon", ".", "<p", ">", "Note", ":", "previous", "color", "setup", "and", "animations", "are", "reset", "as", "well", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/visual/javafx/src/main/java/org/openbase/jul/visual/javafx/geometry/svg/SVGIcon.java#L559-L582
revapi/revapi
revapi-java-spi/src/main/java/org/revapi/java/spi/CheckBase.java
CheckBase.isBothAccessible
public boolean isBothAccessible(@Nullable JavaModelElement a, @Nullable JavaModelElement b) { """ Checks whether both provided elements are public or protected. If one at least one of them is null, the method returns false, because the accessibility cannot be truthfully detected in that case. @param a first element @param b second element @return true if both elements are not null and accessible (i.e. public or protected) """ if (a == null || b == null) { return false; } return isAccessible(a) && isAccessible(b); }
java
public boolean isBothAccessible(@Nullable JavaModelElement a, @Nullable JavaModelElement b) { if (a == null || b == null) { return false; } return isAccessible(a) && isAccessible(b); }
[ "public", "boolean", "isBothAccessible", "(", "@", "Nullable", "JavaModelElement", "a", ",", "@", "Nullable", "JavaModelElement", "b", ")", "{", "if", "(", "a", "==", "null", "||", "b", "==", "null", ")", "{", "return", "false", ";", "}", "return", "isAccessible", "(", "a", ")", "&&", "isAccessible", "(", "b", ")", ";", "}" ]
Checks whether both provided elements are public or protected. If one at least one of them is null, the method returns false, because the accessibility cannot be truthfully detected in that case. @param a first element @param b second element @return true if both elements are not null and accessible (i.e. public or protected)
[ "Checks", "whether", "both", "provided", "elements", "are", "public", "or", "protected", ".", "If", "one", "at", "least", "one", "of", "them", "is", "null", "the", "method", "returns", "false", "because", "the", "accessibility", "cannot", "be", "truthfully", "detected", "in", "that", "case", "." ]
train
https://github.com/revapi/revapi/blob/e070b136d977441ab96fdce067a13e7e0423295b/revapi-java-spi/src/main/java/org/revapi/java/spi/CheckBase.java#L83-L89
lessthanoptimal/ejml
main/ejml-core/src/org/ejml/ops/ComplexMath_F64.java
ComplexMath_F64.plus
public static void plus(Complex_F64 a , Complex_F64 b , Complex_F64 result ) { """ <p> Addition: result = a + b </p> @param a Complex number. Not modified. @param b Complex number. Not modified. @param result Storage for output """ result.real = a.real + b.real; result.imaginary = a.imaginary + b.imaginary; }
java
public static void plus(Complex_F64 a , Complex_F64 b , Complex_F64 result ) { result.real = a.real + b.real; result.imaginary = a.imaginary + b.imaginary; }
[ "public", "static", "void", "plus", "(", "Complex_F64", "a", ",", "Complex_F64", "b", ",", "Complex_F64", "result", ")", "{", "result", ".", "real", "=", "a", ".", "real", "+", "b", ".", "real", ";", "result", ".", "imaginary", "=", "a", ".", "imaginary", "+", "b", ".", "imaginary", ";", "}" ]
<p> Addition: result = a + b </p> @param a Complex number. Not modified. @param b Complex number. Not modified. @param result Storage for output
[ "<p", ">", "Addition", ":", "result", "=", "a", "+", "b", "<", "/", "p", ">" ]
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-core/src/org/ejml/ops/ComplexMath_F64.java#L52-L55
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java
MappedParametrizedObjectEntry.getParameterBoolean
public Boolean getParameterBoolean(String name, Boolean defaultValue) { """ Parse named parameter as Boolean. @param name parameter name @param defaultValue default value @return boolean value """ String value = getParameterValue(name, null); if (value != null) { return new Boolean(value); } return defaultValue; }
java
public Boolean getParameterBoolean(String name, Boolean defaultValue) { String value = getParameterValue(name, null); if (value != null) { return new Boolean(value); } return defaultValue; }
[ "public", "Boolean", "getParameterBoolean", "(", "String", "name", ",", "Boolean", "defaultValue", ")", "{", "String", "value", "=", "getParameterValue", "(", "name", ",", "null", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "new", "Boolean", "(", "value", ")", ";", "}", "return", "defaultValue", ";", "}" ]
Parse named parameter as Boolean. @param name parameter name @param defaultValue default value @return boolean value
[ "Parse", "named", "parameter", "as", "Boolean", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/config/MappedParametrizedObjectEntry.java#L349-L358
alkacon/opencms-core
src/org/opencms/ui/CmsVaadinUtils.java
CmsVaadinUtils.getOUComboBox
public static ComboBox getOUComboBox(CmsObject cms, String baseOu, Log log) { """ Creates the ComboBox for OU selection.<p> @param cms CmsObject @param baseOu OU @param log Logger object @return ComboBox """ return getOUComboBox(cms, baseOu, log, true); }
java
public static ComboBox getOUComboBox(CmsObject cms, String baseOu, Log log) { return getOUComboBox(cms, baseOu, log, true); }
[ "public", "static", "ComboBox", "getOUComboBox", "(", "CmsObject", "cms", ",", "String", "baseOu", ",", "Log", "log", ")", "{", "return", "getOUComboBox", "(", "cms", ",", "baseOu", ",", "log", ",", "true", ")", ";", "}" ]
Creates the ComboBox for OU selection.<p> @param cms CmsObject @param baseOu OU @param log Logger object @return ComboBox
[ "Creates", "the", "ComboBox", "for", "OU", "selection", ".", "<p", ">", "@param", "cms", "CmsObject", "@param", "baseOu", "OU", "@param", "log", "Logger", "object" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/CmsVaadinUtils.java#L657-L660
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/query/Criteria.java
Criteria.addNotIn
public void addNotIn(String attribute, Collection values) { """ Adds NOT IN criteria, customer_id not in(1,10,33,44) large values are split into multiple InCriteria NOT IN (1,10) AND NOT IN(33, 44) @param attribute The field name to be used @param values The value Collection """ List list = splitInCriteria(attribute, values, true, IN_LIMIT); InCriteria inCrit; for (int index = 0; index < list.size(); index++) { inCrit = (InCriteria) list.get(index); addSelectionCriteria(inCrit); } }
java
public void addNotIn(String attribute, Collection values) { List list = splitInCriteria(attribute, values, true, IN_LIMIT); InCriteria inCrit; for (int index = 0; index < list.size(); index++) { inCrit = (InCriteria) list.get(index); addSelectionCriteria(inCrit); } }
[ "public", "void", "addNotIn", "(", "String", "attribute", ",", "Collection", "values", ")", "{", "List", "list", "=", "splitInCriteria", "(", "attribute", ",", "values", ",", "true", ",", "IN_LIMIT", ")", ";", "InCriteria", "inCrit", ";", "for", "(", "int", "index", "=", "0", ";", "index", "<", "list", ".", "size", "(", ")", ";", "index", "++", ")", "{", "inCrit", "=", "(", "InCriteria", ")", "list", ".", "get", "(", "index", ")", ";", "addSelectionCriteria", "(", "inCrit", ")", ";", "}", "}" ]
Adds NOT IN criteria, customer_id not in(1,10,33,44) large values are split into multiple InCriteria NOT IN (1,10) AND NOT IN(33, 44) @param attribute The field name to be used @param values The value Collection
[ "Adds", "NOT", "IN", "criteria", "customer_id", "not", "in", "(", "1", "10", "33", "44", ")", "large", "values", "are", "split", "into", "multiple", "InCriteria", "NOT", "IN", "(", "1", "10", ")", "AND", "NOT", "IN", "(", "33", "44", ")" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/query/Criteria.java#L825-L834
ThreeTen/threeten-extra
src/main/java/org/threeten/extra/chrono/Symmetry454Date.java
Symmetry454Date.resolvePreviousValid
private static Symmetry454Date resolvePreviousValid(int prolepticYear, int month, int day) { """ Consistency check for dates manipulations after calls to {@link #plus(long, TemporalUnit)}, {@link #minus(long, TemporalUnit)}, {@link #until(AbstractDate, TemporalUnit)} or {@link #with(TemporalField, long)}. @param prolepticYear the Symmetry454 proleptic-year @param month the Symmetry454 month, from 1 to 12 @return the resolved date """ int monthR = Math.min(month, MONTHS_IN_YEAR); int dayR = Math.min(day, (monthR % 3 == 2) || (monthR == 12 && INSTANCE.isLeapYear(prolepticYear)) ? DAYS_IN_MONTH_LONG : DAYS_IN_MONTH); return create(prolepticYear, monthR, dayR); }
java
private static Symmetry454Date resolvePreviousValid(int prolepticYear, int month, int day) { int monthR = Math.min(month, MONTHS_IN_YEAR); int dayR = Math.min(day, (monthR % 3 == 2) || (monthR == 12 && INSTANCE.isLeapYear(prolepticYear)) ? DAYS_IN_MONTH_LONG : DAYS_IN_MONTH); return create(prolepticYear, monthR, dayR); }
[ "private", "static", "Symmetry454Date", "resolvePreviousValid", "(", "int", "prolepticYear", ",", "int", "month", ",", "int", "day", ")", "{", "int", "monthR", "=", "Math", ".", "min", "(", "month", ",", "MONTHS_IN_YEAR", ")", ";", "int", "dayR", "=", "Math", ".", "min", "(", "day", ",", "(", "monthR", "%", "3", "==", "2", ")", "||", "(", "monthR", "==", "12", "&&", "INSTANCE", ".", "isLeapYear", "(", "prolepticYear", ")", ")", "?", "DAYS_IN_MONTH_LONG", ":", "DAYS_IN_MONTH", ")", ";", "return", "create", "(", "prolepticYear", ",", "monthR", ",", "dayR", ")", ";", "}" ]
Consistency check for dates manipulations after calls to {@link #plus(long, TemporalUnit)}, {@link #minus(long, TemporalUnit)}, {@link #until(AbstractDate, TemporalUnit)} or {@link #with(TemporalField, long)}. @param prolepticYear the Symmetry454 proleptic-year @param month the Symmetry454 month, from 1 to 12 @return the resolved date
[ "Consistency", "check", "for", "dates", "manipulations", "after", "calls", "to", "{", "@link", "#plus", "(", "long", "TemporalUnit", ")", "}", "{", "@link", "#minus", "(", "long", "TemporalUnit", ")", "}", "{", "@link", "#until", "(", "AbstractDate", "TemporalUnit", ")", "}", "or", "{", "@link", "#with", "(", "TemporalField", "long", ")", "}", "." ]
train
https://github.com/ThreeTen/threeten-extra/blob/e94ecd3592ef70e54d6eea21095239ea9ffbab78/src/main/java/org/threeten/extra/chrono/Symmetry454Date.java#L296-L302
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java
InterfaceEndpointsInner.getByResourceGroup
public InterfaceEndpointInner getByResourceGroup(String resourceGroupName, String interfaceEndpointName) { """ Gets the specified interface endpoint by resource group. @param resourceGroupName The name of the resource group. @param interfaceEndpointName The name of the interface endpoint. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the InterfaceEndpointInner object if successful. """ return getByResourceGroupWithServiceResponseAsync(resourceGroupName, interfaceEndpointName).toBlocking().single().body(); }
java
public InterfaceEndpointInner getByResourceGroup(String resourceGroupName, String interfaceEndpointName) { return getByResourceGroupWithServiceResponseAsync(resourceGroupName, interfaceEndpointName).toBlocking().single().body(); }
[ "public", "InterfaceEndpointInner", "getByResourceGroup", "(", "String", "resourceGroupName", ",", "String", "interfaceEndpointName", ")", "{", "return", "getByResourceGroupWithServiceResponseAsync", "(", "resourceGroupName", ",", "interfaceEndpointName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Gets the specified interface endpoint by resource group. @param resourceGroupName The name of the resource group. @param interfaceEndpointName The name of the interface endpoint. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the InterfaceEndpointInner object if successful.
[ "Gets", "the", "specified", "interface", "endpoint", "by", "resource", "group", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/InterfaceEndpointsInner.java#L266-L268
cloudinary/cloudinary_java
cloudinary-core/src/main/java/com/cloudinary/Api.java
Api.updateResourcesAccessModeByIds
public ApiResponse updateResourcesAccessModeByIds(String accessMode, Iterable<String> publicIds, Map options) throws Exception { """ Update access mode of one or more resources by publicIds @param accessMode The new access mode, "public" or "authenticated" @param publicIds A list of public ids of resources to be updated @param options additional options <ul> <li>resource_type - (default "image") - the type of resources to modify</li> <li>max_results - optional - the maximum resources to process in a single invocation</li> <li>next_cursor - optional - provided by a previous call to the method</li> </ul> @return a map of the returned values <ul> <li>updated - an array of resources</li> <li>next_cursor - optional - provided if more resources can be processed</li> </ul> @throws ApiException an API exception """ return updateResourcesAccessMode(accessMode, "public_ids", publicIds, options); }
java
public ApiResponse updateResourcesAccessModeByIds(String accessMode, Iterable<String> publicIds, Map options) throws Exception { return updateResourcesAccessMode(accessMode, "public_ids", publicIds, options); }
[ "public", "ApiResponse", "updateResourcesAccessModeByIds", "(", "String", "accessMode", ",", "Iterable", "<", "String", ">", "publicIds", ",", "Map", "options", ")", "throws", "Exception", "{", "return", "updateResourcesAccessMode", "(", "accessMode", ",", "\"public_ids\"", ",", "publicIds", ",", "options", ")", ";", "}" ]
Update access mode of one or more resources by publicIds @param accessMode The new access mode, "public" or "authenticated" @param publicIds A list of public ids of resources to be updated @param options additional options <ul> <li>resource_type - (default "image") - the type of resources to modify</li> <li>max_results - optional - the maximum resources to process in a single invocation</li> <li>next_cursor - optional - provided by a previous call to the method</li> </ul> @return a map of the returned values <ul> <li>updated - an array of resources</li> <li>next_cursor - optional - provided if more resources can be processed</li> </ul> @throws ApiException an API exception
[ "Update", "access", "mode", "of", "one", "or", "more", "resources", "by", "publicIds" ]
train
https://github.com/cloudinary/cloudinary_java/blob/58ee1823180da2dea6a2eb7e5cf00d5a760f8aef/cloudinary-core/src/main/java/com/cloudinary/Api.java#L540-L542
JoeKerouac/utils
src/main/java/com/joe/utils/serialize/json/JsonParser.java
JsonParser.readAsObject
@SuppressWarnings("unchecked") public <T> T readAsObject(String content, Class<T> type) { """ 解析json @param content json字符串 @param type json解析后对应的实体类型 @param <T> 实体类型的实际类型 @return 解析失败将返回null """ Assert.notNull(type); try { if (StringUtils.isEmpty(content)) { log.debug("content为空,返回null", content, type); return null; } else if (type.equals(String.class)) { return (T) content; } return MAPPER.readValue(content, type); } catch (Exception e) { log.error("json解析失败,失败原因:", e); return null; } }
java
@SuppressWarnings("unchecked") public <T> T readAsObject(String content, Class<T> type) { Assert.notNull(type); try { if (StringUtils.isEmpty(content)) { log.debug("content为空,返回null", content, type); return null; } else if (type.equals(String.class)) { return (T) content; } return MAPPER.readValue(content, type); } catch (Exception e) { log.error("json解析失败,失败原因:", e); return null; } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "<", "T", ">", "T", "readAsObject", "(", "String", "content", ",", "Class", "<", "T", ">", "type", ")", "{", "Assert", ".", "notNull", "(", "type", ")", ";", "try", "{", "if", "(", "StringUtils", ".", "isEmpty", "(", "content", ")", ")", "{", "log", ".", "debug", "(", "\"content为空,返回null\", content,", " ", "ype);", "", "", "", "", "return", "null", ";", "}", "else", "if", "(", "type", ".", "equals", "(", "String", ".", "class", ")", ")", "{", "return", "(", "T", ")", "content", ";", "}", "return", "MAPPER", ".", "readValue", "(", "content", ",", "type", ")", ";", "}", "catch", "(", "Exception", "e", ")", "{", "log", ".", "error", "(", "\"json解析失败,失败原因:\", e);", "", "", "", "", "return", "null", ";", "}", "}" ]
解析json @param content json字符串 @param type json解析后对应的实体类型 @param <T> 实体类型的实际类型 @return 解析失败将返回null
[ "解析json" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/serialize/json/JsonParser.java#L114-L129
QSFT/Doradus
doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java
SpiderTransaction.addAllObjectsColumn
public void addAllObjectsColumn(TableDefinition tableDef, String objID, int shardNo) { """ Add an "all objects" column for an object in the given table with the given ID. The "all objects" lives in the Terms store and its row key is "_" for objects residing in shard 0, "{shard number}/_" for objects residing in other shards. The column added is named with the object's ID but has no value. @param tableDef {@link TableDefinition} of table that owns object. @param objID ID of object being added. @param shardNo Shard number if owing table is sharded. """ String rowKey = ALL_OBJECTS_ROW_KEY; if (shardNo > 0) { rowKey = shardNo + "/" + ALL_OBJECTS_ROW_KEY; } addColumn(SpiderService.termsStoreName(tableDef), rowKey, objID); }
java
public void addAllObjectsColumn(TableDefinition tableDef, String objID, int shardNo) { String rowKey = ALL_OBJECTS_ROW_KEY; if (shardNo > 0) { rowKey = shardNo + "/" + ALL_OBJECTS_ROW_KEY; } addColumn(SpiderService.termsStoreName(tableDef), rowKey, objID); }
[ "public", "void", "addAllObjectsColumn", "(", "TableDefinition", "tableDef", ",", "String", "objID", ",", "int", "shardNo", ")", "{", "String", "rowKey", "=", "ALL_OBJECTS_ROW_KEY", ";", "if", "(", "shardNo", ">", "0", ")", "{", "rowKey", "=", "shardNo", "+", "\"/\"", "+", "ALL_OBJECTS_ROW_KEY", ";", "}", "addColumn", "(", "SpiderService", ".", "termsStoreName", "(", "tableDef", ")", ",", "rowKey", ",", "objID", ")", ";", "}" ]
Add an "all objects" column for an object in the given table with the given ID. The "all objects" lives in the Terms store and its row key is "_" for objects residing in shard 0, "{shard number}/_" for objects residing in other shards. The column added is named with the object's ID but has no value. @param tableDef {@link TableDefinition} of table that owns object. @param objID ID of object being added. @param shardNo Shard number if owing table is sharded.
[ "Add", "an", "all", "objects", "column", "for", "an", "object", "in", "the", "given", "table", "with", "the", "given", "ID", ".", "The", "all", "objects", "lives", "in", "the", "Terms", "store", "and", "its", "row", "key", "is", "_", "for", "objects", "residing", "in", "shard", "0", "{", "shard", "number", "}", "/", "_", "for", "objects", "residing", "in", "other", "shards", ".", "The", "column", "added", "is", "named", "with", "the", "object", "s", "ID", "but", "has", "no", "value", "." ]
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-server/src/main/java/com/dell/doradus/service/spider/SpiderTransaction.java#L207-L213
OpenLiberty/open-liberty
dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/FormLoginAuthenticator.java
FormLoginAuthenticator.handleRedirect
private AuthenticationResult handleRedirect(HttpServletRequest req, HttpServletResponse res, WebRequest webRequest) { """ This method save post parameters in the cookie or session and redirect to a login page. @param req @param res @param loginURL @return authenticationResult """ AuthenticationResult authResult; String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "form login URL: " + loginURL); } authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL); if (allowToAddCookieToResponse(webAppSecurityConfig, req)) { postParameterHelper.save(req, res, authResult); ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler(); // referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req)); Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req); authResult.setCookie(c); } return authResult; }
java
private AuthenticationResult handleRedirect(HttpServletRequest req, HttpServletResponse res, WebRequest webRequest) { AuthenticationResult authResult; String loginURL = getFormLoginURL(req, webRequest, webAppSecurityConfig); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "form login URL: " + loginURL); } authResult = new AuthenticationResult(AuthResult.REDIRECT, loginURL); if (allowToAddCookieToResponse(webAppSecurityConfig, req)) { postParameterHelper.save(req, res, authResult); ReferrerURLCookieHandler referrerURLHandler = webAppSecurityConfig.createReferrerURLCookieHandler(); // referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req)); Cookie c = referrerURLHandler.createReferrerURLCookie(ReferrerURLCookieHandler.REFERRER_URL_COOKIENAME, getReqURL(req), req); authResult.setCookie(c); } return authResult; }
[ "private", "AuthenticationResult", "handleRedirect", "(", "HttpServletRequest", "req", ",", "HttpServletResponse", "res", ",", "WebRequest", "webRequest", ")", "{", "AuthenticationResult", "authResult", ";", "String", "loginURL", "=", "getFormLoginURL", "(", "req", ",", "webRequest", ",", "webAppSecurityConfig", ")", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "Tr", ".", "debug", "(", "tc", ",", "\"form login URL: \"", "+", "loginURL", ")", ";", "}", "authResult", "=", "new", "AuthenticationResult", "(", "AuthResult", ".", "REDIRECT", ",", "loginURL", ")", ";", "if", "(", "allowToAddCookieToResponse", "(", "webAppSecurityConfig", ",", "req", ")", ")", "{", "postParameterHelper", ".", "save", "(", "req", ",", "res", ",", "authResult", ")", ";", "ReferrerURLCookieHandler", "referrerURLHandler", "=", "webAppSecurityConfig", ".", "createReferrerURLCookieHandler", "(", ")", ";", "// referrerURLHandler.setReferrerURLCookie(authResult, getReqURL(req));", "Cookie", "c", "=", "referrerURLHandler", ".", "createReferrerURLCookie", "(", "ReferrerURLCookieHandler", ".", "REFERRER_URL_COOKIENAME", ",", "getReqURL", "(", "req", ")", ",", "req", ")", ";", "authResult", ".", "setCookie", "(", "c", ")", ";", "}", "return", "authResult", ";", "}" ]
This method save post parameters in the cookie or session and redirect to a login page. @param req @param res @param loginURL @return authenticationResult
[ "This", "method", "save", "post", "parameters", "in", "the", "cookie", "or", "session", "and", "redirect", "to", "a", "login", "page", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/internal/FormLoginAuthenticator.java#L126-L147
kaazing/gateway
mina.core/core/src/main/java/org/apache/mina/handler/demux/DemuxingIoHandler.java
DemuxingIoHandler.messageReceived
@Override public void messageReceived(IoSession session, Object message) throws Exception { """ Forwards the received events into the appropriate {@link MessageHandler} which is registered by {@link #addReceivedMessageHandler(Class, MessageHandler)}. <b>Warning !</b> If you are to overload this method, be aware that you _must_ call the messageHandler in your own method, otherwise it won't be called. """ MessageHandler<Object> handler = findReceivedMessageHandler(message.getClass()); if (handler != null) { handler.handleMessage(session, message); } else { throw new UnknownMessageTypeException( "No message handler found for message type: " + message.getClass().getSimpleName()); } }
java
@Override public void messageReceived(IoSession session, Object message) throws Exception { MessageHandler<Object> handler = findReceivedMessageHandler(message.getClass()); if (handler != null) { handler.handleMessage(session, message); } else { throw new UnknownMessageTypeException( "No message handler found for message type: " + message.getClass().getSimpleName()); } }
[ "@", "Override", "public", "void", "messageReceived", "(", "IoSession", "session", ",", "Object", "message", ")", "throws", "Exception", "{", "MessageHandler", "<", "Object", ">", "handler", "=", "findReceivedMessageHandler", "(", "message", ".", "getClass", "(", ")", ")", ";", "if", "(", "handler", "!=", "null", ")", "{", "handler", ".", "handleMessage", "(", "session", ",", "message", ")", ";", "}", "else", "{", "throw", "new", "UnknownMessageTypeException", "(", "\"No message handler found for message type: \"", "+", "message", ".", "getClass", "(", ")", ".", "getSimpleName", "(", ")", ")", ";", "}", "}" ]
Forwards the received events into the appropriate {@link MessageHandler} which is registered by {@link #addReceivedMessageHandler(Class, MessageHandler)}. <b>Warning !</b> If you are to overload this method, be aware that you _must_ call the messageHandler in your own method, otherwise it won't be called.
[ "Forwards", "the", "received", "events", "into", "the", "appropriate", "{", "@link", "MessageHandler", "}", "which", "is", "registered", "by", "{", "@link", "#addReceivedMessageHandler", "(", "Class", "MessageHandler", ")", "}", "." ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/handler/demux/DemuxingIoHandler.java#L223-L234
Samsung/GearVRf
GVRf/Extensions/script/src/main/java/org/gearvrf/script/GVRScriptFile.java
GVRScriptFile.invokeFunction
@Override public boolean invokeFunction(String funcName, Object[] params) { """ Invokes a function defined in the script. @param funcName The function name. @param params The parameter array. @return A boolean value representing whether the function is executed correctly. If the function cannot be found, or parameters don't match, {@code false} is returned. """ // Run script if it is dirty. This makes sure the script is run // on the same thread as the caller (suppose the caller is always // calling from the same thread). checkDirty(); // Skip bad functions if (isBadFunction(funcName)) { return false; } String statement = getInvokeStatementCached(funcName, params); synchronized (mEngineLock) { localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (localBindings == null) { localBindings = mLocalEngine.createBindings(); mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE); } } fillBindings(localBindings, params); try { mLocalEngine.eval(statement); } catch (ScriptException e) { // The function is either undefined or throws, avoid invoking it later addBadFunction(funcName); mLastError = e.getMessage(); return false; } finally { removeBindings(localBindings, params); } return true; }
java
@Override public boolean invokeFunction(String funcName, Object[] params) { // Run script if it is dirty. This makes sure the script is run // on the same thread as the caller (suppose the caller is always // calling from the same thread). checkDirty(); // Skip bad functions if (isBadFunction(funcName)) { return false; } String statement = getInvokeStatementCached(funcName, params); synchronized (mEngineLock) { localBindings = mLocalEngine.getBindings(ScriptContext.ENGINE_SCOPE); if (localBindings == null) { localBindings = mLocalEngine.createBindings(); mLocalEngine.setBindings(localBindings, ScriptContext.ENGINE_SCOPE); } } fillBindings(localBindings, params); try { mLocalEngine.eval(statement); } catch (ScriptException e) { // The function is either undefined or throws, avoid invoking it later addBadFunction(funcName); mLastError = e.getMessage(); return false; } finally { removeBindings(localBindings, params); } return true; }
[ "@", "Override", "public", "boolean", "invokeFunction", "(", "String", "funcName", ",", "Object", "[", "]", "params", ")", "{", "// Run script if it is dirty. This makes sure the script is run", "// on the same thread as the caller (suppose the caller is always", "// calling from the same thread).", "checkDirty", "(", ")", ";", "// Skip bad functions", "if", "(", "isBadFunction", "(", "funcName", ")", ")", "{", "return", "false", ";", "}", "String", "statement", "=", "getInvokeStatementCached", "(", "funcName", ",", "params", ")", ";", "synchronized", "(", "mEngineLock", ")", "{", "localBindings", "=", "mLocalEngine", ".", "getBindings", "(", "ScriptContext", ".", "ENGINE_SCOPE", ")", ";", "if", "(", "localBindings", "==", "null", ")", "{", "localBindings", "=", "mLocalEngine", ".", "createBindings", "(", ")", ";", "mLocalEngine", ".", "setBindings", "(", "localBindings", ",", "ScriptContext", ".", "ENGINE_SCOPE", ")", ";", "}", "}", "fillBindings", "(", "localBindings", ",", "params", ")", ";", "try", "{", "mLocalEngine", ".", "eval", "(", "statement", ")", ";", "}", "catch", "(", "ScriptException", "e", ")", "{", "// The function is either undefined or throws, avoid invoking it later", "addBadFunction", "(", "funcName", ")", ";", "mLastError", "=", "e", ".", "getMessage", "(", ")", ";", "return", "false", ";", "}", "finally", "{", "removeBindings", "(", "localBindings", ",", "params", ")", ";", "}", "return", "true", ";", "}" ]
Invokes a function defined in the script. @param funcName The function name. @param params The parameter array. @return A boolean value representing whether the function is executed correctly. If the function cannot be found, or parameters don't match, {@code false} is returned.
[ "Invokes", "a", "function", "defined", "in", "the", "script", "." ]
train
https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Extensions/script/src/main/java/org/gearvrf/script/GVRScriptFile.java#L172-L208
Javen205/IJPay
src/main/java/com/jpay/unionpay/AcpService.java
AcpService.validate
public static boolean validate(Map<String, String> rspData, String encoding) { """ 验证签名(SHA-1摘要算法)<br> @param resData 返回报文数据<br> @param encoding 上送请求报文域encoding字段的值<br> @return true 通过 false 未通过<br> """ return SDKUtil.validate(rspData, encoding); }
java
public static boolean validate(Map<String, String> rspData, String encoding) { return SDKUtil.validate(rspData, encoding); }
[ "public", "static", "boolean", "validate", "(", "Map", "<", "String", ",", "String", ">", "rspData", ",", "String", "encoding", ")", "{", "return", "SDKUtil", ".", "validate", "(", "rspData", ",", "encoding", ")", ";", "}" ]
验证签名(SHA-1摘要算法)<br> @param resData 返回报文数据<br> @param encoding 上送请求报文域encoding字段的值<br> @return true 通过 false 未通过<br>
[ "验证签名", "(", "SHA", "-", "1摘要算法", ")", "<br", ">" ]
train
https://github.com/Javen205/IJPay/blob/78da6be4b70675abc6a41df74817532fa257ef29/src/main/java/com/jpay/unionpay/AcpService.java#L65-L67
eclipse/xtext-extras
org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/AbstractXbaseCompiler.java
AbstractXbaseCompiler.isVariableDeclarationRequired
@Deprecated protected final boolean isVariableDeclarationRequired(XExpression expr, ITreeAppendable b) { """ whether an expression needs to be declared in a statement If an expression has side effects this method must return true for it. @param expr the checked expression @param b the appendable which represents the current compiler state @deprecated use {@link #isVariableDeclarationRequired(XExpression, ITreeAppendable, boolean)} instead. """ return isVariableDeclarationRequired(expr, b, true); }
java
@Deprecated protected final boolean isVariableDeclarationRequired(XExpression expr, ITreeAppendable b) { return isVariableDeclarationRequired(expr, b, true); }
[ "@", "Deprecated", "protected", "final", "boolean", "isVariableDeclarationRequired", "(", "XExpression", "expr", ",", "ITreeAppendable", "b", ")", "{", "return", "isVariableDeclarationRequired", "(", "expr", ",", "b", ",", "true", ")", ";", "}" ]
whether an expression needs to be declared in a statement If an expression has side effects this method must return true for it. @param expr the checked expression @param b the appendable which represents the current compiler state @deprecated use {@link #isVariableDeclarationRequired(XExpression, ITreeAppendable, boolean)} instead.
[ "whether", "an", "expression", "needs", "to", "be", "declared", "in", "a", "statement", "If", "an", "expression", "has", "side", "effects", "this", "method", "must", "return", "true", "for", "it", "." ]
train
https://github.com/eclipse/xtext-extras/blob/451359541295323a29f5855e633f770cec02069a/org.eclipse.xtext.xbase/src/org/eclipse/xtext/xbase/compiler/AbstractXbaseCompiler.java#L661-L664
redkale/redkale
src/org/redkale/source/EntityInfo.java
EntityInfo.getEntityValue
protected T getEntityValue(final SelectColumn sels, final ResultSet set) throws SQLException { """ 将一行的ResultSet组装成一个Entity对象 @param sels 指定字段 @param set ResultSet @return Entity对象 @throws SQLException SQLException """ T obj; Attribute<T, Serializable>[] attrs = this.queryAttributes; if (this.constructorParameters == null) { obj = creator.create(); } else { Object[] cps = new Object[this.constructorParameters.length]; for (int i = 0; i < this.constructorAttributes.length; i++) { Attribute<T, Serializable> attr = this.constructorAttributes[i]; if (sels == null || sels.test(attr.field())) { cps[i] = getFieldValue(attr, set); } } obj = creator.create(cps); attrs = this.unconstructorAttributes; } for (Attribute<T, Serializable> attr : attrs) { if (sels == null || sels.test(attr.field())) { attr.set(obj, getFieldValue(attr, set)); } } return obj; }
java
protected T getEntityValue(final SelectColumn sels, final ResultSet set) throws SQLException { T obj; Attribute<T, Serializable>[] attrs = this.queryAttributes; if (this.constructorParameters == null) { obj = creator.create(); } else { Object[] cps = new Object[this.constructorParameters.length]; for (int i = 0; i < this.constructorAttributes.length; i++) { Attribute<T, Serializable> attr = this.constructorAttributes[i]; if (sels == null || sels.test(attr.field())) { cps[i] = getFieldValue(attr, set); } } obj = creator.create(cps); attrs = this.unconstructorAttributes; } for (Attribute<T, Serializable> attr : attrs) { if (sels == null || sels.test(attr.field())) { attr.set(obj, getFieldValue(attr, set)); } } return obj; }
[ "protected", "T", "getEntityValue", "(", "final", "SelectColumn", "sels", ",", "final", "ResultSet", "set", ")", "throws", "SQLException", "{", "T", "obj", ";", "Attribute", "<", "T", ",", "Serializable", ">", "[", "]", "attrs", "=", "this", ".", "queryAttributes", ";", "if", "(", "this", ".", "constructorParameters", "==", "null", ")", "{", "obj", "=", "creator", ".", "create", "(", ")", ";", "}", "else", "{", "Object", "[", "]", "cps", "=", "new", "Object", "[", "this", ".", "constructorParameters", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "constructorAttributes", ".", "length", ";", "i", "++", ")", "{", "Attribute", "<", "T", ",", "Serializable", ">", "attr", "=", "this", ".", "constructorAttributes", "[", "i", "]", ";", "if", "(", "sels", "==", "null", "||", "sels", ".", "test", "(", "attr", ".", "field", "(", ")", ")", ")", "{", "cps", "[", "i", "]", "=", "getFieldValue", "(", "attr", ",", "set", ")", ";", "}", "}", "obj", "=", "creator", ".", "create", "(", "cps", ")", ";", "attrs", "=", "this", ".", "unconstructorAttributes", ";", "}", "for", "(", "Attribute", "<", "T", ",", "Serializable", ">", "attr", ":", "attrs", ")", "{", "if", "(", "sels", "==", "null", "||", "sels", ".", "test", "(", "attr", ".", "field", "(", ")", ")", ")", "{", "attr", ".", "set", "(", "obj", ",", "getFieldValue", "(", "attr", ",", "set", ")", ")", ";", "}", "}", "return", "obj", ";", "}" ]
将一行的ResultSet组装成一个Entity对象 @param sels 指定字段 @param set ResultSet @return Entity对象 @throws SQLException SQLException
[ "将一行的ResultSet组装成一个Entity对象" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/source/EntityInfo.java#L1044-L1066
googleapis/google-cloud-java
google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/SubnetworkId.java
SubnetworkId.of
public static SubnetworkId of(String project, String region, String subnetwork) { """ Returns a subnetwork identity given project, region and subnetwork names. The subnetwork name must be 1-63 characters long and comply with RFC1035. Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. @see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a> """ return new SubnetworkId(project, region, subnetwork); }
java
public static SubnetworkId of(String project, String region, String subnetwork) { return new SubnetworkId(project, region, subnetwork); }
[ "public", "static", "SubnetworkId", "of", "(", "String", "project", ",", "String", "region", ",", "String", "subnetwork", ")", "{", "return", "new", "SubnetworkId", "(", "project", ",", "region", ",", "subnetwork", ")", ";", "}" ]
Returns a subnetwork identity given project, region and subnetwork names. The subnetwork name must be 1-63 characters long and comply with RFC1035. Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, and all following characters must be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. @see <a href="https://www.ietf.org/rfc/rfc1035.txt">RFC1035</a>
[ "Returns", "a", "subnetwork", "identity", "given", "project", "region", "and", "subnetwork", "names", ".", "The", "subnetwork", "name", "must", "be", "1", "-", "63", "characters", "long", "and", "comply", "with", "RFC1035", ".", "Specifically", "the", "name", "must", "match", "the", "regular", "expression", "{", "@code", "[", "a", "-", "z", "]", "(", "[", "-", "a", "-", "z0", "-", "9", "]", "*", "[", "a", "-", "z0", "-", "9", "]", ")", "?", "}", "which", "means", "the", "first", "character", "must", "be", "a", "lowercase", "letter", "and", "all", "following", "characters", "must", "be", "a", "dash", "lowercase", "letter", "or", "digit", "except", "the", "last", "character", "which", "cannot", "be", "a", "dash", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-compute/src/main/java/com/google/cloud/compute/deprecated/SubnetworkId.java#L153-L155
groupon/odo
proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java
PathOverrideService.setResponseEnabled
public void setResponseEnabled(int pathId, boolean enabled, String clientUUID) throws Exception { """ Sets enabled/disabled for a response @param pathId ID of path @param enabled 1 for enabled, 0 for disabled @param clientUUID client ID @throws Exception exception """ PreparedStatement statement = null; int profileId = EditService.getProfileIdFromPathID(pathId); try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE + " SET " + Constants.DB_TABLE_PATH_RESPONSE_ENABLED + "= ?" + " WHERE " + Constants.GENERIC_PROFILE_ID + "= ?" + " AND " + Constants.GENERIC_CLIENT_UUID + "= ?" + " AND " + Constants.REQUEST_RESPONSE_PATH_ID + "= ?" ); statement.setBoolean(1, enabled); statement.setInt(2, profileId); statement.setString(3, clientUUID); statement.setInt(4, pathId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
java
public void setResponseEnabled(int pathId, boolean enabled, String clientUUID) throws Exception { PreparedStatement statement = null; int profileId = EditService.getProfileIdFromPathID(pathId); try (Connection sqlConnection = sqlService.getConnection()) { statement = sqlConnection.prepareStatement( "UPDATE " + Constants.DB_TABLE_REQUEST_RESPONSE + " SET " + Constants.DB_TABLE_PATH_RESPONSE_ENABLED + "= ?" + " WHERE " + Constants.GENERIC_PROFILE_ID + "= ?" + " AND " + Constants.GENERIC_CLIENT_UUID + "= ?" + " AND " + Constants.REQUEST_RESPONSE_PATH_ID + "= ?" ); statement.setBoolean(1, enabled); statement.setInt(2, profileId); statement.setString(3, clientUUID); statement.setInt(4, pathId); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (statement != null) { statement.close(); } } catch (Exception e) { } } }
[ "public", "void", "setResponseEnabled", "(", "int", "pathId", ",", "boolean", "enabled", ",", "String", "clientUUID", ")", "throws", "Exception", "{", "PreparedStatement", "statement", "=", "null", ";", "int", "profileId", "=", "EditService", ".", "getProfileIdFromPathID", "(", "pathId", ")", ";", "try", "(", "Connection", "sqlConnection", "=", "sqlService", ".", "getConnection", "(", ")", ")", "{", "statement", "=", "sqlConnection", ".", "prepareStatement", "(", "\"UPDATE \"", "+", "Constants", ".", "DB_TABLE_REQUEST_RESPONSE", "+", "\" SET \"", "+", "Constants", ".", "DB_TABLE_PATH_RESPONSE_ENABLED", "+", "\"= ?\"", "+", "\" WHERE \"", "+", "Constants", ".", "GENERIC_PROFILE_ID", "+", "\"= ?\"", "+", "\" AND \"", "+", "Constants", ".", "GENERIC_CLIENT_UUID", "+", "\"= ?\"", "+", "\" AND \"", "+", "Constants", ".", "REQUEST_RESPONSE_PATH_ID", "+", "\"= ?\"", ")", ";", "statement", ".", "setBoolean", "(", "1", ",", "enabled", ")", ";", "statement", ".", "setInt", "(", "2", ",", "profileId", ")", ";", "statement", ".", "setString", "(", "3", ",", "clientUUID", ")", ";", "statement", ".", "setInt", "(", "4", ",", "pathId", ")", ";", "statement", ".", "executeUpdate", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "try", "{", "if", "(", "statement", "!=", "null", ")", "{", "statement", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "Exception", "e", ")", "{", "}", "}", "}" ]
Sets enabled/disabled for a response @param pathId ID of path @param enabled 1 for enabled, 0 for disabled @param clientUUID client ID @throws Exception exception
[ "Sets", "enabled", "/", "disabled", "for", "a", "response" ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/proxylib/src/main/java/com/groupon/odo/proxylib/PathOverrideService.java#L1351-L1377
dita-ot/dita-ot
src/main/java/org/dita/dost/writer/ValidationFilter.java
ValidationFilter.validateReference
private AttributesImpl validateReference(final String attrName, final Attributes atts, final AttributesImpl modified) { """ Validate and fix {@code href} or {@code conref} attribute for URI validity. @return modified attributes, {@code null} if there have been no changes """ AttributesImpl res = modified; final String href = atts.getValue(attrName); if (href != null) { try { new URI(href); } catch (final URISyntaxException e) { switch (processingMode) { case STRICT: throw new RuntimeException(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ": " + e.getMessage(), e); case SKIP: logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using invalid value."); break; case LAX: try { final URI uri = new URI(URLUtils.clean(href.trim())); if (res == null) { res = new AttributesImpl(atts); } res.setValue(res.getIndex(attrName), uri.toASCIIString()); logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using '" + uri.toASCIIString() + "'."); } catch (final URISyntaxException e1) { logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using invalid value."); } break; } } } return res; }
java
private AttributesImpl validateReference(final String attrName, final Attributes atts, final AttributesImpl modified) { AttributesImpl res = modified; final String href = atts.getValue(attrName); if (href != null) { try { new URI(href); } catch (final URISyntaxException e) { switch (processingMode) { case STRICT: throw new RuntimeException(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ": " + e.getMessage(), e); case SKIP: logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using invalid value."); break; case LAX: try { final URI uri = new URI(URLUtils.clean(href.trim())); if (res == null) { res = new AttributesImpl(atts); } res.setValue(res.getIndex(attrName), uri.toASCIIString()); logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using '" + uri.toASCIIString() + "'."); } catch (final URISyntaxException e1) { logger.error(MessageUtils.getMessage("DOTJ054E", attrName, href).setLocation(locator) + ", using invalid value."); } break; } } } return res; }
[ "private", "AttributesImpl", "validateReference", "(", "final", "String", "attrName", ",", "final", "Attributes", "atts", ",", "final", "AttributesImpl", "modified", ")", "{", "AttributesImpl", "res", "=", "modified", ";", "final", "String", "href", "=", "atts", ".", "getValue", "(", "attrName", ")", ";", "if", "(", "href", "!=", "null", ")", "{", "try", "{", "new", "URI", "(", "href", ")", ";", "}", "catch", "(", "final", "URISyntaxException", "e", ")", "{", "switch", "(", "processingMode", ")", "{", "case", "STRICT", ":", "throw", "new", "RuntimeException", "(", "MessageUtils", ".", "getMessage", "(", "\"DOTJ054E\"", ",", "attrName", ",", "href", ")", ".", "setLocation", "(", "locator", ")", "+", "\": \"", "+", "e", ".", "getMessage", "(", ")", ",", "e", ")", ";", "case", "SKIP", ":", "logger", ".", "error", "(", "MessageUtils", ".", "getMessage", "(", "\"DOTJ054E\"", ",", "attrName", ",", "href", ")", ".", "setLocation", "(", "locator", ")", "+", "\", using invalid value.\"", ")", ";", "break", ";", "case", "LAX", ":", "try", "{", "final", "URI", "uri", "=", "new", "URI", "(", "URLUtils", ".", "clean", "(", "href", ".", "trim", "(", ")", ")", ")", ";", "if", "(", "res", "==", "null", ")", "{", "res", "=", "new", "AttributesImpl", "(", "atts", ")", ";", "}", "res", ".", "setValue", "(", "res", ".", "getIndex", "(", "attrName", ")", ",", "uri", ".", "toASCIIString", "(", ")", ")", ";", "logger", ".", "error", "(", "MessageUtils", ".", "getMessage", "(", "\"DOTJ054E\"", ",", "attrName", ",", "href", ")", ".", "setLocation", "(", "locator", ")", "+", "\", using '\"", "+", "uri", ".", "toASCIIString", "(", ")", "+", "\"'.\"", ")", ";", "}", "catch", "(", "final", "URISyntaxException", "e1", ")", "{", "logger", ".", "error", "(", "MessageUtils", ".", "getMessage", "(", "\"DOTJ054E\"", ",", "attrName", ",", "href", ")", ".", "setLocation", "(", "locator", ")", "+", "\", using invalid value.\"", ")", ";", "}", "break", ";", "}", "}", "}", "return", "res", ";", "}" ]
Validate and fix {@code href} or {@code conref} attribute for URI validity. @return modified attributes, {@code null} if there have been no changes
[ "Validate", "and", "fix", "{", "@code", "href", "}", "or", "{", "@code", "conref", "}", "attribute", "for", "URI", "validity", "." ]
train
https://github.com/dita-ot/dita-ot/blob/ea776b3c60c03d9f033b6f7ea072349e49dbcdd2/src/main/java/org/dita/dost/writer/ValidationFilter.java#L183-L212
aws/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutMethodResult.java
PutMethodResult.withRequestModels
public PutMethodResult withRequestModels(java.util.Map<String, String> requestModels) { """ <p> A key-value map specifying data schemas, represented by <a>Model</a> resources, (as the mapped value) of the request payloads of given content types (as the mapping key). </p> @param requestModels A key-value map specifying data schemas, represented by <a>Model</a> resources, (as the mapped value) of the request payloads of given content types (as the mapping key). @return Returns a reference to this object so that method calls can be chained together. """ setRequestModels(requestModels); return this; }
java
public PutMethodResult withRequestModels(java.util.Map<String, String> requestModels) { setRequestModels(requestModels); return this; }
[ "public", "PutMethodResult", "withRequestModels", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "requestModels", ")", "{", "setRequestModels", "(", "requestModels", ")", ";", "return", "this", ";", "}" ]
<p> A key-value map specifying data schemas, represented by <a>Model</a> resources, (as the mapped value) of the request payloads of given content types (as the mapping key). </p> @param requestModels A key-value map specifying data schemas, represented by <a>Model</a> resources, (as the mapped value) of the request payloads of given content types (as the mapping key). @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "key", "-", "value", "map", "specifying", "data", "schemas", "represented", "by", "<a", ">", "Model<", "/", "a", ">", "resources", "(", "as", "the", "mapped", "value", ")", "of", "the", "request", "payloads", "of", "given", "content", "types", "(", "as", "the", "mapping", "key", ")", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/PutMethodResult.java#L614-L617
google/error-prone-javac
src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java
ClassReader.sigToType
Type sigToType(byte[] sig, int offset, int len) { """ Convert signature to type, where signature is a byte array segment. """ signature = sig; sigp = offset; siglimit = offset + len; return sigToType(); }
java
Type sigToType(byte[] sig, int offset, int len) { signature = sig; sigp = offset; siglimit = offset + len; return sigToType(); }
[ "Type", "sigToType", "(", "byte", "[", "]", "sig", ",", "int", "offset", ",", "int", "len", ")", "{", "signature", "=", "sig", ";", "sigp", "=", "offset", ";", "siglimit", "=", "offset", "+", "len", ";", "return", "sigToType", "(", ")", ";", "}" ]
Convert signature to type, where signature is a byte array segment.
[ "Convert", "signature", "to", "type", "where", "signature", "is", "a", "byte", "array", "segment", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassReader.java#L652-L657
windup/windup
reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java
IssueCategoryRegistry.addDefaults
private void addDefaults() { """ Make sure that we have some reasonable defaults available. These would typically be provided by the rulesets in the real world. """ this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true)); this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true)); this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true)); }
java
private void addDefaults() { this.issueCategories.putIfAbsent(MANDATORY, new IssueCategory(MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Mandatory", MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(OPTIONAL, new IssueCategory(OPTIONAL, IssueCategoryRegistry.class.getCanonicalName(), "Optional", OPTIONAL, 1000, true)); this.issueCategories.putIfAbsent(POTENTIAL, new IssueCategory(POTENTIAL, IssueCategoryRegistry.class.getCanonicalName(), "Potential Issues", POTENTIAL, 1000, true)); this.issueCategories.putIfAbsent(CLOUD_MANDATORY, new IssueCategory(CLOUD_MANDATORY, IssueCategoryRegistry.class.getCanonicalName(), "Cloud Mandatory", CLOUD_MANDATORY, 1000, true)); this.issueCategories.putIfAbsent(INFORMATION, new IssueCategory(INFORMATION, IssueCategoryRegistry.class.getCanonicalName(), "Information", INFORMATION, 1000, true)); }
[ "private", "void", "addDefaults", "(", ")", "{", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "MANDATORY", ",", "new", "IssueCategory", "(", "MANDATORY", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Mandatory\"", ",", "MANDATORY", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "OPTIONAL", ",", "new", "IssueCategory", "(", "OPTIONAL", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Optional\"", ",", "OPTIONAL", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "POTENTIAL", ",", "new", "IssueCategory", "(", "POTENTIAL", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Potential Issues\"", ",", "POTENTIAL", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "CLOUD_MANDATORY", ",", "new", "IssueCategory", "(", "CLOUD_MANDATORY", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Cloud Mandatory\"", ",", "CLOUD_MANDATORY", ",", "1000", ",", "true", ")", ")", ";", "this", ".", "issueCategories", ".", "putIfAbsent", "(", "INFORMATION", ",", "new", "IssueCategory", "(", "INFORMATION", ",", "IssueCategoryRegistry", ".", "class", ".", "getCanonicalName", "(", ")", ",", "\"Information\"", ",", "INFORMATION", ",", "1000", ",", "true", ")", ")", ";", "}" ]
Make sure that we have some reasonable defaults available. These would typically be provided by the rulesets in the real world.
[ "Make", "sure", "that", "we", "have", "some", "reasonable", "defaults", "available", ".", "These", "would", "typically", "be", "provided", "by", "the", "rulesets", "in", "the", "real", "world", "." ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/category/IssueCategoryRegistry.java#L165-L172
OpenLiberty/open-liberty
dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java
CommonMpJwtFat.buildStringToCheck
public String buildStringToCheck(String claimIdentifier, String key, String value) throws Exception { """ Build the string to search for (the test app should have logged this string if everything is working as it should) @param claimIdentifier - an identifier logged by the test app - could be the method used to obtain the key @param key - the key to validate @param value - the value to validate @return - returns the string to look for in the output @throws Exception """ String builtString = claimIdentifier.trim(); if (!claimIdentifier.contains(":")) { builtString = builtString + ":"; } if (key != null) { builtString = builtString + " key: " + key + " value:.*" + value; } else { builtString = builtString + " " + value.replace("[", "\\[").replace("]", "\\]"); } return builtString; }
java
public String buildStringToCheck(String claimIdentifier, String key, String value) throws Exception { String builtString = claimIdentifier.trim(); if (!claimIdentifier.contains(":")) { builtString = builtString + ":"; } if (key != null) { builtString = builtString + " key: " + key + " value:.*" + value; } else { builtString = builtString + " " + value.replace("[", "\\[").replace("]", "\\]"); } return builtString; }
[ "public", "String", "buildStringToCheck", "(", "String", "claimIdentifier", ",", "String", "key", ",", "String", "value", ")", "throws", "Exception", "{", "String", "builtString", "=", "claimIdentifier", ".", "trim", "(", ")", ";", "if", "(", "!", "claimIdentifier", ".", "contains", "(", "\":\"", ")", ")", "{", "builtString", "=", "builtString", "+", "\":\"", ";", "}", "if", "(", "key", "!=", "null", ")", "{", "builtString", "=", "builtString", "+", "\" key: \"", "+", "key", "+", "\" value:.*\"", "+", "value", ";", "}", "else", "{", "builtString", "=", "builtString", "+", "\" \"", "+", "value", ".", "replace", "(", "\"[\"", ",", "\"\\\\[\"", ")", ".", "replace", "(", "\"]\"", ",", "\"\\\\]\"", ")", ";", "}", "return", "builtString", ";", "}" ]
Build the string to search for (the test app should have logged this string if everything is working as it should) @param claimIdentifier - an identifier logged by the test app - could be the method used to obtain the key @param key - the key to validate @param value - the value to validate @return - returns the string to look for in the output @throws Exception
[ "Build", "the", "string", "to", "search", "for", "(", "the", "test", "app", "should", "have", "logged", "this", "string", "if", "everything", "is", "working", "as", "it", "should", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.mp.jwt_fat/fat/src/com/ibm/ws/security/mp/jwt/fat/CommonMpJwtFat.java#L279-L292
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java
TypeRegistry.getReloadableType
public ReloadableType getReloadableType(String slashedClassname, boolean allocateIdIfNotYetLoaded) { """ Find the ReloadableType object for a given classname. If the allocateIdIfNotYetLoaded option is set then a new id will be allocated for this classname if it hasn't previously been seen before. This method does not create new ReloadableType objects, they are expected to come into existence when defined by the classloader. @param slashedClassname the slashed class name (e.g. java/lang/String) @param allocateIdIfNotYetLoaded if true an id will be allocated because sometime later the type will be loaded (and made reloadable) @return the ReloadableType discovered or allocated, or null if not found and !allocateIdIfNotYetLoaded """ if (allocateIdIfNotYetLoaded) { return getReloadableType(getTypeIdFor(slashedClassname, allocateIdIfNotYetLoaded)); } else { for (int i = 0; i < reloadableTypesSize; i++) { ReloadableType rtype = reloadableTypes[i]; if (rtype != null && rtype.getSlashedName().equals(slashedClassname)) { return rtype; } } return null; } }
java
public ReloadableType getReloadableType(String slashedClassname, boolean allocateIdIfNotYetLoaded) { if (allocateIdIfNotYetLoaded) { return getReloadableType(getTypeIdFor(slashedClassname, allocateIdIfNotYetLoaded)); } else { for (int i = 0; i < reloadableTypesSize; i++) { ReloadableType rtype = reloadableTypes[i]; if (rtype != null && rtype.getSlashedName().equals(slashedClassname)) { return rtype; } } return null; } }
[ "public", "ReloadableType", "getReloadableType", "(", "String", "slashedClassname", ",", "boolean", "allocateIdIfNotYetLoaded", ")", "{", "if", "(", "allocateIdIfNotYetLoaded", ")", "{", "return", "getReloadableType", "(", "getTypeIdFor", "(", "slashedClassname", ",", "allocateIdIfNotYetLoaded", ")", ")", ";", "}", "else", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "reloadableTypesSize", ";", "i", "++", ")", "{", "ReloadableType", "rtype", "=", "reloadableTypes", "[", "i", "]", ";", "if", "(", "rtype", "!=", "null", "&&", "rtype", ".", "getSlashedName", "(", ")", ".", "equals", "(", "slashedClassname", ")", ")", "{", "return", "rtype", ";", "}", "}", "return", "null", ";", "}", "}" ]
Find the ReloadableType object for a given classname. If the allocateIdIfNotYetLoaded option is set then a new id will be allocated for this classname if it hasn't previously been seen before. This method does not create new ReloadableType objects, they are expected to come into existence when defined by the classloader. @param slashedClassname the slashed class name (e.g. java/lang/String) @param allocateIdIfNotYetLoaded if true an id will be allocated because sometime later the type will be loaded (and made reloadable) @return the ReloadableType discovered or allocated, or null if not found and !allocateIdIfNotYetLoaded
[ "Find", "the", "ReloadableType", "object", "for", "a", "given", "classname", ".", "If", "the", "allocateIdIfNotYetLoaded", "option", "is", "set", "then", "a", "new", "id", "will", "be", "allocated", "for", "this", "classname", "if", "it", "hasn", "t", "previously", "been", "seen", "before", ".", "This", "method", "does", "not", "create", "new", "ReloadableType", "objects", "they", "are", "expected", "to", "come", "into", "existence", "when", "defined", "by", "the", "classloader", "." ]
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/TypeRegistry.java#L1269-L1282
grpc/grpc-java
context/src/main/java/io/grpc/Context.java
Context.withDeadlineAfter
public CancellableContext withDeadlineAfter(long duration, TimeUnit unit, ScheduledExecutorService scheduler) { """ Create a new context which will cancel itself after the given {@code duration} from now. The returned context will cascade cancellation of its parent. Callers may explicitly cancel the returned context prior to the deadline just as for {@link #withCancellation()}. If the unit of work completes before the deadline, the context should be explicitly cancelled to allow it to be garbage collected. <p>Sample usage: <pre> Context.CancellableContext withDeadline = Context.current() .withDeadlineAfter(5, TimeUnit.SECONDS, scheduler); try { withDeadline.run(new Runnable() { public void run() { Context current = Context.current(); while (!current.isCancelled()) { keepWorking(); } } }); } finally { withDeadline.cancel(null); } </pre> """ return withDeadline(Deadline.after(duration, unit), scheduler); }
java
public CancellableContext withDeadlineAfter(long duration, TimeUnit unit, ScheduledExecutorService scheduler) { return withDeadline(Deadline.after(duration, unit), scheduler); }
[ "public", "CancellableContext", "withDeadlineAfter", "(", "long", "duration", ",", "TimeUnit", "unit", ",", "ScheduledExecutorService", "scheduler", ")", "{", "return", "withDeadline", "(", "Deadline", ".", "after", "(", "duration", ",", "unit", ")", ",", "scheduler", ")", ";", "}" ]
Create a new context which will cancel itself after the given {@code duration} from now. The returned context will cascade cancellation of its parent. Callers may explicitly cancel the returned context prior to the deadline just as for {@link #withCancellation()}. If the unit of work completes before the deadline, the context should be explicitly cancelled to allow it to be garbage collected. <p>Sample usage: <pre> Context.CancellableContext withDeadline = Context.current() .withDeadlineAfter(5, TimeUnit.SECONDS, scheduler); try { withDeadline.run(new Runnable() { public void run() { Context current = Context.current(); while (!current.isCancelled()) { keepWorking(); } } }); } finally { withDeadline.cancel(null); } </pre>
[ "Create", "a", "new", "context", "which", "will", "cancel", "itself", "after", "the", "given", "{", "@code", "duration", "}", "from", "now", ".", "The", "returned", "context", "will", "cascade", "cancellation", "of", "its", "parent", ".", "Callers", "may", "explicitly", "cancel", "the", "returned", "context", "prior", "to", "the", "deadline", "just", "as", "for", "{", "@link", "#withCancellation", "()", "}", ".", "If", "the", "unit", "of", "work", "completes", "before", "the", "deadline", "the", "context", "should", "be", "explicitly", "cancelled", "to", "allow", "it", "to", "be", "garbage", "collected", "." ]
train
https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/context/src/main/java/io/grpc/Context.java#L269-L272
astrapi69/mystic-crypt
crypt-data/src/main/java/de/alpharogroup/crypto/factories/CipherFactory.java
CipherFactory.newCipher
public static Cipher newCipher(final String privateKey, final String algorithm, final byte[] salt, final int iterationCount, final int operationMode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException { """ Factory method for creating a new {@link Cipher} from the given parameters. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Cipher} from the given parameters. @param privateKey the private key @param algorithm the algorithm @param salt the salt. @param iterationCount the iteration count @param operationMode the operation mode for the new cipher object @return the cipher @throws NoSuchAlgorithmException is thrown if instantiation of the SecretKeyFactory object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails. @throws NoSuchPaddingException is thrown if instantiation of the cypher object fails. @throws InvalidKeyException is thrown if initialization of the cypher object fails. @throws InvalidAlgorithmParameterException is thrown if initialization of the cypher object fails. @throws UnsupportedEncodingException is thrown if the named charset is not supported. """ final KeySpec keySpec = KeySpecFactory.newPBEKeySpec(privateKey, salt, iterationCount); final SecretKeyFactory factory = SecretKeyFactoryExtensions.newSecretKeyFactory(algorithm); final SecretKey key = factory.generateSecret(keySpec); final AlgorithmParameterSpec paramSpec = AlgorithmParameterSpecFactory .newPBEParameterSpec(salt, iterationCount); return newCipher(operationMode, key, paramSpec, key.getAlgorithm()); }
java
public static Cipher newCipher(final String privateKey, final String algorithm, final byte[] salt, final int iterationCount, final int operationMode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, UnsupportedEncodingException { final KeySpec keySpec = KeySpecFactory.newPBEKeySpec(privateKey, salt, iterationCount); final SecretKeyFactory factory = SecretKeyFactoryExtensions.newSecretKeyFactory(algorithm); final SecretKey key = factory.generateSecret(keySpec); final AlgorithmParameterSpec paramSpec = AlgorithmParameterSpecFactory .newPBEParameterSpec(salt, iterationCount); return newCipher(operationMode, key, paramSpec, key.getAlgorithm()); }
[ "public", "static", "Cipher", "newCipher", "(", "final", "String", "privateKey", ",", "final", "String", "algorithm", ",", "final", "byte", "[", "]", "salt", ",", "final", "int", "iterationCount", ",", "final", "int", "operationMode", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecException", ",", "NoSuchPaddingException", ",", "InvalidKeyException", ",", "InvalidAlgorithmParameterException", ",", "UnsupportedEncodingException", "{", "final", "KeySpec", "keySpec", "=", "KeySpecFactory", ".", "newPBEKeySpec", "(", "privateKey", ",", "salt", ",", "iterationCount", ")", ";", "final", "SecretKeyFactory", "factory", "=", "SecretKeyFactoryExtensions", ".", "newSecretKeyFactory", "(", "algorithm", ")", ";", "final", "SecretKey", "key", "=", "factory", ".", "generateSecret", "(", "keySpec", ")", ";", "final", "AlgorithmParameterSpec", "paramSpec", "=", "AlgorithmParameterSpecFactory", ".", "newPBEParameterSpec", "(", "salt", ",", "iterationCount", ")", ";", "return", "newCipher", "(", "operationMode", ",", "key", ",", "paramSpec", ",", "key", ".", "getAlgorithm", "(", ")", ")", ";", "}" ]
Factory method for creating a new {@link Cipher} from the given parameters. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new {@link Cipher} from the given parameters. @param privateKey the private key @param algorithm the algorithm @param salt the salt. @param iterationCount the iteration count @param operationMode the operation mode for the new cipher object @return the cipher @throws NoSuchAlgorithmException is thrown if instantiation of the SecretKeyFactory object fails. @throws InvalidKeySpecException is thrown if generation of the SecretKey object fails. @throws NoSuchPaddingException is thrown if instantiation of the cypher object fails. @throws InvalidKeyException is thrown if initialization of the cypher object fails. @throws InvalidAlgorithmParameterException is thrown if initialization of the cypher object fails. @throws UnsupportedEncodingException is thrown if the named charset is not supported.
[ "Factory", "method", "for", "creating", "a", "new", "{", "@link", "Cipher", "}", "from", "the", "given", "parameters", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridden", "so", "users", "can", "provide", "their", "own", "version", "of", "a", "new", "{", "@link", "Cipher", "}", "from", "the", "given", "parameters", "." ]
train
https://github.com/astrapi69/mystic-crypt/blob/7f51ef5e4457e24de7ff391f10bfc5609e6f1a34/crypt-data/src/main/java/de/alpharogroup/crypto/factories/CipherFactory.java#L158-L169
picoff/java-commons
src/main/java/com/picoff/commons/net/InetAddressAnonymizer.java
InetAddressAnonymizer.anonymize
public static InetAddress anonymize(final InetAddress inetAddress) throws UnknownHostException { """ IPv4 addresses have their length truncated to 24 bits, IPv6 to 48 bits """ if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) { return inetAddress; } final int mask = inetAddress instanceof Inet4Address ? 24 : 48; return truncate(inetAddress, mask); }
java
public static InetAddress anonymize(final InetAddress inetAddress) throws UnknownHostException { if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) { return inetAddress; } final int mask = inetAddress instanceof Inet4Address ? 24 : 48; return truncate(inetAddress, mask); }
[ "public", "static", "InetAddress", "anonymize", "(", "final", "InetAddress", "inetAddress", ")", "throws", "UnknownHostException", "{", "if", "(", "inetAddress", ".", "isAnyLocalAddress", "(", ")", "||", "inetAddress", ".", "isLoopbackAddress", "(", ")", ")", "{", "return", "inetAddress", ";", "}", "final", "int", "mask", "=", "inetAddress", "instanceof", "Inet4Address", "?", "24", ":", "48", ";", "return", "truncate", "(", "inetAddress", ",", "mask", ")", ";", "}" ]
IPv4 addresses have their length truncated to 24 bits, IPv6 to 48 bits
[ "IPv4", "addresses", "have", "their", "length", "truncated", "to", "24", "bits", "IPv6", "to", "48", "bits" ]
train
https://github.com/picoff/java-commons/blob/522d12db77c240edfb62db10a3eb8e0023b87317/src/main/java/com/picoff/commons/net/InetAddressAnonymizer.java#L26-L33
icode/ameba
src/main/java/ameba/mvc/template/internal/TemplateHelper.java
TemplateHelper.getTemplateOutputEncoding
public static Charset getTemplateOutputEncoding(Configuration configuration, String suffix) { """ Get output encoding from configuration. @param configuration Configuration. @param suffix Template processor suffix of the to configuration property {@link org.glassfish.jersey.server.mvc.MvcFeature#ENCODING}. @return Encoding read from configuration properties or a default encoding if no encoding is configured. """ final String enc = PropertiesHelper.getValue(configuration.getProperties(), MvcFeature.ENCODING + suffix, String.class, null); if (enc == null) { return DEFAULT_ENCODING; } else { return Charset.forName(enc); } }
java
public static Charset getTemplateOutputEncoding(Configuration configuration, String suffix) { final String enc = PropertiesHelper.getValue(configuration.getProperties(), MvcFeature.ENCODING + suffix, String.class, null); if (enc == null) { return DEFAULT_ENCODING; } else { return Charset.forName(enc); } }
[ "public", "static", "Charset", "getTemplateOutputEncoding", "(", "Configuration", "configuration", ",", "String", "suffix", ")", "{", "final", "String", "enc", "=", "PropertiesHelper", ".", "getValue", "(", "configuration", ".", "getProperties", "(", ")", ",", "MvcFeature", ".", "ENCODING", "+", "suffix", ",", "String", ".", "class", ",", "null", ")", ";", "if", "(", "enc", "==", "null", ")", "{", "return", "DEFAULT_ENCODING", ";", "}", "else", "{", "return", "Charset", ".", "forName", "(", "enc", ")", ";", "}", "}" ]
Get output encoding from configuration. @param configuration Configuration. @param suffix Template processor suffix of the to configuration property {@link org.glassfish.jersey.server.mvc.MvcFeature#ENCODING}. @return Encoding read from configuration properties or a default encoding if no encoding is configured.
[ "Get", "output", "encoding", "from", "configuration", "." ]
train
https://github.com/icode/ameba/blob/9d4956e935898e41331b2745e400ef869cd265e0/src/main/java/ameba/mvc/template/internal/TemplateHelper.java#L152-L160
haifengl/smile
core/src/main/java/smile/clustering/PartitionClustering.java
PartitionClustering.squaredDistance
static double squaredDistance(double[] x, double[] y) { """ Squared Euclidean distance with handling missing values (represented as NaN). """ int n = x.length; int m = 0; double dist = 0.0; for (int i = 0; i < n; i++) { if (!Double.isNaN(x[i]) && !Double.isNaN(y[i])) { m++; double d = x[i] - y[i]; dist += d * d; } } if (m == 0) { dist = Double.MAX_VALUE; } else { dist = n * dist / m; } return dist; }
java
static double squaredDistance(double[] x, double[] y) { int n = x.length; int m = 0; double dist = 0.0; for (int i = 0; i < n; i++) { if (!Double.isNaN(x[i]) && !Double.isNaN(y[i])) { m++; double d = x[i] - y[i]; dist += d * d; } } if (m == 0) { dist = Double.MAX_VALUE; } else { dist = n * dist / m; } return dist; }
[ "static", "double", "squaredDistance", "(", "double", "[", "]", "x", ",", "double", "[", "]", "y", ")", "{", "int", "n", "=", "x", ".", "length", ";", "int", "m", "=", "0", ";", "double", "dist", "=", "0.0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "!", "Double", ".", "isNaN", "(", "x", "[", "i", "]", ")", "&&", "!", "Double", ".", "isNaN", "(", "y", "[", "i", "]", ")", ")", "{", "m", "++", ";", "double", "d", "=", "x", "[", "i", "]", "-", "y", "[", "i", "]", ";", "dist", "+=", "d", "*", "d", ";", "}", "}", "if", "(", "m", "==", "0", ")", "{", "dist", "=", "Double", ".", "MAX_VALUE", ";", "}", "else", "{", "dist", "=", "n", "*", "dist", "/", "m", ";", "}", "return", "dist", ";", "}" ]
Squared Euclidean distance with handling missing values (represented as NaN).
[ "Squared", "Euclidean", "distance", "with", "handling", "missing", "values", "(", "represented", "as", "NaN", ")", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/clustering/PartitionClustering.java#L67-L87
VoltDB/voltdb
src/frontend/org/voltcore/zk/MapCache.java
MapCache.processChildEvent
private void processChildEvent(WatchedEvent event) throws Exception { """ Update a modified child and republish a new snapshot. This may indicate a deleted child or a child with modified data. """ HashMap<String, JSONObject> cacheCopy = new HashMap<String, JSONObject>(m_publicCache.get()); ByteArrayCallback cb = new ByteArrayCallback(); m_zk.getData(event.getPath(), m_childWatch, cb, null); try { byte payload[] = cb.get(); JSONObject jsObj = new JSONObject(new String(payload, "UTF-8")); cacheCopy.put(cb.getPath(), jsObj); } catch (KeeperException.NoNodeException e) { cacheCopy.remove(event.getPath()); } m_publicCache.set(ImmutableMap.copyOf(cacheCopy)); if (m_cb != null) { m_cb.run(m_publicCache.get()); } }
java
private void processChildEvent(WatchedEvent event) throws Exception { HashMap<String, JSONObject> cacheCopy = new HashMap<String, JSONObject>(m_publicCache.get()); ByteArrayCallback cb = new ByteArrayCallback(); m_zk.getData(event.getPath(), m_childWatch, cb, null); try { byte payload[] = cb.get(); JSONObject jsObj = new JSONObject(new String(payload, "UTF-8")); cacheCopy.put(cb.getPath(), jsObj); } catch (KeeperException.NoNodeException e) { cacheCopy.remove(event.getPath()); } m_publicCache.set(ImmutableMap.copyOf(cacheCopy)); if (m_cb != null) { m_cb.run(m_publicCache.get()); } }
[ "private", "void", "processChildEvent", "(", "WatchedEvent", "event", ")", "throws", "Exception", "{", "HashMap", "<", "String", ",", "JSONObject", ">", "cacheCopy", "=", "new", "HashMap", "<", "String", ",", "JSONObject", ">", "(", "m_publicCache", ".", "get", "(", ")", ")", ";", "ByteArrayCallback", "cb", "=", "new", "ByteArrayCallback", "(", ")", ";", "m_zk", ".", "getData", "(", "event", ".", "getPath", "(", ")", ",", "m_childWatch", ",", "cb", ",", "null", ")", ";", "try", "{", "byte", "payload", "[", "]", "=", "cb", ".", "get", "(", ")", ";", "JSONObject", "jsObj", "=", "new", "JSONObject", "(", "new", "String", "(", "payload", ",", "\"UTF-8\"", ")", ")", ";", "cacheCopy", ".", "put", "(", "cb", ".", "getPath", "(", ")", ",", "jsObj", ")", ";", "}", "catch", "(", "KeeperException", ".", "NoNodeException", "e", ")", "{", "cacheCopy", ".", "remove", "(", "event", ".", "getPath", "(", ")", ")", ";", "}", "m_publicCache", ".", "set", "(", "ImmutableMap", ".", "copyOf", "(", "cacheCopy", ")", ")", ";", "if", "(", "m_cb", "!=", "null", ")", "{", "m_cb", ".", "run", "(", "m_publicCache", ".", "get", "(", ")", ")", ";", "}", "}" ]
Update a modified child and republish a new snapshot. This may indicate a deleted child or a child with modified data.
[ "Update", "a", "modified", "child", "and", "republish", "a", "new", "snapshot", ".", "This", "may", "indicate", "a", "deleted", "child", "or", "a", "child", "with", "modified", "data", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltcore/zk/MapCache.java#L277-L292
phax/ph-masterdata
ph-masterdata/src/main/java/com/helger/masterdata/ean/AbstractUPCEAN.java
AbstractUPCEAN.calcChecksumChar
protected static char calcChecksumChar (@Nonnull final String sMsg, @Nonnegative final int nLength) { """ Calculates the check character for a given message @param sMsg the message @param nLength The number of characters to be checked. Must be &ge; 0 and &lt; message.length @return char the check character """ ValueEnforcer.notNull (sMsg, "Msg"); ValueEnforcer.isBetweenInclusive (nLength, "Length", 0, sMsg.length ()); return asChar (calcChecksum (sMsg.toCharArray (), nLength)); }
java
protected static char calcChecksumChar (@Nonnull final String sMsg, @Nonnegative final int nLength) { ValueEnforcer.notNull (sMsg, "Msg"); ValueEnforcer.isBetweenInclusive (nLength, "Length", 0, sMsg.length ()); return asChar (calcChecksum (sMsg.toCharArray (), nLength)); }
[ "protected", "static", "char", "calcChecksumChar", "(", "@", "Nonnull", "final", "String", "sMsg", ",", "@", "Nonnegative", "final", "int", "nLength", ")", "{", "ValueEnforcer", ".", "notNull", "(", "sMsg", ",", "\"Msg\"", ")", ";", "ValueEnforcer", ".", "isBetweenInclusive", "(", "nLength", ",", "\"Length\"", ",", "0", ",", "sMsg", ".", "length", "(", ")", ")", ";", "return", "asChar", "(", "calcChecksum", "(", "sMsg", ".", "toCharArray", "(", ")", ",", "nLength", ")", ")", ";", "}" ]
Calculates the check character for a given message @param sMsg the message @param nLength The number of characters to be checked. Must be &ge; 0 and &lt; message.length @return char the check character
[ "Calculates", "the", "check", "character", "for", "a", "given", "message" ]
train
https://github.com/phax/ph-masterdata/blob/ca5e0b03c735b30b47930c018bfb5e71f00d0ff4/ph-masterdata/src/main/java/com/helger/masterdata/ean/AbstractUPCEAN.java#L144-L150
jenkinsci/artifactory-plugin
src/main/java/org/jfrog/hudson/pipeline/common/docker/utils/DockerAgentUtils.java
DockerAgentUtils.pullImage
public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host) throws IOException, InterruptedException { """ Execute pull docker image on agent @param launcher @param imageTag @param username @param password @param host @return @throws IOException @throws InterruptedException """ return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { public Boolean call() throws IOException { DockerUtils.pullImage(imageTag, username, password, host); return true; } }); }
java
public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host) throws IOException, InterruptedException { return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() { public Boolean call() throws IOException { DockerUtils.pullImage(imageTag, username, password, host); return true; } }); }
[ "public", "static", "boolean", "pullImage", "(", "Launcher", "launcher", ",", "final", "String", "imageTag", ",", "final", "String", "username", ",", "final", "String", "password", ",", "final", "String", "host", ")", "throws", "IOException", ",", "InterruptedException", "{", "return", "launcher", ".", "getChannel", "(", ")", ".", "call", "(", "new", "MasterToSlaveCallable", "<", "Boolean", ",", "IOException", ">", "(", ")", "{", "public", "Boolean", "call", "(", ")", "throws", "IOException", "{", "DockerUtils", ".", "pullImage", "(", "imageTag", ",", "username", ",", "password", ",", "host", ")", ";", "return", "true", ";", "}", "}", ")", ";", "}" ]
Execute pull docker image on agent @param launcher @param imageTag @param username @param password @param host @return @throws IOException @throws InterruptedException
[ "Execute", "pull", "docker", "image", "on", "agent" ]
train
https://github.com/jenkinsci/artifactory-plugin/blob/f5fcfff6a5a50be5374813e49d1fe3aaf6422333/src/main/java/org/jfrog/hudson/pipeline/common/docker/utils/DockerAgentUtils.java#L205-L214
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java
AbstractPlainDatagramSocketImpl.joinGroup
protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException { """ Join the multicast group. @param mcastaddr multicast address to join. @param netIf specifies the local interface to receive multicast datagram packets @throws IllegalArgumentException if mcastaddr is null or is a SocketAddress subclass not supported by this socket @since 1.4 """ if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress)) throw new IllegalArgumentException("Unsupported address type"); join(((InetSocketAddress)mcastaddr).getAddress(), netIf); }
java
protected void joinGroup(SocketAddress mcastaddr, NetworkInterface netIf) throws IOException { if (mcastaddr == null || !(mcastaddr instanceof InetSocketAddress)) throw new IllegalArgumentException("Unsupported address type"); join(((InetSocketAddress)mcastaddr).getAddress(), netIf); }
[ "protected", "void", "joinGroup", "(", "SocketAddress", "mcastaddr", ",", "NetworkInterface", "netIf", ")", "throws", "IOException", "{", "if", "(", "mcastaddr", "==", "null", "||", "!", "(", "mcastaddr", "instanceof", "InetSocketAddress", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported address type\"", ")", ";", "join", "(", "(", "(", "InetSocketAddress", ")", "mcastaddr", ")", ".", "getAddress", "(", ")", ",", "netIf", ")", ";", "}" ]
Join the multicast group. @param mcastaddr multicast address to join. @param netIf specifies the local interface to receive multicast datagram packets @throws IllegalArgumentException if mcastaddr is null or is a SocketAddress subclass not supported by this socket @since 1.4
[ "Join", "the", "multicast", "group", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/net/AbstractPlainDatagramSocketImpl.java#L199-L204
acromusashi/acromusashi-stream
src/main/java/acromusashi/stream/component/infinispan/bolt/InfinispanLookupBolt.java
InfinispanLookupBolt.onLookupAfter
protected void onLookupAfter(StreamMessage input, K lookupKey, V lookupValue) { """ Infinispanからのデータ取得後に実行される処理。 @param input Tuple @param lookupKey 取得に使用したKey @param lookupValue 取得したValue(取得されなかった場合はnull) """ // デフォルトでは取得した結果がnull以外の場合、下流にデータを流す。 if (lookupValue != null) { StreamMessage message = new StreamMessage(); message.addField(FieldName.MESSAGE_KEY, lookupKey); message.addField(FieldName.MESSAGE_VALUE, lookupValue); emitWithGrouping(message, lookupKey, lookupKey.toString()); } }
java
protected void onLookupAfter(StreamMessage input, K lookupKey, V lookupValue) { // デフォルトでは取得した結果がnull以外の場合、下流にデータを流す。 if (lookupValue != null) { StreamMessage message = new StreamMessage(); message.addField(FieldName.MESSAGE_KEY, lookupKey); message.addField(FieldName.MESSAGE_VALUE, lookupValue); emitWithGrouping(message, lookupKey, lookupKey.toString()); } }
[ "protected", "void", "onLookupAfter", "(", "StreamMessage", "input", ",", "K", "lookupKey", ",", "V", "lookupValue", ")", "{", "// デフォルトでは取得した結果がnull以外の場合、下流にデータを流す。", "if", "(", "lookupValue", "!=", "null", ")", "{", "StreamMessage", "message", "=", "new", "StreamMessage", "(", ")", ";", "message", ".", "addField", "(", "FieldName", ".", "MESSAGE_KEY", ",", "lookupKey", ")", ";", "message", ".", "addField", "(", "FieldName", ".", "MESSAGE_VALUE", ",", "lookupValue", ")", ";", "emitWithGrouping", "(", "message", ",", "lookupKey", ",", "lookupKey", ".", "toString", "(", ")", ")", ";", "}", "}" ]
Infinispanからのデータ取得後に実行される処理。 @param input Tuple @param lookupKey 取得に使用したKey @param lookupValue 取得したValue(取得されなかった場合はnull)
[ "Infinispanからのデータ取得後に実行される処理。" ]
train
https://github.com/acromusashi/acromusashi-stream/blob/65b1f335d771d657c5640a2056ab5c8546eddec9/src/main/java/acromusashi/stream/component/infinispan/bolt/InfinispanLookupBolt.java#L140-L151
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java
BouncyCastleCertProcessingFactory.createCredential
public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.CertificateType certType) throws GeneralSecurityException { """ Creates a new proxy credential from the specified certificate chain and a private key. @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) createCredential """ return createCredential(certs, privateKey, bits, lifetime, certType, (X509ExtensionSet) null, null); }
java
public X509Credential createCredential(X509Certificate[] certs, PrivateKey privateKey, int bits, int lifetime, GSIConstants.CertificateType certType) throws GeneralSecurityException { return createCredential(certs, privateKey, bits, lifetime, certType, (X509ExtensionSet) null, null); }
[ "public", "X509Credential", "createCredential", "(", "X509Certificate", "[", "]", "certs", ",", "PrivateKey", "privateKey", ",", "int", "bits", ",", "int", "lifetime", ",", "GSIConstants", ".", "CertificateType", "certType", ")", "throws", "GeneralSecurityException", "{", "return", "createCredential", "(", "certs", ",", "privateKey", ",", "bits", ",", "lifetime", ",", "certType", ",", "(", "X509ExtensionSet", ")", "null", ",", "null", ")", ";", "}" ]
Creates a new proxy credential from the specified certificate chain and a private key. @see #createCredential(X509Certificate[], PrivateKey, int, int, GSIConstants.CertificateType, X509ExtensionSet, String) createCredential
[ "Creates", "a", "new", "proxy", "credential", "from", "the", "specified", "certificate", "chain", "and", "a", "private", "key", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/gsi/bc/BouncyCastleCertProcessingFactory.java#L595-L598
OpenTSDB/opentsdb
src/core/RowKey.java
RowKey.metricName
static String metricName(final TSDB tsdb, final byte[] row) { """ Extracts the name of the metric ID contained in a row key. @param tsdb The TSDB to use. @param row The actual row key. @return The name of the metric. @throws NoSuchUniqueId if the UID could not resolve to a string """ try { return metricNameAsync(tsdb, row).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } }
java
static String metricName(final TSDB tsdb, final byte[] row) { try { return metricNameAsync(tsdb, row).joinUninterruptibly(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException("Should never be here", e); } }
[ "static", "String", "metricName", "(", "final", "TSDB", "tsdb", ",", "final", "byte", "[", "]", "row", ")", "{", "try", "{", "return", "metricNameAsync", "(", "tsdb", ",", "row", ")", ".", "joinUninterruptibly", "(", ")", ";", "}", "catch", "(", "RuntimeException", "e", ")", "{", "throw", "e", ";", "}", "catch", "(", "Exception", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Should never be here\"", ",", "e", ")", ";", "}", "}" ]
Extracts the name of the metric ID contained in a row key. @param tsdb The TSDB to use. @param row The actual row key. @return The name of the metric. @throws NoSuchUniqueId if the UID could not resolve to a string
[ "Extracts", "the", "name", "of", "the", "metric", "ID", "contained", "in", "a", "row", "key", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/RowKey.java#L38-L46
graphhopper/graphhopper
core/src/main/java/com/graphhopper/storage/IntsRef.java
IntsRef.deepCopyOf
public static IntsRef deepCopyOf(IntsRef other) { """ Creates a new IntsRef that points to a copy of the ints from <code>other</code> <p> The returned IntsRef will have a length of other.length and an offset of zero. """ return new IntsRef(Arrays.copyOfRange(other.ints, other.offset, other.offset + other.length), 0, other.length); }
java
public static IntsRef deepCopyOf(IntsRef other) { return new IntsRef(Arrays.copyOfRange(other.ints, other.offset, other.offset + other.length), 0, other.length); }
[ "public", "static", "IntsRef", "deepCopyOf", "(", "IntsRef", "other", ")", "{", "return", "new", "IntsRef", "(", "Arrays", ".", "copyOfRange", "(", "other", ".", "ints", ",", "other", ".", "offset", ",", "other", ".", "offset", "+", "other", ".", "length", ")", ",", "0", ",", "other", ".", "length", ")", ";", "}" ]
Creates a new IntsRef that points to a copy of the ints from <code>other</code> <p> The returned IntsRef will have a length of other.length and an offset of zero.
[ "Creates", "a", "new", "IntsRef", "that", "points", "to", "a", "copy", "of", "the", "ints", "from", "<code", ">", "other<", "/", "code", ">", "<p", ">", "The", "returned", "IntsRef", "will", "have", "a", "length", "of", "other", ".", "length", "and", "an", "offset", "of", "zero", "." ]
train
https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/storage/IntsRef.java#L138-L140