repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 204 | func_name stringlengths 5 103 | whole_func_string stringlengths 87 3.44k | language stringclasses 1
value | func_code_string stringlengths 87 3.44k | func_code_tokens listlengths 21 714 | func_documentation_string stringlengths 61 1.95k | func_documentation_tokens listlengths 1 482 | split_name stringclasses 1
value | func_code_url stringlengths 102 309 |
|---|---|---|---|---|---|---|---|---|---|---|
enasequence/sequencetools | src/main/java/uk/ac/ebi/embl/api/validation/SequenceEntryUtils.java | SequenceEntryUtils.deleteDuplicatedQualfiier | public static boolean deleteDuplicatedQualfiier(Feature feature, String qualifierName)
{
ArrayList<Qualifier> qualifiers = (ArrayList<Qualifier>) feature.getQualifiers(qualifierName);
Set<String> qualifierValueSet = new HashSet<String>();
for (Qualifier qual : qualifiers)
{
if (qual.getValue() != null)
{
if (!qualifierValueSet.add(qual.getValue()))
{
feature.removeQualifier(qual);
return true;
}
}
}
return false;
} | java | public static boolean deleteDuplicatedQualfiier(Feature feature, String qualifierName)
{
ArrayList<Qualifier> qualifiers = (ArrayList<Qualifier>) feature.getQualifiers(qualifierName);
Set<String> qualifierValueSet = new HashSet<String>();
for (Qualifier qual : qualifiers)
{
if (qual.getValue() != null)
{
if (!qualifierValueSet.add(qual.getValue()))
{
feature.removeQualifier(qual);
return true;
}
}
}
return false;
} | [
"public",
"static",
"boolean",
"deleteDuplicatedQualfiier",
"(",
"Feature",
"feature",
",",
"String",
"qualifierName",
")",
"{",
"ArrayList",
"<",
"Qualifier",
">",
"qualifiers",
"=",
"(",
"ArrayList",
"<",
"Qualifier",
">",
")",
"feature",
".",
"getQualifiers",
... | Delete duplicated qualfiier.
@param feature
the feature
@param qualifierName
the qualifier name | [
"Delete",
"duplicated",
"qualfiier",
"."
] | train | https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/api/validation/SequenceEntryUtils.java#L637-L656 |
undertow-io/undertow | core/src/main/java/io/undertow/websockets/core/WebSockets.java | WebSockets.sendBinaryBlocking | public static void sendBinaryBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(data, WebSocketFrameType.BINARY, wsChannel);
} | java | public static void sendBinaryBlocking(final ByteBuffer data, final WebSocketChannel wsChannel) throws IOException {
sendBlockingInternal(data, WebSocketFrameType.BINARY, wsChannel);
} | [
"public",
"static",
"void",
"sendBinaryBlocking",
"(",
"final",
"ByteBuffer",
"data",
",",
"final",
"WebSocketChannel",
"wsChannel",
")",
"throws",
"IOException",
"{",
"sendBlockingInternal",
"(",
"data",
",",
"WebSocketFrameType",
".",
"BINARY",
",",
"wsChannel",
"... | Sends a complete binary message using blocking IO
@param data The data to send
@param wsChannel The web socket channel | [
"Sends",
"a",
"complete",
"binary",
"message",
"using",
"blocking",
"IO"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L736-L738 |
threerings/nenya | core/src/main/java/com/threerings/media/tile/TileSet.java | TileSet.getTileMirage | public Mirage getTileMirage (int tileIndex, Colorization[] zations)
{
Rectangle bounds = computeTileBounds(tileIndex, new Rectangle());
Mirage mirage = null;
if (checkTileIndex(tileIndex)) {
if (_improv == null) {
log.warning("Aiya! Tile set missing image provider", "path", _imagePath);
} else {
mirage = _improv.getTileImage(_imagePath, bounds, zations);
}
}
if (mirage == null) {
mirage = new BufferedMirage(ImageUtil.createErrorImage(bounds.width, bounds.height));
}
return mirage;
} | java | public Mirage getTileMirage (int tileIndex, Colorization[] zations)
{
Rectangle bounds = computeTileBounds(tileIndex, new Rectangle());
Mirage mirage = null;
if (checkTileIndex(tileIndex)) {
if (_improv == null) {
log.warning("Aiya! Tile set missing image provider", "path", _imagePath);
} else {
mirage = _improv.getTileImage(_imagePath, bounds, zations);
}
}
if (mirage == null) {
mirage = new BufferedMirage(ImageUtil.createErrorImage(bounds.width, bounds.height));
}
return mirage;
} | [
"public",
"Mirage",
"getTileMirage",
"(",
"int",
"tileIndex",
",",
"Colorization",
"[",
"]",
"zations",
")",
"{",
"Rectangle",
"bounds",
"=",
"computeTileBounds",
"(",
"tileIndex",
",",
"new",
"Rectangle",
"(",
")",
")",
";",
"Mirage",
"mirage",
"=",
"null",... | Returns a prepared version of the image that would be used by the tile at the specified
index. Because tilesets are often used simply to provide access to a collection of uniform
images, this method is provided to bypass the creation of a {@link Tile} object when all
that is desired is access to the underlying image. | [
"Returns",
"a",
"prepared",
"version",
"of",
"the",
"image",
"that",
"would",
"be",
"used",
"by",
"the",
"tile",
"at",
"the",
"specified",
"index",
".",
"Because",
"tilesets",
"are",
"often",
"used",
"simply",
"to",
"provide",
"access",
"to",
"a",
"collect... | train | https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/tile/TileSet.java#L266-L281 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/SignatureSpi.java | SignatureSpi.engineVerify | protected boolean engineVerify(byte[] sigBytes, int offset, int length)
throws SignatureException {
byte[] sigBytesCopy = new byte[length];
System.arraycopy(sigBytes, offset, sigBytesCopy, 0, length);
return engineVerify(sigBytesCopy);
} | java | protected boolean engineVerify(byte[] sigBytes, int offset, int length)
throws SignatureException {
byte[] sigBytesCopy = new byte[length];
System.arraycopy(sigBytes, offset, sigBytesCopy, 0, length);
return engineVerify(sigBytesCopy);
} | [
"protected",
"boolean",
"engineVerify",
"(",
"byte",
"[",
"]",
"sigBytes",
",",
"int",
"offset",
",",
"int",
"length",
")",
"throws",
"SignatureException",
"{",
"byte",
"[",
"]",
"sigBytesCopy",
"=",
"new",
"byte",
"[",
"length",
"]",
";",
"System",
".",
... | Verifies the passed-in signature in the specified array
of bytes, starting at the specified offset.
<p> Note: Subclasses should overwrite the default implementation.
@param sigBytes the signature bytes to be verified.
@param offset the offset to start from in the array of bytes.
@param length the number of bytes to use, starting at offset.
@return true if the signature was verified, false if not.
@exception SignatureException if the engine is not
initialized properly, the passed-in signature is improperly
encoded or of the wrong type, if this signature algorithm is unable to
process the input data provided, etc.
@since 1.4 | [
"Verifies",
"the",
"passed",
"-",
"in",
"signature",
"in",
"the",
"specified",
"array",
"of",
"bytes",
"starting",
"at",
"the",
"specified",
"offset",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/SignatureSpi.java#L275-L280 |
tvesalainen/util | rpm/src/main/java/org/vesalainen/pm/deb/DEBBuilder.java | DEBBuilder.addRequire | @Override
public DEBBuilder addRequire(String name, String version, Condition... dependency)
{
control.addDepends(release, version, dependency);
return this;
} | java | @Override
public DEBBuilder addRequire(String name, String version, Condition... dependency)
{
control.addDepends(release, version, dependency);
return this;
} | [
"@",
"Override",
"public",
"DEBBuilder",
"addRequire",
"(",
"String",
"name",
",",
"String",
"version",
",",
"Condition",
"...",
"dependency",
")",
"{",
"control",
".",
"addDepends",
"(",
"release",
",",
"version",
",",
"dependency",
")",
";",
"return",
"thi... | Add debian/control Depends field.
@param name
@param version
@param dependency
@return | [
"Add",
"debian",
"/",
"control",
"Depends",
"field",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/rpm/src/main/java/org/vesalainen/pm/deb/DEBBuilder.java#L174-L179 |
cdk/cdk | base/core/src/main/java/org/openscience/cdk/graph/SpanningTree.java | SpanningTree.getPath | public IAtomContainer getPath(IAtomContainer spt, IAtom atom1, IAtom atom2) throws NoSuchAtomException {
IAtomContainer path = spt.getBuilder().newInstance(IAtomContainer.class);
PathTools.resetFlags(spt);
path.addAtom(atom1);
PathTools.depthFirstTargetSearch(spt, atom1, atom2, path);
if (path.getAtomCount() == 1) path.removeAtomOnly(atom1); // no path found: remove initial atom
return path;
} | java | public IAtomContainer getPath(IAtomContainer spt, IAtom atom1, IAtom atom2) throws NoSuchAtomException {
IAtomContainer path = spt.getBuilder().newInstance(IAtomContainer.class);
PathTools.resetFlags(spt);
path.addAtom(atom1);
PathTools.depthFirstTargetSearch(spt, atom1, atom2, path);
if (path.getAtomCount() == 1) path.removeAtomOnly(atom1); // no path found: remove initial atom
return path;
} | [
"public",
"IAtomContainer",
"getPath",
"(",
"IAtomContainer",
"spt",
",",
"IAtom",
"atom1",
",",
"IAtom",
"atom2",
")",
"throws",
"NoSuchAtomException",
"{",
"IAtomContainer",
"path",
"=",
"spt",
".",
"getBuilder",
"(",
")",
".",
"newInstance",
"(",
"IAtomContai... | Find a path connected <i>a1</i> and <i>a2</i> in the tree. If there was
an edge between <i>a1</i> and <i>a2</i> this path is a cycle.
@param spt spanning tree
@param atom1 start of path (source)
@param atom2 end of path (target)
@return a path through the spanning tree from the source to the target
@throws NoSuchAtomException thrown if the atom is not in the spanning
tree | [
"Find",
"a",
"path",
"connected",
"<i",
">",
"a1<",
"/",
"i",
">",
"and",
"<i",
">",
"a2<",
"/",
"i",
">",
"in",
"the",
"tree",
".",
"If",
"there",
"was",
"an",
"edge",
"between",
"<i",
">",
"a1<",
"/",
"i",
">",
"and",
"<i",
">",
"a2<",
"/",... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/SpanningTree.java#L200-L207 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.scrollToSide | public void scrollToSide(int side, float scrollPosition, int stepCount) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "scrollToSide("+side+", "+scrollPosition+", "+stepCount+")");
}
switch (side){
case RIGHT: scroller.scrollToSide(Scroller.Side.RIGHT, scrollPosition, stepCount); break;
case LEFT: scroller.scrollToSide(Scroller.Side.LEFT, scrollPosition, stepCount); break;
}
} | java | public void scrollToSide(int side, float scrollPosition, int stepCount) {
if(config.commandLogging){
Log.d(config.commandLoggingTag, "scrollToSide("+side+", "+scrollPosition+", "+stepCount+")");
}
switch (side){
case RIGHT: scroller.scrollToSide(Scroller.Side.RIGHT, scrollPosition, stepCount); break;
case LEFT: scroller.scrollToSide(Scroller.Side.LEFT, scrollPosition, stepCount); break;
}
} | [
"public",
"void",
"scrollToSide",
"(",
"int",
"side",
",",
"float",
"scrollPosition",
",",
"int",
"stepCount",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",",
"\"scrollToSide(\"",... | Scrolls horizontally.
@param side the side to scroll; {@link #RIGHT} or {@link #LEFT}
@param scrollPosition the position to scroll to, from 0 to 1 where 1 is all the way. Example is: 0.60
@param stepCount how many move steps to include in the scroll. Less steps results in a faster scroll | [
"Scrolls",
"horizontally",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L2307-L2316 |
j256/ormlite-core | src/main/java/com/j256/ormlite/stmt/Where.java | Where.appendSql | void appendSql(String tableName, StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException {
if (clauseStackLevel == 0) {
throw new IllegalStateException("No where clauses defined. Did you miss a where operation?");
}
if (clauseStackLevel != 1) {
throw new IllegalStateException(
"Both the \"left-hand\" and \"right-hand\" clauses have been defined. Did you miss an AND or OR?");
}
if (needsFuture != null) {
throw new IllegalStateException(
"The SQL statement has not been finished since there are previous operations still waiting for clauses.");
}
// we don't pop here because we may want to run the query multiple times
peek().appendSql(databaseType, tableName, sb, columnArgList);
} | java | void appendSql(String tableName, StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException {
if (clauseStackLevel == 0) {
throw new IllegalStateException("No where clauses defined. Did you miss a where operation?");
}
if (clauseStackLevel != 1) {
throw new IllegalStateException(
"Both the \"left-hand\" and \"right-hand\" clauses have been defined. Did you miss an AND or OR?");
}
if (needsFuture != null) {
throw new IllegalStateException(
"The SQL statement has not been finished since there are previous operations still waiting for clauses.");
}
// we don't pop here because we may want to run the query multiple times
peek().appendSql(databaseType, tableName, sb, columnArgList);
} | [
"void",
"appendSql",
"(",
"String",
"tableName",
",",
"StringBuilder",
"sb",
",",
"List",
"<",
"ArgumentHolder",
">",
"columnArgList",
")",
"throws",
"SQLException",
"{",
"if",
"(",
"clauseStackLevel",
"==",
"0",
")",
"{",
"throw",
"new",
"IllegalStateException"... | Used by the internal classes to add the where SQL to the {@link StringBuilder}.
@param tableName
Name of the table to prepend to any column names or null to be ignored. | [
"Used",
"by",
"the",
"internal",
"classes",
"to",
"add",
"the",
"where",
"SQL",
"to",
"the",
"{",
"@link",
"StringBuilder",
"}",
"."
] | train | https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/Where.java#L558-L573 |
undertow-io/undertow | core/src/main/java/io/undertow/websockets/core/WebSockets.java | WebSockets.sendPing | public static <T> void sendPing(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PING, wsChannel, callback, context, -1);
} | java | public static <T> void sendPing(final ByteBuffer[] data, final WebSocketChannel wsChannel, final WebSocketCallback<T> callback, T context) {
sendInternal(mergeBuffers(data), WebSocketFrameType.PING, wsChannel, callback, context, -1);
} | [
"public",
"static",
"<",
"T",
">",
"void",
"sendPing",
"(",
"final",
"ByteBuffer",
"[",
"]",
"data",
",",
"final",
"WebSocketChannel",
"wsChannel",
",",
"final",
"WebSocketCallback",
"<",
"T",
">",
"callback",
",",
"T",
"context",
")",
"{",
"sendInternal",
... | Sends a complete ping message, invoking the callback when complete
@param data The data to send
@param wsChannel The web socket channel
@param callback The callback to invoke on completion
@param context The context object that will be passed to the callback on completion | [
"Sends",
"a",
"complete",
"ping",
"message",
"invoking",
"the",
"callback",
"when",
"complete"
] | train | https://github.com/undertow-io/undertow/blob/87de0b856a7a4ba8faf5b659537b9af07b763263/core/src/main/java/io/undertow/websockets/core/WebSockets.java#L291-L293 |
apache/incubator-gobblin | gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java | JdbcExtractor.getTargetColumnName | private String getTargetColumnName(String sourceColumnName, String alias) {
String targetColumnName = alias;
Schema obj = this.getMetadataColumnMap().get(sourceColumnName.toLowerCase());
if (obj == null) {
targetColumnName = (targetColumnName == null ? "unknown" + this.unknownColumnCounter : targetColumnName);
this.unknownColumnCounter++;
} else {
targetColumnName = (StringUtils.isNotBlank(targetColumnName) ? targetColumnName : sourceColumnName);
}
targetColumnName = this.toCase(targetColumnName);
return Utils.escapeSpecialCharacters(targetColumnName, ConfigurationKeys.ESCAPE_CHARS_IN_COLUMN_NAME, "_");
} | java | private String getTargetColumnName(String sourceColumnName, String alias) {
String targetColumnName = alias;
Schema obj = this.getMetadataColumnMap().get(sourceColumnName.toLowerCase());
if (obj == null) {
targetColumnName = (targetColumnName == null ? "unknown" + this.unknownColumnCounter : targetColumnName);
this.unknownColumnCounter++;
} else {
targetColumnName = (StringUtils.isNotBlank(targetColumnName) ? targetColumnName : sourceColumnName);
}
targetColumnName = this.toCase(targetColumnName);
return Utils.escapeSpecialCharacters(targetColumnName, ConfigurationKeys.ESCAPE_CHARS_IN_COLUMN_NAME, "_");
} | [
"private",
"String",
"getTargetColumnName",
"(",
"String",
"sourceColumnName",
",",
"String",
"alias",
")",
"{",
"String",
"targetColumnName",
"=",
"alias",
";",
"Schema",
"obj",
"=",
"this",
".",
"getMetadataColumnMap",
"(",
")",
".",
"get",
"(",
"sourceColumnN... | Get target column name if column is not found in metadata, then name it
as unknown column If alias is not found, target column is nothing but
source column
@param sourceColumnName
@param alias
@return targetColumnName | [
"Get",
"target",
"column",
"name",
"if",
"column",
"is",
"not",
"found",
"in",
"metadata",
"then",
"name",
"it",
"as",
"unknown",
"column",
"If",
"alias",
"is",
"not",
"found",
"target",
"column",
"is",
"nothing",
"but",
"source",
"column"
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-modules/gobblin-sql/src/main/java/org/apache/gobblin/source/jdbc/JdbcExtractor.java#L473-L484 |
AltBeacon/android-beacon-library | lib/src/main/java/org/altbeacon/beacon/BeaconManager.java | BeaconManager.logDebug | @Deprecated
public static void logDebug(String tag, String message, Throwable t) {
LogManager.d(t, tag, message);
} | java | @Deprecated
public static void logDebug(String tag, String message, Throwable t) {
LogManager.d(t, tag, message);
} | [
"@",
"Deprecated",
"public",
"static",
"void",
"logDebug",
"(",
"String",
"tag",
",",
"String",
"message",
",",
"Throwable",
"t",
")",
"{",
"LogManager",
".",
"d",
"(",
"t",
",",
"tag",
",",
"message",
")",
";",
"}"
] | Convenience method for logging debug by the library
@param tag
@param message
@param t
@deprecated This will be removed in a later release. Use
{@link org.altbeacon.beacon.logging.LogManager#d(Throwable, String, String, Object...)}
instead. | [
"Convenience",
"method",
"for",
"logging",
"debug",
"by",
"the",
"library"
] | train | https://github.com/AltBeacon/android-beacon-library/blob/f7f3a323ea7415d53e7bd695ff6a01f1501d5dc3/lib/src/main/java/org/altbeacon/beacon/BeaconManager.java#L1138-L1141 |
joniles/mpxj | src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java | MSPDIReader.readException | private void readException(ProjectCalendar bc, Project.Calendars.Calendar.Exceptions.Exception exception)
{
Date fromDate = exception.getTimePeriod().getFromDate();
Date toDate = exception.getTimePeriod().getToDate();
// Vico Schedule Planner seems to write start and end dates to FromTime and ToTime
// rather than FromDate and ToDate. This is plain wrong, and appears to be ignored by MS Project
// so we will ignore it too!
if (fromDate != null && toDate != null)
{
ProjectCalendarException bce = bc.addCalendarException(fromDate, toDate);
bce.setName(exception.getName());
readRecurringData(bce, exception);
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = exception.getWorkingTimes();
if (times != null)
{
List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> time = times.getWorkingTime();
for (Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime period : time)
{
Date startTime = period.getFromTime();
Date endTime = period.getToTime();
if (startTime != null && endTime != null)
{
if (startTime.getTime() >= endTime.getTime())
{
endTime = DateHelper.addDays(endTime, 1);
}
bce.addRange(new DateRange(startTime, endTime));
}
}
}
}
} | java | private void readException(ProjectCalendar bc, Project.Calendars.Calendar.Exceptions.Exception exception)
{
Date fromDate = exception.getTimePeriod().getFromDate();
Date toDate = exception.getTimePeriod().getToDate();
// Vico Schedule Planner seems to write start and end dates to FromTime and ToTime
// rather than FromDate and ToDate. This is plain wrong, and appears to be ignored by MS Project
// so we will ignore it too!
if (fromDate != null && toDate != null)
{
ProjectCalendarException bce = bc.addCalendarException(fromDate, toDate);
bce.setName(exception.getName());
readRecurringData(bce, exception);
Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes times = exception.getWorkingTimes();
if (times != null)
{
List<Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime> time = times.getWorkingTime();
for (Project.Calendars.Calendar.Exceptions.Exception.WorkingTimes.WorkingTime period : time)
{
Date startTime = period.getFromTime();
Date endTime = period.getToTime();
if (startTime != null && endTime != null)
{
if (startTime.getTime() >= endTime.getTime())
{
endTime = DateHelper.addDays(endTime, 1);
}
bce.addRange(new DateRange(startTime, endTime));
}
}
}
}
} | [
"private",
"void",
"readException",
"(",
"ProjectCalendar",
"bc",
",",
"Project",
".",
"Calendars",
".",
"Calendar",
".",
"Exceptions",
".",
"Exception",
"exception",
")",
"{",
"Date",
"fromDate",
"=",
"exception",
".",
"getTimePeriod",
"(",
")",
".",
"getFrom... | Read a single calendar exception.
@param bc parent calendar
@param exception exception data | [
"Read",
"a",
"single",
"calendar",
"exception",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L604-L638 |
alibaba/vlayout | vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java | BaseLayoutHelper.layoutChildWithMargin | protected void layoutChildWithMargin(final View child, int left, int top, int right, int bottom, @NonNull LayoutManagerHelper helper) {
layoutChildWithMargin(child, left, top, right, bottom, helper, false);
} | java | protected void layoutChildWithMargin(final View child, int left, int top, int right, int bottom, @NonNull LayoutManagerHelper helper) {
layoutChildWithMargin(child, left, top, right, bottom, helper, false);
} | [
"protected",
"void",
"layoutChildWithMargin",
"(",
"final",
"View",
"child",
",",
"int",
"left",
",",
"int",
"top",
",",
"int",
"right",
",",
"int",
"bottom",
",",
"@",
"NonNull",
"LayoutManagerHelper",
"helper",
")",
"{",
"layoutChildWithMargin",
"(",
"child"... | Helper function which do layout children and also update layoutRegion
but it won't consider margin in layout, so you need take care of margin if you apply margin to your layoutView
@param child child that will be laid
@param left left position
@param top top position
@param right right position
@param bottom bottom position
@param helper layoutManagerHelper, help to lay child | [
"Helper",
"function",
"which",
"do",
"layout",
"children",
"and",
"also",
"update",
"layoutRegion",
"but",
"it",
"won",
"t",
"consider",
"margin",
"in",
"layout",
"so",
"you",
"need",
"take",
"care",
"of",
"margin",
"if",
"you",
"apply",
"margin",
"to",
"y... | train | https://github.com/alibaba/vlayout/blob/8a5a51d9d2eeb91fed2ee331a4cf3496282452ce/vlayout/src/main/java/com/alibaba/android/vlayout/layout/BaseLayoutHelper.java#L332-L334 |
jOOQ/jOOL | jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java | Unchecked.intFunction | public static <R> IntFunction<R> intFunction(CheckedIntFunction<R> function) {
return intFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | java | public static <R> IntFunction<R> intFunction(CheckedIntFunction<R> function) {
return intFunction(function, THROWABLE_TO_RUNTIME_EXCEPTION);
} | [
"public",
"static",
"<",
"R",
">",
"IntFunction",
"<",
"R",
">",
"intFunction",
"(",
"CheckedIntFunction",
"<",
"R",
">",
"function",
")",
"{",
"return",
"intFunction",
"(",
"function",
",",
"THROWABLE_TO_RUNTIME_EXCEPTION",
")",
";",
"}"
] | Wrap a {@link CheckedIntFunction} in a {@link IntFunction}.
<p>
Example:
<code><pre>
IntStream.of(1, 2, 3).mapToObj(Unchecked.intFunction(i -> {
if (i < 0)
throw new Exception("Only positive numbers allowed");
return "" + i;
});
</pre></code> | [
"Wrap",
"a",
"{",
"@link",
"CheckedIntFunction",
"}",
"in",
"a",
"{",
"@link",
"IntFunction",
"}",
".",
"<p",
">",
"Example",
":",
"<code",
">",
"<pre",
">",
"IntStream",
".",
"of",
"(",
"1",
"2",
"3",
")",
".",
"mapToObj",
"(",
"Unchecked",
".",
"... | train | https://github.com/jOOQ/jOOL/blob/889d87c85ca57bafd4eddd78e0f7ae2804d2ee86/jOOL-java-8/src/main/java/org/jooq/lambda/Unchecked.java#L1045-L1047 |
julianhyde/sqlline | src/main/java/sqlline/Commands.java | Commands.closeall | public void closeall(String line, DispatchCallback callback) {
close(null, callback);
if (callback.isSuccess()) {
while (callback.isSuccess()) {
close(null, callback);
}
// the last "close" will set it to fail so reset it to success.
callback.setToSuccess();
}
// probably a holdover of the old boolean returns.
callback.setToFailure();
} | java | public void closeall(String line, DispatchCallback callback) {
close(null, callback);
if (callback.isSuccess()) {
while (callback.isSuccess()) {
close(null, callback);
}
// the last "close" will set it to fail so reset it to success.
callback.setToSuccess();
}
// probably a holdover of the old boolean returns.
callback.setToFailure();
} | [
"public",
"void",
"closeall",
"(",
"String",
"line",
",",
"DispatchCallback",
"callback",
")",
"{",
"close",
"(",
"null",
",",
"callback",
")",
";",
"if",
"(",
"callback",
".",
"isSuccess",
"(",
")",
")",
"{",
"while",
"(",
"callback",
".",
"isSuccess",
... | Closes all connections.
@param line Command line
@param callback Callback for command status | [
"Closes",
"all",
"connections",
"."
] | train | https://github.com/julianhyde/sqlline/blob/7577f3ebaca0897a9ff01d1553d4576487e1d2c3/src/main/java/sqlline/Commands.java#L1028-L1039 |
teatrove/teatrove | teaapps/src/main/java/org/teatrove/teaapps/contexts/FileSystemContext.java | FileSystemContext.writeToFile | public void writeToFile(String filePath, String fileData)
throws IOException {
writeToFile(filePath, fileData, false);
} | java | public void writeToFile(String filePath, String fileData)
throws IOException {
writeToFile(filePath, fileData, false);
} | [
"public",
"void",
"writeToFile",
"(",
"String",
"filePath",
",",
"String",
"fileData",
")",
"throws",
"IOException",
"{",
"writeToFile",
"(",
"filePath",
",",
"fileData",
",",
"false",
")",
";",
"}"
] | Write the contents of the given file data to the file at the given path.
This will replace any existing data.
@param filePath The path to the file to write to
@param fileData The data to write to the given file
@throws IOException if an error occurs writing the data
@see #writeToFile(String, String, boolean) | [
"Write",
"the",
"contents",
"of",
"the",
"given",
"file",
"data",
"to",
"the",
"file",
"at",
"the",
"given",
"path",
".",
"This",
"will",
"replace",
"any",
"existing",
"data",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaapps/src/main/java/org/teatrove/teaapps/contexts/FileSystemContext.java#L250-L254 |
JavaMoney/jsr354-ri | moneta-core/src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java | MonetaryFunctions.min | static MonetaryAmount min(MonetaryAmount a, MonetaryAmount b) {
MoneyUtils.checkAmountParameter(Objects.requireNonNull(a), Objects.requireNonNull(b.getCurrency()));
return a.isLessThan(b) ? a : b;
} | java | static MonetaryAmount min(MonetaryAmount a, MonetaryAmount b) {
MoneyUtils.checkAmountParameter(Objects.requireNonNull(a), Objects.requireNonNull(b.getCurrency()));
return a.isLessThan(b) ? a : b;
} | [
"static",
"MonetaryAmount",
"min",
"(",
"MonetaryAmount",
"a",
",",
"MonetaryAmount",
"b",
")",
"{",
"MoneyUtils",
".",
"checkAmountParameter",
"(",
"Objects",
".",
"requireNonNull",
"(",
"a",
")",
",",
"Objects",
".",
"requireNonNull",
"(",
"b",
".",
"getCurr... | Returns the smaller of two {@code MonetaryAmount} values. If the arguments
have the same value, the result is that same value.
@param a an argument.
@param b another argument.
@return the smaller of {@code a} and {@code b}. | [
"Returns",
"the",
"smaller",
"of",
"two",
"{"
] | train | https://github.com/JavaMoney/jsr354-ri/blob/cf8ff2bbaf9b115acc05eb9b0c76c8397c308284/moneta-core/src/main/java/org/javamoney/moneta/function/MonetaryFunctions.java#L285-L288 |
easymock/objenesis | tck/src/main/java/org/objenesis/tck/AbstractLoader.java | AbstractLoader.loadFromResource | public void loadFromResource(String resource, Candidate.CandidateType type) throws IOException {
InputStream candidatesConfig = classloader.getResourceAsStream(resource);
if(candidatesConfig == null) {
throw new IOException("Resource '" + resource + "' not found");
}
try {
loadFrom(candidatesConfig, type);
}
finally {
candidatesConfig.close();
}
} | java | public void loadFromResource(String resource, Candidate.CandidateType type) throws IOException {
InputStream candidatesConfig = classloader.getResourceAsStream(resource);
if(candidatesConfig == null) {
throw new IOException("Resource '" + resource + "' not found");
}
try {
loadFrom(candidatesConfig, type);
}
finally {
candidatesConfig.close();
}
} | [
"public",
"void",
"loadFromResource",
"(",
"String",
"resource",
",",
"Candidate",
".",
"CandidateType",
"type",
")",
"throws",
"IOException",
"{",
"InputStream",
"candidatesConfig",
"=",
"classloader",
".",
"getResourceAsStream",
"(",
"resource",
")",
";",
"if",
... | Load a candidate property file
@param resource File name
@param type Type of the candidate loaded from the stream
@throws IOException If there's problem reading the file | [
"Load",
"a",
"candidate",
"property",
"file"
] | train | https://github.com/easymock/objenesis/blob/8f601c8ba1aa20bbc640e2c2bc48d55df52c489f/tck/src/main/java/org/objenesis/tck/AbstractLoader.java#L103-L114 |
wcm-io/wcm-io-handler | url/src/main/java/io/wcm/handler/url/impl/modes/AbstractUrlMode.java | AbstractUrlMode.getUrlConfigForTarget | protected UrlConfig getUrlConfigForTarget(Adaptable adaptable, Page targetPage) {
Resource targetResource = null;
if (targetPage != null) {
targetResource = targetPage.adaptTo(Resource.class);
}
return getUrlConfigForTarget(adaptable, targetResource);
} | java | protected UrlConfig getUrlConfigForTarget(Adaptable adaptable, Page targetPage) {
Resource targetResource = null;
if (targetPage != null) {
targetResource = targetPage.adaptTo(Resource.class);
}
return getUrlConfigForTarget(adaptable, targetResource);
} | [
"protected",
"UrlConfig",
"getUrlConfigForTarget",
"(",
"Adaptable",
"adaptable",
",",
"Page",
"targetPage",
")",
"{",
"Resource",
"targetResource",
"=",
"null",
";",
"if",
"(",
"targetPage",
"!=",
"null",
")",
"{",
"targetResource",
"=",
"targetPage",
".",
"ada... | Get URL configuration for target page. If this is invalid or not available, get it from adaptable.
@param adaptable Adaptable (request or resource)
@param targetPage Target page (may be null)
@return Url config (never null) | [
"Get",
"URL",
"configuration",
"for",
"target",
"page",
".",
"If",
"this",
"is",
"invalid",
"or",
"not",
"available",
"get",
"it",
"from",
"adaptable",
"."
] | train | https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/url/src/main/java/io/wcm/handler/url/impl/modes/AbstractUrlMode.java#L55-L61 |
apache/groovy | src/main/java/org/codehaus/groovy/transform/stc/AbstractTypeCheckingExtension.java | AbstractTypeCheckingExtension.makeDynamic | public MethodNode makeDynamic(MethodCall call, ClassNode returnType) {
TypeCheckingContext.EnclosingClosure enclosingClosure = context.getEnclosingClosure();
MethodNode enclosingMethod = context.getEnclosingMethod();
((ASTNode)call).putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
if (enclosingClosure!=null) {
enclosingClosure.getClosureExpression().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
} else {
enclosingMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
}
setHandled(true);
if (debug) {
LOG.info("Turning "+call.getText()+" into a dynamic method call returning "+returnType.toString(false));
}
return new MethodNode(call.getMethodAsString(), 0, returnType, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE);
} | java | public MethodNode makeDynamic(MethodCall call, ClassNode returnType) {
TypeCheckingContext.EnclosingClosure enclosingClosure = context.getEnclosingClosure();
MethodNode enclosingMethod = context.getEnclosingMethod();
((ASTNode)call).putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, returnType);
if (enclosingClosure!=null) {
enclosingClosure.getClosureExpression().putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
} else {
enclosingMethod.putNodeMetaData(StaticTypesMarker.DYNAMIC_RESOLUTION, Boolean.TRUE);
}
setHandled(true);
if (debug) {
LOG.info("Turning "+call.getText()+" into a dynamic method call returning "+returnType.toString(false));
}
return new MethodNode(call.getMethodAsString(), 0, returnType, Parameter.EMPTY_ARRAY, ClassNode.EMPTY_ARRAY, EmptyStatement.INSTANCE);
} | [
"public",
"MethodNode",
"makeDynamic",
"(",
"MethodCall",
"call",
",",
"ClassNode",
"returnType",
")",
"{",
"TypeCheckingContext",
".",
"EnclosingClosure",
"enclosingClosure",
"=",
"context",
".",
"getEnclosingClosure",
"(",
")",
";",
"MethodNode",
"enclosingMethod",
... | Used to instruct the type checker that the call is a dynamic method call.
Calling this method automatically sets the handled flag to true.
@param call the method call which is a dynamic method call
@param returnType the expected return type of the dynamic call
@return a virtual method node with the same name as the expected call | [
"Used",
"to",
"instruct",
"the",
"type",
"checker",
"that",
"the",
"call",
"is",
"a",
"dynamic",
"method",
"call",
".",
"Calling",
"this",
"method",
"automatically",
"sets",
"the",
"handled",
"flag",
"to",
"true",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/transform/stc/AbstractTypeCheckingExtension.java#L275-L289 |
wellner/jcarafe | jcarafe-core/src/main/java/cern/colt/list/BooleanArrayList.java | BooleanArrayList.partFromTo | public AbstractBooleanList partFromTo(int from, int to) {
if (size==0) return new BooleanArrayList(0);
checkRangeFromTo(from, to, size);
boolean[] part = new boolean[to-from+1];
System.arraycopy(elements, from, part, 0, to-from+1);
return new BooleanArrayList(part);
} | java | public AbstractBooleanList partFromTo(int from, int to) {
if (size==0) return new BooleanArrayList(0);
checkRangeFromTo(from, to, size);
boolean[] part = new boolean[to-from+1];
System.arraycopy(elements, from, part, 0, to-from+1);
return new BooleanArrayList(part);
} | [
"public",
"AbstractBooleanList",
"partFromTo",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"if",
"(",
"size",
"==",
"0",
")",
"return",
"new",
"BooleanArrayList",
"(",
"0",
")",
";",
"checkRangeFromTo",
"(",
"from",
",",
"to",
",",
"size",
")",
";"... | Returns a new list of the part of the receiver between <code>from</code>, inclusive, and <code>to</code>, inclusive.
@param from the index of the first element (inclusive).
@param to the index of the last element (inclusive).
@return a new list
@exception IndexOutOfBoundsException index is out of range (<tt>size()>0 && (from<0 || from>to || to>=size())</tt>). | [
"Returns",
"a",
"new",
"list",
"of",
"the",
"part",
"of",
"the",
"receiver",
"between",
"<code",
">",
"from<",
"/",
"code",
">",
"inclusive",
"and",
"<code",
">",
"to<",
"/",
"code",
">",
"inclusive",
"."
] | train | https://github.com/wellner/jcarafe/blob/ab8b0a83dbf600fe80c27711815c90bd3055b217/jcarafe-core/src/main/java/cern/colt/list/BooleanArrayList.java#L284-L292 |
jbundle/jbundle | base/screen/model/src/main/java/org/jbundle/base/screen/model/GridScreen.java | GridScreen.init | public void init(Record record, ScreenLocation itsLocation, BasePanel parentScreen, Converter fieldConverter, int iDisplayFieldDesc, Map<String, Object> properties)
{
m_iNavCount = 0; // Nav buttons
super.init(record, itsLocation, parentScreen, fieldConverter, iDisplayFieldDesc, properties);
int iErrorCode = this.checkSecurity();
if ((iErrorCode != DBConstants.NORMAL_RETURN) && (iErrorCode != Constants.READ_ACCESS))
return;
if (iErrorCode == Constants.READ_ACCESS)
this.setAppending(false);
// Add in the columns
m_iNavCount = this.getSFieldCount();
this.addNavButtons();
m_iNavCount = this.getSFieldCount() - m_iNavCount; // Nav buttons
this.getScreenFieldView().setupTableFromModel();
this.resizeToContent(this.getTitle());
} | java | public void init(Record record, ScreenLocation itsLocation, BasePanel parentScreen, Converter fieldConverter, int iDisplayFieldDesc, Map<String, Object> properties)
{
m_iNavCount = 0; // Nav buttons
super.init(record, itsLocation, parentScreen, fieldConverter, iDisplayFieldDesc, properties);
int iErrorCode = this.checkSecurity();
if ((iErrorCode != DBConstants.NORMAL_RETURN) && (iErrorCode != Constants.READ_ACCESS))
return;
if (iErrorCode == Constants.READ_ACCESS)
this.setAppending(false);
// Add in the columns
m_iNavCount = this.getSFieldCount();
this.addNavButtons();
m_iNavCount = this.getSFieldCount() - m_iNavCount; // Nav buttons
this.getScreenFieldView().setupTableFromModel();
this.resizeToContent(this.getTitle());
} | [
"public",
"void",
"init",
"(",
"Record",
"record",
",",
"ScreenLocation",
"itsLocation",
",",
"BasePanel",
"parentScreen",
",",
"Converter",
"fieldConverter",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",... | Open the files and setup the screen.
@param record The main record for this screen.
@param itsLocation The location of this component within the parent.
@param parentScreen The parent screen.
@param fieldConverter The field this screen field is linked to.
@param iDisplayFieldDesc Do I display the field desc? | [
"Open",
"the",
"files",
"and",
"setup",
"the",
"screen",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/screen/model/src/main/java/org/jbundle/base/screen/model/GridScreen.java#L66-L86 |
google/j2objc | xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java | RedundentExprEliminator.createPseudoVarDecl | protected ElemVariable createPseudoVarDecl(
ElemTemplateElement psuedoVarRecipient,
LocPathIterator lpi, boolean isGlobal)
throws org.w3c.dom.DOMException
{
QName uniquePseudoVarName = new QName (PSUEDOVARNAMESPACE, "#"+getPseudoVarID());
if(isGlobal)
{
return createGlobalPseudoVarDecl(uniquePseudoVarName,
(StylesheetRoot)psuedoVarRecipient, lpi);
}
else
return createLocalPseudoVarDecl(uniquePseudoVarName, psuedoVarRecipient, lpi);
} | java | protected ElemVariable createPseudoVarDecl(
ElemTemplateElement psuedoVarRecipient,
LocPathIterator lpi, boolean isGlobal)
throws org.w3c.dom.DOMException
{
QName uniquePseudoVarName = new QName (PSUEDOVARNAMESPACE, "#"+getPseudoVarID());
if(isGlobal)
{
return createGlobalPseudoVarDecl(uniquePseudoVarName,
(StylesheetRoot)psuedoVarRecipient, lpi);
}
else
return createLocalPseudoVarDecl(uniquePseudoVarName, psuedoVarRecipient, lpi);
} | [
"protected",
"ElemVariable",
"createPseudoVarDecl",
"(",
"ElemTemplateElement",
"psuedoVarRecipient",
",",
"LocPathIterator",
"lpi",
",",
"boolean",
"isGlobal",
")",
"throws",
"org",
".",
"w3c",
".",
"dom",
".",
"DOMException",
"{",
"QName",
"uniquePseudoVarName",
"="... | Create a psuedo variable reference that will represent the
shared redundent XPath, and add it to the stylesheet.
@param psuedoVarRecipient The broadest scope of where the variable
should be inserted, usually an xsl:template or xsl:for-each.
@param lpi The LocationPathIterator that the variable should represent.
@param isGlobal true if the paths are global.
@return The new psuedo var element. | [
"Create",
"a",
"psuedo",
"variable",
"reference",
"that",
"will",
"represent",
"the",
"shared",
"redundent",
"XPath",
"and",
"add",
"it",
"to",
"the",
"stylesheet",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/RedundentExprEliminator.java#L816-L830 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/javac/code/Types.java | Types.isEqualityComparable | public boolean isEqualityComparable(Type s, Type t, Warner warn) {
if (t.isNumeric() && s.isNumeric())
return true;
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (!tPrimitive && !sPrimitive) {
return isCastable(s, t, warn) || isCastable(t, s, warn);
} else {
return false;
}
} | java | public boolean isEqualityComparable(Type s, Type t, Warner warn) {
if (t.isNumeric() && s.isNumeric())
return true;
boolean tPrimitive = t.isPrimitive();
boolean sPrimitive = s.isPrimitive();
if (!tPrimitive && !sPrimitive) {
return isCastable(s, t, warn) || isCastable(t, s, warn);
} else {
return false;
}
} | [
"public",
"boolean",
"isEqualityComparable",
"(",
"Type",
"s",
",",
"Type",
"t",
",",
"Warner",
"warn",
")",
"{",
"if",
"(",
"t",
".",
"isNumeric",
"(",
")",
"&&",
"s",
".",
"isNumeric",
"(",
")",
")",
"return",
"true",
";",
"boolean",
"tPrimitive",
... | Can t and s be compared for equality? Any primitive ==
primitive or primitive == object comparisons here are an error.
Unboxing and correct primitive == primitive comparisons are
already dealt with in Attr.visitBinary. | [
"Can",
"t",
"and",
"s",
"be",
"compared",
"for",
"equality?",
"Any",
"primitive",
"==",
"primitive",
"or",
"primitive",
"==",
"object",
"comparisons",
"here",
"are",
"an",
"error",
".",
"Unboxing",
"and",
"correct",
"primitive",
"==",
"primitive",
"comparisons... | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/javac/code/Types.java#L1456-L1467 |
twilio/twilio-java | src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java | EngagementReader.firstPage | @Override
@SuppressWarnings("checkstyle:linelength")
public Page<Engagement> firstPage(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.STUDIO.toString(),
"/v1/Flows/" + this.pathFlowSid + "/Engagements",
client.getRegion()
);
addQueryParams(request);
return pageForRequest(client, request);
} | java | @Override
@SuppressWarnings("checkstyle:linelength")
public Page<Engagement> firstPage(final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
Domains.STUDIO.toString(),
"/v1/Flows/" + this.pathFlowSid + "/Engagements",
client.getRegion()
);
addQueryParams(request);
return pageForRequest(client, request);
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"checkstyle:linelength\"",
")",
"public",
"Page",
"<",
"Engagement",
">",
"firstPage",
"(",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GE... | Make the request to the Twilio API to perform the read.
@param client TwilioRestClient with which to make the request
@return Engagement ResourceSet | [
"Make",
"the",
"request",
"to",
"the",
"Twilio",
"API",
"to",
"perform",
"the",
"read",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/studio/v1/flow/EngagementReader.java#L51-L63 |
UrielCh/ovh-java-sdk | ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java | ApiOvhDomain.zone_zoneName_record_id_PUT | public void zone_zoneName_record_id_PUT(String zoneName, Long id, OvhRecord body) throws IOException {
String qPath = "/domain/zone/{zoneName}/record/{id}";
StringBuilder sb = path(qPath, zoneName, id);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void zone_zoneName_record_id_PUT(String zoneName, Long id, OvhRecord body) throws IOException {
String qPath = "/domain/zone/{zoneName}/record/{id}";
StringBuilder sb = path(qPath, zoneName, id);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"zone_zoneName_record_id_PUT",
"(",
"String",
"zoneName",
",",
"Long",
"id",
",",
"OvhRecord",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/domain/zone/{zoneName}/record/{id}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(... | Alter this object properties
REST: PUT /domain/zone/{zoneName}/record/{id}
@param body [required] New object properties
@param zoneName [required] The internal name of your zone
@param id [required] Id of the object | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-domain/src/main/java/net/minidev/ovh/api/ApiOvhDomain.java#L903-L907 |
raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/matcher/MethodOverrideMatcher.java | MethodOverrideMatcher.matches | private boolean matches(MethodDescription target, TypeDefinition typeDefinition) {
for (MethodDescription methodDescription : typeDefinition.getDeclaredMethods().filter(isVirtual())) {
if (methodDescription.asSignatureToken().equals(target.asSignatureToken())) {
if (matcher.matches(typeDefinition.asGenericType())) {
return true;
} else {
break;
}
}
}
return false;
} | java | private boolean matches(MethodDescription target, TypeDefinition typeDefinition) {
for (MethodDescription methodDescription : typeDefinition.getDeclaredMethods().filter(isVirtual())) {
if (methodDescription.asSignatureToken().equals(target.asSignatureToken())) {
if (matcher.matches(typeDefinition.asGenericType())) {
return true;
} else {
break;
}
}
}
return false;
} | [
"private",
"boolean",
"matches",
"(",
"MethodDescription",
"target",
",",
"TypeDefinition",
"typeDefinition",
")",
"{",
"for",
"(",
"MethodDescription",
"methodDescription",
":",
"typeDefinition",
".",
"getDeclaredMethods",
"(",
")",
".",
"filter",
"(",
"isVirtual",
... | Checks if a type declares a method with the same signature as {@code target}.
@param target The method to be checked.
@param typeDefinition The type to check for declaring a method with the same signature as {@code target}.
@return {@code true} if the supplied type declares a compatible method. | [
"Checks",
"if",
"a",
"type",
"declares",
"a",
"method",
"with",
"the",
"same",
"signature",
"as",
"{",
"@code",
"target",
"}",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/matcher/MethodOverrideMatcher.java#L88-L99 |
biojava/biojava | biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java | LocationHelper.scanLocations | private static Location scanLocations(List<Location> locations, LocationPredicate predicate) {
Location location = null;
for (Location l : locations) {
if (location == null) {
location = l;
}
else {
if (predicate.accept(location, l)) {
location = l;
}
}
}
return location;
} | java | private static Location scanLocations(List<Location> locations, LocationPredicate predicate) {
Location location = null;
for (Location l : locations) {
if (location == null) {
location = l;
}
else {
if (predicate.accept(location, l)) {
location = l;
}
}
}
return location;
} | [
"private",
"static",
"Location",
"scanLocations",
"(",
"List",
"<",
"Location",
">",
"locations",
",",
"LocationPredicate",
"predicate",
")",
"{",
"Location",
"location",
"=",
"null",
";",
"for",
"(",
"Location",
"l",
":",
"locations",
")",
"{",
"if",
"(",
... | Used for scanning through a list of locations; assumes the
locations given will have at least one value otherwise
we will get a null pointer | [
"Used",
"for",
"scanning",
"through",
"a",
"list",
"of",
"locations",
";",
"assumes",
"the",
"locations",
"given",
"will",
"have",
"at",
"least",
"one",
"value",
"otherwise",
"we",
"will",
"get",
"a",
"null",
"pointer"
] | train | https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/sequence/location/LocationHelper.java#L203-L216 |
voldemort/voldemort | src/java/voldemort/utils/JmxUtils.java | JmxUtils.unregisterMbean | public static void unregisterMbean(MBeanServer server, ObjectName name) {
try {
server.unregisterMBean(name);
} catch(Exception e) {
logger.error("Error unregistering mbean", e);
}
} | java | public static void unregisterMbean(MBeanServer server, ObjectName name) {
try {
server.unregisterMBean(name);
} catch(Exception e) {
logger.error("Error unregistering mbean", e);
}
} | [
"public",
"static",
"void",
"unregisterMbean",
"(",
"MBeanServer",
"server",
",",
"ObjectName",
"name",
")",
"{",
"try",
"{",
"server",
".",
"unregisterMBean",
"(",
"name",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"logger",
".",
"error",
... | Unregister the mbean with the given name
@param server The server to unregister from
@param name The name of the mbean to unregister | [
"Unregister",
"the",
"mbean",
"with",
"the",
"given",
"name"
] | train | https://github.com/voldemort/voldemort/blob/a7dbdea58032021361680faacf2782cf981c5332/src/java/voldemort/utils/JmxUtils.java#L333-L339 |
sawano/java-commons | src/main/java/se/sawano/java/commons/lang/validate/Validate.java | Validate.isTrue | public static void isTrue(final boolean expression, final String message, final double value) {
INSTANCE.isTrue(expression, message, value);
} | java | public static void isTrue(final boolean expression, final String message, final double value) {
INSTANCE.isTrue(expression, message, value);
} | [
"public",
"static",
"void",
"isTrue",
"(",
"final",
"boolean",
"expression",
",",
"final",
"String",
"message",
",",
"final",
"double",
"value",
")",
"{",
"INSTANCE",
".",
"isTrue",
"(",
"expression",
",",
"message",
",",
"value",
")",
";",
"}"
] | <p>Validate that the argument condition is {@code true}; otherwise throwing an exception with the specified message. This method is useful when validating according to an arbitrary boolean
expression, such as validating a primitive number or using your own custom validation expression.</p>
<pre>
Validate.isTrue(d > 0.0, "The value must be greater than zero: %s", d);
</pre>
<p>For performance reasons, the double value is passed as a separate parameter and appended to the exception message only in the case of an error.</p>
@param expression
the boolean expression to check
@param message
the {@link String#format(String, Object...)} exception message if invalid, not null
@param value
the value to append to the message when invalid
@throws IllegalArgumentValidationException
if expression is {@code false}
@see #isTrue(boolean)
@see #isTrue(boolean, String, long)
@see #isTrue(boolean, String, Object...) | [
"<p",
">",
"Validate",
"that",
"the",
"argument",
"condition",
"is",
"{",
"@code",
"true",
"}",
";",
"otherwise",
"throwing",
"an",
"exception",
"with",
"the",
"specified",
"message",
".",
"This",
"method",
"is",
"useful",
"when",
"validating",
"according",
... | train | https://github.com/sawano/java-commons/blob/6f219c9e8dec4401dbe528d17ae6ec1ef9c0d284/src/main/java/se/sawano/java/commons/lang/validate/Validate.java#L695-L697 |
JetBrains/xodus | vfs/src/main/java/jetbrains/exodus/vfs/VirtualFileSystem.java | VirtualFileSystem.createFile | @NotNull
public File createFile(@NotNull final Transaction txn, @NotNull String path) {
return doCreateFile(txn, fileDescriptorSequence.getAndIncrement(), path);
} | java | @NotNull
public File createFile(@NotNull final Transaction txn, @NotNull String path) {
return doCreateFile(txn, fileDescriptorSequence.getAndIncrement(), path);
} | [
"@",
"NotNull",
"public",
"File",
"createFile",
"(",
"@",
"NotNull",
"final",
"Transaction",
"txn",
",",
"@",
"NotNull",
"String",
"path",
")",
"{",
"return",
"doCreateFile",
"(",
"txn",
",",
"fileDescriptorSequence",
".",
"getAndIncrement",
"(",
")",
",",
"... | Creates new file inside specified {@linkplain Transaction} with specified path and returns
the {@linkplain File} instance.
@param txn {@linkplain Transaction} instance
@param path file path
@return new {@linkplain File}
@throws FileExistsException if a {@linkplain File} with specified path already exists
@see #createFile(Transaction, long, String)
@see File | [
"Creates",
"new",
"file",
"inside",
"specified",
"{",
"@linkplain",
"Transaction",
"}",
"with",
"specified",
"path",
"and",
"returns",
"the",
"{",
"@linkplain",
"File",
"}",
"instance",
"."
] | train | https://github.com/JetBrains/xodus/blob/7b3476c4e81db66f9c7529148c761605cc8eea6d/vfs/src/main/java/jetbrains/exodus/vfs/VirtualFileSystem.java#L207-L210 |
fuinorg/units4j | src/main/java/org/fuin/units4j/AssertUsage.java | AssertUsage.assertMethodsNotUsed | public static final void assertMethodsNotUsed(final File classesDir, final FileFilter filter, final List<MCAMethod> methodsToFind) {
Utils4J.checkNotNull("classesDir", classesDir);
Utils4J.checkValidDir(classesDir);
Utils4J.checkNotNull("methodsToFind", methodsToFind);
final MethodCallAnalyzer analyzer = new MethodCallAnalyzer(methodsToFind);
analyzer.findCallingMethodsInDir(classesDir, filter);
final List<MCAMethodCall> methodCalls = analyzer.getMethodCalls();
if (methodCalls.size() > 0) {
final StringBuilder sb = new StringBuilder("Illegal method call(s) found:");
for (final MCAMethodCall methodCall : methodCalls) {
sb.append("\n");
sb.append(methodCall);
}
Assert.fail(sb.toString());
}
} | java | public static final void assertMethodsNotUsed(final File classesDir, final FileFilter filter, final List<MCAMethod> methodsToFind) {
Utils4J.checkNotNull("classesDir", classesDir);
Utils4J.checkValidDir(classesDir);
Utils4J.checkNotNull("methodsToFind", methodsToFind);
final MethodCallAnalyzer analyzer = new MethodCallAnalyzer(methodsToFind);
analyzer.findCallingMethodsInDir(classesDir, filter);
final List<MCAMethodCall> methodCalls = analyzer.getMethodCalls();
if (methodCalls.size() > 0) {
final StringBuilder sb = new StringBuilder("Illegal method call(s) found:");
for (final MCAMethodCall methodCall : methodCalls) {
sb.append("\n");
sb.append(methodCall);
}
Assert.fail(sb.toString());
}
} | [
"public",
"static",
"final",
"void",
"assertMethodsNotUsed",
"(",
"final",
"File",
"classesDir",
",",
"final",
"FileFilter",
"filter",
",",
"final",
"List",
"<",
"MCAMethod",
">",
"methodsToFind",
")",
"{",
"Utils4J",
".",
"checkNotNull",
"(",
"\"classesDir\"",
... | Asserts that a set of methods is not used.
@param classesDir
Directory with the ".class" files to check - Cannot be <code>null</code> and must be a valid directory.
@param filter
File filter or NULL (process all '*.class' files).
@param methodsToFind
List of methods to find - Cannot be NULL. | [
"Asserts",
"that",
"a",
"set",
"of",
"methods",
"is",
"not",
"used",
"."
] | train | https://github.com/fuinorg/units4j/blob/29383e30b0f9c246b309e734df9cc63dc5d5499e/src/main/java/org/fuin/units4j/AssertUsage.java#L70-L89 |
apache/flink | flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java | SqlFunctionUtils.splitIndex | public static String splitIndex(String str, String separator, int index) {
if (index < 0) {
return null;
}
String[] values = StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separator);
if (index >= values.length) {
return null;
} else {
return values[index];
}
} | java | public static String splitIndex(String str, String separator, int index) {
if (index < 0) {
return null;
}
String[] values = StringUtils.splitByWholeSeparatorPreserveAllTokens(str, separator);
if (index >= values.length) {
return null;
} else {
return values[index];
}
} | [
"public",
"static",
"String",
"splitIndex",
"(",
"String",
"str",
",",
"String",
"separator",
",",
"int",
"index",
")",
"{",
"if",
"(",
"index",
"<",
"0",
")",
"{",
"return",
"null",
";",
"}",
"String",
"[",
"]",
"values",
"=",
"StringUtils",
".",
"s... | Split target string with custom separator and pick the index-th(start with 0) result.
@param str target string.
@param separator custom separator.
@param index index of the result which you want.
@return the string at the index of split results. | [
"Split",
"target",
"string",
"with",
"custom",
"separator",
"and",
"pick",
"the",
"index",
"-",
"th",
"(",
"start",
"with",
"0",
")",
"result",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/functions/SqlFunctionUtils.java#L310-L320 |
google/closure-compiler | src/com/google/javascript/jscomp/RemoveUnusedCode.java | RemoveUnusedCode.traverseObjectDefinePropertiesLiteral | private void traverseObjectDefinePropertiesLiteral(Node propertyDefinitions, Scope scope) {
for (Node property = propertyDefinitions.getFirstChild();
property != null;
property = property.getNext()) {
if (property.isQuotedString()) {
// Quoted property name counts as a reference to the property and protects it from removal.
markPropertyNameReferenced(property.getString());
traverseNode(property.getOnlyChild(), scope);
} else if (property.isStringKey()) {
Node definition = property.getOnlyChild();
if (NodeUtil.mayHaveSideEffects(definition, compiler)) {
traverseNode(definition, scope);
} else {
considerForIndependentRemoval(
new RemovableBuilder()
.addContinuation(new Continuation(definition, scope))
.buildObjectDefinePropertiesDefinition(property));
}
} else {
// TODO(bradfordcsmith): Maybe report error for anything other than a computed property,
// since getters, setters, and methods don't make much sense in this context.
traverseNode(property, scope);
}
}
} | java | private void traverseObjectDefinePropertiesLiteral(Node propertyDefinitions, Scope scope) {
for (Node property = propertyDefinitions.getFirstChild();
property != null;
property = property.getNext()) {
if (property.isQuotedString()) {
// Quoted property name counts as a reference to the property and protects it from removal.
markPropertyNameReferenced(property.getString());
traverseNode(property.getOnlyChild(), scope);
} else if (property.isStringKey()) {
Node definition = property.getOnlyChild();
if (NodeUtil.mayHaveSideEffects(definition, compiler)) {
traverseNode(definition, scope);
} else {
considerForIndependentRemoval(
new RemovableBuilder()
.addContinuation(new Continuation(definition, scope))
.buildObjectDefinePropertiesDefinition(property));
}
} else {
// TODO(bradfordcsmith): Maybe report error for anything other than a computed property,
// since getters, setters, and methods don't make much sense in this context.
traverseNode(property, scope);
}
}
} | [
"private",
"void",
"traverseObjectDefinePropertiesLiteral",
"(",
"Node",
"propertyDefinitions",
",",
"Scope",
"scope",
")",
"{",
"for",
"(",
"Node",
"property",
"=",
"propertyDefinitions",
".",
"getFirstChild",
"(",
")",
";",
"property",
"!=",
"null",
";",
"proper... | Traverse the object literal passed as the second argument to `Object.defineProperties()`. | [
"Traverse",
"the",
"object",
"literal",
"passed",
"as",
"the",
"second",
"argument",
"to",
"Object",
".",
"defineProperties",
"()",
"."
] | train | https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/RemoveUnusedCode.java#L682-L706 |
alkacon/opencms-core | src/org/opencms/jsp/CmsJspTagInfo.java | CmsJspTagInfo.getDescriptionInfo | public static String getDescriptionInfo(CmsFlexController controller, HttpServletRequest req) {
String result = null;
CmsObject cms = controller.getCmsObject();
try {
CmsJspStandardContextBean contextBean = CmsJspStandardContextBean.getInstance(req);
if (contextBean.isDetailRequest()) {
// this is a request to a detail page
CmsResource res = contextBean.getDetailContent();
// read the description of the detail resource as fall back (may contain mapping from another locale)
result = cms.readPropertyObject(res, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
}
if (result == null) {
// read the title of the requested resource as fall back
result = cms.readPropertyObject(
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_DESCRIPTION,
true).getValue();
}
} catch (CmsException e) {
// NOOP, result will be null
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = "";
}
return result;
} | java | public static String getDescriptionInfo(CmsFlexController controller, HttpServletRequest req) {
String result = null;
CmsObject cms = controller.getCmsObject();
try {
CmsJspStandardContextBean contextBean = CmsJspStandardContextBean.getInstance(req);
if (contextBean.isDetailRequest()) {
// this is a request to a detail page
CmsResource res = contextBean.getDetailContent();
// read the description of the detail resource as fall back (may contain mapping from another locale)
result = cms.readPropertyObject(res, CmsPropertyDefinition.PROPERTY_DESCRIPTION, false).getValue();
}
if (result == null) {
// read the title of the requested resource as fall back
result = cms.readPropertyObject(
cms.getRequestContext().getUri(),
CmsPropertyDefinition.PROPERTY_DESCRIPTION,
true).getValue();
}
} catch (CmsException e) {
// NOOP, result will be null
}
if (CmsStringUtil.isEmptyOrWhitespaceOnly(result)) {
result = "";
}
return result;
} | [
"public",
"static",
"String",
"getDescriptionInfo",
"(",
"CmsFlexController",
"controller",
",",
"HttpServletRequest",
"req",
")",
"{",
"String",
"result",
"=",
"null",
";",
"CmsObject",
"cms",
"=",
"controller",
".",
"getCmsObject",
"(",
")",
";",
"try",
"{",
... | Returns the description of a page delivered from OpenCms, usually used for the <code>description</code> metatag of
a HTML page.<p>
If no description information has been found, the empty String "" is returned.<p>
@param controller the current OpenCms request controller
@param req the current request
@return the description of a page delivered from OpenCms | [
"Returns",
"the",
"description",
"of",
"a",
"page",
"delivered",
"from",
"OpenCms",
"usually",
"used",
"for",
"the",
"<code",
">",
"description<",
"/",
"code",
">",
"metatag",
"of",
"a",
"HTML",
"page",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagInfo.java#L136-L165 |
alkacon/opencms-core | src/org/opencms/db/CmsSecurityManager.java | CmsSecurityManager.deleteAliases | public void deleteAliases(CmsRequestContext context, CmsAliasFilter filter) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.deleteAliases(dbc, context.getCurrentProject(), filter);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e);
} finally {
dbc.clear();
}
} | java | public void deleteAliases(CmsRequestContext context, CmsAliasFilter filter) throws CmsException {
CmsDbContext dbc = m_dbContextFactory.getDbContext(context);
try {
m_driverManager.deleteAliases(dbc, context.getCurrentProject(), filter);
} catch (Exception e) {
dbc.report(null, Messages.get().container(Messages.ERR_DB_OPERATION_0), e);
} finally {
dbc.clear();
}
} | [
"public",
"void",
"deleteAliases",
"(",
"CmsRequestContext",
"context",
",",
"CmsAliasFilter",
"filter",
")",
"throws",
"CmsException",
"{",
"CmsDbContext",
"dbc",
"=",
"m_dbContextFactory",
".",
"getDbContext",
"(",
"context",
")",
";",
"try",
"{",
"m_driverManager... | Deletes alias entries matching a filter.<p>
@param context the request context
@param filter the alias filter
@throws CmsException if something goes wrong | [
"Deletes",
"alias",
"entries",
"matching",
"a",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L1259-L1270 |
netscaler/nitro | src/main/java/com/citrix/netscaler/nitro/resource/config/cs/csvserver_binding.java | csvserver_binding.get | public static csvserver_binding get(nitro_service service, String name) throws Exception{
csvserver_binding obj = new csvserver_binding();
obj.set_name(name);
csvserver_binding response = (csvserver_binding) obj.get_resource(service);
return response;
} | java | public static csvserver_binding get(nitro_service service, String name) throws Exception{
csvserver_binding obj = new csvserver_binding();
obj.set_name(name);
csvserver_binding response = (csvserver_binding) obj.get_resource(service);
return response;
} | [
"public",
"static",
"csvserver_binding",
"get",
"(",
"nitro_service",
"service",
",",
"String",
"name",
")",
"throws",
"Exception",
"{",
"csvserver_binding",
"obj",
"=",
"new",
"csvserver_binding",
"(",
")",
";",
"obj",
".",
"set_name",
"(",
"name",
")",
";",
... | Use this API to fetch csvserver_binding resource of given name . | [
"Use",
"this",
"API",
"to",
"fetch",
"csvserver_binding",
"resource",
"of",
"given",
"name",
"."
] | train | https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/cs/csvserver_binding.java#L268-L273 |
aboutsip/sipstack | sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxy/ProxyHandler.java | ProxyHandler.proxyTo | private void proxyTo(final SipURI destination, final SipRequest msg) {
final Connection connection = this.stack.connect(destination.getHost(), destination.getPort());
final ViaHeader via =
ViaHeader.with().host("127.0.0.1").port(5060).transportUDP().branch(ViaHeader.generateBranch()).build();
msg.addHeaderFirst(via);
connection.send(msg);
} | java | private void proxyTo(final SipURI destination, final SipRequest msg) {
final Connection connection = this.stack.connect(destination.getHost(), destination.getPort());
final ViaHeader via =
ViaHeader.with().host("127.0.0.1").port(5060).transportUDP().branch(ViaHeader.generateBranch()).build();
msg.addHeaderFirst(via);
connection.send(msg);
} | [
"private",
"void",
"proxyTo",
"(",
"final",
"SipURI",
"destination",
",",
"final",
"SipRequest",
"msg",
")",
"{",
"final",
"Connection",
"connection",
"=",
"this",
".",
"stack",
".",
"connect",
"(",
"destination",
".",
"getHost",
"(",
")",
",",
"destination"... | Whenever we proxy a request we must also add a Via-header, which essentially says that the
request went "via this network address using this protocol". The {@link ViaHeader}s are used
for responses to find their way back the exact same path as the request took.
@param destination
@param msg | [
"Whenever",
"we",
"proxy",
"a",
"request",
"we",
"must",
"also",
"add",
"a",
"Via",
"-",
"header",
"which",
"essentially",
"says",
"that",
"the",
"request",
"went",
"via",
"this",
"network",
"address",
"using",
"this",
"protocol",
".",
"The",
"{",
"@link",... | train | https://github.com/aboutsip/sipstack/blob/33f2db1d580738f0385687b0429fab0630118f42/sipstack-example/src/main/java/io/sipstack/example/netty/sip/proxy/ProxyHandler.java#L82-L88 |
square/okhttp | mockwebserver/src/main/java/okhttp3/mockwebserver/MockResponse.java | MockResponse.setChunkedBody | public MockResponse setChunkedBody(String body, int maxChunkSize) {
return setChunkedBody(new Buffer().writeUtf8(body), maxChunkSize);
} | java | public MockResponse setChunkedBody(String body, int maxChunkSize) {
return setChunkedBody(new Buffer().writeUtf8(body), maxChunkSize);
} | [
"public",
"MockResponse",
"setChunkedBody",
"(",
"String",
"body",
",",
"int",
"maxChunkSize",
")",
"{",
"return",
"setChunkedBody",
"(",
"new",
"Buffer",
"(",
")",
".",
"writeUtf8",
"(",
"body",
")",
",",
"maxChunkSize",
")",
";",
"}"
] | Sets the response body to the UTF-8 encoded bytes of {@code body}, chunked every {@code
maxChunkSize} bytes. | [
"Sets",
"the",
"response",
"body",
"to",
"the",
"UTF",
"-",
"8",
"encoded",
"bytes",
"of",
"{"
] | train | https://github.com/square/okhttp/blob/a8c65a822dd6cadd2de7d115bf94adf312e67868/mockwebserver/src/main/java/okhttp3/mockwebserver/MockResponse.java#L225-L227 |
davidcarboni-archive/httpino | src/main/java/com/github/davidcarboni/httpino/Http.java | Http.postJson | public <T> Response<T> postJson(Endpoint endpoint, Object requestMessage, Class<T> responseClass, NameValuePair... headers) throws IOException {
if (requestMessage == null) {
return post(endpoint, responseClass, headers);
} // deal with null case
// Create the request
HttpPost post = new HttpPost(endpoint.url());
post.setHeaders(combineHeaders(headers));
// Add the request message if there is one
post.setEntity(serialiseRequestMessage(requestMessage));
// Send the request and process the response
try (CloseableHttpResponse response = httpClient().execute(post)) {
T body = deserialiseResponseMessage(response, responseClass);
return new Response<>(response.getStatusLine(), body);
}
} | java | public <T> Response<T> postJson(Endpoint endpoint, Object requestMessage, Class<T> responseClass, NameValuePair... headers) throws IOException {
if (requestMessage == null) {
return post(endpoint, responseClass, headers);
} // deal with null case
// Create the request
HttpPost post = new HttpPost(endpoint.url());
post.setHeaders(combineHeaders(headers));
// Add the request message if there is one
post.setEntity(serialiseRequestMessage(requestMessage));
// Send the request and process the response
try (CloseableHttpResponse response = httpClient().execute(post)) {
T body = deserialiseResponseMessage(response, responseClass);
return new Response<>(response.getStatusLine(), body);
}
} | [
"public",
"<",
"T",
">",
"Response",
"<",
"T",
">",
"postJson",
"(",
"Endpoint",
"endpoint",
",",
"Object",
"requestMessage",
",",
"Class",
"<",
"T",
">",
"responseClass",
",",
"NameValuePair",
"...",
"headers",
")",
"throws",
"IOException",
"{",
"if",
"("... | Sends a POST request and returns the response.
@param endpoint The endpoint to send the request to.
@param requestMessage A message to send in the request body. Can be null.
@param responseClass The class to deserialise the Json response to. Can be null if no response message is expected.
@param headers Any additional headers to send with this request. You can use {@link org.apache.http.HttpHeaders} constants for header names.
@param <T> The type to deserialise the response to.
@return A {@link Response} containing the deserialised body, if any.
@throws IOException If an error occurs. | [
"Sends",
"a",
"POST",
"request",
"and",
"returns",
"the",
"response",
"."
] | train | https://github.com/davidcarboni-archive/httpino/blob/a78c91874e6d9b2e452cf3aa68d4fea804d977ca/src/main/java/com/github/davidcarboni/httpino/Http.java#L133-L150 |
jayantk/jklol | src/com/jayantkrish/jklol/util/Assignment.java | Assignment.fromSortedArrays | public static final Assignment fromSortedArrays(int[] vars, Object[] values) {
// Verify that the assignment is sorted and contains no duplicate values.
for (int i = 1; i < vars.length; i++) {
Preconditions.checkArgument(vars[i - 1] < vars[i], "Illegal assignment variable nums: %s %s",
vars[i - 1], vars[i]);
}
return new Assignment(vars, values);
} | java | public static final Assignment fromSortedArrays(int[] vars, Object[] values) {
// Verify that the assignment is sorted and contains no duplicate values.
for (int i = 1; i < vars.length; i++) {
Preconditions.checkArgument(vars[i - 1] < vars[i], "Illegal assignment variable nums: %s %s",
vars[i - 1], vars[i]);
}
return new Assignment(vars, values);
} | [
"public",
"static",
"final",
"Assignment",
"fromSortedArrays",
"(",
"int",
"[",
"]",
"vars",
",",
"Object",
"[",
"]",
"values",
")",
"{",
"// Verify that the assignment is sorted and contains no duplicate values.",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
... | Creates an {@code Assignment} mapping each variable in {@code vars} to
the value at the corresponding index of {@code values}. {@code vars}
must be sorted in ascending order. This method does not copy either
{@code vars} or {@code values}; the caller should not read or modify
either of these arrays after invoking this method.
@param vars
@param values
@return | [
"Creates",
"an",
"{",
"@code",
"Assignment",
"}",
"mapping",
"each",
"variable",
"in",
"{",
"@code",
"vars",
"}",
"to",
"the",
"value",
"at",
"the",
"corresponding",
"index",
"of",
"{",
"@code",
"values",
"}",
".",
"{",
"@code",
"vars",
"}",
"must",
"b... | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/util/Assignment.java#L71-L78 |
UrielCh/ovh-java-sdk | ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java | ApiOvhSms.serviceName_templatesControl_name_PUT | public void serviceName_templatesControl_name_PUT(String serviceName, String name, OvhTemplateControl body) throws IOException {
String qPath = "/sms/{serviceName}/templatesControl/{name}";
StringBuilder sb = path(qPath, serviceName, name);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void serviceName_templatesControl_name_PUT(String serviceName, String name, OvhTemplateControl body) throws IOException {
String qPath = "/sms/{serviceName}/templatesControl/{name}";
StringBuilder sb = path(qPath, serviceName, name);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"serviceName_templatesControl_name_PUT",
"(",
"String",
"serviceName",
",",
"String",
"name",
",",
"OvhTemplateControl",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/sms/{serviceName}/templatesControl/{name}\"",
";",
"StringBuilde... | Alter this object properties
REST: PUT /sms/{serviceName}/templatesControl/{name}
@param body [required] New object properties
@param serviceName [required] The internal name of your SMS offer
@param name [required] Name of the template | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L1621-L1625 |
Omertron/api-themoviedb | src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java | TheMovieDbApi.getTVCredits | public MediaCreditList getTVCredits(int tvID, String language) throws MovieDbException {
return tmdbTv.getTVCredits(tvID, language);
} | java | public MediaCreditList getTVCredits(int tvID, String language) throws MovieDbException {
return tmdbTv.getTVCredits(tvID, language);
} | [
"public",
"MediaCreditList",
"getTVCredits",
"(",
"int",
"tvID",
",",
"String",
"language",
")",
"throws",
"MovieDbException",
"{",
"return",
"tmdbTv",
".",
"getTVCredits",
"(",
"tvID",
",",
"language",
")",
";",
"}"
] | Get the cast & crew information about a TV series.
@param tvID tvID
@param language language
@return
@throws com.omertron.themoviedbapi.MovieDbException | [
"Get",
"the",
"cast",
"&",
"crew",
"information",
"about",
"a",
"TV",
"series",
"."
] | train | https://github.com/Omertron/api-themoviedb/blob/bf132d7c7271734e13b58ba3bc92bba46f220118/src/main/java/com/omertron/themoviedbapi/TheMovieDbApi.java#L1497-L1499 |
hpsa/hpe-application-automation-tools-plugin | src/main/java/com/hp/application/automation/tools/results/projectparser/performance/LrProjectScenarioResults.java | LrProjectScenarioResults.vUserMapInit | public static void vUserMapInit(SortedMap<String, Integer> map) {
map.put("Passed", 0);
map.put("Stopped", 0);
map.put("Failed", 0);
map.put("Count", 0);
map.put("MaxVuserRun", 0);
} | java | public static void vUserMapInit(SortedMap<String, Integer> map) {
map.put("Passed", 0);
map.put("Stopped", 0);
map.put("Failed", 0);
map.put("Count", 0);
map.put("MaxVuserRun", 0);
} | [
"public",
"static",
"void",
"vUserMapInit",
"(",
"SortedMap",
"<",
"String",
",",
"Integer",
">",
"map",
")",
"{",
"map",
".",
"put",
"(",
"\"Passed\"",
",",
"0",
")",
";",
"map",
".",
"put",
"(",
"\"Stopped\"",
",",
"0",
")",
";",
"map",
".",
"put... | initilize vuser maps with required values
@param map the map | [
"initilize",
"vuser",
"maps",
"with",
"required",
"values"
] | train | https://github.com/hpsa/hpe-application-automation-tools-plugin/blob/987536f5551bc76fd028d746a951d1fd72c7567a/src/main/java/com/hp/application/automation/tools/results/projectparser/performance/LrProjectScenarioResults.java#L106-L112 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/TenantUsage.java | TenantUsage.addUsageData | public TenantUsage addUsageData(final String key, final String value) {
getLazyUsageData().put(key, value);
return this;
} | java | public TenantUsage addUsageData(final String key, final String value) {
getLazyUsageData().put(key, value);
return this;
} | [
"public",
"TenantUsage",
"addUsageData",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"getLazyUsageData",
"(",
")",
".",
"put",
"(",
"key",
",",
"value",
")",
";",
"return",
"this",
";",
"}"
] | Add a key and value as usage data to the system usage stats.
@param key
the key to set
@param value
the value to set
@return tenant stats element with new usage added | [
"Add",
"a",
"key",
"and",
"value",
"as",
"usage",
"data",
"to",
"the",
"system",
"usage",
"stats",
"."
] | train | https://github.com/eclipse/hawkbit/blob/9884452ad42f3b4827461606d8a9215c8625a7fe/hawkbit-repository/hawkbit-repository-api/src/main/java/org/eclipse/hawkbit/repository/report/model/TenantUsage.java#L97-L100 |
aws/aws-sdk-java | aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/DescribeTransformJobResult.java | DescribeTransformJobResult.withEnvironment | public DescribeTransformJobResult withEnvironment(java.util.Map<String, String> environment) {
setEnvironment(environment);
return this;
} | java | public DescribeTransformJobResult withEnvironment(java.util.Map<String, String> environment) {
setEnvironment(environment);
return this;
} | [
"public",
"DescribeTransformJobResult",
"withEnvironment",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"environment",
")",
"{",
"setEnvironment",
"(",
"environment",
")",
";",
"return",
"this",
";",
"}"
] | <p>
The environment variables to set in the Docker container. We support up to 16 key and values entries in the map.
</p>
@param environment
The environment variables to set in the Docker container. We support up to 16 key and values entries in
the map.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"The",
"environment",
"variables",
"to",
"set",
"in",
"the",
"Docker",
"container",
".",
"We",
"support",
"up",
"to",
"16",
"key",
"and",
"values",
"entries",
"in",
"the",
"map",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sagemaker/src/main/java/com/amazonaws/services/sagemaker/model/DescribeTransformJobResult.java#L604-L607 |
rolfl/MicroBench | src/main/java/net/tuis/ubench/UBench.java | UBench.addTask | public <T> UBench addTask(String name, Supplier<T> task) {
return addTask(name, task, null);
} | java | public <T> UBench addTask(String name, Supplier<T> task) {
return addTask(name, task, null);
} | [
"public",
"<",
"T",
">",
"UBench",
"addTask",
"(",
"String",
"name",
",",
"Supplier",
"<",
"T",
">",
"task",
")",
"{",
"return",
"addTask",
"(",
"name",
",",
"task",
",",
"null",
")",
";",
"}"
] | Include a named task in to the benchmark.
@param <T>
The type of the return value from the task. It is ignored.
@param name
The name of the task. Only one task with any one name is
allowed.
@param task
The task to perform
@return The same object, for chaining calls. | [
"Include",
"a",
"named",
"task",
"in",
"to",
"the",
"benchmark",
"."
] | train | https://github.com/rolfl/MicroBench/blob/f2bfa92dacd7ea0d6b8eae4d4fe2975139d317ce/src/main/java/net/tuis/ubench/UBench.java#L153-L155 |
cdk/cdk | base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/Mappings.java | Mappings.uniqueBonds | public Mappings uniqueBonds() {
// we need the unique predicate to be reset for each new iterator -
// otherwise multiple iterations are always filtered (seen before)
final int[][] g = GraphUtil.toAdjList(query);
return new Mappings(query, target, new Iterable<int[]>() {
@Override
public Iterator<int[]> iterator() {
return Iterators.filter(iterable.iterator(), new UniqueBondMatches(g));
}
});
} | java | public Mappings uniqueBonds() {
// we need the unique predicate to be reset for each new iterator -
// otherwise multiple iterations are always filtered (seen before)
final int[][] g = GraphUtil.toAdjList(query);
return new Mappings(query, target, new Iterable<int[]>() {
@Override
public Iterator<int[]> iterator() {
return Iterators.filter(iterable.iterator(), new UniqueBondMatches(g));
}
});
} | [
"public",
"Mappings",
"uniqueBonds",
"(",
")",
"{",
"// we need the unique predicate to be reset for each new iterator -",
"// otherwise multiple iterations are always filtered (seen before)",
"final",
"int",
"[",
"]",
"[",
"]",
"g",
"=",
"GraphUtil",
".",
"toAdjList",
"(",
"... | Filter the mappings for those which cover a unique set of bonds in the
target.
@return fluent-api instance
@see #uniqueAtoms() | [
"Filter",
"the",
"mappings",
"for",
"those",
"which",
"cover",
"a",
"unique",
"set",
"of",
"bonds",
"in",
"the",
"target",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/isomorphism/src/main/java/org/openscience/cdk/isomorphism/Mappings.java#L297-L308 |
ACRA/acra | acra-core/src/main/java/org/acra/collector/ConfigurationCollector.java | ConfigurationCollector.getFieldValueName | private Object getFieldValueName(@NonNull Map<String, SparseArray<String>> valueArrays, @NonNull Configuration conf, @NonNull Field f) throws IllegalAccessException {
final String fieldName = f.getName();
switch (fieldName) {
case FIELD_MCC:
case FIELD_MNC:
return f.getInt(conf);
case FIELD_UIMODE:
return activeFlags(valueArrays.get(PREFIX_UI_MODE), f.getInt(conf));
case FIELD_SCREENLAYOUT:
return activeFlags(valueArrays.get(PREFIX_SCREENLAYOUT), f.getInt(conf));
default:
final SparseArray<String> values = valueArrays.get(fieldName.toUpperCase() + '_');
if (values == null) {
// Unknown field, return the raw int as String
return f.getInt(conf);
}
final String value = values.get(f.getInt(conf));
if (value == null) {
// Unknown value, return the raw int as String
return f.getInt(conf);
}
return value;
}
} | java | private Object getFieldValueName(@NonNull Map<String, SparseArray<String>> valueArrays, @NonNull Configuration conf, @NonNull Field f) throws IllegalAccessException {
final String fieldName = f.getName();
switch (fieldName) {
case FIELD_MCC:
case FIELD_MNC:
return f.getInt(conf);
case FIELD_UIMODE:
return activeFlags(valueArrays.get(PREFIX_UI_MODE), f.getInt(conf));
case FIELD_SCREENLAYOUT:
return activeFlags(valueArrays.get(PREFIX_SCREENLAYOUT), f.getInt(conf));
default:
final SparseArray<String> values = valueArrays.get(fieldName.toUpperCase() + '_');
if (values == null) {
// Unknown field, return the raw int as String
return f.getInt(conf);
}
final String value = values.get(f.getInt(conf));
if (value == null) {
// Unknown value, return the raw int as String
return f.getInt(conf);
}
return value;
}
} | [
"private",
"Object",
"getFieldValueName",
"(",
"@",
"NonNull",
"Map",
"<",
"String",
",",
"SparseArray",
"<",
"String",
">",
">",
"valueArrays",
",",
"@",
"NonNull",
"Configuration",
"conf",
",",
"@",
"NonNull",
"Field",
"f",
")",
"throws",
"IllegalAccessExcep... | Retrieve the name of the constant defined in the {@link Configuration}
class which defines the value of a field in a {@link Configuration}
instance.
@param conf The instance of {@link Configuration} where the value is
stored.
@param f The {@link Field} to be inspected in the {@link Configuration}
instance.
@return The value of the field f in instance conf translated to its
constant name.
@throws IllegalAccessException if the supplied field is inaccessible. | [
"Retrieve",
"the",
"name",
"of",
"the",
"constant",
"defined",
"in",
"the",
"{",
"@link",
"Configuration",
"}",
"class",
"which",
"defines",
"the",
"value",
"of",
"a",
"field",
"in",
"a",
"{",
"@link",
"Configuration",
"}",
"instance",
"."
] | train | https://github.com/ACRA/acra/blob/bfa3235ab110328c5ab2f792ddf8ee87be4a32d1/acra-core/src/main/java/org/acra/collector/ConfigurationCollector.java#L201-L225 |
dlemmermann/PreferencesFX | preferencesfx/src/main/java/com/dlsc/preferencesfx/history/History.java | History.doWithoutListeners | public void doWithoutListeners(Setting setting, Runnable action) {
LOGGER.trace(String.format("doWithoutListeners: setting: %s", setting));
setListenerActive(false);
LOGGER.trace("removed listener");
action.run();
LOGGER.trace("performed action");
setListenerActive(true);
LOGGER.trace("add listener back");
} | java | public void doWithoutListeners(Setting setting, Runnable action) {
LOGGER.trace(String.format("doWithoutListeners: setting: %s", setting));
setListenerActive(false);
LOGGER.trace("removed listener");
action.run();
LOGGER.trace("performed action");
setListenerActive(true);
LOGGER.trace("add listener back");
} | [
"public",
"void",
"doWithoutListeners",
"(",
"Setting",
"setting",
",",
"Runnable",
"action",
")",
"{",
"LOGGER",
".",
"trace",
"(",
"String",
".",
"format",
"(",
"\"doWithoutListeners: setting: %s\"",
",",
"setting",
")",
")",
";",
"setListenerActive",
"(",
"fa... | Enables to perform an action, without firing the attached ChangeListener of a Setting.
This is used by undo and redo, since those shouldn't cause a new change to be added.
@param setting the setting, whose ChangeListener should be ignored
@param action the action to be performed | [
"Enables",
"to",
"perform",
"an",
"action",
"without",
"firing",
"the",
"attached",
"ChangeListener",
"of",
"a",
"Setting",
".",
"This",
"is",
"used",
"by",
"undo",
"and",
"redo",
"since",
"those",
"shouldn",
"t",
"cause",
"a",
"new",
"change",
"to",
"be",... | train | https://github.com/dlemmermann/PreferencesFX/blob/e06a49663ec949c2f7eb56e6b5952c030ed42d33/preferencesfx/src/main/java/com/dlsc/preferencesfx/history/History.java#L150-L158 |
knowm/XChange | xchange-simulated/src/main/java/org/knowm/xchange/simulated/MatchingEngine.java | MatchingEngine.marketCostOrProceeds | public BigDecimal marketCostOrProceeds(OrderType orderType, BigDecimal amount) {
BigDecimal remaining = amount;
BigDecimal cost = ZERO;
List<BookLevel> orderbookSide = orderType.equals(BID) ? asks : bids;
for (BookOrder order :
FluentIterable.from(orderbookSide).transformAndConcat(BookLevel::getOrders)) {
BigDecimal available = order.getRemainingAmount();
BigDecimal tradeAmount = remaining.compareTo(available) >= 0 ? available : remaining;
BigDecimal tradeCost = tradeAmount.multiply(order.getLimitPrice());
cost = cost.add(tradeCost);
remaining = remaining.subtract(tradeAmount);
if (remaining.compareTo(ZERO) == 0) return cost;
}
throw new ExchangeException("Insufficient liquidity in book");
} | java | public BigDecimal marketCostOrProceeds(OrderType orderType, BigDecimal amount) {
BigDecimal remaining = amount;
BigDecimal cost = ZERO;
List<BookLevel> orderbookSide = orderType.equals(BID) ? asks : bids;
for (BookOrder order :
FluentIterable.from(orderbookSide).transformAndConcat(BookLevel::getOrders)) {
BigDecimal available = order.getRemainingAmount();
BigDecimal tradeAmount = remaining.compareTo(available) >= 0 ? available : remaining;
BigDecimal tradeCost = tradeAmount.multiply(order.getLimitPrice());
cost = cost.add(tradeCost);
remaining = remaining.subtract(tradeAmount);
if (remaining.compareTo(ZERO) == 0) return cost;
}
throw new ExchangeException("Insufficient liquidity in book");
} | [
"public",
"BigDecimal",
"marketCostOrProceeds",
"(",
"OrderType",
"orderType",
",",
"BigDecimal",
"amount",
")",
"{",
"BigDecimal",
"remaining",
"=",
"amount",
";",
"BigDecimal",
"cost",
"=",
"ZERO",
";",
"List",
"<",
"BookLevel",
">",
"orderbookSide",
"=",
"ord... | Calculates the total cost or proceeds at market price of the specified bid/ask amount.
@param orderType Ask or bid.
@param amount The amount.
@return The market cost/proceeds
@throws ExchangeException If there is insufficient liquidity. | [
"Calculates",
"the",
"total",
"cost",
"or",
"proceeds",
"at",
"market",
"price",
"of",
"the",
"specified",
"bid",
"/",
"ask",
"amount",
"."
] | train | https://github.com/knowm/XChange/blob/e45f437ac8e0b89cd66cdcb3258bdb1bf3d88186/xchange-simulated/src/main/java/org/knowm/xchange/simulated/MatchingEngine.java#L187-L201 |
jnidzwetzki/bitfinex-v2-wss-api-java | src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java | BitfinexSymbols.rawOrderBook | public static BitfinexOrderBookSymbol rawOrderBook(final String currency, final String profitCurrency) {
final String currencyNonNull = Objects.requireNonNull(currency).toUpperCase();
final String profitCurrencyNonNull = Objects.requireNonNull(profitCurrency).toUpperCase();
return rawOrderBook(BitfinexCurrencyPair.of(currencyNonNull, profitCurrencyNonNull));
} | java | public static BitfinexOrderBookSymbol rawOrderBook(final String currency, final String profitCurrency) {
final String currencyNonNull = Objects.requireNonNull(currency).toUpperCase();
final String profitCurrencyNonNull = Objects.requireNonNull(profitCurrency).toUpperCase();
return rawOrderBook(BitfinexCurrencyPair.of(currencyNonNull, profitCurrencyNonNull));
} | [
"public",
"static",
"BitfinexOrderBookSymbol",
"rawOrderBook",
"(",
"final",
"String",
"currency",
",",
"final",
"String",
"profitCurrency",
")",
"{",
"final",
"String",
"currencyNonNull",
"=",
"Objects",
".",
"requireNonNull",
"(",
"currency",
")",
".",
"toUpperCas... | Returns symbol for raw order book channel
@param currency of raw order book channel
@param profitCurrency of raw order book channel
@return symbol | [
"Returns",
"symbol",
"for",
"raw",
"order",
"book",
"channel"
] | train | https://github.com/jnidzwetzki/bitfinex-v2-wss-api-java/blob/2e6adf1eb6f8cd4c8722f1619f78ab2cc3c600ee/src/main/java/com/github/jnidzwetzki/bitfinex/v2/symbol/BitfinexSymbols.java#L118-L123 |
hypfvieh/java-utils | src/main/java/com/github/hypfvieh/system/NativeLibraryLoader.java | NativeLibraryLoader.loadFromStream | private Throwable loadFromStream(String _fileNameWithPath, InputStream _libAsStream) {
String fileExt = getFileExtension(_fileNameWithPath);
String prefix = _fileNameWithPath.replace(new File(_fileNameWithPath).getParent(), "").replace("." + fileExt, "");
// extract the library
try {
File tmpFile = extractToTemp(_libAsStream, prefix, fileExt);
Throwable loadLibErr = loadLib(tmpFile.getAbsolutePath());
if (loadLibErr != null) {
return loadLibErr;
}
} catch (Exception _ex) {
return _ex;
}
return null;
} | java | private Throwable loadFromStream(String _fileNameWithPath, InputStream _libAsStream) {
String fileExt = getFileExtension(_fileNameWithPath);
String prefix = _fileNameWithPath.replace(new File(_fileNameWithPath).getParent(), "").replace("." + fileExt, "");
// extract the library
try {
File tmpFile = extractToTemp(_libAsStream, prefix, fileExt);
Throwable loadLibErr = loadLib(tmpFile.getAbsolutePath());
if (loadLibErr != null) {
return loadLibErr;
}
} catch (Exception _ex) {
return _ex;
}
return null;
} | [
"private",
"Throwable",
"loadFromStream",
"(",
"String",
"_fileNameWithPath",
",",
"InputStream",
"_libAsStream",
")",
"{",
"String",
"fileExt",
"=",
"getFileExtension",
"(",
"_fileNameWithPath",
")",
";",
"String",
"prefix",
"=",
"_fileNameWithPath",
".",
"replace",
... | Loads a library from the given stream, using the given filename (including path).
@param _fileNameWithPath filename with path
@param _libAsStream library is input stream
@return {@link Throwable} if any Exception/Error occurs, null otherwise | [
"Loads",
"a",
"library",
"from",
"the",
"given",
"stream",
"using",
"the",
"given",
"filename",
"(",
"including",
"path",
")",
"."
] | train | https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/system/NativeLibraryLoader.java#L153-L169 |
jMotif/SAX | src/main/java/net/seninp/jmotif/sax/TSProcessor.java | TSProcessor.num2index | public int num2index(double value, double[] cuts) {
int count = 0;
while ((count < cuts.length) && (cuts[count] <= value)) {
count++;
}
return count;
} | java | public int num2index(double value, double[] cuts) {
int count = 0;
while ((count < cuts.length) && (cuts[count] <= value)) {
count++;
}
return count;
} | [
"public",
"int",
"num2index",
"(",
"double",
"value",
",",
"double",
"[",
"]",
"cuts",
")",
"{",
"int",
"count",
"=",
"0",
";",
"while",
"(",
"(",
"count",
"<",
"cuts",
".",
"length",
")",
"&&",
"(",
"cuts",
"[",
"count",
"]",
"<=",
"value",
")",... | Get mapping of number to cut index.
@param value the value to map.
@param cuts the array of intervals.
@return character corresponding to numeric value. | [
"Get",
"mapping",
"of",
"number",
"to",
"cut",
"index",
"."
] | train | https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/TSProcessor.java#L427-L433 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java | JBBPTextWriter.Int | public JBBPTextWriter Int(final int[] values, int off, int len) throws IOException {
while (len-- > 0) {
this.Int(values[off++]);
}
return this;
} | java | public JBBPTextWriter Int(final int[] values, int off, int len) throws IOException {
while (len-- > 0) {
this.Int(values[off++]);
}
return this;
} | [
"public",
"JBBPTextWriter",
"Int",
"(",
"final",
"int",
"[",
"]",
"values",
",",
"int",
"off",
",",
"int",
"len",
")",
"throws",
"IOException",
"{",
"while",
"(",
"len",
"--",
">",
"0",
")",
"{",
"this",
".",
"Int",
"(",
"values",
"[",
"off",
"++",... | Print values from integer array.
@param values integer array, must not be null
@param off offset to the first element in array
@param len number of elements to print
@return the context
@throws IOException it will be thrown for transport error | [
"Print",
"values",
"from",
"integer",
"array",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPTextWriter.java#L1050-L1055 |
Alluxio/alluxio | core/common/src/main/java/alluxio/util/CommonUtils.java | CommonUtils.argsToString | public static <T> String argsToString(String separator, T... args) {
StringBuilder sb = new StringBuilder();
for (T s : args) {
if (sb.length() != 0) {
sb.append(separator);
}
sb.append(s);
}
return sb.toString();
} | java | public static <T> String argsToString(String separator, T... args) {
StringBuilder sb = new StringBuilder();
for (T s : args) {
if (sb.length() != 0) {
sb.append(separator);
}
sb.append(s);
}
return sb.toString();
} | [
"public",
"static",
"<",
"T",
">",
"String",
"argsToString",
"(",
"String",
"separator",
",",
"T",
"...",
"args",
")",
"{",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"for",
"(",
"T",
"s",
":",
"args",
")",
"{",
"if",
"(",
"... | Converts varargs of objects to a string.
@param separator separator string
@param args variable arguments
@param <T> type of the objects
@return concatenation of the string representation returned by Object#toString
of the individual objects | [
"Converts",
"varargs",
"of",
"objects",
"to",
"a",
"string",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/util/CommonUtils.java#L132-L141 |
facebookarchive/hadoop-20 | src/core/org/apache/hadoop/util/LineReader.java | LineReader.readLine | public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
} | java | public int readLine(Text str) throws IOException {
return readLine(str, Integer.MAX_VALUE, Integer.MAX_VALUE);
} | [
"public",
"int",
"readLine",
"(",
"Text",
"str",
")",
"throws",
"IOException",
"{",
"return",
"readLine",
"(",
"str",
",",
"Integer",
".",
"MAX_VALUE",
",",
"Integer",
".",
"MAX_VALUE",
")",
";",
"}"
] | Read from the InputStream into the given Text.
@param str the object to store the given line
@return the number of bytes read including the newline
@throws IOException if the underlying stream throws | [
"Read",
"from",
"the",
"InputStream",
"into",
"the",
"given",
"Text",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/util/LineReader.java#L311-L313 |
alkacon/opencms-core | src/org/opencms/search/CmsSearchIndex.java | CmsSearchIndex.getDocument | public I_CmsSearchDocument getDocument(String field, String term) {
Document result = null;
IndexSearcher searcher = getSearcher();
if (searcher != null) {
// search for an exact match on the selected field
Term resultTerm = new Term(field, term);
try {
TopDocs hits = searcher.search(new TermQuery(resultTerm), 1);
if (hits.scoreDocs.length > 0) {
result = searcher.doc(hits.scoreDocs[0].doc);
}
} catch (IOException e) {
// ignore, return null and assume document was not found
}
}
if (result != null) {
return new CmsLuceneDocument(result);
}
return null;
} | java | public I_CmsSearchDocument getDocument(String field, String term) {
Document result = null;
IndexSearcher searcher = getSearcher();
if (searcher != null) {
// search for an exact match on the selected field
Term resultTerm = new Term(field, term);
try {
TopDocs hits = searcher.search(new TermQuery(resultTerm), 1);
if (hits.scoreDocs.length > 0) {
result = searcher.doc(hits.scoreDocs[0].doc);
}
} catch (IOException e) {
// ignore, return null and assume document was not found
}
}
if (result != null) {
return new CmsLuceneDocument(result);
}
return null;
} | [
"public",
"I_CmsSearchDocument",
"getDocument",
"(",
"String",
"field",
",",
"String",
"term",
")",
"{",
"Document",
"result",
"=",
"null",
";",
"IndexSearcher",
"searcher",
"=",
"getSearcher",
"(",
")",
";",
"if",
"(",
"searcher",
"!=",
"null",
")",
"{",
... | Returns the first document where the given term matches the selected index field.<p>
Use this method to search for documents which have unique field values, like a unique id.<p>
@param field the field to search in
@param term the term to search for
@return the first document where the given term matches the selected index field | [
"Returns",
"the",
"first",
"document",
"where",
"the",
"given",
"term",
"matches",
"the",
"selected",
"index",
"field",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/search/CmsSearchIndex.java#L613-L633 |
baratine/baratine | kraken/src/main/java/com/caucho/v5/kelp/segment/OutSegment.java | OutSegment.fsyncImpl | private void fsyncImpl(Result<Boolean> result, FsyncType fsyncType)
{
try {
flushData();
ArrayList<SegmentFsyncCallback> fsyncListeners
= new ArrayList<>(_fsyncListeners);
_fsyncListeners.clear();
Result<Boolean> resultNext = result.then((v,r)->
afterDataFsync(r, _position, fsyncType, fsyncListeners));
if (_isDirty || ! fsyncType.isSchedule()) {
_isDirty = false;
try (OutStore sOut = _readWrite.openWrite(_segment.extent())) {
if (fsyncType.isSchedule()) {
sOut.fsyncSchedule(resultNext);
}
else {
sOut.fsync(resultNext);
}
}
}
else {
resultNext.ok(true);
}
} catch (Throwable e) {
e.printStackTrace();
result.fail(e);
}
} | java | private void fsyncImpl(Result<Boolean> result, FsyncType fsyncType)
{
try {
flushData();
ArrayList<SegmentFsyncCallback> fsyncListeners
= new ArrayList<>(_fsyncListeners);
_fsyncListeners.clear();
Result<Boolean> resultNext = result.then((v,r)->
afterDataFsync(r, _position, fsyncType, fsyncListeners));
if (_isDirty || ! fsyncType.isSchedule()) {
_isDirty = false;
try (OutStore sOut = _readWrite.openWrite(_segment.extent())) {
if (fsyncType.isSchedule()) {
sOut.fsyncSchedule(resultNext);
}
else {
sOut.fsync(resultNext);
}
}
}
else {
resultNext.ok(true);
}
} catch (Throwable e) {
e.printStackTrace();
result.fail(e);
}
} | [
"private",
"void",
"fsyncImpl",
"(",
"Result",
"<",
"Boolean",
">",
"result",
",",
"FsyncType",
"fsyncType",
")",
"{",
"try",
"{",
"flushData",
"(",
")",
";",
"ArrayList",
"<",
"SegmentFsyncCallback",
">",
"fsyncListeners",
"=",
"new",
"ArrayList",
"<>",
"("... | Syncs the segment to the disk. After the segment's data is synced, the
headers can be written. A second sync is needed to complete the header
writes. | [
"Syncs",
"the",
"segment",
"to",
"the",
"disk",
".",
"After",
"the",
"segment",
"s",
"data",
"is",
"synced",
"the",
"headers",
"can",
"be",
"written",
".",
"A",
"second",
"sync",
"is",
"needed",
"to",
"complete",
"the",
"header",
"writes",
"."
] | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kelp/segment/OutSegment.java#L476-L507 |
sailthru/sailthru-java-client | src/main/com/sailthru/client/SailthruClient.java | SailthruClient.cancelSend | public JsonResponse cancelSend(String sendId) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Send.PARAM_SEND_ID, sendId);
return apiDelete(ApiAction.send, data);
} | java | public JsonResponse cancelSend(String sendId) throws IOException {
Map<String, Object> data = new HashMap<String, Object>();
data.put(Send.PARAM_SEND_ID, sendId);
return apiDelete(ApiAction.send, data);
} | [
"public",
"JsonResponse",
"cancelSend",
"(",
"String",
"sendId",
")",
"throws",
"IOException",
"{",
"Map",
"<",
"String",
",",
"Object",
">",
"data",
"=",
"new",
"HashMap",
"<",
"String",
",",
"Object",
">",
"(",
")",
";",
"data",
".",
"put",
"(",
"Sen... | Cancel a send that was scheduled for a future time.
@param sendId
@return JsonResponse
@throws IOException | [
"Cancel",
"a",
"send",
"that",
"was",
"scheduled",
"for",
"a",
"future",
"time",
"."
] | train | https://github.com/sailthru/sailthru-java-client/blob/62b491f6a39b41b836bfc021779200d29b6d2069/src/main/com/sailthru/client/SailthruClient.java#L133-L137 |
aws/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java | ValueMap.withList | public ValueMap withList(String key, List<?> val) {
super.put(key, val == null ? null : new ArrayList<Object>(val));
return this;
} | java | public ValueMap withList(String key, List<?> val) {
super.put(key, val == null ? null : new ArrayList<Object>(val));
return this;
} | [
"public",
"ValueMap",
"withList",
"(",
"String",
"key",
",",
"List",
"<",
"?",
">",
"val",
")",
"{",
"super",
".",
"put",
"(",
"key",
",",
"val",
"==",
"null",
"?",
"null",
":",
"new",
"ArrayList",
"<",
"Object",
">",
"(",
"val",
")",
")",
";",
... | Sets the value of the specified key in the current ValueMap to the
given value. | [
"Sets",
"the",
"value",
"of",
"the",
"specified",
"key",
"in",
"the",
"current",
"ValueMap",
"to",
"the",
"given",
"value",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/document/utils/ValueMap.java#L158-L161 |
ivanceras/orm | src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java | SynchronousEntityManager.insertNoChangeLog | @Override
public <T extends DAO> T insertNoChangeLog(DAO dao, ModelDef model) throws DatabaseException{
DAO ret = db.insert(dao, null, model, null);
Class<? extends DAO> clazz = getDaoClass(dao.getModelName());
return cast(clazz, ret);
} | java | @Override
public <T extends DAO> T insertNoChangeLog(DAO dao, ModelDef model) throws DatabaseException{
DAO ret = db.insert(dao, null, model, null);
Class<? extends DAO> clazz = getDaoClass(dao.getModelName());
return cast(clazz, ret);
} | [
"@",
"Override",
"public",
"<",
"T",
"extends",
"DAO",
">",
"T",
"insertNoChangeLog",
"(",
"DAO",
"dao",
",",
"ModelDef",
"model",
")",
"throws",
"DatabaseException",
"{",
"DAO",
"ret",
"=",
"db",
".",
"insert",
"(",
"dao",
",",
"null",
",",
"model",
"... | Insert the record without bothering changelog, to avoid infinite method recursive calls when inserting changelogs into record_changelog table
@param dao
@param model
@return
@throws DatabaseException | [
"Insert",
"the",
"record",
"without",
"bothering",
"changelog",
"to",
"avoid",
"infinite",
"method",
"recursive",
"calls",
"when",
"inserting",
"changelogs",
"into",
"record_changelog",
"table"
] | train | https://github.com/ivanceras/orm/blob/e63213cb8abefd11df0e2d34b1c95477788e600e/src/main/java/com/ivanceras/db/api/SynchronousEntityManager.java#L301-L306 |
redkale/redkale-plugins | src/org/redkalex/convert/pson/ProtobufReader.java | ProtobufReader.hasNext | @Override
public boolean hasNext(int startPosition, int contentLength) {
//("-------------: " + startPosition + ", " + contentLength + ", " + this.position);
if (startPosition >= 0 && contentLength >= 0) {
return (this.position) < (startPosition + contentLength);
}
return (this.position + 1) < this.content.length;
} | java | @Override
public boolean hasNext(int startPosition, int contentLength) {
//("-------------: " + startPosition + ", " + contentLength + ", " + this.position);
if (startPosition >= 0 && contentLength >= 0) {
return (this.position) < (startPosition + contentLength);
}
return (this.position + 1) < this.content.length;
} | [
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
"int",
"startPosition",
",",
"int",
"contentLength",
")",
"{",
"//(\"-------------: \" + startPosition + \", \" + contentLength + \", \" + this.position);\r",
"if",
"(",
"startPosition",
">=",
"0",
"&&",
"contentLength",
... | 判断对象是否存在下一个属性或者数组是否存在下一个元素
@param startPosition 起始位置
@param contentLength 内容大小, 不确定的传-1
@return 是否存在 | [
"判断对象是否存在下一个属性或者数组是否存在下一个元素"
] | train | https://github.com/redkale/redkale-plugins/blob/a1edfc906a444ae19fe6aababce2957c9b5ea9d2/src/org/redkalex/convert/pson/ProtobufReader.java#L239-L246 |
ironjacamar/ironjacamar | embedded/src/main/java/org/ironjacamar/embedded/byteman/IronJacamarWithByteman.java | IronJacamarWithByteman.createScriptText | private ScriptText createScriptText(int key, BMRule rule)
{
StringBuilder builder = new StringBuilder();
builder.append("# BMUnit autogenerated script: ").append(rule.name());
builder.append("\nRULE ");
builder.append(rule.name());
if (rule.isInterface())
{
builder.append("\nINTERFACE ");
}
else
{
builder.append("\nCLASS ");
}
builder.append(rule.targetClass());
builder.append("\nMETHOD ");
builder.append(rule.targetMethod());
String location = rule.targetLocation();
if (location != null && location.length() > 0)
{
builder.append("\nAT ");
builder.append(location);
}
String binding = rule.binding();
if (binding != null && binding.length() > 0)
{
builder.append("\nBIND ");
builder.append(binding);
}
String helper = rule.helper();
if (helper != null && helper.length() > 0)
{
builder.append("\nHELPER ");
builder.append(helper);
}
builder.append("\nIF ");
builder.append(rule.condition());
builder.append("\nDO ");
builder.append(rule.action());
builder.append("\nENDRULE\n");
return new ScriptText("IronJacamarWithByteman" + key, builder.toString());
} | java | private ScriptText createScriptText(int key, BMRule rule)
{
StringBuilder builder = new StringBuilder();
builder.append("# BMUnit autogenerated script: ").append(rule.name());
builder.append("\nRULE ");
builder.append(rule.name());
if (rule.isInterface())
{
builder.append("\nINTERFACE ");
}
else
{
builder.append("\nCLASS ");
}
builder.append(rule.targetClass());
builder.append("\nMETHOD ");
builder.append(rule.targetMethod());
String location = rule.targetLocation();
if (location != null && location.length() > 0)
{
builder.append("\nAT ");
builder.append(location);
}
String binding = rule.binding();
if (binding != null && binding.length() > 0)
{
builder.append("\nBIND ");
builder.append(binding);
}
String helper = rule.helper();
if (helper != null && helper.length() > 0)
{
builder.append("\nHELPER ");
builder.append(helper);
}
builder.append("\nIF ");
builder.append(rule.condition());
builder.append("\nDO ");
builder.append(rule.action());
builder.append("\nENDRULE\n");
return new ScriptText("IronJacamarWithByteman" + key, builder.toString());
} | [
"private",
"ScriptText",
"createScriptText",
"(",
"int",
"key",
",",
"BMRule",
"rule",
")",
"{",
"StringBuilder",
"builder",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"builder",
".",
"append",
"(",
"\"# BMUnit autogenerated script: \"",
")",
".",
"append",
"("... | Create a ScriptText instance
@param key The key
@param rule The rule
@return The ScriptText instance | [
"Create",
"a",
"ScriptText",
"instance"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/embedded/src/main/java/org/ironjacamar/embedded/byteman/IronJacamarWithByteman.java#L118-L166 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/Drawer.java | Drawer.setHeader | public void setHeader(@NonNull View view, boolean padding, boolean divider, DimenHolder height) {
mDrawerBuilder.getHeaderAdapter().clear();
if (padding) {
mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withHeight(height).withViewPosition(ContainerDrawerItem.Position.TOP));
} else {
mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withHeight(height).withViewPosition(ContainerDrawerItem.Position.NONE));
}
//we need to set the padding so the header starts on top
mDrawerBuilder.mRecyclerView.setPadding(mDrawerBuilder.mRecyclerView.getPaddingLeft(), 0, mDrawerBuilder.mRecyclerView.getPaddingRight(), mDrawerBuilder.mRecyclerView.getPaddingBottom());
} | java | public void setHeader(@NonNull View view, boolean padding, boolean divider, DimenHolder height) {
mDrawerBuilder.getHeaderAdapter().clear();
if (padding) {
mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withHeight(height).withViewPosition(ContainerDrawerItem.Position.TOP));
} else {
mDrawerBuilder.getHeaderAdapter().add(new ContainerDrawerItem().withView(view).withDivider(divider).withHeight(height).withViewPosition(ContainerDrawerItem.Position.NONE));
}
//we need to set the padding so the header starts on top
mDrawerBuilder.mRecyclerView.setPadding(mDrawerBuilder.mRecyclerView.getPaddingLeft(), 0, mDrawerBuilder.mRecyclerView.getPaddingRight(), mDrawerBuilder.mRecyclerView.getPaddingBottom());
} | [
"public",
"void",
"setHeader",
"(",
"@",
"NonNull",
"View",
"view",
",",
"boolean",
"padding",
",",
"boolean",
"divider",
",",
"DimenHolder",
"height",
")",
"{",
"mDrawerBuilder",
".",
"getHeaderAdapter",
"(",
")",
".",
"clear",
"(",
")",
";",
"if",
"(",
... | method to replace a previous set header
@param view
@param padding
@param divider
@param height | [
"method",
"to",
"replace",
"a",
"previous",
"set",
"header"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/Drawer.java#L336-L345 |
BlueBrain/bluima | modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java | Document.setEvents | public void setEvents(int i, Event v) {
if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_events == null)
jcasType.jcas.throwFeatMissing("events", "de.julielab.jules.types.ace.Document");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_events), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_events), i, jcasType.ll_cas.ll_getFSRef(v));} | java | public void setEvents(int i, Event v) {
if (Document_Type.featOkTst && ((Document_Type)jcasType).casFeat_events == null)
jcasType.jcas.throwFeatMissing("events", "de.julielab.jules.types.ace.Document");
jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_events), i);
jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Document_Type)jcasType).casFeatCode_events), i, jcasType.ll_cas.ll_getFSRef(v));} | [
"public",
"void",
"setEvents",
"(",
"int",
"i",
",",
"Event",
"v",
")",
"{",
"if",
"(",
"Document_Type",
".",
"featOkTst",
"&&",
"(",
"(",
"Document_Type",
")",
"jcasType",
")",
".",
"casFeat_events",
"==",
"null",
")",
"jcasType",
".",
"jcas",
".",
"t... | indexed setter for events - sets an indexed value -
@generated
@param i index in the array to set
@param v value to set into the array | [
"indexed",
"setter",
"for",
"events",
"-",
"sets",
"an",
"indexed",
"value",
"-"
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Document.java#L314-L318 |
UrielCh/ovh-java-sdk | ovh-java-sdk-dbaasqueue/src/main/java/net/minidev/ovh/api/ApiOvhDbaasqueue.java | ApiOvhDbaasqueue.serviceName_role_roleName_GET | public OvhRole serviceName_role_roleName_GET(String serviceName, String roleName) throws IOException {
String qPath = "/dbaas/queue/{serviceName}/role/{roleName}";
StringBuilder sb = path(qPath, serviceName, roleName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRole.class);
} | java | public OvhRole serviceName_role_roleName_GET(String serviceName, String roleName) throws IOException {
String qPath = "/dbaas/queue/{serviceName}/role/{roleName}";
StringBuilder sb = path(qPath, serviceName, roleName);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhRole.class);
} | [
"public",
"OvhRole",
"serviceName_role_roleName_GET",
"(",
"String",
"serviceName",
",",
"String",
"roleName",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/dbaas/queue/{serviceName}/role/{roleName}\"",
";",
"StringBuilder",
"sb",
"=",
"path",
"(",
"qPa... | Get a role
REST: GET /dbaas/queue/{serviceName}/role/{roleName}
@param serviceName [required] Application ID
@param roleName [required] Role name
API beta | [
"Get",
"a",
"role"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-dbaasqueue/src/main/java/net/minidev/ovh/api/ApiOvhDbaasqueue.java#L211-L216 |
kkopacz/agiso-core | bundles/agiso-core-lang/src/main/java/org/agiso/core/lang/util/ConvertUtils.java | ConvertUtils.toDigest | public static String toDigest(byte[] bytes, String algorithm) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
byte[] hash = digest.digest();
StringBuffer result = new StringBuffer();
for(int i = 0; i < hash.length; i++) {
String s = Integer.toHexString(hash[i]);
int length = s.length();
if(length >= 2) {
result.append(s.substring(length - 2, length));
} else {
result.append("0");
result.append(s);
}
}
return result.toString();
} | java | public static String toDigest(byte[] bytes, String algorithm) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(bytes);
byte[] hash = digest.digest();
StringBuffer result = new StringBuffer();
for(int i = 0; i < hash.length; i++) {
String s = Integer.toHexString(hash[i]);
int length = s.length();
if(length >= 2) {
result.append(s.substring(length - 2, length));
} else {
result.append("0");
result.append(s);
}
}
return result.toString();
} | [
"public",
"static",
"String",
"toDigest",
"(",
"byte",
"[",
"]",
"bytes",
",",
"String",
"algorithm",
")",
"throws",
"NoSuchAlgorithmException",
"{",
"MessageDigest",
"digest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"\"MD5\"",
")",
";",
"digest",
".",
... | Konwertuje tablicę bajtów na skrót zgodnie z algorytmem określonym przez
parametr wywołania <code>algorithm</code>.
@param bytes Tablica bajtów do konwersji.
@param algorithm Algorytm wyznaczenia skrótu.
@return Łańcuch reprezentujący skrót.
@throws NoSuchAlgorithmException | [
"Konwertuje",
"tablicę",
"bajtów",
"na",
"skrót",
"zgodnie",
"z",
"algorytmem",
"określonym",
"przez",
"parametr",
"wywołania",
"<code",
">",
"algorithm<",
"/",
"code",
">",
"."
] | train | https://github.com/kkopacz/agiso-core/blob/b994ec0146be1fe3f10829d69cd719bdbdebe1c5/bundles/agiso-core-lang/src/main/java/org/agiso/core/lang/util/ConvertUtils.java#L212-L229 |
JavaMoney/jsr354-api | src/main/java/javax/money/Monetary.java | Monetary.isCurrencyAvailable | public static boolean isCurrencyAvailable(Locale locale, String... providers) {
return Objects.nonNull(MONETARY_CURRENCIES_SINGLETON_SPI()) && MONETARY_CURRENCIES_SINGLETON_SPI().isCurrencyAvailable(locale, providers);
} | java | public static boolean isCurrencyAvailable(Locale locale, String... providers) {
return Objects.nonNull(MONETARY_CURRENCIES_SINGLETON_SPI()) && MONETARY_CURRENCIES_SINGLETON_SPI().isCurrencyAvailable(locale, providers);
} | [
"public",
"static",
"boolean",
"isCurrencyAvailable",
"(",
"Locale",
"locale",
",",
"String",
"...",
"providers",
")",
"{",
"return",
"Objects",
".",
"nonNull",
"(",
"MONETARY_CURRENCIES_SINGLETON_SPI",
"(",
")",
")",
"&&",
"MONETARY_CURRENCIES_SINGLETON_SPI",
"(",
... | Allows to check if a {@link javax.money.CurrencyUnit} instance is
defined, i.e. accessible from {@link #getCurrency(String, String...)}.
@param locale the target {@link Locale}, not {@code null}.
@param providers the (optional) specification of providers to consider.
@return {@code true} if {@link #getCurrencies(Locale, String...)} would return a
result containing a currency with the given code. | [
"Allows",
"to",
"check",
"if",
"a",
"{",
"@link",
"javax",
".",
"money",
".",
"CurrencyUnit",
"}",
"instance",
"is",
"defined",
"i",
".",
"e",
".",
"accessible",
"from",
"{",
"@link",
"#getCurrency",
"(",
"String",
"String",
"...",
")",
"}",
"."
] | train | https://github.com/JavaMoney/jsr354-api/blob/49a7ae436eaf45cac1040879185531ef22de5525/src/main/java/javax/money/Monetary.java#L448-L450 |
Mthwate/DatLib | src/main/java/com/mthwate/datlib/math/MathUtils.java | MathUtils.lcm | public static BigInteger lcm(BigInteger a, BigInteger b) {
return lcm(a, b, Calculator.BIG_INTEGER_CALCULATOR);
} | java | public static BigInteger lcm(BigInteger a, BigInteger b) {
return lcm(a, b, Calculator.BIG_INTEGER_CALCULATOR);
} | [
"public",
"static",
"BigInteger",
"lcm",
"(",
"BigInteger",
"a",
",",
"BigInteger",
"b",
")",
"{",
"return",
"lcm",
"(",
"a",
",",
"b",
",",
"Calculator",
".",
"BIG_INTEGER_CALCULATOR",
")",
";",
"}"
] | Gets the least common multiple of 2 numbers.
@since 1.3
@param a the first BigInteger
@param b the second BigInteger
@return the least common multiple as a BigInteger | [
"Gets",
"the",
"least",
"common",
"multiple",
"of",
"2",
"numbers",
"."
] | train | https://github.com/Mthwate/DatLib/blob/f0b3a9f9cf6fdc773d4f86234ebd95986c9b6077/src/main/java/com/mthwate/datlib/math/MathUtils.java#L96-L98 |
facebookarchive/hadoop-20 | src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred/CapacityTaskScheduler.java | CapacityTaskScheduler.assignTasks | @Override
public synchronized List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
TaskTrackerStatus taskTrackerStatus = taskTracker.getStatus();
ClusterStatus c = taskTrackerManager.getClusterStatus();
int mapClusterCapacity = c.getMaxMapTasks();
int reduceClusterCapacity = c.getMaxReduceTasks();
int maxMapSlots = taskTrackerStatus.getMaxMapSlots();
int currentMapSlots = taskTrackerStatus.countOccupiedMapSlots();
int maxReduceSlots = taskTrackerStatus.getMaxReduceSlots();
int currentReduceSlots = taskTrackerStatus.countOccupiedReduceSlots();
LOG.debug("TT asking for task, max maps=" + taskTrackerStatus.getMaxMapSlots() +
", run maps=" + taskTrackerStatus.countMapTasks() + ", max reds=" +
taskTrackerStatus.getMaxReduceSlots() + ", run reds=" +
taskTrackerStatus.countReduceTasks() + ", map cap=" +
mapClusterCapacity + ", red cap = " +
reduceClusterCapacity);
/*
* update all our QSI objects.
* This involves updating each qsi structure. This operation depends
* on the number of running jobs in a queue, and some waiting jobs. If it
* becomes expensive, do it once every few heartbeats only.
*/
updateQSIObjects(mapClusterCapacity, reduceClusterCapacity);
List<Task> result = new ArrayList<Task>();
if (assignMultipleTasks) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
} else {
/*
* If TT has Map and Reduce slot free, we need to figure out whether to
* give it a Map or Reduce task.
* Number of ways to do this. For now, base decision on how much is needed
* versus how much is used (default to Map, if equal).
*/
if ((maxReduceSlots - currentReduceSlots)
> (maxMapSlots - currentMapSlots)) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
if (result.size() == 0) {
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
}
} else {
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
if (result.size() == 0) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
}
}
if (result.size() == 0) {
return null;
}
}
return result;
} | java | @Override
public synchronized List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
TaskTrackerStatus taskTrackerStatus = taskTracker.getStatus();
ClusterStatus c = taskTrackerManager.getClusterStatus();
int mapClusterCapacity = c.getMaxMapTasks();
int reduceClusterCapacity = c.getMaxReduceTasks();
int maxMapSlots = taskTrackerStatus.getMaxMapSlots();
int currentMapSlots = taskTrackerStatus.countOccupiedMapSlots();
int maxReduceSlots = taskTrackerStatus.getMaxReduceSlots();
int currentReduceSlots = taskTrackerStatus.countOccupiedReduceSlots();
LOG.debug("TT asking for task, max maps=" + taskTrackerStatus.getMaxMapSlots() +
", run maps=" + taskTrackerStatus.countMapTasks() + ", max reds=" +
taskTrackerStatus.getMaxReduceSlots() + ", run reds=" +
taskTrackerStatus.countReduceTasks() + ", map cap=" +
mapClusterCapacity + ", red cap = " +
reduceClusterCapacity);
/*
* update all our QSI objects.
* This involves updating each qsi structure. This operation depends
* on the number of running jobs in a queue, and some waiting jobs. If it
* becomes expensive, do it once every few heartbeats only.
*/
updateQSIObjects(mapClusterCapacity, reduceClusterCapacity);
List<Task> result = new ArrayList<Task>();
if (assignMultipleTasks) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
} else {
/*
* If TT has Map and Reduce slot free, we need to figure out whether to
* give it a Map or Reduce task.
* Number of ways to do this. For now, base decision on how much is needed
* versus how much is used (default to Map, if equal).
*/
if ((maxReduceSlots - currentReduceSlots)
> (maxMapSlots - currentMapSlots)) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
if (result.size() == 0) {
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
}
} else {
addMapTask(taskTracker, result, maxMapSlots, currentMapSlots);
if (result.size() == 0) {
addReduceTask(taskTracker, result, maxReduceSlots, currentReduceSlots);
}
}
if (result.size() == 0) {
return null;
}
}
return result;
} | [
"@",
"Override",
"public",
"synchronized",
"List",
"<",
"Task",
">",
"assignTasks",
"(",
"TaskTracker",
"taskTracker",
")",
"throws",
"IOException",
"{",
"TaskTrackerStatus",
"taskTrackerStatus",
"=",
"taskTracker",
".",
"getStatus",
"(",
")",
";",
"ClusterStatus",
... | /*
The grand plan for assigning a task.
If multiple task assignment is enabled, it tries to get one map and
one reduce slot depending on free slots on the TT.
Otherwise, we decide whether a Map or Reduce task should be given to a TT
(if the TT can accept either).
Either way, we first pick a queue. We only look at queues that need
a slot. Among these, we first look at queues whose
(# of running tasks)/capacity is the least.
Next, pick a job in a queue. we pick the job at the front of the queue
unless its user is over the user limit.
Finally, given a job, pick a task from the job. | [
"/",
"*",
"The",
"grand",
"plan",
"for",
"assigning",
"a",
"task",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred/CapacityTaskScheduler.java#L1321-L1374 |
StanKocken/EfficientAdapter | efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java | ViewHelper.setTag | public static void setTag(EfficientCacheView cacheView, int viewId, Object tag) {
View view = cacheView.findViewByIdEfficient(viewId);
if (view != null) {
view.setTag(tag);
}
} | java | public static void setTag(EfficientCacheView cacheView, int viewId, Object tag) {
View view = cacheView.findViewByIdEfficient(viewId);
if (view != null) {
view.setTag(tag);
}
} | [
"public",
"static",
"void",
"setTag",
"(",
"EfficientCacheView",
"cacheView",
",",
"int",
"viewId",
",",
"Object",
"tag",
")",
"{",
"View",
"view",
"=",
"cacheView",
".",
"findViewByIdEfficient",
"(",
"viewId",
")",
";",
"if",
"(",
"view",
"!=",
"null",
")... | Equivalent to calling View.setTag
@param cacheView The cache of views to get the view from
@param viewId The id of the view whose tag should change
@param tag An Object to tag the view with | [
"Equivalent",
"to",
"calling",
"View",
".",
"setTag"
] | train | https://github.com/StanKocken/EfficientAdapter/blob/0bcc3a20182cbce9d7901e1e2a9104251637167d/efficientadapter/src/main/java/com/skocken/efficientadapter/lib/util/ViewHelper.java#L86-L91 |
census-instrumentation/opencensus-java | api/src/main/java/io/opencensus/trace/SpanId.java | SpanId.fromBytes | public static SpanId fromBytes(byte[] src) {
Utils.checkNotNull(src, "src");
// TODO: Remove this extra condition.
Utils.checkArgument(src.length == SIZE, "Invalid size: expected %s, got %s", SIZE, src.length);
return fromBytes(src, 0);
} | java | public static SpanId fromBytes(byte[] src) {
Utils.checkNotNull(src, "src");
// TODO: Remove this extra condition.
Utils.checkArgument(src.length == SIZE, "Invalid size: expected %s, got %s", SIZE, src.length);
return fromBytes(src, 0);
} | [
"public",
"static",
"SpanId",
"fromBytes",
"(",
"byte",
"[",
"]",
"src",
")",
"{",
"Utils",
".",
"checkNotNull",
"(",
"src",
",",
"\"src\"",
")",
";",
"// TODO: Remove this extra condition.",
"Utils",
".",
"checkArgument",
"(",
"src",
".",
"length",
"==",
"S... | Returns a {@code SpanId} built from a byte representation.
@param src the representation of the {@code SpanId}.
@return a {@code SpanId} whose representation is given by the {@code src} parameter.
@throws NullPointerException if {@code src} is null.
@throws IllegalArgumentException if {@code src.length} is not {@link SpanId#SIZE}.
@since 0.5 | [
"Returns",
"a",
"{",
"@code",
"SpanId",
"}",
"built",
"from",
"a",
"byte",
"representation",
"."
] | train | https://github.com/census-instrumentation/opencensus-java/blob/deefac9bed77e40a2297bff1ca5ec5aa48a5f755/api/src/main/java/io/opencensus/trace/SpanId.java#L65-L70 |
grpc/grpc-java | services/src/main/java/io/grpc/services/HealthCheckingLoadBalancerUtil.java | HealthCheckingLoadBalancerUtil.newHealthCheckingLoadBalancer | public static LoadBalancer newHealthCheckingLoadBalancer(Factory factory, Helper helper) {
HealthCheckingLoadBalancerFactory hcFactory =
new HealthCheckingLoadBalancerFactory(
factory, new ExponentialBackoffPolicy.Provider(),
GrpcUtil.STOPWATCH_SUPPLIER);
return hcFactory.newLoadBalancer(helper);
} | java | public static LoadBalancer newHealthCheckingLoadBalancer(Factory factory, Helper helper) {
HealthCheckingLoadBalancerFactory hcFactory =
new HealthCheckingLoadBalancerFactory(
factory, new ExponentialBackoffPolicy.Provider(),
GrpcUtil.STOPWATCH_SUPPLIER);
return hcFactory.newLoadBalancer(helper);
} | [
"public",
"static",
"LoadBalancer",
"newHealthCheckingLoadBalancer",
"(",
"Factory",
"factory",
",",
"Helper",
"helper",
")",
"{",
"HealthCheckingLoadBalancerFactory",
"hcFactory",
"=",
"new",
"HealthCheckingLoadBalancerFactory",
"(",
"factory",
",",
"new",
"ExponentialBack... | Creates a health-checking-capable LoadBalancer. This method is used to implement
health-checking-capable {@link Factory}s, which will typically written this way:
<pre>
public class HealthCheckingFooLbFactory extends LoadBalancer.Factory {
// This is the original balancer implementation that doesn't have health checking
private final LoadBalancer.Factory fooLbFactory;
...
// Returns the health-checking-capable version of FooLb
public LoadBalancer newLoadBalancer(Helper helper) {
return HealthCheckingLoadBalancerUtil.newHealthCheckingLoadBalancer(fooLbFactory, helper);
}
}
</pre>
<p>As a requirement for the original LoadBalancer, it must call
{@code Helper.createSubchannel()} from the {@link
io.grpc.LoadBalancer.Helper#getSynchronizationContext() Synchronization Context}, or
{@code createSubchannel()} will throw.
@param factory the original factory that implements load-balancing logic without health
checking
@param helper the helper passed to the resulting health-checking LoadBalancer. | [
"Creates",
"a",
"health",
"-",
"checking",
"-",
"capable",
"LoadBalancer",
".",
"This",
"method",
"is",
"used",
"to",
"implement",
"health",
"-",
"checking",
"-",
"capable",
"{",
"@link",
"Factory",
"}",
"s",
"which",
"will",
"typically",
"written",
"this",
... | train | https://github.com/grpc/grpc-java/blob/973885457f9609de232d2553b82c67f6c3ff57bf/services/src/main/java/io/grpc/services/HealthCheckingLoadBalancerUtil.java#L63-L69 |
ThreeTen/threetenbp | src/main/java/org/threeten/bp/zone/ZoneRulesBuilder.java | ZoneRulesBuilder.addRuleToWindow | public ZoneRulesBuilder addRuleToWindow(
int year,
Month month,
int dayOfMonthIndicator,
LocalTime time,
boolean timeEndOfDay,
TimeDefinition timeDefinition,
int savingAmountSecs) {
return addRuleToWindow(year, year, month, dayOfMonthIndicator, null, time, timeEndOfDay, timeDefinition, savingAmountSecs);
} | java | public ZoneRulesBuilder addRuleToWindow(
int year,
Month month,
int dayOfMonthIndicator,
LocalTime time,
boolean timeEndOfDay,
TimeDefinition timeDefinition,
int savingAmountSecs) {
return addRuleToWindow(year, year, month, dayOfMonthIndicator, null, time, timeEndOfDay, timeDefinition, savingAmountSecs);
} | [
"public",
"ZoneRulesBuilder",
"addRuleToWindow",
"(",
"int",
"year",
",",
"Month",
"month",
",",
"int",
"dayOfMonthIndicator",
",",
"LocalTime",
"time",
",",
"boolean",
"timeEndOfDay",
",",
"TimeDefinition",
"timeDefinition",
",",
"int",
"savingAmountSecs",
")",
"{"... | Adds a single transition rule to the current window.
<p>
This adds a rule such that the offset, expressed as a daylight savings amount,
changes at the specified date-time.
@param year the year of the transition, from MIN_VALUE to MAX_VALUE
@param month the month of the transition, not null
@param dayOfMonthIndicator the day-of-month of the transition, adjusted by dayOfWeek,
from 1 to 31 adjusted later, or -1 to -28 adjusted earlier from the last day of the month
@param time the time that the transition occurs as defined by timeDefintion, not null
@param timeEndOfDay whether midnight is at the end of day
@param timeDefinition the definition of how to convert local to actual time, not null
@param savingAmountSecs the amount of saving from the standard offset after the transition in seconds
@return this, for chaining
@throws DateTimeException if a date-time field is out of range
@throws IllegalStateException if no window has yet been added
@throws IllegalStateException if the window already has fixed savings
@throws IllegalStateException if the window has reached the maximum capacity of 2000 rules | [
"Adds",
"a",
"single",
"transition",
"rule",
"to",
"the",
"current",
"window",
".",
"<p",
">",
"This",
"adds",
"a",
"rule",
"such",
"that",
"the",
"offset",
"expressed",
"as",
"a",
"daylight",
"savings",
"amount",
"changes",
"at",
"the",
"specified",
"date... | train | https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/zone/ZoneRulesBuilder.java#L222-L231 |
fhoeben/hsac-fitnesse-fixtures | src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java | FirstNonNullHelper.firstNonNull | public static <T, R> R firstNonNull(Function<T, R> function, T[] values) {
return values == null ? null : firstNonNull(function, Stream.of(values));
} | java | public static <T, R> R firstNonNull(Function<T, R> function, T[] values) {
return values == null ? null : firstNonNull(function, Stream.of(values));
} | [
"public",
"static",
"<",
"T",
",",
"R",
">",
"R",
"firstNonNull",
"(",
"Function",
"<",
"T",
",",
"R",
">",
"function",
",",
"T",
"[",
"]",
"values",
")",
"{",
"return",
"values",
"==",
"null",
"?",
"null",
":",
"firstNonNull",
"(",
"function",
","... | Gets first result of function which is not null.
@param <T> type of values.
@param <R> element to return.
@param function function to apply to each value.
@param values all possible values to apply function to.
@return first result which was not null,
OR <code>null</code> if either result for all values was <code>null</code> or values was <code>null</code>. | [
"Gets",
"first",
"result",
"of",
"function",
"which",
"is",
"not",
"null",
"."
] | train | https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/FirstNonNullHelper.java#L36-L38 |
facebookarchive/hadoop-20 | src/mapred/org/apache/hadoop/mapred/TaskTracker.java | TaskTracker.shuffleError | public synchronized void shuffleError(TaskAttemptID taskId, String message)
throws IOException {
LOG.fatal("Task: " + taskId + " - Killed due to Shuffle Failure: " + message);
TaskInProgress tip = runningTasks.get(taskId);
if (tip != null) {
tip.reportDiagnosticInfo("Shuffle Error: " + message);
purgeTask(tip, true);
}
} | java | public synchronized void shuffleError(TaskAttemptID taskId, String message)
throws IOException {
LOG.fatal("Task: " + taskId + " - Killed due to Shuffle Failure: " + message);
TaskInProgress tip = runningTasks.get(taskId);
if (tip != null) {
tip.reportDiagnosticInfo("Shuffle Error: " + message);
purgeTask(tip, true);
}
} | [
"public",
"synchronized",
"void",
"shuffleError",
"(",
"TaskAttemptID",
"taskId",
",",
"String",
"message",
")",
"throws",
"IOException",
"{",
"LOG",
".",
"fatal",
"(",
"\"Task: \"",
"+",
"taskId",
"+",
"\" - Killed due to Shuffle Failure: \"",
"+",
"message",
")",
... | A reduce-task failed to shuffle the map-outputs. Kill the task. | [
"A",
"reduce",
"-",
"task",
"failed",
"to",
"shuffle",
"the",
"map",
"-",
"outputs",
".",
"Kill",
"the",
"task",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskTracker.java#L3698-L3706 |
Azure/azure-sdk-for-java | keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java | KeyVaultClientBaseImpl.updateStorageAccountAsync | public Observable<StorageBundle> updateStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
} | java | public Observable<StorageBundle> updateStorageAccountAsync(String vaultBaseUrl, String storageAccountName) {
return updateStorageAccountWithServiceResponseAsync(vaultBaseUrl, storageAccountName).map(new Func1<ServiceResponse<StorageBundle>, StorageBundle>() {
@Override
public StorageBundle call(ServiceResponse<StorageBundle> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"StorageBundle",
">",
"updateStorageAccountAsync",
"(",
"String",
"vaultBaseUrl",
",",
"String",
"storageAccountName",
")",
"{",
"return",
"updateStorageAccountWithServiceResponseAsync",
"(",
"vaultBaseUrl",
",",
"storageAccountName",
")",
".",
... | Updates the specified attributes associated with the given storage account. This operation requires the storage/set/update permission.
@param vaultBaseUrl The vault name, for example https://myvault.vault.azure.net.
@param storageAccountName The name of the storage account.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the StorageBundle object | [
"Updates",
"the",
"specified",
"attributes",
"associated",
"with",
"the",
"given",
"storage",
"account",
".",
"This",
"operation",
"requires",
"the",
"storage",
"/",
"set",
"/",
"update",
"permission",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/keyvault/data-plane/azure-keyvault/src/main/java/com/microsoft/azure/keyvault/implementation/KeyVaultClientBaseImpl.java#L10118-L10125 |
Wikidata/Wikidata-Toolkit | wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/StatementUpdate.java | StatementUpdate.getDatamodelObjectFromResponse | protected <T> T getDatamodelObjectFromResponse(JsonNode response, List<String> path, Class<T> targetClass) throws JsonProcessingException {
if(response == null) {
throw new JsonMappingException("The API response is null");
}
JsonNode currentNode = response;
for(String field : path) {
if (!currentNode.has(field)) {
throw new JsonMappingException("Field '"+field+"' not found in API response.");
}
currentNode = currentNode.path(field);
}
return mapper.treeToValue(currentNode, targetClass);
} | java | protected <T> T getDatamodelObjectFromResponse(JsonNode response, List<String> path, Class<T> targetClass) throws JsonProcessingException {
if(response == null) {
throw new JsonMappingException("The API response is null");
}
JsonNode currentNode = response;
for(String field : path) {
if (!currentNode.has(field)) {
throw new JsonMappingException("Field '"+field+"' not found in API response.");
}
currentNode = currentNode.path(field);
}
return mapper.treeToValue(currentNode, targetClass);
} | [
"protected",
"<",
"T",
">",
"T",
"getDatamodelObjectFromResponse",
"(",
"JsonNode",
"response",
",",
"List",
"<",
"String",
">",
"path",
",",
"Class",
"<",
"T",
">",
"targetClass",
")",
"throws",
"JsonProcessingException",
"{",
"if",
"(",
"response",
"==",
"... | Extracts a particular data model instance from a JSON response
returned by MediaWiki. The location is described by a list of successive
fields to use, from the root to the target object.
@param response
the API response as returned by MediaWiki
@param path
a list of fields from the root to the target object
@return
the parsed POJO object
@throws JsonProcessingException | [
"Extracts",
"a",
"particular",
"data",
"model",
"instance",
"from",
"a",
"JSON",
"response",
"returned",
"by",
"MediaWiki",
".",
"The",
"location",
"is",
"described",
"by",
"a",
"list",
"of",
"successive",
"fields",
"to",
"use",
"from",
"the",
"root",
"to",
... | train | https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/StatementUpdate.java#L623-L635 |
jfinal/jfinal | src/main/java/com/jfinal/config/JFinalConfig.java | JFinalConfig.loadPropertyFile | public Properties loadPropertyFile(String fileName, String encoding) {
prop = new Prop(fileName, encoding);
return prop.getProperties();
} | java | public Properties loadPropertyFile(String fileName, String encoding) {
prop = new Prop(fileName, encoding);
return prop.getProperties();
} | [
"public",
"Properties",
"loadPropertyFile",
"(",
"String",
"fileName",
",",
"String",
"encoding",
")",
"{",
"prop",
"=",
"new",
"Prop",
"(",
"fileName",
",",
"encoding",
")",
";",
"return",
"prop",
".",
"getProperties",
"(",
")",
";",
"}"
] | Load property file.
Example:<br>
loadPropertyFile("db_username_pass.txt", "UTF-8");
@param fileName the file in CLASSPATH or the sub directory of the CLASSPATH
@param encoding the encoding | [
"Load",
"property",
"file",
".",
"Example",
":",
"<br",
">",
"loadPropertyFile",
"(",
"db_username_pass",
".",
"txt",
"UTF",
"-",
"8",
")",
";"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/config/JFinalConfig.java#L104-L107 |
killbilling/recurly-java-library | src/main/java/com/ning/billing/recurly/RecurlyClient.java | RecurlyClient.redeemGiftCard | public GiftCard redeemGiftCard(final String redemptionCode, final String accountCode) {
final GiftCard.Redemption redemptionData = GiftCard.createRedemption(accountCode);
final String url = GiftCards.GIFT_CARDS_RESOURCE + "/" + redemptionCode + "/redeem";
return doPOST(url, redemptionData, GiftCard.class);
} | java | public GiftCard redeemGiftCard(final String redemptionCode, final String accountCode) {
final GiftCard.Redemption redemptionData = GiftCard.createRedemption(accountCode);
final String url = GiftCards.GIFT_CARDS_RESOURCE + "/" + redemptionCode + "/redeem";
return doPOST(url, redemptionData, GiftCard.class);
} | [
"public",
"GiftCard",
"redeemGiftCard",
"(",
"final",
"String",
"redemptionCode",
",",
"final",
"String",
"accountCode",
")",
"{",
"final",
"GiftCard",
".",
"Redemption",
"redemptionData",
"=",
"GiftCard",
".",
"createRedemption",
"(",
"accountCode",
")",
";",
"fi... | Redeem a Gift Card
<p>
@param redemptionCode The redemption code the {@link GiftCard}
@param accountCode The account code for the {@link Account}
@return The updated {@link GiftCard} object as identified by the passed in id | [
"Redeem",
"a",
"Gift",
"Card",
"<p",
">"
] | train | https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1843-L1848 |
netty/netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java | HttpHeaders.getDateHeader | @Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name, Date defaultValue) {
final String value = getHeader(message, name);
Date date = DateFormatter.parseHttpDate(value);
return date != null ? date : defaultValue;
} | java | @Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name, Date defaultValue) {
final String value = getHeader(message, name);
Date date = DateFormatter.parseHttpDate(value);
return date != null ? date : defaultValue;
} | [
"@",
"Deprecated",
"public",
"static",
"Date",
"getDateHeader",
"(",
"HttpMessage",
"message",
",",
"CharSequence",
"name",
",",
"Date",
"defaultValue",
")",
"{",
"final",
"String",
"value",
"=",
"getHeader",
"(",
"message",
",",
"name",
")",
";",
"Date",
"d... | @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
Returns the date header value with the specified header name. If
there are more than one header value for the specified header name, the
first value is returned.
@return the header value or the {@code defaultValue} if there is no such
header or the header value is not a formatted date | [
"@deprecated",
"Use",
"{",
"@link",
"#getTimeMillis",
"(",
"CharSequence",
"long",
")",
"}",
"instead",
"."
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpHeaders.java#L875-L880 |
apiman/apiman | manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java | EsMarshalling.unmarshallAuditEntry | public static AuditEntryBean unmarshallAuditEntry(Map<String, Object> source) {
if (source == null) {
return null;
}
AuditEntryBean bean = new AuditEntryBean();
bean.setId(asLong(source.get("id")));
bean.setOrganizationId(asString(source.get("organizationId")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setData(asString(source.get("data")));
bean.setEntityId(asString(source.get("entityId")));
bean.setEntityType(asEnum(source.get("entityType"), AuditEntityType.class));
bean.setEntityVersion(asString(source.get("entityVersion")));
bean.setWhat(asEnum(source.get("what"), AuditEntryType.class));
bean.setWho(asString(source.get("who")));
postMarshall(bean);
return bean;
} | java | public static AuditEntryBean unmarshallAuditEntry(Map<String, Object> source) {
if (source == null) {
return null;
}
AuditEntryBean bean = new AuditEntryBean();
bean.setId(asLong(source.get("id")));
bean.setOrganizationId(asString(source.get("organizationId")));
bean.setCreatedOn(asDate(source.get("createdOn")));
bean.setData(asString(source.get("data")));
bean.setEntityId(asString(source.get("entityId")));
bean.setEntityType(asEnum(source.get("entityType"), AuditEntityType.class));
bean.setEntityVersion(asString(source.get("entityVersion")));
bean.setWhat(asEnum(source.get("what"), AuditEntryType.class));
bean.setWho(asString(source.get("who")));
postMarshall(bean);
return bean;
} | [
"public",
"static",
"AuditEntryBean",
"unmarshallAuditEntry",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"source",
")",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"AuditEntryBean",
"bean",
"=",
"new",
"AuditEntryBean",
... | Unmarshals the given map source into a bean.
@param source the source
@return the audit entry | [
"Unmarshals",
"the",
"given",
"map",
"source",
"into",
"a",
"bean",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1209-L1225 |
Ellzord/JALSE | src/main/java/jalse/entities/Entities.java | Entities.asType | public static <T extends Entity> T asType(final Entity entity, final Class<T> type) {
return getProxyFactory().proxyOfEntity(entity, type);
} | java | public static <T extends Entity> T asType(final Entity entity, final Class<T> type) {
return getProxyFactory().proxyOfEntity(entity, type);
} | [
"public",
"static",
"<",
"T",
"extends",
"Entity",
">",
"T",
"asType",
"(",
"final",
"Entity",
"entity",
",",
"final",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"getProxyFactory",
"(",
")",
".",
"proxyOfEntity",
"(",
"entity",
",",
"type",
")... | Wraps an Entity as the supplied Entity type. This is a convenience method for
{@link EntityProxyFactory#proxyOfEntity(Entity, Class)}.
@param entity
Entity to wrap.
@param type
Entity type to wrap to.
@return The wrapped Entity.
@see #getProxyFactory() | [
"Wraps",
"an",
"Entity",
"as",
"the",
"supplied",
"Entity",
"type",
".",
"This",
"is",
"a",
"convenience",
"method",
"for",
"{",
"@link",
"EntityProxyFactory#proxyOfEntity",
"(",
"Entity",
"Class",
")",
"}",
"."
] | train | https://github.com/Ellzord/JALSE/blob/43fc6572de9b16eb8474aa21a88b6b2d11291615/src/main/java/jalse/entities/Entities.java#L110-L112 |
liferay/com-liferay-commerce | commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java | CommerceOrderPersistenceImpl.countByG_U_O | @Override
public int countByG_U_O(long groupId, long userId, int orderStatus) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_U_O;
Object[] finderArgs = new Object[] { groupId, userId, orderStatus };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_COUNT_COMMERCEORDER_WHERE);
query.append(_FINDER_COLUMN_G_U_O_GROUPID_2);
query.append(_FINDER_COLUMN_G_U_O_USERID_2);
query.append(_FINDER_COLUMN_G_U_O_ORDERSTATUS_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
qPos.add(userId);
qPos.add(orderStatus);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | java | @Override
public int countByG_U_O(long groupId, long userId, int orderStatus) {
FinderPath finderPath = FINDER_PATH_COUNT_BY_G_U_O;
Object[] finderArgs = new Object[] { groupId, userId, orderStatus };
Long count = (Long)finderCache.getResult(finderPath, finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(4);
query.append(_SQL_COUNT_COMMERCEORDER_WHERE);
query.append(_FINDER_COLUMN_G_U_O_GROUPID_2);
query.append(_FINDER_COLUMN_G_U_O_USERID_2);
query.append(_FINDER_COLUMN_G_U_O_ORDERSTATUS_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(groupId);
qPos.add(userId);
qPos.add(orderStatus);
count = (Long)q.uniqueResult();
finderCache.putResult(finderPath, finderArgs, count);
}
catch (Exception e) {
finderCache.removeResult(finderPath, finderArgs);
throw processException(e);
}
finally {
closeSession(session);
}
}
return count.intValue();
} | [
"@",
"Override",
"public",
"int",
"countByG_U_O",
"(",
"long",
"groupId",
",",
"long",
"userId",
",",
"int",
"orderStatus",
")",
"{",
"FinderPath",
"finderPath",
"=",
"FINDER_PATH_COUNT_BY_G_U_O",
";",
"Object",
"[",
"]",
"finderArgs",
"=",
"new",
"Object",
"[... | Returns the number of commerce orders where groupId = ? and userId = ? and orderStatus = ?.
@param groupId the group ID
@param userId the user ID
@param orderStatus the order status
@return the number of matching commerce orders | [
"Returns",
"the",
"number",
"of",
"commerce",
"orders",
"where",
"groupId",
"=",
"?",
";",
"and",
"userId",
"=",
"?",
";",
"and",
"orderStatus",
"=",
"?",
";",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceOrderPersistenceImpl.java#L4599-L4650 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.rotateAffineYXZ | public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ) {
return rotateAffineYXZ(angleY, angleX, angleZ, thisOrNew());
} | java | public Matrix4f rotateAffineYXZ(float angleY, float angleX, float angleZ) {
return rotateAffineYXZ(angleY, angleX, angleZ, thisOrNew());
} | [
"public",
"Matrix4f",
"rotateAffineYXZ",
"(",
"float",
"angleY",
",",
"float",
"angleX",
",",
"float",
"angleZ",
")",
"{",
"return",
"rotateAffineYXZ",
"(",
"angleY",
",",
"angleX",
",",
"angleZ",
",",
"thisOrNew",
"(",
")",
")",
";",
"}"
] | Apply rotation of <code>angleY</code> radians about the Y axis, followed by a rotation of <code>angleX</code> radians about the X axis and
followed by a rotation of <code>angleZ</code> radians about the Z axis.
<p>
When used with a right-handed coordinate system, the produced rotation will rotate a vector
counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin.
When used with a left-handed coordinate system, the rotation is clockwise.
<p>
This method assumes that <code>this</code> matrix represents an {@link #isAffine() affine} transformation (i.e. its last row is equal to <code>(0, 0, 0, 1)</code>)
and can be used to speed up matrix multiplication if the matrix only represents affine transformations, such as translation, rotation, scaling and shearing (in any combination).
<p>
If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix,
then the new matrix will be <code>M * R</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * R * v</code>, the
rotation will be applied first!
@param angleY
the angle to rotate about Y
@param angleX
the angle to rotate about X
@param angleZ
the angle to rotate about Z
@return a matrix holding the result | [
"Apply",
"rotation",
"of",
"<code",
">",
"angleY<",
"/",
"code",
">",
"radians",
"about",
"the",
"Y",
"axis",
"followed",
"by",
"a",
"rotation",
"of",
"<code",
">",
"angleX<",
"/",
"code",
">",
"radians",
"about",
"the",
"X",
"axis",
"and",
"followed",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L5759-L5761 |
jcuda/jcuda | JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java | JCudaDriver.cuDeviceCanAccessPeer | public static int cuDeviceCanAccessPeer(int canAccessPeer[], CUdevice dev, CUdevice peerDev)
{
return checkResult(cuDeviceCanAccessPeerNative(canAccessPeer, dev, peerDev));
} | java | public static int cuDeviceCanAccessPeer(int canAccessPeer[], CUdevice dev, CUdevice peerDev)
{
return checkResult(cuDeviceCanAccessPeerNative(canAccessPeer, dev, peerDev));
} | [
"public",
"static",
"int",
"cuDeviceCanAccessPeer",
"(",
"int",
"canAccessPeer",
"[",
"]",
",",
"CUdevice",
"dev",
",",
"CUdevice",
"peerDev",
")",
"{",
"return",
"checkResult",
"(",
"cuDeviceCanAccessPeerNative",
"(",
"canAccessPeer",
",",
"dev",
",",
"peerDev",
... | Queries if a device may directly access a peer device's memory.
<pre>
CUresult cuDeviceCanAccessPeer (
int* canAccessPeer,
CUdevice dev,
CUdevice peerDev )
</pre>
<div>
<p>Queries if a device may directly access
a peer device's memory. Returns in <tt>*canAccessPeer</tt> a value
of 1 if contexts on <tt>dev</tt> are capable of directly accessing
memory from contexts on <tt>peerDev</tt> and 0 otherwise. If direct
access of <tt>peerDev</tt> from <tt>dev</tt> is possible, then access
may be enabled on two specific contexts by calling
cuCtxEnablePeerAccess().
</p>
<div>
<span>Note:</span>
<p>Note that this
function may also return error codes from previous, asynchronous
launches.
</p>
</div>
</p>
</div>
@param canAccessPeer Returned access capability
@param dev Device from which allocations on peerDev are to be directly accessed.
@param peerDev Device on which the allocations to be directly accessed by dev reside.
@return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED,
CUDA_ERROR_INVALID_DEVICE
@see JCudaDriver#cuCtxEnablePeerAccess
@see JCudaDriver#cuCtxDisablePeerAccess | [
"Queries",
"if",
"a",
"device",
"may",
"directly",
"access",
"a",
"peer",
"device",
"s",
"memory",
"."
] | train | https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L11538-L11541 |
BlueBrain/bluima | modules/bluima_utils/src/main/java/ch/epfl/bbp/uima/annotationviewer/BlueAnnotationViewGenerator.java | BlueAnnotationViewGenerator.autoGenerateStyleMapFile | public void autoGenerateStyleMapFile(AnalysisEngine aAE, File aStyleMapFile)
throws IOException {
this.autoGenerateStyleMapFile(aAE.getAnalysisEngineMetaData(),
aStyleMapFile);
} | java | public void autoGenerateStyleMapFile(AnalysisEngine aAE, File aStyleMapFile)
throws IOException {
this.autoGenerateStyleMapFile(aAE.getAnalysisEngineMetaData(),
aStyleMapFile);
} | [
"public",
"void",
"autoGenerateStyleMapFile",
"(",
"AnalysisEngine",
"aAE",
",",
"File",
"aStyleMapFile",
")",
"throws",
"IOException",
"{",
"this",
".",
"autoGenerateStyleMapFile",
"(",
"aAE",
".",
"getAnalysisEngineMetaData",
"(",
")",
",",
"aStyleMapFile",
")",
"... | Automatically generates a style map file for the given analysis engine.
The style map will be written to the file <code>aStyleMapFile</code>.
@param aAE
the Analysis Engine whose outputs will be viewed using the
generated style map.
@param aStyleMapFile
file to which autogenerated style map will be written | [
"Automatically",
"generates",
"a",
"style",
"map",
"file",
"for",
"the",
"given",
"analysis",
"engine",
".",
"The",
"style",
"map",
"will",
"be",
"written",
"to",
"the",
"file",
"<code",
">",
"aStyleMapFile<",
"/",
"code",
">",
"."
] | train | https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_utils/src/main/java/ch/epfl/bbp/uima/annotationviewer/BlueAnnotationViewGenerator.java#L383-L387 |
mikepenz/MaterialDrawer | library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java | DrawerUtils.getDrawerItem | public static IDrawerItem getDrawerItem(List<IDrawerItem> drawerItems, Object tag) {
if (tag != null) {
for (IDrawerItem drawerItem : drawerItems) {
if (tag.equals(drawerItem.getTag())) {
return drawerItem;
}
}
}
return null;
} | java | public static IDrawerItem getDrawerItem(List<IDrawerItem> drawerItems, Object tag) {
if (tag != null) {
for (IDrawerItem drawerItem : drawerItems) {
if (tag.equals(drawerItem.getTag())) {
return drawerItem;
}
}
}
return null;
} | [
"public",
"static",
"IDrawerItem",
"getDrawerItem",
"(",
"List",
"<",
"IDrawerItem",
">",
"drawerItems",
",",
"Object",
"tag",
")",
"{",
"if",
"(",
"tag",
"!=",
"null",
")",
"{",
"for",
"(",
"IDrawerItem",
"drawerItem",
":",
"drawerItems",
")",
"{",
"if",
... | gets the drawerItem by a defined tag from a drawerItem list
@param drawerItems
@param tag
@return | [
"gets",
"the",
"drawerItem",
"by",
"a",
"defined",
"tag",
"from",
"a",
"drawerItem",
"list"
] | train | https://github.com/mikepenz/MaterialDrawer/blob/f4fb31635767edead0a01cee7b7588942b89d8d9/library/src/main/java/com/mikepenz/materialdrawer/DrawerUtils.java#L143-L152 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/training/CenterLossOutputLayer.java | CenterLossOutputLayer.computeScore | @Override
public double computeScore(double fullNetRegTerm, boolean training, LayerWorkspaceMgr workspaceMgr) {
if (input == null || labels == null)
throw new IllegalStateException("Cannot calculate score without input and labels " + layerId());
this.fullNetRegTerm = fullNetRegTerm;
INDArray preOut = preOutput2d(training, workspaceMgr);
// center loss has two components
// the first enforces inter-class dissimilarity, the second intra-class dissimilarity (squared l2 norm of differences)
ILossFunction interClassLoss = layerConf().getLossFn();
// calculate the intra-class score component
INDArray centers = params.get(CenterLossParamInitializer.CENTER_KEY);
INDArray l = labels.castTo(centers.dataType()); //Ensure correct dtype (same as params); no-op if already correct dtype
INDArray centersForExamples = l.mmul(centers);
// double intraClassScore = intraClassLoss.computeScore(centersForExamples, input, Activation.IDENTITY.getActivationFunction(), maskArray, false);
INDArray norm2DifferenceSquared = input.sub(centersForExamples).norm2(1);
norm2DifferenceSquared.muli(norm2DifferenceSquared);
double sum = norm2DifferenceSquared.sumNumber().doubleValue();
double lambda = layerConf().getLambda();
double intraClassScore = lambda / 2.0 * sum;
// intraClassScore = intraClassScore * layerConf().getLambda() / 2;
// now calculate the inter-class score component
double interClassScore = interClassLoss.computeScore(getLabels2d(workspaceMgr, ArrayType.FF_WORKING_MEM), preOut, layerConf().getActivationFn(),
maskArray, false);
double score = interClassScore + intraClassScore;
score /= getInputMiniBatchSize();
score += fullNetRegTerm;
this.score = score;
return score;
} | java | @Override
public double computeScore(double fullNetRegTerm, boolean training, LayerWorkspaceMgr workspaceMgr) {
if (input == null || labels == null)
throw new IllegalStateException("Cannot calculate score without input and labels " + layerId());
this.fullNetRegTerm = fullNetRegTerm;
INDArray preOut = preOutput2d(training, workspaceMgr);
// center loss has two components
// the first enforces inter-class dissimilarity, the second intra-class dissimilarity (squared l2 norm of differences)
ILossFunction interClassLoss = layerConf().getLossFn();
// calculate the intra-class score component
INDArray centers = params.get(CenterLossParamInitializer.CENTER_KEY);
INDArray l = labels.castTo(centers.dataType()); //Ensure correct dtype (same as params); no-op if already correct dtype
INDArray centersForExamples = l.mmul(centers);
// double intraClassScore = intraClassLoss.computeScore(centersForExamples, input, Activation.IDENTITY.getActivationFunction(), maskArray, false);
INDArray norm2DifferenceSquared = input.sub(centersForExamples).norm2(1);
norm2DifferenceSquared.muli(norm2DifferenceSquared);
double sum = norm2DifferenceSquared.sumNumber().doubleValue();
double lambda = layerConf().getLambda();
double intraClassScore = lambda / 2.0 * sum;
// intraClassScore = intraClassScore * layerConf().getLambda() / 2;
// now calculate the inter-class score component
double interClassScore = interClassLoss.computeScore(getLabels2d(workspaceMgr, ArrayType.FF_WORKING_MEM), preOut, layerConf().getActivationFn(),
maskArray, false);
double score = interClassScore + intraClassScore;
score /= getInputMiniBatchSize();
score += fullNetRegTerm;
this.score = score;
return score;
} | [
"@",
"Override",
"public",
"double",
"computeScore",
"(",
"double",
"fullNetRegTerm",
",",
"boolean",
"training",
",",
"LayerWorkspaceMgr",
"workspaceMgr",
")",
"{",
"if",
"(",
"input",
"==",
"null",
"||",
"labels",
"==",
"null",
")",
"throw",
"new",
"IllegalS... | Compute score after labels and input have been set.
@param fullNetRegTerm Regularization score term for the entire network
@param training whether score should be calculated at train or test time (this affects things like application of
dropout, etc)
@return score (loss function) | [
"Compute",
"score",
"after",
"labels",
"and",
"input",
"have",
"been",
"set",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/nn/layers/training/CenterLossOutputLayer.java#L59-L96 |
rundeck/rundeck | core/src/main/java/com/dtolabs/rundeck/core/utils/ZipUtil.java | ZipUtil.extractZip | public static void extractZip(final String path, final File dest, final String prefix, final renamer rename,
final streamCopier copier) throws IOException {
FilenameFilter filter = null;
if (null != prefix) {
filter = new FilenameFilter() {
public boolean accept(final File file, final String name) {
return name.startsWith(prefix);
}
};
}
extractZip(path, dest, filter, rename, copier);
} | java | public static void extractZip(final String path, final File dest, final String prefix, final renamer rename,
final streamCopier copier) throws IOException {
FilenameFilter filter = null;
if (null != prefix) {
filter = new FilenameFilter() {
public boolean accept(final File file, final String name) {
return name.startsWith(prefix);
}
};
}
extractZip(path, dest, filter, rename, copier);
} | [
"public",
"static",
"void",
"extractZip",
"(",
"final",
"String",
"path",
",",
"final",
"File",
"dest",
",",
"final",
"String",
"prefix",
",",
"final",
"renamer",
"rename",
",",
"final",
"streamCopier",
"copier",
")",
"throws",
"IOException",
"{",
"FilenameFil... | Extract the zip file to the destination, optionally only the matching files and renaming the files
@param path zip file path
@param dest destination directory to contain files
@param prefix match files within the zip if they have this prefix path, or null selects all files
@param rename renamer instance
@param copier streamCopier instance
@throws IOException on io error | [
"Extract",
"the",
"zip",
"file",
"to",
"the",
"destination",
"optionally",
"only",
"the",
"matching",
"files",
"and",
"renaming",
"the",
"files"
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/ZipUtil.java#L124-L136 |
cdk/cdk | tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java | InChITautomerGenerator.getTautomers | @Deprecated
public List<IAtomContainer> getTautomers(IAtomContainer mol, String inchi) throws CDKException, CloneNotSupportedException {
return getTautomers(mol, inchi, null);
} | java | @Deprecated
public List<IAtomContainer> getTautomers(IAtomContainer mol, String inchi) throws CDKException, CloneNotSupportedException {
return getTautomers(mol, inchi, null);
} | [
"@",
"Deprecated",
"public",
"List",
"<",
"IAtomContainer",
">",
"getTautomers",
"(",
"IAtomContainer",
"mol",
",",
"String",
"inchi",
")",
"throws",
"CDKException",
",",
"CloneNotSupportedException",
"{",
"return",
"getTautomers",
"(",
"mol",
",",
"inchi",
",",
... | This method is slower than recalculating the InChI with {@link #getTautomers(IAtomContainer)} as the mapping
between the two can be found more efficiently.
@param mol
@param inchi
@return
@throws CDKException
@throws CloneNotSupportedException
@deprecated use {@link #getTautomers(IAtomContainer)} directly | [
"This",
"method",
"is",
"slower",
"than",
"recalculating",
"the",
"InChI",
"with",
"{",
"@link",
"#getTautomers",
"(",
"IAtomContainer",
")",
"}",
"as",
"the",
"mapping",
"between",
"the",
"two",
"can",
"be",
"found",
"more",
"efficiently",
"."
] | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/tautomer/src/main/java/org/openscience/cdk/tautomers/InChITautomerGenerator.java#L134-L137 |
exoplatform/jcr | exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java | MultiIndex.createIndex | private void createIndex(final Queue<Callable<Void>> tasks, final NodeDataIndexingIterator iterator,
final NodeData rootNode, final AtomicLong count, final AtomicLong processing) throws IOException,
RepositoryException, InterruptedException
{
while (iterator.hasNext())
{
Callable<Void> task = new Callable<Void>()
{
public Void call() throws Exception
{
createIndex(iterator, rootNode, count, processing);
return null;
}
};
if (!tasks.offer(task))
{
// All threads have tasks to do so we do it ourself
createIndex(iterator, rootNode, count, processing);
}
}
} | java | private void createIndex(final Queue<Callable<Void>> tasks, final NodeDataIndexingIterator iterator,
final NodeData rootNode, final AtomicLong count, final AtomicLong processing) throws IOException,
RepositoryException, InterruptedException
{
while (iterator.hasNext())
{
Callable<Void> task = new Callable<Void>()
{
public Void call() throws Exception
{
createIndex(iterator, rootNode, count, processing);
return null;
}
};
if (!tasks.offer(task))
{
// All threads have tasks to do so we do it ourself
createIndex(iterator, rootNode, count, processing);
}
}
} | [
"private",
"void",
"createIndex",
"(",
"final",
"Queue",
"<",
"Callable",
"<",
"Void",
">",
">",
"tasks",
",",
"final",
"NodeDataIndexingIterator",
"iterator",
",",
"final",
"NodeData",
"rootNode",
",",
"final",
"AtomicLong",
"count",
",",
"final",
"AtomicLong",... | Creates an index.
@param tasks
the queue of existing indexing tasks
@param rootNode
the root node of the index
@param iterator
the NodeDataIndexing iterator
@param count
the number of nodes already indexed.
@throws IOException
if an error occurs while writing to the index.
@throws RepositoryException
if any other error occurs
@throws InterruptedException
if thread was interrupted | [
"Creates",
"an",
"index",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/MultiIndex.java#L2199-L2221 |
baratine/baratine | core/src/main/java/com/caucho/v5/amp/stub/StubClass.java | StubClass.createPin | private MethodAmp createPin(MethodAmp delegate,
Parameter result)
{
Class<?> api = TypeRef.of(result.getParameterizedType())
.to(ResultChain.class)
.param(0)
.rawClass();
return new MethodStubResultPin(delegate, api);
} | java | private MethodAmp createPin(MethodAmp delegate,
Parameter result)
{
Class<?> api = TypeRef.of(result.getParameterizedType())
.to(ResultChain.class)
.param(0)
.rawClass();
return new MethodStubResultPin(delegate, api);
} | [
"private",
"MethodAmp",
"createPin",
"(",
"MethodAmp",
"delegate",
",",
"Parameter",
"result",
")",
"{",
"Class",
"<",
"?",
">",
"api",
"=",
"TypeRef",
".",
"of",
"(",
"result",
".",
"getParameterizedType",
"(",
")",
")",
".",
"to",
"(",
"ResultChain",
"... | /*
private MethodAmp createCopyShim(MethodAmp delegate,
Parameter result)
{
TypeRef resultRef = TypeRef.of(result.getParameterizedType());
TypeRef transferRef = resultRef.to(Result.class).param(0);
ShimConverter<?,?> shim = new ShimConverter(_type, transferRef.rawClass());
return new MethodStubResultCopy(delegate, shim);
} | [
"/",
"*",
"private",
"MethodAmp",
"createCopyShim",
"(",
"MethodAmp",
"delegate",
"Parameter",
"result",
")",
"{",
"TypeRef",
"resultRef",
"=",
"TypeRef",
".",
"of",
"(",
"result",
".",
"getParameterizedType",
"()",
")",
";",
"TypeRef",
"transferRef",
"=",
"re... | train | https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/core/src/main/java/com/caucho/v5/amp/stub/StubClass.java#L650-L659 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java | AbstractAttributeDefinitionBuilder.addArbitraryDescriptor | @SuppressWarnings("deprecation")
public BUILDER addArbitraryDescriptor(String arbitraryDescriptor, ModelNode value) {
if (this.arbitraryDescriptors == null) {
this.arbitraryDescriptors = Collections.singletonMap(arbitraryDescriptor, value);
} else {
if (this.arbitraryDescriptors.size() == 1) {
this.arbitraryDescriptors = new HashMap<>(this.arbitraryDescriptors);
}
arbitraryDescriptors.put(arbitraryDescriptor, value);
}
return (BUILDER) this;
} | java | @SuppressWarnings("deprecation")
public BUILDER addArbitraryDescriptor(String arbitraryDescriptor, ModelNode value) {
if (this.arbitraryDescriptors == null) {
this.arbitraryDescriptors = Collections.singletonMap(arbitraryDescriptor, value);
} else {
if (this.arbitraryDescriptors.size() == 1) {
this.arbitraryDescriptors = new HashMap<>(this.arbitraryDescriptors);
}
arbitraryDescriptors.put(arbitraryDescriptor, value);
}
return (BUILDER) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"public",
"BUILDER",
"addArbitraryDescriptor",
"(",
"String",
"arbitraryDescriptor",
",",
"ModelNode",
"value",
")",
"{",
"if",
"(",
"this",
".",
"arbitraryDescriptors",
"==",
"null",
")",
"{",
"this",
".",
"... | Adds {@link AttributeDefinition#getArbitraryDescriptors() arbitrary descriptor}.
@param arbitraryDescriptor the arbitrary descriptor name.
@param value the value of the arbitrary descriptor.
@return a builder that can be used to continue building the attribute definition | [
"Adds",
"{"
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AbstractAttributeDefinitionBuilder.java#L458-L469 |
LearnLib/automatalib | visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java | DOT.runDOT | public static void runDOT(Reader r, String format, File out) throws IOException {
String[] dotCommand = buildDOTCommand(format, "-o" + out.getAbsolutePath());
try {
ProcessUtil.invokeProcess(dotCommand, r, LOGGER::warn);
} catch (InterruptedException ex) {
LOGGER.error("Interrupted while waiting for 'dot' process to exit.", ex);
}
} | java | public static void runDOT(Reader r, String format, File out) throws IOException {
String[] dotCommand = buildDOTCommand(format, "-o" + out.getAbsolutePath());
try {
ProcessUtil.invokeProcess(dotCommand, r, LOGGER::warn);
} catch (InterruptedException ex) {
LOGGER.error("Interrupted while waiting for 'dot' process to exit.", ex);
}
} | [
"public",
"static",
"void",
"runDOT",
"(",
"Reader",
"r",
",",
"String",
"format",
",",
"File",
"out",
")",
"throws",
"IOException",
"{",
"String",
"[",
"]",
"dotCommand",
"=",
"buildDOTCommand",
"(",
"format",
",",
"\"-o\"",
"+",
"out",
".",
"getAbsoluteP... | Invokes the GraphVIZ DOT utility for rendering graphs, writing output to the specified file.
@param r
the reader from which the GraphVIZ description is read.
@param format
the output format to produce.
@param out
the file to which the output is written.
@throws IOException
if an I/O error occurs reading from the given input or writing to the output file. | [
"Invokes",
"the",
"GraphVIZ",
"DOT",
"utility",
"for",
"rendering",
"graphs",
"writing",
"output",
"to",
"the",
"specified",
"file",
"."
] | train | https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/visualization/dot-visualizer/src/main/java/net/automatalib/visualization/dot/DOT.java#L174-L182 |
OpenLiberty/open-liberty | dev/com.ibm.ws.session.store/src/com/ibm/ws/session/store/common/BackedStore.java | BackedStore.createSession | public ISession createSession(String sessionId, boolean newId) {
//create local variable - JIT performance improvement
final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled();
//need some way to checkForDuplicateCreatedIds or synchronize on some object or something ... look at in-memory
if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
StringBuffer sb = new StringBuffer("id = ").append(sessionId).append(appNameForLogging);
LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[CREATE_SESSION], sb.toString());
}
if (inProcessOfStopping) {
throwException("SessionContext.createWhenStop");
}
BackedSession session = null;
session = createSessionObject(sessionId);
session.updateLastAccessTime(session.getCreationTime());
session.setInsert(); // flag new session for insertion into store
session.setMaxInactiveInterval((int) _smc.getSessionInvalidationTime());
session.setUserName(ANONYMOUS_USER);
_sessions.put(sessionId, session);
// if (session.duplicateIdDetected) { // could happen on zOS if key is defined incorrectly - perhaps doesn't include appname
// // other than that, this really should never happen - duplicate ids should not be generated
// LoggingUtil.SESSION_LOGGER_CORE.logp(Level.WARNING, methodClassName, methodNames[CREATE_SESSION], "Store.createSessionIdAlreadyExists");
// session = null;
// }
if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[CREATE_SESSION], "session = " + session);
}
return session;
} | java | public ISession createSession(String sessionId, boolean newId) {
//create local variable - JIT performance improvement
final boolean isTraceOn = com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled();
//need some way to checkForDuplicateCreatedIds or synchronize on some object or something ... look at in-memory
if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
StringBuffer sb = new StringBuffer("id = ").append(sessionId).append(appNameForLogging);
LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[CREATE_SESSION], sb.toString());
}
if (inProcessOfStopping) {
throwException("SessionContext.createWhenStop");
}
BackedSession session = null;
session = createSessionObject(sessionId);
session.updateLastAccessTime(session.getCreationTime());
session.setInsert(); // flag new session for insertion into store
session.setMaxInactiveInterval((int) _smc.getSessionInvalidationTime());
session.setUserName(ANONYMOUS_USER);
_sessions.put(sessionId, session);
// if (session.duplicateIdDetected) { // could happen on zOS if key is defined incorrectly - perhaps doesn't include appname
// // other than that, this really should never happen - duplicate ids should not be generated
// LoggingUtil.SESSION_LOGGER_CORE.logp(Level.WARNING, methodClassName, methodNames[CREATE_SESSION], "Store.createSessionIdAlreadyExists");
// session = null;
// }
if (isTraceOn && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINER)) {
LoggingUtil.SESSION_LOGGER_WAS.exiting(methodClassName, methodNames[CREATE_SESSION], "session = " + session);
}
return session;
} | [
"public",
"ISession",
"createSession",
"(",
"String",
"sessionId",
",",
"boolean",
"newId",
")",
"{",
"//create local variable - JIT performance improvement",
"final",
"boolean",
"isTraceOn",
"=",
"com",
".",
"ibm",
".",
"websphere",
".",
"ras",
".",
"TraceComponent",... | /*
createSession - ensures that a newly generated id is not a duplicate and
also ensures if another thread just created the session, we return it rather
than creating another. | [
"/",
"*",
"createSession",
"-",
"ensures",
"that",
"a",
"newly",
"generated",
"id",
"is",
"not",
"a",
"duplicate",
"and",
"also",
"ensures",
"if",
"another",
"thread",
"just",
"created",
"the",
"session",
"we",
"return",
"it",
"rather",
"than",
"creating",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session.store/src/com/ibm/ws/session/store/common/BackedStore.java#L229-L257 |
sdl/environment-api | src/main/java/com/fredhopper/lifecycle/AbstractLifeCycle.java | AbstractLifeCycle.publishState | protected void publishState(State from, State to) throws Exception {
final Collection<StateListener> listeners = getStateListeners();
synchronized (listeners) {
for (StateListener listener : listeners) {
listener.stateChanged(from, to);
}
}
} | java | protected void publishState(State from, State to) throws Exception {
final Collection<StateListener> listeners = getStateListeners();
synchronized (listeners) {
for (StateListener listener : listeners) {
listener.stateChanged(from, to);
}
}
} | [
"protected",
"void",
"publishState",
"(",
"State",
"from",
",",
"State",
"to",
")",
"throws",
"Exception",
"{",
"final",
"Collection",
"<",
"StateListener",
">",
"listeners",
"=",
"getStateListeners",
"(",
")",
";",
"synchronized",
"(",
"listeners",
")",
"{",
... | Propagates a change of {@link State} to all the
{@link StateListener}registered with this life cycle
object.
@see #changeState(State, State)
@param from the old state
@param to the new state
@throws Exception if a listener fails to accept the change | [
"Propagates",
"a",
"change",
"of",
"{",
"@link",
"State",
"}",
"to",
"all",
"the",
"{",
"@link",
"StateListener",
"}",
"registered",
"with",
"this",
"life",
"cycle",
"object",
"."
] | train | https://github.com/sdl/environment-api/blob/7ec346022675a21fec301f88ab2856acd1201f7d/src/main/java/com/fredhopper/lifecycle/AbstractLifeCycle.java#L110-L117 |
dbracewell/hermes | hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java | DocumentFactory.fromTokens | public Document fromTokens(@NonNull Iterable<String> tokens, @NonNull Language language) {
StringBuilder content = new StringBuilder();
List<Span> tokenSpans = new ArrayList<>();
for (String token : tokens) {
tokenSpans.add(new Span(content.length(), content.length() + token.length()));
content.append(token);
if (language.usesWhitespace()) {
content.append(" ");
}
}
Document doc = new Document(null, content.toString().trim(), defaultLanguage);
for (int idx = 0; idx < tokenSpans.size(); idx++) {
doc.annotationBuilder()
.type(Types.TOKEN)
.bounds(tokenSpans.get(idx))
.attribute(Types.INDEX, idx).createAttached();
}
doc.getAnnotationSet().setIsCompleted(Types.TOKEN, true, "PROVIDED");
return doc;
} | java | public Document fromTokens(@NonNull Iterable<String> tokens, @NonNull Language language) {
StringBuilder content = new StringBuilder();
List<Span> tokenSpans = new ArrayList<>();
for (String token : tokens) {
tokenSpans.add(new Span(content.length(), content.length() + token.length()));
content.append(token);
if (language.usesWhitespace()) {
content.append(" ");
}
}
Document doc = new Document(null, content.toString().trim(), defaultLanguage);
for (int idx = 0; idx < tokenSpans.size(); idx++) {
doc.annotationBuilder()
.type(Types.TOKEN)
.bounds(tokenSpans.get(idx))
.attribute(Types.INDEX, idx).createAttached();
}
doc.getAnnotationSet().setIsCompleted(Types.TOKEN, true, "PROVIDED");
return doc;
} | [
"public",
"Document",
"fromTokens",
"(",
"@",
"NonNull",
"Iterable",
"<",
"String",
">",
"tokens",
",",
"@",
"NonNull",
"Language",
"language",
")",
"{",
"StringBuilder",
"content",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"List",
"<",
"Span",
">",
"tok... | Creates a document from the given tokens. The language parameter controls how the content of the documents is
created. If the language has whitespace tokens are joined with a single space between them, otherwise no space is
inserted between tokens.
@param tokens the tokens
@param language the language
@return the document | [
"Creates",
"a",
"document",
"from",
"the",
"given",
"tokens",
".",
"The",
"language",
"parameter",
"controls",
"how",
"the",
"content",
"of",
"the",
"documents",
"is",
"created",
".",
"If",
"the",
"language",
"has",
"whitespace",
"tokens",
"are",
"joined",
"... | train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java#L277-L296 |
PureSolTechnologies/parsers | parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratMemo.java | PackratMemo.setMemo | void setMemo(String production, int position, int line, final MemoEntry stackElement) {
Map<String, MemoEntry> map = memo.get(position);
if (map == null) {
map = new HashMap<String, MemoEntry>();
memo.put(position, map);
map.put(production, stackElement);
} else {
if (map.containsKey(production)) {
throw new RuntimeException("We should not set a memo twice. Modifying is needed afterwards.");
}
map.put(production, stackElement);
}
} | java | void setMemo(String production, int position, int line, final MemoEntry stackElement) {
Map<String, MemoEntry> map = memo.get(position);
if (map == null) {
map = new HashMap<String, MemoEntry>();
memo.put(position, map);
map.put(production, stackElement);
} else {
if (map.containsKey(production)) {
throw new RuntimeException("We should not set a memo twice. Modifying is needed afterwards.");
}
map.put(production, stackElement);
}
} | [
"void",
"setMemo",
"(",
"String",
"production",
",",
"int",
"position",
",",
"int",
"line",
",",
"final",
"MemoEntry",
"stackElement",
")",
"{",
"Map",
"<",
"String",
",",
"MemoEntry",
">",
"map",
"=",
"memo",
".",
"get",
"(",
"position",
")",
";",
"if... | This method puts memozation elements into the buffer. It is designed in a
way, that entries, once set, are not changed anymore. This is needed not to
break references!
@param production
@param position
@param stackElement | [
"This",
"method",
"puts",
"memozation",
"elements",
"into",
"the",
"buffer",
".",
"It",
"is",
"designed",
"in",
"a",
"way",
"that",
"entries",
"once",
"set",
"are",
"not",
"changed",
"anymore",
".",
"This",
"is",
"needed",
"not",
"to",
"break",
"references... | train | https://github.com/PureSolTechnologies/parsers/blob/61077223b90d3768ff9445ae13036343c98b63cd/parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratMemo.java#L58-L70 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.