repository_name stringlengths 7 58 | func_path_in_repository stringlengths 18 192 | func_name stringlengths 5 108 | whole_func_string stringlengths 75 3.91k | language stringclasses 1
value | func_code_string stringlengths 75 3.91k | func_code_tokens listlengths 21 629 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 111 306 |
|---|---|---|---|---|---|---|---|---|---|---|
ralscha/wampspring | src/main/java/ch/rasc/wampspring/user/UserEventMessenger.java | UserEventMessenger.sendToUserDirect | public void sendToUserDirect(String topicURI, Object event, String user) {
sendToUsersDirect(topicURI, event, Collections.singleton(user));
} | java | public void sendToUserDirect(String topicURI, Object event, String user) {
sendToUsersDirect(topicURI, event, Collections.singleton(user));
} | [
"public",
"void",
"sendToUserDirect",
"(",
"String",
"topicURI",
",",
"Object",
"event",
",",
"String",
"user",
")",
"{",
"sendToUsersDirect",
"(",
"topicURI",
",",
"event",
",",
"Collections",
".",
"singleton",
"(",
"user",
")",
")",
";",
"}"
] | Send an EventMessage directly to the client specified with the user parameter. If
there is no entry in the {@link SimpUserRegistry} for this user nothing happens.
<p>
In contrast to {@link #sendToUser(String, Object, String)} this method does not
check if the receiver is subscribed to the destination. The
{@link SimpleBrokerMessageHandler} is not involved in sending this message.
@param topicURI the name of the topic
@param event the payload of the {@link EventMessage}
@param user receiver of the EVENT message | [
"Send",
"an",
"EventMessage",
"directly",
"to",
"the",
"client",
"specified",
"with",
"the",
"user",
"parameter",
".",
"If",
"there",
"is",
"no",
"entry",
"in",
"the",
"{",
"@link",
"SimpUserRegistry",
"}",
"for",
"this",
"user",
"nothing",
"happens",
".",
... | train | https://github.com/ralscha/wampspring/blob/7571bb6773b848c580b29890587eb35397bfe5b5/src/main/java/ch/rasc/wampspring/user/UserEventMessenger.java#L217-L219 |
graphhopper/graphhopper | reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java | OSMReader.addBarrierEdge | Collection<EdgeIteratorState> addBarrierEdge(long fromId, long toId, IntsRef inEdgeFlags, long nodeFlags, long wayOsmId) {
IntsRef edgeFlags = IntsRef.deepCopyOf(inEdgeFlags);
// clear blocked directions from flags
for (BooleanEncodedValue accessEnc : encodingManager.getAccessEncFromNodeFlags(nodeFlags)) {
accessEnc.setBool(false, edgeFlags, false);
accessEnc.setBool(true, edgeFlags, false);
}
// add edge
barrierNodeIds.clear();
barrierNodeIds.add(fromId);
barrierNodeIds.add(toId);
return addOSMWay(barrierNodeIds, edgeFlags, wayOsmId);
} | java | Collection<EdgeIteratorState> addBarrierEdge(long fromId, long toId, IntsRef inEdgeFlags, long nodeFlags, long wayOsmId) {
IntsRef edgeFlags = IntsRef.deepCopyOf(inEdgeFlags);
// clear blocked directions from flags
for (BooleanEncodedValue accessEnc : encodingManager.getAccessEncFromNodeFlags(nodeFlags)) {
accessEnc.setBool(false, edgeFlags, false);
accessEnc.setBool(true, edgeFlags, false);
}
// add edge
barrierNodeIds.clear();
barrierNodeIds.add(fromId);
barrierNodeIds.add(toId);
return addOSMWay(barrierNodeIds, edgeFlags, wayOsmId);
} | [
"Collection",
"<",
"EdgeIteratorState",
">",
"addBarrierEdge",
"(",
"long",
"fromId",
",",
"long",
"toId",
",",
"IntsRef",
"inEdgeFlags",
",",
"long",
"nodeFlags",
",",
"long",
"wayOsmId",
")",
"{",
"IntsRef",
"edgeFlags",
"=",
"IntsRef",
".",
"deepCopyOf",
"(... | Add a zero length edge with reduced routing options to the graph. | [
"Add",
"a",
"zero",
"length",
"edge",
"with",
"reduced",
"routing",
"options",
"to",
"the",
"graph",
"."
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/reader-osm/src/main/java/com/graphhopper/reader/osm/OSMReader.java#L843-L855 |
gsi-upm/Shanks | shanks-core/src/main/java/es/upm/dit/gsi/shanks/notification/NotificationManager.java | NotificationManager.addNotification | @SuppressWarnings("unchecked")
public static void addNotification(Event e, String interaction) {
NotificationManager.notifications.add(new InteractionNotification(getNotificationID(),
NotificationManager.sim.getSchedule().getSteps(), e.getLauncher(),
interaction, (List<Object>) e.getAffected()));
logger.fine("New notification added to notifications list. There is currently: " +
notifications.size()+" notifications\n Notification added: "
+NotificationManager.notifications.get(NotificationManager.notifications.size()-1));
} | java | @SuppressWarnings("unchecked")
public static void addNotification(Event e, String interaction) {
NotificationManager.notifications.add(new InteractionNotification(getNotificationID(),
NotificationManager.sim.getSchedule().getSteps(), e.getLauncher(),
interaction, (List<Object>) e.getAffected()));
logger.fine("New notification added to notifications list. There is currently: " +
notifications.size()+" notifications\n Notification added: "
+NotificationManager.notifications.get(NotificationManager.notifications.size()-1));
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"void",
"addNotification",
"(",
"Event",
"e",
",",
"String",
"interaction",
")",
"{",
"NotificationManager",
".",
"notifications",
".",
"add",
"(",
"new",
"InteractionNotification",
"(",
"getN... | Whenever a new event triggers it will use this method to add the corresponding notification
to the notification lists.
@param e
the event that for the notification.
@param interaction | [
"Whenever",
"a",
"new",
"event",
"triggers",
"it",
"will",
"use",
"this",
"method",
"to",
"add",
"the",
"corresponding",
"notification",
"to",
"the",
"notification",
"lists",
"."
] | train | https://github.com/gsi-upm/Shanks/blob/35d87a81c22731f4f83bbd0571c9c6d466bd16be/shanks-core/src/main/java/es/upm/dit/gsi/shanks/notification/NotificationManager.java#L128-L136 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayReader.java | ByteArrayReader.readString | public String readString(String charset) throws IOException {
long len = readInt();
if (len > available())
throw new IOException("Cannot read string of length " + len
+ " bytes when only " + available()
+ " bytes are available");
byte[] raw = new byte[(int) len];
readFully(raw);
if (encode) {
return new String(raw, charset);
}
return new String(raw);
} | java | public String readString(String charset) throws IOException {
long len = readInt();
if (len > available())
throw new IOException("Cannot read string of length " + len
+ " bytes when only " + available()
+ " bytes are available");
byte[] raw = new byte[(int) len];
readFully(raw);
if (encode) {
return new String(raw, charset);
}
return new String(raw);
} | [
"public",
"String",
"readString",
"(",
"String",
"charset",
")",
"throws",
"IOException",
"{",
"long",
"len",
"=",
"readInt",
"(",
")",
";",
"if",
"(",
"len",
">",
"available",
"(",
")",
")",
"throw",
"new",
"IOException",
"(",
"\"Cannot read string of lengt... | Read a String from the array converting using the given character set.
@param charset
@return
@throws IOException | [
"Read",
"a",
"String",
"from",
"the",
"array",
"converting",
"using",
"the",
"given",
"character",
"set",
"."
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/util/ByteArrayReader.java#L249-L264 |
ngageoint/geopackage-core-java | src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java | TileBoundingBoxUtils.tileGridZoomDecrease | public static TileGrid tileGridZoomDecrease(TileGrid tileGrid,
int zoomLevels) {
long minX = tileGridMinZoomDecrease(tileGrid.getMinX(), zoomLevels);
long maxX = tileGridMaxZoomDecrease(tileGrid.getMaxX(), zoomLevels);
long minY = tileGridMinZoomDecrease(tileGrid.getMinY(), zoomLevels);
long maxY = tileGridMaxZoomDecrease(tileGrid.getMaxY(), zoomLevels);
TileGrid newTileGrid = new TileGrid(minX, minY, maxX, maxY);
return newTileGrid;
} | java | public static TileGrid tileGridZoomDecrease(TileGrid tileGrid,
int zoomLevels) {
long minX = tileGridMinZoomDecrease(tileGrid.getMinX(), zoomLevels);
long maxX = tileGridMaxZoomDecrease(tileGrid.getMaxX(), zoomLevels);
long minY = tileGridMinZoomDecrease(tileGrid.getMinY(), zoomLevels);
long maxY = tileGridMaxZoomDecrease(tileGrid.getMaxY(), zoomLevels);
TileGrid newTileGrid = new TileGrid(minX, minY, maxX, maxY);
return newTileGrid;
} | [
"public",
"static",
"TileGrid",
"tileGridZoomDecrease",
"(",
"TileGrid",
"tileGrid",
",",
"int",
"zoomLevels",
")",
"{",
"long",
"minX",
"=",
"tileGridMinZoomDecrease",
"(",
"tileGrid",
".",
"getMinX",
"(",
")",
",",
"zoomLevels",
")",
";",
"long",
"maxX",
"="... | Get the tile grid starting from the tile grid and zooming out /
decreasing the number of levels
@param tileGrid
current tile grid
@param zoomLevels
number of zoom levels to decrease by
@return tile grid at new zoom level
@since 2.0.1 | [
"Get",
"the",
"tile",
"grid",
"starting",
"from",
"the",
"tile",
"grid",
"and",
"zooming",
"out",
"/",
"decreasing",
"the",
"number",
"of",
"levels"
] | train | https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java#L1316-L1324 |
nyla-solutions/nyla | nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/builder/mapped/MappedKeyDirector.java | MappedKeyDirector.constructDocument | public void constructDocument(String id, MappedKeyEngineer<K,V> engineer)
{
try
{
//construct map
Map<K,V> textableMap = this.constructMapToText(id);
engineer.construct(id,textableMap);
}
catch (NoDataFoundException e)
{
throw new SystemException("No textable found for id="+id+" ERROR:"+Debugger.stackTrace(e));
}
} | java | public void constructDocument(String id, MappedKeyEngineer<K,V> engineer)
{
try
{
//construct map
Map<K,V> textableMap = this.constructMapToText(id);
engineer.construct(id,textableMap);
}
catch (NoDataFoundException e)
{
throw new SystemException("No textable found for id="+id+" ERROR:"+Debugger.stackTrace(e));
}
} | [
"public",
"void",
"constructDocument",
"(",
"String",
"id",
",",
"MappedKeyEngineer",
"<",
"K",
",",
"V",
">",
"engineer",
")",
"{",
"try",
"{",
"//construct map\r",
"Map",
"<",
"K",
",",
"V",
">",
"textableMap",
"=",
"this",
".",
"constructMapToText",
"("... | Director method to construct a document
@param id the for construction
@param engineer the strategy creation | [
"Director",
"method",
"to",
"construct",
"a",
"document"
] | train | https://github.com/nyla-solutions/nyla/blob/38d5b843c76eae9762bbca20453ed0f0ad8412a9/nyla.solutions.core/src/main/java/nyla/solutions/core/patterns/creational/builder/mapped/MappedKeyDirector.java#L32-L45 |
future-architect/uroborosql | src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java | DefaultSqlConfig.getConfig | public static SqlConfig getConfig(final String dataSourceName, final boolean autoCommit, final boolean readOnly,
final int transactionIsolation) {
DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSourceName);
connectionSupplier.setDefaultAutoCommit(autoCommit);
connectionSupplier.setDefaultReadOnly(readOnly);
connectionSupplier.setDefaultTransactionIsolation(transactionIsolation);
return new DefaultSqlConfig(connectionSupplier, null);
} | java | public static SqlConfig getConfig(final String dataSourceName, final boolean autoCommit, final boolean readOnly,
final int transactionIsolation) {
DataSourceConnectionSupplierImpl connectionSupplier = new DataSourceConnectionSupplierImpl(dataSourceName);
connectionSupplier.setDefaultAutoCommit(autoCommit);
connectionSupplier.setDefaultReadOnly(readOnly);
connectionSupplier.setDefaultTransactionIsolation(transactionIsolation);
return new DefaultSqlConfig(connectionSupplier, null);
} | [
"public",
"static",
"SqlConfig",
"getConfig",
"(",
"final",
"String",
"dataSourceName",
",",
"final",
"boolean",
"autoCommit",
",",
"final",
"boolean",
"readOnly",
",",
"final",
"int",
"transactionIsolation",
")",
"{",
"DataSourceConnectionSupplierImpl",
"connectionSupp... | データソース名を指定してSqlConfigを取得する
@param dataSourceName データソース名
@param autoCommit 自動コミットの指定
@param readOnly 読み取り専用モードの指定
@param transactionIsolation トランザクション隔離レベルの指定
@return SqlConfigオブジェクト | [
"データソース名を指定してSqlConfigを取得する"
] | train | https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/config/DefaultSqlConfig.java#L225-L232 |
xvik/dropwizard-guicey | src/main/java/ru/vyarus/dropwizard/guice/module/context/ConfigurationInfo.java | ConfigurationInfo.getItems | public <T, K extends ItemInfo> List<Class<T>> getItems(final ConfigItem type, final Predicate<K> filter) {
final List<Class<T>> items = getItems(type);
return filter(items, filter);
} | java | public <T, K extends ItemInfo> List<Class<T>> getItems(final ConfigItem type, final Predicate<K> filter) {
final List<Class<T>> items = getItems(type);
return filter(items, filter);
} | [
"public",
"<",
"T",
",",
"K",
"extends",
"ItemInfo",
">",
"List",
"<",
"Class",
"<",
"T",
">",
">",
"getItems",
"(",
"final",
"ConfigItem",
"type",
",",
"final",
"Predicate",
"<",
"K",
">",
"filter",
")",
"{",
"final",
"List",
"<",
"Class",
"<",
"T... | Used to query items of one configuration type (e.g. only installers or bundles). Some common filters are
predefined in {@link Filters}. Use {@link Predicate#and(Predicate)}, {@link Predicate#or(Predicate)}
and {@link Predicate#negate()} to reuse default filters.
<p>
Pay attention that disabled (or disabled and never registered) items are also returned.
@param type configuration item type
@param filter predicate to filter definitions
@param <T> expected class
@param <K> expected info container class
@return registered item classes in registration order, filtered with provided filter or empty list | [
"Used",
"to",
"query",
"items",
"of",
"one",
"configuration",
"type",
"(",
"e",
".",
"g",
".",
"only",
"installers",
"or",
"bundles",
")",
".",
"Some",
"common",
"filters",
"are",
"predefined",
"in",
"{",
"@link",
"Filters",
"}",
".",
"Use",
"{",
"@lin... | train | https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/context/ConfigurationInfo.java#L77-L80 |
teatrove/teatrove | teaservlet/src/main/java/org/teatrove/teatools/TeaToolsUtils.java | TeaToolsUtils.createMethodDescriptions | public MethodDescription[] createMethodDescriptions(
MethodDescriptor[] mds) {
if (mds == null) {
return null;
}
MethodDescription[] descriptions =
new MethodDescription[mds.length];
for (int i = 0; i < mds.length; i++) {
descriptions[i] = new MethodDescription(mds[i], this);
}
return descriptions;
} | java | public MethodDescription[] createMethodDescriptions(
MethodDescriptor[] mds) {
if (mds == null) {
return null;
}
MethodDescription[] descriptions =
new MethodDescription[mds.length];
for (int i = 0; i < mds.length; i++) {
descriptions[i] = new MethodDescription(mds[i], this);
}
return descriptions;
} | [
"public",
"MethodDescription",
"[",
"]",
"createMethodDescriptions",
"(",
"MethodDescriptor",
"[",
"]",
"mds",
")",
"{",
"if",
"(",
"mds",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"MethodDescription",
"[",
"]",
"descriptions",
"=",
"new",
"MethodD... | Returns an array of MethodDescriptions to wrap and describe the
specified MethodDescriptors. | [
"Returns",
"an",
"array",
"of",
"MethodDescriptions",
"to",
"wrap",
"and",
"describe",
"the",
"specified",
"MethodDescriptors",
"."
] | train | https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/teaservlet/src/main/java/org/teatrove/teatools/TeaToolsUtils.java#L126-L140 |
thinkaurelius/titan | titan-cassandra/src/main/java/com/thinkaurelius/titan/diskstorage/cassandra/embedded/CassandraEmbeddedKeyColumnValueStore.java | CassandraEmbeddedKeyColumnValueStore.getKeySlice | private List<Row> getKeySlice(Token start,
Token end,
@Nullable SliceQuery sliceQuery,
int pageSize,
long nowMillis) throws BackendException {
IPartitioner partitioner = StorageService.getPartitioner();
SliceRange columnSlice = new SliceRange();
if (sliceQuery == null) {
columnSlice.setStart(ArrayUtils.EMPTY_BYTE_ARRAY)
.setFinish(ArrayUtils.EMPTY_BYTE_ARRAY)
.setCount(5);
} else {
columnSlice.setStart(sliceQuery.getSliceStart().asByteBuffer())
.setFinish(sliceQuery.getSliceEnd().asByteBuffer())
.setCount(sliceQuery.hasLimit() ? sliceQuery.getLimit() : Integer.MAX_VALUE);
}
/* Note: we need to fetch columns for each row as well to remove "range ghosts" */
SlicePredicate predicate = new SlicePredicate().setSlice_range(columnSlice);
RowPosition startPosition = start.minKeyBound(partitioner);
RowPosition endPosition = end.minKeyBound(partitioner);
List<Row> rows;
try {
CFMetaData cfm = Schema.instance.getCFMetaData(keyspace, columnFamily);
IDiskAtomFilter filter = ThriftValidation.asIFilter(predicate, cfm, null);
RangeSliceCommand cmd = new RangeSliceCommand(keyspace, columnFamily, nowMillis, filter, new Bounds<RowPosition>(startPosition, endPosition), pageSize);
rows = StorageProxy.getRangeSlice(cmd, ConsistencyLevel.QUORUM);
} catch (Exception e) {
throw new PermanentBackendException(e);
}
return rows;
} | java | private List<Row> getKeySlice(Token start,
Token end,
@Nullable SliceQuery sliceQuery,
int pageSize,
long nowMillis) throws BackendException {
IPartitioner partitioner = StorageService.getPartitioner();
SliceRange columnSlice = new SliceRange();
if (sliceQuery == null) {
columnSlice.setStart(ArrayUtils.EMPTY_BYTE_ARRAY)
.setFinish(ArrayUtils.EMPTY_BYTE_ARRAY)
.setCount(5);
} else {
columnSlice.setStart(sliceQuery.getSliceStart().asByteBuffer())
.setFinish(sliceQuery.getSliceEnd().asByteBuffer())
.setCount(sliceQuery.hasLimit() ? sliceQuery.getLimit() : Integer.MAX_VALUE);
}
/* Note: we need to fetch columns for each row as well to remove "range ghosts" */
SlicePredicate predicate = new SlicePredicate().setSlice_range(columnSlice);
RowPosition startPosition = start.minKeyBound(partitioner);
RowPosition endPosition = end.minKeyBound(partitioner);
List<Row> rows;
try {
CFMetaData cfm = Schema.instance.getCFMetaData(keyspace, columnFamily);
IDiskAtomFilter filter = ThriftValidation.asIFilter(predicate, cfm, null);
RangeSliceCommand cmd = new RangeSliceCommand(keyspace, columnFamily, nowMillis, filter, new Bounds<RowPosition>(startPosition, endPosition), pageSize);
rows = StorageProxy.getRangeSlice(cmd, ConsistencyLevel.QUORUM);
} catch (Exception e) {
throw new PermanentBackendException(e);
}
return rows;
} | [
"private",
"List",
"<",
"Row",
">",
"getKeySlice",
"(",
"Token",
"start",
",",
"Token",
"end",
",",
"@",
"Nullable",
"SliceQuery",
"sliceQuery",
",",
"int",
"pageSize",
",",
"long",
"nowMillis",
")",
"throws",
"BackendException",
"{",
"IPartitioner",
"partitio... | Create a RangeSliceCommand and run it against the StorageProxy.
<p>
To match the behavior of the standard Cassandra thrift API endpoint, the
{@code nowMillis} argument should be the number of milliseconds since the
UNIX Epoch (e.g. System.currentTimeMillis() or equivalent obtained
through a {@link TimestampProvider}). This is per
{@link org.apache.cassandra.thrift.CassandraServer#get_range_slices(ColumnParent, SlicePredicate, KeyRange, ConsistencyLevel)},
which passes the server's System.currentTimeMillis() to the
{@code RangeSliceCommand} constructor. | [
"Create",
"a",
"RangeSliceCommand",
"and",
"run",
"it",
"against",
"the",
"StorageProxy",
".",
"<p",
">",
"To",
"match",
"the",
"behavior",
"of",
"the",
"standard",
"Cassandra",
"thrift",
"API",
"endpoint",
"the",
"{"
] | train | https://github.com/thinkaurelius/titan/blob/ee226e52415b8bf43b700afac75fa5b9767993a5/titan-cassandra/src/main/java/com/thinkaurelius/titan/diskstorage/cassandra/embedded/CassandraEmbeddedKeyColumnValueStore.java#L104-L141 |
fabric8io/docker-maven-plugin | src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java | AnsiLogger.format | private String format(String message, Object[] params) {
if (params.length == 0) {
return message;
} else if (params.length == 1 && params[0] instanceof Throwable) {
// We print only the message here since breaking exception will bubble up
// anyway
return message + ": " + params[0].toString();
} else {
return String.format(message, params);
}
} | java | private String format(String message, Object[] params) {
if (params.length == 0) {
return message;
} else if (params.length == 1 && params[0] instanceof Throwable) {
// We print only the message here since breaking exception will bubble up
// anyway
return message + ": " + params[0].toString();
} else {
return String.format(message, params);
}
} | [
"private",
"String",
"format",
"(",
"String",
"message",
",",
"Object",
"[",
"]",
"params",
")",
"{",
"if",
"(",
"params",
".",
"length",
"==",
"0",
")",
"{",
"return",
"message",
";",
"}",
"else",
"if",
"(",
"params",
".",
"length",
"==",
"1",
"&&... | Use parameters when given, otherwise we use the string directly | [
"Use",
"parameters",
"when",
"given",
"otherwise",
"we",
"use",
"the",
"string",
"directly"
] | train | https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/AnsiLogger.java#L232-L242 |
mebigfatguy/fb-contrib | src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java | ExceptionSoftening.getConstrainingInfo | @Nullable
private Map<String, Set<String>> getConstrainingInfo(JavaClass cls, Method m) throws ClassNotFoundException {
String methodName = m.getName();
String methodSig = m.getSignature();
{
// First look for the method in interfaces of the class
JavaClass[] infClasses = cls.getInterfaces();
for (JavaClass infCls : infClasses) {
Method infMethod = findMethod(infCls, methodName, methodSig);
if (infMethod != null) {
return buildConstrainingInfo(infCls, infMethod);
}
Map<String, Set<String>> constrainingExs = getConstrainingInfo(infCls, m);
if (constrainingExs != null) {
return constrainingExs;
}
}
}
{
// Next look at the superclass
JavaClass superCls = cls.getSuperClass();
if (superCls == null) {
return null;
}
Method superMethod = findMethod(superCls, methodName, methodSig);
if (superMethod != null) {
return buildConstrainingInfo(superCls, superMethod);
}
// Otherwise recursively call this on the super class
return getConstrainingInfo(superCls, m);
}
} | java | @Nullable
private Map<String, Set<String>> getConstrainingInfo(JavaClass cls, Method m) throws ClassNotFoundException {
String methodName = m.getName();
String methodSig = m.getSignature();
{
// First look for the method in interfaces of the class
JavaClass[] infClasses = cls.getInterfaces();
for (JavaClass infCls : infClasses) {
Method infMethod = findMethod(infCls, methodName, methodSig);
if (infMethod != null) {
return buildConstrainingInfo(infCls, infMethod);
}
Map<String, Set<String>> constrainingExs = getConstrainingInfo(infCls, m);
if (constrainingExs != null) {
return constrainingExs;
}
}
}
{
// Next look at the superclass
JavaClass superCls = cls.getSuperClass();
if (superCls == null) {
return null;
}
Method superMethod = findMethod(superCls, methodName, methodSig);
if (superMethod != null) {
return buildConstrainingInfo(superCls, superMethod);
}
// Otherwise recursively call this on the super class
return getConstrainingInfo(superCls, m);
}
} | [
"@",
"Nullable",
"private",
"Map",
"<",
"String",
",",
"Set",
"<",
"String",
">",
">",
"getConstrainingInfo",
"(",
"JavaClass",
"cls",
",",
"Method",
"m",
")",
"throws",
"ClassNotFoundException",
"{",
"String",
"methodName",
"=",
"m",
".",
"getName",
"(",
... | finds the super class or interface that constrains the types of exceptions
that can be thrown from the given method
@param cls the currently parsed class
@param m the method to check
@return a map containing the class name to a set of exceptions that constrain
this method
@throws ClassNotFoundException if a super class or super interface can't be
loaded from the repository | [
"finds",
"the",
"super",
"class",
"or",
"interface",
"that",
"constrains",
"the",
"types",
"of",
"exceptions",
"that",
"can",
"be",
"thrown",
"from",
"the",
"given",
"method"
] | train | https://github.com/mebigfatguy/fb-contrib/blob/3b5203196f627b399fbcea3c2ab2b1f4e56cc7b8/src/main/java/com/mebigfatguy/fbcontrib/detect/ExceptionSoftening.java#L381-L419 |
GenesysPureEngage/workspace-client-java | src/main/java/com/genesys/internal/workspace/api/ReportingApi.java | ReportingApi.subscribeAsync | public com.squareup.okhttp.Call subscribeAsync(StatisticsSubscribeData statisticsSubscribeData, final ApiCallback<InlineResponse2002> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = subscribeValidateBeforeCall(statisticsSubscribeData, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<InlineResponse2002>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | java | public com.squareup.okhttp.Call subscribeAsync(StatisticsSubscribeData statisticsSubscribeData, final ApiCallback<InlineResponse2002> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = subscribeValidateBeforeCall(statisticsSubscribeData, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<InlineResponse2002>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
} | [
"public",
"com",
".",
"squareup",
".",
"okhttp",
".",
"Call",
"subscribeAsync",
"(",
"StatisticsSubscribeData",
"statisticsSubscribeData",
",",
"final",
"ApiCallback",
"<",
"InlineResponse2002",
">",
"callback",
")",
"throws",
"ApiException",
"{",
"ProgressResponseBody"... | Subscribe to statistics (asynchronously)
Open a subscription for the specified set of statistics. The values are returned when you request them using [/reporting/subscriptions/{subscriptionId}](/reference/workspace/Reporting/index.html#peek).
@param statisticsSubscribeData The collection of statistics you want to include in your subscription. (required)
@param callback The callback to be executed when the API call finishes
@return The request call
@throws ApiException If fail to process the API call, e.g. serializing the request body object | [
"Subscribe",
"to",
"statistics",
"(",
"asynchronously",
")",
"Open",
"a",
"subscription",
"for",
"the",
"specified",
"set",
"of",
"statistics",
".",
"The",
"values",
"are",
"returned",
"when",
"you",
"request",
"them",
"using",
"[",
"/",
"reporting",
"/",
"s... | train | https://github.com/GenesysPureEngage/workspace-client-java/blob/509fdd9e89b9359d012f9a72be95037a3cef53e6/src/main/java/com/genesys/internal/workspace/api/ReportingApi.java#L404-L429 |
arxanchain/java-common | src/main/java/com/arxanfintech/common/crypto/core/ECIESCoder.java | ECIESCoder.decryptSimple | public static byte[] decryptSimple(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException {
ArxanIESEngine iesEngine = new ArxanIESEngine(
new ECDHBasicAgreement(),
new MGF1BytesGeneratorExt(new SHA1Digest(), 1),
new HMac(new SHA1Digest()),
new SHA1Digest(),
null);
IESParameters p = new IESParameters(null, null, KEY_SIZE);
ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]);
iesEngine.setHashMacKey(false);
iesEngine.init(new ECPrivateKeyParameters(privKey, CURVE), parametersWithIV,
new ECIESPublicKeyParser(ECKey.CURVE));
return iesEngine.processBlock(cipher, 0, cipher.length);
} | java | public static byte[] decryptSimple(BigInteger privKey, byte[] cipher) throws IOException, InvalidCipherTextException {
ArxanIESEngine iesEngine = new ArxanIESEngine(
new ECDHBasicAgreement(),
new MGF1BytesGeneratorExt(new SHA1Digest(), 1),
new HMac(new SHA1Digest()),
new SHA1Digest(),
null);
IESParameters p = new IESParameters(null, null, KEY_SIZE);
ParametersWithIV parametersWithIV = new ParametersWithIV(p, new byte[0]);
iesEngine.setHashMacKey(false);
iesEngine.init(new ECPrivateKeyParameters(privKey, CURVE), parametersWithIV,
new ECIESPublicKeyParser(ECKey.CURVE));
return iesEngine.processBlock(cipher, 0, cipher.length);
} | [
"public",
"static",
"byte",
"[",
"]",
"decryptSimple",
"(",
"BigInteger",
"privKey",
",",
"byte",
"[",
"]",
"cipher",
")",
"throws",
"IOException",
",",
"InvalidCipherTextException",
"{",
"ArxanIESEngine",
"iesEngine",
"=",
"new",
"ArxanIESEngine",
"(",
"new",
"... | Encryption equivalent to the Crypto++ default ECIES ECP settings:
DL_KeyAgreementAlgorithm: DL_KeyAgreementAlgorithm_DH struct ECPPoint,struct EnumToType enum CofactorMultiplicationOption,0
DL_KeyDerivationAlgorithm: DL_KeyDerivationAlgorithm_P1363 struct ECPPoint,0,class P1363_KDF2 class SHA1
DL_SymmetricEncryptionAlgorithm: DL_EncryptionAlgorithm_Xor class HMAC class SHA1 ,0
DL_PrivateKey: DL_Key ECPPoint
DL_PrivateKey_EC class ECP
Used for Whisper V3
@param privKey privKey
@param cipher cipher
@return decryptSimple byte[] data
@throws IOException IOException
@throws InvalidCipherTextException InvalidCipherTextException | [
"Encryption",
"equivalent",
"to",
"the",
"Crypto",
"++",
"default",
"ECIES",
"ECP",
"settings",
":"
] | train | https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/crypto/core/ECIESCoder.java#L111-L128 |
nguyenq/tess4j | src/main/java/net/sourceforge/tess4j/util/PdfUtilities.java | PdfUtilities.splitPdf | public static void splitPdf(File inputPdfFile, File outputPdfFile, int firstPage, int lastPage) {
if (PDFBOX.equals(System.getProperty(PDF_LIBRARY))) {
PdfBoxUtilities.splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
} else {
try {
PdfGsUtilities.splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
} catch (Exception e) {
System.setProperty(PDF_LIBRARY, PDFBOX);
splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
}
}
} | java | public static void splitPdf(File inputPdfFile, File outputPdfFile, int firstPage, int lastPage) {
if (PDFBOX.equals(System.getProperty(PDF_LIBRARY))) {
PdfBoxUtilities.splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
} else {
try {
PdfGsUtilities.splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
} catch (Exception e) {
System.setProperty(PDF_LIBRARY, PDFBOX);
splitPdf(inputPdfFile, outputPdfFile, firstPage, lastPage);
}
}
} | [
"public",
"static",
"void",
"splitPdf",
"(",
"File",
"inputPdfFile",
",",
"File",
"outputPdfFile",
",",
"int",
"firstPage",
",",
"int",
"lastPage",
")",
"{",
"if",
"(",
"PDFBOX",
".",
"equals",
"(",
"System",
".",
"getProperty",
"(",
"PDF_LIBRARY",
")",
")... | Splits PDF.
@param inputPdfFile input file
@param outputPdfFile output file
@param firstPage begin page
@param lastPage end page | [
"Splits",
"PDF",
"."
] | train | https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/PdfUtilities.java#L101-L112 |
citrusframework/citrus | modules/citrus-core/src/main/java/com/consol/citrus/config/util/BeanDefinitionParserUtils.java | BeanDefinitionParserUtils.registerBean | public static BeanDefinitionHolder registerBean(String beanId, BeanDefinition beanDefinition, ParserContext parserContext, boolean shouldFireEvents) {
if (parserContext.getRegistry().containsBeanDefinition(beanId)) {
return new BeanDefinitionHolder(parserContext.getRegistry().getBeanDefinition(beanId), beanId);
}
BeanDefinitionHolder configurationHolder = new BeanDefinitionHolder(beanDefinition, beanId);
BeanDefinitionReaderUtils.registerBeanDefinition(configurationHolder, parserContext.getRegistry());
if (shouldFireEvents) {
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(configurationHolder);
parserContext.registerComponent(componentDefinition);
}
return configurationHolder;
} | java | public static BeanDefinitionHolder registerBean(String beanId, BeanDefinition beanDefinition, ParserContext parserContext, boolean shouldFireEvents) {
if (parserContext.getRegistry().containsBeanDefinition(beanId)) {
return new BeanDefinitionHolder(parserContext.getRegistry().getBeanDefinition(beanId), beanId);
}
BeanDefinitionHolder configurationHolder = new BeanDefinitionHolder(beanDefinition, beanId);
BeanDefinitionReaderUtils.registerBeanDefinition(configurationHolder, parserContext.getRegistry());
if (shouldFireEvents) {
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(configurationHolder);
parserContext.registerComponent(componentDefinition);
}
return configurationHolder;
} | [
"public",
"static",
"BeanDefinitionHolder",
"registerBean",
"(",
"String",
"beanId",
",",
"BeanDefinition",
"beanDefinition",
",",
"ParserContext",
"parserContext",
",",
"boolean",
"shouldFireEvents",
")",
"{",
"if",
"(",
"parserContext",
".",
"getRegistry",
"(",
")",... | Registers bean definition in parser registry and returns bean definition holder.
@param beanId
@param beanDefinition
@param parserContext
@param shouldFireEvents
@return | [
"Registers",
"bean",
"definition",
"in",
"parser",
"registry",
"and",
"returns",
"bean",
"definition",
"holder",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-core/src/main/java/com/consol/citrus/config/util/BeanDefinitionParserUtils.java#L130-L144 |
BotMill/fb-botmill | src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java | FbBotMillServlet.doGet | @Override
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Retrieves GET parameters.
String validationToken = FbBotMillContext.getInstance()
.getValidationToken();
Map<String, String[]> parameters = req.getParameterMap();
String hubMode = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_MODE_PARAMETER));
String hubToken = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_VERIFY_TOKEN_PARAMETER));
String hubChallenge = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_CHALLENGE_PARAMETER));
// Checks parameters and responds according to that.
if (hubMode.equals(FbBotMillNetworkConstants.HUB_MODE_SUBSCRIBE)
&& hubToken.equals(validationToken)) {
logger.info("Subscription OK.");
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().write(hubChallenge);
} else {
logger.warn("GET received is not a subscription or wrong validation token. Ensure you have set the correct validation token using FbBotMillContext.getInstance().setup(String, String).");
resp.sendError(403);
}
} | java | @Override
@SuppressWarnings("unchecked")
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Retrieves GET parameters.
String validationToken = FbBotMillContext.getInstance()
.getValidationToken();
Map<String, String[]> parameters = req.getParameterMap();
String hubMode = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_MODE_PARAMETER));
String hubToken = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_VERIFY_TOKEN_PARAMETER));
String hubChallenge = safeUnwrapGetParameters(parameters
.get(FbBotMillNetworkConstants.HUB_CHALLENGE_PARAMETER));
// Checks parameters and responds according to that.
if (hubMode.equals(FbBotMillNetworkConstants.HUB_MODE_SUBSCRIBE)
&& hubToken.equals(validationToken)) {
logger.info("Subscription OK.");
resp.setStatus(200);
resp.setContentType("text/plain");
resp.getWriter().write(hubChallenge);
} else {
logger.warn("GET received is not a subscription or wrong validation token. Ensure you have set the correct validation token using FbBotMillContext.getInstance().setup(String, String).");
resp.sendError(403);
}
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"protected",
"void",
"doGet",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"resp",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"// Retrieves GET parameters.\r",
"String... | Specifies how to handle a GET request. GET requests are used by Facebook
only during the WebHook registration. During this phase, the
FbBotMillServlet checks that the
{@link FbBotMillNetworkConstants#HUB_MODE_PARAMETER} value received
equals to {@link FbBotMillNetworkConstants#HUB_MODE_SUBSCRIBE} and that
the {@link FbBotMillNetworkConstants#HUB_VERIFY_TOKEN_PARAMETER} value
received equals to the {@link FbBotMillContext#getValidationToken()}. If
that's true, then the FbBotMillServlet will reply sending back the value
of the {@link FbBotMillNetworkConstants#HUB_CHALLENGE_PARAMETER}
received, in order to confirm the registration, otherwise it will return
an error 403.
@param req
the req
@param resp
the resp
@throws ServletException
the servlet exception
@throws IOException
Signals that an I/O exception has occurred. | [
"Specifies",
"how",
"to",
"handle",
"a",
"GET",
"request",
".",
"GET",
"requests",
"are",
"used",
"by",
"Facebook",
"only",
"during",
"the",
"WebHook",
"registration",
".",
"During",
"this",
"phase",
"the",
"FbBotMillServlet",
"checks",
"that",
"the",
"{",
"... | train | https://github.com/BotMill/fb-botmill/blob/d94da3615a7339822c137ef75c92a03d791ee969/src/main/java/co/aurasphere/botmill/fb/FbBotMillServlet.java#L104-L131 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/client/gui/render/GuiRenderer.java | GuiRenderer.drawItemStack | public void drawItemStack(ItemStack itemStack, int x, int y, Style format)
{
drawItemStack(itemStack, x, y, null, format, true);
} | java | public void drawItemStack(ItemStack itemStack, int x, int y, Style format)
{
drawItemStack(itemStack, x, y, null, format, true);
} | [
"public",
"void",
"drawItemStack",
"(",
"ItemStack",
"itemStack",
",",
"int",
"x",
",",
"int",
"y",
",",
"Style",
"format",
")",
"{",
"drawItemStack",
"(",
"itemStack",
",",
"x",
",",
"y",
",",
"null",
",",
"format",
",",
"true",
")",
";",
"}"
] | Draws an itemStack to the GUI at the specified coordinates with a custom format for the label.
@param itemStack the item stack
@param x the x
@param y the y
@param format the format | [
"Draws",
"an",
"itemStack",
"to",
"the",
"GUI",
"at",
"the",
"specified",
"coordinates",
"with",
"a",
"custom",
"format",
"for",
"the",
"label",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/client/gui/render/GuiRenderer.java#L385-L388 |
JoeKerouac/utils | src/main/java/com/joe/utils/serialize/xml/XmlParser.java | XmlParser.setValue | @SuppressWarnings("unchecked")
private void setValue(List<Element> elements, String attrName, Object pojo,
CustomPropertyDescriptor field) {
XmlNode attrXmlNode = field.getAnnotation(XmlNode.class);
log.debug("要赋值的fieldName为{}", field.getName());
final XmlTypeConvert convert = XmlTypeConverterUtil.resolve(attrXmlNode, field);
Class<? extends Collection> collectionClass;
Class<? extends Collection> real = (Class<? extends Collection>) field.getRealType();
if (attrXmlNode != null) {
collectionClass = attrXmlNode.arrayType();
if (!collectionClass.equals(real) && !real.isAssignableFrom(collectionClass)) {
log.warn("用户指定的集合类型[{}]不是字段的实际集合类型[{}]的子类,使用字段的实际集合类型", collectionClass, real);
collectionClass = real;
}
} else {
collectionClass = real;
}
if (!StringUtils.isEmpty(attrXmlNode.arrayRoot()) && !elements.isEmpty()) {
elements = elements.get(0).elements(attrXmlNode.arrayRoot());
}
//将数据转换为用户指定数据
List<?> list = elements.stream().map(d -> convert.read(d, attrName))
.collect(Collectors.toList());
if (!trySetValue(list, pojo, field, collectionClass)) {
//使用注解标记的类型赋值失败并且注解的集合类型与实际字段类型不符时尝试使用字段实际类型赋值
if (!trySetValue(list, pojo, field, real)) {
log.warn("无法为字段[{}]赋值", field.getName());
}
}
} | java | @SuppressWarnings("unchecked")
private void setValue(List<Element> elements, String attrName, Object pojo,
CustomPropertyDescriptor field) {
XmlNode attrXmlNode = field.getAnnotation(XmlNode.class);
log.debug("要赋值的fieldName为{}", field.getName());
final XmlTypeConvert convert = XmlTypeConverterUtil.resolve(attrXmlNode, field);
Class<? extends Collection> collectionClass;
Class<? extends Collection> real = (Class<? extends Collection>) field.getRealType();
if (attrXmlNode != null) {
collectionClass = attrXmlNode.arrayType();
if (!collectionClass.equals(real) && !real.isAssignableFrom(collectionClass)) {
log.warn("用户指定的集合类型[{}]不是字段的实际集合类型[{}]的子类,使用字段的实际集合类型", collectionClass, real);
collectionClass = real;
}
} else {
collectionClass = real;
}
if (!StringUtils.isEmpty(attrXmlNode.arrayRoot()) && !elements.isEmpty()) {
elements = elements.get(0).elements(attrXmlNode.arrayRoot());
}
//将数据转换为用户指定数据
List<?> list = elements.stream().map(d -> convert.read(d, attrName))
.collect(Collectors.toList());
if (!trySetValue(list, pojo, field, collectionClass)) {
//使用注解标记的类型赋值失败并且注解的集合类型与实际字段类型不符时尝试使用字段实际类型赋值
if (!trySetValue(list, pojo, field, real)) {
log.warn("无法为字段[{}]赋值", field.getName());
}
}
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"private",
"void",
"setValue",
"(",
"List",
"<",
"Element",
">",
"elements",
",",
"String",
"attrName",
",",
"Object",
"pojo",
",",
"CustomPropertyDescriptor",
"field",
")",
"{",
"XmlNode",
"attrXmlNode",
"=",
... | 往pojo中指定字段设置值(字段为Collection类型)
@param elements 要设置的数据节点
@param attrName 要获取的属性名,如果该值不为空则认为数据需要从属性中取而不是从节点数据中取
@param pojo pojo
@param field 字段说明 | [
"往pojo中指定字段设置值(字段为Collection类型)"
] | train | https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/serialize/xml/XmlParser.java#L571-L605 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringParser.java | StringParser.parseDouble | public static double parseDouble (@Nullable final Object aObject, final double dDefault)
{
if (aObject == null)
return dDefault;
if (aObject instanceof Number)
return ((Number) aObject).doubleValue ();
return parseDouble (aObject.toString (), dDefault);
} | java | public static double parseDouble (@Nullable final Object aObject, final double dDefault)
{
if (aObject == null)
return dDefault;
if (aObject instanceof Number)
return ((Number) aObject).doubleValue ();
return parseDouble (aObject.toString (), dDefault);
} | [
"public",
"static",
"double",
"parseDouble",
"(",
"@",
"Nullable",
"final",
"Object",
"aObject",
",",
"final",
"double",
"dDefault",
")",
"{",
"if",
"(",
"aObject",
"==",
"null",
")",
"return",
"dDefault",
";",
"if",
"(",
"aObject",
"instanceof",
"Number",
... | Parse the given {@link Object} as double. Note: both the locale independent
form of a double can be parsed here (e.g. 4.523) as well as a localized
form using the comma as the decimal separator (e.g. the German 4,523).
@param aObject
The object to parse. May be <code>null</code>.
@param dDefault
The default value to be returned if the passed object could not be
converted to a valid value.
@return The default value if the object does not represent a valid value. | [
"Parse",
"the",
"given",
"{",
"@link",
"Object",
"}",
"as",
"double",
".",
"Note",
":",
"both",
"the",
"locale",
"independent",
"form",
"of",
"a",
"double",
"can",
"be",
"parsed",
"here",
"(",
"e",
".",
"g",
".",
"4",
".",
"523",
")",
"as",
"well",... | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringParser.java#L465-L472 |
sahan/DroidBallet | droidballet/src/main/java/com/lonepulse/droidballet/detector/VerticalMotionDetector.java | VerticalMotionDetector.processVerticalDirection | private VERTICAL_DIRECTION processVerticalDirection(float[] output, float midRangeHigh, float midRangeLow) {
output[1] = (output[1] < 0)? 0.0f : output[1];
if (output[1] < midRangeLow) {
output[1] *= -1;
return VERTICAL_DIRECTION.UP;
}
else if (output[1] > midRangeHigh) {
return VERTICAL_DIRECTION.DOWN;
}
else {
return VERTICAL_DIRECTION.NONE;
}
} | java | private VERTICAL_DIRECTION processVerticalDirection(float[] output, float midRangeHigh, float midRangeLow) {
output[1] = (output[1] < 0)? 0.0f : output[1];
if (output[1] < midRangeLow) {
output[1] *= -1;
return VERTICAL_DIRECTION.UP;
}
else if (output[1] > midRangeHigh) {
return VERTICAL_DIRECTION.DOWN;
}
else {
return VERTICAL_DIRECTION.NONE;
}
} | [
"private",
"VERTICAL_DIRECTION",
"processVerticalDirection",
"(",
"float",
"[",
"]",
"output",
",",
"float",
"midRangeHigh",
",",
"float",
"midRangeLow",
")",
"{",
"output",
"[",
"1",
"]",
"=",
"(",
"output",
"[",
"1",
"]",
"<",
"0",
")",
"?",
"0.0f",
":... | <p>Determines the {@link VERTICAL_DIRECTION} of the motion and trims the
sensor reading on the Y-Axis to within the bounds handled by the the
motion detector.
@param output
the smoothed sensor values
@param midRangeHigh
the upperbound of the mid-range which correlates with {@link VERTICAL_DIRECTION#NONE}
@param midRangeLow
the lowerbound of the mid-range which correlates with {@link VERTICAL_DIRECTION#NONE}
@return the {@link VERTICAL_DIRECTION} of the motion | [
"<p",
">",
"Determines",
"the",
"{",
"@link",
"VERTICAL_DIRECTION",
"}",
"of",
"the",
"motion",
"and",
"trims",
"the",
"sensor",
"reading",
"on",
"the",
"Y",
"-",
"Axis",
"to",
"within",
"the",
"bounds",
"handled",
"by",
"the",
"the",
"motion",
"detector",... | train | https://github.com/sahan/DroidBallet/blob/c6001c9e933cb2c8dbcabe1ae561678b31b10b62/droidballet/src/main/java/com/lonepulse/droidballet/detector/VerticalMotionDetector.java#L143-L160 |
jenkinsci/jenkins | core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java | NodeMonitorUpdater.onOnline | @Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
synchronized(this) {
future.cancel(false);
future = Timer.get().schedule(MONITOR_UPDATER, 5, TimeUnit.SECONDS);
}
} | java | @Override
public void onOnline(Computer c, TaskListener listener) throws IOException, InterruptedException {
synchronized(this) {
future.cancel(false);
future = Timer.get().schedule(MONITOR_UPDATER, 5, TimeUnit.SECONDS);
}
} | [
"@",
"Override",
"public",
"void",
"onOnline",
"(",
"Computer",
"c",
",",
"TaskListener",
"listener",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"synchronized",
"(",
"this",
")",
"{",
"future",
".",
"cancel",
"(",
"false",
")",
";",
"fut... | Triggers the update with 5 seconds quiet period, to avoid triggering data check too often
when multiple agents become online at about the same time. | [
"Triggers",
"the",
"update",
"with",
"5",
"seconds",
"quiet",
"period",
"to",
"avoid",
"triggering",
"data",
"check",
"too",
"often",
"when",
"multiple",
"agents",
"become",
"online",
"at",
"about",
"the",
"same",
"time",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/node_monitors/NodeMonitorUpdater.java#L39-L45 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java | LegacyBehavior.determinePropagatingExecutionOnEnd | public static PvmExecutionImpl determinePropagatingExecutionOnEnd(PvmExecutionImpl propagatingExecution, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
if (!propagatingExecution.isScope()) {
// non-scope executions may end in the "wrong" flow scope
return propagatingExecution;
}
else {
// superfluous scope executions won't be contained in the activity-execution mapping
if (activityExecutionMapping.values().contains(propagatingExecution)) {
return propagatingExecution;
}
else {
// skip one scope
propagatingExecution.remove();
PvmExecutionImpl parent = propagatingExecution.getParent();
parent.setActivity(propagatingExecution.getActivity());
return propagatingExecution.getParent();
}
}
} | java | public static PvmExecutionImpl determinePropagatingExecutionOnEnd(PvmExecutionImpl propagatingExecution, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
if (!propagatingExecution.isScope()) {
// non-scope executions may end in the "wrong" flow scope
return propagatingExecution;
}
else {
// superfluous scope executions won't be contained in the activity-execution mapping
if (activityExecutionMapping.values().contains(propagatingExecution)) {
return propagatingExecution;
}
else {
// skip one scope
propagatingExecution.remove();
PvmExecutionImpl parent = propagatingExecution.getParent();
parent.setActivity(propagatingExecution.getActivity());
return propagatingExecution.getParent();
}
}
} | [
"public",
"static",
"PvmExecutionImpl",
"determinePropagatingExecutionOnEnd",
"(",
"PvmExecutionImpl",
"propagatingExecution",
",",
"Map",
"<",
"ScopeImpl",
",",
"PvmExecutionImpl",
">",
"activityExecutionMapping",
")",
"{",
"if",
"(",
"!",
"propagatingExecution",
".",
"i... | Tolerates the broken execution trees fixed with CAM-3727 where there may be more
ancestor scope executions than ancestor flow scopes;
In that case, the argument execution is removed, the parent execution of the argument
is returned such that one level of mismatch is corrected.
Note that this does not necessarily skip the correct scope execution, since
the broken parent-child relationships may be anywhere in the tree (e.g. consider a non-interrupting
boundary event followed by a subprocess (i.e. scope), when the subprocess ends, we would
skip the subprocess's execution). | [
"Tolerates",
"the",
"broken",
"execution",
"trees",
"fixed",
"with",
"CAM",
"-",
"3727",
"where",
"there",
"may",
"be",
"more",
"ancestor",
"scope",
"executions",
"than",
"ancestor",
"flow",
"scopes",
";"
] | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java#L382-L400 |
BigBadaboom/androidsvg | androidsvg/src/main/java/com/caverock/androidsvg/SVGAndroidRenderer.java | SVGAndroidRenderer.realignMarkerMid | private MarkerVector realignMarkerMid(MarkerVector lastPos, MarkerVector thisPos, MarkerVector nextPos)
{
// Check the temporary marker vector against the incoming vector
float dot = dotProduct(thisPos.dx, thisPos.dy, (thisPos.x - lastPos.x), (thisPos.y - lastPos.y));
if (dot == 0f) {
// Those two were perpendicular, so instead try the outgoing vector
dot = dotProduct(thisPos.dx, thisPos.dy, (nextPos.x - thisPos.x), (nextPos.y - thisPos.y));
}
if (dot > 0)
return thisPos;
if (dot == 0f) {
// If that was perpendicular also, then give up.
// Else use the one that points in the same direction as 0deg (1,0) or has non-negative y.
if (thisPos.dx > 0f || thisPos.dy >= 0)
return thisPos;
}
// Reverse this vector and point the marker in the opposite direction.
thisPos.dx = -thisPos.dx;
thisPos.dy = -thisPos.dy;
return thisPos;
} | java | private MarkerVector realignMarkerMid(MarkerVector lastPos, MarkerVector thisPos, MarkerVector nextPos)
{
// Check the temporary marker vector against the incoming vector
float dot = dotProduct(thisPos.dx, thisPos.dy, (thisPos.x - lastPos.x), (thisPos.y - lastPos.y));
if (dot == 0f) {
// Those two were perpendicular, so instead try the outgoing vector
dot = dotProduct(thisPos.dx, thisPos.dy, (nextPos.x - thisPos.x), (nextPos.y - thisPos.y));
}
if (dot > 0)
return thisPos;
if (dot == 0f) {
// If that was perpendicular also, then give up.
// Else use the one that points in the same direction as 0deg (1,0) or has non-negative y.
if (thisPos.dx > 0f || thisPos.dy >= 0)
return thisPos;
}
// Reverse this vector and point the marker in the opposite direction.
thisPos.dx = -thisPos.dx;
thisPos.dy = -thisPos.dy;
return thisPos;
} | [
"private",
"MarkerVector",
"realignMarkerMid",
"(",
"MarkerVector",
"lastPos",
",",
"MarkerVector",
"thisPos",
",",
"MarkerVector",
"nextPos",
")",
"{",
"// Check the temporary marker vector against the incoming vector\r",
"float",
"dot",
"=",
"dotProduct",
"(",
"thisPos",
... | /*
This was one of the ambiguous markers. Try to see if we can find a better direction for
it, now that we have more info available on the neighbouring marker positions. | [
"/",
"*",
"This",
"was",
"one",
"of",
"the",
"ambiguous",
"markers",
".",
"Try",
"to",
"see",
"if",
"we",
"can",
"find",
"a",
"better",
"direction",
"for",
"it",
"now",
"that",
"we",
"have",
"more",
"info",
"available",
"on",
"the",
"neighbouring",
"ma... | train | https://github.com/BigBadaboom/androidsvg/blob/0d1614dd1a4da10ea4afe3b0cea1361a4ac6b45a/androidsvg/src/main/java/com/caverock/androidsvg/SVGAndroidRenderer.java#L3052-L3072 |
jamesagnew/hapi-fhir | hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/filters/Newline_To_Br.java | Newline_To_Br.apply | @Override
public Object apply(Object value, Object... params) {
return super.asString(value).replaceAll("[\n]", "<br />\n");
} | java | @Override
public Object apply(Object value, Object... params) {
return super.asString(value).replaceAll("[\n]", "<br />\n");
} | [
"@",
"Override",
"public",
"Object",
"apply",
"(",
"Object",
"value",
",",
"Object",
"...",
"params",
")",
"{",
"return",
"super",
".",
"asString",
"(",
"value",
")",
".",
"replaceAll",
"(",
"\"[\\n]\"",
",",
"\"<br />\\n\"",
")",
";",
"}"
] | /*
newline_to_br(input)
Add <br /> tags in front of all newlines in input string | [
"/",
"*",
"newline_to_br",
"(",
"input",
")"
] | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-narrativegenerator/src/main/java/ca/uhn/fhir/narrative/template/filters/Newline_To_Br.java#L10-L14 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/linear/NewGLMNET.java | NewGLMNET.setC | @WarmParameter(prefLowToHigh = true)
public void setC(double C)
{
if(C <= 0 || Double.isInfinite(C) || Double.isNaN(C))
throw new IllegalArgumentException("Regularization term C must be a positive value, not " + C);
this.C = C;
} | java | @WarmParameter(prefLowToHigh = true)
public void setC(double C)
{
if(C <= 0 || Double.isInfinite(C) || Double.isNaN(C))
throw new IllegalArgumentException("Regularization term C must be a positive value, not " + C);
this.C = C;
} | [
"@",
"WarmParameter",
"(",
"prefLowToHigh",
"=",
"true",
")",
"public",
"void",
"setC",
"(",
"double",
"C",
")",
"{",
"if",
"(",
"C",
"<=",
"0",
"||",
"Double",
".",
"isInfinite",
"(",
"C",
")",
"||",
"Double",
".",
"isNaN",
"(",
"C",
")",
")",
"... | Sets the regularization term, where smaller values indicate a larger
regularization penalty.
@param C the positive regularization term | [
"Sets",
"the",
"regularization",
"term",
"where",
"smaller",
"values",
"indicate",
"a",
"larger",
"regularization",
"penalty",
"."
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/NewGLMNET.java#L156-L162 |
timols/java-gitlab-api | src/main/java/org/gitlab/api/GitlabAPI.java | GitlabAPI.addProjectMember | public GitlabProjectMember addProjectMember(GitlabProject project, GitlabUser user, GitlabAccessLevel accessLevel) throws IOException {
return addProjectMember(project.getId(), user.getId(), accessLevel);
} | java | public GitlabProjectMember addProjectMember(GitlabProject project, GitlabUser user, GitlabAccessLevel accessLevel) throws IOException {
return addProjectMember(project.getId(), user.getId(), accessLevel);
} | [
"public",
"GitlabProjectMember",
"addProjectMember",
"(",
"GitlabProject",
"project",
",",
"GitlabUser",
"user",
",",
"GitlabAccessLevel",
"accessLevel",
")",
"throws",
"IOException",
"{",
"return",
"addProjectMember",
"(",
"project",
".",
"getId",
"(",
")",
",",
"u... | Add a project member.
@param project the GitlabProject
@param user the GitlabUser
@param accessLevel the GitlabAccessLevel
@return the GitlabProjectMember
@throws IOException on gitlab api call error | [
"Add",
"a",
"project",
"member",
"."
] | train | https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3028-L3030 |
NoraUi/NoraUi | src/main/java/com/github/noraui/browser/DriverFactory.java | DriverFactory.generateWebDriver | private WebDriver generateWebDriver(String driverName) throws TechnicalException {
WebDriver driver;
if (IE.equals(driverName)) {
driver = generateIEDriver();
} else if (CHROME.equals(driverName)) {
driver = generateGoogleChromeDriver();
} else if (FIREFOX.equals(driverName)) {
driver = generateFirefoxDriver();
} else {
driver = generateGoogleChromeDriver();
}
// As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).
driver.manage().window().setSize(new Dimension(1920, 1080));
driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.MILLISECONDS);
drivers.put(driverName, driver);
return driver;
} | java | private WebDriver generateWebDriver(String driverName) throws TechnicalException {
WebDriver driver;
if (IE.equals(driverName)) {
driver = generateIEDriver();
} else if (CHROME.equals(driverName)) {
driver = generateGoogleChromeDriver();
} else if (FIREFOX.equals(driverName)) {
driver = generateFirefoxDriver();
} else {
driver = generateGoogleChromeDriver();
}
// As a workaround: NoraUi specify window size manually, e.g. window_size: 1920 x 1080 (instead of .window().maximize()).
driver.manage().window().setSize(new Dimension(1920, 1080));
driver.manage().timeouts().implicitlyWait(IMPLICIT_WAIT, TimeUnit.MILLISECONDS);
drivers.put(driverName, driver);
return driver;
} | [
"private",
"WebDriver",
"generateWebDriver",
"(",
"String",
"driverName",
")",
"throws",
"TechnicalException",
"{",
"WebDriver",
"driver",
";",
"if",
"(",
"IE",
".",
"equals",
"(",
"driverName",
")",
")",
"{",
"driver",
"=",
"generateIEDriver",
"(",
")",
";",
... | Generates a selenium webdriver following a name given in parameter.
By default a chrome driver is generated.
@param driverName
The name of the web driver to generate
@return
An instance a web driver whose type is provided by driver name given in parameter
@throws TechnicalException
if an error occured when Webdriver setExecutable to true. | [
"Generates",
"a",
"selenium",
"webdriver",
"following",
"a",
"name",
"given",
"in",
"parameter",
".",
"By",
"default",
"a",
"chrome",
"driver",
"is",
"generated",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/browser/DriverFactory.java#L253-L270 |
alkacon/opencms-core | src-modules/org/opencms/workplace/tools/sites/CmsSitesWebserverDialog.java | CmsSitesWebserverDialog.getParameter | private String getParameter(Map<String, String> params, String key, String defaultValue) {
String value = params.get(key);
return (value != null) ? value : defaultValue;
} | java | private String getParameter(Map<String, String> params, String key, String defaultValue) {
String value = params.get(key);
return (value != null) ? value : defaultValue;
} | [
"private",
"String",
"getParameter",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"params",
",",
"String",
"key",
",",
"String",
"defaultValue",
")",
"{",
"String",
"value",
"=",
"params",
".",
"get",
"(",
"key",
")",
";",
"return",
"(",
"value",
"!=... | Returns a parameter value from the module parameters,
or a given default value in case the parameter is not set.<p>
@param params the parameter map to get a value from
@param key the parameter to return the value for
@param defaultValue the default value in case there is no value stored for this key
@return the parameter value from the module parameters | [
"Returns",
"a",
"parameter",
"value",
"from",
"the",
"module",
"parameters",
"or",
"a",
"given",
"default",
"value",
"in",
"case",
"the",
"parameter",
"is",
"not",
"set",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/tools/sites/CmsSitesWebserverDialog.java#L429-L433 |
OpenLiberty/open-liberty | dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java | ProbeManagerImpl.buildListenersFromAnnotated | Set<ProbeListener> buildListenersFromAnnotated(Object monitor) {
Set<ProbeListener> listeners = new HashSet<ProbeListener>();
Class<?> clazz = monitor.getClass();
for (Method method : ReflectionHelper.getMethods(clazz)) {
ProbeSite probeSite = method.getAnnotation(ProbeSite.class);
if (probeSite == null) {
continue;
}
synchronized (notMonitorable) {
Class<?> rClass = null;
for (Class<?> tClass : notMonitorable) {
if (tClass != null && ((tClass.getName()).equals(probeSite.clazz()))) {
rClass = tClass;
monitorable.add(tClass);
break;
}
}
if (rClass != null) {
notMonitorable.remove(rClass);
}
}
// TODO: Handle monitoring groups
Monitor monitorData = clazz.getAnnotation(Monitor.class);
ListenerConfiguration config = new ListenerConfiguration(monitorData, probeSite, method);
// ProbeListener listener = new ProbeListener(this, config, monitor, method);
ProbeListener listener = new ProbeListener(null, config, monitor, method);
listeners.add(listener);
}
return listeners;
} | java | Set<ProbeListener> buildListenersFromAnnotated(Object monitor) {
Set<ProbeListener> listeners = new HashSet<ProbeListener>();
Class<?> clazz = monitor.getClass();
for (Method method : ReflectionHelper.getMethods(clazz)) {
ProbeSite probeSite = method.getAnnotation(ProbeSite.class);
if (probeSite == null) {
continue;
}
synchronized (notMonitorable) {
Class<?> rClass = null;
for (Class<?> tClass : notMonitorable) {
if (tClass != null && ((tClass.getName()).equals(probeSite.clazz()))) {
rClass = tClass;
monitorable.add(tClass);
break;
}
}
if (rClass != null) {
notMonitorable.remove(rClass);
}
}
// TODO: Handle monitoring groups
Monitor monitorData = clazz.getAnnotation(Monitor.class);
ListenerConfiguration config = new ListenerConfiguration(monitorData, probeSite, method);
// ProbeListener listener = new ProbeListener(this, config, monitor, method);
ProbeListener listener = new ProbeListener(null, config, monitor, method);
listeners.add(listener);
}
return listeners;
} | [
"Set",
"<",
"ProbeListener",
">",
"buildListenersFromAnnotated",
"(",
"Object",
"monitor",
")",
"{",
"Set",
"<",
"ProbeListener",
">",
"listeners",
"=",
"new",
"HashSet",
"<",
"ProbeListener",
">",
"(",
")",
";",
"Class",
"<",
"?",
">",
"clazz",
"=",
"moni... | Create a set of {@link ProbeListener}s that delegate annotated
methods on the specified monitor.
@return the set of listeners to activate | [
"Create",
"a",
"set",
"of",
"{",
"@link",
"ProbeListener",
"}",
"s",
"that",
"delegate",
"annotated",
"methods",
"on",
"the",
"specified",
"monitor",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.monitor/src/com/ibm/ws/monitor/internal/ProbeManagerImpl.java#L384-L415 |
networknt/light-4j | utility/src/main/java/com/networknt/utility/NioUtils.java | NioUtils.deleteOldFiles | public static void deleteOldFiles(String dirPath, int olderThanMinute) {
File folder = new File(dirPath);
if (folder.exists()) {
File[] listFiles = folder.listFiles();
long eligibleForDeletion = System.currentTimeMillis() - (olderThanMinute * 60 * 1000L);
for (File listFile: listFiles) {
if (listFile.lastModified() < eligibleForDeletion) {
if (!listFile.delete()) {
logger.error("Unable to delete file %s", listFile);
}
}
}
}
} | java | public static void deleteOldFiles(String dirPath, int olderThanMinute) {
File folder = new File(dirPath);
if (folder.exists()) {
File[] listFiles = folder.listFiles();
long eligibleForDeletion = System.currentTimeMillis() - (olderThanMinute * 60 * 1000L);
for (File listFile: listFiles) {
if (listFile.lastModified() < eligibleForDeletion) {
if (!listFile.delete()) {
logger.error("Unable to delete file %s", listFile);
}
}
}
}
} | [
"public",
"static",
"void",
"deleteOldFiles",
"(",
"String",
"dirPath",
",",
"int",
"olderThanMinute",
")",
"{",
"File",
"folder",
"=",
"new",
"File",
"(",
"dirPath",
")",
";",
"if",
"(",
"folder",
".",
"exists",
"(",
")",
")",
"{",
"File",
"[",
"]",
... | Delele old files
@param dirPath path of the filesystem
@param olderThanMinute the minutes that defines older files | [
"Delele",
"old",
"files"
] | train | https://github.com/networknt/light-4j/blob/2a60257c60663684c8f6dc8b5ea3cf184e534db6/utility/src/main/java/com/networknt/utility/NioUtils.java#L230-L244 |
TheCoder4eu/BootsFaces-OSP | src/main/java/net/bootsfaces/component/flyOutMenu/FlyOutMenuRenderer.java | FlyOutMenuRenderer.encodeBegin | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
FlyOutMenu flyOutMenu = (FlyOutMenu) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = flyOutMenu.getClientId();
// put custom code here
// Simple demo widget that simply renders every attribute value
rw.startElement("ul", flyOutMenu);
rw.writeAttribute("id", clientId, "id");
Tooltip.generateTooltip(context, flyOutMenu, rw);
String styleClass = flyOutMenu.getStyleClass();
if (null == styleClass)
styleClass = "dropdown-menu";
else
styleClass = "dropdown-menu " + flyOutMenu.getStyleClass();
writeAttribute(rw, "class", styleClass);
String width = flyOutMenu.getWidth();
addUnitToWidthIfNecessary(width);
String style = flyOutMenu.getStyle();
if (null == style)
style = "display: block; position: static; margin-bottom: 5px; *width: "+width;
else
style = "display: block; position: static; margin-bottom: 5px; *width: " + width +";" + flyOutMenu.getStyle();
writeAttribute(rw, "style", style);
} | java | @Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
if (!component.isRendered()) {
return;
}
FlyOutMenu flyOutMenu = (FlyOutMenu) component;
ResponseWriter rw = context.getResponseWriter();
String clientId = flyOutMenu.getClientId();
// put custom code here
// Simple demo widget that simply renders every attribute value
rw.startElement("ul", flyOutMenu);
rw.writeAttribute("id", clientId, "id");
Tooltip.generateTooltip(context, flyOutMenu, rw);
String styleClass = flyOutMenu.getStyleClass();
if (null == styleClass)
styleClass = "dropdown-menu";
else
styleClass = "dropdown-menu " + flyOutMenu.getStyleClass();
writeAttribute(rw, "class", styleClass);
String width = flyOutMenu.getWidth();
addUnitToWidthIfNecessary(width);
String style = flyOutMenu.getStyle();
if (null == style)
style = "display: block; position: static; margin-bottom: 5px; *width: "+width;
else
style = "display: block; position: static; margin-bottom: 5px; *width: " + width +";" + flyOutMenu.getStyle();
writeAttribute(rw, "style", style);
} | [
"@",
"Override",
"public",
"void",
"encodeBegin",
"(",
"FacesContext",
"context",
",",
"UIComponent",
"component",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"component",
".",
"isRendered",
"(",
")",
")",
"{",
"return",
";",
"}",
"FlyOutMenu",
"flyOu... | This methods generates the HTML code of the current b:flyOutMenu.
<code>encodeBegin</code> generates the start of the component. After the,
the JSF framework calls <code>encodeChildren()</code> to generate the
HTML code between the beginning and the end of the component. For
instance, in the case of a panel component the content of the panel is
generated by <code>encodeChildren()</code>. After that,
<code>encodeEnd()</code> is called to generate the rest of the HTML code.
@param context
the FacesContext.
@param component
the current b:flyOutMenu.
@throws IOException
thrown if something goes wrong when writing the HTML code. | [
"This",
"methods",
"generates",
"the",
"HTML",
"code",
"of",
"the",
"current",
"b",
":",
"flyOutMenu",
".",
"<code",
">",
"encodeBegin<",
"/",
"code",
">",
"generates",
"the",
"start",
"of",
"the",
"component",
".",
"After",
"the",
"the",
"JSF",
"framework... | train | https://github.com/TheCoder4eu/BootsFaces-OSP/blob/d1a70952bc240979b5272fa4fe1c7f100873add0/src/main/java/net/bootsfaces/component/flyOutMenu/FlyOutMenuRenderer.java#L51-L81 |
joniles/mpxj | src/main/java/net/sf/mpxj/mpx/MPXWriter.java | MPXWriter.writeCalendarException | private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
{
m_buffer.setLength(0);
if (!parentCalendar.isDerived())
{
m_buffer.append(MPXConstants.BASE_CALENDAR_EXCEPTION_RECORD_NUMBER);
}
else
{
m_buffer.append(MPXConstants.RESOURCE_CALENDAR_EXCEPTION_RECORD_NUMBER);
}
m_buffer.append(m_delimiter);
m_buffer.append(format(formatDate(record.getFromDate())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatDate(record.getToDate())));
m_buffer.append(m_delimiter);
m_buffer.append(record.getWorking() ? "1" : "0");
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(0).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(0).getEnd())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(1).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(1).getEnd())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(2).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(2).getEnd())));
stripTrailingDelimiters(m_buffer);
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | java | private void writeCalendarException(ProjectCalendar parentCalendar, ProjectCalendarException record) throws IOException
{
m_buffer.setLength(0);
if (!parentCalendar.isDerived())
{
m_buffer.append(MPXConstants.BASE_CALENDAR_EXCEPTION_RECORD_NUMBER);
}
else
{
m_buffer.append(MPXConstants.RESOURCE_CALENDAR_EXCEPTION_RECORD_NUMBER);
}
m_buffer.append(m_delimiter);
m_buffer.append(format(formatDate(record.getFromDate())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatDate(record.getToDate())));
m_buffer.append(m_delimiter);
m_buffer.append(record.getWorking() ? "1" : "0");
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(0).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(0).getEnd())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(1).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(1).getEnd())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(2).getStart())));
m_buffer.append(m_delimiter);
m_buffer.append(format(formatTime(record.getRange(2).getEnd())));
stripTrailingDelimiters(m_buffer);
m_buffer.append(MPXConstants.EOL);
m_writer.write(m_buffer.toString());
} | [
"private",
"void",
"writeCalendarException",
"(",
"ProjectCalendar",
"parentCalendar",
",",
"ProjectCalendarException",
"record",
")",
"throws",
"IOException",
"{",
"m_buffer",
".",
"setLength",
"(",
"0",
")",
";",
"if",
"(",
"!",
"parentCalendar",
".",
"isDerived",... | Write a calendar exception.
@param parentCalendar parent calendar instance
@param record calendar exception instance
@throws IOException | [
"Write",
"a",
"calendar",
"exception",
"."
] | train | https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpx/MPXWriter.java#L455-L489 |
buyi/RecyclerViewPagerIndicator | recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java | RecyclerTitlePageIndicator.clipViewOnTheRight | private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, int right) {
curViewBound.right = (int) (right - mClipPadding);
curViewBound.left = (int) (curViewBound.right - curViewWidth);
} | java | private void clipViewOnTheRight(Rect curViewBound, float curViewWidth, int right) {
curViewBound.right = (int) (right - mClipPadding);
curViewBound.left = (int) (curViewBound.right - curViewWidth);
} | [
"private",
"void",
"clipViewOnTheRight",
"(",
"Rect",
"curViewBound",
",",
"float",
"curViewWidth",
",",
"int",
"right",
")",
"{",
"curViewBound",
".",
"right",
"=",
"(",
"int",
")",
"(",
"right",
"-",
"mClipPadding",
")",
";",
"curViewBound",
".",
"left",
... | Set bounds for the right textView including clip padding.
@param curViewBound
current bounds.
@param curViewWidth
width of the view. | [
"Set",
"bounds",
"for",
"the",
"right",
"textView",
"including",
"clip",
"padding",
"."
] | train | https://github.com/buyi/RecyclerViewPagerIndicator/blob/b3b5283801b60d40f7325c7f590c945262194fad/recycler-viewpager-indicator/src/main/java/com/viewpagerindicator/as/library/indicator/RecyclerTitlePageIndicator.java#L647-L650 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java | ReflectUtil.getMethodIgnoreCase | public static Method getMethodIgnoreCase(Class<?> clazz, String methodName, Class<?>... paramTypes) throws SecurityException {
return getMethod(clazz, true, methodName, paramTypes);
} | java | public static Method getMethodIgnoreCase(Class<?> clazz, String methodName, Class<?>... paramTypes) throws SecurityException {
return getMethod(clazz, true, methodName, paramTypes);
} | [
"public",
"static",
"Method",
"getMethodIgnoreCase",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"...",
"paramTypes",
")",
"throws",
"SecurityException",
"{",
"return",
"getMethod",
"(",
"clazz",
",",
"true... | 忽略大小写查找指定方法,如果找不到对应的方法则返回<code>null</code>
<p>
此方法为精准获取方法名,即方法名和参数数量和类型必须一致,否则返回<code>null</code>。
</p>
@param clazz 类,如果为{@code null}返回{@code null}
@param methodName 方法名,如果为空字符串返回{@code null}
@param paramTypes 参数类型,指定参数类型如果是方法的子类也算
@return 方法
@throws SecurityException 无权访问抛出异常
@since 3.2.0 | [
"忽略大小写查找指定方法,如果找不到对应的方法则返回<code",
">",
"null<",
"/",
"code",
">"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ReflectUtil.java#L414-L416 |
jblas-project/jblas | src/main/java/org/jblas/ComplexDouble.java | ComplexDouble.addi | public ComplexDouble addi(double a, ComplexDouble result) {
if (this == result) {
r += a;
} else {
result.r = r + a;
result.i = i;
}
return result;
} | java | public ComplexDouble addi(double a, ComplexDouble result) {
if (this == result) {
r += a;
} else {
result.r = r + a;
result.i = i;
}
return result;
} | [
"public",
"ComplexDouble",
"addi",
"(",
"double",
"a",
",",
"ComplexDouble",
"result",
")",
"{",
"if",
"(",
"this",
"==",
"result",
")",
"{",
"r",
"+=",
"a",
";",
"}",
"else",
"{",
"result",
".",
"r",
"=",
"r",
"+",
"a",
";",
"result",
".",
"i",
... | Add a real number to a complex number in-place.
@param a real number to add
@param result complex number to hold result
@return same as result | [
"Add",
"a",
"real",
"number",
"to",
"a",
"complex",
"number",
"in",
"-",
"place",
"."
] | train | https://github.com/jblas-project/jblas/blob/2818f231228e655cda80dfd8e0b87709fdfd8a70/src/main/java/org/jblas/ComplexDouble.java#L139-L147 |
xcesco/kripton | kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java | JQLBuilder.buildJQLDelete | private static JQL buildJQLDelete(SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
final SQLiteDaoDefinition dao = method.getParent();
if (StringUtils.hasText(preparedJql)) {
// in DELETE SQL only where statement can contains bind parameter
result.value = preparedJql;
JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {
@Override
public void enterBind_parameter(Bind_parameterContext ctx) {
result.bindParameterOnWhereStatementCounter++;
}
@Override
public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
String dynamicWhere = result.value.substring(start, stop);
dynamicReplace.put(dynamicType, dynamicWhere);
}
});
// where management
JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {
@Override
public String onWhere(String statement) {
result.annotatedWhere = true;
result.staticWhereConditions = true;
return null;
}
});
} else {
StringBuilder builder = new StringBuilder();
builder.append(DELETE_KEYWORD + " " + FROM_KEYWORD);
// entity name
builder.append(" " + dao.getEntitySimplyClassName());
builder.append(defineWhereStatement(method, result, BindSqlDelete.class, dynamicReplace));
result.value = builder.toString();
}
result.operationType = JQLType.DELETE;
result.dynamicReplace = dynamicReplace;
return result;
} | java | private static JQL buildJQLDelete(SQLiteModelMethod method, final JQL result, final Map<JQLDynamicStatementType, String> dynamicReplace, String preparedJql) {
final SQLiteDaoDefinition dao = method.getParent();
if (StringUtils.hasText(preparedJql)) {
// in DELETE SQL only where statement can contains bind parameter
result.value = preparedJql;
JQLChecker.getInstance().analyze(method, result, new JqlBaseListener() {
@Override
public void enterBind_parameter(Bind_parameterContext ctx) {
result.bindParameterOnWhereStatementCounter++;
}
@Override
public void enterBind_dynamic_sql(Bind_dynamic_sqlContext ctx) {
JQLDynamicStatementType dynamicType = JQLDynamicStatementType.valueOf(ctx.bind_parameter_name().getText().toUpperCase());
int start = ctx.getStart().getStartIndex() - 1;
int stop = ctx.getStop().getStopIndex() + 1;
String dynamicWhere = result.value.substring(start, stop);
dynamicReplace.put(dynamicType, dynamicWhere);
}
});
// where management
JQLChecker.getInstance().replaceVariableStatements(method, preparedJql, new JQLReplaceVariableStatementListenerImpl() {
@Override
public String onWhere(String statement) {
result.annotatedWhere = true;
result.staticWhereConditions = true;
return null;
}
});
} else {
StringBuilder builder = new StringBuilder();
builder.append(DELETE_KEYWORD + " " + FROM_KEYWORD);
// entity name
builder.append(" " + dao.getEntitySimplyClassName());
builder.append(defineWhereStatement(method, result, BindSqlDelete.class, dynamicReplace));
result.value = builder.toString();
}
result.operationType = JQLType.DELETE;
result.dynamicReplace = dynamicReplace;
return result;
} | [
"private",
"static",
"JQL",
"buildJQLDelete",
"(",
"SQLiteModelMethod",
"method",
",",
"final",
"JQL",
"result",
",",
"final",
"Map",
"<",
"JQLDynamicStatementType",
",",
"String",
">",
"dynamicReplace",
",",
"String",
"preparedJql",
")",
"{",
"final",
"SQLiteDaoD... | <pre>
DELETE person WHERE id = :bean.id AND #{where}
</pre>
@param method
the method
@param result
the result
@param dynamicReplace
the dynamic replace
@param preparedJql
the prepared jql
@return the jql | [
"<pre",
">",
"DELETE",
"person",
"WHERE",
"id",
"=",
":",
"bean",
".",
"id",
"AND",
"#",
"{",
"where",
"}",
"<",
"/",
"pre",
">"
] | train | https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sqlite/grammars/jql/JQLBuilder.java#L222-L273 |
dbracewell/hermes | hermes-core/src/main/java/com/davidbracewell/hermes/Document.java | Document.createAnnotation | public Annotation createAnnotation(@NonNull AnnotationType type, int start, int end, @NonNull Map<AttributeType, ?> attributeMap) {
Preconditions.checkArgument(start >= start(),
"Annotation must have a starting position >= the start of the document");
Preconditions.checkArgument(end <= end(), "Annotation must have a ending position <= the end of the document");
Annotation annotation = new Annotation(this, type, start, end);
annotation.setId(idGenerator.getAndIncrement());
annotation.putAll(attributeMap);
annotationSet.add(annotation);
return annotation;
} | java | public Annotation createAnnotation(@NonNull AnnotationType type, int start, int end, @NonNull Map<AttributeType, ?> attributeMap) {
Preconditions.checkArgument(start >= start(),
"Annotation must have a starting position >= the start of the document");
Preconditions.checkArgument(end <= end(), "Annotation must have a ending position <= the end of the document");
Annotation annotation = new Annotation(this, type, start, end);
annotation.setId(idGenerator.getAndIncrement());
annotation.putAll(attributeMap);
annotationSet.add(annotation);
return annotation;
} | [
"public",
"Annotation",
"createAnnotation",
"(",
"@",
"NonNull",
"AnnotationType",
"type",
",",
"int",
"start",
",",
"int",
"end",
",",
"@",
"NonNull",
"Map",
"<",
"AttributeType",
",",
"?",
">",
"attributeMap",
")",
"{",
"Preconditions",
".",
"checkArgument",... | Creates an annotation of the given type encompassing the given span and having the given attributes. The
annotation
is added to the document and has a unique id assigned.
@param type the type of annotation
@param start the start of the span
@param end the end of the span
@param attributeMap the attributes associated with the annotation
@return the created annotation | [
"Creates",
"an",
"annotation",
"of",
"the",
"given",
"type",
"encompassing",
"the",
"given",
"span",
"and",
"having",
"the",
"given",
"attributes",
".",
"The",
"annotation",
"is",
"added",
"to",
"the",
"document",
"and",
"has",
"a",
"unique",
"id",
"assigned... | train | https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/Document.java#L366-L375 |
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.xmlClassExistent | public static void xmlClassExistent(String path, Class<?> aClass){
throw new XmlMappingClassExistException (MSG.INSTANCE.message(xmlMappingClassExistException1,aClass.getSimpleName(),path));
} | java | public static void xmlClassExistent(String path, Class<?> aClass){
throw new XmlMappingClassExistException (MSG.INSTANCE.message(xmlMappingClassExistException1,aClass.getSimpleName(),path));
} | [
"public",
"static",
"void",
"xmlClassExistent",
"(",
"String",
"path",
",",
"Class",
"<",
"?",
">",
"aClass",
")",
"{",
"throw",
"new",
"XmlMappingClassExistException",
"(",
"MSG",
".",
"INSTANCE",
".",
"message",
"(",
"xmlMappingClassExistException1",
",",
"aCl... | Thrown if class is present in xml file.
@param path xml path
@param aClass Class analyzed | [
"Thrown",
"if",
"class",
"is",
"present",
"in",
"xml",
"file",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L319-L321 |
nmdp-bioinformatics/ngs | hml/src/main/java/org/nmdp/ngs/hml/HmlUtils.java | HmlUtils.createSequences | public static Iterable<Sequence> createSequences(final BufferedReader reader) throws IOException {
checkNotNull(reader);
List<Sequence> sequences = new ArrayList<Sequence>();
for (SequenceIterator it = SeqIOTools.readFastaDNA(reader); it.hasNext(); ) {
try {
sequences.add(createSequence(it.nextSequence()));
}
catch (BioException e) {
throw new IOException("could not read DNA sequences", e);
}
}
return sequences;
} | java | public static Iterable<Sequence> createSequences(final BufferedReader reader) throws IOException {
checkNotNull(reader);
List<Sequence> sequences = new ArrayList<Sequence>();
for (SequenceIterator it = SeqIOTools.readFastaDNA(reader); it.hasNext(); ) {
try {
sequences.add(createSequence(it.nextSequence()));
}
catch (BioException e) {
throw new IOException("could not read DNA sequences", e);
}
}
return sequences;
} | [
"public",
"static",
"Iterable",
"<",
"Sequence",
">",
"createSequences",
"(",
"final",
"BufferedReader",
"reader",
")",
"throws",
"IOException",
"{",
"checkNotNull",
"(",
"reader",
")",
";",
"List",
"<",
"Sequence",
">",
"sequences",
"=",
"new",
"ArrayList",
"... | Create and return zero or more DNA HML Sequences read from the specified reader in FASTA format.
@param reader reader to read from, must not be null
@return zero or more DNA HML Sequences read from the specified reader in FASTA format
@throws IOException if an I/O error occurs | [
"Create",
"and",
"return",
"zero",
"or",
"more",
"DNA",
"HML",
"Sequences",
"read",
"from",
"the",
"specified",
"reader",
"in",
"FASTA",
"format",
"."
] | train | https://github.com/nmdp-bioinformatics/ngs/blob/277627e4311313a80f5dc110b3185b0d7af32bd0/hml/src/main/java/org/nmdp/ngs/hml/HmlUtils.java#L94-L106 |
zk1931/jzab | src/main/java/com/github/zk1931/jzab/MessageBuilder.java | MessageBuilder.fromProposal | public static Transaction fromProposal(Proposal prop) {
Zxid zxid = fromProtoZxid(prop.getZxid());
ByteBuffer buffer = prop.getBody().asReadOnlyByteBuffer();
return new Transaction(zxid, prop.getType().getNumber(), buffer);
} | java | public static Transaction fromProposal(Proposal prop) {
Zxid zxid = fromProtoZxid(prop.getZxid());
ByteBuffer buffer = prop.getBody().asReadOnlyByteBuffer();
return new Transaction(zxid, prop.getType().getNumber(), buffer);
} | [
"public",
"static",
"Transaction",
"fromProposal",
"(",
"Proposal",
"prop",
")",
"{",
"Zxid",
"zxid",
"=",
"fromProtoZxid",
"(",
"prop",
".",
"getZxid",
"(",
")",
")",
";",
"ByteBuffer",
"buffer",
"=",
"prop",
".",
"getBody",
"(",
")",
".",
"asReadOnlyByte... | Converts protobuf Proposal object to Transaction object.
@param prop the protobuf Proposal object.
@return the Transaction object. | [
"Converts",
"protobuf",
"Proposal",
"object",
"to",
"Transaction",
"object",
"."
] | train | https://github.com/zk1931/jzab/blob/2a8893bcc1a125f3aebdaddee80ad49c9761bba1/src/main/java/com/github/zk1931/jzab/MessageBuilder.java#L83-L87 |
atomix/catalyst | concurrent/src/main/java/io/atomix/catalyst/concurrent/Runnables.java | Runnables.logFailure | static Runnable logFailure(final Runnable runnable, Logger logger) {
return () -> {
try {
runnable.run();
} catch (Throwable t) {
if (!(t instanceof RejectedExecutionException)) {
logger.error("An uncaught exception occurred", t);
}
throw t;
}
};
} | java | static Runnable logFailure(final Runnable runnable, Logger logger) {
return () -> {
try {
runnable.run();
} catch (Throwable t) {
if (!(t instanceof RejectedExecutionException)) {
logger.error("An uncaught exception occurred", t);
}
throw t;
}
};
} | [
"static",
"Runnable",
"logFailure",
"(",
"final",
"Runnable",
"runnable",
",",
"Logger",
"logger",
")",
"{",
"return",
"(",
")",
"->",
"{",
"try",
"{",
"runnable",
".",
"run",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"if",
"(",
... | Returns a wrapped runnable that logs and rethrows uncaught exceptions. | [
"Returns",
"a",
"wrapped",
"runnable",
"that",
"logs",
"and",
"rethrows",
"uncaught",
"exceptions",
"."
] | train | https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/concurrent/src/main/java/io/atomix/catalyst/concurrent/Runnables.java#L17-L28 |
atomix/atomix | utils/src/main/java/io/atomix/utils/concurrent/Retries.java | Retries.randomDelay | public static void randomDelay(int ms) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(ms));
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted", e);
}
} | java | public static void randomDelay(int ms) {
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(ms));
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted", e);
}
} | [
"public",
"static",
"void",
"randomDelay",
"(",
"int",
"ms",
")",
"{",
"try",
"{",
"Thread",
".",
"sleep",
"(",
"ThreadLocalRandom",
".",
"current",
"(",
")",
".",
"nextInt",
"(",
"ms",
")",
")",
";",
"}",
"catch",
"(",
"InterruptedException",
"e",
")"... | Suspends the current thread for a random number of millis between 0 and
the indicated limit.
@param ms max number of millis | [
"Suspends",
"the",
"current",
"thread",
"for",
"a",
"random",
"number",
"of",
"millis",
"between",
"0",
"and",
"the",
"indicated",
"limit",
"."
] | train | https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/utils/src/main/java/io/atomix/utils/concurrent/Retries.java#L71-L77 |
marklogic/marklogic-sesame | marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java | MarkLogicClient.sendTupleQuery | public TupleQueryResult sendTupleQuery(String queryString,SPARQLQueryBindingSet bindings, long start, long pageLength, boolean includeInferred, String baseURI) throws RepositoryException, MalformedQueryException,
QueryInterruptedException {
InputStream stream = null;
try {
stream = getClient().performSPARQLQuery(queryString, bindings, start, pageLength, this.tx, includeInferred, baseURI);
} catch (JsonProcessingException e) {
logger.error(e.getLocalizedMessage());
throw new MarkLogicSesameException("Issue processing json.");
}
TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
MarkLogicBackgroundTupleResult tRes = new MarkLogicBackgroundTupleResult(parser,stream);
execute(tRes);
return tRes;
} | java | public TupleQueryResult sendTupleQuery(String queryString,SPARQLQueryBindingSet bindings, long start, long pageLength, boolean includeInferred, String baseURI) throws RepositoryException, MalformedQueryException,
QueryInterruptedException {
InputStream stream = null;
try {
stream = getClient().performSPARQLQuery(queryString, bindings, start, pageLength, this.tx, includeInferred, baseURI);
} catch (JsonProcessingException e) {
logger.error(e.getLocalizedMessage());
throw new MarkLogicSesameException("Issue processing json.");
}
TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
MarkLogicBackgroundTupleResult tRes = new MarkLogicBackgroundTupleResult(parser,stream);
execute(tRes);
return tRes;
} | [
"public",
"TupleQueryResult",
"sendTupleQuery",
"(",
"String",
"queryString",
",",
"SPARQLQueryBindingSet",
"bindings",
",",
"long",
"start",
",",
"long",
"pageLength",
",",
"boolean",
"includeInferred",
",",
"String",
"baseURI",
")",
"throws",
"RepositoryException",
... | TupleQuery
@param queryString
@param bindings
@param start
@param pageLength
@param includeInferred
@param baseURI
@return
@throws RepositoryException
@throws MalformedQueryException
@throws UnauthorizedException
@throws QueryInterruptedException | [
"TupleQuery"
] | train | https://github.com/marklogic/marklogic-sesame/blob/d5b668ed2b3d5e90c9f1d5096012813c272062a2/marklogic-sesame/src/main/java/com/marklogic/semantics/sesame/client/MarkLogicClient.java#L211-L224 |
Alluxio/alluxio | core/server/worker/src/main/java/alluxio/worker/block/BlockMetadataManager.java | BlockMetadataManager.getTempBlockMeta | public TempBlockMeta getTempBlockMeta(long blockId) throws BlockDoesNotExistException {
TempBlockMeta blockMeta = getTempBlockMetaOrNull(blockId);
if (blockMeta == null) {
throw new BlockDoesNotExistException(ExceptionMessage.TEMP_BLOCK_META_NOT_FOUND, blockId);
}
return blockMeta;
} | java | public TempBlockMeta getTempBlockMeta(long blockId) throws BlockDoesNotExistException {
TempBlockMeta blockMeta = getTempBlockMetaOrNull(blockId);
if (blockMeta == null) {
throw new BlockDoesNotExistException(ExceptionMessage.TEMP_BLOCK_META_NOT_FOUND, blockId);
}
return blockMeta;
} | [
"public",
"TempBlockMeta",
"getTempBlockMeta",
"(",
"long",
"blockId",
")",
"throws",
"BlockDoesNotExistException",
"{",
"TempBlockMeta",
"blockMeta",
"=",
"getTempBlockMetaOrNull",
"(",
"blockId",
")",
";",
"if",
"(",
"blockMeta",
"==",
"null",
")",
"{",
"throw",
... | Gets the metadata of a temp block.
@param blockId the id of the temp block
@return metadata of the block
@throws BlockDoesNotExistException when block id can not be found | [
"Gets",
"the",
"metadata",
"of",
"a",
"temp",
"block",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/worker/src/main/java/alluxio/worker/block/BlockMetadataManager.java#L252-L258 |
orbisgis/h2gis | h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMTablesFactory.java | OSMTablesFactory.dropOSMTables | public static void dropOSMTables(Connection connection, boolean isH2, String tablePrefix) throws SQLException {
TableLocation requestedTable = TableLocation.parse(tablePrefix, isH2);
String osmTableName = requestedTable.getTable();
String[] omsTables = new String[]{TAG, NODE, NODE_TAG, WAY, WAY_NODE, WAY_TAG, RELATION, RELATION_TAG, NODE_MEMBER, WAY_MEMBER, RELATION_MEMBER};
StringBuilder sb = new StringBuilder("drop table if exists ");
String omsTableSuffix = omsTables[0];
String osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
sb.append(osmTable);
for (int i = 1; i < omsTables.length; i++) {
omsTableSuffix = omsTables[i];
osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
sb.append(",").append(osmTable);
}
try (Statement stmt = connection.createStatement()) {
stmt.execute(sb.toString());
}
} | java | public static void dropOSMTables(Connection connection, boolean isH2, String tablePrefix) throws SQLException {
TableLocation requestedTable = TableLocation.parse(tablePrefix, isH2);
String osmTableName = requestedTable.getTable();
String[] omsTables = new String[]{TAG, NODE, NODE_TAG, WAY, WAY_NODE, WAY_TAG, RELATION, RELATION_TAG, NODE_MEMBER, WAY_MEMBER, RELATION_MEMBER};
StringBuilder sb = new StringBuilder("drop table if exists ");
String omsTableSuffix = omsTables[0];
String osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
sb.append(osmTable);
for (int i = 1; i < omsTables.length; i++) {
omsTableSuffix = omsTables[i];
osmTable = TableUtilities.caseIdentifier(requestedTable, osmTableName + omsTableSuffix, isH2);
sb.append(",").append(osmTable);
}
try (Statement stmt = connection.createStatement()) {
stmt.execute(sb.toString());
}
} | [
"public",
"static",
"void",
"dropOSMTables",
"(",
"Connection",
"connection",
",",
"boolean",
"isH2",
",",
"String",
"tablePrefix",
")",
"throws",
"SQLException",
"{",
"TableLocation",
"requestedTable",
"=",
"TableLocation",
".",
"parse",
"(",
"tablePrefix",
",",
... | Drop the existing OSM tables used to store the imported OSM data
@param connection
@param isH2
@param tablePrefix
@throws SQLException | [
"Drop",
"the",
"existing",
"OSM",
"tables",
"used",
"to",
"store",
"the",
"imported",
"OSM",
"data"
] | train | https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/osm/OSMTablesFactory.java#L327-L343 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java | SSLUtils.createRestSSLContext | @Nullable
private static SSLContext createRestSSLContext(Configuration config, RestSSLContextConfigMode configMode) throws Exception {
checkNotNull(config, "config");
if (!isRestSSLEnabled(config)) {
return null;
}
KeyManager[] keyManagers = null;
if (configMode == RestSSLContextConfigMode.SERVER || configMode == RestSSLContextConfigMode.MUTUAL) {
String keystoreFilePath = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEYSTORE, SecurityOptions.SSL_KEYSTORE);
String keystorePassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEYSTORE_PASSWORD, SecurityOptions.SSL_KEYSTORE_PASSWORD);
String certPassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEY_PASSWORD, SecurityOptions.SSL_KEY_PASSWORD);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
keyStore.load(keyStoreFile, keystorePassword.toCharArray());
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, certPassword.toCharArray());
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (configMode == RestSSLContextConfigMode.CLIENT || configMode == RestSSLContextConfigMode.MUTUAL) {
String trustStoreFilePath = getAndCheckOption(
config, SecurityOptions.SSL_REST_TRUSTSTORE, SecurityOptions.SSL_TRUSTSTORE);
String trustStorePassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_TRUSTSTORE_PASSWORD, SecurityOptions.SSL_TRUSTSTORE_PASSWORD);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream trustStoreFile = Files.newInputStream(new File(trustStoreFilePath).toPath())) {
trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
trustManagers = tmf.getTrustManagers();
}
String sslProtocolVersion = config.getString(SecurityOptions.SSL_PROTOCOL);
SSLContext sslContext = SSLContext.getInstance(sslProtocolVersion);
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
} | java | @Nullable
private static SSLContext createRestSSLContext(Configuration config, RestSSLContextConfigMode configMode) throws Exception {
checkNotNull(config, "config");
if (!isRestSSLEnabled(config)) {
return null;
}
KeyManager[] keyManagers = null;
if (configMode == RestSSLContextConfigMode.SERVER || configMode == RestSSLContextConfigMode.MUTUAL) {
String keystoreFilePath = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEYSTORE, SecurityOptions.SSL_KEYSTORE);
String keystorePassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEYSTORE_PASSWORD, SecurityOptions.SSL_KEYSTORE_PASSWORD);
String certPassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_KEY_PASSWORD, SecurityOptions.SSL_KEY_PASSWORD);
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream keyStoreFile = Files.newInputStream(new File(keystoreFilePath).toPath())) {
keyStore.load(keyStoreFile, keystorePassword.toCharArray());
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, certPassword.toCharArray());
keyManagers = kmf.getKeyManagers();
}
TrustManager[] trustManagers = null;
if (configMode == RestSSLContextConfigMode.CLIENT || configMode == RestSSLContextConfigMode.MUTUAL) {
String trustStoreFilePath = getAndCheckOption(
config, SecurityOptions.SSL_REST_TRUSTSTORE, SecurityOptions.SSL_TRUSTSTORE);
String trustStorePassword = getAndCheckOption(
config, SecurityOptions.SSL_REST_TRUSTSTORE_PASSWORD, SecurityOptions.SSL_TRUSTSTORE_PASSWORD);
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
try (InputStream trustStoreFile = Files.newInputStream(new File(trustStoreFilePath).toPath())) {
trustStore.load(trustStoreFile, trustStorePassword.toCharArray());
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
trustManagers = tmf.getTrustManagers();
}
String sslProtocolVersion = config.getString(SecurityOptions.SSL_PROTOCOL);
SSLContext sslContext = SSLContext.getInstance(sslProtocolVersion);
sslContext.init(keyManagers, trustManagers, null);
return sslContext;
} | [
"@",
"Nullable",
"private",
"static",
"SSLContext",
"createRestSSLContext",
"(",
"Configuration",
"config",
",",
"RestSSLContextConfigMode",
"configMode",
")",
"throws",
"Exception",
"{",
"checkNotNull",
"(",
"config",
",",
"\"config\"",
")",
";",
"if",
"(",
"!",
... | Creates an SSL context for the external REST SSL.
If mutual authentication is configured the client and the server side configuration are identical. | [
"Creates",
"an",
"SSL",
"context",
"for",
"the",
"external",
"REST",
"SSL",
".",
"If",
"mutual",
"authentication",
"is",
"configured",
"the",
"client",
"and",
"the",
"server",
"side",
"configuration",
"are",
"identical",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/net/SSLUtils.java#L269-L323 |
rholder/fauxflake | fauxflake-core/src/main/java/com/github/rholder/fauxflake/provider/twitter/SnowflakeEncodingProvider.java | SnowflakeEncodingProvider.encodeAsString | @Override
public String encodeAsString(long time, int sequence) {
return leftPad(toHexString(encodeAsLong(time, sequence)), 16, '0');
} | java | @Override
public String encodeAsString(long time, int sequence) {
return leftPad(toHexString(encodeAsLong(time, sequence)), 16, '0');
} | [
"@",
"Override",
"public",
"String",
"encodeAsString",
"(",
"long",
"time",
",",
"int",
"sequence",
")",
"{",
"return",
"leftPad",
"(",
"toHexString",
"(",
"encodeAsLong",
"(",
"time",
",",
"sequence",
")",
")",
",",
"16",
",",
"'",
"'",
")",
";",
"}"
... | Return the 16 character left padded hex version of the given id. These
can be lexicographically sorted. | [
"Return",
"the",
"16",
"character",
"left",
"padded",
"hex",
"version",
"of",
"the",
"given",
"id",
".",
"These",
"can",
"be",
"lexicographically",
"sorted",
"."
] | train | https://github.com/rholder/fauxflake/blob/54631faefdaf6b0b4d27b365f18c085771575cb3/fauxflake-core/src/main/java/com/github/rholder/fauxflake/provider/twitter/SnowflakeEncodingProvider.java#L97-L100 |
jbundle/jbundle | main/msg/src/main/java/org/jbundle/main/msg/db/MessageStatusField.java | MessageStatusField.setupDefaultView | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
ScreenComponent screenField = null;
this.makeReferenceRecord(); // Get/make the record that describes the referenced class.
screenField = this.setupIconView(itsLocation, targetScreen, converter, iDisplayFieldDesc, false);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_BUTTON_WITH_GAP, ScreenConstants.DONT_SET_ANCHOR);
iDisplayFieldDesc = ScreenConstants.DONT_DISPLAY_DESC;
screenField = super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
return screenField;
} | java | public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties)
{
ScreenComponent screenField = null;
this.makeReferenceRecord(); // Get/make the record that describes the referenced class.
screenField = this.setupIconView(itsLocation, targetScreen, converter, iDisplayFieldDesc, false);
itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_BUTTON_WITH_GAP, ScreenConstants.DONT_SET_ANCHOR);
iDisplayFieldDesc = ScreenConstants.DONT_DISPLAY_DESC;
screenField = super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties);
return screenField;
} | [
"public",
"ScreenComponent",
"setupDefaultView",
"(",
"ScreenLoc",
"itsLocation",
",",
"ComponentParent",
"targetScreen",
",",
"Convert",
"converter",
",",
"int",
"iDisplayFieldDesc",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"properties",
")",
"{",
"ScreenComp... | Set up the default screen control for this field.
@param itsLocation Location of this component on screen (ie., GridBagConstraint).
@param targetScreen Where to place this component (ie., Parent screen or GridBagLayout).
@param converter The converter to set the screenfield to.
@param iDisplayFieldDesc Display the label? (optional).
@param properties Extra properties
@return Return the component or ScreenField that is created for this field. | [
"Set",
"up",
"the",
"default",
"screen",
"control",
"for",
"this",
"field",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/main/msg/src/main/java/org/jbundle/main/msg/db/MessageStatusField.java#L72-L84 |
JOML-CI/JOML | src/org/joml/Quaterniond.java | Quaterniond.setAngleAxis | public Quaterniond setAngleAxis(double angle, double x, double y, double z) {
double s = Math.sin(angle * 0.5);
this.x = x * s;
this.y = y * s;
this.z = z * s;
this.w = Math.cosFromSin(s, angle * 0.5);
return this;
} | java | public Quaterniond setAngleAxis(double angle, double x, double y, double z) {
double s = Math.sin(angle * 0.5);
this.x = x * s;
this.y = y * s;
this.z = z * s;
this.w = Math.cosFromSin(s, angle * 0.5);
return this;
} | [
"public",
"Quaterniond",
"setAngleAxis",
"(",
"double",
"angle",
",",
"double",
"x",
",",
"double",
"y",
",",
"double",
"z",
")",
"{",
"double",
"s",
"=",
"Math",
".",
"sin",
"(",
"angle",
"*",
"0.5",
")",
";",
"this",
".",
"x",
"=",
"x",
"*",
"s... | Set this quaternion to a rotation equivalent to the supplied axis and
angle (in radians).
<p>
This method assumes that the given rotation axis <code>(x, y, z)</code> is already normalized
@param angle
the angle in radians
@param x
the x-component of the normalized rotation axis
@param y
the y-component of the normalized rotation axis
@param z
the z-component of the normalized rotation axis
@return this | [
"Set",
"this",
"quaternion",
"to",
"a",
"rotation",
"equivalent",
"to",
"the",
"supplied",
"axis",
"and",
"angle",
"(",
"in",
"radians",
")",
".",
"<p",
">",
"This",
"method",
"assumes",
"that",
"the",
"given",
"rotation",
"axis",
"<code",
">",
"(",
"x",... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Quaterniond.java#L399-L406 |
phax/ph-schedule | ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java | DateBuilder.nextGivenMinuteDate | public static Date nextGivenMinuteDate (final Date date, final int minuteBase)
{
if (minuteBase < 0 || minuteBase > 59)
{
throw new IllegalArgumentException ("minuteBase must be >=0 and <= 59");
}
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date != null ? date : new Date ());
c.setLenient (true);
if (minuteBase == 0)
{
c.set (Calendar.HOUR_OF_DAY, c.get (Calendar.HOUR_OF_DAY) + 1);
c.set (Calendar.MINUTE, 0);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
final int minute = c.get (Calendar.MINUTE);
final int arItr = minute / minuteBase;
final int nextMinuteOccurance = minuteBase * (arItr + 1);
if (nextMinuteOccurance < 60)
{
c.set (Calendar.MINUTE, nextMinuteOccurance);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
c.set (Calendar.HOUR_OF_DAY, c.get (Calendar.HOUR_OF_DAY) + 1);
c.set (Calendar.MINUTE, 0);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
}
return c.getTime ();
} | java | public static Date nextGivenMinuteDate (final Date date, final int minuteBase)
{
if (minuteBase < 0 || minuteBase > 59)
{
throw new IllegalArgumentException ("minuteBase must be >=0 and <= 59");
}
final Calendar c = PDTFactory.createCalendar ();
c.setTime (date != null ? date : new Date ());
c.setLenient (true);
if (minuteBase == 0)
{
c.set (Calendar.HOUR_OF_DAY, c.get (Calendar.HOUR_OF_DAY) + 1);
c.set (Calendar.MINUTE, 0);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
final int minute = c.get (Calendar.MINUTE);
final int arItr = minute / minuteBase;
final int nextMinuteOccurance = minuteBase * (arItr + 1);
if (nextMinuteOccurance < 60)
{
c.set (Calendar.MINUTE, nextMinuteOccurance);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
else
{
c.set (Calendar.HOUR_OF_DAY, c.get (Calendar.HOUR_OF_DAY) + 1);
c.set (Calendar.MINUTE, 0);
c.set (Calendar.SECOND, 0);
c.set (Calendar.MILLISECOND, 0);
}
}
return c.getTime ();
} | [
"public",
"static",
"Date",
"nextGivenMinuteDate",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"minuteBase",
")",
"{",
"if",
"(",
"minuteBase",
"<",
"0",
"||",
"minuteBase",
">",
"59",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"minu... | <p>
Returns a date that is rounded to the next even multiple of the given
minute.
</p>
<p>
For example an input date with a time of 08:13:54, and an input minute-base
of 5 would result in a date with the time of 08:15:00. The same input date
with an input minute-base of 10 would result in a date with the time of
08:20:00. But a date with the time 08:53:31 and an input minute-base of 45
would result in 09:00:00, because the even-hour is the next 'base' for
45-minute intervals.
</p>
<p>
More examples:
</p>
<table summary="examples">
<tr>
<th>Input Time</th>
<th>Minute-Base</th>
<th>Result Time</th>
</tr>
<tr>
<td>11:16:41</td>
<td>20</td>
<td>11:20:00</td>
</tr>
<tr>
<td>11:36:41</td>
<td>20</td>
<td>11:40:00</td>
</tr>
<tr>
<td>11:46:41</td>
<td>20</td>
<td>12:00:00</td>
</tr>
<tr>
<td>11:26:41</td>
<td>30</td>
<td>11:30:00</td>
</tr>
<tr>
<td>11:36:41</td>
<td>30</td>
<td>12:00:00</td>
</tr>
<tr>
<td>11:16:41</td>
<td>17</td>
<td>11:17:00</td>
</tr>
<tr>
<td>11:17:41</td>
<td>17</td>
<td>11:34:00</td>
</tr>
<tr>
<td>11:52:41</td>
<td>17</td>
<td>12:00:00</td>
</tr>
<tr>
<td>11:52:41</td>
<td>5</td>
<td>11:55:00</td>
</tr>
<tr>
<td>11:57:41</td>
<td>5</td>
<td>12:00:00</td>
</tr>
<tr>
<td>11:17:41</td>
<td>0</td>
<td>12:00:00</td>
</tr>
<tr>
<td>11:17:41</td>
<td>1</td>
<td>11:08:00</td>
</tr>
</table>
@param date
the Date to round, if <code>null</code> the current time will be
used
@param minuteBase
the base-minute to set the time on
@return the new rounded date
@see #nextGivenSecondDate(Date, int) | [
"<p",
">",
"Returns",
"a",
"date",
"that",
"is",
"rounded",
"to",
"the",
"next",
"even",
"multiple",
"of",
"the",
"given",
"minute",
".",
"<",
"/",
"p",
">",
"<p",
">",
"For",
"example",
"an",
"input",
"date",
"with",
"a",
"time",
"of",
"08",
":",
... | train | https://github.com/phax/ph-schedule/blob/b000790b46a9f8d23ad44cc20591f753d07c0229/ph-mini-quartz/src/main/java/com/helger/quartz/DateBuilder.java#L809-L848 |
liferay/com-liferay-commerce | commerce-tax-engine-fixed-service/src/main/java/com/liferay/commerce/tax/engine/fixed/service/persistence/impl/CommerceTaxFixedRatePersistenceImpl.java | CommerceTaxFixedRatePersistenceImpl.findAll | @Override
public List<CommerceTaxFixedRate> findAll(int start, int end) {
return findAll(start, end, null);
} | java | @Override
public List<CommerceTaxFixedRate> findAll(int start, int end) {
return findAll(start, end, null);
} | [
"@",
"Override",
"public",
"List",
"<",
"CommerceTaxFixedRate",
">",
"findAll",
"(",
"int",
"start",
",",
"int",
"end",
")",
"{",
"return",
"findAll",
"(",
"start",
",",
"end",
",",
"null",
")",
";",
"}"
] | Returns a range of all the commerce tax fixed rates.
<p>
Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceTaxFixedRateModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
</p>
@param start the lower bound of the range of commerce tax fixed rates
@param end the upper bound of the range of commerce tax fixed rates (not inclusive)
@return the range of commerce tax fixed rates | [
"Returns",
"a",
"range",
"of",
"all",
"the",
"commerce",
"tax",
"fixed",
"rates",
"."
] | train | https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-engine-fixed-service/src/main/java/com/liferay/commerce/tax/engine/fixed/service/persistence/impl/CommerceTaxFixedRatePersistenceImpl.java#L1969-L1972 |
datasift/datasift-java | src/main/java/com/datasift/client/managedsource/sources/GooglePlus.java | GooglePlus.addOAutToken | public GooglePlus addOAutToken(String oAuthAccessToken, String oAuthRefreshToken, String name, long expires) {
if (oAuthAccessToken == null || oAuthAccessToken.isEmpty() ||
oAuthRefreshToken == null || oAuthRefreshToken.isEmpty()) {
throw new IllegalArgumentException("A valid OAuth and refresh token is required");
}
AuthParams parameterSet = newAuthParams(name, expires);
parameterSet.set("value", oAuthAccessToken);
parameterSet.set("refresh_token", oAuthRefreshToken);
return this;
} | java | public GooglePlus addOAutToken(String oAuthAccessToken, String oAuthRefreshToken, String name, long expires) {
if (oAuthAccessToken == null || oAuthAccessToken.isEmpty() ||
oAuthRefreshToken == null || oAuthRefreshToken.isEmpty()) {
throw new IllegalArgumentException("A valid OAuth and refresh token is required");
}
AuthParams parameterSet = newAuthParams(name, expires);
parameterSet.set("value", oAuthAccessToken);
parameterSet.set("refresh_token", oAuthRefreshToken);
return this;
} | [
"public",
"GooglePlus",
"addOAutToken",
"(",
"String",
"oAuthAccessToken",
",",
"String",
"oAuthRefreshToken",
",",
"String",
"name",
",",
"long",
"expires",
")",
"{",
"if",
"(",
"oAuthAccessToken",
"==",
"null",
"||",
"oAuthAccessToken",
".",
"isEmpty",
"(",
")... | /*
Adds an OAuth token to the managed source
@param oAuthAccessToken an oauth2 token
@param oAuthRefreshToken an oauth2 refresh token
@param name a human friendly name for this auth token
@param expires identity resource expiry date/time as a UTC timestamp, i.e. when the token expires
@return this | [
"/",
"*",
"Adds",
"an",
"OAuth",
"token",
"to",
"the",
"managed",
"source"
] | train | https://github.com/datasift/datasift-java/blob/09de124f2a1a507ff6181e59875c6f325290850e/src/main/java/com/datasift/client/managedsource/sources/GooglePlus.java#L72-L81 |
kaazing/gateway | mina.core/core/src/main/java/org/apache/mina/proxy/filter/ProxyFilter.java | ProxyFilter.sessionClosed | @Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
ProxyIoSession proxyIoSession = (ProxyIoSession) session
.getAttribute(ProxyIoSession.PROXY_SESSION);
proxyIoSession.getEventQueue().enqueueEventIfNecessary(
new IoSessionEvent(nextFilter, session,
IoSessionEventType.CLOSED));
} | java | @Override
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws Exception {
ProxyIoSession proxyIoSession = (ProxyIoSession) session
.getAttribute(ProxyIoSession.PROXY_SESSION);
proxyIoSession.getEventQueue().enqueueEventIfNecessary(
new IoSessionEvent(nextFilter, session,
IoSessionEventType.CLOSED));
} | [
"@",
"Override",
"public",
"void",
"sessionClosed",
"(",
"NextFilter",
"nextFilter",
",",
"IoSession",
"session",
")",
"throws",
"Exception",
"{",
"ProxyIoSession",
"proxyIoSession",
"=",
"(",
"ProxyIoSession",
")",
"session",
".",
"getAttribute",
"(",
"ProxyIoSessi... | Event is stored in an {@link IoSessionEventQueue} for later delivery to the next filter
in the chain when the handshake would have succeed. This will prevent the rest of
the filter chain from being affected by this filter internals.
@param nextFilter the next filter in filter chain
@param session the session object | [
"Event",
"is",
"stored",
"in",
"an",
"{",
"@link",
"IoSessionEventQueue",
"}",
"for",
"later",
"delivery",
"to",
"the",
"next",
"filter",
"in",
"the",
"chain",
"when",
"the",
"handshake",
"would",
"have",
"succeed",
".",
"This",
"will",
"prevent",
"the",
"... | train | https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/mina.core/core/src/main/java/org/apache/mina/proxy/filter/ProxyFilter.java#L351-L359 |
bitcoinj/bitcoinj | core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java | WalletProtobufSerializer.readWallet | public Wallet readWallet(NetworkParameters params, @Nullable WalletExtension[] extensions,
Protos.Wallet walletProto) throws UnreadableWalletException {
return readWallet(params, extensions, walletProto, false);
} | java | public Wallet readWallet(NetworkParameters params, @Nullable WalletExtension[] extensions,
Protos.Wallet walletProto) throws UnreadableWalletException {
return readWallet(params, extensions, walletProto, false);
} | [
"public",
"Wallet",
"readWallet",
"(",
"NetworkParameters",
"params",
",",
"@",
"Nullable",
"WalletExtension",
"[",
"]",
"extensions",
",",
"Protos",
".",
"Wallet",
"walletProto",
")",
"throws",
"UnreadableWalletException",
"{",
"return",
"readWallet",
"(",
"params"... | <p>Loads wallet data from the given protocol buffer and inserts it into the given Wallet object. This is primarily
useful when you wish to pre-register extension objects. Note that if loading fails the provided Wallet object
may be in an indeterminate state and should be thrown away.</p>
<p>A wallet can be unreadable for various reasons, such as inability to open the file, corrupt data, internally
inconsistent data, a wallet extension marked as mandatory that cannot be handled and so on. You should always
handle {@link UnreadableWalletException} and communicate failure to the user in an appropriate manner.</p>
@throws UnreadableWalletException thrown in various error conditions (see description). | [
"<p",
">",
"Loads",
"wallet",
"data",
"from",
"the",
"given",
"protocol",
"buffer",
"and",
"inserts",
"it",
"into",
"the",
"given",
"Wallet",
"object",
".",
"This",
"is",
"primarily",
"useful",
"when",
"you",
"wish",
"to",
"pre",
"-",
"register",
"extensio... | train | https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/wallet/WalletProtobufSerializer.java#L467-L470 |
Javacord/Javacord | javacord-api/src/main/java/org/javacord/api/entity/message/MessageBuilder.java | MessageBuilder.appendCode | public MessageBuilder appendCode(String language, String code) {
delegate.appendCode(language, code);
return this;
} | java | public MessageBuilder appendCode(String language, String code) {
delegate.appendCode(language, code);
return this;
} | [
"public",
"MessageBuilder",
"appendCode",
"(",
"String",
"language",
",",
"String",
"code",
")",
"{",
"delegate",
".",
"appendCode",
"(",
"language",
",",
"code",
")",
";",
"return",
"this",
";",
"}"
] | Appends code to the message.
@param language The language, e.g. "java".
@param code The code.
@return The current instance in order to chain call methods. | [
"Appends",
"code",
"to",
"the",
"message",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/message/MessageBuilder.java#L53-L56 |
apache/flink | flink-connectors/flink-orc/src/main/java/org/apache/flink/orc/OrcBatchReader.java | OrcBatchReader.schemaToTypeInfo | static TypeInformation schemaToTypeInfo(TypeDescription schema) {
switch (schema.getCategory()) {
case BOOLEAN:
return BasicTypeInfo.BOOLEAN_TYPE_INFO;
case BYTE:
return BasicTypeInfo.BYTE_TYPE_INFO;
case SHORT:
return BasicTypeInfo.SHORT_TYPE_INFO;
case INT:
return BasicTypeInfo.INT_TYPE_INFO;
case LONG:
return BasicTypeInfo.LONG_TYPE_INFO;
case FLOAT:
return BasicTypeInfo.FLOAT_TYPE_INFO;
case DOUBLE:
return BasicTypeInfo.DOUBLE_TYPE_INFO;
case DECIMAL:
return BasicTypeInfo.BIG_DEC_TYPE_INFO;
case STRING:
case CHAR:
case VARCHAR:
return BasicTypeInfo.STRING_TYPE_INFO;
case DATE:
return SqlTimeTypeInfo.DATE;
case TIMESTAMP:
return SqlTimeTypeInfo.TIMESTAMP;
case BINARY:
return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO;
case STRUCT:
List<TypeDescription> fieldSchemas = schema.getChildren();
TypeInformation[] fieldTypes = new TypeInformation[fieldSchemas.size()];
for (int i = 0; i < fieldSchemas.size(); i++) {
fieldTypes[i] = schemaToTypeInfo(fieldSchemas.get(i));
}
String[] fieldNames = schema.getFieldNames().toArray(new String[]{});
return new RowTypeInfo(fieldTypes, fieldNames);
case LIST:
TypeDescription elementSchema = schema.getChildren().get(0);
TypeInformation<?> elementType = schemaToTypeInfo(elementSchema);
// arrays of primitive types are handled as object arrays to support null values
return ObjectArrayTypeInfo.getInfoFor(elementType);
case MAP:
TypeDescription keySchema = schema.getChildren().get(0);
TypeDescription valSchema = schema.getChildren().get(1);
TypeInformation<?> keyType = schemaToTypeInfo(keySchema);
TypeInformation<?> valType = schemaToTypeInfo(valSchema);
return new MapTypeInfo<>(keyType, valType);
case UNION:
throw new UnsupportedOperationException("UNION type is not supported yet.");
default:
throw new IllegalArgumentException("Unknown type " + schema);
}
} | java | static TypeInformation schemaToTypeInfo(TypeDescription schema) {
switch (schema.getCategory()) {
case BOOLEAN:
return BasicTypeInfo.BOOLEAN_TYPE_INFO;
case BYTE:
return BasicTypeInfo.BYTE_TYPE_INFO;
case SHORT:
return BasicTypeInfo.SHORT_TYPE_INFO;
case INT:
return BasicTypeInfo.INT_TYPE_INFO;
case LONG:
return BasicTypeInfo.LONG_TYPE_INFO;
case FLOAT:
return BasicTypeInfo.FLOAT_TYPE_INFO;
case DOUBLE:
return BasicTypeInfo.DOUBLE_TYPE_INFO;
case DECIMAL:
return BasicTypeInfo.BIG_DEC_TYPE_INFO;
case STRING:
case CHAR:
case VARCHAR:
return BasicTypeInfo.STRING_TYPE_INFO;
case DATE:
return SqlTimeTypeInfo.DATE;
case TIMESTAMP:
return SqlTimeTypeInfo.TIMESTAMP;
case BINARY:
return PrimitiveArrayTypeInfo.BYTE_PRIMITIVE_ARRAY_TYPE_INFO;
case STRUCT:
List<TypeDescription> fieldSchemas = schema.getChildren();
TypeInformation[] fieldTypes = new TypeInformation[fieldSchemas.size()];
for (int i = 0; i < fieldSchemas.size(); i++) {
fieldTypes[i] = schemaToTypeInfo(fieldSchemas.get(i));
}
String[] fieldNames = schema.getFieldNames().toArray(new String[]{});
return new RowTypeInfo(fieldTypes, fieldNames);
case LIST:
TypeDescription elementSchema = schema.getChildren().get(0);
TypeInformation<?> elementType = schemaToTypeInfo(elementSchema);
// arrays of primitive types are handled as object arrays to support null values
return ObjectArrayTypeInfo.getInfoFor(elementType);
case MAP:
TypeDescription keySchema = schema.getChildren().get(0);
TypeDescription valSchema = schema.getChildren().get(1);
TypeInformation<?> keyType = schemaToTypeInfo(keySchema);
TypeInformation<?> valType = schemaToTypeInfo(valSchema);
return new MapTypeInfo<>(keyType, valType);
case UNION:
throw new UnsupportedOperationException("UNION type is not supported yet.");
default:
throw new IllegalArgumentException("Unknown type " + schema);
}
} | [
"static",
"TypeInformation",
"schemaToTypeInfo",
"(",
"TypeDescription",
"schema",
")",
"{",
"switch",
"(",
"schema",
".",
"getCategory",
"(",
")",
")",
"{",
"case",
"BOOLEAN",
":",
"return",
"BasicTypeInfo",
".",
"BOOLEAN_TYPE_INFO",
";",
"case",
"BYTE",
":",
... | Converts an ORC schema to a Flink TypeInformation.
@param schema The ORC schema.
@return The TypeInformation that corresponds to the ORC schema. | [
"Converts",
"an",
"ORC",
"schema",
"to",
"a",
"Flink",
"TypeInformation",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-orc/src/main/java/org/apache/flink/orc/OrcBatchReader.java#L72-L124 |
apiman/apiman | manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/audit/AuditUtils.java | AuditUtils.contractBrokenToApi | public static AuditEntryBean contractBrokenToApi(ContractBean bean, ISecurityContext securityContext) {
AuditEntryBean entry = newEntry(bean.getApi().getApi().getOrganization().getId(), AuditEntityType.Api, securityContext);
entry.setWhat(AuditEntryType.BreakContract);
entry.setEntityId(bean.getApi().getApi().getId());
entry.setEntityVersion(bean.getApi().getVersion());
ContractData data = new ContractData(bean);
entry.setData(toJSON(data));
return entry;
} | java | public static AuditEntryBean contractBrokenToApi(ContractBean bean, ISecurityContext securityContext) {
AuditEntryBean entry = newEntry(bean.getApi().getApi().getOrganization().getId(), AuditEntityType.Api, securityContext);
entry.setWhat(AuditEntryType.BreakContract);
entry.setEntityId(bean.getApi().getApi().getId());
entry.setEntityVersion(bean.getApi().getVersion());
ContractData data = new ContractData(bean);
entry.setData(toJSON(data));
return entry;
} | [
"public",
"static",
"AuditEntryBean",
"contractBrokenToApi",
"(",
"ContractBean",
"bean",
",",
"ISecurityContext",
"securityContext",
")",
"{",
"AuditEntryBean",
"entry",
"=",
"newEntry",
"(",
"bean",
".",
"getApi",
"(",
")",
".",
"getApi",
"(",
")",
".",
"getOr... | Creates an audit entry for the 'contract broken' event.
@param bean the bean
@param securityContext the security context
@return the audit entry | [
"Creates",
"an",
"audit",
"entry",
"for",
"the",
"contract",
"broken",
"event",
"."
] | train | https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/rest-impl/src/main/java/io/apiman/manager/api/rest/impl/audit/AuditUtils.java#L474-L482 |
prestodb/presto | presto-parquet/src/main/java/com/facebook/presto/parquet/ParquetTypeUtils.java | ParquetTypeUtils.lookupColumnByName | public static ColumnIO lookupColumnByName(GroupColumnIO groupColumnIO, String columnName)
{
ColumnIO columnIO = groupColumnIO.getChild(columnName);
if (columnIO != null) {
return columnIO;
}
for (int i = 0; i < groupColumnIO.getChildrenCount(); i++) {
if (groupColumnIO.getChild(i).getName().equalsIgnoreCase(columnName)) {
return groupColumnIO.getChild(i);
}
}
return null;
} | java | public static ColumnIO lookupColumnByName(GroupColumnIO groupColumnIO, String columnName)
{
ColumnIO columnIO = groupColumnIO.getChild(columnName);
if (columnIO != null) {
return columnIO;
}
for (int i = 0; i < groupColumnIO.getChildrenCount(); i++) {
if (groupColumnIO.getChild(i).getName().equalsIgnoreCase(columnName)) {
return groupColumnIO.getChild(i);
}
}
return null;
} | [
"public",
"static",
"ColumnIO",
"lookupColumnByName",
"(",
"GroupColumnIO",
"groupColumnIO",
",",
"String",
"columnName",
")",
"{",
"ColumnIO",
"columnIO",
"=",
"groupColumnIO",
".",
"getChild",
"(",
"columnName",
")",
";",
"if",
"(",
"columnIO",
"!=",
"null",
"... | Parquet column names are case-sensitive unlike Hive, which converts all column names to lowercase.
Therefore, when we look up columns we first check for exact match, and if that fails we look for a case-insensitive match. | [
"Parquet",
"column",
"names",
"are",
"case",
"-",
"sensitive",
"unlike",
"Hive",
"which",
"converts",
"all",
"column",
"names",
"to",
"lowercase",
".",
"Therefore",
"when",
"we",
"look",
"up",
"columns",
"we",
"first",
"check",
"for",
"exact",
"match",
"and"... | train | https://github.com/prestodb/presto/blob/89de5e379d8f85e139d292b0add8c537a2a01a88/presto-parquet/src/main/java/com/facebook/presto/parquet/ParquetTypeUtils.java#L207-L222 |
pro-grade/pro-grade | src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java | ProGradePolicy.fixEncodedURI | private static String fixEncodedURI(final String encodedUri) {
if (encodedUri == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
int lastPercIdx = -3; // we will check position-2
for (int i = 0, n = encodedUri.length(); i < n; i++) {
char c = encodedUri.charAt(i);
if (c == '%') {
lastPercIdx = i;
} else if (lastPercIdx >= i - 2 && c >= 'A' && c <= 'F') {
c = (char) (c - 'A' + 'a');
}
sb.append(c);
}
return sb.toString();
} | java | private static String fixEncodedURI(final String encodedUri) {
if (encodedUri == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
int lastPercIdx = -3; // we will check position-2
for (int i = 0, n = encodedUri.length(); i < n; i++) {
char c = encodedUri.charAt(i);
if (c == '%') {
lastPercIdx = i;
} else if (lastPercIdx >= i - 2 && c >= 'A' && c <= 'F') {
c = (char) (c - 'A' + 'a');
}
sb.append(c);
}
return sb.toString();
} | [
"private",
"static",
"String",
"fixEncodedURI",
"(",
"final",
"String",
"encodedUri",
")",
"{",
"if",
"(",
"encodedUri",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
... | Gets {@link URI#toASCIIString()} as an input and the escaped octets %XX are converted to lower case (because of the
Oracle PolicyFile implementation of CodeSource comparing).
@param encodedUri
@return given URI String with lower-cased codes of non-ascii characters | [
"Gets",
"{",
"@link",
"URI#toASCIIString",
"()",
"}",
"as",
"an",
"input",
"and",
"the",
"escaped",
"octets",
"%XX",
"are",
"converted",
"to",
"lower",
"case",
"(",
"because",
"of",
"the",
"Oracle",
"PolicyFile",
"implementation",
"of",
"CodeSource",
"comparin... | train | https://github.com/pro-grade/pro-grade/blob/371b0d1349c37bd048a06206d3fa1b0c3c1cd9ab/src/main/java/net/sourceforge/prograde/policy/ProGradePolicy.java#L866-L882 |
SonarSource/sonarqube | server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandler.java | MssqlCharsetHandler.isCollationCorrect | private static boolean isCollationCorrect(String collation) {
return containsIgnoreCase(collation, CASE_SENSITIVE_ACCENT_SENSITIVE)
|| containsIgnoreCase(collation, BIN)
|| containsIgnoreCase(collation, BIN2);
} | java | private static boolean isCollationCorrect(String collation) {
return containsIgnoreCase(collation, CASE_SENSITIVE_ACCENT_SENSITIVE)
|| containsIgnoreCase(collation, BIN)
|| containsIgnoreCase(collation, BIN2);
} | [
"private",
"static",
"boolean",
"isCollationCorrect",
"(",
"String",
"collation",
")",
"{",
"return",
"containsIgnoreCase",
"(",
"collation",
",",
"CASE_SENSITIVE_ACCENT_SENSITIVE",
")",
"||",
"containsIgnoreCase",
"(",
"collation",
",",
"BIN",
")",
"||",
"containsIgn... | Collation is correct if contains {@link #CASE_SENSITIVE_ACCENT_SENSITIVE} or {@link #BIN} or {@link #BIN2}. | [
"Collation",
"is",
"correct",
"if",
"contains",
"{"
] | train | https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-db-migration/src/main/java/org/sonar/server/platform/db/migration/charset/MssqlCharsetHandler.java#L91-L95 |
phax/ph-commons | ph-commons/src/main/java/com/helger/commons/string/StringHelper.java | StringHelper.getExplodedToSortedSet | @Nonnull
@ReturnsMutableCopy
public static CommonsTreeSet <String> getExplodedToSortedSet (@Nonnull final String sSep,
@Nullable final String sElements)
{
return getExploded (sSep, sElements, -1, new CommonsTreeSet <> ());
} | java | @Nonnull
@ReturnsMutableCopy
public static CommonsTreeSet <String> getExplodedToSortedSet (@Nonnull final String sSep,
@Nullable final String sElements)
{
return getExploded (sSep, sElements, -1, new CommonsTreeSet <> ());
} | [
"@",
"Nonnull",
"@",
"ReturnsMutableCopy",
"public",
"static",
"CommonsTreeSet",
"<",
"String",
">",
"getExplodedToSortedSet",
"(",
"@",
"Nonnull",
"final",
"String",
"sSep",
",",
"@",
"Nullable",
"final",
"String",
"sElements",
")",
"{",
"return",
"getExploded",
... | Take a concatenated String and return a sorted {@link CommonsTreeSet} of all
elements in the passed string, using specified separator string.
@param sSep
The separator to use. May not be <code>null</code>.
@param sElements
The concatenated String to convert. May be <code>null</code> or empty.
@return The sorted {@link Set} represented by the passed string. Never
<code>null</code>. If the passed input string is <code>null</code> or
"" an empty list is returned. | [
"Take",
"a",
"concatenated",
"String",
"and",
"return",
"a",
"sorted",
"{",
"@link",
"CommonsTreeSet",
"}",
"of",
"all",
"elements",
"in",
"the",
"passed",
"string",
"using",
"specified",
"separator",
"string",
"."
] | train | https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L2334-L2340 |
gallandarakhneorg/afc | advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/DBaseFileReader.java | DBaseFileReader.read4ByteIntegerRecordValue | @SuppressWarnings("checkstyle:magicnumber")
private static int read4ByteIntegerRecordValue(DBaseFileField field, int nrecord, int nfield,
byte[] rawData, int rawOffset, OutputParameter<Long> value) throws IOException {
final int rawNumber = EndianNumbers.toLEInt(
rawData[rawOffset], rawData[rawOffset + 1],
rawData[rawOffset + 2], rawData[rawOffset + 3]);
try {
value.set(new Long(rawNumber));
return 4;
} catch (NumberFormatException exception) {
throw new InvalidRawDataFormatException(nrecord, nfield, Long.toString(rawNumber));
}
} | java | @SuppressWarnings("checkstyle:magicnumber")
private static int read4ByteIntegerRecordValue(DBaseFileField field, int nrecord, int nfield,
byte[] rawData, int rawOffset, OutputParameter<Long> value) throws IOException {
final int rawNumber = EndianNumbers.toLEInt(
rawData[rawOffset], rawData[rawOffset + 1],
rawData[rawOffset + 2], rawData[rawOffset + 3]);
try {
value.set(new Long(rawNumber));
return 4;
} catch (NumberFormatException exception) {
throw new InvalidRawDataFormatException(nrecord, nfield, Long.toString(rawNumber));
}
} | [
"@",
"SuppressWarnings",
"(",
"\"checkstyle:magicnumber\"",
")",
"private",
"static",
"int",
"read4ByteIntegerRecordValue",
"(",
"DBaseFileField",
"field",
",",
"int",
"nrecord",
",",
"int",
"nfield",
",",
"byte",
"[",
"]",
"rawData",
",",
"int",
"rawOffset",
",",... | Read a 4 BYTE INTEGER record value.
@param field is the current parsed field.
@param nrecord is the number of the record
@param nfield is the number of the field
@param rawData raw data
@param rawOffset is the index at which the data could be obtained
@param value will be set with the value extracted from the dBASE file
@return the count of consumed bytes
@throws IOException in case of error. | [
"Read",
"a",
"4",
"BYTE",
"INTEGER",
"record",
"value",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/dbasefile/src/main/java/org/arakhne/afc/io/dbase/DBaseFileReader.java#L1199-L1211 |
OpenLiberty/open-liberty | dev/com.ibm.ws.dynacache.monitor/src/com/ibm/ws/cache/stat/internal/CacheStatsModule.java | CacheStatsModule.onCacheMiss | public void onCacheMiss(String template, int locality) {
final String methodName = "onCacheMiss()";
CacheStatsModule csm = null;
if ((csm = getCSM(template)) == null) {
return;
}
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " cacheName=" + _sCacheName + " template=" + template + " locality=" + locality + " enable=" + csm._enable
+ " " + this);
if (csm._enable && csm._missCount != null)
csm._missCount.increment();
return;
} | java | public void onCacheMiss(String template, int locality) {
final String methodName = "onCacheMiss()";
CacheStatsModule csm = null;
if ((csm = getCSM(template)) == null) {
return;
}
if (tc.isDebugEnabled())
Tr.debug(tc, methodName + " cacheName=" + _sCacheName + " template=" + template + " locality=" + locality + " enable=" + csm._enable
+ " " + this);
if (csm._enable && csm._missCount != null)
csm._missCount.increment();
return;
} | [
"public",
"void",
"onCacheMiss",
"(",
"String",
"template",
",",
"int",
"locality",
")",
"{",
"final",
"String",
"methodName",
"=",
"\"onCacheMiss()\"",
";",
"CacheStatsModule",
"csm",
"=",
"null",
";",
"if",
"(",
"(",
"csm",
"=",
"getCSM",
"(",
"template",
... | Updates statistics for the cache miss case.
@param template
the template of the cache entry. The template cannot be null for Servlet cache.
@param locality
Whether the miss was local or remote | [
"Updates",
"statistics",
"for",
"the",
"cache",
"miss",
"case",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.dynacache.monitor/src/com/ibm/ws/cache/stat/internal/CacheStatsModule.java#L810-L823 |
Prototik/HoloEverywhere | library/src/org/holoeverywhere/widget/datetimepicker/date/SimpleMonthView.java | SimpleMonthView.getDayFromLocation | public CalendarDay getDayFromLocation(float x, float y) {
int dayStart = mPadding;
if (x < dayStart || x > mWidth - mPadding) {
return null;
}
// Selection is (x - start) / (pixels/day) == (x -s) * day / pixels
int row = (int) (y - MONTH_HEADER_SIZE) / mRowHeight;
int column = (int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding));
int day = column - findDayOffset() + 1;
day += row * mNumDays;
if (day < 1 || day > mNumCells) {
return null;
}
return new CalendarDay(mYear, mMonth, day);
} | java | public CalendarDay getDayFromLocation(float x, float y) {
int dayStart = mPadding;
if (x < dayStart || x > mWidth - mPadding) {
return null;
}
// Selection is (x - start) / (pixels/day) == (x -s) * day / pixels
int row = (int) (y - MONTH_HEADER_SIZE) / mRowHeight;
int column = (int) ((x - dayStart) * mNumDays / (mWidth - dayStart - mPadding));
int day = column - findDayOffset() + 1;
day += row * mNumDays;
if (day < 1 || day > mNumCells) {
return null;
}
return new CalendarDay(mYear, mMonth, day);
} | [
"public",
"CalendarDay",
"getDayFromLocation",
"(",
"float",
"x",
",",
"float",
"y",
")",
"{",
"int",
"dayStart",
"=",
"mPadding",
";",
"if",
"(",
"x",
"<",
"dayStart",
"||",
"x",
">",
"mWidth",
"-",
"mPadding",
")",
"{",
"return",
"null",
";",
"}",
... | Calculates the day that the given x position is in, accounting for week
number. Returns a Time referencing that day or null if
@param x The x position of the touch event
@return A time object for the tapped day or null if the position wasn't
in a day | [
"Calculates",
"the",
"day",
"that",
"the",
"given",
"x",
"position",
"is",
"in",
"accounting",
"for",
"week",
"number",
".",
"Returns",
"a",
"Time",
"referencing",
"that",
"day",
"or",
"null",
"if"
] | train | https://github.com/Prototik/HoloEverywhere/blob/b870abb5ab009a5a6dbab3fb855ec2854e35e125/library/src/org/holoeverywhere/widget/datetimepicker/date/SimpleMonthView.java#L448-L463 |
alkacon/opencms-core | src/org/opencms/util/CmsStringUtil.java | CmsStringUtil.readStringTemplateGroup | public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {
try {
return new StringTemplateGroup(
new InputStreamReader(stream, "UTF-8"),
DefaultTemplateLexer.class,
new StringTemplateErrorListener() {
@SuppressWarnings("synthetic-access")
public void error(String arg0, Throwable arg1) {
LOG.error(arg0 + ": " + arg1.getMessage(), arg1);
}
@SuppressWarnings("synthetic-access")
public void warning(String arg0) {
LOG.warn(arg0);
}
});
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
return new StringTemplateGroup("dummy");
}
} | java | public static StringTemplateGroup readStringTemplateGroup(InputStream stream) {
try {
return new StringTemplateGroup(
new InputStreamReader(stream, "UTF-8"),
DefaultTemplateLexer.class,
new StringTemplateErrorListener() {
@SuppressWarnings("synthetic-access")
public void error(String arg0, Throwable arg1) {
LOG.error(arg0 + ": " + arg1.getMessage(), arg1);
}
@SuppressWarnings("synthetic-access")
public void warning(String arg0) {
LOG.warn(arg0);
}
});
} catch (Exception e) {
LOG.error(e.getLocalizedMessage(), e);
return new StringTemplateGroup("dummy");
}
} | [
"public",
"static",
"StringTemplateGroup",
"readStringTemplateGroup",
"(",
"InputStream",
"stream",
")",
"{",
"try",
"{",
"return",
"new",
"StringTemplateGroup",
"(",
"new",
"InputStreamReader",
"(",
"stream",
",",
"\"UTF-8\"",
")",
",",
"DefaultTemplateLexer",
".",
... | Reads a stringtemplate group from a stream.
This will always return a group (empty if necessary), even if reading it from the stream fails.
@param stream the stream to read from
@return the string template group | [
"Reads",
"a",
"stringtemplate",
"group",
"from",
"a",
"stream",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsStringUtil.java#L1403-L1428 |
tomgibara/bits | src/main/java/com/tomgibara/bits/ImmutableBitStore.java | ImmutableBitStore.range | @Override
public BitStore range(int from, int to) {
return store.range(from, to).immutableView();
} | java | @Override
public BitStore range(int from, int to) {
return store.range(from, to).immutableView();
} | [
"@",
"Override",
"public",
"BitStore",
"range",
"(",
"int",
"from",
",",
"int",
"to",
")",
"{",
"return",
"store",
".",
"range",
"(",
"from",
",",
"to",
")",
".",
"immutableView",
"(",
")",
";",
"}"
] | /*
@Override
public Op and() {
return IMM_AND;
}
@Override
public Op or() {
return IMM_OR;
}
@Override
public Op xor() {
return IMM_XOR;
}
@Override
public Op set() {
return IMM_SET;
} | [
"/",
"*",
"@Override",
"public",
"Op",
"and",
"()",
"{",
"return",
"IMM_AND",
";",
"}"
] | train | https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/ImmutableBitStore.java#L151-L154 |
Nexmo/nexmo-java | src/main/java/com/nexmo/client/account/AccountClient.java | AccountClient.revokeSecret | public void revokeSecret(String apiKey, String secretId) throws IOException, NexmoClientException {
revokeSecret(new SecretRequest(apiKey, secretId));
} | java | public void revokeSecret(String apiKey, String secretId) throws IOException, NexmoClientException {
revokeSecret(new SecretRequest(apiKey, secretId));
} | [
"public",
"void",
"revokeSecret",
"(",
"String",
"apiKey",
",",
"String",
"secretId",
")",
"throws",
"IOException",
",",
"NexmoClientException",
"{",
"revokeSecret",
"(",
"new",
"SecretRequest",
"(",
"apiKey",
",",
"secretId",
")",
")",
";",
"}"
] | Revoke a secret associated with a specific API key.
@param apiKey The API key that the secret is associated to.
@param secretId The id of the secret to revoke.
@throws IOException if a network error occurred contacting the Nexmo Account API
@throws NexmoClientException if there was a problem wit hthe Nexmo request or response object indicating that the request was unsuccessful. | [
"Revoke",
"a",
"secret",
"associated",
"with",
"a",
"specific",
"API",
"key",
"."
] | train | https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/account/AccountClient.java#L195-L197 |
wuman/orientdb-android | client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java | OServerAdmin.createDatabase | public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException {
storage.checkConnection();
try {
if (storage.getName() == null || storage.getName().length() <= 0) {
OLogManager.instance().error(this, "Cannot create unnamed remote storage. Check your syntax", OStorageException.class);
} else {
if (iStorageMode == null)
iStorageMode = "csv";
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_CREATE);
try {
network.writeString(storage.getName());
if (network.getSrvProtocolVersion() >= 8)
network.writeString(iDatabaseType);
network.writeString(iStorageMode);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create the remote storage: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
} | java | public synchronized OServerAdmin createDatabase(final String iDatabaseType, String iStorageMode) throws IOException {
storage.checkConnection();
try {
if (storage.getName() == null || storage.getName().length() <= 0) {
OLogManager.instance().error(this, "Cannot create unnamed remote storage. Check your syntax", OStorageException.class);
} else {
if (iStorageMode == null)
iStorageMode = "csv";
final OChannelBinaryClient network = storage.beginRequest(OChannelBinaryProtocol.REQUEST_DB_CREATE);
try {
network.writeString(storage.getName());
if (network.getSrvProtocolVersion() >= 8)
network.writeString(iDatabaseType);
network.writeString(iStorageMode);
} finally {
storage.endRequest(network);
}
storage.getResponse(network);
}
} catch (Exception e) {
OLogManager.instance().error(this, "Cannot create the remote storage: " + storage.getName(), e, OStorageException.class);
storage.close(true);
}
return this;
} | [
"public",
"synchronized",
"OServerAdmin",
"createDatabase",
"(",
"final",
"String",
"iDatabaseType",
",",
"String",
"iStorageMode",
")",
"throws",
"IOException",
"{",
"storage",
".",
"checkConnection",
"(",
")",
";",
"try",
"{",
"if",
"(",
"storage",
".",
"getNa... | Creates a database in a remote server.
@param iDatabaseType
'document' or 'graph'
@param iStorageMode
local or memory
@return The instance itself. Useful to execute method in chain
@throws IOException | [
"Creates",
"a",
"database",
"in",
"a",
"remote",
"server",
"."
] | train | https://github.com/wuman/orientdb-android/blob/ff9b17e4349f26168b2d0c4facb1a18cbfbe8cf0/client/src/main/java/com/orientechnologies/orient/client/remote/OServerAdmin.java#L164-L193 |
b3dgs/lionengine | lionengine-network/src/main/java/com/b3dgs/lionengine/network/ServerImpl.java | ServerImpl.writeIdAndName | private static void writeIdAndName(ClientSocket client, int id, String name) throws IOException
{
// New client id
client.getOut().writeByte(id);
// New client name
final byte[] data = name.getBytes(NetworkMessage.CHARSET);
client.getOut().writeByte(data.length);
client.getOut().write(data);
} | java | private static void writeIdAndName(ClientSocket client, int id, String name) throws IOException
{
// New client id
client.getOut().writeByte(id);
// New client name
final byte[] data = name.getBytes(NetworkMessage.CHARSET);
client.getOut().writeByte(data.length);
client.getOut().write(data);
} | [
"private",
"static",
"void",
"writeIdAndName",
"(",
"ClientSocket",
"client",
",",
"int",
"id",
",",
"String",
"name",
")",
"throws",
"IOException",
"{",
"// New client id",
"client",
".",
"getOut",
"(",
")",
".",
"writeByte",
"(",
"id",
")",
";",
"// New cl... | Send the id and the name to the client.
@param client The client to send to.
@param id The id to send.
@param name The name to send.
@throws IOException In case of error. | [
"Send",
"the",
"id",
"and",
"the",
"name",
"to",
"the",
"client",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/ServerImpl.java#L55-L63 |
elki-project/elki | elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/MCEDependenceMeasure.java | MCEDependenceMeasure.getMCEntropy | private double getMCEntropy(int[][] mat, ArrayList<int[]> partsx, ArrayList<int[]> partsy, int size, int gridsize, double loggrid) {
// Margin entropies:
double[] mx = new double[gridsize];
double[] my = new double[gridsize];
for(int i = 0; i < gridsize; i++) {
// Note: indexes are a bit tricky here, because we compute both margin
// entropies at the same time!
final double sumx = (double) partsx.get(i).length;
final double sumy = (double) partsy.get(i).length;
for(int j = 0; j < gridsize; j++) {
double px = mat[i][j] / sumx;
double py = mat[j][i] / sumy;
if(px > 0.) {
mx[i] -= px * FastMath.log(px);
}
if(py > 0.) {
my[i] -= py * FastMath.log(py);
}
}
}
// Weighted sums of margin entropies.
double sumx = 0., sumy = 0.;
for(int i = 0; i < gridsize; i++) {
sumx += mx[i] * partsx.get(i).length;
sumy += my[i] * partsy.get(i).length;
}
double max = ((sumx > sumy) ? sumx : sumy);
return max / (size * loggrid);
} | java | private double getMCEntropy(int[][] mat, ArrayList<int[]> partsx, ArrayList<int[]> partsy, int size, int gridsize, double loggrid) {
// Margin entropies:
double[] mx = new double[gridsize];
double[] my = new double[gridsize];
for(int i = 0; i < gridsize; i++) {
// Note: indexes are a bit tricky here, because we compute both margin
// entropies at the same time!
final double sumx = (double) partsx.get(i).length;
final double sumy = (double) partsy.get(i).length;
for(int j = 0; j < gridsize; j++) {
double px = mat[i][j] / sumx;
double py = mat[j][i] / sumy;
if(px > 0.) {
mx[i] -= px * FastMath.log(px);
}
if(py > 0.) {
my[i] -= py * FastMath.log(py);
}
}
}
// Weighted sums of margin entropies.
double sumx = 0., sumy = 0.;
for(int i = 0; i < gridsize; i++) {
sumx += mx[i] * partsx.get(i).length;
sumy += my[i] * partsy.get(i).length;
}
double max = ((sumx > sumy) ? sumx : sumy);
return max / (size * loggrid);
} | [
"private",
"double",
"getMCEntropy",
"(",
"int",
"[",
"]",
"[",
"]",
"mat",
",",
"ArrayList",
"<",
"int",
"[",
"]",
">",
"partsx",
",",
"ArrayList",
"<",
"int",
"[",
"]",
">",
"partsy",
",",
"int",
"size",
",",
"int",
"gridsize",
",",
"double",
"lo... | Compute the MCE entropy value.
@param mat Partition size matrix
@param partsx Partitions on X
@param partsy Partitions on Y
@param size Data set size
@param gridsize Size of grids
@param loggrid Logarithm of grid sizes, for normalization
@return MCE score. | [
"Compute",
"the",
"MCE",
"entropy",
"value",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-math/src/main/java/de/lmu/ifi/dbs/elki/math/statistics/dependence/MCEDependenceMeasure.java#L221-L253 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.ortho2D | public Matrix4d ortho2D(double left, double right, double bottom, double top) {
return ortho2D(left, right, bottom, top, this);
} | java | public Matrix4d ortho2D(double left, double right, double bottom, double top) {
return ortho2D(left, right, bottom, top, this);
} | [
"public",
"Matrix4d",
"ortho2D",
"(",
"double",
"left",
",",
"double",
"right",
",",
"double",
"bottom",
",",
"double",
"top",
")",
"{",
"return",
"ortho2D",
"(",
"left",
",",
"right",
",",
"bottom",
",",
"top",
",",
"this",
")",
";",
"}"
] | Apply an orthographic projection transformation for a right-handed coordinate system to this matrix.
<p>
This method is equivalent to calling {@link #ortho(double, double, double, double, double, double) ortho()} with
<code>zNear=-1</code> and <code>zFar=+1</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix,
then the new matrix will be <code>M * O</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the
orthographic projection transformation will be applied first!
<p>
In order to set the matrix to an orthographic projection without post-multiplying it,
use {@link #setOrtho2D(double, double, double, double) setOrtho2D()}.
<p>
Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a>
@see #ortho(double, double, double, double, double, double)
@see #setOrtho2D(double, double, double, double)
@param left
the distance from the center to the left frustum edge
@param right
the distance from the center to the right frustum edge
@param bottom
the distance from the center to the bottom frustum edge
@param top
the distance from the center to the top frustum edge
@return this | [
"Apply",
"an",
"orthographic",
"projection",
"transformation",
"for",
"a",
"right",
"-",
"handed",
"coordinate",
"system",
"to",
"this",
"matrix",
".",
"<p",
">",
"This",
"method",
"is",
"equivalent",
"to",
"calling",
"{",
"@link",
"#ortho",
"(",
"double",
"... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L10623-L10625 |
buschmais/jqa-maven3-plugin | src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenProjectScannerPlugin.java | MavenProjectScannerPlugin.addModel | private void addModel(MavenProject project, MavenProjectDirectoryDescriptor projectDescriptor, Scanner scanner) {
File pomXmlFile = project.getFile();
FileDescriptor mavenPomXmlDescriptor = scanner.scan(pomXmlFile, pomXmlFile.getAbsolutePath(), MavenScope.PROJECT);
projectDescriptor.setModel(mavenPomXmlDescriptor);
// Effective model
MavenPomDescriptor effectiveModelDescriptor = scanner.getContext().getStore().create(MavenPomDescriptor.class);
Model model = new EffectiveModel(project.getModel());
scanner.getContext().push(MavenPomDescriptor.class, effectiveModelDescriptor);
scanner.scan(model, pomXmlFile.getAbsolutePath(), MavenScope.PROJECT);
scanner.getContext().pop(MavenPomDescriptor.class);
projectDescriptor.setEffectiveModel(effectiveModelDescriptor);
} | java | private void addModel(MavenProject project, MavenProjectDirectoryDescriptor projectDescriptor, Scanner scanner) {
File pomXmlFile = project.getFile();
FileDescriptor mavenPomXmlDescriptor = scanner.scan(pomXmlFile, pomXmlFile.getAbsolutePath(), MavenScope.PROJECT);
projectDescriptor.setModel(mavenPomXmlDescriptor);
// Effective model
MavenPomDescriptor effectiveModelDescriptor = scanner.getContext().getStore().create(MavenPomDescriptor.class);
Model model = new EffectiveModel(project.getModel());
scanner.getContext().push(MavenPomDescriptor.class, effectiveModelDescriptor);
scanner.scan(model, pomXmlFile.getAbsolutePath(), MavenScope.PROJECT);
scanner.getContext().pop(MavenPomDescriptor.class);
projectDescriptor.setEffectiveModel(effectiveModelDescriptor);
} | [
"private",
"void",
"addModel",
"(",
"MavenProject",
"project",
",",
"MavenProjectDirectoryDescriptor",
"projectDescriptor",
",",
"Scanner",
"scanner",
")",
"{",
"File",
"pomXmlFile",
"=",
"project",
".",
"getFile",
"(",
")",
";",
"FileDescriptor",
"mavenPomXmlDescript... | Scan the pom.xml file and add it as model.
@param project
The Maven project
@param projectDescriptor
The project descriptor.
@param scanner
The scanner. | [
"Scan",
"the",
"pom",
".",
"xml",
"file",
"and",
"add",
"it",
"as",
"model",
"."
] | train | https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenProjectScannerPlugin.java#L216-L227 |
carewebframework/carewebframework-core | org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandRegistry.java | CommandRegistry.get | public Command get(String commandName, boolean forceCreate) {
Command command = commands.get(commandName);
if (command == null && forceCreate) {
command = new Command(commandName);
add(command);
}
return command;
} | java | public Command get(String commandName, boolean forceCreate) {
Command command = commands.get(commandName);
if (command == null && forceCreate) {
command = new Command(commandName);
add(command);
}
return command;
} | [
"public",
"Command",
"get",
"(",
"String",
"commandName",
",",
"boolean",
"forceCreate",
")",
"{",
"Command",
"command",
"=",
"commands",
".",
"get",
"(",
"commandName",
")",
";",
"if",
"(",
"command",
"==",
"null",
"&&",
"forceCreate",
")",
"{",
"command"... | Retrieves the command associated with the specified name from the registry.
@param commandName Name of the command sought.
@param forceCreate If true and the command does not exist, one is created and added to the
registry.
@return The associated command, or null if it does not exist (and forceCreate is false). | [
"Retrieves",
"the",
"command",
"associated",
"with",
"the",
"specified",
"name",
"from",
"the",
"registry",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.ui-parent/org.carewebframework.ui.core/src/main/java/org/carewebframework/ui/command/CommandRegistry.java#L84-L93 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java | ImageMiscOps.insertBand | public static void insertBand( GrayS64 input, int band , InterleavedS64 output) {
final int numBands = output.numBands;
for (int y = 0; y < input.height; y++) {
int indexIn = input.getStartIndex() + y * input.getStride();
int indexOut = output.getStartIndex() + y * output.getStride() + band;
int end = indexOut + output.width*numBands - band;
for (; indexOut < end; indexOut += numBands , indexIn++ ) {
output.data[indexOut] = input.data[indexIn];
}
}
} | java | public static void insertBand( GrayS64 input, int band , InterleavedS64 output) {
final int numBands = output.numBands;
for (int y = 0; y < input.height; y++) {
int indexIn = input.getStartIndex() + y * input.getStride();
int indexOut = output.getStartIndex() + y * output.getStride() + band;
int end = indexOut + output.width*numBands - band;
for (; indexOut < end; indexOut += numBands , indexIn++ ) {
output.data[indexOut] = input.data[indexIn];
}
}
} | [
"public",
"static",
"void",
"insertBand",
"(",
"GrayS64",
"input",
",",
"int",
"band",
",",
"InterleavedS64",
"output",
")",
"{",
"final",
"int",
"numBands",
"=",
"output",
".",
"numBands",
";",
"for",
"(",
"int",
"y",
"=",
"0",
";",
"y",
"<",
"input",... | Inserts a single band into a multi-band image overwriting the original band
@param input Single band image
@param band Which band the image is to be inserted into
@param output The multi-band image which the input image is to be inserted into | [
"Inserts",
"a",
"single",
"band",
"into",
"a",
"multi",
"-",
"band",
"image",
"overwriting",
"the",
"original",
"band"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/misc/ImageMiscOps.java#L1790-L1801 |
DataSketches/sketches-core | src/main/java/com/yahoo/sketches/cpc/CpcSketch.java | CpcSketch.modifyOffset | private static void modifyOffset(final CpcSketch sketch, final int newOffset) {
assert ((newOffset >= 0) && (newOffset <= 56));
assert (newOffset == (sketch.windowOffset + 1));
assert (newOffset == CpcUtil.determineCorrectOffset(sketch.lgK, sketch.numCoupons));
assert (sketch.slidingWindow != null);
assert (sketch.pairTable != null);
final int k = 1 << sketch.lgK;
// Construct the full-sized bit matrix that corresponds to the sketch
final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sketch);
// refresh the KXP register on every 8th window shift.
if ((newOffset & 0x7) == 0) { refreshKXP(sketch, bitMatrix); }
sketch.pairTable.clear();
final PairTable table = sketch.pairTable;
final byte[] window = sketch.slidingWindow;
final long maskForClearingWindow = (0XFFL << newOffset) ^ -1L;
final long maskForFlippingEarlyZone = (1L << newOffset) - 1L;
long allSurprisesORed = 0;
for (int i = 0; i < k; i++) {
long pattern = bitMatrix[i];
window[i] = (byte) ((pattern >>> newOffset) & 0XFFL);
pattern &= maskForClearingWindow;
// The following line converts surprising 0's to 1's in the "early zone",
// (and vice versa, which is essential for this procedure's O(k) time cost).
pattern ^= maskForFlippingEarlyZone;
allSurprisesORed |= pattern; // a cheap way to recalculate fiCol
while (pattern != 0) {
final int col = Long.numberOfTrailingZeros(pattern);
pattern = pattern ^ (1L << col); // erase the 1.
final int rowCol = (i << 6) | col;
final boolean isNovel = PairTable.maybeInsert(table, rowCol);
assert isNovel == true;
}
}
sketch.windowOffset = newOffset;
sketch.fiCol = Long.numberOfTrailingZeros(allSurprisesORed);
if (sketch.fiCol > newOffset) {
sketch.fiCol = newOffset; // corner case
}
} | java | private static void modifyOffset(final CpcSketch sketch, final int newOffset) {
assert ((newOffset >= 0) && (newOffset <= 56));
assert (newOffset == (sketch.windowOffset + 1));
assert (newOffset == CpcUtil.determineCorrectOffset(sketch.lgK, sketch.numCoupons));
assert (sketch.slidingWindow != null);
assert (sketch.pairTable != null);
final int k = 1 << sketch.lgK;
// Construct the full-sized bit matrix that corresponds to the sketch
final long[] bitMatrix = CpcUtil.bitMatrixOfSketch(sketch);
// refresh the KXP register on every 8th window shift.
if ((newOffset & 0x7) == 0) { refreshKXP(sketch, bitMatrix); }
sketch.pairTable.clear();
final PairTable table = sketch.pairTable;
final byte[] window = sketch.slidingWindow;
final long maskForClearingWindow = (0XFFL << newOffset) ^ -1L;
final long maskForFlippingEarlyZone = (1L << newOffset) - 1L;
long allSurprisesORed = 0;
for (int i = 0; i < k; i++) {
long pattern = bitMatrix[i];
window[i] = (byte) ((pattern >>> newOffset) & 0XFFL);
pattern &= maskForClearingWindow;
// The following line converts surprising 0's to 1's in the "early zone",
// (and vice versa, which is essential for this procedure's O(k) time cost).
pattern ^= maskForFlippingEarlyZone;
allSurprisesORed |= pattern; // a cheap way to recalculate fiCol
while (pattern != 0) {
final int col = Long.numberOfTrailingZeros(pattern);
pattern = pattern ^ (1L << col); // erase the 1.
final int rowCol = (i << 6) | col;
final boolean isNovel = PairTable.maybeInsert(table, rowCol);
assert isNovel == true;
}
}
sketch.windowOffset = newOffset;
sketch.fiCol = Long.numberOfTrailingZeros(allSurprisesORed);
if (sketch.fiCol > newOffset) {
sketch.fiCol = newOffset; // corner case
}
} | [
"private",
"static",
"void",
"modifyOffset",
"(",
"final",
"CpcSketch",
"sketch",
",",
"final",
"int",
"newOffset",
")",
"{",
"assert",
"(",
"(",
"newOffset",
">=",
"0",
")",
"&&",
"(",
"newOffset",
"<=",
"56",
")",
")",
";",
"assert",
"(",
"newOffset",
... | This moves the sliding window
@param sketch the given sketch
@param newOffset the new offset, which must be oldOffset + 1 | [
"This",
"moves",
"the",
"sliding",
"window"
] | train | https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/cpc/CpcSketch.java#L508-L552 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java | DiagnosticsInner.listSiteAnalysesAsync | public Observable<Page<AnalysisDefinitionInner>> listSiteAnalysesAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory) {
return listSiteAnalysesWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory)
.map(new Func1<ServiceResponse<Page<AnalysisDefinitionInner>>, Page<AnalysisDefinitionInner>>() {
@Override
public Page<AnalysisDefinitionInner> call(ServiceResponse<Page<AnalysisDefinitionInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<AnalysisDefinitionInner>> listSiteAnalysesAsync(final String resourceGroupName, final String siteName, final String diagnosticCategory) {
return listSiteAnalysesWithServiceResponseAsync(resourceGroupName, siteName, diagnosticCategory)
.map(new Func1<ServiceResponse<Page<AnalysisDefinitionInner>>, Page<AnalysisDefinitionInner>>() {
@Override
public Page<AnalysisDefinitionInner> call(ServiceResponse<Page<AnalysisDefinitionInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"AnalysisDefinitionInner",
">",
">",
"listSiteAnalysesAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"siteName",
",",
"final",
"String",
"diagnosticCategory",
")",
"{",
"return",
"listSiteAnalyses... | Get Site Analyses.
Get Site Analyses.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param siteName Site Name
@param diagnosticCategory Diagnostic Category
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<AnalysisDefinitionInner> object | [
"Get",
"Site",
"Analyses",
".",
"Get",
"Site",
"Analyses",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/DiagnosticsInner.java#L440-L448 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java | ArrayUtil.lastIndexOf | public static int lastIndexOf(short[] array, short value) {
if (null != array) {
for (int i = array.length - 1; i >= 0; i--) {
if (value == array[i]) {
return i;
}
}
}
return INDEX_NOT_FOUND;
} | java | public static int lastIndexOf(short[] array, short value) {
if (null != array) {
for (int i = array.length - 1; i >= 0; i--) {
if (value == array[i]) {
return i;
}
}
}
return INDEX_NOT_FOUND;
} | [
"public",
"static",
"int",
"lastIndexOf",
"(",
"short",
"[",
"]",
"array",
",",
"short",
"value",
")",
"{",
"if",
"(",
"null",
"!=",
"array",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"array",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i"... | 返回数组中指定元素所在最后的位置,未找到返回{@link #INDEX_NOT_FOUND}
@param array 数组
@param value 被检查的元素
@return 数组中指定元素所在位置,未找到返回{@link #INDEX_NOT_FOUND}
@since 3.0.7 | [
"返回数组中指定元素所在最后的位置,未找到返回",
"{",
"@link",
"#INDEX_NOT_FOUND",
"}"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/util/ArrayUtil.java#L1119-L1128 |
katjahahn/PortEx | src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java | Visualizer.variate | private Color variate(Color color) {
assert color != null;
final int diff = 30;
// darken the color for value of diff
int newRed = shiftColorPart(color.getRed() - diff);
int newGreen = shiftColorPart(color.getGreen() - diff);
int newBlue = shiftColorPart(color.getBlue() - diff);
Color newColor = new Color(newRed, newGreen, newBlue);
// start at the original section color again if darkening accidentally
// resulted in black, which has already the meaning of section caves.
if (newColor.equals(Color.black)) {
newColor = colorMap.get(SECTION_START);
}
return newColor;
} | java | private Color variate(Color color) {
assert color != null;
final int diff = 30;
// darken the color for value of diff
int newRed = shiftColorPart(color.getRed() - diff);
int newGreen = shiftColorPart(color.getGreen() - diff);
int newBlue = shiftColorPart(color.getBlue() - diff);
Color newColor = new Color(newRed, newGreen, newBlue);
// start at the original section color again if darkening accidentally
// resulted in black, which has already the meaning of section caves.
if (newColor.equals(Color.black)) {
newColor = colorMap.get(SECTION_START);
}
return newColor;
} | [
"private",
"Color",
"variate",
"(",
"Color",
"color",
")",
"{",
"assert",
"color",
"!=",
"null",
";",
"final",
"int",
"diff",
"=",
"30",
";",
"// darken the color for value of diff",
"int",
"newRed",
"=",
"shiftColorPart",
"(",
"color",
".",
"getRed",
"(",
"... | Shift the given section color one step.
This creates a color similar to the given color, but still different
enough to tell the new color apart from the old one.
@param color
@return modified color | [
"Shift",
"the",
"given",
"section",
"color",
"one",
"step",
"."
] | train | https://github.com/katjahahn/PortEx/blob/319f08560aa58e3d5d7abe346ffdf623d6dc6990/src/main/java/com/github/katjahahn/tools/visualizer/Visualizer.java#L636-L650 |
GwtMaterialDesign/gwt-material-addins | src/main/java/gwt/material/design/addins/client/combobox/MaterialComboBox.java | MaterialComboBox.addItem | public void addItem(String text, T value, OptGroup optGroup) {
if (!values.contains(value)) {
values.add(value);
optGroup.add(buildOption(text, value));
}
} | java | public void addItem(String text, T value, OptGroup optGroup) {
if (!values.contains(value)) {
values.add(value);
optGroup.add(buildOption(text, value));
}
} | [
"public",
"void",
"addItem",
"(",
"String",
"text",
",",
"T",
"value",
",",
"OptGroup",
"optGroup",
")",
"{",
"if",
"(",
"!",
"values",
".",
"contains",
"(",
"value",
")",
")",
"{",
"values",
".",
"add",
"(",
"value",
")",
";",
"optGroup",
".",
"ad... | Add item directly to combobox component with existing OptGroup
@param text - The text you want to labeled on the option item
@param value - The value you want to pass through in this option
@param optGroup - Add directly this option into the existing group | [
"Add",
"item",
"directly",
"to",
"combobox",
"component",
"with",
"existing",
"OptGroup"
] | train | https://github.com/GwtMaterialDesign/gwt-material-addins/blob/11aec9d92918225f70f936285d0ae94f2178c36e/src/main/java/gwt/material/design/addins/client/combobox/MaterialComboBox.java#L237-L242 |
google/error-prone-javac | src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java | Configuration.getResource | public Content getResource(String key, Object o0, Object o1, Object o2) {
Content c = newContent();
Pattern p = Pattern.compile("\\{([012])\\}");
String text = getText(key);
Matcher m = p.matcher(text);
int start = 0;
while (m.find(start)) {
c.addContent(text.substring(start, m.start()));
Object o = null;
switch (m.group(1).charAt(0)) {
case '0': o = o0; break;
case '1': o = o1; break;
case '2': o = o2; break;
}
if (o == null) {
c.addContent("{" + m.group(1) + "}");
} else if (o instanceof String) {
c.addContent((String) o);
} else if (o instanceof Content) {
c.addContent((Content) o);
}
start = m.end();
}
c.addContent(text.substring(start));
return c;
} | java | public Content getResource(String key, Object o0, Object o1, Object o2) {
Content c = newContent();
Pattern p = Pattern.compile("\\{([012])\\}");
String text = getText(key);
Matcher m = p.matcher(text);
int start = 0;
while (m.find(start)) {
c.addContent(text.substring(start, m.start()));
Object o = null;
switch (m.group(1).charAt(0)) {
case '0': o = o0; break;
case '1': o = o1; break;
case '2': o = o2; break;
}
if (o == null) {
c.addContent("{" + m.group(1) + "}");
} else if (o instanceof String) {
c.addContent((String) o);
} else if (o instanceof Content) {
c.addContent((Content) o);
}
start = m.end();
}
c.addContent(text.substring(start));
return c;
} | [
"public",
"Content",
"getResource",
"(",
"String",
"key",
",",
"Object",
"o0",
",",
"Object",
"o1",
",",
"Object",
"o2",
")",
"{",
"Content",
"c",
"=",
"newContent",
"(",
")",
";",
"Pattern",
"p",
"=",
"Pattern",
".",
"compile",
"(",
"\"\\\\{([012])\\\\}... | Get the configuration string as a content.
@param key the key to look for in the configuration file
@param o1 string or content argument added to configuration text
@param o2 string or content argument added to configuration text
@return a content tree for the text | [
"Get",
"the",
"configuration",
"string",
"as",
"a",
"content",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java#L801-L830 |
OpenLiberty/open-liberty | dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ReferrerURLCookieHandler.java | ReferrerURLCookieHandler.invalidateReferrerURLCookie | public void invalidateReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) {
invalidateCookie(req, res, cookieName, true);
} | java | public void invalidateReferrerURLCookie(HttpServletRequest req, HttpServletResponse res, String cookieName) {
invalidateCookie(req, res, cookieName, true);
} | [
"public",
"void",
"invalidateReferrerURLCookie",
"(",
"HttpServletRequest",
"req",
",",
"HttpServletResponse",
"res",
",",
"String",
"cookieName",
")",
"{",
"invalidateCookie",
"(",
"req",
",",
"res",
",",
"cookieName",
",",
"true",
")",
";",
"}"
] | Invalidate (clear) the referrer URL cookie in the HttpServletResponse.
Setting age to 0 invalidates it.
@param res | [
"Invalidate",
"(",
"clear",
")",
"the",
"referrer",
"URL",
"cookie",
"in",
"the",
"HttpServletResponse",
".",
"Setting",
"age",
"to",
"0",
"invalidates",
"it",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.webcontainer.security/src/com/ibm/ws/webcontainer/security/ReferrerURLCookieHandler.java#L120-L122 |
robocup-atan/atan | src/main/java/com/github/robocup_atan/atan/model/CommandFactory.java | CommandFactory.addPlayerInitCommand | public void addPlayerInitCommand(String teamName, boolean isGoalie) {
StringBuilder buf = new StringBuilder();
buf.append("(init ");
buf.append(teamName);
buf.append(" (version ");
if (isGoalie) {
buf.append(serverVersion);
buf.append(") (goalie))");
} else {
buf.append(serverVersion);
buf.append("))");
}
fifo.add(fifo.size(), buf.toString());
} | java | public void addPlayerInitCommand(String teamName, boolean isGoalie) {
StringBuilder buf = new StringBuilder();
buf.append("(init ");
buf.append(teamName);
buf.append(" (version ");
if (isGoalie) {
buf.append(serverVersion);
buf.append(") (goalie))");
} else {
buf.append(serverVersion);
buf.append("))");
}
fifo.add(fifo.size(), buf.toString());
} | [
"public",
"void",
"addPlayerInitCommand",
"(",
"String",
"teamName",
",",
"boolean",
"isGoalie",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"buf",
".",
"append",
"(",
"\"(init \"",
")",
";",
"buf",
".",
"append",
"(",
"te... | This is used to initialise a player.
@param teamName The team the player belongs to.
@param isGoalie If the player is a goalie. Note: Only one goalie per team. | [
"This",
"is",
"used",
"to",
"initialise",
"a",
"player",
"."
] | train | https://github.com/robocup-atan/atan/blob/52237b468b09ba5b7c52d290984dbe0326c96df7/src/main/java/com/github/robocup_atan/atan/model/CommandFactory.java#L61-L74 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.println | public static void println(PrintWriter self, Object value) {
self.println(InvokerHelper.toString(value));
} | java | public static void println(PrintWriter self, Object value) {
self.println(InvokerHelper.toString(value));
} | [
"public",
"static",
"void",
"println",
"(",
"PrintWriter",
"self",
",",
"Object",
"value",
")",
"{",
"self",
".",
"println",
"(",
"InvokerHelper",
".",
"toString",
"(",
"value",
")",
")",
";",
"}"
] | Print a value formatted Groovy style (followed by a newline) to the print writer.
@param self a PrintWriter
@param value the value to print
@since 1.0 | [
"Print",
"a",
"value",
"formatted",
"Groovy",
"style",
"(",
"followed",
"by",
"a",
"newline",
")",
"to",
"the",
"print",
"writer",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L814-L816 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyUtil.java | PropertyUtil.findGetter | public static Method findGetter(String methodName, Object instance, Class<?> valueClass) throws NoSuchMethodException {
return findMethod(methodName, instance, valueClass, false);
} | java | public static Method findGetter(String methodName, Object instance, Class<?> valueClass) throws NoSuchMethodException {
return findMethod(methodName, instance, valueClass, false);
} | [
"public",
"static",
"Method",
"findGetter",
"(",
"String",
"methodName",
",",
"Object",
"instance",
",",
"Class",
"<",
"?",
">",
"valueClass",
")",
"throws",
"NoSuchMethodException",
"{",
"return",
"findMethod",
"(",
"methodName",
",",
"instance",
",",
"valueCla... | Returns the requested getter method from an object instance.
@param methodName Name of the getter method.
@param instance Object instance to search.
@param valueClass The return value type (null if don't care).
@return The getter method.
@throws NoSuchMethodException If method was not found. | [
"Returns",
"the",
"requested",
"getter",
"method",
"from",
"an",
"object",
"instance",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/property/PropertyUtil.java#L59-L61 |
impossibl/stencil | engine/src/main/java/com/impossibl/stencil/engine/StencilEngine.java | StencilEngine.renderInline | public void renderInline(String text, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException, ParseException {
render(loadInline(text), parameters, out, extraGlobalScopes);
} | java | public void renderInline(String text, Map<String, Object> parameters, Writer out, GlobalScope... extraGlobalScopes) throws IOException, ParseException {
render(loadInline(text), parameters, out, extraGlobalScopes);
} | [
"public",
"void",
"renderInline",
"(",
"String",
"text",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
",",
"Writer",
"out",
",",
"GlobalScope",
"...",
"extraGlobalScopes",
")",
"throws",
"IOException",
",",
"ParseException",
"{",
"render",
"(",... | Renders given text with the provided parameters to the given character
stream.
@param text Template text to render
@param parameters Parameters to pass to template
@param out Character stream to write to
@param extraGlobalScopes Any extra global scopes to make available
@throws IOException
@throws ParseException | [
"Renders",
"given",
"text",
"with",
"the",
"provided",
"parameters",
"to",
"the",
"given",
"character",
"stream",
"."
] | train | https://github.com/impossibl/stencil/blob/4aac1be605542b4248be95bf8916be4e2f755d1c/engine/src/main/java/com/impossibl/stencil/engine/StencilEngine.java#L174-L176 |
RestComm/load-balancer | jar/src/main/java/org/mobicents/tools/http/balancer/WebsocketModifyServerPipelineFactory.java | WebsocketModifyServerPipelineFactory.upgradeServerPipelineFactory | public void upgradeServerPipelineFactory(ChannelPipeline p, String wsVersion) {
if (p.get(HttpChunkAggregator.class) != null) {
p.remove(HttpChunkAggregator.class);
}
p.get(HttpRequestDecoder.class).replace("wsdecoder",
new WebSocket13FrameDecoder(true, true, Long.MAX_VALUE));
p.replace(HttpResponseEncoder.class, "wsencoder", new WebSocket13FrameEncoder(false));
} | java | public void upgradeServerPipelineFactory(ChannelPipeline p, String wsVersion) {
if (p.get(HttpChunkAggregator.class) != null) {
p.remove(HttpChunkAggregator.class);
}
p.get(HttpRequestDecoder.class).replace("wsdecoder",
new WebSocket13FrameDecoder(true, true, Long.MAX_VALUE));
p.replace(HttpResponseEncoder.class, "wsencoder", new WebSocket13FrameEncoder(false));
} | [
"public",
"void",
"upgradeServerPipelineFactory",
"(",
"ChannelPipeline",
"p",
",",
"String",
"wsVersion",
")",
"{",
"if",
"(",
"p",
".",
"get",
"(",
"HttpChunkAggregator",
".",
"class",
")",
"!=",
"null",
")",
"{",
"p",
".",
"remove",
"(",
"HttpChunkAggrega... | Upgrade the Server ChannelPipelineFactory. This method should be called from the HttpResponseHandler.messageReceived(ChannelHandlerContext, MessageEvent)
when the handler detects that the response contains WebSocket header "Sec-WebSocket-Protocol"
@param ChannelPipeline p
@param String WebSocket version | [
"Upgrade",
"the",
"Server",
"ChannelPipelineFactory",
".",
"This",
"method",
"should",
"be",
"called",
"from",
"the",
"HttpResponseHandler",
".",
"messageReceived",
"(",
"ChannelHandlerContext",
"MessageEvent",
")",
"when",
"the",
"handler",
"detects",
"that",
"the",
... | train | https://github.com/RestComm/load-balancer/blob/54768d0b81004b2653d429720016ad2617fe754f/jar/src/main/java/org/mobicents/tools/http/balancer/WebsocketModifyServerPipelineFactory.java#L24-L32 |
lemonlabs/ExpandableButtonMenu | library/src/main/java/lt/lemonlabs/android/expandablebuttonmenu/ExpandableButtonMenu.java | ExpandableButtonMenu.setMenuButtonText | public void setMenuButtonText(MenuButton button, String text) {
switch (button) {
case MID:
mMidText.setText(text);
break;
case LEFT:
mLeftText.setText(text);
break;
case RIGHT:
mRightText.setText(text);
break;
}
} | java | public void setMenuButtonText(MenuButton button, String text) {
switch (button) {
case MID:
mMidText.setText(text);
break;
case LEFT:
mLeftText.setText(text);
break;
case RIGHT:
mRightText.setText(text);
break;
}
} | [
"public",
"void",
"setMenuButtonText",
"(",
"MenuButton",
"button",
",",
"String",
"text",
")",
"{",
"switch",
"(",
"button",
")",
"{",
"case",
"MID",
":",
"mMidText",
".",
"setText",
"(",
"text",
")",
";",
"break",
";",
"case",
"LEFT",
":",
"mLeftText",... | Set text displayed under a menu button
@param button
@param text | [
"Set",
"text",
"displayed",
"under",
"a",
"menu",
"button"
] | train | https://github.com/lemonlabs/ExpandableButtonMenu/blob/2284593fc76b9bf7cc6b4aec311f24ee2bbbaa9d/library/src/main/java/lt/lemonlabs/android/expandablebuttonmenu/ExpandableButtonMenu.java#L226-L238 |
carewebframework/carewebframework-core | org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java | LayoutParser.parseElement | private LayoutElement parseElement(Element node, LayoutElement parent) {
LayoutElement layoutElement = newLayoutElement(node, parent, null);
parseChildren(node, layoutElement, Tag.ELEMENT, Tag.TRIGGER);
return layoutElement;
} | java | private LayoutElement parseElement(Element node, LayoutElement parent) {
LayoutElement layoutElement = newLayoutElement(node, parent, null);
parseChildren(node, layoutElement, Tag.ELEMENT, Tag.TRIGGER);
return layoutElement;
} | [
"private",
"LayoutElement",
"parseElement",
"(",
"Element",
"node",
",",
"LayoutElement",
"parent",
")",
"{",
"LayoutElement",
"layoutElement",
"=",
"newLayoutElement",
"(",
"node",
",",
"parent",
",",
"null",
")",
";",
"parseChildren",
"(",
"node",
",",
"layout... | Parse a layout element node.
@param node The DOM node.
@param parent The parent layout element.
@return The newly created layout element. | [
"Parse",
"a",
"layout",
"element",
"node",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java#L273-L277 |
nohana/Amalgam | amalgam/src/main/java/com/amalgam/os/BundleUtils.java | BundleUtils.optByte | public static byte optByte(@Nullable Bundle bundle, @Nullable String key, byte fallback) {
if (bundle == null) {
return fallback;
}
return bundle.getByte(key, fallback);
} | java | public static byte optByte(@Nullable Bundle bundle, @Nullable String key, byte fallback) {
if (bundle == null) {
return fallback;
}
return bundle.getByte(key, fallback);
} | [
"public",
"static",
"byte",
"optByte",
"(",
"@",
"Nullable",
"Bundle",
"bundle",
",",
"@",
"Nullable",
"String",
"key",
",",
"byte",
"fallback",
")",
"{",
"if",
"(",
"bundle",
"==",
"null",
")",
"{",
"return",
"fallback",
";",
"}",
"return",
"bundle",
... | Returns a optional byte value. In other words, returns the value mapped by key if it exists and is a byte.
The bundle argument is allowed to be {@code null}. If the bundle is null, this method returns a fallback value.
@param bundle a bundle. If the bundle is null, this method will return a fallback value.
@param key a key for the value.
@param fallback fallback value.
@return a byte value if exists, fallback value otherwise.
@see android.os.Bundle#getByte(String, byte) | [
"Returns",
"a",
"optional",
"byte",
"value",
".",
"In",
"other",
"words",
"returns",
"the",
"value",
"mapped",
"by",
"key",
"if",
"it",
"exists",
"and",
"is",
"a",
"byte",
".",
"The",
"bundle",
"argument",
"is",
"allowed",
"to",
"be",
"{"
] | train | https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/os/BundleUtils.java#L226-L231 |
MGunlogson/CuckooFilter4J | src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java | FilterTable.findTag | boolean findTag(long i1, long i2, long tag) {
for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) {
if (checkTag(i1, i, tag) || checkTag(i2, i, tag))
return true;
}
return false;
} | java | boolean findTag(long i1, long i2, long tag) {
for (int i = 0; i < CuckooFilter.BUCKET_SIZE; i++) {
if (checkTag(i1, i, tag) || checkTag(i2, i, tag))
return true;
}
return false;
} | [
"boolean",
"findTag",
"(",
"long",
"i1",
",",
"long",
"i2",
",",
"long",
"tag",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"CuckooFilter",
".",
"BUCKET_SIZE",
";",
"i",
"++",
")",
"{",
"if",
"(",
"checkTag",
"(",
"i1",
",",
"i",... | Finds a tag if present in two buckets.
@param i1
first bucket index
@param i2
second bucket index (alternate)
@param tag
tag
@return true if tag found in one of the buckets | [
"Finds",
"a",
"tag",
"if",
"present",
"in",
"two",
"buckets",
"."
] | train | https://github.com/MGunlogson/CuckooFilter4J/blob/e8472aa150b201f05046d1c81cac5a5ca4348db8/src/main/java/com/github/mgunlogson/cuckoofilter4j/FilterTable.java#L130-L136 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java | ExtensionHttpSessions.unmarkRemovedDefaultSessionToken | private void unmarkRemovedDefaultSessionToken(String site, String token) {
if (removedDefaultTokens == null)
return;
HashSet<String> removed = removedDefaultTokens.get(site);
if (removed == null)
return;
removed.remove(token);
} | java | private void unmarkRemovedDefaultSessionToken(String site, String token) {
if (removedDefaultTokens == null)
return;
HashSet<String> removed = removedDefaultTokens.get(site);
if (removed == null)
return;
removed.remove(token);
} | [
"private",
"void",
"unmarkRemovedDefaultSessionToken",
"(",
"String",
"site",
",",
"String",
"token",
")",
"{",
"if",
"(",
"removedDefaultTokens",
"==",
"null",
")",
"return",
";",
"HashSet",
"<",
"String",
">",
"removed",
"=",
"removedDefaultTokens",
".",
"get"... | Unmarks a default session token as removed for a particular site.
@param site the site. This parameter has to be formed as defined in the
{@link ExtensionHttpSessions} class documentation.
@param token the token | [
"Unmarks",
"a",
"default",
"session",
"token",
"as",
"removed",
"for",
"a",
"particular",
"site",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/httpsessions/ExtensionHttpSessions.java#L343-L350 |
JOML-CI/JOML | src/org/joml/Matrix4d.java | Matrix4d.ortho2DLH | public Matrix4d ortho2DLH(double left, double right, double bottom, double top) {
return ortho2DLH(left, right, bottom, top, this);
} | java | public Matrix4d ortho2DLH(double left, double right, double bottom, double top) {
return ortho2DLH(left, right, bottom, top, this);
} | [
"public",
"Matrix4d",
"ortho2DLH",
"(",
"double",
"left",
",",
"double",
"right",
",",
"double",
"bottom",
",",
"double",
"top",
")",
"{",
"return",
"ortho2DLH",
"(",
"left",
",",
"right",
",",
"bottom",
",",
"top",
",",
"this",
")",
";",
"}"
] | Apply an orthographic projection transformation for a left-handed coordinate system to this matrix.
<p>
This method is equivalent to calling {@link #orthoLH(double, double, double, double, double, double) orthoLH()} with
<code>zNear=-1</code> and <code>zFar=+1</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix,
then the new matrix will be <code>M * O</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the
orthographic projection transformation will be applied first!
<p>
In order to set the matrix to an orthographic projection without post-multiplying it,
use {@link #setOrtho2DLH(double, double, double, double) setOrtho2DLH()}.
<p>
Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a>
@see #orthoLH(double, double, double, double, double, double)
@see #setOrtho2DLH(double, double, double, double)
@param left
the distance from the center to the left frustum edge
@param right
the distance from the center to the right frustum edge
@param bottom
the distance from the center to the bottom frustum edge
@param top
the distance from the center to the top frustum edge
@return this | [
"Apply",
"an",
"orthographic",
"projection",
"transformation",
"for",
"a",
"left",
"-",
"handed",
"coordinate",
"system",
"to",
"this",
"matrix",
".",
"<p",
">",
"This",
"method",
"is",
"equivalent",
"to",
"calling",
"{",
"@link",
"#orthoLH",
"(",
"double",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L10722-L10724 |
line/armeria | core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpServiceFactory.java | AnnotatedHttpServiceFactory.userDefinedDecorator | @Nullable
private static DecoratorAndOrder userDefinedDecorator(Annotation annotation) {
// User-defined decorator MUST be annotated with @DecoratorFactory annotation.
final DecoratorFactory d =
findFirstDeclared(annotation.annotationType(), DecoratorFactory.class).orElse(null);
if (d == null) {
return null;
}
// In case of user-defined decorator, we need to create a new decorator from its factory.
@SuppressWarnings("unchecked")
final DecoratorFactoryFunction<Annotation> factory = getInstance(d, DecoratorFactoryFunction.class);
// If the annotation has "order" attribute, we can use it when sorting decorators.
int order = 0;
try {
final Method method = Iterables.getFirst(getMethods(annotation.annotationType(),
withName("order")), null);
if (method != null) {
final Object value = method.invoke(annotation);
if (value instanceof Integer) {
order = (Integer) value;
}
}
} catch (Throwable ignore) {
// A user-defined decorator may not have an 'order' attribute.
// If it does not exist, '0' is used by default.
}
return new DecoratorAndOrder(annotation, factory.newDecorator(annotation), order);
} | java | @Nullable
private static DecoratorAndOrder userDefinedDecorator(Annotation annotation) {
// User-defined decorator MUST be annotated with @DecoratorFactory annotation.
final DecoratorFactory d =
findFirstDeclared(annotation.annotationType(), DecoratorFactory.class).orElse(null);
if (d == null) {
return null;
}
// In case of user-defined decorator, we need to create a new decorator from its factory.
@SuppressWarnings("unchecked")
final DecoratorFactoryFunction<Annotation> factory = getInstance(d, DecoratorFactoryFunction.class);
// If the annotation has "order" attribute, we can use it when sorting decorators.
int order = 0;
try {
final Method method = Iterables.getFirst(getMethods(annotation.annotationType(),
withName("order")), null);
if (method != null) {
final Object value = method.invoke(annotation);
if (value instanceof Integer) {
order = (Integer) value;
}
}
} catch (Throwable ignore) {
// A user-defined decorator may not have an 'order' attribute.
// If it does not exist, '0' is used by default.
}
return new DecoratorAndOrder(annotation, factory.newDecorator(annotation), order);
} | [
"@",
"Nullable",
"private",
"static",
"DecoratorAndOrder",
"userDefinedDecorator",
"(",
"Annotation",
"annotation",
")",
"{",
"// User-defined decorator MUST be annotated with @DecoratorFactory annotation.",
"final",
"DecoratorFactory",
"d",
"=",
"findFirstDeclared",
"(",
"annota... | Returns a decorator with its order if the specified {@code annotation} is one of the user-defined
decorator annotation. | [
"Returns",
"a",
"decorator",
"with",
"its",
"order",
"if",
"the",
"specified",
"{"
] | train | https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/core/src/main/java/com/linecorp/armeria/internal/annotation/AnnotatedHttpServiceFactory.java#L676-L705 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/MediaservicesInner.java | MediaservicesInner.syncStorageKeysAsync | public Observable<Void> syncStorageKeysAsync(String resourceGroupName, String accountName) {
return syncStorageKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> syncStorageKeysAsync(String resourceGroupName, String accountName) {
return syncStorageKeysWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"syncStorageKeysAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"accountName",
")",
"{",
"return",
"syncStorageKeysWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
")",
".",
"map",
"(",
"new"... | Synchronizes Storage Account Keys.
Synchronizes storage account keys for a storage account associated with the Media Service account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Synchronizes",
"Storage",
"Account",
"Keys",
".",
"Synchronizes",
"storage",
"account",
"keys",
"for",
"a",
"storage",
"account",
"associated",
"with",
"the",
"Media",
"Service",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/MediaservicesInner.java#L644-L651 |
JodaOrg/joda-time | src/main/java/org/joda/time/field/RemainderDateTimeField.java | RemainderDateTimeField.addWrapField | public long addWrapField(long instant, int amount) {
return set(instant, FieldUtils.getWrappedValue(get(instant), amount, 0, iDivisor - 1));
} | java | public long addWrapField(long instant, int amount) {
return set(instant, FieldUtils.getWrappedValue(get(instant), amount, 0, iDivisor - 1));
} | [
"public",
"long",
"addWrapField",
"(",
"long",
"instant",
",",
"int",
"amount",
")",
"{",
"return",
"set",
"(",
"instant",
",",
"FieldUtils",
".",
"getWrappedValue",
"(",
"get",
"(",
"instant",
")",
",",
"amount",
",",
"0",
",",
"iDivisor",
"-",
"1",
"... | Add the specified amount to the specified time instant, wrapping around
within the remainder range if necessary. The amount added may be
negative.
@param instant the time instant in millis to update.
@param amount the amount to add (can be negative).
@return the updated time instant. | [
"Add",
"the",
"specified",
"amount",
"to",
"the",
"specified",
"time",
"instant",
"wrapping",
"around",
"within",
"the",
"remainder",
"range",
"if",
"necessary",
".",
"The",
"amount",
"added",
"may",
"be",
"negative",
"."
] | train | https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/field/RemainderDateTimeField.java#L153-L155 |
Appendium/objectlabkit | utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java | ConsoleMenu.getString | public static String getString(final String msg, final String defaultVal) {
String s = getString(msg + "(default:" + defaultVal + "):");
if (StringUtils.isBlank(s)) {
s = defaultVal;
}
return s;
} | java | public static String getString(final String msg, final String defaultVal) {
String s = getString(msg + "(default:" + defaultVal + "):");
if (StringUtils.isBlank(s)) {
s = defaultVal;
}
return s;
} | [
"public",
"static",
"String",
"getString",
"(",
"final",
"String",
"msg",
",",
"final",
"String",
"defaultVal",
")",
"{",
"String",
"s",
"=",
"getString",
"(",
"msg",
"+",
"\"(default:\"",
"+",
"defaultVal",
"+",
"\"):\"",
")",
";",
"if",
"(",
"StringUtils... | Gets a String from the System.in
@param msg
for the command line
@return String as entered by the user of the console app | [
"Gets",
"a",
"String",
"from",
"the",
"System",
".",
"in"
] | train | https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/console/ConsoleMenu.java#L331-L338 |
phoenixnap/springmvc-raml-plugin | src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/interpreters/EnumBuilder.java | EnumBuilder.withName | public EnumBuilder withName(String pojoPackage, String className) {
className = NamingHelper.convertToClassName(className);
final String fullyQualifiedClassName = pojoPackage + "." + className;
// Initiate package if necessary
if (this.pojoPackage == null) {
withPackage(pojoPackage);
}
// Builders should only have 1 active pojo under their responsibility
if (this.pojo != null) {
throw new IllegalStateException("Enum already created");
}
try {
// create the class
logger.debug("Creating Enum " + fullyQualifiedClassName);
this.pojo = this.pojoModel._class(fullyQualifiedClassName, ClassType.ENUM);
// Handle Serialization
// Do enums need to be serializable?
// implementsSerializable();
} catch (JClassAlreadyExistsException e) {
// class already exists - reuse it!
logger.debug("Enum {} already exists. Reusing it!", fullyQualifiedClassName);
this.pojo = this.pojoModel._getClass(fullyQualifiedClassName);
}
// Add to shortcuts
this.codeModels.put(fullyQualifiedClassName, this.pojo);
return this;
} | java | public EnumBuilder withName(String pojoPackage, String className) {
className = NamingHelper.convertToClassName(className);
final String fullyQualifiedClassName = pojoPackage + "." + className;
// Initiate package if necessary
if (this.pojoPackage == null) {
withPackage(pojoPackage);
}
// Builders should only have 1 active pojo under their responsibility
if (this.pojo != null) {
throw new IllegalStateException("Enum already created");
}
try {
// create the class
logger.debug("Creating Enum " + fullyQualifiedClassName);
this.pojo = this.pojoModel._class(fullyQualifiedClassName, ClassType.ENUM);
// Handle Serialization
// Do enums need to be serializable?
// implementsSerializable();
} catch (JClassAlreadyExistsException e) {
// class already exists - reuse it!
logger.debug("Enum {} already exists. Reusing it!", fullyQualifiedClassName);
this.pojo = this.pojoModel._getClass(fullyQualifiedClassName);
}
// Add to shortcuts
this.codeModels.put(fullyQualifiedClassName, this.pojo);
return this;
} | [
"public",
"EnumBuilder",
"withName",
"(",
"String",
"pojoPackage",
",",
"String",
"className",
")",
"{",
"className",
"=",
"NamingHelper",
".",
"convertToClassName",
"(",
"className",
")",
";",
"final",
"String",
"fullyQualifiedClassName",
"=",
"pojoPackage",
"+",
... | Sets this Pojo's name
@param pojoPackage
The Package used to create POJO
@param className
Class to be created
@return This instance | [
"Sets",
"this",
"Pojo",
"s",
"name"
] | train | https://github.com/phoenixnap/springmvc-raml-plugin/blob/6387072317cd771eb7d6f30943f556ac20dd3c84/src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/interpreters/EnumBuilder.java#L83-L113 |
kiegroup/drools | drools-model/drools-constraint-parser/src/main/javacc-support/org/drools/constraint/parser/GeneratedDrlConstraintParserBase.java | GeneratedDrlConstraintParserBase.juggleArrayType | Type juggleArrayType(Type partialType, List<ArrayType.ArrayBracketPair> additionalBrackets) {
Pair<Type, List<ArrayType.ArrayBracketPair>> partialParts = unwrapArrayTypes(partialType);
Type elementType = partialParts.a;
List<ArrayType.ArrayBracketPair> leftMostBrackets = partialParts.b;
return wrapInArrayTypes(elementType, leftMostBrackets, additionalBrackets).clone();
} | java | Type juggleArrayType(Type partialType, List<ArrayType.ArrayBracketPair> additionalBrackets) {
Pair<Type, List<ArrayType.ArrayBracketPair>> partialParts = unwrapArrayTypes(partialType);
Type elementType = partialParts.a;
List<ArrayType.ArrayBracketPair> leftMostBrackets = partialParts.b;
return wrapInArrayTypes(elementType, leftMostBrackets, additionalBrackets).clone();
} | [
"Type",
"juggleArrayType",
"(",
"Type",
"partialType",
",",
"List",
"<",
"ArrayType",
".",
"ArrayBracketPair",
">",
"additionalBrackets",
")",
"{",
"Pair",
"<",
"Type",
",",
"List",
"<",
"ArrayType",
".",
"ArrayBracketPair",
">",
">",
"partialParts",
"=",
"unw... | Throws together a Type, taking care of all the array brackets | [
"Throws",
"together",
"a",
"Type",
"taking",
"care",
"of",
"all",
"the",
"array",
"brackets"
] | train | https://github.com/kiegroup/drools/blob/22b0275d6dbe93070b8090948502cf46eda543c4/drools-model/drools-constraint-parser/src/main/javacc-support/org/drools/constraint/parser/GeneratedDrlConstraintParserBase.java#L253-L258 |
sahan/RoboZombie | robozombie/src/main/java/org/apache/http42/client/utils/URLEncodedUtils.java | URLEncodedUtils.encodeFormFields | private static String encodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urlencode(content, charset != null ? Charset.forName(charset) :
Consts.UTF_8, URLENCODER, true);
} | java | private static String encodeFormFields (final String content, final String charset) {
if (content == null) {
return null;
}
return urlencode(content, charset != null ? Charset.forName(charset) :
Consts.UTF_8, URLENCODER, true);
} | [
"private",
"static",
"String",
"encodeFormFields",
"(",
"final",
"String",
"content",
",",
"final",
"String",
"charset",
")",
"{",
"if",
"(",
"content",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"urlencode",
"(",
"content",
",",
"charse... | Encode/escape www-url-form-encoded content.
<p>
Uses the {@link #URLENCODER} set of characters, rather than
the {@link #UNRSERVED} set; this is for compatibilty with previous
releases, URLEncoder.encode() and most browsers.
@param content the content to encode, will convert space to '+'
@param charset the charset to use
@return | [
"Encode",
"/",
"escape",
"www",
"-",
"url",
"-",
"form",
"-",
"encoded",
"content",
".",
"<p",
">",
"Uses",
"the",
"{",
"@link",
"#URLENCODER",
"}",
"set",
"of",
"characters",
"rather",
"than",
"the",
"{",
"@link",
"#UNRSERVED",
"}",
"set",
";",
"this"... | train | https://github.com/sahan/RoboZombie/blob/2e02f0d41647612e9d89360c5c48811ea86b33c8/robozombie/src/main/java/org/apache/http42/client/utils/URLEncodedUtils.java#L479-L485 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.