id
int32 0
165k
| repo
stringlengths 7
58
| path
stringlengths 12
218
| func_name
stringlengths 3
140
| original_string
stringlengths 73
34.1k
| language
stringclasses 1
value | code
stringlengths 73
34.1k
| code_tokens
list | docstring
stringlengths 3
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 105
339
|
|---|---|---|---|---|---|---|---|---|---|---|---|
145,300
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/storage/ModelBatch.java
|
ModelBatch.writeToFileWithoutFactors
|
public void writeToFileWithoutFactors(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
writeToStreamWithoutFactors(fos);
fos.close();
}
|
java
|
public void writeToFileWithoutFactors(String filename) throws IOException {
FileOutputStream fos = new FileOutputStream(filename);
writeToStreamWithoutFactors(fos);
fos.close();
}
|
[
"public",
"void",
"writeToFileWithoutFactors",
"(",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"FileOutputStream",
"fos",
"=",
"new",
"FileOutputStream",
"(",
"filename",
")",
";",
"writeToStreamWithoutFactors",
"(",
"fos",
")",
";",
"fos",
".",
"close",
"(",
")",
";",
"}"
] |
Convenience function to write the current state of the modelBatch out to a file, without factors.
@param filename the file to write the batch to
@throws IOException
|
[
"Convenience",
"function",
"to",
"write",
"the",
"current",
"state",
"of",
"the",
"modelBatch",
"out",
"to",
"a",
"file",
"without",
"factors",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/storage/ModelBatch.java#L112-L116
|
145,301
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/storage/ModelBatch.java
|
ModelBatch.writeToStreamWithoutFactors
|
public void writeToStreamWithoutFactors(OutputStream outputStream) throws IOException {
Set<GraphicalModel.Factor> emptySet = new HashSet<>();
for (GraphicalModel model : this) {
Set<GraphicalModel.Factor> cachedFactors = model.factors;
model.factors = emptySet;
model.writeToStream(outputStream);
model.factors = cachedFactors;
}
}
|
java
|
public void writeToStreamWithoutFactors(OutputStream outputStream) throws IOException {
Set<GraphicalModel.Factor> emptySet = new HashSet<>();
for (GraphicalModel model : this) {
Set<GraphicalModel.Factor> cachedFactors = model.factors;
model.factors = emptySet;
model.writeToStream(outputStream);
model.factors = cachedFactors;
}
}
|
[
"public",
"void",
"writeToStreamWithoutFactors",
"(",
"OutputStream",
"outputStream",
")",
"throws",
"IOException",
"{",
"Set",
"<",
"GraphicalModel",
".",
"Factor",
">",
"emptySet",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"GraphicalModel",
"model",
":",
"this",
")",
"{",
"Set",
"<",
"GraphicalModel",
".",
"Factor",
">",
"cachedFactors",
"=",
"model",
".",
"factors",
";",
"model",
".",
"factors",
"=",
"emptySet",
";",
"model",
".",
"writeToStream",
"(",
"outputStream",
")",
";",
"model",
".",
"factors",
"=",
"cachedFactors",
";",
"}",
"}"
] |
This writes the whole batch, WITHOUT FACTORS, which means that anyone loading this batch will need to include
their own featurizer. Make sure that you have sufficient metadata to be able to do full featurizations.
@param outputStream the outputstream to write our files to
@throws IOException
|
[
"This",
"writes",
"the",
"whole",
"batch",
"WITHOUT",
"FACTORS",
"which",
"means",
"that",
"anyone",
"loading",
"this",
"batch",
"will",
"need",
"to",
"include",
"their",
"own",
"featurizer",
".",
"Make",
"sure",
"that",
"you",
"have",
"sufficient",
"metadata",
"to",
"be",
"able",
"to",
"do",
"full",
"featurizations",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/storage/ModelBatch.java#L139-L147
|
145,302
|
dbracewell/mango
|
src/main/java/com/davidbracewell/tuple/Tuple2.java
|
Tuple2.of
|
public static <K, V> Tuple2<K, V> of(K key, V value) {
return new Tuple2<>(key, value);
}
|
java
|
public static <K, V> Tuple2<K, V> of(K key, V value) {
return new Tuple2<>(key, value);
}
|
[
"public",
"static",
"<",
"K",
",",
"V",
">",
"Tuple2",
"<",
"K",
",",
"V",
">",
"of",
"(",
"K",
"key",
",",
"V",
"value",
")",
"{",
"return",
"new",
"Tuple2",
"<>",
"(",
"key",
",",
"value",
")",
";",
"}"
] |
Of tuple 2.
@param <K> the type parameter
@param <V> the type parameter
@param key the key
@param value the value
@return the tuple 2
|
[
"Of",
"tuple",
"2",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/tuple/Tuple2.java#L102-L104
|
145,303
|
LevelFourAB/commons
|
commons-types/src/main/java/se/l4/commons/types/internal/TypeFinderOverScanResult.java
|
TypeFinderOverScanResult.create
|
private <T> Set<? extends T> create(Iterable<Class<? extends T>> types)
{
Set<T> result = new HashSet<>();
for(Class<? extends T> t : types)
{
if(! Modifier.isAbstract(t.getModifiers()) && ! t.isInterface())
{
T instance = factory.create(t);
result.add(instance);
}
}
return Collections.unmodifiableSet(result);
}
|
java
|
private <T> Set<? extends T> create(Iterable<Class<? extends T>> types)
{
Set<T> result = new HashSet<>();
for(Class<? extends T> t : types)
{
if(! Modifier.isAbstract(t.getModifiers()) && ! t.isInterface())
{
T instance = factory.create(t);
result.add(instance);
}
}
return Collections.unmodifiableSet(result);
}
|
[
"private",
"<",
"T",
">",
"Set",
"<",
"?",
"extends",
"T",
">",
"create",
"(",
"Iterable",
"<",
"Class",
"<",
"?",
"extends",
"T",
">",
">",
"types",
")",
"{",
"Set",
"<",
"T",
">",
"result",
"=",
"new",
"HashSet",
"<>",
"(",
")",
";",
"for",
"(",
"Class",
"<",
"?",
"extends",
"T",
">",
"t",
":",
"types",
")",
"{",
"if",
"(",
"!",
"Modifier",
".",
"isAbstract",
"(",
"t",
".",
"getModifiers",
"(",
")",
")",
"&&",
"!",
"t",
".",
"isInterface",
"(",
")",
")",
"{",
"T",
"instance",
"=",
"factory",
".",
"create",
"(",
"t",
")",
";",
"result",
".",
"add",
"(",
"instance",
")",
";",
"}",
"}",
"return",
"Collections",
".",
"unmodifiableSet",
"(",
"result",
")",
";",
"}"
] |
Create the given types.
@param types
@return
|
[
"Create",
"the",
"given",
"types",
"."
] |
aa121b3a5504b43d0c10450a1b984694fcd2b8ee
|
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-types/src/main/java/se/l4/commons/types/internal/TypeFinderOverScanResult.java#L94-L108
|
145,304
|
duraspace/fcrepo-cloudsync
|
fcrepo-cloudsync-service/src/main/java/org/duraspace/fcrepo/cloudsync/service/dao/TaskDao.java
|
TaskDao.updateIdleTask
|
private void updateIdleTask(final Task orig, Task mods) {
// only allow transition to "starting" state
String newState = StringUtil.normalize(mods.getState());
if (newState != null && !newState.equals(Task.IDLE) && !newState.equals(Task.STARTING)) {
throw new IllegalArgumentException("Illegal state transition: " + Task.IDLE + " -> " + newState);
}
if (newState != null) {
orig.setState(newState);
}
// At this point, id, activeLogId, and state have been validated/set.
// Now we need to validate/set name, type, schedule, and data.
if (StringUtil.normalize(mods.getName()) != null) {
orig.setName(StringUtil.validate("name", mods.getName(), 256));
}
if (StringUtil.normalize(mods.getType()) != null) {
orig.setType(StringUtil.validate("type", mods.getType(), 32));
}
if (StringUtil.normalize(mods.getSchedule()) != null) {
orig.setSchedule(StringUtil.validate("schedule", mods.getType(), 1024));
}
if (StringUtil.normalize(mods.getData()) != null) {
orig.setData(StringUtil.validate("data", mods.getData(), 32672));
}
// Validate schedule content, type-specific data,
// and do dependency determination
final TaskRunner runner = TaskRunner.getInstance(orig, this,
objectSetDao, objectStoreDao, null, null, new HttpClientConfig());
// Finally, update the necessary tables in a transaction
final int taskId = Integer.parseInt(orig.getId());
tt.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
boolean success = false;
try {
db.update(UPDATE_SQL,
orig.getName(),
orig.getType(),
orig.getState(),
orig.getSchedule(),
orig.getData(),
taskId);
db.update("DELETE FROM TaskSetDeps WHERE taskId = ?", taskId);
db.update("DELETE FROM TaskStoreDeps WHERE taskId = ?", taskId);
for (String setId: runner.getRelatedSetIds()) {
db.update(INSERT_SQL2, taskId, Integer.parseInt(setId));
}
for (String storeId: runner.getRelatedStoreIds()) {
db.update(INSERT_SQL3, taskId, Integer.parseInt(storeId));
}
success = true;
} finally {
if (!success) {
status.setRollbackOnly();
}
}
}
});
}
|
java
|
private void updateIdleTask(final Task orig, Task mods) {
// only allow transition to "starting" state
String newState = StringUtil.normalize(mods.getState());
if (newState != null && !newState.equals(Task.IDLE) && !newState.equals(Task.STARTING)) {
throw new IllegalArgumentException("Illegal state transition: " + Task.IDLE + " -> " + newState);
}
if (newState != null) {
orig.setState(newState);
}
// At this point, id, activeLogId, and state have been validated/set.
// Now we need to validate/set name, type, schedule, and data.
if (StringUtil.normalize(mods.getName()) != null) {
orig.setName(StringUtil.validate("name", mods.getName(), 256));
}
if (StringUtil.normalize(mods.getType()) != null) {
orig.setType(StringUtil.validate("type", mods.getType(), 32));
}
if (StringUtil.normalize(mods.getSchedule()) != null) {
orig.setSchedule(StringUtil.validate("schedule", mods.getType(), 1024));
}
if (StringUtil.normalize(mods.getData()) != null) {
orig.setData(StringUtil.validate("data", mods.getData(), 32672));
}
// Validate schedule content, type-specific data,
// and do dependency determination
final TaskRunner runner = TaskRunner.getInstance(orig, this,
objectSetDao, objectStoreDao, null, null, new HttpClientConfig());
// Finally, update the necessary tables in a transaction
final int taskId = Integer.parseInt(orig.getId());
tt.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
boolean success = false;
try {
db.update(UPDATE_SQL,
orig.getName(),
orig.getType(),
orig.getState(),
orig.getSchedule(),
orig.getData(),
taskId);
db.update("DELETE FROM TaskSetDeps WHERE taskId = ?", taskId);
db.update("DELETE FROM TaskStoreDeps WHERE taskId = ?", taskId);
for (String setId: runner.getRelatedSetIds()) {
db.update(INSERT_SQL2, taskId, Integer.parseInt(setId));
}
for (String storeId: runner.getRelatedStoreIds()) {
db.update(INSERT_SQL3, taskId, Integer.parseInt(storeId));
}
success = true;
} finally {
if (!success) {
status.setRollbackOnly();
}
}
}
});
}
|
[
"private",
"void",
"updateIdleTask",
"(",
"final",
"Task",
"orig",
",",
"Task",
"mods",
")",
"{",
"// only allow transition to \"starting\" state",
"String",
"newState",
"=",
"StringUtil",
".",
"normalize",
"(",
"mods",
".",
"getState",
"(",
")",
")",
";",
"if",
"(",
"newState",
"!=",
"null",
"&&",
"!",
"newState",
".",
"equals",
"(",
"Task",
".",
"IDLE",
")",
"&&",
"!",
"newState",
".",
"equals",
"(",
"Task",
".",
"STARTING",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Illegal state transition: \"",
"+",
"Task",
".",
"IDLE",
"+",
"\" -> \"",
"+",
"newState",
")",
";",
"}",
"if",
"(",
"newState",
"!=",
"null",
")",
"{",
"orig",
".",
"setState",
"(",
"newState",
")",
";",
"}",
"// At this point, id, activeLogId, and state have been validated/set.",
"// Now we need to validate/set name, type, schedule, and data.",
"if",
"(",
"StringUtil",
".",
"normalize",
"(",
"mods",
".",
"getName",
"(",
")",
")",
"!=",
"null",
")",
"{",
"orig",
".",
"setName",
"(",
"StringUtil",
".",
"validate",
"(",
"\"name\"",
",",
"mods",
".",
"getName",
"(",
")",
",",
"256",
")",
")",
";",
"}",
"if",
"(",
"StringUtil",
".",
"normalize",
"(",
"mods",
".",
"getType",
"(",
")",
")",
"!=",
"null",
")",
"{",
"orig",
".",
"setType",
"(",
"StringUtil",
".",
"validate",
"(",
"\"type\"",
",",
"mods",
".",
"getType",
"(",
")",
",",
"32",
")",
")",
";",
"}",
"if",
"(",
"StringUtil",
".",
"normalize",
"(",
"mods",
".",
"getSchedule",
"(",
")",
")",
"!=",
"null",
")",
"{",
"orig",
".",
"setSchedule",
"(",
"StringUtil",
".",
"validate",
"(",
"\"schedule\"",
",",
"mods",
".",
"getType",
"(",
")",
",",
"1024",
")",
")",
";",
"}",
"if",
"(",
"StringUtil",
".",
"normalize",
"(",
"mods",
".",
"getData",
"(",
")",
")",
"!=",
"null",
")",
"{",
"orig",
".",
"setData",
"(",
"StringUtil",
".",
"validate",
"(",
"\"data\"",
",",
"mods",
".",
"getData",
"(",
")",
",",
"32672",
")",
")",
";",
"}",
"// Validate schedule content, type-specific data,",
"// and do dependency determination",
"final",
"TaskRunner",
"runner",
"=",
"TaskRunner",
".",
"getInstance",
"(",
"orig",
",",
"this",
",",
"objectSetDao",
",",
"objectStoreDao",
",",
"null",
",",
"null",
",",
"new",
"HttpClientConfig",
"(",
")",
")",
";",
"// Finally, update the necessary tables in a transaction",
"final",
"int",
"taskId",
"=",
"Integer",
".",
"parseInt",
"(",
"orig",
".",
"getId",
"(",
")",
")",
";",
"tt",
".",
"execute",
"(",
"new",
"TransactionCallbackWithoutResult",
"(",
")",
"{",
"public",
"void",
"doInTransactionWithoutResult",
"(",
"TransactionStatus",
"status",
")",
"{",
"boolean",
"success",
"=",
"false",
";",
"try",
"{",
"db",
".",
"update",
"(",
"UPDATE_SQL",
",",
"orig",
".",
"getName",
"(",
")",
",",
"orig",
".",
"getType",
"(",
")",
",",
"orig",
".",
"getState",
"(",
")",
",",
"orig",
".",
"getSchedule",
"(",
")",
",",
"orig",
".",
"getData",
"(",
")",
",",
"taskId",
")",
";",
"db",
".",
"update",
"(",
"\"DELETE FROM TaskSetDeps WHERE taskId = ?\"",
",",
"taskId",
")",
";",
"db",
".",
"update",
"(",
"\"DELETE FROM TaskStoreDeps WHERE taskId = ?\"",
",",
"taskId",
")",
";",
"for",
"(",
"String",
"setId",
":",
"runner",
".",
"getRelatedSetIds",
"(",
")",
")",
"{",
"db",
".",
"update",
"(",
"INSERT_SQL2",
",",
"taskId",
",",
"Integer",
".",
"parseInt",
"(",
"setId",
")",
")",
";",
"}",
"for",
"(",
"String",
"storeId",
":",
"runner",
".",
"getRelatedStoreIds",
"(",
")",
")",
"{",
"db",
".",
"update",
"(",
"INSERT_SQL3",
",",
"taskId",
",",
"Integer",
".",
"parseInt",
"(",
"storeId",
")",
")",
";",
"}",
"success",
"=",
"true",
";",
"}",
"finally",
"{",
"if",
"(",
"!",
"success",
")",
"{",
"status",
".",
"setRollbackOnly",
"(",
")",
";",
"}",
"}",
"}",
"}",
")",
";",
"}"
] |
allow prop changes and state transition to "starting"
|
[
"allow",
"prop",
"changes",
"and",
"state",
"transition",
"to",
"starting"
] |
2d90e2c9c84a827f2605607ff40e116c67eff9b9
|
https://github.com/duraspace/fcrepo-cloudsync/blob/2d90e2c9c84a827f2605607ff40e116c67eff9b9/fcrepo-cloudsync-service/src/main/java/org/duraspace/fcrepo/cloudsync/service/dao/TaskDao.java#L231-L290
|
145,305
|
LevelFourAB/commons
|
commons-config/src/main/java/se/l4/commons/config/ConfigKey.java
|
ConfigKey.asObject
|
public <T> T asObject(Class<T> type)
{
return config.asObject(key, type);
}
|
java
|
public <T> T asObject(Class<T> type)
{
return config.asObject(key, type);
}
|
[
"public",
"<",
"T",
">",
"T",
"asObject",
"(",
"Class",
"<",
"T",
">",
"type",
")",
"{",
"return",
"config",
".",
"asObject",
"(",
"key",
",",
"type",
")",
";",
"}"
] |
Get this object as another type.
@param type
@return
|
[
"Get",
"this",
"object",
"as",
"another",
"type",
"."
] |
aa121b3a5504b43d0c10450a1b984694fcd2b8ee
|
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-config/src/main/java/se/l4/commons/config/ConfigKey.java#L77-L80
|
145,306
|
dbracewell/mango
|
src/main/java/com/davidbracewell/reflection/BeanUtils.java
|
BeanUtils.getBean
|
public static <T> T getBean(Class<T> clazz) throws ReflectionException {
return parameterizeObject(Reflect.onClass(clazz).create().<T>get());
}
|
java
|
public static <T> T getBean(Class<T> clazz) throws ReflectionException {
return parameterizeObject(Reflect.onClass(clazz).create().<T>get());
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"getBean",
"(",
"Class",
"<",
"T",
">",
"clazz",
")",
"throws",
"ReflectionException",
"{",
"return",
"parameterizeObject",
"(",
"Reflect",
".",
"onClass",
"(",
"clazz",
")",
".",
"create",
"(",
")",
".",
"<",
"T",
">",
"get",
"(",
")",
")",
";",
"}"
] |
Constructs a new instance of the given class and then sets it properties using configuration.
@param clazz The class that we want to instantiate
@return A new instance of the given class
|
[
"Constructs",
"a",
"new",
"instance",
"of",
"the",
"given",
"class",
"and",
"then",
"sets",
"it",
"properties",
"using",
"configuration",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/reflection/BeanUtils.java#L66-L68
|
145,307
|
dbracewell/mango
|
src/main/java/com/davidbracewell/reflection/BeanUtils.java
|
BeanUtils.parameterizeObject
|
public static <T> T parameterizeObject(T object) {
if (object == null) {
return null;
}
BeanMap beanMap = new BeanMap(object);
List<Class<?>> list = ReflectionUtils.getAncestorClasses(object);
Collections.reverse(list);
for (Class<?> clazz : list) {
doParametrization(beanMap, clazz.getName());
}
return object;
}
|
java
|
public static <T> T parameterizeObject(T object) {
if (object == null) {
return null;
}
BeanMap beanMap = new BeanMap(object);
List<Class<?>> list = ReflectionUtils.getAncestorClasses(object);
Collections.reverse(list);
for (Class<?> clazz : list) {
doParametrization(beanMap, clazz.getName());
}
return object;
}
|
[
"public",
"static",
"<",
"T",
">",
"T",
"parameterizeObject",
"(",
"T",
"object",
")",
"{",
"if",
"(",
"object",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"BeanMap",
"beanMap",
"=",
"new",
"BeanMap",
"(",
"object",
")",
";",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"list",
"=",
"ReflectionUtils",
".",
"getAncestorClasses",
"(",
"object",
")",
";",
"Collections",
".",
"reverse",
"(",
"list",
")",
";",
"for",
"(",
"Class",
"<",
"?",
">",
"clazz",
":",
"list",
")",
"{",
"doParametrization",
"(",
"beanMap",
",",
"clazz",
".",
"getName",
"(",
")",
")",
";",
"}",
"return",
"object",
";",
"}"
] |
Sets properties on an object using the values defined in the Config. Will set properties defined in the Config
for all of this object's super classes as well.
@param object The object to parameterize
@return The object
|
[
"Sets",
"properties",
"on",
"an",
"object",
"using",
"the",
"values",
"defined",
"in",
"the",
"Config",
".",
"Will",
"set",
"properties",
"defined",
"in",
"the",
"Config",
"for",
"all",
"of",
"this",
"object",
"s",
"super",
"classes",
"as",
"well",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/reflection/BeanUtils.java#L168-L181
|
145,308
|
josueeduardo/snappy
|
snappy/src/main/java/io/joshworks/snappy/http/MediaType.java
|
MediaType.valueOf
|
public static MediaType valueOf(String type) throws IllegalArgumentException {
if (type == null || type.trim().isEmpty() || type.startsWith(SUBTYPE_SEPARATOR) || type.endsWith(SUBTYPE_SEPARATOR)) {
throw new IllegalArgumentException("Invalid mime type '" + type + "'");
}
String[] splitType = type.split(SUBTYPE_SEPARATOR);
if (splitType.length == 2) {
nonEmpty(type, splitType[0]);
nonEmpty(type, splitType[1]);
Map<String, String> parameters = new HashMap<>();
String subType = splitType[1];
if (splitType[1].contains(PARAMETERS_SEPARATOR)) {
String[] subTypeWithparameter = splitType[1].split(PARAMETERS_SEPARATOR);
String paramString = subTypeWithparameter[1].trim();
subType = subTypeWithparameter[0];
parameters = parseParameters(paramString);
}
return new MediaType(splitType[0].trim(), subType.trim(), parameters);
}
if (!type.contains(SUBTYPE_SEPARATOR)) {
String mimeType = mimeMappings.getMimeType(type);
if (mimeType != null) {
return valueOf(mimeType);
}
}
throw new IllegalArgumentException("Invalid mime type '" + type + "'");
}
|
java
|
public static MediaType valueOf(String type) throws IllegalArgumentException {
if (type == null || type.trim().isEmpty() || type.startsWith(SUBTYPE_SEPARATOR) || type.endsWith(SUBTYPE_SEPARATOR)) {
throw new IllegalArgumentException("Invalid mime type '" + type + "'");
}
String[] splitType = type.split(SUBTYPE_SEPARATOR);
if (splitType.length == 2) {
nonEmpty(type, splitType[0]);
nonEmpty(type, splitType[1]);
Map<String, String> parameters = new HashMap<>();
String subType = splitType[1];
if (splitType[1].contains(PARAMETERS_SEPARATOR)) {
String[] subTypeWithparameter = splitType[1].split(PARAMETERS_SEPARATOR);
String paramString = subTypeWithparameter[1].trim();
subType = subTypeWithparameter[0];
parameters = parseParameters(paramString);
}
return new MediaType(splitType[0].trim(), subType.trim(), parameters);
}
if (!type.contains(SUBTYPE_SEPARATOR)) {
String mimeType = mimeMappings.getMimeType(type);
if (mimeType != null) {
return valueOf(mimeType);
}
}
throw new IllegalArgumentException("Invalid mime type '" + type + "'");
}
|
[
"public",
"static",
"MediaType",
"valueOf",
"(",
"String",
"type",
")",
"throws",
"IllegalArgumentException",
"{",
"if",
"(",
"type",
"==",
"null",
"||",
"type",
".",
"trim",
"(",
")",
".",
"isEmpty",
"(",
")",
"||",
"type",
".",
"startsWith",
"(",
"SUBTYPE_SEPARATOR",
")",
"||",
"type",
".",
"endsWith",
"(",
"SUBTYPE_SEPARATOR",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid mime type '\"",
"+",
"type",
"+",
"\"'\"",
")",
";",
"}",
"String",
"[",
"]",
"splitType",
"=",
"type",
".",
"split",
"(",
"SUBTYPE_SEPARATOR",
")",
";",
"if",
"(",
"splitType",
".",
"length",
"==",
"2",
")",
"{",
"nonEmpty",
"(",
"type",
",",
"splitType",
"[",
"0",
"]",
")",
";",
"nonEmpty",
"(",
"type",
",",
"splitType",
"[",
"1",
"]",
")",
";",
"Map",
"<",
"String",
",",
"String",
">",
"parameters",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"String",
"subType",
"=",
"splitType",
"[",
"1",
"]",
";",
"if",
"(",
"splitType",
"[",
"1",
"]",
".",
"contains",
"(",
"PARAMETERS_SEPARATOR",
")",
")",
"{",
"String",
"[",
"]",
"subTypeWithparameter",
"=",
"splitType",
"[",
"1",
"]",
".",
"split",
"(",
"PARAMETERS_SEPARATOR",
")",
";",
"String",
"paramString",
"=",
"subTypeWithparameter",
"[",
"1",
"]",
".",
"trim",
"(",
")",
";",
"subType",
"=",
"subTypeWithparameter",
"[",
"0",
"]",
";",
"parameters",
"=",
"parseParameters",
"(",
"paramString",
")",
";",
"}",
"return",
"new",
"MediaType",
"(",
"splitType",
"[",
"0",
"]",
".",
"trim",
"(",
")",
",",
"subType",
".",
"trim",
"(",
")",
",",
"parameters",
")",
";",
"}",
"if",
"(",
"!",
"type",
".",
"contains",
"(",
"SUBTYPE_SEPARATOR",
")",
")",
"{",
"String",
"mimeType",
"=",
"mimeMappings",
".",
"getMimeType",
"(",
"type",
")",
";",
"if",
"(",
"mimeType",
"!=",
"null",
")",
"{",
"return",
"valueOf",
"(",
"mimeType",
")",
";",
"}",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Invalid mime type '\"",
"+",
"type",
"+",
"\"'\"",
")",
";",
"}"
] |
Creates a new instance of MediaType by parsing the supplied string.
@param type the media type string
@return the newly created MediaType
@throws IllegalArgumentException if the supplied string cannot be parsed
or is null
|
[
"Creates",
"a",
"new",
"instance",
"of",
"MediaType",
"by",
"parsing",
"the",
"supplied",
"string",
"."
] |
d95a9e811eda3c24a5e53086369208819884fa49
|
https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/snappy/src/main/java/io/joshworks/snappy/http/MediaType.java#L221-L246
|
145,309
|
devcon5io/common
|
mixin/src/main/java/io/devcon5/mixin/Mixin.java
|
Mixin.invoke
|
private static Object invoke(final Object target, final Method method, Object... args) {
try {
return method.invoke(target, args);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
java
|
private static Object invoke(final Object target, final Method method, Object... args) {
try {
return method.invoke(target, args);
} catch (IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
[
"private",
"static",
"Object",
"invoke",
"(",
"final",
"Object",
"target",
",",
"final",
"Method",
"method",
",",
"Object",
"...",
"args",
")",
"{",
"try",
"{",
"return",
"method",
".",
"invoke",
"(",
"target",
",",
"args",
")",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"|",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Invokes the specified method on the specified object and wrapping all exceptions in a RuntimeException.
@param target the target object on which the method should be invoked. May be null for static method invocation
@param method the method to be invoked
@param args the arguments to be passed to the method. May be empty
@return the result of the invocation
|
[
"Invokes",
"the",
"specified",
"method",
"on",
"the",
"specified",
"object",
"and",
"wrapping",
"all",
"exceptions",
"in",
"a",
"RuntimeException",
"."
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L69-L76
|
145,310
|
devcon5io/common
|
mixin/src/main/java/io/devcon5/mixin/Mixin.java
|
Mixin.invokeDefault
|
private static Object invokeDefault(final Object proxy, final Method method, final Object[] args) {
final Class<?> declaringClass = method.getDeclaringClass();
try {
return lookupIn(declaringClass).unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
|
java
|
private static Object invokeDefault(final Object proxy, final Method method, final Object[] args) {
final Class<?> declaringClass = method.getDeclaringClass();
try {
return lookupIn(declaringClass).unreflectSpecial(method, declaringClass)
.bindTo(proxy)
.invokeWithArguments(args);
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
|
[
"private",
"static",
"Object",
"invokeDefault",
"(",
"final",
"Object",
"proxy",
",",
"final",
"Method",
"method",
",",
"final",
"Object",
"[",
"]",
"args",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"declaringClass",
"=",
"method",
".",
"getDeclaringClass",
"(",
")",
";",
"try",
"{",
"return",
"lookupIn",
"(",
"declaringClass",
")",
".",
"unreflectSpecial",
"(",
"method",
",",
"declaringClass",
")",
".",
"bindTo",
"(",
"proxy",
")",
".",
"invokeWithArguments",
"(",
"args",
")",
";",
"}",
"catch",
"(",
"Throwable",
"throwable",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"throwable",
")",
";",
"}",
"}"
] |
Invokes a default method. Default methods are implemented in an interface which is overrided by applying the
interface to the proxy. This method allows to invoke the default method on the proxy itselfs bypassing the
overriden method.
@param proxy the proxy object on which the method should be invoked
@param method the method to be invoked
@param args arguments that are passed to the method
@return the return value of the invocation
@throws Throwable
|
[
"Invokes",
"a",
"default",
"method",
".",
"Default",
"methods",
"are",
"implemented",
"in",
"an",
"interface",
"which",
"is",
"overrided",
"by",
"applying",
"the",
"interface",
"to",
"the",
"proxy",
".",
"This",
"method",
"allows",
"to",
"invoke",
"the",
"default",
"method",
"on",
"the",
"proxy",
"itselfs",
"bypassing",
"the",
"overriden",
"method",
"."
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L89-L99
|
145,311
|
devcon5io/common
|
mixin/src/main/java/io/devcon5/mixin/Mixin.java
|
Mixin.lookupIn
|
private static MethodHandles.Lookup lookupIn(final Class<?> declaringClass) {
try {
final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(
Class.class,
int.class);
constructor.setAccessible(true);
return constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
|
java
|
private static MethodHandles.Lookup lookupIn(final Class<?> declaringClass) {
try {
final Constructor<MethodHandles.Lookup> constructor = MethodHandles.Lookup.class.getDeclaredConstructor(
Class.class,
int.class);
constructor.setAccessible(true);
return constructor.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
|
[
"private",
"static",
"MethodHandles",
".",
"Lookup",
"lookupIn",
"(",
"final",
"Class",
"<",
"?",
">",
"declaringClass",
")",
"{",
"try",
"{",
"final",
"Constructor",
"<",
"MethodHandles",
".",
"Lookup",
">",
"constructor",
"=",
"MethodHandles",
".",
"Lookup",
".",
"class",
".",
"getDeclaredConstructor",
"(",
"Class",
".",
"class",
",",
"int",
".",
"class",
")",
";",
"constructor",
".",
"setAccessible",
"(",
"true",
")",
";",
"return",
"constructor",
".",
"newInstance",
"(",
"declaringClass",
",",
"MethodHandles",
".",
"Lookup",
".",
"PRIVATE",
")",
";",
"}",
"catch",
"(",
"NoSuchMethodException",
"|",
"InvocationTargetException",
"|",
"InstantiationException",
"|",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Creates a method lookup that is capable of accessing private members of declaring classes this Mixin factory has
usually no access to.
@param declaringClass
@return
@throws NoSuchMethodException
@throws IllegalAccessException
@throws InvocationTargetException
@throws InstantiationException
|
[
"Creates",
"a",
"method",
"lookup",
"that",
"is",
"capable",
"of",
"accessing",
"private",
"members",
"of",
"declaring",
"classes",
"this",
"Mixin",
"factory",
"has",
"usually",
"no",
"access",
"to",
"."
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L112-L124
|
145,312
|
devcon5io/common
|
mixin/src/main/java/io/devcon5/mixin/Mixin.java
|
Mixin.newInvocable
|
private static Optional<Invocable> newInvocable(final Object target, final Collection<Supplier<Reader>> scripts) {
Optional<Invocable> invocable;
if (!scripts.isEmpty()) {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
engine.put("target", target);
scripts.stream().forEach(script -> loadScript(engine, script));
invocable = Optional.of((Invocable) engine);
} else {
invocable = Optional.empty();
}
return invocable;
}
|
java
|
private static Optional<Invocable> newInvocable(final Object target, final Collection<Supplier<Reader>> scripts) {
Optional<Invocable> invocable;
if (!scripts.isEmpty()) {
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
engine.put("target", target);
scripts.stream().forEach(script -> loadScript(engine, script));
invocable = Optional.of((Invocable) engine);
} else {
invocable = Optional.empty();
}
return invocable;
}
|
[
"private",
"static",
"Optional",
"<",
"Invocable",
">",
"newInvocable",
"(",
"final",
"Object",
"target",
",",
"final",
"Collection",
"<",
"Supplier",
"<",
"Reader",
">",
">",
"scripts",
")",
"{",
"Optional",
"<",
"Invocable",
">",
"invocable",
";",
"if",
"(",
"!",
"scripts",
".",
"isEmpty",
"(",
")",
")",
"{",
"final",
"ScriptEngine",
"engine",
"=",
"new",
"ScriptEngineManager",
"(",
")",
".",
"getEngineByName",
"(",
"\"javascript\"",
")",
";",
"engine",
".",
"put",
"(",
"\"target\"",
",",
"target",
")",
";",
"scripts",
".",
"stream",
"(",
")",
".",
"forEach",
"(",
"script",
"->",
"loadScript",
"(",
"engine",
",",
"script",
")",
")",
";",
"invocable",
"=",
"Optional",
".",
"of",
"(",
"(",
"Invocable",
")",
"engine",
")",
";",
"}",
"else",
"{",
"invocable",
"=",
"Optional",
".",
"empty",
"(",
")",
";",
"}",
"return",
"invocable",
";",
"}"
] |
Creates a new invocable proxy. The proxy may be used to create interface implementations that are implemented in
javascript.
@param target the target object that is passed into the scripting context so that the methods in the script may access
the target object.
@param scripts scripts to be loaded into the engine
@return the invocable instance
|
[
"Creates",
"a",
"new",
"invocable",
"proxy",
".",
"The",
"proxy",
"may",
"be",
"used",
"to",
"create",
"interface",
"implementations",
"that",
"are",
"implemented",
"in",
"javascript",
"."
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L135-L148
|
145,313
|
devcon5io/common
|
mixin/src/main/java/io/devcon5/mixin/Mixin.java
|
Mixin.loadScript
|
private static void loadScript(ScriptEngine engine, Supplier<Reader> scriptReader) {
try (Reader reader = scriptReader.get()) {
engine.eval(reader);
} catch (ScriptException | IOException e) {
throw new RuntimeException(e);
}
}
|
java
|
private static void loadScript(ScriptEngine engine, Supplier<Reader> scriptReader) {
try (Reader reader = scriptReader.get()) {
engine.eval(reader);
} catch (ScriptException | IOException e) {
throw new RuntimeException(e);
}
}
|
[
"private",
"static",
"void",
"loadScript",
"(",
"ScriptEngine",
"engine",
",",
"Supplier",
"<",
"Reader",
">",
"scriptReader",
")",
"{",
"try",
"(",
"Reader",
"reader",
"=",
"scriptReader",
".",
"get",
"(",
")",
")",
"{",
"engine",
".",
"eval",
"(",
"reader",
")",
";",
"}",
"catch",
"(",
"ScriptException",
"|",
"IOException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Loads a single script from an URL into the script engine
@param engine the engine that should evaluate the script
@param scriptReader the script source to be loaded into the script
|
[
"Loads",
"a",
"single",
"script",
"from",
"an",
"URL",
"into",
"the",
"script",
"engine"
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/mixin/src/main/java/io/devcon5/mixin/Mixin.java#L156-L164
|
145,314
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.addConstructor
|
public final void addConstructor(final SgConstructor constructor) {
if (constructor == null) {
throw new IllegalArgumentException("The argument 'constructor' cannot be null!");
}
if (constructor.getOwner() != this) {
throw new IllegalArgumentException(
"The owner of 'constructor' is different from 'this'!");
}
if (!constructors.contains(constructor)) {
constructors.add(constructor);
}
}
|
java
|
public final void addConstructor(final SgConstructor constructor) {
if (constructor == null) {
throw new IllegalArgumentException("The argument 'constructor' cannot be null!");
}
if (constructor.getOwner() != this) {
throw new IllegalArgumentException(
"The owner of 'constructor' is different from 'this'!");
}
if (!constructors.contains(constructor)) {
constructors.add(constructor);
}
}
|
[
"public",
"final",
"void",
"addConstructor",
"(",
"final",
"SgConstructor",
"constructor",
")",
"{",
"if",
"(",
"constructor",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'constructor' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"constructor",
".",
"getOwner",
"(",
")",
"!=",
"this",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The owner of 'constructor' is different from 'this'!\"",
")",
";",
"}",
"if",
"(",
"!",
"constructors",
".",
"contains",
"(",
"constructor",
")",
")",
"{",
"constructors",
".",
"add",
"(",
"constructor",
")",
";",
"}",
"}"
] |
Adds a constructor to the class. Does nothing if the constructor is
already in the list of constructors. You will never need to use this
method in your code! A constructor is added automatically to the owning
class when it's constructed!
@param constructor
Constructor to add - Cannot be null.
|
[
"Adds",
"a",
"constructor",
"to",
"the",
"class",
".",
"Does",
"nothing",
"if",
"the",
"constructor",
"is",
"already",
"in",
"the",
"list",
"of",
"constructors",
".",
"You",
"will",
"never",
"need",
"to",
"use",
"this",
"method",
"in",
"your",
"code!",
"A",
"constructor",
"is",
"added",
"automatically",
"to",
"the",
"owning",
"class",
"when",
"it",
"s",
"constructed!"
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L261-L272
|
145,315
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.addMethod
|
public final void addMethod(final SgMethod method) {
if (method == null) {
throw new IllegalArgumentException("The argument 'method' cannot be null!");
}
if (method.getOwner() != this) {
throw new IllegalArgumentException("The owner of 'method' is different from 'this'!");
}
if (!methods.contains(method)) {
methods.add(method);
}
}
|
java
|
public final void addMethod(final SgMethod method) {
if (method == null) {
throw new IllegalArgumentException("The argument 'method' cannot be null!");
}
if (method.getOwner() != this) {
throw new IllegalArgumentException("The owner of 'method' is different from 'this'!");
}
if (!methods.contains(method)) {
methods.add(method);
}
}
|
[
"public",
"final",
"void",
"addMethod",
"(",
"final",
"SgMethod",
"method",
")",
"{",
"if",
"(",
"method",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'method' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"method",
".",
"getOwner",
"(",
")",
"!=",
"this",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The owner of 'method' is different from 'this'!\"",
")",
";",
"}",
"if",
"(",
"!",
"methods",
".",
"contains",
"(",
"method",
")",
")",
"{",
"methods",
".",
"add",
"(",
"method",
")",
";",
"}",
"}"
] |
Adds a method to the class. Does nothing if the method is already in the
list of methods. You will never need to use this method in your code! A
method is added automatically to the owning class when it's constructed!
@param method
Method to add - Cannot be null.
|
[
"Adds",
"a",
"method",
"to",
"the",
"class",
".",
"Does",
"nothing",
"if",
"the",
"method",
"is",
"already",
"in",
"the",
"list",
"of",
"methods",
".",
"You",
"will",
"never",
"need",
"to",
"use",
"this",
"method",
"in",
"your",
"code!",
"A",
"method",
"is",
"added",
"automatically",
"to",
"the",
"owning",
"class",
"when",
"it",
"s",
"constructed!"
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L300-L310
|
145,316
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.addField
|
public final void addField(final SgField field) {
if (field == null) {
throw new IllegalArgumentException("The argument 'field' cannot be null!");
}
if (field.getOwner() != this) {
throw new IllegalArgumentException("The owner of 'field' is different from 'this'!");
}
if (!fields.contains(field)) {
fields.add(field);
}
}
|
java
|
public final void addField(final SgField field) {
if (field == null) {
throw new IllegalArgumentException("The argument 'field' cannot be null!");
}
if (field.getOwner() != this) {
throw new IllegalArgumentException("The owner of 'field' is different from 'this'!");
}
if (!fields.contains(field)) {
fields.add(field);
}
}
|
[
"public",
"final",
"void",
"addField",
"(",
"final",
"SgField",
"field",
")",
"{",
"if",
"(",
"field",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'field' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"field",
".",
"getOwner",
"(",
")",
"!=",
"this",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The owner of 'field' is different from 'this'!\"",
")",
";",
"}",
"if",
"(",
"!",
"fields",
".",
"contains",
"(",
"field",
")",
")",
"{",
"fields",
".",
"add",
"(",
"field",
")",
";",
"}",
"}"
] |
Adds a field to the class. Does nothing if the field is already in the
list of fields. You will never need to use this method in your code! A
field is added automatically to the owning class when it's constructed!
@param field
Field to add - Cannot be null.
|
[
"Adds",
"a",
"field",
"to",
"the",
"class",
".",
"Does",
"nothing",
"if",
"the",
"field",
"is",
"already",
"in",
"the",
"list",
"of",
"fields",
".",
"You",
"will",
"never",
"need",
"to",
"use",
"this",
"method",
"in",
"your",
"code!",
"A",
"field",
"is",
"added",
"automatically",
"to",
"the",
"owning",
"class",
"when",
"it",
"s",
"constructed!"
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L458-L468
|
145,317
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.addClass
|
public final void addClass(final SgClass clasz) {
if (clasz == null) {
throw new IllegalArgumentException("The argument 'clasz' cannot be null!");
}
if (!classes.contains(clasz)) {
classes.add(clasz);
}
}
|
java
|
public final void addClass(final SgClass clasz) {
if (clasz == null) {
throw new IllegalArgumentException("The argument 'clasz' cannot be null!");
}
if (!classes.contains(clasz)) {
classes.add(clasz);
}
}
|
[
"public",
"final",
"void",
"addClass",
"(",
"final",
"SgClass",
"clasz",
")",
"{",
"if",
"(",
"clasz",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'clasz' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"!",
"classes",
".",
"contains",
"(",
"clasz",
")",
")",
"{",
"classes",
".",
"add",
"(",
"clasz",
")",
";",
"}",
"}"
] |
Adds an inner to this class. Does nothing if the class is already in the
list of inner classes.
@param clasz
Inner class to add - Cannot be null.
|
[
"Adds",
"an",
"inner",
"to",
"this",
"class",
".",
"Does",
"nothing",
"if",
"the",
"class",
"is",
"already",
"in",
"the",
"list",
"of",
"inner",
"classes",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L486-L493
|
145,318
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.findClassByName
|
public final SgClass findClassByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < classes.size(); i++) {
final SgClass clasz = classes.get(i);
if (clasz.getName().equals(name)) {
return clasz;
}
}
return null;
}
|
java
|
public final SgClass findClassByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < classes.size(); i++) {
final SgClass clasz = classes.get(i);
if (clasz.getName().equals(name)) {
return clasz;
}
}
return null;
}
|
[
"public",
"final",
"SgClass",
"findClassByName",
"(",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'name' cannot be null!\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"classes",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"SgClass",
"clasz",
"=",
"classes",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"clasz",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
"clasz",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find an inner class by it's name.
@param name
Full qualified name of the class to find - Cannot be null.
@return Class or null if it's not found.
|
[
"Find",
"an",
"inner",
"class",
"by",
"it",
"s",
"name",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L512-L523
|
145,319
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.findMethodByName
|
public final SgMethod findMethodByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < methods.size(); i++) {
final SgMethod method = methods.get(i);
if (method.getName().equals(name)) {
return method;
}
}
return null;
}
|
java
|
public final SgMethod findMethodByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < methods.size(); i++) {
final SgMethod method = methods.get(i);
if (method.getName().equals(name)) {
return method;
}
}
return null;
}
|
[
"public",
"final",
"SgMethod",
"findMethodByName",
"(",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'name' cannot be null!\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"methods",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"SgMethod",
"method",
"=",
"methods",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"method",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
"method",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find a method by it's name.
@param name
Name of the method to find - Cannot be null.
@return Method or null if it's not found.
|
[
"Find",
"a",
"method",
"by",
"it",
"s",
"name",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L533-L544
|
145,320
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.findFieldByName
|
public final SgField findFieldByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < fields.size(); i++) {
final SgField field = fields.get(i);
if (field.getName().equals(name)) {
return field;
}
}
return null;
}
|
java
|
public final SgField findFieldByName(final String name) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
for (int i = 0; i < fields.size(); i++) {
final SgField field = fields.get(i);
if (field.getName().equals(name)) {
return field;
}
}
return null;
}
|
[
"public",
"final",
"SgField",
"findFieldByName",
"(",
"final",
"String",
"name",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'name' cannot be null!\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"fields",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"SgField",
"field",
"=",
"fields",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"field",
".",
"getName",
"(",
")",
".",
"equals",
"(",
"name",
")",
")",
"{",
"return",
"field",
";",
"}",
"}",
"return",
"null",
";",
"}"
] |
Find a field by it's name.
@param name
Name of the field to find - Cannot be null.
@return Field or null if it's not found.
|
[
"Find",
"a",
"field",
"by",
"it",
"s",
"name",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L554-L565
|
145,321
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.hasInterface
|
public final boolean hasInterface(final SgClass intf) {
if (intf == null) {
throw new IllegalArgumentException("The argument 'intf' cannot be null!");
}
if (!intf.isInterface()) {
throw new IllegalArgumentException(
"The argument 'intf' is a class an not an interface!");
}
for (int i = 0; i < interfaces.size(); i++) {
if (interfaces.get(i).equals(intf)) {
return true;
}
}
if (superClass != null) {
return superClass.hasInterface(intf);
}
return false;
}
|
java
|
public final boolean hasInterface(final SgClass intf) {
if (intf == null) {
throw new IllegalArgumentException("The argument 'intf' cannot be null!");
}
if (!intf.isInterface()) {
throw new IllegalArgumentException(
"The argument 'intf' is a class an not an interface!");
}
for (int i = 0; i < interfaces.size(); i++) {
if (interfaces.get(i).equals(intf)) {
return true;
}
}
if (superClass != null) {
return superClass.hasInterface(intf);
}
return false;
}
|
[
"public",
"final",
"boolean",
"hasInterface",
"(",
"final",
"SgClass",
"intf",
")",
"{",
"if",
"(",
"intf",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'intf' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"!",
"intf",
".",
"isInterface",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'intf' is a class an not an interface!\"",
")",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"interfaces",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"interfaces",
".",
"get",
"(",
"i",
")",
".",
"equals",
"(",
"intf",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"if",
"(",
"superClass",
"!=",
"null",
")",
"{",
"return",
"superClass",
".",
"hasInterface",
"(",
"intf",
")",
";",
"}",
"return",
"false",
";",
"}"
] |
Checks if this class or any of it's super classes has a given interface.
@param intf
Interface to find - Cannot be <code>null</code>.
@return If the class implements the interface <code>true</code> else
<code>false</code>.
|
[
"Checks",
"if",
"this",
"class",
"or",
"any",
"of",
"it",
"s",
"super",
"classes",
"has",
"a",
"given",
"interface",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L725-L744
|
145,322
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.create
|
public static SgClass create(final SgClassPool pool, final Class<?> clasz) {
if (pool == null) {
throw new IllegalArgumentException("The argument 'pool' cannot be null!");
}
if (clasz == null) {
throw new IllegalArgumentException("The argument 'clasz' cannot be null!");
}
final SgClass cached = pool.get(clasz.getName());
if (cached != null) {
return cached;
}
try {
final SgClass cl = createClass(pool, clasz);
addInterfaces(pool, cl, clasz);
addFields(pool, cl, clasz);
addConstructors(pool, cl, clasz);
addMethods(pool, cl, clasz);
addInnerClasses(pool, cl, clasz);
return cl;
} catch (final RuntimeException ex) {
System.out.println("ERROR CLASS: " + clasz);
throw ex;
}
}
|
java
|
public static SgClass create(final SgClassPool pool, final Class<?> clasz) {
if (pool == null) {
throw new IllegalArgumentException("The argument 'pool' cannot be null!");
}
if (clasz == null) {
throw new IllegalArgumentException("The argument 'clasz' cannot be null!");
}
final SgClass cached = pool.get(clasz.getName());
if (cached != null) {
return cached;
}
try {
final SgClass cl = createClass(pool, clasz);
addInterfaces(pool, cl, clasz);
addFields(pool, cl, clasz);
addConstructors(pool, cl, clasz);
addMethods(pool, cl, clasz);
addInnerClasses(pool, cl, clasz);
return cl;
} catch (final RuntimeException ex) {
System.out.println("ERROR CLASS: " + clasz);
throw ex;
}
}
|
[
"public",
"static",
"SgClass",
"create",
"(",
"final",
"SgClassPool",
"pool",
",",
"final",
"Class",
"<",
"?",
">",
"clasz",
")",
"{",
"if",
"(",
"pool",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'pool' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"clasz",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'clasz' cannot be null!\"",
")",
";",
"}",
"final",
"SgClass",
"cached",
"=",
"pool",
".",
"get",
"(",
"clasz",
".",
"getName",
"(",
")",
")",
";",
"if",
"(",
"cached",
"!=",
"null",
")",
"{",
"return",
"cached",
";",
"}",
"try",
"{",
"final",
"SgClass",
"cl",
"=",
"createClass",
"(",
"pool",
",",
"clasz",
")",
";",
"addInterfaces",
"(",
"pool",
",",
"cl",
",",
"clasz",
")",
";",
"addFields",
"(",
"pool",
",",
"cl",
",",
"clasz",
")",
";",
"addConstructors",
"(",
"pool",
",",
"cl",
",",
"clasz",
")",
";",
"addMethods",
"(",
"pool",
",",
"cl",
",",
"clasz",
")",
";",
"addInnerClasses",
"(",
"pool",
",",
"cl",
",",
"clasz",
")",
";",
"return",
"cl",
";",
"}",
"catch",
"(",
"final",
"RuntimeException",
"ex",
")",
"{",
"System",
".",
"out",
".",
"println",
"(",
"\"ERROR CLASS: \"",
"+",
"clasz",
")",
";",
"throw",
"ex",
";",
"}",
"}"
] |
Creates a model class by analyzing the "real" class.
@param pool
Pool to use.
@param clasz
Class to analyze.
@return Class.
|
[
"Creates",
"a",
"model",
"class",
"by",
"analyzing",
"the",
"real",
"class",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L815-L843
|
145,323
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgClass.java
|
SgClass.getNonPrimitiveClass
|
public static final SgClass getNonPrimitiveClass(final SgClassPool pool, final SgClass primitive) {
if (primitive.equals(BOOLEAN)) {
return SgClass.create(pool, Boolean.class);
}
if (primitive.equals(BYTE)) {
return SgClass.create(pool, Byte.class);
}
if (primitive.equals(CHAR)) {
return SgClass.create(pool, Character.class);
}
if (primitive.equals(SHORT)) {
return SgClass.create(pool, Short.class);
}
if (primitive.equals(INT)) {
return SgClass.create(pool, Integer.class);
}
if (primitive.equals(LONG)) {
return SgClass.create(pool, Long.class);
}
if (primitive.equals(FLOAT)) {
return SgClass.create(pool, Float.class);
}
if (primitive.equals(DOUBLE)) {
return SgClass.create(pool, Double.class);
}
throw new IllegalArgumentException("No primitive or 'void' class: '" + primitive.getName()
+ "'!");
}
|
java
|
public static final SgClass getNonPrimitiveClass(final SgClassPool pool, final SgClass primitive) {
if (primitive.equals(BOOLEAN)) {
return SgClass.create(pool, Boolean.class);
}
if (primitive.equals(BYTE)) {
return SgClass.create(pool, Byte.class);
}
if (primitive.equals(CHAR)) {
return SgClass.create(pool, Character.class);
}
if (primitive.equals(SHORT)) {
return SgClass.create(pool, Short.class);
}
if (primitive.equals(INT)) {
return SgClass.create(pool, Integer.class);
}
if (primitive.equals(LONG)) {
return SgClass.create(pool, Long.class);
}
if (primitive.equals(FLOAT)) {
return SgClass.create(pool, Float.class);
}
if (primitive.equals(DOUBLE)) {
return SgClass.create(pool, Double.class);
}
throw new IllegalArgumentException("No primitive or 'void' class: '" + primitive.getName()
+ "'!");
}
|
[
"public",
"static",
"final",
"SgClass",
"getNonPrimitiveClass",
"(",
"final",
"SgClassPool",
"pool",
",",
"final",
"SgClass",
"primitive",
")",
"{",
"if",
"(",
"primitive",
".",
"equals",
"(",
"BOOLEAN",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Boolean",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"BYTE",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Byte",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"CHAR",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Character",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"SHORT",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Short",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"INT",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Integer",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"LONG",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Long",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"FLOAT",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Float",
".",
"class",
")",
";",
"}",
"if",
"(",
"primitive",
".",
"equals",
"(",
"DOUBLE",
")",
")",
"{",
"return",
"SgClass",
".",
"create",
"(",
"pool",
",",
"Double",
".",
"class",
")",
";",
"}",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"No primitive or 'void' class: '\"",
"+",
"primitive",
".",
"getName",
"(",
")",
"+",
"\"'!\"",
")",
";",
"}"
] |
Returns the corresponding class for a primitive.
@param pool
Pool to use.
@param primitive
Primitive class to convert. A call to {@link #isPrimitive()}
on this argument must return true and a call to
<code>equals(SgClass.VOID)</code> returns false else an
{@link IllegalArgumentException} will be thrown.
@return Non primitive class.
|
[
"Returns",
"the",
"corresponding",
"class",
"for",
"a",
"primitive",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgClass.java#L969-L996
|
145,324
|
bsblabs/embed-for-vaadin
|
com.bsb.common.vaadin.embed/src/main/java/com/bsb/common/vaadin/embed/EmbedVaadinConfig.java
|
EmbedVaadinConfig.getOpenBrowserUrl
|
public String getOpenBrowserUrl() {
final String customUrl = getCustomBrowserUrl();
final String deployUrl = getDeployUrl();
if (customUrl == null) {
return deployUrl;
} else if (customUrl.startsWith("http://")) {
return customUrl;
} else if (customUrl.startsWith("/")) {
return buildUrl(getPort(), customUrl);
} else {
return deployUrl + customUrl;
}
}
|
java
|
public String getOpenBrowserUrl() {
final String customUrl = getCustomBrowserUrl();
final String deployUrl = getDeployUrl();
if (customUrl == null) {
return deployUrl;
} else if (customUrl.startsWith("http://")) {
return customUrl;
} else if (customUrl.startsWith("/")) {
return buildUrl(getPort(), customUrl);
} else {
return deployUrl + customUrl;
}
}
|
[
"public",
"String",
"getOpenBrowserUrl",
"(",
")",
"{",
"final",
"String",
"customUrl",
"=",
"getCustomBrowserUrl",
"(",
")",
";",
"final",
"String",
"deployUrl",
"=",
"getDeployUrl",
"(",
")",
";",
"if",
"(",
"customUrl",
"==",
"null",
")",
"{",
"return",
"deployUrl",
";",
"}",
"else",
"if",
"(",
"customUrl",
".",
"startsWith",
"(",
"\"http://\"",
")",
")",
"{",
"return",
"customUrl",
";",
"}",
"else",
"if",
"(",
"customUrl",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"{",
"return",
"buildUrl",
"(",
"getPort",
"(",
")",
",",
"customUrl",
")",
";",
"}",
"else",
"{",
"return",
"deployUrl",
"+",
"customUrl",
";",
"}",
"}"
] |
Returns the url to use when the browser opens, according to both the deploy url
and a custom browser url, if set.
@return the url to use when to open the browser
|
[
"Returns",
"the",
"url",
"to",
"use",
"when",
"the",
"browser",
"opens",
"according",
"to",
"both",
"the",
"deploy",
"url",
"and",
"a",
"custom",
"browser",
"url",
"if",
"set",
"."
] |
f902e70def56ab54d287d2600f9c6eef9e66c225
|
https://github.com/bsblabs/embed-for-vaadin/blob/f902e70def56ab54d287d2600f9c6eef9e66c225/com.bsb.common.vaadin.embed/src/main/java/com/bsb/common/vaadin/embed/EmbedVaadinConfig.java#L310-L322
|
145,325
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/learning/LogLikelihoodDifferentiableFunction.java
|
LogLikelihoodDifferentiableFunction.getDeterministicAssignment
|
private static int getDeterministicAssignment(double[] distribution) {
int assignment = -1;
for (int i = 0; i < distribution.length; i++) {
if (distribution[i] == 1.0) {
if (assignment == -1) assignment = i;
else return -1;
} else if (distribution[i] != 0.0) return -1;
}
return assignment;
}
|
java
|
private static int getDeterministicAssignment(double[] distribution) {
int assignment = -1;
for (int i = 0; i < distribution.length; i++) {
if (distribution[i] == 1.0) {
if (assignment == -1) assignment = i;
else return -1;
} else if (distribution[i] != 0.0) return -1;
}
return assignment;
}
|
[
"private",
"static",
"int",
"getDeterministicAssignment",
"(",
"double",
"[",
"]",
"distribution",
")",
"{",
"int",
"assignment",
"=",
"-",
"1",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"distribution",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"distribution",
"[",
"i",
"]",
"==",
"1.0",
")",
"{",
"if",
"(",
"assignment",
"==",
"-",
"1",
")",
"assignment",
"=",
"i",
";",
"else",
"return",
"-",
"1",
";",
"}",
"else",
"if",
"(",
"distribution",
"[",
"i",
"]",
"!=",
"0.0",
")",
"return",
"-",
"1",
";",
"}",
"return",
"assignment",
";",
"}"
] |
Finds the deterministic assignment forced by a distribution, or if none exists returns -1
@param distribution the potentially deterministic distribution
@return the assignment given by the distribution with probability 1, if one exists, else -1
|
[
"Finds",
"the",
"deterministic",
"assignment",
"forced",
"by",
"a",
"distribution",
"or",
"if",
"none",
"exists",
"returns",
"-",
"1"
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/learning/LogLikelihoodDifferentiableFunction.java#L124-L133
|
145,326
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java
|
CliqueTree.compileModel
|
public GraphicalModel compileModel() {
GraphicalModel compiled = new GraphicalModel();
for (GraphicalModel.Factor factor : model.factors) {
compiled.addStaticFactor(factor.neigborIndices, factor.getDimensions(),
assign -> factor.getAssignmentValue(assign, weights));
}
// Add any metadata
for (int var = 0; var < model.numVariables(); ++var) {
Map<String, String> metadata = model.getVariableMetaDataByReference(var);
if (metadata.containsKey(VARIABLE_OBSERVED_VALUE)) {
compiled.getVariableMetaDataByReference(var).put(VARIABLE_OBSERVED_VALUE, metadata.get(VARIABLE_OBSERVED_VALUE));
}
}
return compiled;
}
|
java
|
public GraphicalModel compileModel() {
GraphicalModel compiled = new GraphicalModel();
for (GraphicalModel.Factor factor : model.factors) {
compiled.addStaticFactor(factor.neigborIndices, factor.getDimensions(),
assign -> factor.getAssignmentValue(assign, weights));
}
// Add any metadata
for (int var = 0; var < model.numVariables(); ++var) {
Map<String, String> metadata = model.getVariableMetaDataByReference(var);
if (metadata.containsKey(VARIABLE_OBSERVED_VALUE)) {
compiled.getVariableMetaDataByReference(var).put(VARIABLE_OBSERVED_VALUE, metadata.get(VARIABLE_OBSERVED_VALUE));
}
}
return compiled;
}
|
[
"public",
"GraphicalModel",
"compileModel",
"(",
")",
"{",
"GraphicalModel",
"compiled",
"=",
"new",
"GraphicalModel",
"(",
")",
";",
"for",
"(",
"GraphicalModel",
".",
"Factor",
"factor",
":",
"model",
".",
"factors",
")",
"{",
"compiled",
".",
"addStaticFactor",
"(",
"factor",
".",
"neigborIndices",
",",
"factor",
".",
"getDimensions",
"(",
")",
",",
"assign",
"->",
"factor",
".",
"getAssignmentValue",
"(",
"assign",
",",
"weights",
")",
")",
";",
"}",
"// Add any metadata",
"for",
"(",
"int",
"var",
"=",
"0",
";",
"var",
"<",
"model",
".",
"numVariables",
"(",
")",
";",
"++",
"var",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"metadata",
"=",
"model",
".",
"getVariableMetaDataByReference",
"(",
"var",
")",
";",
"if",
"(",
"metadata",
".",
"containsKey",
"(",
"VARIABLE_OBSERVED_VALUE",
")",
")",
"{",
"compiled",
".",
"getVariableMetaDataByReference",
"(",
"var",
")",
".",
"put",
"(",
"VARIABLE_OBSERVED_VALUE",
",",
"metadata",
".",
"get",
"(",
"VARIABLE_OBSERVED_VALUE",
")",
")",
";",
"}",
"}",
"return",
"compiled",
";",
"}"
] |
Compile this model into a static model, given the model and weights in this
clique tree.
@return A graphical model which is composed entirely of static (i.e.,
not featurized) factors.
|
[
"Compile",
"this",
"model",
"into",
"a",
"static",
"model",
"given",
"the",
"model",
"and",
"weights",
"in",
"this",
"clique",
"tree",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java#L191-L206
|
145,327
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java
|
CliqueTree.marginalizeMessage
|
private TableFactor marginalizeMessage(TableFactor message, int[] relevant, MarginalizationMethod marginalize) {
TableFactor result = message;
for (int i : message.neighborIndices) {
boolean contains = false;
for (int j : relevant) {
if (i == j) {
contains = true;
break;
}
}
if (!contains) {
switch (marginalize) {
case SUM:
result = result.sumOut(i);
break;
case MAX:
result = result.maxOut(i);
break;
}
}
}
return result;
}
|
java
|
private TableFactor marginalizeMessage(TableFactor message, int[] relevant, MarginalizationMethod marginalize) {
TableFactor result = message;
for (int i : message.neighborIndices) {
boolean contains = false;
for (int j : relevant) {
if (i == j) {
contains = true;
break;
}
}
if (!contains) {
switch (marginalize) {
case SUM:
result = result.sumOut(i);
break;
case MAX:
result = result.maxOut(i);
break;
}
}
}
return result;
}
|
[
"private",
"TableFactor",
"marginalizeMessage",
"(",
"TableFactor",
"message",
",",
"int",
"[",
"]",
"relevant",
",",
"MarginalizationMethod",
"marginalize",
")",
"{",
"TableFactor",
"result",
"=",
"message",
";",
"for",
"(",
"int",
"i",
":",
"message",
".",
"neighborIndices",
")",
"{",
"boolean",
"contains",
"=",
"false",
";",
"for",
"(",
"int",
"j",
":",
"relevant",
")",
"{",
"if",
"(",
"i",
"==",
"j",
")",
"{",
"contains",
"=",
"true",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"contains",
")",
"{",
"switch",
"(",
"marginalize",
")",
"{",
"case",
"SUM",
":",
"result",
"=",
"result",
".",
"sumOut",
"(",
"i",
")",
";",
"break",
";",
"case",
"MAX",
":",
"result",
"=",
"result",
".",
"maxOut",
"(",
"i",
")",
";",
"break",
";",
"}",
"}",
"}",
"return",
"result",
";",
"}"
] |
This is a key step in message passing. When we are calculating a message, we want to marginalize out all variables
not relevant to the recipient of the message. This function does that.
@param message the message to marginalize
@param relevant the variables that are relevant
@return the marginalized message
|
[
"This",
"is",
"a",
"key",
"step",
"in",
"message",
"passing",
".",
"When",
"we",
"are",
"calculating",
"a",
"message",
"we",
"want",
"to",
"marginalize",
"out",
"all",
"variables",
"not",
"relevant",
"to",
"the",
"recipient",
"of",
"the",
"message",
".",
"This",
"function",
"does",
"that",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java#L885-L909
|
145,328
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java
|
CliqueTree.domainsOverlap
|
private boolean domainsOverlap(TableFactor f1, TableFactor f2) {
for (int n1 : f1.neighborIndices) {
for (int n2 : f2.neighborIndices) {
if (n1 == n2) return true;
}
}
return false;
}
|
java
|
private boolean domainsOverlap(TableFactor f1, TableFactor f2) {
for (int n1 : f1.neighborIndices) {
for (int n2 : f2.neighborIndices) {
if (n1 == n2) return true;
}
}
return false;
}
|
[
"private",
"boolean",
"domainsOverlap",
"(",
"TableFactor",
"f1",
",",
"TableFactor",
"f2",
")",
"{",
"for",
"(",
"int",
"n1",
":",
"f1",
".",
"neighborIndices",
")",
"{",
"for",
"(",
"int",
"n2",
":",
"f2",
".",
"neighborIndices",
")",
"{",
"if",
"(",
"n1",
"==",
"n2",
")",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Just a quick inline to check if two factors have overlapping domains. Since factor neighbor sets are super small,
this n^2 algorithm is fine.
@param f1 first factor to compare
@param f2 second factor to compare
@return whether their domains overlap
|
[
"Just",
"a",
"quick",
"inline",
"to",
"check",
"if",
"two",
"factors",
"have",
"overlapping",
"domains",
".",
"Since",
"factor",
"neighbor",
"sets",
"are",
"super",
"small",
"this",
"n^2",
"algorithm",
"is",
"fine",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/CliqueTree.java#L919-L926
|
145,329
|
akberc/ceylon-maven-plugin
|
src/main/java/com/dgwave/car/repo/CeylonRepoLayout.java
|
CeylonRepoLayout.getPath
|
public URI getPath(final org.eclipse.aether.artifact.Artifact artifact) {
return toUri(pathOf(new DefaultArtifact(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getBaseVersion(),
"", artifact.getExtension(),
artifact.getClassifier(), new DefaultArtifactHandler(artifact.getExtension()))));
}
|
java
|
public URI getPath(final org.eclipse.aether.artifact.Artifact artifact) {
return toUri(pathOf(new DefaultArtifact(artifact.getGroupId(),
artifact.getArtifactId(), artifact.getBaseVersion(),
"", artifact.getExtension(),
artifact.getClassifier(), new DefaultArtifactHandler(artifact.getExtension()))));
}
|
[
"public",
"URI",
"getPath",
"(",
"final",
"org",
".",
"eclipse",
".",
"aether",
".",
"artifact",
".",
"Artifact",
"artifact",
")",
"{",
"return",
"toUri",
"(",
"pathOf",
"(",
"new",
"DefaultArtifact",
"(",
"artifact",
".",
"getGroupId",
"(",
")",
",",
"artifact",
".",
"getArtifactId",
"(",
")",
",",
"artifact",
".",
"getBaseVersion",
"(",
")",
",",
"\"\"",
",",
"artifact",
".",
"getExtension",
"(",
")",
",",
"artifact",
".",
"getClassifier",
"(",
")",
",",
"new",
"DefaultArtifactHandler",
"(",
"artifact",
".",
"getExtension",
"(",
")",
")",
")",
")",
")",
";",
"}"
] |
The Aether implementation.
@param artifact The artifact to get the path for
@return URI of the artifact
@see org.eclipse.aether.util.repository.layout.RepositoryLayout#getPath(org.eclipse.aether.artifact.Artifact)
|
[
"The",
"Aether",
"implementation",
"."
] |
b7f6c4a2b24f2fa237350c9e715f4193e83415ef
|
https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/repo/CeylonRepoLayout.java#L62-L67
|
145,330
|
akberc/ceylon-maven-plugin
|
src/main/java/com/dgwave/car/repo/CeylonRepoLayout.java
|
CeylonRepoLayout.toUri
|
private URI toUri(final String path) {
try {
return new URI(null, null, path, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
|
java
|
private URI toUri(final String path) {
try {
return new URI(null, null, path, null);
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
}
|
[
"private",
"URI",
"toUri",
"(",
"final",
"String",
"path",
")",
"{",
"try",
"{",
"return",
"new",
"URI",
"(",
"null",
",",
"null",
",",
"path",
",",
"null",
")",
";",
"}",
"catch",
"(",
"URISyntaxException",
"e",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"e",
")",
";",
"}",
"}"
] |
Converts from String to URI.
@param path The string to convert
@return URI if there was no exception
|
[
"Converts",
"from",
"String",
"to",
"URI",
"."
] |
b7f6c4a2b24f2fa237350c9e715f4193e83415ef
|
https://github.com/akberc/ceylon-maven-plugin/blob/b7f6c4a2b24f2fa237350c9e715f4193e83415ef/src/main/java/com/dgwave/car/repo/CeylonRepoLayout.java#L84-L90
|
145,331
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgMethod.java
|
SgMethod.addBodyLine
|
public final void addBodyLine(final String line) {
if (line == null) {
throw new IllegalArgumentException("The argument 'line' cannot be NULL!");
}
body.add(line.trim());
}
|
java
|
public final void addBodyLine(final String line) {
if (line == null) {
throw new IllegalArgumentException("The argument 'line' cannot be NULL!");
}
body.add(line.trim());
}
|
[
"public",
"final",
"void",
"addBodyLine",
"(",
"final",
"String",
"line",
")",
"{",
"if",
"(",
"line",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'line' cannot be NULL!\"",
")",
";",
"}",
"body",
".",
"add",
"(",
"line",
".",
"trim",
"(",
")",
")",
";",
"}"
] |
Add a new line to the body.
@param line
Line to add - Cannot be null (but empty).
|
[
"Add",
"a",
"new",
"line",
"to",
"the",
"body",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgMethod.java#L96-L101
|
145,332
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgMethod.java
|
SgMethod.getSignature
|
public final String getSignature() {
final StringBuffer sb = new StringBuffer();
if (getModifiers().length() > 0) {
sb.append(getModifiers());
sb.append(" ");
}
sb.append(returnType.getName());
sb.append(" ");
sb.append(getName());
sb.append("(");
for (int i = 0; i < getArguments().size(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(getArguments().get(i));
}
sb.append(")");
if (getExceptions().size() > 0) {
sb.append(" throws ");
for (int i = 0; i < getExceptions().size(); i++) {
if (i > 0) {
sb.append(",");
}
sb.append(getExceptions().get(i).getName());
}
}
return sb.toString();
}
|
java
|
public final String getSignature() {
final StringBuffer sb = new StringBuffer();
if (getModifiers().length() > 0) {
sb.append(getModifiers());
sb.append(" ");
}
sb.append(returnType.getName());
sb.append(" ");
sb.append(getName());
sb.append("(");
for (int i = 0; i < getArguments().size(); i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(getArguments().get(i));
}
sb.append(")");
if (getExceptions().size() > 0) {
sb.append(" throws ");
for (int i = 0; i < getExceptions().size(); i++) {
if (i > 0) {
sb.append(",");
}
sb.append(getExceptions().get(i).getName());
}
}
return sb.toString();
}
|
[
"public",
"final",
"String",
"getSignature",
"(",
")",
"{",
"final",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"if",
"(",
"getModifiers",
"(",
")",
".",
"length",
"(",
")",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"getModifiers",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\" \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"returnType",
".",
"getName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\" \"",
")",
";",
"sb",
".",
"append",
"(",
"getName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"(\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getArguments",
"(",
")",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"getArguments",
"(",
")",
".",
"get",
"(",
"i",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\")\"",
")",
";",
"if",
"(",
"getExceptions",
"(",
")",
".",
"size",
"(",
")",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\" throws \"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getExceptions",
"(",
")",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\",\"",
")",
";",
"}",
"sb",
".",
"append",
"(",
"getExceptions",
"(",
")",
".",
"get",
"(",
"i",
")",
".",
"getName",
"(",
")",
")",
";",
"}",
"}",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns the "signature" of the method.
@return Modifiers, return type, name and arguments - Always non-null.
|
[
"Returns",
"the",
"signature",
"of",
"the",
"method",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgMethod.java#L127-L154
|
145,333
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgMethod.java
|
SgMethod.getCallSignature
|
public final String getCallSignature() {
final StringBuffer sb = new StringBuffer();
sb.append(getName());
sb.append("(");
for (int i = 0; i < getArguments().size(); i++) {
if (i > 0) {
sb.append(", ");
}
final SgArgument arg = getArguments().get(i);
sb.append(arg.getName());
}
sb.append(")");
return sb.toString();
}
|
java
|
public final String getCallSignature() {
final StringBuffer sb = new StringBuffer();
sb.append(getName());
sb.append("(");
for (int i = 0; i < getArguments().size(); i++) {
if (i > 0) {
sb.append(", ");
}
final SgArgument arg = getArguments().get(i);
sb.append(arg.getName());
}
sb.append(")");
return sb.toString();
}
|
[
"public",
"final",
"String",
"getCallSignature",
"(",
")",
"{",
"final",
"StringBuffer",
"sb",
"=",
"new",
"StringBuffer",
"(",
")",
";",
"sb",
".",
"append",
"(",
"getName",
"(",
")",
")",
";",
"sb",
".",
"append",
"(",
"\"(\"",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"getArguments",
"(",
")",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"if",
"(",
"i",
">",
"0",
")",
"{",
"sb",
".",
"append",
"(",
"\", \"",
")",
";",
"}",
"final",
"SgArgument",
"arg",
"=",
"getArguments",
"(",
")",
".",
"get",
"(",
"i",
")",
";",
"sb",
".",
"append",
"(",
"arg",
".",
"getName",
"(",
")",
")",
";",
"}",
"sb",
".",
"append",
"(",
"\")\"",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Returns the "call" signature of the method.
@return Method name and argument names (like "methodXY(a, b, c)").
|
[
"Returns",
"the",
"call",
"signature",
"of",
"the",
"method",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgMethod.java#L161-L174
|
145,334
|
chr78rm/tracelogger
|
src/main/java/de/christofreichardt/diagnosis/TracerConfigNamespaceContextImpl.java
|
TracerConfigNamespaceContextImpl.getNamespaceURI
|
@Override
public String getNamespaceURI(String prefix)
{
if (prefix == null || !prefix.equals("dns"))
throw new IllegalArgumentException("Accept only default namespace.");
return "http://www.christofreichardt.de/java/tracer";
}
|
java
|
@Override
public String getNamespaceURI(String prefix)
{
if (prefix == null || !prefix.equals("dns"))
throw new IllegalArgumentException("Accept only default namespace.");
return "http://www.christofreichardt.de/java/tracer";
}
|
[
"@",
"Override",
"public",
"String",
"getNamespaceURI",
"(",
"String",
"prefix",
")",
"{",
"if",
"(",
"prefix",
"==",
"null",
"||",
"!",
"prefix",
".",
"equals",
"(",
"\"dns\"",
")",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Accept only default namespace.\"",
")",
";",
"return",
"\"http://www.christofreichardt.de/java/tracer\"",
";",
"}"
] |
Returns the fixed namespace URI for the prefix "dns". Other prefixes will cause an IllegalArgumentException.
@param prefix the namespace prefix
@return the URI "http://www.christofreichardt.de/java/tracer"
|
[
"Returns",
"the",
"fixed",
"namespace",
"URI",
"for",
"the",
"prefix",
"dns",
".",
"Other",
"prefixes",
"will",
"cause",
"an",
"IllegalArgumentException",
"."
] |
ad22452b20f8111ad4d367302c2b26a100a20200
|
https://github.com/chr78rm/tracelogger/blob/ad22452b20f8111ad4d367302c2b26a100a20200/src/main/java/de/christofreichardt/diagnosis/TracerConfigNamespaceContextImpl.java#L90-L97
|
145,335
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.get
|
public final String get(final String key) {
final Property prop = find(key);
if (prop == null) {
return null;
}
return prop.getValue();
}
|
java
|
public final String get(final String key) {
final Property prop = find(key);
if (prop == null) {
return null;
}
return prop.getValue();
}
|
[
"public",
"final",
"String",
"get",
"(",
"final",
"String",
"key",
")",
"{",
"final",
"Property",
"prop",
"=",
"find",
"(",
"key",
")",
";",
"if",
"(",
"prop",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"prop",
".",
"getValue",
"(",
")",
";",
"}"
] |
Returns a value for a given key.
@param key
Key to find.
@return Value or <code>null</code> if the key is unknown.
|
[
"Returns",
"a",
"value",
"for",
"a",
"given",
"key",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L331-L337
|
145,336
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.getStatus
|
public final String getStatus(final String key) {
final Property prop = find(key);
if (prop == null) {
return null;
}
return prop.getStatus();
}
|
java
|
public final String getStatus(final String key) {
final Property prop = find(key);
if (prop == null) {
return null;
}
return prop.getStatus();
}
|
[
"public",
"final",
"String",
"getStatus",
"(",
"final",
"String",
"key",
")",
"{",
"final",
"Property",
"prop",
"=",
"find",
"(",
"key",
")",
";",
"if",
"(",
"prop",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"prop",
".",
"getStatus",
"(",
")",
";",
"}"
] |
Returns a status text for a given key.
@param key
Key to find.
@return Status text or <code>null</code> if the key is unknown.
|
[
"Returns",
"a",
"status",
"text",
"for",
"a",
"given",
"key",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L347-L353
|
145,337
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.put
|
public final void put(final String key, final String value) {
final Property prop = find(key);
if (prop == null) {
props.add(new Property(key, null, value));
} else {
prop.setValue(value);
}
}
|
java
|
public final void put(final String key, final String value) {
final Property prop = find(key);
if (prop == null) {
props.add(new Property(key, null, value));
} else {
prop.setValue(value);
}
}
|
[
"public",
"final",
"void",
"put",
"(",
"final",
"String",
"key",
",",
"final",
"String",
"value",
")",
"{",
"final",
"Property",
"prop",
"=",
"find",
"(",
"key",
")",
";",
"if",
"(",
"prop",
"==",
"null",
")",
"{",
"props",
".",
"add",
"(",
"new",
"Property",
"(",
"key",
",",
"null",
",",
"value",
")",
")",
";",
"}",
"else",
"{",
"prop",
".",
"setValue",
"(",
"value",
")",
";",
"}",
"}"
] |
Set a value for a property. If a property with the key is already known the value will be changed. Otherwise a new property will be
created.
@param key
Key to set.
@param value
Value to set.
|
[
"Set",
"a",
"value",
"for",
"a",
"property",
".",
"If",
"a",
"property",
"with",
"the",
"key",
"is",
"already",
"known",
"the",
"value",
"will",
"be",
"changed",
".",
"Otherwise",
"a",
"new",
"property",
"will",
"be",
"created",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L364-L371
|
145,338
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.isRemoved
|
public final boolean isRemoved(final String key) {
final Property prop = find(key);
if (prop == null) {
return true;
}
return prop.isDeleted();
}
|
java
|
public final boolean isRemoved(final String key) {
final Property prop = find(key);
if (prop == null) {
return true;
}
return prop.isDeleted();
}
|
[
"public",
"final",
"boolean",
"isRemoved",
"(",
"final",
"String",
"key",
")",
"{",
"final",
"Property",
"prop",
"=",
"find",
"(",
"key",
")",
";",
"if",
"(",
"prop",
"==",
"null",
")",
"{",
"return",
"true",
";",
"}",
"return",
"prop",
".",
"isDeleted",
"(",
")",
";",
"}"
] |
Returns if a property has been deleted.
@param key
Key for the property to check.
@return If the property is unknown or has been deleted <code>true</code> else <code>false</code>.
|
[
"Returns",
"if",
"a",
"property",
"has",
"been",
"deleted",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L395-L401
|
145,339
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.getKeyList
|
public final List<String> getKeyList() {
final List<String> keys = new ArrayList<>();
final Iterator<String> it = keyIterator();
while (it.hasNext()) {
keys.add(it.next());
}
return keys;
}
|
java
|
public final List<String> getKeyList() {
final List<String> keys = new ArrayList<>();
final Iterator<String> it = keyIterator();
while (it.hasNext()) {
keys.add(it.next());
}
return keys;
}
|
[
"public",
"final",
"List",
"<",
"String",
">",
"getKeyList",
"(",
")",
"{",
"final",
"List",
"<",
"String",
">",
"keys",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"final",
"Iterator",
"<",
"String",
">",
"it",
"=",
"keyIterator",
"(",
")",
";",
"while",
"(",
"it",
".",
"hasNext",
"(",
")",
")",
"{",
"keys",
".",
"add",
"(",
"it",
".",
"next",
"(",
")",
")",
";",
"}",
"return",
"keys",
";",
"}"
] |
Returns a list of all known keys including the deleted ones.
@return List of keys.
|
[
"Returns",
"a",
"list",
"of",
"all",
"known",
"keys",
"including",
"the",
"deleted",
"ones",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L426-L433
|
145,340
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.keyIterator
|
public final Iterator<String> keyIterator() {
return new Iterator<String>() {
private final Iterator<Property> it = props.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public String next() {
final Property prop = it.next();
return prop.getKey();
}
@Override
public void remove() {
it.remove();
}
};
}
|
java
|
public final Iterator<String> keyIterator() {
return new Iterator<String>() {
private final Iterator<Property> it = props.iterator();
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public String next() {
final Property prop = it.next();
return prop.getKey();
}
@Override
public void remove() {
it.remove();
}
};
}
|
[
"public",
"final",
"Iterator",
"<",
"String",
">",
"keyIterator",
"(",
")",
"{",
"return",
"new",
"Iterator",
"<",
"String",
">",
"(",
")",
"{",
"private",
"final",
"Iterator",
"<",
"Property",
">",
"it",
"=",
"props",
".",
"iterator",
"(",
")",
";",
"@",
"Override",
"public",
"boolean",
"hasNext",
"(",
")",
"{",
"return",
"it",
".",
"hasNext",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"String",
"next",
"(",
")",
"{",
"final",
"Property",
"prop",
"=",
"it",
".",
"next",
"(",
")",
";",
"return",
"prop",
".",
"getKey",
"(",
")",
";",
"}",
"@",
"Override",
"public",
"void",
"remove",
"(",
")",
"{",
"it",
".",
"remove",
"(",
")",
";",
"}",
"}",
";",
"}"
] |
Returns a key iterator.
@return Iterates over all keys including the deleted ones.
|
[
"Returns",
"a",
"key",
"iterator",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L449-L469
|
145,341
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/PropertiesFile.java
|
PropertiesFile.toProperties
|
public final Properties toProperties() {
final Properties retVal = new Properties();
for (int i = 0; i < props.size(); i++) {
final Property prop = props.get(i);
if (!prop.isDeleted()) {
retVal.put(prop.getKey(), prop.getValue());
}
}
return retVal;
}
|
java
|
public final Properties toProperties() {
final Properties retVal = new Properties();
for (int i = 0; i < props.size(); i++) {
final Property prop = props.get(i);
if (!prop.isDeleted()) {
retVal.put(prop.getKey(), prop.getValue());
}
}
return retVal;
}
|
[
"public",
"final",
"Properties",
"toProperties",
"(",
")",
"{",
"final",
"Properties",
"retVal",
"=",
"new",
"Properties",
"(",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"props",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"final",
"Property",
"prop",
"=",
"props",
".",
"get",
"(",
"i",
")",
";",
"if",
"(",
"!",
"prop",
".",
"isDeleted",
"(",
")",
")",
"{",
"retVal",
".",
"put",
"(",
"prop",
".",
"getKey",
"(",
")",
",",
"prop",
".",
"getValue",
"(",
")",
")",
";",
"}",
"}",
"return",
"retVal",
";",
"}"
] |
Returns a copy of all properties.
@return All key/values without deleted ones.
|
[
"Returns",
"a",
"copy",
"of",
"all",
"properties",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/PropertiesFile.java#L476-L485
|
145,342
|
LevelFourAB/commons
|
commons-types/src/main/java/se/l4/commons/types/internal/ExtendedTypeBuilderImpl.java
|
ExtendedTypeBuilderImpl.resolveAndExtend
|
private static <CT, I> Function<CT, I> resolveAndExtend(
Class<CT> contextType,
List<MethodResolver<CT>> resolvers,
Class<I> typeToExtend)
{
// Resolve generics
ResolvedTypeWithMembers withMembers = Types.resolveMembers(typeToExtend);
Map<Method, MethodInvocationHandler<CT>> handlers = new HashMap<>();
try
{
// Go through methods and create invokers for each of them
for(ResolvedMethod method : withMembers.getMemberMethods())
{
// Only try to implement abstract methods
if(! method.isAbstract()) continue;
// Create an encounter and let the first method resolver that matches handle the method
boolean foundInvoker = false;
MethodEncounter encounter = new MethodEncounterImpl(method);
for(MethodResolver<CT> resolver : resolvers)
{
Optional<MethodInvocationHandler<CT>> opt = resolver.create(encounter);
if(opt.isPresent())
{
// This resolver created an invoker to use
foundInvoker = true;
handlers.put(method.getRawMember(), opt.get());
break;
}
}
if(! foundInvoker)
{
// No invoker was found, can not handle the method
throw new ProxyException("The method " + method.getName() + " could not be handled");
}
}
}
catch(ProxyException e)
{
throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage());
}
catch(Exception e)
{
throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage(), e);
}
return createFunction(contextType, typeToExtend, Collections.unmodifiableMap(handlers));
}
|
java
|
private static <CT, I> Function<CT, I> resolveAndExtend(
Class<CT> contextType,
List<MethodResolver<CT>> resolvers,
Class<I> typeToExtend)
{
// Resolve generics
ResolvedTypeWithMembers withMembers = Types.resolveMembers(typeToExtend);
Map<Method, MethodInvocationHandler<CT>> handlers = new HashMap<>();
try
{
// Go through methods and create invokers for each of them
for(ResolvedMethod method : withMembers.getMemberMethods())
{
// Only try to implement abstract methods
if(! method.isAbstract()) continue;
// Create an encounter and let the first method resolver that matches handle the method
boolean foundInvoker = false;
MethodEncounter encounter = new MethodEncounterImpl(method);
for(MethodResolver<CT> resolver : resolvers)
{
Optional<MethodInvocationHandler<CT>> opt = resolver.create(encounter);
if(opt.isPresent())
{
// This resolver created an invoker to use
foundInvoker = true;
handlers.put(method.getRawMember(), opt.get());
break;
}
}
if(! foundInvoker)
{
// No invoker was found, can not handle the method
throw new ProxyException("The method " + method.getName() + " could not be handled");
}
}
}
catch(ProxyException e)
{
throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage());
}
catch(Exception e)
{
throw new ProxyException(typeToExtend.getName() + ":\n" + e.getMessage(), e);
}
return createFunction(contextType, typeToExtend, Collections.unmodifiableMap(handlers));
}
|
[
"private",
"static",
"<",
"CT",
",",
"I",
">",
"Function",
"<",
"CT",
",",
"I",
">",
"resolveAndExtend",
"(",
"Class",
"<",
"CT",
">",
"contextType",
",",
"List",
"<",
"MethodResolver",
"<",
"CT",
">",
">",
"resolvers",
",",
"Class",
"<",
"I",
">",
"typeToExtend",
")",
"{",
"// Resolve generics",
"ResolvedTypeWithMembers",
"withMembers",
"=",
"Types",
".",
"resolveMembers",
"(",
"typeToExtend",
")",
";",
"Map",
"<",
"Method",
",",
"MethodInvocationHandler",
"<",
"CT",
">",
">",
"handlers",
"=",
"new",
"HashMap",
"<>",
"(",
")",
";",
"try",
"{",
"// Go through methods and create invokers for each of them",
"for",
"(",
"ResolvedMethod",
"method",
":",
"withMembers",
".",
"getMemberMethods",
"(",
")",
")",
"{",
"// Only try to implement abstract methods",
"if",
"(",
"!",
"method",
".",
"isAbstract",
"(",
")",
")",
"continue",
";",
"// Create an encounter and let the first method resolver that matches handle the method",
"boolean",
"foundInvoker",
"=",
"false",
";",
"MethodEncounter",
"encounter",
"=",
"new",
"MethodEncounterImpl",
"(",
"method",
")",
";",
"for",
"(",
"MethodResolver",
"<",
"CT",
">",
"resolver",
":",
"resolvers",
")",
"{",
"Optional",
"<",
"MethodInvocationHandler",
"<",
"CT",
">>",
"opt",
"=",
"resolver",
".",
"create",
"(",
"encounter",
")",
";",
"if",
"(",
"opt",
".",
"isPresent",
"(",
")",
")",
"{",
"// This resolver created an invoker to use",
"foundInvoker",
"=",
"true",
";",
"handlers",
".",
"put",
"(",
"method",
".",
"getRawMember",
"(",
")",
",",
"opt",
".",
"get",
"(",
")",
")",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"foundInvoker",
")",
"{",
"// No invoker was found, can not handle the method",
"throw",
"new",
"ProxyException",
"(",
"\"The method \"",
"+",
"method",
".",
"getName",
"(",
")",
"+",
"\" could not be handled\"",
")",
";",
"}",
"}",
"}",
"catch",
"(",
"ProxyException",
"e",
")",
"{",
"throw",
"new",
"ProxyException",
"(",
"typeToExtend",
".",
"getName",
"(",
")",
"+",
"\":\\n\"",
"+",
"e",
".",
"getMessage",
"(",
")",
")",
";",
"}",
"catch",
"(",
"Exception",
"e",
")",
"{",
"throw",
"new",
"ProxyException",
"(",
"typeToExtend",
".",
"getName",
"(",
")",
"+",
"\":\\n\"",
"+",
"e",
".",
"getMessage",
"(",
")",
",",
"e",
")",
";",
"}",
"return",
"createFunction",
"(",
"contextType",
",",
"typeToExtend",
",",
"Collections",
".",
"unmodifiableMap",
"(",
"handlers",
")",
")",
";",
"}"
] |
Internal helper that resolves all the invokers using the given resolvers.
@param contextType
the type of context the invokers use
@param resolvers
list of resolvers
@param typeToExtend
interface or abstract class to extend
|
[
"Internal",
"helper",
"that",
"resolves",
"all",
"the",
"invokers",
"using",
"the",
"given",
"resolvers",
"."
] |
aa121b3a5504b43d0c10450a1b984694fcd2b8ee
|
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-types/src/main/java/se/l4/commons/types/internal/ExtendedTypeBuilderImpl.java#L85-L134
|
145,343
|
LevelFourAB/commons
|
commons-types/src/main/java/se/l4/commons/types/internal/ExtendedTypeBuilderImpl.java
|
ExtendedTypeBuilderImpl.createFunction
|
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <CT, I> Function<CT, I> createFunction(
Class<CT> contextType,
Class<I> typeToExtend,
Map<Method, MethodInvocationHandler<CT>> invokers
)
{
try
{
DynamicType.Builder builder = new ByteBuddy()
.subclass(typeToExtend);
// Add the context field
builder = builder.defineField("context", contextType, Visibility.PRIVATE);
// Add the constructor
builder = builder.defineConstructor(Visibility.PUBLIC)
.withParameter(contextType)
.intercept(
MethodCall.invoke(Object.class.getDeclaredConstructor())
.onSuper()
.andThen(FieldAccessor.ofField("context").setsArgumentAt(0))
);
// TODO: The constructor needs to support abstract base classes and injection via InstanceFactory
for(Map.Entry<Method, MethodInvocationHandler<CT>> e : invokers.entrySet())
{
builder = builder.define(e.getKey())
.intercept(
MethodDelegation.to(new Runner(e.getValue()))
);
}
Class createdClass = builder.make()
.load(typeToExtend.getClassLoader())
.getLoaded();
return createFactory(createdClass, contextType);
}
catch(Throwable e)
{
if(e instanceof ProxyException) throw (ProxyException) e;
throw new ProxyException(e);
}
}
|
java
|
@SuppressWarnings({ "unchecked", "rawtypes" })
private static <CT, I> Function<CT, I> createFunction(
Class<CT> contextType,
Class<I> typeToExtend,
Map<Method, MethodInvocationHandler<CT>> invokers
)
{
try
{
DynamicType.Builder builder = new ByteBuddy()
.subclass(typeToExtend);
// Add the context field
builder = builder.defineField("context", contextType, Visibility.PRIVATE);
// Add the constructor
builder = builder.defineConstructor(Visibility.PUBLIC)
.withParameter(contextType)
.intercept(
MethodCall.invoke(Object.class.getDeclaredConstructor())
.onSuper()
.andThen(FieldAccessor.ofField("context").setsArgumentAt(0))
);
// TODO: The constructor needs to support abstract base classes and injection via InstanceFactory
for(Map.Entry<Method, MethodInvocationHandler<CT>> e : invokers.entrySet())
{
builder = builder.define(e.getKey())
.intercept(
MethodDelegation.to(new Runner(e.getValue()))
);
}
Class createdClass = builder.make()
.load(typeToExtend.getClassLoader())
.getLoaded();
return createFactory(createdClass, contextType);
}
catch(Throwable e)
{
if(e instanceof ProxyException) throw (ProxyException) e;
throw new ProxyException(e);
}
}
|
[
"@",
"SuppressWarnings",
"(",
"{",
"\"unchecked\"",
",",
"\"rawtypes\"",
"}",
")",
"private",
"static",
"<",
"CT",
",",
"I",
">",
"Function",
"<",
"CT",
",",
"I",
">",
"createFunction",
"(",
"Class",
"<",
"CT",
">",
"contextType",
",",
"Class",
"<",
"I",
">",
"typeToExtend",
",",
"Map",
"<",
"Method",
",",
"MethodInvocationHandler",
"<",
"CT",
">",
">",
"invokers",
")",
"{",
"try",
"{",
"DynamicType",
".",
"Builder",
"builder",
"=",
"new",
"ByteBuddy",
"(",
")",
".",
"subclass",
"(",
"typeToExtend",
")",
";",
"// Add the context field",
"builder",
"=",
"builder",
".",
"defineField",
"(",
"\"context\"",
",",
"contextType",
",",
"Visibility",
".",
"PRIVATE",
")",
";",
"// Add the constructor",
"builder",
"=",
"builder",
".",
"defineConstructor",
"(",
"Visibility",
".",
"PUBLIC",
")",
".",
"withParameter",
"(",
"contextType",
")",
".",
"intercept",
"(",
"MethodCall",
".",
"invoke",
"(",
"Object",
".",
"class",
".",
"getDeclaredConstructor",
"(",
")",
")",
".",
"onSuper",
"(",
")",
".",
"andThen",
"(",
"FieldAccessor",
".",
"ofField",
"(",
"\"context\"",
")",
".",
"setsArgumentAt",
"(",
"0",
")",
")",
")",
";",
"// TODO: The constructor needs to support abstract base classes and injection via InstanceFactory",
"for",
"(",
"Map",
".",
"Entry",
"<",
"Method",
",",
"MethodInvocationHandler",
"<",
"CT",
">",
">",
"e",
":",
"invokers",
".",
"entrySet",
"(",
")",
")",
"{",
"builder",
"=",
"builder",
".",
"define",
"(",
"e",
".",
"getKey",
"(",
")",
")",
".",
"intercept",
"(",
"MethodDelegation",
".",
"to",
"(",
"new",
"Runner",
"(",
"e",
".",
"getValue",
"(",
")",
")",
")",
")",
";",
"}",
"Class",
"createdClass",
"=",
"builder",
".",
"make",
"(",
")",
".",
"load",
"(",
"typeToExtend",
".",
"getClassLoader",
"(",
")",
")",
".",
"getLoaded",
"(",
")",
";",
"return",
"createFactory",
"(",
"createdClass",
",",
"contextType",
")",
";",
"}",
"catch",
"(",
"Throwable",
"e",
")",
"{",
"if",
"(",
"e",
"instanceof",
"ProxyException",
")",
"throw",
"(",
"ProxyException",
")",
"e",
";",
"throw",
"new",
"ProxyException",
"(",
"e",
")",
";",
"}",
"}"
] |
Create the actual function that creates instances.
@param contextType
the context type being used
@param typeToExtend
the type being extended
@param invokers
the resolved invokers
|
[
"Create",
"the",
"actual",
"function",
"that",
"creates",
"instances",
"."
] |
aa121b3a5504b43d0c10450a1b984694fcd2b8ee
|
https://github.com/LevelFourAB/commons/blob/aa121b3a5504b43d0c10450a1b984694fcd2b8ee/commons-types/src/main/java/se/l4/commons/types/internal/ExtendedTypeBuilderImpl.java#L146-L191
|
145,344
|
fnklabs/draenei
|
src/main/java/com/fnklabs/draenei/orm/DataProvider.java
|
DataProvider.find
|
public List<V> find(Object... keys) {
Timer timer = getMetrics().getTimer(MetricsType.DATA_PROVIDER_FIND.name());
List<Object> parameters = new ArrayList<>();
Collections.addAll(parameters, keys);
List<V> resultFuture = fetch(parameters);
timer.stop();
return resultFuture;
}
|
java
|
public List<V> find(Object... keys) {
Timer timer = getMetrics().getTimer(MetricsType.DATA_PROVIDER_FIND.name());
List<Object> parameters = new ArrayList<>();
Collections.addAll(parameters, keys);
List<V> resultFuture = fetch(parameters);
timer.stop();
return resultFuture;
}
|
[
"public",
"List",
"<",
"V",
">",
"find",
"(",
"Object",
"...",
"keys",
")",
"{",
"Timer",
"timer",
"=",
"getMetrics",
"(",
")",
".",
"getTimer",
"(",
"MetricsType",
".",
"DATA_PROVIDER_FIND",
".",
"name",
"(",
")",
")",
";",
"List",
"<",
"Object",
">",
"parameters",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Collections",
".",
"addAll",
"(",
"parameters",
",",
"keys",
")",
";",
"List",
"<",
"V",
">",
"resultFuture",
"=",
"fetch",
"(",
"parameters",
")",
";",
"timer",
".",
"stop",
"(",
")",
";",
"return",
"resultFuture",
";",
"}"
] |
Get records by specified keys and send result to consumer
@param keys Primary keys
@return True if result will be completed successfully and False if result will be completed with error
|
[
"Get",
"records",
"by",
"specified",
"keys",
"and",
"send",
"result",
"to",
"consumer"
] |
0a8cac54f1f635be3e2950375a23291d38453ae8
|
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/DataProvider.java#L274-L286
|
145,345
|
fnklabs/draenei
|
src/main/java/com/fnklabs/draenei/orm/DataProvider.java
|
DataProvider.monitorFuture
|
private <Input, Output> ListenableFuture<Output> monitorFuture(Timer timer, ListenableFuture<Input> listenableFuture, Function<Input, Output> userCallback) {
Futures.addCallback(listenableFuture, new FutureTimerCallback<>(timer));
return Futures.transform(listenableFuture, new JdkFunctionWrapper<>(userCallback));
}
|
java
|
private <Input, Output> ListenableFuture<Output> monitorFuture(Timer timer, ListenableFuture<Input> listenableFuture, Function<Input, Output> userCallback) {
Futures.addCallback(listenableFuture, new FutureTimerCallback<>(timer));
return Futures.transform(listenableFuture, new JdkFunctionWrapper<>(userCallback));
}
|
[
"private",
"<",
"Input",
",",
"Output",
">",
"ListenableFuture",
"<",
"Output",
">",
"monitorFuture",
"(",
"Timer",
"timer",
",",
"ListenableFuture",
"<",
"Input",
">",
"listenableFuture",
",",
"Function",
"<",
"Input",
",",
"Output",
">",
"userCallback",
")",
"{",
"Futures",
".",
"addCallback",
"(",
"listenableFuture",
",",
"new",
"FutureTimerCallback",
"<>",
"(",
"timer",
")",
")",
";",
"return",
"Futures",
".",
"transform",
"(",
"listenableFuture",
",",
"new",
"JdkFunctionWrapper",
"<>",
"(",
"userCallback",
")",
")",
";",
"}"
] |
Monitor future completion
@param timer Timer that will be close on Future success or failure
@param listenableFuture Listenable future
@param userCallback User callback that will be executed on Future success
@param <Input> Future class type
@param <Output> User callback output
@return Listenable future
|
[
"Monitor",
"future",
"completion"
] |
0a8cac54f1f635be3e2950375a23291d38453ae8
|
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/DataProvider.java#L385-L389
|
145,346
|
fnklabs/draenei
|
src/main/java/com/fnklabs/draenei/orm/DataProvider.java
|
DataProvider.build
|
private EntityMetadata build(Class<V> clazz) throws MetadataException {
return EntityMetadata.buildEntityMetadata(clazz, getCassandraClient());
}
|
java
|
private EntityMetadata build(Class<V> clazz) throws MetadataException {
return EntityMetadata.buildEntityMetadata(clazz, getCassandraClient());
}
|
[
"private",
"EntityMetadata",
"build",
"(",
"Class",
"<",
"V",
">",
"clazz",
")",
"throws",
"MetadataException",
"{",
"return",
"EntityMetadata",
".",
"buildEntityMetadata",
"(",
"clazz",
",",
"getCassandraClient",
"(",
")",
")",
";",
"}"
] |
Build entity metadata from entity class
@param clazz Entity class
@return EntityMetadata
@throws MetadataException
|
[
"Build",
"entity",
"metadata",
"from",
"entity",
"class"
] |
0a8cac54f1f635be3e2950375a23291d38453ae8
|
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/DataProvider.java#L594-L596
|
145,347
|
fnklabs/draenei
|
src/main/java/com/fnklabs/draenei/orm/DataProvider.java
|
DataProvider.buildHashCode
|
final long buildHashCode(Object... keys) {
ArrayList<Object> keyList = new ArrayList<>();
Collections.addAll(keyList, keys);
return buildHashCode(keyList);
}
|
java
|
final long buildHashCode(Object... keys) {
ArrayList<Object> keyList = new ArrayList<>();
Collections.addAll(keyList, keys);
return buildHashCode(keyList);
}
|
[
"final",
"long",
"buildHashCode",
"(",
"Object",
"...",
"keys",
")",
"{",
"ArrayList",
"<",
"Object",
">",
"keyList",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"Collections",
".",
"addAll",
"(",
"keyList",
",",
"keys",
")",
";",
"return",
"buildHashCode",
"(",
"keyList",
")",
";",
"}"
] |
Build cache key
@param keys Entity keys
@return Cache key
|
[
"Build",
"cache",
"key"
] |
0a8cac54f1f635be3e2950375a23291d38453ae8
|
https://github.com/fnklabs/draenei/blob/0a8cac54f1f635be3e2950375a23291d38453ae8/src/main/java/com/fnklabs/draenei/orm/DataProvider.java#L673-L679
|
145,348
|
dbracewell/mango
|
src/main/java/com/davidbracewell/conversion/Cast.java
|
Cast.as
|
@SuppressWarnings("unchecked")
public static <T> T as(Object o) {
return o == null ? null : (T) o;
}
|
java
|
@SuppressWarnings("unchecked")
public static <T> T as(Object o) {
return o == null ? null : (T) o;
}
|
[
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"T",
">",
"T",
"as",
"(",
"Object",
"o",
")",
"{",
"return",
"o",
"==",
"null",
"?",
"null",
":",
"(",
"T",
")",
"o",
";",
"}"
] |
Casts an object in an unchecked manner.
@param <T> the type parameter
@param o the object
@return the casted object or null if the object was null
|
[
"Casts",
"an",
"object",
"in",
"an",
"unchecked",
"manner",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/conversion/Cast.java#L51-L54
|
145,349
|
fuinorg/srcgen4javassist
|
src/main/java/org/fuin/srcgen4javassist/SgAnnotation.java
|
SgAnnotation.addArgument
|
public final void addArgument(final String name, final Object value) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
if (value == null) {
throw new IllegalArgumentException("The argument 'value' cannot be null!");
}
arguments.put(name.trim(), value);
}
|
java
|
public final void addArgument(final String name, final Object value) {
if (name == null) {
throw new IllegalArgumentException("The argument 'name' cannot be null!");
}
if (value == null) {
throw new IllegalArgumentException("The argument 'value' cannot be null!");
}
arguments.put(name.trim(), value);
}
|
[
"public",
"final",
"void",
"addArgument",
"(",
"final",
"String",
"name",
",",
"final",
"Object",
"value",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'name' cannot be null!\"",
")",
";",
"}",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'value' cannot be null!\"",
")",
";",
"}",
"arguments",
".",
"put",
"(",
"name",
".",
"trim",
"(",
")",
",",
"value",
")",
";",
"}"
] |
Adds an argument.
@param name
Name of the argument - Cannot be null.
@param value
Value of the argument - Cannot be null.
|
[
"Adds",
"an",
"argument",
"."
] |
355828113cfce3cdd3d69ba242c5bdfc7d899f2f
|
https://github.com/fuinorg/srcgen4javassist/blob/355828113cfce3cdd3d69ba242c5bdfc7d899f2f/src/main/java/org/fuin/srcgen4javassist/SgAnnotation.java#L114-L122
|
145,350
|
dbracewell/mango
|
src/main/java/com/davidbracewell/reflection/BeanDescriptor.java
|
BeanDescriptor.createInstanceQuietly
|
public Object createInstanceQuietly() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
log.finest(e);
return null;
} catch (IllegalAccessException e) {
log.finest(e);
return null;
}
}
|
java
|
public Object createInstanceQuietly() {
try {
return clazz.newInstance();
} catch (InstantiationException e) {
log.finest(e);
return null;
} catch (IllegalAccessException e) {
log.finest(e);
return null;
}
}
|
[
"public",
"Object",
"createInstanceQuietly",
"(",
")",
"{",
"try",
"{",
"return",
"clazz",
".",
"newInstance",
"(",
")",
";",
"}",
"catch",
"(",
"InstantiationException",
"e",
")",
"{",
"log",
".",
"finest",
"(",
"e",
")",
";",
"return",
"null",
";",
"}",
"catch",
"(",
"IllegalAccessException",
"e",
")",
"{",
"log",
".",
"finest",
"(",
"e",
")",
";",
"return",
"null",
";",
"}",
"}"
] |
Constructs an instance of the wrapped class ignoring any errors.
@return An instance of the class or <code>null</code> if something went wrong.
|
[
"Constructs",
"an",
"instance",
"of",
"the",
"wrapped",
"class",
"ignoring",
"any",
"errors",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/reflection/BeanDescriptor.java#L203-L213
|
145,351
|
dbracewell/mango
|
src/main/java/com/davidbracewell/collection/Span.java
|
Span.overlaps
|
public boolean overlaps(Span other) {
return other != null && this.start() < other.end() && this.end() > other.start();
}
|
java
|
public boolean overlaps(Span other) {
return other != null && this.start() < other.end() && this.end() > other.start();
}
|
[
"public",
"boolean",
"overlaps",
"(",
"Span",
"other",
")",
"{",
"return",
"other",
"!=",
"null",
"&&",
"this",
".",
"start",
"(",
")",
"<",
"other",
".",
"end",
"(",
")",
"&&",
"this",
".",
"end",
"(",
")",
">",
"other",
".",
"start",
"(",
")",
";",
"}"
] |
Returns true if the bounds of other text are connected with the bounds of this text.
@param other The other text to check if this one overlaps
@return True if the two texts are in the same document and overlap, False otherwise
|
[
"Returns",
"true",
"if",
"the",
"bounds",
"of",
"other",
"text",
"are",
"connected",
"with",
"the",
"bounds",
"of",
"this",
"text",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/collection/Span.java#L72-L74
|
145,352
|
dbracewell/mango
|
src/main/java/com/davidbracewell/collection/Span.java
|
Span.encloses
|
public boolean encloses(Span other) {
return other != null && other.start() >= this.start() && other.end() < this.end();
}
|
java
|
public boolean encloses(Span other) {
return other != null && other.start() >= this.start() && other.end() < this.end();
}
|
[
"public",
"boolean",
"encloses",
"(",
"Span",
"other",
")",
"{",
"return",
"other",
"!=",
"null",
"&&",
"other",
".",
"start",
"(",
")",
">=",
"this",
".",
"start",
"(",
")",
"&&",
"other",
".",
"end",
"(",
")",
"<",
"this",
".",
"end",
"(",
")",
";",
"}"
] |
Returns true if the bounds of the other text do not extend outside the bounds of this text.
@param other The other text to check if this one encloses
@return True if the two texts are in the same document and this text encloses the other, False otherwise
|
[
"Returns",
"true",
"if",
"the",
"bounds",
"of",
"the",
"other",
"text",
"do",
"not",
"extend",
"outside",
"the",
"bounds",
"of",
"this",
"text",
"."
] |
2cec08826f1fccd658694dd03abce10fc97618ec
|
https://github.com/dbracewell/mango/blob/2cec08826f1fccd658694dd03abce10fc97618ec/src/main/java/com/davidbracewell/collection/Span.java#L82-L84
|
145,353
|
devcon5io/common
|
cli/src/main/java/io/devcon5/cli/OptionCollector.java
|
OptionCollector.collectFrom
|
public Options collectFrom(Class type) {
final Options opts = new Options();
collectOptions(type, opts);
return opts;
}
|
java
|
public Options collectFrom(Class type) {
final Options opts = new Options();
collectOptions(type, opts);
return opts;
}
|
[
"public",
"Options",
"collectFrom",
"(",
"Class",
"type",
")",
"{",
"final",
"Options",
"opts",
"=",
"new",
"Options",
"(",
")",
";",
"collectOptions",
"(",
"type",
",",
"opts",
")",
";",
"return",
"opts",
";",
"}"
] |
Collects all Options for a given type. The collector traverses the type hierarchy and resolves Option groups.
@param type
the type to collect options from
@return
|
[
"Collects",
"all",
"Options",
"for",
"a",
"given",
"type",
".",
"The",
"collector",
"traverses",
"the",
"type",
"hierarchy",
"and",
"resolves",
"Option",
"groups",
"."
] |
363688e0dc904d559682bf796bd6c836b4e0efc7
|
https://github.com/devcon5io/common/blob/363688e0dc904d559682bf796bd6c836b4e0efc7/cli/src/main/java/io/devcon5/cli/OptionCollector.java#L43-L47
|
145,354
|
duraspace/fcrepo-cloudsync
|
fcrepo-cloudsync-service/src/main/java/org/duraspace/fcrepo/cloudsync/service/backend/FilesystemConnector.java
|
FilesystemConnector.decode
|
static String[] decode(String filename) {
int i = filename.indexOf("+");
if (i == -1) return new String[] { decodePart(filename), null, null };
int j = filename.lastIndexOf("+");
return new String[] { decodePart(filename.substring(0, i)),
decodePart(filename.substring(i + 1, j)),
decodePart(filename.substring(j + 1)) };
}
|
java
|
static String[] decode(String filename) {
int i = filename.indexOf("+");
if (i == -1) return new String[] { decodePart(filename), null, null };
int j = filename.lastIndexOf("+");
return new String[] { decodePart(filename.substring(0, i)),
decodePart(filename.substring(i + 1, j)),
decodePart(filename.substring(j + 1)) };
}
|
[
"static",
"String",
"[",
"]",
"decode",
"(",
"String",
"filename",
")",
"{",
"int",
"i",
"=",
"filename",
".",
"indexOf",
"(",
"\"+\"",
")",
";",
"if",
"(",
"i",
"==",
"-",
"1",
")",
"return",
"new",
"String",
"[",
"]",
"{",
"decodePart",
"(",
"filename",
")",
",",
"null",
",",
"null",
"}",
";",
"int",
"j",
"=",
"filename",
".",
"lastIndexOf",
"(",
"\"+\"",
")",
";",
"return",
"new",
"String",
"[",
"]",
"{",
"decodePart",
"(",
"filename",
".",
"substring",
"(",
"0",
",",
"i",
")",
")",
",",
"decodePart",
"(",
"filename",
".",
"substring",
"(",
"i",
"+",
"1",
",",
"j",
")",
")",
",",
"decodePart",
"(",
"filename",
".",
"substring",
"(",
"j",
"+",
"1",
")",
")",
"}",
";",
"}"
] |
reverses the encoding
|
[
"reverses",
"the",
"encoding"
] |
2d90e2c9c84a827f2605607ff40e116c67eff9b9
|
https://github.com/duraspace/fcrepo-cloudsync/blob/2d90e2c9c84a827f2605607ff40e116c67eff9b9/fcrepo-cloudsync-service/src/main/java/org/duraspace/fcrepo/cloudsync/service/backend/FilesystemConnector.java#L234-L241
|
145,355
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.sum
|
public static double sum (double[] vector) {
// Declare and initialize the accumulator:
double total = 0.0;
// Iterate over the vector:
for (int i = 0; i < vector.length; i++) {
total += vector[i];
}
// Done, return:
return total;
}
|
java
|
public static double sum (double[] vector) {
// Declare and initialize the accumulator:
double total = 0.0;
// Iterate over the vector:
for (int i = 0; i < vector.length; i++) {
total += vector[i];
}
// Done, return:
return total;
}
|
[
"public",
"static",
"double",
"sum",
"(",
"double",
"[",
"]",
"vector",
")",
"{",
"// Declare and initialize the accumulator:",
"double",
"total",
"=",
"0.0",
";",
"// Iterate over the vector:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"vector",
".",
"length",
";",
"i",
"++",
")",
"{",
"total",
"+=",
"vector",
"[",
"i",
"]",
";",
"}",
"// Done, return:",
"return",
"total",
";",
"}"
] |
Returns the sum of the vector.
@param vector The input vector as a double array
@return The sum of the vector
|
[
"Returns",
"the",
"sum",
"of",
"the",
"vector",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L44-L55
|
145,356
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.sumOfAbsolutes
|
public static double sumOfAbsolutes (double[] vector) {
// Declare and initialize the accumulator:
double total = 0.0;
// Iterate over the vector:
for (int i = 0; i < vector.length; i++) {
total += Math.abs(vector[i]);
}
// Done, return:
return total;
}
|
java
|
public static double sumOfAbsolutes (double[] vector) {
// Declare and initialize the accumulator:
double total = 0.0;
// Iterate over the vector:
for (int i = 0; i < vector.length; i++) {
total += Math.abs(vector[i]);
}
// Done, return:
return total;
}
|
[
"public",
"static",
"double",
"sumOfAbsolutes",
"(",
"double",
"[",
"]",
"vector",
")",
"{",
"// Declare and initialize the accumulator:",
"double",
"total",
"=",
"0.0",
";",
"// Iterate over the vector:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"vector",
".",
"length",
";",
"i",
"++",
")",
"{",
"total",
"+=",
"Math",
".",
"abs",
"(",
"vector",
"[",
"i",
"]",
")",
";",
"}",
"// Done, return:",
"return",
"total",
";",
"}"
] |
Returns the sum of the absolute values in the vector.
@param vector The input vector as a double array
@return The sum of the absolute values in the vector
|
[
"Returns",
"the",
"sum",
"of",
"the",
"absolute",
"values",
"in",
"the",
"vector",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L63-L74
|
145,357
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.median
|
public static double median (double[] vector) {
final double[] sorted = vector.clone();
Arrays.sort(sorted);
if (vector.length % 2 == 1) {
return sorted[vector.length / 2];
}
return (sorted[vector.length / 2 - 1] + sorted[vector.length / 2]) / 2;
}
|
java
|
public static double median (double[] vector) {
final double[] sorted = vector.clone();
Arrays.sort(sorted);
if (vector.length % 2 == 1) {
return sorted[vector.length / 2];
}
return (sorted[vector.length / 2 - 1] + sorted[vector.length / 2]) / 2;
}
|
[
"public",
"static",
"double",
"median",
"(",
"double",
"[",
"]",
"vector",
")",
"{",
"final",
"double",
"[",
"]",
"sorted",
"=",
"vector",
".",
"clone",
"(",
")",
";",
"Arrays",
".",
"sort",
"(",
"sorted",
")",
";",
"if",
"(",
"vector",
".",
"length",
"%",
"2",
"==",
"1",
")",
"{",
"return",
"sorted",
"[",
"vector",
".",
"length",
"/",
"2",
"]",
";",
"}",
"return",
"(",
"sorted",
"[",
"vector",
".",
"length",
"/",
"2",
"-",
"1",
"]",
"+",
"sorted",
"[",
"vector",
".",
"length",
"/",
"2",
"]",
")",
"/",
"2",
";",
"}"
] |
Returns the median of the vector.
@param vector The input vector as a double array
@return The median of the vector
|
[
"Returns",
"the",
"median",
"of",
"the",
"vector",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L92-L99
|
145,358
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.sequence
|
public static double[] sequence (double start, double end, int length) {
// Declare and initialize the return value:
double[] retval = new double[length];
// Calculate step:
double step = (end - start) / (length == 1 ? 1 : length - 1);
// Iterate and fill:
for (int i = 0; i < length; i++) {
retval[i] = start + (i * step);
}
// Done, return;
return retval;
}
|
java
|
public static double[] sequence (double start, double end, int length) {
// Declare and initialize the return value:
double[] retval = new double[length];
// Calculate step:
double step = (end - start) / (length == 1 ? 1 : length - 1);
// Iterate and fill:
for (int i = 0; i < length; i++) {
retval[i] = start + (i * step);
}
// Done, return;
return retval;
}
|
[
"public",
"static",
"double",
"[",
"]",
"sequence",
"(",
"double",
"start",
",",
"double",
"end",
",",
"int",
"length",
")",
"{",
"// Declare and initialize the return value:",
"double",
"[",
"]",
"retval",
"=",
"new",
"double",
"[",
"length",
"]",
";",
"// Calculate step:",
"double",
"step",
"=",
"(",
"end",
"-",
"start",
")",
"/",
"(",
"length",
"==",
"1",
"?",
"1",
":",
"length",
"-",
"1",
")",
";",
"// Iterate and fill:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"start",
"+",
"(",
"i",
"*",
"step",
")",
";",
"}",
"// Done, return;",
"return",
"retval",
";",
"}"
] |
Generates a sequence of specified length from specified start to specified end.
@param start The number to start with.
@param end The number to end with.
@param length The length of the desired sequence.
@return A sequence of length {@code length} starting with {@code start} and ending with {@code end}.
|
[
"Generates",
"a",
"sequence",
"of",
"specified",
"length",
"from",
"specified",
"start",
"to",
"specified",
"end",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L109-L123
|
145,359
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.getOrder
|
public static int[] getOrder(double[] values, boolean descending) {
return DMatrixUtils.getOrder(values, IntStream.range(0, values.length).toArray(), descending);
}
|
java
|
public static int[] getOrder(double[] values, boolean descending) {
return DMatrixUtils.getOrder(values, IntStream.range(0, values.length).toArray(), descending);
}
|
[
"public",
"static",
"int",
"[",
"]",
"getOrder",
"(",
"double",
"[",
"]",
"values",
",",
"boolean",
"descending",
")",
"{",
"return",
"DMatrixUtils",
".",
"getOrder",
"(",
"values",
",",
"IntStream",
".",
"range",
"(",
"0",
",",
"values",
".",
"length",
")",
".",
"toArray",
"(",
")",
",",
"descending",
")",
";",
"}"
] |
Get the order of the elements in descending or ascending order.
@param values A vector of double values.
@param descending Flag indicating if we go descending or not.
@return A vector of indices sorted in the provided order.
|
[
"Get",
"the",
"order",
"of",
"the",
"elements",
"in",
"descending",
"or",
"ascending",
"order",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L242-L244
|
145,360
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.getOrder
|
public static int[] getOrder(int[] values, int[] indices, boolean descending) {
// Create an index series:
Integer[] opIndices = ArrayUtils.toObject(indices);
// Sort indices:
Arrays.sort(opIndices, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (descending) {
return Double.compare(values[o2], values[o1]);
} else {
return Double.compare(values[o1], values[o2]);
}
}
});
return ArrayUtils.toPrimitive(opIndices);
}
|
java
|
public static int[] getOrder(int[] values, int[] indices, boolean descending) {
// Create an index series:
Integer[] opIndices = ArrayUtils.toObject(indices);
// Sort indices:
Arrays.sort(opIndices, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (descending) {
return Double.compare(values[o2], values[o1]);
} else {
return Double.compare(values[o1], values[o2]);
}
}
});
return ArrayUtils.toPrimitive(opIndices);
}
|
[
"public",
"static",
"int",
"[",
"]",
"getOrder",
"(",
"int",
"[",
"]",
"values",
",",
"int",
"[",
"]",
"indices",
",",
"boolean",
"descending",
")",
"{",
"// Create an index series:",
"Integer",
"[",
"]",
"opIndices",
"=",
"ArrayUtils",
".",
"toObject",
"(",
"indices",
")",
";",
"// Sort indices:",
"Arrays",
".",
"sort",
"(",
"opIndices",
",",
"new",
"Comparator",
"<",
"Integer",
">",
"(",
")",
"{",
"@",
"Override",
"public",
"int",
"compare",
"(",
"Integer",
"o1",
",",
"Integer",
"o2",
")",
"{",
"if",
"(",
"descending",
")",
"{",
"return",
"Double",
".",
"compare",
"(",
"values",
"[",
"o2",
"]",
",",
"values",
"[",
"o1",
"]",
")",
";",
"}",
"else",
"{",
"return",
"Double",
".",
"compare",
"(",
"values",
"[",
"o1",
"]",
",",
"values",
"[",
"o2",
"]",
")",
";",
"}",
"}",
"}",
")",
";",
"return",
"ArrayUtils",
".",
"toPrimitive",
"(",
"opIndices",
")",
";",
"}"
] |
Get the order of the specified elements in descending or ascending order.
@param values A vector of integer values.
@param indices The indices which will be considered for ordering.
@param descending Flag indicating if we go descending or not.
@return A vector of indices sorted in the provided order.
|
[
"Get",
"the",
"order",
"of",
"the",
"specified",
"elements",
"in",
"descending",
"or",
"ascending",
"order",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L264-L281
|
145,361
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.roundDownTo
|
public static BigDecimal roundDownTo(double value, double steps) {
final BigDecimal bValue = BigDecimal.valueOf(value);
final BigDecimal bSteps = BigDecimal.valueOf(steps);
if (Objects.equals(bSteps, BigDecimal.ZERO)) {
return bValue;
} else {
return bValue.divide(bSteps, 0, RoundingMode.FLOOR).multiply(bSteps);
}
}
|
java
|
public static BigDecimal roundDownTo(double value, double steps) {
final BigDecimal bValue = BigDecimal.valueOf(value);
final BigDecimal bSteps = BigDecimal.valueOf(steps);
if (Objects.equals(bSteps, BigDecimal.ZERO)) {
return bValue;
} else {
return bValue.divide(bSteps, 0, RoundingMode.FLOOR).multiply(bSteps);
}
}
|
[
"public",
"static",
"BigDecimal",
"roundDownTo",
"(",
"double",
"value",
",",
"double",
"steps",
")",
"{",
"final",
"BigDecimal",
"bValue",
"=",
"BigDecimal",
".",
"valueOf",
"(",
"value",
")",
";",
"final",
"BigDecimal",
"bSteps",
"=",
"BigDecimal",
".",
"valueOf",
"(",
"steps",
")",
";",
"if",
"(",
"Objects",
".",
"equals",
"(",
"bSteps",
",",
"BigDecimal",
".",
"ZERO",
")",
")",
"{",
"return",
"bValue",
";",
"}",
"else",
"{",
"return",
"bValue",
".",
"divide",
"(",
"bSteps",
",",
"0",
",",
"RoundingMode",
".",
"FLOOR",
")",
".",
"multiply",
"(",
"bSteps",
")",
";",
"}",
"}"
] |
Returns the DOWN rounded value of the given value for the given steps.
@param value The original value to be rounded.
@param steps The steps.
@return The DOWN rounded value of the given value for the given steps.
|
[
"Returns",
"the",
"DOWN",
"rounded",
"value",
"of",
"the",
"given",
"value",
"for",
"the",
"given",
"steps",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L311-L320
|
145,362
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.roundUpTo
|
public static BigDecimal roundUpTo(double value, double steps) {
final BigDecimal bValue = BigDecimal.valueOf(value);
final BigDecimal bSteps = BigDecimal.valueOf(steps);
if (Objects.equals(bSteps, BigDecimal.ZERO)) {
return bValue;
} else {
return bValue.divide(bSteps, 0, RoundingMode.CEILING).multiply(bSteps);
}
}
|
java
|
public static BigDecimal roundUpTo(double value, double steps) {
final BigDecimal bValue = BigDecimal.valueOf(value);
final BigDecimal bSteps = BigDecimal.valueOf(steps);
if (Objects.equals(bSteps, BigDecimal.ZERO)) {
return bValue;
} else {
return bValue.divide(bSteps, 0, RoundingMode.CEILING).multiply(bSteps);
}
}
|
[
"public",
"static",
"BigDecimal",
"roundUpTo",
"(",
"double",
"value",
",",
"double",
"steps",
")",
"{",
"final",
"BigDecimal",
"bValue",
"=",
"BigDecimal",
".",
"valueOf",
"(",
"value",
")",
";",
"final",
"BigDecimal",
"bSteps",
"=",
"BigDecimal",
".",
"valueOf",
"(",
"steps",
")",
";",
"if",
"(",
"Objects",
".",
"equals",
"(",
"bSteps",
",",
"BigDecimal",
".",
"ZERO",
")",
")",
"{",
"return",
"bValue",
";",
"}",
"else",
"{",
"return",
"bValue",
".",
"divide",
"(",
"bSteps",
",",
"0",
",",
"RoundingMode",
".",
"CEILING",
")",
".",
"multiply",
"(",
"bSteps",
")",
";",
"}",
"}"
] |
Returns the UP rounded value of the given value for the given steps.
@param value The original value to be rounded.
@param steps The steps.
@return The UP rounded value of the given value for the given steps.
|
[
"Returns",
"the",
"UP",
"rounded",
"value",
"of",
"the",
"given",
"value",
"for",
"the",
"given",
"steps",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L329-L338
|
145,363
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.roundToClosest
|
public static BigDecimal roundToClosest(double value, double steps) {
final BigDecimal down = DMatrixUtils.roundDownTo(value, steps);
final BigDecimal up = DMatrixUtils.roundUpTo(value, steps);
final BigDecimal orig = new BigDecimal(String.valueOf(value));
if (orig.subtract(down).abs().compareTo(orig.subtract(up).abs()) < 0) {
return down;
}
return up;
}
|
java
|
public static BigDecimal roundToClosest(double value, double steps) {
final BigDecimal down = DMatrixUtils.roundDownTo(value, steps);
final BigDecimal up = DMatrixUtils.roundUpTo(value, steps);
final BigDecimal orig = new BigDecimal(String.valueOf(value));
if (orig.subtract(down).abs().compareTo(orig.subtract(up).abs()) < 0) {
return down;
}
return up;
}
|
[
"public",
"static",
"BigDecimal",
"roundToClosest",
"(",
"double",
"value",
",",
"double",
"steps",
")",
"{",
"final",
"BigDecimal",
"down",
"=",
"DMatrixUtils",
".",
"roundDownTo",
"(",
"value",
",",
"steps",
")",
";",
"final",
"BigDecimal",
"up",
"=",
"DMatrixUtils",
".",
"roundUpTo",
"(",
"value",
",",
"steps",
")",
";",
"final",
"BigDecimal",
"orig",
"=",
"new",
"BigDecimal",
"(",
"String",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"if",
"(",
"orig",
".",
"subtract",
"(",
"down",
")",
".",
"abs",
"(",
")",
".",
"compareTo",
"(",
"orig",
".",
"subtract",
"(",
"up",
")",
".",
"abs",
"(",
")",
")",
"<",
"0",
")",
"{",
"return",
"down",
";",
"}",
"return",
"up",
";",
"}"
] |
Returns the closest rounded value of the given value for the given steps.
@param value The original value to be rounded.
@param steps The steps.
@return The closest rounded value of the given value for the given steps.
|
[
"Returns",
"the",
"closest",
"rounded",
"value",
"of",
"the",
"given",
"value",
"for",
"the",
"given",
"steps",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L347-L355
|
145,364
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.matrixFromRange
|
public static double[][] matrixFromRange (double[] lower, double[] upper, int rows) {
// Get the number of columns:
final int cols = lower.length;
// Initialize the return value:
final double[][] matrix = new double[rows][cols];
// Iterate over columns and fill the array:
for (int col = 0; col < cols; col++) {
// Get the sequence:
final double[] sequence = DMatrixUtils.sequence(lower[col], upper[col], rows);
// Assign to each row in the column:
for (int row = 0; row < sequence.length; row++) {
matrix[row][col] = sequence[row];
}
}
// Done, return the populated matrix:
return matrix;
}
|
java
|
public static double[][] matrixFromRange (double[] lower, double[] upper, int rows) {
// Get the number of columns:
final int cols = lower.length;
// Initialize the return value:
final double[][] matrix = new double[rows][cols];
// Iterate over columns and fill the array:
for (int col = 0; col < cols; col++) {
// Get the sequence:
final double[] sequence = DMatrixUtils.sequence(lower[col], upper[col], rows);
// Assign to each row in the column:
for (int row = 0; row < sequence.length; row++) {
matrix[row][col] = sequence[row];
}
}
// Done, return the populated matrix:
return matrix;
}
|
[
"public",
"static",
"double",
"[",
"]",
"[",
"]",
"matrixFromRange",
"(",
"double",
"[",
"]",
"lower",
",",
"double",
"[",
"]",
"upper",
",",
"int",
"rows",
")",
"{",
"// Get the number of columns:",
"final",
"int",
"cols",
"=",
"lower",
".",
"length",
";",
"// Initialize the return value:",
"final",
"double",
"[",
"]",
"[",
"]",
"matrix",
"=",
"new",
"double",
"[",
"rows",
"]",
"[",
"cols",
"]",
";",
"// Iterate over columns and fill the array:",
"for",
"(",
"int",
"col",
"=",
"0",
";",
"col",
"<",
"cols",
";",
"col",
"++",
")",
"{",
"// Get the sequence:",
"final",
"double",
"[",
"]",
"sequence",
"=",
"DMatrixUtils",
".",
"sequence",
"(",
"lower",
"[",
"col",
"]",
",",
"upper",
"[",
"col",
"]",
",",
"rows",
")",
";",
"// Assign to each row in the column:",
"for",
"(",
"int",
"row",
"=",
"0",
";",
"row",
"<",
"sequence",
".",
"length",
";",
"row",
"++",
")",
"{",
"matrix",
"[",
"row",
"]",
"[",
"col",
"]",
"=",
"sequence",
"[",
"row",
"]",
";",
"}",
"}",
"// Done, return the populated matrix:",
"return",
"matrix",
";",
"}"
] |
Creates a matrix from the provided range for columns with the given number of rows.
@param lower The lower bound (inclusive) for the range.
@param upper The upper bound (exclusive) for the range.
@param rows The number of rows.
@return A new matrix.
|
[
"Creates",
"a",
"matrix",
"from",
"the",
"provided",
"range",
"for",
"columns",
"with",
"the",
"given",
"number",
"of",
"rows",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L399-L419
|
145,365
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.cumsum
|
public static double[] cumsum (double[] vector) {
// Initialize the return value:
final double[] retval = new double[vector.length];
// Iterate and cumulate:
retval[0] = vector[0];
for (int i = 1; i < retval.length; i++) {
retval[i] = vector[i] + retval[i - 1];
}
// Done, return:
return retval;
}
|
java
|
public static double[] cumsum (double[] vector) {
// Initialize the return value:
final double[] retval = new double[vector.length];
// Iterate and cumulate:
retval[0] = vector[0];
for (int i = 1; i < retval.length; i++) {
retval[i] = vector[i] + retval[i - 1];
}
// Done, return:
return retval;
}
|
[
"public",
"static",
"double",
"[",
"]",
"cumsum",
"(",
"double",
"[",
"]",
"vector",
")",
"{",
"// Initialize the return value:",
"final",
"double",
"[",
"]",
"retval",
"=",
"new",
"double",
"[",
"vector",
".",
"length",
"]",
";",
"// Iterate and cumulate:",
"retval",
"[",
"0",
"]",
"=",
"vector",
"[",
"0",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"1",
";",
"i",
"<",
"retval",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"vector",
"[",
"i",
"]",
"+",
"retval",
"[",
"i",
"-",
"1",
"]",
";",
"}",
"// Done, return:",
"return",
"retval",
";",
"}"
] |
Computes the cumulative sums of a given vector.
@param vector Vector which the cumulative sums to be computed of.
@return Cumulative sums of the vector.
|
[
"Computes",
"the",
"cumulative",
"sums",
"of",
"a",
"given",
"vector",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L427-L439
|
145,366
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.shuffleIndices
|
public static int[] shuffleIndices (int length, RandomGenerator randomGenerator) {
// Initialize indices:
final int[] indices = IntStream.range(0, length).toArray();
// Shuffle the array:
MathArrays.shuffle(indices, randomGenerator);
// Done return shuffled indices:
return indices;
}
|
java
|
public static int[] shuffleIndices (int length, RandomGenerator randomGenerator) {
// Initialize indices:
final int[] indices = IntStream.range(0, length).toArray();
// Shuffle the array:
MathArrays.shuffle(indices, randomGenerator);
// Done return shuffled indices:
return indices;
}
|
[
"public",
"static",
"int",
"[",
"]",
"shuffleIndices",
"(",
"int",
"length",
",",
"RandomGenerator",
"randomGenerator",
")",
"{",
"// Initialize indices:",
"final",
"int",
"[",
"]",
"indices",
"=",
"IntStream",
".",
"range",
"(",
"0",
",",
"length",
")",
".",
"toArray",
"(",
")",
";",
"// Shuffle the array:",
"MathArrays",
".",
"shuffle",
"(",
"indices",
",",
"randomGenerator",
")",
";",
"// Done return shuffled indices:",
"return",
"indices",
";",
"}"
] |
Consumes the length of an array and returns its shuffled indices.
@param length The length of the arrays of which indices to be shuffled.
@param randomGenerator Random number generator.
@return Shuffled indices.
|
[
"Consumes",
"the",
"length",
"of",
"an",
"array",
"and",
"returns",
"its",
"shuffled",
"indices",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L665-L674
|
145,367
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.applyIndices
|
public static double[] applyIndices (double[] vector, int[] indices) {
// Initialize the return array:
final double[] retval = new double[indices.length];
// Iterate over indices and populate:
for (int i = 0; i < retval.length; i++) {
retval[i] = vector[indices[i]];
}
// Done, return the return value:
return retval;
}
|
java
|
public static double[] applyIndices (double[] vector, int[] indices) {
// Initialize the return array:
final double[] retval = new double[indices.length];
// Iterate over indices and populate:
for (int i = 0; i < retval.length; i++) {
retval[i] = vector[indices[i]];
}
// Done, return the return value:
return retval;
}
|
[
"public",
"static",
"double",
"[",
"]",
"applyIndices",
"(",
"double",
"[",
"]",
"vector",
",",
"int",
"[",
"]",
"indices",
")",
"{",
"// Initialize the return array:",
"final",
"double",
"[",
"]",
"retval",
"=",
"new",
"double",
"[",
"indices",
".",
"length",
"]",
";",
"// Iterate over indices and populate:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"retval",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"vector",
"[",
"indices",
"[",
"i",
"]",
"]",
";",
"}",
"// Done, return the return value:",
"return",
"retval",
";",
"}"
] |
Consumes an array and desired respective indices in an array and return a new array with values from the desired indices.
@param vector Values.
@param indices Desired indices for order.
@return A new array.
|
[
"Consumes",
"an",
"array",
"and",
"desired",
"respective",
"indices",
"in",
"an",
"array",
"and",
"return",
"a",
"new",
"array",
"with",
"values",
"from",
"the",
"desired",
"indices",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L683-L694
|
145,368
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.pairwiseMin
|
public static double[] pairwiseMin (double[] vector1, double[] vector2) {
// Initialize the return value:
final double[] retval = new double[vector1.length];
// Iterate over values and get mins:
for (int i = 0; i < retval.length; i++) {
retval[i] = Math.min(vector1[i], vector2[i]);
}
// Done, return:
return retval;
}
|
java
|
public static double[] pairwiseMin (double[] vector1, double[] vector2) {
// Initialize the return value:
final double[] retval = new double[vector1.length];
// Iterate over values and get mins:
for (int i = 0; i < retval.length; i++) {
retval[i] = Math.min(vector1[i], vector2[i]);
}
// Done, return:
return retval;
}
|
[
"public",
"static",
"double",
"[",
"]",
"pairwiseMin",
"(",
"double",
"[",
"]",
"vector1",
",",
"double",
"[",
"]",
"vector2",
")",
"{",
"// Initialize the return value:",
"final",
"double",
"[",
"]",
"retval",
"=",
"new",
"double",
"[",
"vector1",
".",
"length",
"]",
";",
"// Iterate over values and get mins:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"retval",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"Math",
".",
"min",
"(",
"vector1",
"[",
"i",
"]",
",",
"vector2",
"[",
"i",
"]",
")",
";",
"}",
"// Done, return:",
"return",
"retval",
";",
"}"
] |
Computes a vector as the min of respective pairs from two arrays.
@param vector1 The first vector.
@param vector2 The second vector.
@return Mins of two vectors.
|
[
"Computes",
"a",
"vector",
"as",
"the",
"min",
"of",
"respective",
"pairs",
"from",
"two",
"arrays",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L740-L751
|
145,369
|
vst/commons-math-extensions
|
src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java
|
DMatrixUtils.pairwiseMax
|
public static double[] pairwiseMax (double[] vector1, double[] vector2) {
// Initialize the return value:
final double[] retval = new double[vector1.length];
// Iterate over values and get maxs:
for (int i = 0; i < retval.length; i++) {
retval[i] = Math.max(vector1[i], vector2[i]);
}
// Done, return:
return retval;
}
|
java
|
public static double[] pairwiseMax (double[] vector1, double[] vector2) {
// Initialize the return value:
final double[] retval = new double[vector1.length];
// Iterate over values and get maxs:
for (int i = 0; i < retval.length; i++) {
retval[i] = Math.max(vector1[i], vector2[i]);
}
// Done, return:
return retval;
}
|
[
"public",
"static",
"double",
"[",
"]",
"pairwiseMax",
"(",
"double",
"[",
"]",
"vector1",
",",
"double",
"[",
"]",
"vector2",
")",
"{",
"// Initialize the return value:",
"final",
"double",
"[",
"]",
"retval",
"=",
"new",
"double",
"[",
"vector1",
".",
"length",
"]",
";",
"// Iterate over values and get maxs:",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"retval",
".",
"length",
";",
"i",
"++",
")",
"{",
"retval",
"[",
"i",
"]",
"=",
"Math",
".",
"max",
"(",
"vector1",
"[",
"i",
"]",
",",
"vector2",
"[",
"i",
"]",
")",
";",
"}",
"// Done, return:",
"return",
"retval",
";",
"}"
] |
Computes a vector as the max of respective pairs from two arrays.
@param vector1 The first vector.
@param vector2 The second vector.
@return Maxs of two vectors.
|
[
"Computes",
"a",
"vector",
"as",
"the",
"max",
"of",
"respective",
"pairs",
"from",
"two",
"arrays",
"."
] |
a11ee78ffe53ab7c016062be93c5af07aa8e1823
|
https://github.com/vst/commons-math-extensions/blob/a11ee78ffe53ab7c016062be93c5af07aa8e1823/src/main/java/com/vsthost/rnd/commons/math/ext/linear/DMatrixUtils.java#L760-L771
|
145,370
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.observe
|
public TableFactor observe(int variable, final int value) {
return marginalize(variable, 0, (marginalizedVariableValue, assignment) -> {
if (marginalizedVariableValue == value) {
return (old, n) -> {
// This would mean that we're observing something with 0 probability, which will wonk up downstream
// stuff
// assert(n != 0);
assert !Double.isNaN(n);
return n;
};
} else {
return (old, n) -> {
assert !Double.isNaN(old);
return old;
};
}
});
}
|
java
|
public TableFactor observe(int variable, final int value) {
return marginalize(variable, 0, (marginalizedVariableValue, assignment) -> {
if (marginalizedVariableValue == value) {
return (old, n) -> {
// This would mean that we're observing something with 0 probability, which will wonk up downstream
// stuff
// assert(n != 0);
assert !Double.isNaN(n);
return n;
};
} else {
return (old, n) -> {
assert !Double.isNaN(old);
return old;
};
}
});
}
|
[
"public",
"TableFactor",
"observe",
"(",
"int",
"variable",
",",
"final",
"int",
"value",
")",
"{",
"return",
"marginalize",
"(",
"variable",
",",
"0",
",",
"(",
"marginalizedVariableValue",
",",
"assignment",
")",
"->",
"{",
"if",
"(",
"marginalizedVariableValue",
"==",
"value",
")",
"{",
"return",
"(",
"old",
",",
"n",
")",
"->",
"{",
"// This would mean that we're observing something with 0 probability, which will wonk up downstream",
"// stuff",
"// assert(n != 0);",
"assert",
"!",
"Double",
".",
"isNaN",
"(",
"n",
")",
";",
"return",
"n",
";",
"}",
";",
"}",
"else",
"{",
"return",
"(",
"old",
",",
"n",
")",
"->",
"{",
"assert",
"!",
"Double",
".",
"isNaN",
"(",
"old",
")",
";",
"return",
"old",
";",
"}",
";",
"}",
"}",
")",
";",
"}"
] |
Remove a variable by observing it at a certain value, return a new factor without that variable.
@param variable the variable to be observed
@param value the value the variable takes when observed
@return a new factor with 'variable' in it
|
[
"Remove",
"a",
"variable",
"by",
"observing",
"it",
"at",
"a",
"certain",
"value",
"return",
"a",
"new",
"factor",
"without",
"that",
"variable",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L119-L136
|
145,371
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.getMaxedMarginals
|
public double[][] getMaxedMarginals() {
double[][] maxValues = new double[neighborIndices.length][];
for (int i = 0; i < neighborIndices.length; i++) {
maxValues[i] = new double[getDimensions()[i]];
for (int j = 0; j < maxValues[i].length; j++) maxValues[i][j] = Double.NEGATIVE_INFINITY;
}
// Get max values
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
int[] assignment = fastPassByReferenceIterator.next();
while (true) {
double v = getAssignmentLogValue(assignment);
for (int i = 0; i < neighborIndices.length; i++) {
if (maxValues[i][assignment[i]] < v) maxValues[i][assignment[i]] = v;
}
// This mutates the resultAssignment[] array, rather than creating a new one
if (fastPassByReferenceIterator.hasNext()) {
fastPassByReferenceIterator.next();
} else break;
}
for (int i = 0; i < neighborIndices.length; i++) {
normalizeLogArr(maxValues[i]);
}
return maxValues;
}
|
java
|
public double[][] getMaxedMarginals() {
double[][] maxValues = new double[neighborIndices.length][];
for (int i = 0; i < neighborIndices.length; i++) {
maxValues[i] = new double[getDimensions()[i]];
for (int j = 0; j < maxValues[i].length; j++) maxValues[i][j] = Double.NEGATIVE_INFINITY;
}
// Get max values
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
int[] assignment = fastPassByReferenceIterator.next();
while (true) {
double v = getAssignmentLogValue(assignment);
for (int i = 0; i < neighborIndices.length; i++) {
if (maxValues[i][assignment[i]] < v) maxValues[i][assignment[i]] = v;
}
// This mutates the resultAssignment[] array, rather than creating a new one
if (fastPassByReferenceIterator.hasNext()) {
fastPassByReferenceIterator.next();
} else break;
}
for (int i = 0; i < neighborIndices.length; i++) {
normalizeLogArr(maxValues[i]);
}
return maxValues;
}
|
[
"public",
"double",
"[",
"]",
"[",
"]",
"getMaxedMarginals",
"(",
")",
"{",
"double",
"[",
"]",
"[",
"]",
"maxValues",
"=",
"new",
"double",
"[",
"neighborIndices",
".",
"length",
"]",
"[",
"",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"neighborIndices",
".",
"length",
";",
"i",
"++",
")",
"{",
"maxValues",
"[",
"i",
"]",
"=",
"new",
"double",
"[",
"getDimensions",
"(",
")",
"[",
"i",
"]",
"]",
";",
"for",
"(",
"int",
"j",
"=",
"0",
";",
"j",
"<",
"maxValues",
"[",
"i",
"]",
".",
"length",
";",
"j",
"++",
")",
"maxValues",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"}",
"// Get max values",
"// OPTIMIZATION:",
"// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,",
"// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.",
"Iterator",
"<",
"int",
"[",
"]",
">",
"fastPassByReferenceIterator",
"=",
"fastPassByReferenceIterator",
"(",
")",
";",
"int",
"[",
"]",
"assignment",
"=",
"fastPassByReferenceIterator",
".",
"next",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"double",
"v",
"=",
"getAssignmentLogValue",
"(",
"assignment",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"neighborIndices",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"maxValues",
"[",
"i",
"]",
"[",
"assignment",
"[",
"i",
"]",
"]",
"<",
"v",
")",
"maxValues",
"[",
"i",
"]",
"[",
"assignment",
"[",
"i",
"]",
"]",
"=",
"v",
";",
"}",
"// This mutates the resultAssignment[] array, rather than creating a new one",
"if",
"(",
"fastPassByReferenceIterator",
".",
"hasNext",
"(",
")",
")",
"{",
"fastPassByReferenceIterator",
".",
"next",
"(",
")",
";",
"}",
"else",
"break",
";",
"}",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"neighborIndices",
".",
"length",
";",
"i",
"++",
")",
"{",
"normalizeLogArr",
"(",
"maxValues",
"[",
"i",
"]",
")",
";",
"}",
"return",
"maxValues",
";",
"}"
] |
Convenience function to max out all but one variable, and return the marginal array.
@return an array of doubles one-to-one with variable states for each variable
|
[
"Convenience",
"function",
"to",
"max",
"out",
"all",
"but",
"one",
"variable",
"and",
"return",
"the",
"marginal",
"array",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L229-L260
|
145,372
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.maxOut
|
public TableFactor maxOut(int variable) {
return marginalize(variable, Double.NEGATIVE_INFINITY, (marginalizedVariableValue, assignment) -> Math::max);
}
|
java
|
public TableFactor maxOut(int variable) {
return marginalize(variable, Double.NEGATIVE_INFINITY, (marginalizedVariableValue, assignment) -> Math::max);
}
|
[
"public",
"TableFactor",
"maxOut",
"(",
"int",
"variable",
")",
"{",
"return",
"marginalize",
"(",
"variable",
",",
"Double",
".",
"NEGATIVE_INFINITY",
",",
"(",
"marginalizedVariableValue",
",",
"assignment",
")",
"->",
"Math",
"::",
"max",
")",
";",
"}"
] |
Marginalize out a variable by taking the max value.
@param variable the variable to be maxed out.
@return a table factor that will contain the largest value of the variable being marginalized out.
|
[
"Marginalize",
"out",
"a",
"variable",
"by",
"taking",
"the",
"max",
"value",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L268-L270
|
145,373
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.getBestAssignment
|
public int[] getBestAssignment() {
double maxValue = Double.NEGATIVE_INFINITY;
for (int i = 0; i < values.length; i++) if (values[i] > maxValue) {
maxValue = values[i];
}
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
do {
int[] assignment = fastPassByReferenceIterator.next();
double v = getAssignmentLogValue(assignment);
if (v == maxValue) return assignment;
} while (fastPassByReferenceIterator.hasNext());
throw new IllegalStateException("This is unreachable.");
}
|
java
|
public int[] getBestAssignment() {
double maxValue = Double.NEGATIVE_INFINITY;
for (int i = 0; i < values.length; i++) if (values[i] > maxValue) {
maxValue = values[i];
}
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
do {
int[] assignment = fastPassByReferenceIterator.next();
double v = getAssignmentLogValue(assignment);
if (v == maxValue) return assignment;
} while (fastPassByReferenceIterator.hasNext());
throw new IllegalStateException("This is unreachable.");
}
|
[
"public",
"int",
"[",
"]",
"getBestAssignment",
"(",
")",
"{",
"double",
"maxValue",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"values",
".",
"length",
";",
"i",
"++",
")",
"if",
"(",
"values",
"[",
"i",
"]",
">",
"maxValue",
")",
"{",
"maxValue",
"=",
"values",
"[",
"i",
"]",
";",
"}",
"// OPTIMIZATION:",
"// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,",
"// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.",
"Iterator",
"<",
"int",
"[",
"]",
">",
"fastPassByReferenceIterator",
"=",
"fastPassByReferenceIterator",
"(",
")",
";",
"do",
"{",
"int",
"[",
"]",
"assignment",
"=",
"fastPassByReferenceIterator",
".",
"next",
"(",
")",
";",
"double",
"v",
"=",
"getAssignmentLogValue",
"(",
"assignment",
")",
";",
"if",
"(",
"v",
"==",
"maxValue",
")",
"return",
"assignment",
";",
"}",
"while",
"(",
"fastPassByReferenceIterator",
".",
"hasNext",
"(",
")",
")",
";",
"throw",
"new",
"IllegalStateException",
"(",
"\"This is unreachable.\"",
")",
";",
"}"
] |
Returns the highest value assignment to this TableFactor
@return an array of variable assignments, corresponding to the variables listed in neighborIndices, that has the
highest value
|
[
"Returns",
"the",
"highest",
"value",
"assignment",
"to",
"this",
"TableFactor"
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L277-L295
|
145,374
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.valueSum
|
public double valueSum() {
// We want the exp(log-sum-exp), for stability
// This rearranges to exp(a)*(sum-exp)
double max = 0.0;
for (int[] assignment : this) {
double v = getAssignmentLogValue(assignment);
if (v > max) {
max = v;
}
}
double sumExp = 0.0;
for (int[] assignment : this) {
double assigmentLogValue = getAssignmentLogValue(assignment);
assert !Double.isNaN(assigmentLogValue);
sumExp += Math.exp(getAssignmentLogValue(assignment) - max);
}
assert !Double.isNaN(sumExp);
assert !Double.isNaN(max);
return sumExp * Math.exp(max);
}
|
java
|
public double valueSum() {
// We want the exp(log-sum-exp), for stability
// This rearranges to exp(a)*(sum-exp)
double max = 0.0;
for (int[] assignment : this) {
double v = getAssignmentLogValue(assignment);
if (v > max) {
max = v;
}
}
double sumExp = 0.0;
for (int[] assignment : this) {
double assigmentLogValue = getAssignmentLogValue(assignment);
assert !Double.isNaN(assigmentLogValue);
sumExp += Math.exp(getAssignmentLogValue(assignment) - max);
}
assert !Double.isNaN(sumExp);
assert !Double.isNaN(max);
return sumExp * Math.exp(max);
}
|
[
"public",
"double",
"valueSum",
"(",
")",
"{",
"// We want the exp(log-sum-exp), for stability",
"// This rearranges to exp(a)*(sum-exp)",
"double",
"max",
"=",
"0.0",
";",
"for",
"(",
"int",
"[",
"]",
"assignment",
":",
"this",
")",
"{",
"double",
"v",
"=",
"getAssignmentLogValue",
"(",
"assignment",
")",
";",
"if",
"(",
"v",
">",
"max",
")",
"{",
"max",
"=",
"v",
";",
"}",
"}",
"double",
"sumExp",
"=",
"0.0",
";",
"for",
"(",
"int",
"[",
"]",
"assignment",
":",
"this",
")",
"{",
"double",
"assigmentLogValue",
"=",
"getAssignmentLogValue",
"(",
"assignment",
")",
";",
"assert",
"!",
"Double",
".",
"isNaN",
"(",
"assigmentLogValue",
")",
";",
"sumExp",
"+=",
"Math",
".",
"exp",
"(",
"getAssignmentLogValue",
"(",
"assignment",
")",
"-",
"max",
")",
";",
"}",
"assert",
"!",
"Double",
".",
"isNaN",
"(",
"sumExp",
")",
";",
"assert",
"!",
"Double",
".",
"isNaN",
"(",
"max",
")",
";",
"return",
"sumExp",
"*",
"Math",
".",
"exp",
"(",
"max",
")",
";",
"}"
] |
This is useful for calculating the partition function, and is exposed here because when implemented internally
we can do a much more numerically stable summation.
@return the sum of all values for all assignments to the TableFactor
|
[
"This",
"is",
"useful",
"for",
"calculating",
"the",
"partition",
"function",
"and",
"is",
"exposed",
"here",
"because",
"when",
"implemented",
"internally",
"we",
"can",
"do",
"a",
"much",
"more",
"numerically",
"stable",
"summation",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L563-L586
|
145,375
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.marginalize
|
private TableFactor marginalize(int variable, double startingValue, BiFunction<Integer, int[], BiFunction<Double, Double, Double>> curriedFoldr) {
// Can't marginalize the last variable
assert (getDimensions().length > 1);
// Calculate the result domain
List<Integer> resultDomain = new ArrayList<>();
for (int n : neighborIndices) {
if (n != variable) {
resultDomain.add(n);
}
}
// Create result TableFactor
int[] resultNeighborIndices = new int[resultDomain.size()];
int[] resultDimensions = new int[resultNeighborIndices.length];
for (int i = 0; i < resultDomain.size(); i++) {
int var = resultDomain.get(i);
resultNeighborIndices[i] = var;
resultDimensions[i] = getVariableSize(var);
}
TableFactor result = new TableFactor(resultNeighborIndices, resultDimensions);
// Calculate forward-pointers from the old domain to new domain
int[] mapping = new int[neighborIndices.length];
for (int i = 0; i < neighborIndices.length; i++) {
mapping[i] = resultDomain.indexOf(neighborIndices[i]);
}
// Initialize
for (int[] assignment : result) {
result.setAssignmentLogValue(assignment, startingValue);
}
// Do the actual fold into the result
int[] resultAssignment = new int[result.neighborIndices.length];
int marginalizedVariableValue = 0;
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
int[] assignment = fastPassByReferenceIterator.next();
while (true) {
// Set the assignment arrays correctly
for (int i = 0; i < assignment.length; i++) {
if (mapping[i] != -1) resultAssignment[mapping[i]] = assignment[i];
else marginalizedVariableValue = assignment[i];
}
double value = curriedFoldr.apply(marginalizedVariableValue, resultAssignment)
.apply(result.getAssignmentLogValue(resultAssignment), getAssignmentLogValue(assignment));
assert(!Double.isNaN(value));
result.setAssignmentLogValue(resultAssignment, value);
if (fastPassByReferenceIterator.hasNext()) fastPassByReferenceIterator.next();
else break;
}
return result;
}
|
java
|
private TableFactor marginalize(int variable, double startingValue, BiFunction<Integer, int[], BiFunction<Double, Double, Double>> curriedFoldr) {
// Can't marginalize the last variable
assert (getDimensions().length > 1);
// Calculate the result domain
List<Integer> resultDomain = new ArrayList<>();
for (int n : neighborIndices) {
if (n != variable) {
resultDomain.add(n);
}
}
// Create result TableFactor
int[] resultNeighborIndices = new int[resultDomain.size()];
int[] resultDimensions = new int[resultNeighborIndices.length];
for (int i = 0; i < resultDomain.size(); i++) {
int var = resultDomain.get(i);
resultNeighborIndices[i] = var;
resultDimensions[i] = getVariableSize(var);
}
TableFactor result = new TableFactor(resultNeighborIndices, resultDimensions);
// Calculate forward-pointers from the old domain to new domain
int[] mapping = new int[neighborIndices.length];
for (int i = 0; i < neighborIndices.length; i++) {
mapping[i] = resultDomain.indexOf(neighborIndices[i]);
}
// Initialize
for (int[] assignment : result) {
result.setAssignmentLogValue(assignment, startingValue);
}
// Do the actual fold into the result
int[] resultAssignment = new int[result.neighborIndices.length];
int marginalizedVariableValue = 0;
// OPTIMIZATION:
// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,
// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.
Iterator<int[]> fastPassByReferenceIterator = fastPassByReferenceIterator();
int[] assignment = fastPassByReferenceIterator.next();
while (true) {
// Set the assignment arrays correctly
for (int i = 0; i < assignment.length; i++) {
if (mapping[i] != -1) resultAssignment[mapping[i]] = assignment[i];
else marginalizedVariableValue = assignment[i];
}
double value = curriedFoldr.apply(marginalizedVariableValue, resultAssignment)
.apply(result.getAssignmentLogValue(resultAssignment), getAssignmentLogValue(assignment));
assert(!Double.isNaN(value));
result.setAssignmentLogValue(resultAssignment, value);
if (fastPassByReferenceIterator.hasNext()) fastPassByReferenceIterator.next();
else break;
}
return result;
}
|
[
"private",
"TableFactor",
"marginalize",
"(",
"int",
"variable",
",",
"double",
"startingValue",
",",
"BiFunction",
"<",
"Integer",
",",
"int",
"[",
"]",
",",
"BiFunction",
"<",
"Double",
",",
"Double",
",",
"Double",
">",
">",
"curriedFoldr",
")",
"{",
"// Can't marginalize the last variable",
"assert",
"(",
"getDimensions",
"(",
")",
".",
"length",
">",
"1",
")",
";",
"// Calculate the result domain",
"List",
"<",
"Integer",
">",
"resultDomain",
"=",
"new",
"ArrayList",
"<>",
"(",
")",
";",
"for",
"(",
"int",
"n",
":",
"neighborIndices",
")",
"{",
"if",
"(",
"n",
"!=",
"variable",
")",
"{",
"resultDomain",
".",
"add",
"(",
"n",
")",
";",
"}",
"}",
"// Create result TableFactor",
"int",
"[",
"]",
"resultNeighborIndices",
"=",
"new",
"int",
"[",
"resultDomain",
".",
"size",
"(",
")",
"]",
";",
"int",
"[",
"]",
"resultDimensions",
"=",
"new",
"int",
"[",
"resultNeighborIndices",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"resultDomain",
".",
"size",
"(",
")",
";",
"i",
"++",
")",
"{",
"int",
"var",
"=",
"resultDomain",
".",
"get",
"(",
"i",
")",
";",
"resultNeighborIndices",
"[",
"i",
"]",
"=",
"var",
";",
"resultDimensions",
"[",
"i",
"]",
"=",
"getVariableSize",
"(",
"var",
")",
";",
"}",
"TableFactor",
"result",
"=",
"new",
"TableFactor",
"(",
"resultNeighborIndices",
",",
"resultDimensions",
")",
";",
"// Calculate forward-pointers from the old domain to new domain",
"int",
"[",
"]",
"mapping",
"=",
"new",
"int",
"[",
"neighborIndices",
".",
"length",
"]",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"neighborIndices",
".",
"length",
";",
"i",
"++",
")",
"{",
"mapping",
"[",
"i",
"]",
"=",
"resultDomain",
".",
"indexOf",
"(",
"neighborIndices",
"[",
"i",
"]",
")",
";",
"}",
"// Initialize",
"for",
"(",
"int",
"[",
"]",
"assignment",
":",
"result",
")",
"{",
"result",
".",
"setAssignmentLogValue",
"(",
"assignment",
",",
"startingValue",
")",
";",
"}",
"// Do the actual fold into the result",
"int",
"[",
"]",
"resultAssignment",
"=",
"new",
"int",
"[",
"result",
".",
"neighborIndices",
".",
"length",
"]",
";",
"int",
"marginalizedVariableValue",
"=",
"0",
";",
"// OPTIMIZATION:",
"// Rather than use the standard iterator, which creates lots of int[] arrays on the heap, which need to be GC'd,",
"// we use the fast version that just mutates one array. Since this is read once for us here, this is ideal.",
"Iterator",
"<",
"int",
"[",
"]",
">",
"fastPassByReferenceIterator",
"=",
"fastPassByReferenceIterator",
"(",
")",
";",
"int",
"[",
"]",
"assignment",
"=",
"fastPassByReferenceIterator",
".",
"next",
"(",
")",
";",
"while",
"(",
"true",
")",
"{",
"// Set the assignment arrays correctly",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"assignment",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"mapping",
"[",
"i",
"]",
"!=",
"-",
"1",
")",
"resultAssignment",
"[",
"mapping",
"[",
"i",
"]",
"]",
"=",
"assignment",
"[",
"i",
"]",
";",
"else",
"marginalizedVariableValue",
"=",
"assignment",
"[",
"i",
"]",
";",
"}",
"double",
"value",
"=",
"curriedFoldr",
".",
"apply",
"(",
"marginalizedVariableValue",
",",
"resultAssignment",
")",
".",
"apply",
"(",
"result",
".",
"getAssignmentLogValue",
"(",
"resultAssignment",
")",
",",
"getAssignmentLogValue",
"(",
"assignment",
")",
")",
";",
"assert",
"(",
"!",
"Double",
".",
"isNaN",
"(",
"value",
")",
")",
";",
"result",
".",
"setAssignmentLogValue",
"(",
"resultAssignment",
",",
"value",
")",
";",
"if",
"(",
"fastPassByReferenceIterator",
".",
"hasNext",
"(",
")",
")",
"fastPassByReferenceIterator",
".",
"next",
"(",
")",
";",
"else",
"break",
";",
"}",
"return",
"result",
";",
"}"
] |
Marginalizes out a variable by applying an associative join operation for each possible assignment to the
marginalized variable.
@param variable the variable (by 'name', not offset into neighborIndices)
@param startingValue associativeJoin is basically a foldr over a table, and this is the initialization
@param curriedFoldr the associative function to use when applying the join operation, taking first the
assignment to the value being marginalized, and then a foldr operation
@return a new TableFactor that doesn't contain 'variable', where values were gotten through associative
marginalization.
|
[
"Marginalizes",
"out",
"a",
"variable",
"by",
"applying",
"an",
"associative",
"join",
"operation",
"for",
"each",
"possible",
"assignment",
"to",
"the",
"marginalized",
"variable",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L637-L699
|
145,376
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.getVariableSize
|
private int getVariableSize(int variable) {
for (int i = 0; i < neighborIndices.length; i++) {
if (neighborIndices[i] == variable) return getDimensions()[i];
}
return 0;
}
|
java
|
private int getVariableSize(int variable) {
for (int i = 0; i < neighborIndices.length; i++) {
if (neighborIndices[i] == variable) return getDimensions()[i];
}
return 0;
}
|
[
"private",
"int",
"getVariableSize",
"(",
"int",
"variable",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"neighborIndices",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"neighborIndices",
"[",
"i",
"]",
"==",
"variable",
")",
"return",
"getDimensions",
"(",
")",
"[",
"i",
"]",
";",
"}",
"return",
"0",
";",
"}"
] |
Address a variable by index to get it's size. Basically just a convenience function.
@param variable the name, not index into neighbors, of the variable in question
@return the size of the factor along this dimension
|
[
"Address",
"a",
"variable",
"by",
"index",
"to",
"get",
"it",
"s",
"size",
".",
"Basically",
"just",
"a",
"convenience",
"function",
"."
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L707-L712
|
145,377
|
keenon/loglinear
|
src/main/java/com/github/keenon/loglinear/inference/TableFactor.java
|
TableFactor.normalizeLogArr
|
private void normalizeLogArr(double[] arr) {
// Find the log-scale normalization value
double max = Double.NEGATIVE_INFINITY;
for (double d : arr) {
if (d > max) max = d;
}
double expSum = 0.0;
for (double d : arr) {
expSum += Math.exp(d - max);
}
double logSumExp = max + Math.log(expSum);
if (Double.isInfinite(logSumExp)) {
// Just put in uniform probabilities if we are normalizing all 0s
for (int i = 0; i < arr.length; i++) {
arr[i] = 1.0 / arr.length;
}
} else {
// Normalize in log-scale before exponentiation, to help with stability
for (int i = 0; i < arr.length; i++) {
arr[i] = Math.exp(arr[i] - logSumExp);
}
}
}
|
java
|
private void normalizeLogArr(double[] arr) {
// Find the log-scale normalization value
double max = Double.NEGATIVE_INFINITY;
for (double d : arr) {
if (d > max) max = d;
}
double expSum = 0.0;
for (double d : arr) {
expSum += Math.exp(d - max);
}
double logSumExp = max + Math.log(expSum);
if (Double.isInfinite(logSumExp)) {
// Just put in uniform probabilities if we are normalizing all 0s
for (int i = 0; i < arr.length; i++) {
arr[i] = 1.0 / arr.length;
}
} else {
// Normalize in log-scale before exponentiation, to help with stability
for (int i = 0; i < arr.length; i++) {
arr[i] = Math.exp(arr[i] - logSumExp);
}
}
}
|
[
"private",
"void",
"normalizeLogArr",
"(",
"double",
"[",
"]",
"arr",
")",
"{",
"// Find the log-scale normalization value",
"double",
"max",
"=",
"Double",
".",
"NEGATIVE_INFINITY",
";",
"for",
"(",
"double",
"d",
":",
"arr",
")",
"{",
"if",
"(",
"d",
">",
"max",
")",
"max",
"=",
"d",
";",
"}",
"double",
"expSum",
"=",
"0.0",
";",
"for",
"(",
"double",
"d",
":",
"arr",
")",
"{",
"expSum",
"+=",
"Math",
".",
"exp",
"(",
"d",
"-",
"max",
")",
";",
"}",
"double",
"logSumExp",
"=",
"max",
"+",
"Math",
".",
"log",
"(",
"expSum",
")",
";",
"if",
"(",
"Double",
".",
"isInfinite",
"(",
"logSumExp",
")",
")",
"{",
"// Just put in uniform probabilities if we are normalizing all 0s",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"arr",
"[",
"i",
"]",
"=",
"1.0",
"/",
"arr",
".",
"length",
";",
"}",
"}",
"else",
"{",
"// Normalize in log-scale before exponentiation, to help with stability",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"arr",
"[",
"i",
"]",
"=",
"Math",
".",
"exp",
"(",
"arr",
"[",
"i",
"]",
"-",
"logSumExp",
")",
";",
"}",
"}",
"}"
] |
Super basic in-place array normalization
@param arr the array to normalize
|
[
"Super",
"basic",
"in",
"-",
"place",
"array",
"normalization"
] |
fa0c370ab6782015412f676ef2ab11c97be58e29
|
https://github.com/keenon/loglinear/blob/fa0c370ab6782015412f676ef2ab11c97be58e29/src/main/java/com/github/keenon/loglinear/inference/TableFactor.java#L719-L742
|
145,378
|
triceo/splitlog
|
splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java
|
MessageStore.add
|
public synchronized int add(final Message msg) {
final int nextKey = this.getNextPosition();
this.store.put(nextKey, msg);
MessageStore.LOGGER.info("Message #{} stored on position #{}", msg.getUniqueId(), nextKey);
this.nextMessagePosition.incrementAndGet();
if (this.store.size() > this.messageLimit) {
// discard first message if we're over limit
this.store.remove(this.store.firstKey());
}
return nextKey;
}
|
java
|
public synchronized int add(final Message msg) {
final int nextKey = this.getNextPosition();
this.store.put(nextKey, msg);
MessageStore.LOGGER.info("Message #{} stored on position #{}", msg.getUniqueId(), nextKey);
this.nextMessagePosition.incrementAndGet();
if (this.store.size() > this.messageLimit) {
// discard first message if we're over limit
this.store.remove(this.store.firstKey());
}
return nextKey;
}
|
[
"public",
"synchronized",
"int",
"add",
"(",
"final",
"Message",
"msg",
")",
"{",
"final",
"int",
"nextKey",
"=",
"this",
".",
"getNextPosition",
"(",
")",
";",
"this",
".",
"store",
".",
"put",
"(",
"nextKey",
",",
"msg",
")",
";",
"MessageStore",
".",
"LOGGER",
".",
"info",
"(",
"\"Message #{} stored on position #{}\"",
",",
"msg",
".",
"getUniqueId",
"(",
")",
",",
"nextKey",
")",
";",
"this",
".",
"nextMessagePosition",
".",
"incrementAndGet",
"(",
")",
";",
"if",
"(",
"this",
".",
"store",
".",
"size",
"(",
")",
">",
"this",
".",
"messageLimit",
")",
"{",
"// discard first message if we're over limit",
"this",
".",
"store",
".",
"remove",
"(",
"this",
".",
"store",
".",
"firstKey",
"(",
")",
")",
";",
"}",
"return",
"nextKey",
";",
"}"
] |
Add message to the storage.
Every call will change values returned by {@link #getNextPosition()} and
{@link #getLatestPosition()}. Any call may change value returned by
{@link #getFirstPosition()}, which will happen if a message is discarded
due to hitting the message store capacity.
@param msg
Message in question.
@return Position of the message.
|
[
"Add",
"message",
"to",
"the",
"storage",
"."
] |
4e1b188e8c814119f5cf7343bbc53917843d68a2
|
https://github.com/triceo/splitlog/blob/4e1b188e8c814119f5cf7343bbc53917843d68a2/splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java#L62-L72
|
145,379
|
triceo/splitlog
|
splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java
|
MessageStore.getAll
|
public Collection<Message> getAll() {
final int firstMessagePosition = this.getFirstPosition();
if (firstMessagePosition < MessageStore.INITIAL_MESSAGE_POSITION) {
return Collections.unmodifiableList(Collections.emptyList());
}
return this.getFrom(firstMessagePosition);
}
|
java
|
public Collection<Message> getAll() {
final int firstMessagePosition = this.getFirstPosition();
if (firstMessagePosition < MessageStore.INITIAL_MESSAGE_POSITION) {
return Collections.unmodifiableList(Collections.emptyList());
}
return this.getFrom(firstMessagePosition);
}
|
[
"public",
"Collection",
"<",
"Message",
">",
"getAll",
"(",
")",
"{",
"final",
"int",
"firstMessagePosition",
"=",
"this",
".",
"getFirstPosition",
"(",
")",
";",
"if",
"(",
"firstMessagePosition",
"<",
"MessageStore",
".",
"INITIAL_MESSAGE_POSITION",
")",
"{",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"Collections",
".",
"emptyList",
"(",
")",
")",
";",
"}",
"return",
"this",
".",
"getFrom",
"(",
"firstMessagePosition",
")",
";",
"}"
] |
Return all messages currently present.
@return Unmodifiable list containing those messages.
|
[
"Return",
"all",
"messages",
"currently",
"present",
"."
] |
4e1b188e8c814119f5cf7343bbc53917843d68a2
|
https://github.com/triceo/splitlog/blob/4e1b188e8c814119f5cf7343bbc53917843d68a2/splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java#L127-L133
|
145,380
|
triceo/splitlog
|
splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java
|
MessageStore.getFromRange
|
public synchronized List<Message> getFromRange(final int startPosition, final int endPosition) {
// cache this here, so all parts of the method operate on the same data
final int firstMessageId = this.getFirstPosition();
// input validation
if ((startPosition < MessageStore.INITIAL_MESSAGE_POSITION)
|| (endPosition < MessageStore.INITIAL_MESSAGE_POSITION)) {
throw new IllegalArgumentException("Message position cannot be negative.");
} else if ((firstMessageId >= MessageStore.INITIAL_MESSAGE_POSITION) && (startPosition < firstMessageId)) {
throw new IllegalArgumentException("Message at position " + startPosition
+ " had already been discarded. First available message position is " + firstMessageId + ".");
} else if (endPosition <= startPosition) {
throw new IllegalArgumentException("Ending position must be larger than starting message position.");
} else if (endPosition > this.getNextPosition()) {
throw new IllegalArgumentException("Range end cannot be greater than the next message position.");
}
// and properly synchronized range retrieval
return Collections.unmodifiableList(new LinkedList<>(this.store.subMap(startPosition, endPosition)
.values()));
}
|
java
|
public synchronized List<Message> getFromRange(final int startPosition, final int endPosition) {
// cache this here, so all parts of the method operate on the same data
final int firstMessageId = this.getFirstPosition();
// input validation
if ((startPosition < MessageStore.INITIAL_MESSAGE_POSITION)
|| (endPosition < MessageStore.INITIAL_MESSAGE_POSITION)) {
throw new IllegalArgumentException("Message position cannot be negative.");
} else if ((firstMessageId >= MessageStore.INITIAL_MESSAGE_POSITION) && (startPosition < firstMessageId)) {
throw new IllegalArgumentException("Message at position " + startPosition
+ " had already been discarded. First available message position is " + firstMessageId + ".");
} else if (endPosition <= startPosition) {
throw new IllegalArgumentException("Ending position must be larger than starting message position.");
} else if (endPosition > this.getNextPosition()) {
throw new IllegalArgumentException("Range end cannot be greater than the next message position.");
}
// and properly synchronized range retrieval
return Collections.unmodifiableList(new LinkedList<>(this.store.subMap(startPosition, endPosition)
.values()));
}
|
[
"public",
"synchronized",
"List",
"<",
"Message",
">",
"getFromRange",
"(",
"final",
"int",
"startPosition",
",",
"final",
"int",
"endPosition",
")",
"{",
"// cache this here, so all parts of the method operate on the same data",
"final",
"int",
"firstMessageId",
"=",
"this",
".",
"getFirstPosition",
"(",
")",
";",
"// input validation",
"if",
"(",
"(",
"startPosition",
"<",
"MessageStore",
".",
"INITIAL_MESSAGE_POSITION",
")",
"||",
"(",
"endPosition",
"<",
"MessageStore",
".",
"INITIAL_MESSAGE_POSITION",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Message position cannot be negative.\"",
")",
";",
"}",
"else",
"if",
"(",
"(",
"firstMessageId",
">=",
"MessageStore",
".",
"INITIAL_MESSAGE_POSITION",
")",
"&&",
"(",
"startPosition",
"<",
"firstMessageId",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Message at position \"",
"+",
"startPosition",
"+",
"\" had already been discarded. First available message position is \"",
"+",
"firstMessageId",
"+",
"\".\"",
")",
";",
"}",
"else",
"if",
"(",
"endPosition",
"<=",
"startPosition",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Ending position must be larger than starting message position.\"",
")",
";",
"}",
"else",
"if",
"(",
"endPosition",
">",
"this",
".",
"getNextPosition",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Range end cannot be greater than the next message position.\"",
")",
";",
"}",
"// and properly synchronized range retrieval",
"return",
"Collections",
".",
"unmodifiableList",
"(",
"new",
"LinkedList",
"<>",
"(",
"this",
".",
"store",
".",
"subMap",
"(",
"startPosition",
",",
"endPosition",
")",
".",
"values",
"(",
")",
")",
")",
";",
"}"
] |
Return all messages on positions in the given range.
@param startPosition
Least position, inclusive.
@param endPosition
Greatest position, exclusive.
@return Unmodifiable list containing those messages.
|
[
"Return",
"all",
"messages",
"on",
"positions",
"in",
"the",
"given",
"range",
"."
] |
4e1b188e8c814119f5cf7343bbc53917843d68a2
|
https://github.com/triceo/splitlog/blob/4e1b188e8c814119f5cf7343bbc53917843d68a2/splitlog-core/src/main/java/com/github/triceo/splitlog/MessageStore.java#L169-L187
|
145,381
|
jbundle/webapp
|
base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java
|
BaseOsgiServlet.fixPathInfo
|
public String fixPathInfo(String path)
{
if (path == null)
return null;
if (path.startsWith("/"))
path = path.substring(1); // Resources already start from root/baseURL
if (baseURL == null)
if (properties != null)
if (this.getProperty(BASE_PATH) != null)
path = this.getProperty(BASE_PATH) + path;
return path;
}
|
java
|
public String fixPathInfo(String path)
{
if (path == null)
return null;
if (path.startsWith("/"))
path = path.substring(1); // Resources already start from root/baseURL
if (baseURL == null)
if (properties != null)
if (this.getProperty(BASE_PATH) != null)
path = this.getProperty(BASE_PATH) + path;
return path;
}
|
[
"public",
"String",
"fixPathInfo",
"(",
"String",
"path",
")",
"{",
"if",
"(",
"path",
"==",
"null",
")",
"return",
"null",
";",
"if",
"(",
"path",
".",
"startsWith",
"(",
"\"/\"",
")",
")",
"path",
"=",
"path",
".",
"substring",
"(",
"1",
")",
";",
"// Resources already start from root/baseURL",
"if",
"(",
"baseURL",
"==",
"null",
")",
"if",
"(",
"properties",
"!=",
"null",
")",
"if",
"(",
"this",
".",
"getProperty",
"(",
"BASE_PATH",
")",
"!=",
"null",
")",
"path",
"=",
"this",
".",
"getProperty",
"(",
"BASE_PATH",
")",
"+",
"path",
";",
"return",
"path",
";",
"}"
] |
Get the file path from the request.
@param request
@return
|
[
"Get",
"the",
"file",
"path",
"from",
"the",
"request",
"."
] |
af2cf32bd92254073052f1f9b4bcd47c2f76ba7d
|
https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/base/src/main/java/org/jbundle/util/webapp/base/BaseOsgiServlet.java#L128-L139
|
145,382
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.getPackagePath
|
public static String getPackagePath(final Class<?> clasz) {
checkNotNull("clasz", clasz);
return clasz.getPackage().getName().replace('.', '/');
}
|
java
|
public static String getPackagePath(final Class<?> clasz) {
checkNotNull("clasz", clasz);
return clasz.getPackage().getName().replace('.', '/');
}
|
[
"public",
"static",
"String",
"getPackagePath",
"(",
"final",
"Class",
"<",
"?",
">",
"clasz",
")",
"{",
"checkNotNull",
"(",
"\"clasz\"",
",",
"clasz",
")",
";",
"return",
"clasz",
".",
"getPackage",
"(",
")",
".",
"getName",
"(",
")",
".",
"replace",
"(",
"'",
"'",
",",
"'",
"'",
")",
";",
"}"
] |
Returns the package path of a class.
@param clasz
Class to determine the path for - Cannot be <code>null</code>.
@return Package path for the class.
|
[
"Returns",
"the",
"package",
"path",
"of",
"a",
"class",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L118-L121
|
145,383
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.getResource
|
public static URL getResource(final Class<?> clasz, final String name) {
checkNotNull("clasz", clasz);
checkNotNull("name", name);
final String nameAndPath = SLASH + getPackagePath(clasz) + SLASH + name;
return clasz.getResource(nameAndPath);
}
|
java
|
public static URL getResource(final Class<?> clasz, final String name) {
checkNotNull("clasz", clasz);
checkNotNull("name", name);
final String nameAndPath = SLASH + getPackagePath(clasz) + SLASH + name;
return clasz.getResource(nameAndPath);
}
|
[
"public",
"static",
"URL",
"getResource",
"(",
"final",
"Class",
"<",
"?",
">",
"clasz",
",",
"final",
"String",
"name",
")",
"{",
"checkNotNull",
"(",
"\"clasz\"",
",",
"clasz",
")",
";",
"checkNotNull",
"(",
"\"name\"",
",",
"name",
")",
";",
"final",
"String",
"nameAndPath",
"=",
"SLASH",
"+",
"getPackagePath",
"(",
"clasz",
")",
"+",
"SLASH",
"+",
"name",
";",
"return",
"clasz",
".",
"getResource",
"(",
"nameAndPath",
")",
";",
"}"
] |
Get the path to a resource located in the same package as a given class.
@param clasz
Class with the same package where the resource is located - Cannot be <code>null</code>.
@param name
Filename of the resource - Cannot be <code>null</code>.
@return Resource URL.
|
[
"Get",
"the",
"path",
"to",
"a",
"resource",
"located",
"in",
"the",
"same",
"package",
"as",
"a",
"given",
"class",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L133-L138
|
145,384
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.addToClasspath
|
public static void addToClasspath(final File file, final ClassLoader classLoader) {
checkNotNull("file", file);
try {
addToClasspath(file.toURI().toURL(), classLoader);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
}
|
java
|
public static void addToClasspath(final File file, final ClassLoader classLoader) {
checkNotNull("file", file);
try {
addToClasspath(file.toURI().toURL(), classLoader);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
}
|
[
"public",
"static",
"void",
"addToClasspath",
"(",
"final",
"File",
"file",
",",
"final",
"ClassLoader",
"classLoader",
")",
"{",
"checkNotNull",
"(",
"\"file\"",
",",
"file",
")",
";",
"try",
"{",
"addToClasspath",
"(",
"file",
".",
"toURI",
"(",
")",
".",
"toURL",
"(",
")",
",",
"classLoader",
")",
";",
"}",
"catch",
"(",
"final",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Adds a file to the classpath.
@param file
File to add - Cannot be <code>null</code>.
@param classLoader
Class loader to use - Cannot be <code>null</code>.
|
[
"Adds",
"a",
"file",
"to",
"the",
"classpath",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L227-L234
|
145,385
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.addToClasspath
|
public static void addToClasspath(final String url, final ClassLoader classLoader) {
checkNotNull("url", url);
try {
addToClasspath(new URL(url), classLoader);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
}
|
java
|
public static void addToClasspath(final String url, final ClassLoader classLoader) {
checkNotNull("url", url);
try {
addToClasspath(new URL(url), classLoader);
} catch (final MalformedURLException e) {
throw new RuntimeException(e);
}
}
|
[
"public",
"static",
"void",
"addToClasspath",
"(",
"final",
"String",
"url",
",",
"final",
"ClassLoader",
"classLoader",
")",
"{",
"checkNotNull",
"(",
"\"url\"",
",",
"url",
")",
";",
"try",
"{",
"addToClasspath",
"(",
"new",
"URL",
"(",
"url",
")",
",",
"classLoader",
")",
";",
"}",
"catch",
"(",
"final",
"MalformedURLException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}"
] |
Adds an URL to the classpath.
@param url
URL to add - Cannot be <code>null</code>.
@param classLoader
Class loader to use - Cannot be <code>null</code>.
|
[
"Adds",
"an",
"URL",
"to",
"the",
"classpath",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L254-L261
|
145,386
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.containsURL
|
public static boolean containsURL(final URL[] urls, final URL url) {
checkNotNull("urls", urls);
checkNotNull("url", url);
for (int i = 0; i < urls.length; i++) {
final URL element = urls[i];
final String elementStr = element.toExternalForm();
final String urlStr = url.toExternalForm();
if (elementStr.equals(urlStr)) {
return true;
}
}
return false;
}
|
java
|
public static boolean containsURL(final URL[] urls, final URL url) {
checkNotNull("urls", urls);
checkNotNull("url", url);
for (int i = 0; i < urls.length; i++) {
final URL element = urls[i];
final String elementStr = element.toExternalForm();
final String urlStr = url.toExternalForm();
if (elementStr.equals(urlStr)) {
return true;
}
}
return false;
}
|
[
"public",
"static",
"boolean",
"containsURL",
"(",
"final",
"URL",
"[",
"]",
"urls",
",",
"final",
"URL",
"url",
")",
"{",
"checkNotNull",
"(",
"\"urls\"",
",",
"urls",
")",
";",
"checkNotNull",
"(",
"\"url\"",
",",
"url",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"urls",
".",
"length",
";",
"i",
"++",
")",
"{",
"final",
"URL",
"element",
"=",
"urls",
"[",
"i",
"]",
";",
"final",
"String",
"elementStr",
"=",
"element",
".",
"toExternalForm",
"(",
")",
";",
"final",
"String",
"urlStr",
"=",
"url",
".",
"toExternalForm",
"(",
")",
";",
"if",
"(",
"elementStr",
".",
"equals",
"(",
"urlStr",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] |
Checks if the array or URLs contains the given URL.
@param urls
Array of URLs - Cannot be <code>null</code>.
@param url
URL to find - Cannot be <code>null</code>.
@return If the URL is in the array TRUE else FALSE.
|
[
"Checks",
"if",
"the",
"array",
"or",
"URLs",
"contains",
"the",
"given",
"URL",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L273-L285
|
145,387
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.createHash
|
public static String createHash(final File file, final String algorithm) {
checkNotNull("file", file);
checkNotNull("algorithm", algorithm);
try {
try (final FileInputStream in = new FileInputStream(file)) {
return createHash(in, algorithm);
}
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
|
java
|
public static String createHash(final File file, final String algorithm) {
checkNotNull("file", file);
checkNotNull("algorithm", algorithm);
try {
try (final FileInputStream in = new FileInputStream(file)) {
return createHash(in, algorithm);
}
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
|
[
"public",
"static",
"String",
"createHash",
"(",
"final",
"File",
"file",
",",
"final",
"String",
"algorithm",
")",
"{",
"checkNotNull",
"(",
"\"file\"",
",",
"file",
")",
";",
"checkNotNull",
"(",
"\"algorithm\"",
",",
"algorithm",
")",
";",
"try",
"{",
"try",
"(",
"final",
"FileInputStream",
"in",
"=",
"new",
"FileInputStream",
"(",
"file",
")",
")",
"{",
"return",
"createHash",
"(",
"in",
",",
"algorithm",
")",
";",
"}",
"}",
"catch",
"(",
"final",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Creates a HEX encoded hash from a file.
@param file
File to create a hash for - Cannot be <code>null</code>.
@param algorithm
Hash algorithm like "MD5" or "SHA" - Cannot be <code>null</code>.
@return HEX encoded hash.
|
[
"Creates",
"a",
"HEX",
"encoded",
"hash",
"from",
"a",
"file",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L324-L334
|
145,388
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.createHash
|
public static String createHash(final InputStream inputStream, final String algorithm) {
checkNotNull("inputStream", inputStream);
checkNotNull("algorithm", algorithm);
try {
final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
try (final BufferedInputStream in = new BufferedInputStream(inputStream)) {
final byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) > -1) {
messageDigest.update(buf, 0, count);
}
}
return encodeHex(messageDigest.digest());
} catch (final NoSuchAlgorithmException | IOException ex) {
throw new RuntimeException(ex);
}
}
|
java
|
public static String createHash(final InputStream inputStream, final String algorithm) {
checkNotNull("inputStream", inputStream);
checkNotNull("algorithm", algorithm);
try {
final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
try (final BufferedInputStream in = new BufferedInputStream(inputStream)) {
final byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) > -1) {
messageDigest.update(buf, 0, count);
}
}
return encodeHex(messageDigest.digest());
} catch (final NoSuchAlgorithmException | IOException ex) {
throw new RuntimeException(ex);
}
}
|
[
"public",
"static",
"String",
"createHash",
"(",
"final",
"InputStream",
"inputStream",
",",
"final",
"String",
"algorithm",
")",
"{",
"checkNotNull",
"(",
"\"inputStream\"",
",",
"inputStream",
")",
";",
"checkNotNull",
"(",
"\"algorithm\"",
",",
"algorithm",
")",
";",
"try",
"{",
"final",
"MessageDigest",
"messageDigest",
"=",
"MessageDigest",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"try",
"(",
"final",
"BufferedInputStream",
"in",
"=",
"new",
"BufferedInputStream",
"(",
"inputStream",
")",
")",
"{",
"final",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"1024",
"]",
";",
"int",
"count",
"=",
"0",
";",
"while",
"(",
"(",
"count",
"=",
"in",
".",
"read",
"(",
"buf",
")",
")",
">",
"-",
"1",
")",
"{",
"messageDigest",
".",
"update",
"(",
"buf",
",",
"0",
",",
"count",
")",
";",
"}",
"}",
"return",
"encodeHex",
"(",
"messageDigest",
".",
"digest",
"(",
")",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchAlgorithmException",
"|",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Creates a HEX encoded hash from a stream.
@param inputStream
Stream to create a hash for - Cannot be <code>null</code>.
@param algorithm
Hash algorithm like "MD5" or "SHA" - Cannot be <code>null</code>.
@return HEX encoded hash.
|
[
"Creates",
"a",
"HEX",
"encoded",
"hash",
"from",
"a",
"stream",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L346-L362
|
145,389
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.createCipher
|
private static Cipher createCipher(final String algorithm, final int mode, final char[] password, final byte[] salt, final int count)
throws GeneralSecurityException {
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
final PBEKeySpec keySpec = new PBEKeySpec(password);
final SecretKey key = keyFactory.generateSecret(keySpec);
final Cipher cipher = Cipher.getInstance(algorithm);
final PBEParameterSpec params = new PBEParameterSpec(salt, count);
cipher.init(mode, key, params);
return cipher;
}
|
java
|
private static Cipher createCipher(final String algorithm, final int mode, final char[] password, final byte[] salt, final int count)
throws GeneralSecurityException {
final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algorithm);
final PBEKeySpec keySpec = new PBEKeySpec(password);
final SecretKey key = keyFactory.generateSecret(keySpec);
final Cipher cipher = Cipher.getInstance(algorithm);
final PBEParameterSpec params = new PBEParameterSpec(salt, count);
cipher.init(mode, key, params);
return cipher;
}
|
[
"private",
"static",
"Cipher",
"createCipher",
"(",
"final",
"String",
"algorithm",
",",
"final",
"int",
"mode",
",",
"final",
"char",
"[",
"]",
"password",
",",
"final",
"byte",
"[",
"]",
"salt",
",",
"final",
"int",
"count",
")",
"throws",
"GeneralSecurityException",
"{",
"final",
"SecretKeyFactory",
"keyFactory",
"=",
"SecretKeyFactory",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"final",
"PBEKeySpec",
"keySpec",
"=",
"new",
"PBEKeySpec",
"(",
"password",
")",
";",
"final",
"SecretKey",
"key",
"=",
"keyFactory",
".",
"generateSecret",
"(",
"keySpec",
")",
";",
"final",
"Cipher",
"cipher",
"=",
"Cipher",
".",
"getInstance",
"(",
"algorithm",
")",
";",
"final",
"PBEParameterSpec",
"params",
"=",
"new",
"PBEParameterSpec",
"(",
"salt",
",",
"count",
")",
";",
"cipher",
".",
"init",
"(",
"mode",
",",
"key",
",",
"params",
")",
";",
"return",
"cipher",
";",
"}"
] |
Creates a cipher for encryption or decryption.
@param algorithm
PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES".
@param mode
Encyrption or decyrption.
@param password
Password.
@param salt
Salt usable with algorithm.
@param count
Iterations.
@return Ready initialized cipher.
@throws GeneralSecurityException
Error creating the cipher.
|
[
"Creates",
"a",
"cipher",
"for",
"encryption",
"or",
"decryption",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L383-L394
|
145,390
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.encryptPasswordBased
|
public static byte[] encryptPasswordBased(final String algorithm, final byte[] data, final char[] password, final byte[] salt,
final int count) {
checkNotNull("algorithm", algorithm);
checkNotNull("data", data);
checkNotNull("password", password);
checkNotNull("salt", salt);
try {
final Cipher cipher = createCipher(algorithm, Cipher.ENCRYPT_MODE, password, salt, count);
return cipher.doFinal(data);
} catch (final Exception ex) {
throw new RuntimeException("Error encrypting the password!", ex);
}
}
|
java
|
public static byte[] encryptPasswordBased(final String algorithm, final byte[] data, final char[] password, final byte[] salt,
final int count) {
checkNotNull("algorithm", algorithm);
checkNotNull("data", data);
checkNotNull("password", password);
checkNotNull("salt", salt);
try {
final Cipher cipher = createCipher(algorithm, Cipher.ENCRYPT_MODE, password, salt, count);
return cipher.doFinal(data);
} catch (final Exception ex) {
throw new RuntimeException("Error encrypting the password!", ex);
}
}
|
[
"public",
"static",
"byte",
"[",
"]",
"encryptPasswordBased",
"(",
"final",
"String",
"algorithm",
",",
"final",
"byte",
"[",
"]",
"data",
",",
"final",
"char",
"[",
"]",
"password",
",",
"final",
"byte",
"[",
"]",
"salt",
",",
"final",
"int",
"count",
")",
"{",
"checkNotNull",
"(",
"\"algorithm\"",
",",
"algorithm",
")",
";",
"checkNotNull",
"(",
"\"data\"",
",",
"data",
")",
";",
"checkNotNull",
"(",
"\"password\"",
",",
"password",
")",
";",
"checkNotNull",
"(",
"\"salt\"",
",",
"salt",
")",
";",
"try",
"{",
"final",
"Cipher",
"cipher",
"=",
"createCipher",
"(",
"algorithm",
",",
"Cipher",
".",
"ENCRYPT_MODE",
",",
"password",
",",
"salt",
",",
"count",
")",
";",
"return",
"cipher",
".",
"doFinal",
"(",
"data",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Error encrypting the password!\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Encrypts some data based on a password.
@param algorithm
PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be <code>null</code>.
@param data
Data to encrypt - Cannot be <code>null</code>.
@param password
Password - Cannot be <code>null</code>.
@param salt
Salt usable with algorithm - Cannot be <code>null</code>.
@param count
Iterations.
@return Encrypted data.
|
[
"Encrypts",
"some",
"data",
"based",
"on",
"a",
"password",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L412-L426
|
145,391
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.decryptPasswordBased
|
public static byte[] decryptPasswordBased(final String algorithm, final byte[] encryptedData, final char[] password, final byte[] salt,
final int count) {
checkNotNull("algorithm", algorithm);
checkNotNull("encryptedData", encryptedData);
checkNotNull("password", password);
checkNotNull("salt", salt);
try {
final Cipher cipher = createCipher(algorithm, Cipher.DECRYPT_MODE, password, salt, count);
return cipher.doFinal(encryptedData);
} catch (final Exception ex) {
throw new RuntimeException("Error decrypting the password!", ex);
}
}
|
java
|
public static byte[] decryptPasswordBased(final String algorithm, final byte[] encryptedData, final char[] password, final byte[] salt,
final int count) {
checkNotNull("algorithm", algorithm);
checkNotNull("encryptedData", encryptedData);
checkNotNull("password", password);
checkNotNull("salt", salt);
try {
final Cipher cipher = createCipher(algorithm, Cipher.DECRYPT_MODE, password, salt, count);
return cipher.doFinal(encryptedData);
} catch (final Exception ex) {
throw new RuntimeException("Error decrypting the password!", ex);
}
}
|
[
"public",
"static",
"byte",
"[",
"]",
"decryptPasswordBased",
"(",
"final",
"String",
"algorithm",
",",
"final",
"byte",
"[",
"]",
"encryptedData",
",",
"final",
"char",
"[",
"]",
"password",
",",
"final",
"byte",
"[",
"]",
"salt",
",",
"final",
"int",
"count",
")",
"{",
"checkNotNull",
"(",
"\"algorithm\"",
",",
"algorithm",
")",
";",
"checkNotNull",
"(",
"\"encryptedData\"",
",",
"encryptedData",
")",
";",
"checkNotNull",
"(",
"\"password\"",
",",
"password",
")",
";",
"checkNotNull",
"(",
"\"salt\"",
",",
"salt",
")",
";",
"try",
"{",
"final",
"Cipher",
"cipher",
"=",
"createCipher",
"(",
"algorithm",
",",
"Cipher",
".",
"DECRYPT_MODE",
",",
"password",
",",
"salt",
",",
"count",
")",
";",
"return",
"cipher",
".",
"doFinal",
"(",
"encryptedData",
")",
";",
"}",
"catch",
"(",
"final",
"Exception",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"\"Error decrypting the password!\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Decrypts some data based on a password.
@param algorithm
PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be <code>null</code>.
@param encryptedData
Data to decrypt - Cannot be <code>null</code>.
@param password
Password - Cannot be <code>null</code>.
@param salt
Salt usable with algorithm - Cannot be <code>null</code>.
@param count
Iterations.
@return Encrypted data.
|
[
"Decrypts",
"some",
"data",
"based",
"on",
"a",
"password",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L444-L458
|
145,392
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.createUrl
|
public static URL createUrl(final URL baseUrl, final String path, final String filename) {
checkNotNull("baseUrl", baseUrl);
checkNotNull("filename", filename);
try {
String baseUrlStr = baseUrl.toString();
if (!baseUrlStr.endsWith(SLASH)) {
baseUrlStr = baseUrlStr + SLASH;
}
final String pathStr;
if ((path == null) || (path.length() == 0)) {
pathStr = "";
} else {
if (path.endsWith(SLASH)) {
pathStr = path;
} else {
pathStr = path + SLASH;
}
}
return new URL(baseUrlStr + pathStr + filename);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
|
java
|
public static URL createUrl(final URL baseUrl, final String path, final String filename) {
checkNotNull("baseUrl", baseUrl);
checkNotNull("filename", filename);
try {
String baseUrlStr = baseUrl.toString();
if (!baseUrlStr.endsWith(SLASH)) {
baseUrlStr = baseUrlStr + SLASH;
}
final String pathStr;
if ((path == null) || (path.length() == 0)) {
pathStr = "";
} else {
if (path.endsWith(SLASH)) {
pathStr = path;
} else {
pathStr = path + SLASH;
}
}
return new URL(baseUrlStr + pathStr + filename);
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
|
[
"public",
"static",
"URL",
"createUrl",
"(",
"final",
"URL",
"baseUrl",
",",
"final",
"String",
"path",
",",
"final",
"String",
"filename",
")",
"{",
"checkNotNull",
"(",
"\"baseUrl\"",
",",
"baseUrl",
")",
";",
"checkNotNull",
"(",
"\"filename\"",
",",
"filename",
")",
";",
"try",
"{",
"String",
"baseUrlStr",
"=",
"baseUrl",
".",
"toString",
"(",
")",
";",
"if",
"(",
"!",
"baseUrlStr",
".",
"endsWith",
"(",
"SLASH",
")",
")",
"{",
"baseUrlStr",
"=",
"baseUrlStr",
"+",
"SLASH",
";",
"}",
"final",
"String",
"pathStr",
";",
"if",
"(",
"(",
"path",
"==",
"null",
")",
"||",
"(",
"path",
".",
"length",
"(",
")",
"==",
"0",
")",
")",
"{",
"pathStr",
"=",
"\"\"",
";",
"}",
"else",
"{",
"if",
"(",
"path",
".",
"endsWith",
"(",
"SLASH",
")",
")",
"{",
"pathStr",
"=",
"path",
";",
"}",
"else",
"{",
"pathStr",
"=",
"path",
"+",
"SLASH",
";",
"}",
"}",
"return",
"new",
"URL",
"(",
"baseUrlStr",
"+",
"pathStr",
"+",
"filename",
")",
";",
"}",
"catch",
"(",
"final",
"IOException",
"ex",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"ex",
")",
";",
"}",
"}"
] |
Creates an URL based on a directory a relative path and a filename.
@param baseUrl
Directory URL with or without slash ("/") at the end of the string - Cannot be <code>null</code>.
@param path
Relative path inside the base URL (with or without slash ("/") at the end of the string) - Can be <code>null</code> or an
empty string.
@param filename
Filename without path - Cannot be <code>null</code>.
@return URL.
|
[
"Creates",
"an",
"URL",
"based",
"on",
"a",
"directory",
"a",
"relative",
"path",
"and",
"a",
"filename",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L473-L495
|
145,393
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.fileInsideDirectory
|
public static boolean fileInsideDirectory(final File dir, final File file) {
checkNotNull("dir", dir);
checkNotNull("file", file);
final String dirPath = getCanonicalPath(dir);
final String filePath = getCanonicalPath(file);
return filePath.startsWith(dirPath);
}
|
java
|
public static boolean fileInsideDirectory(final File dir, final File file) {
checkNotNull("dir", dir);
checkNotNull("file", file);
final String dirPath = getCanonicalPath(dir);
final String filePath = getCanonicalPath(file);
return filePath.startsWith(dirPath);
}
|
[
"public",
"static",
"boolean",
"fileInsideDirectory",
"(",
"final",
"File",
"dir",
",",
"final",
"File",
"file",
")",
"{",
"checkNotNull",
"(",
"\"dir\"",
",",
"dir",
")",
";",
"checkNotNull",
"(",
"\"file\"",
",",
"file",
")",
";",
"final",
"String",
"dirPath",
"=",
"getCanonicalPath",
"(",
"dir",
")",
";",
"final",
"String",
"filePath",
"=",
"getCanonicalPath",
"(",
"file",
")",
";",
"return",
"filePath",
".",
"startsWith",
"(",
"dirPath",
")",
";",
"}"
] |
Checks if a given file is inside the given directory.
@param dir
Base directory - Cannot be <code>null</code>.
@param file
File - Cannot be <code>null</code>.
@return If the file is inside the directory TRUE, else FALSE.
|
[
"Checks",
"if",
"a",
"given",
"file",
"is",
"inside",
"the",
"given",
"directory",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L533-L540
|
145,394
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.addToClasspath
|
public static void addToClasspath(final URL url, final ClassLoader classLoader) {
checkNotNull("url", url);
checkNotNull("classLoader", classLoader);
if (!(classLoader instanceof URLClassLoader)) {
throw new IllegalArgumentException("Cannot add '" + url + "' to classloader because it's not an URL classloader");
}
final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
if (!containsURL(urlClassLoader.getURLs(), url)) {
try {
final Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
addURL.setAccessible(true);
addURL.invoke(urlClassLoader, new Object[] { url });
} catch (final NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (final IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
} catch (final InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
|
java
|
public static void addToClasspath(final URL url, final ClassLoader classLoader) {
checkNotNull("url", url);
checkNotNull("classLoader", classLoader);
if (!(classLoader instanceof URLClassLoader)) {
throw new IllegalArgumentException("Cannot add '" + url + "' to classloader because it's not an URL classloader");
}
final URLClassLoader urlClassLoader = (URLClassLoader) classLoader;
if (!containsURL(urlClassLoader.getURLs(), url)) {
try {
final Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
addURL.setAccessible(true);
addURL.invoke(urlClassLoader, new Object[] { url });
} catch (final NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (final IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (final IllegalAccessException e) {
throw new RuntimeException(e);
} catch (final InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
|
[
"public",
"static",
"void",
"addToClasspath",
"(",
"final",
"URL",
"url",
",",
"final",
"ClassLoader",
"classLoader",
")",
"{",
"checkNotNull",
"(",
"\"url\"",
",",
"url",
")",
";",
"checkNotNull",
"(",
"\"classLoader\"",
",",
"classLoader",
")",
";",
"if",
"(",
"!",
"(",
"classLoader",
"instanceof",
"URLClassLoader",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Cannot add '\"",
"+",
"url",
"+",
"\"' to classloader because it's not an URL classloader\"",
")",
";",
"}",
"final",
"URLClassLoader",
"urlClassLoader",
"=",
"(",
"URLClassLoader",
")",
"classLoader",
";",
"if",
"(",
"!",
"containsURL",
"(",
"urlClassLoader",
".",
"getURLs",
"(",
")",
",",
"url",
")",
")",
"{",
"try",
"{",
"final",
"Method",
"addURL",
"=",
"URLClassLoader",
".",
"class",
".",
"getDeclaredMethod",
"(",
"\"addURL\"",
",",
"new",
"Class",
"[",
"]",
"{",
"URL",
".",
"class",
"}",
")",
";",
"addURL",
".",
"setAccessible",
"(",
"true",
")",
";",
"addURL",
".",
"invoke",
"(",
"urlClassLoader",
",",
"new",
"Object",
"[",
"]",
"{",
"url",
"}",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchMethodException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalAccessException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"catch",
"(",
"final",
"InvocationTargetException",
"e",
")",
"{",
"throw",
"new",
"RuntimeException",
"(",
"e",
")",
";",
"}",
"}",
"}"
] |
Adds an URL to the class path.
@param url
URL to add - Cannot be <code>null</code>.
@param classLoader
Class loader to use - Cannot be <code>null</code>.
|
[
"Adds",
"an",
"URL",
"to",
"the",
"class",
"path",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L634-L657
|
145,395
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.invoke
|
public static Object invoke(final Object obj, final String methodName, final Class<?>[] argTypes, final Object[] args)
throws InvokeMethodFailedException {
checkNotNull("obj", obj);
checkNotNull("methodName", methodName);
final Class<?>[] argTypesIntern;
final Object[] argsIntern;
if (argTypes == null) {
argTypesIntern = new Class[] {};
if (args != null) {
throw new IllegalArgumentException("The argument 'argTypes' is null but " + "'args' containes values!");
}
argsIntern = new Object[] {};
} else {
argTypesIntern = argTypes;
if (args == null) {
throw new IllegalArgumentException("The argument 'argTypes' contains classes " + "but 'args' is null!");
}
argsIntern = args;
}
checkSameLength(argTypesIntern, argsIntern);
String returnType = null;
try {
final Method method = obj.getClass().getMethod(methodName, argTypesIntern);
if (method.getReturnType() == null) {
returnType = "void";
} else {
returnType = method.getReturnType().getName();
}
return method.invoke(obj, argsIntern);
} catch (final SecurityException ex) {
throw new InvokeMethodFailedException("Security problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final NoSuchMethodException ex) {
throw new InvokeMethodFailedException("Method '" + getMethodSignature(returnType, methodName, argTypesIntern) + "' not found! ["
+ obj.getClass().getName() + "]", ex);
} catch (final IllegalArgumentException ex) {
throw new InvokeMethodFailedException("Argument problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final IllegalAccessException ex) {
throw new InvokeMethodFailedException("Access problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final InvocationTargetException ex) {
throw new InvokeMethodFailedException("Got an exception when calling '"
+ getMethodSignature(returnType, methodName, argTypesIntern) + "'! [" + obj.getClass().getName() + "]", ex);
}
}
|
java
|
public static Object invoke(final Object obj, final String methodName, final Class<?>[] argTypes, final Object[] args)
throws InvokeMethodFailedException {
checkNotNull("obj", obj);
checkNotNull("methodName", methodName);
final Class<?>[] argTypesIntern;
final Object[] argsIntern;
if (argTypes == null) {
argTypesIntern = new Class[] {};
if (args != null) {
throw new IllegalArgumentException("The argument 'argTypes' is null but " + "'args' containes values!");
}
argsIntern = new Object[] {};
} else {
argTypesIntern = argTypes;
if (args == null) {
throw new IllegalArgumentException("The argument 'argTypes' contains classes " + "but 'args' is null!");
}
argsIntern = args;
}
checkSameLength(argTypesIntern, argsIntern);
String returnType = null;
try {
final Method method = obj.getClass().getMethod(methodName, argTypesIntern);
if (method.getReturnType() == null) {
returnType = "void";
} else {
returnType = method.getReturnType().getName();
}
return method.invoke(obj, argsIntern);
} catch (final SecurityException ex) {
throw new InvokeMethodFailedException("Security problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final NoSuchMethodException ex) {
throw new InvokeMethodFailedException("Method '" + getMethodSignature(returnType, methodName, argTypesIntern) + "' not found! ["
+ obj.getClass().getName() + "]", ex);
} catch (final IllegalArgumentException ex) {
throw new InvokeMethodFailedException("Argument problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final IllegalAccessException ex) {
throw new InvokeMethodFailedException("Access problem with '" + getMethodSignature(returnType, methodName, argTypesIntern)
+ "'! [" + obj.getClass().getName() + "]", ex);
} catch (final InvocationTargetException ex) {
throw new InvokeMethodFailedException("Got an exception when calling '"
+ getMethodSignature(returnType, methodName, argTypesIntern) + "'! [" + obj.getClass().getName() + "]", ex);
}
}
|
[
"public",
"static",
"Object",
"invoke",
"(",
"final",
"Object",
"obj",
",",
"final",
"String",
"methodName",
",",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"argTypes",
",",
"final",
"Object",
"[",
"]",
"args",
")",
"throws",
"InvokeMethodFailedException",
"{",
"checkNotNull",
"(",
"\"obj\"",
",",
"obj",
")",
";",
"checkNotNull",
"(",
"\"methodName\"",
",",
"methodName",
")",
";",
"final",
"Class",
"<",
"?",
">",
"[",
"]",
"argTypesIntern",
";",
"final",
"Object",
"[",
"]",
"argsIntern",
";",
"if",
"(",
"argTypes",
"==",
"null",
")",
"{",
"argTypesIntern",
"=",
"new",
"Class",
"[",
"]",
"{",
"}",
";",
"if",
"(",
"args",
"!=",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'argTypes' is null but \"",
"+",
"\"'args' containes values!\"",
")",
";",
"}",
"argsIntern",
"=",
"new",
"Object",
"[",
"]",
"{",
"}",
";",
"}",
"else",
"{",
"argTypesIntern",
"=",
"argTypes",
";",
"if",
"(",
"args",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"The argument 'argTypes' contains classes \"",
"+",
"\"but 'args' is null!\"",
")",
";",
"}",
"argsIntern",
"=",
"args",
";",
"}",
"checkSameLength",
"(",
"argTypesIntern",
",",
"argsIntern",
")",
";",
"String",
"returnType",
"=",
"null",
";",
"try",
"{",
"final",
"Method",
"method",
"=",
"obj",
".",
"getClass",
"(",
")",
".",
"getMethod",
"(",
"methodName",
",",
"argTypesIntern",
")",
";",
"if",
"(",
"method",
".",
"getReturnType",
"(",
")",
"==",
"null",
")",
"{",
"returnType",
"=",
"\"void\"",
";",
"}",
"else",
"{",
"returnType",
"=",
"method",
".",
"getReturnType",
"(",
")",
".",
"getName",
"(",
")",
";",
"}",
"return",
"method",
".",
"invoke",
"(",
"obj",
",",
"argsIntern",
")",
";",
"}",
"catch",
"(",
"final",
"SecurityException",
"ex",
")",
"{",
"throw",
"new",
"InvokeMethodFailedException",
"(",
"\"Security problem with '\"",
"+",
"getMethodSignature",
"(",
"returnType",
",",
"methodName",
",",
"argTypesIntern",
")",
"+",
"\"'! [\"",
"+",
"obj",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"]\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"final",
"NoSuchMethodException",
"ex",
")",
"{",
"throw",
"new",
"InvokeMethodFailedException",
"(",
"\"Method '\"",
"+",
"getMethodSignature",
"(",
"returnType",
",",
"methodName",
",",
"argTypesIntern",
")",
"+",
"\"' not found! [\"",
"+",
"obj",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"]\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalArgumentException",
"ex",
")",
"{",
"throw",
"new",
"InvokeMethodFailedException",
"(",
"\"Argument problem with '\"",
"+",
"getMethodSignature",
"(",
"returnType",
",",
"methodName",
",",
"argTypesIntern",
")",
"+",
"\"'! [\"",
"+",
"obj",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"]\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"final",
"IllegalAccessException",
"ex",
")",
"{",
"throw",
"new",
"InvokeMethodFailedException",
"(",
"\"Access problem with '\"",
"+",
"getMethodSignature",
"(",
"returnType",
",",
"methodName",
",",
"argTypesIntern",
")",
"+",
"\"'! [\"",
"+",
"obj",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"]\"",
",",
"ex",
")",
";",
"}",
"catch",
"(",
"final",
"InvocationTargetException",
"ex",
")",
"{",
"throw",
"new",
"InvokeMethodFailedException",
"(",
"\"Got an exception when calling '\"",
"+",
"getMethodSignature",
"(",
"returnType",
",",
"methodName",
",",
"argTypesIntern",
")",
"+",
"\"'! [\"",
"+",
"obj",
".",
"getClass",
"(",
")",
".",
"getName",
"(",
")",
"+",
"\"]\"",
",",
"ex",
")",
";",
"}",
"}"
] |
Calls a method with reflection and maps all errors into one exception.
@param obj
The object the underlying method is invoked from - Cannot be <code>null</code>.
@param methodName
Name of the Method - Cannot be <code>null</code>.
@param argTypes
The list of parameters - May be <code>null</code>.
@param args
Arguments the arguments used for the method call - May be <code>null</code> if "argTypes" is also <code>null</code>.
@return The result of dispatching the method represented by this object on <code>obj</code> with parameters <code>args</code>.
@throws InvokeMethodFailedException
Invoking the method failed for some reason.
|
[
"Calls",
"a",
"method",
"with",
"reflection",
"and",
"maps",
"all",
"errors",
"into",
"one",
"exception",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L737-L786
|
145,396
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.replaceVars
|
public static String replaceVars(final String str, final Map<String, String> vars) {
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
}
|
java
|
public static String replaceVars(final String str, final Map<String, String> vars) {
if ((str == null) || (str.length() == 0) || (vars == null) || (vars.size() == 0)) {
return str;
}
final StringBuilder sb = new StringBuilder();
int end = -1;
int from = 0;
int start = -1;
while ((start = str.indexOf("${", from)) > -1) {
sb.append(str.substring(end + 1, start));
end = str.indexOf('}', start + 1);
if (end == -1) {
// No closing bracket found...
sb.append(str.substring(start));
from = str.length();
} else {
final String key = str.substring(start + 2, end);
final String value = (String) vars.get(key);
if (value == null) {
sb.append("${");
sb.append(key);
sb.append("}");
} else {
sb.append(value);
}
from = end + 1;
}
}
sb.append(str.substring(from));
return sb.toString();
}
|
[
"public",
"static",
"String",
"replaceVars",
"(",
"final",
"String",
"str",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"vars",
")",
"{",
"if",
"(",
"(",
"str",
"==",
"null",
")",
"||",
"(",
"str",
".",
"length",
"(",
")",
"==",
"0",
")",
"||",
"(",
"vars",
"==",
"null",
")",
"||",
"(",
"vars",
".",
"size",
"(",
")",
"==",
"0",
")",
")",
"{",
"return",
"str",
";",
"}",
"final",
"StringBuilder",
"sb",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"int",
"end",
"=",
"-",
"1",
";",
"int",
"from",
"=",
"0",
";",
"int",
"start",
"=",
"-",
"1",
";",
"while",
"(",
"(",
"start",
"=",
"str",
".",
"indexOf",
"(",
"\"${\"",
",",
"from",
")",
")",
">",
"-",
"1",
")",
"{",
"sb",
".",
"append",
"(",
"str",
".",
"substring",
"(",
"end",
"+",
"1",
",",
"start",
")",
")",
";",
"end",
"=",
"str",
".",
"indexOf",
"(",
"'",
"'",
",",
"start",
"+",
"1",
")",
";",
"if",
"(",
"end",
"==",
"-",
"1",
")",
"{",
"// No closing bracket found...\r",
"sb",
".",
"append",
"(",
"str",
".",
"substring",
"(",
"start",
")",
")",
";",
"from",
"=",
"str",
".",
"length",
"(",
")",
";",
"}",
"else",
"{",
"final",
"String",
"key",
"=",
"str",
".",
"substring",
"(",
"start",
"+",
"2",
",",
"end",
")",
";",
"final",
"String",
"value",
"=",
"(",
"String",
")",
"vars",
".",
"get",
"(",
"key",
")",
";",
"if",
"(",
"value",
"==",
"null",
")",
"{",
"sb",
".",
"append",
"(",
"\"${\"",
")",
";",
"sb",
".",
"append",
"(",
"key",
")",
";",
"sb",
".",
"append",
"(",
"\"}\"",
")",
";",
"}",
"else",
"{",
"sb",
".",
"append",
"(",
"value",
")",
";",
"}",
"from",
"=",
"end",
"+",
"1",
";",
"}",
"}",
"sb",
".",
"append",
"(",
"str",
".",
"substring",
"(",
"from",
")",
")",
";",
"return",
"sb",
".",
"toString",
"(",
")",
";",
"}"
] |
Replaces all variables inside a string with values from a map.
@param str
Text with variables (Format: ${key} ) - May be <code>null</code> or empty.
@param vars
Map with key/values (both of type <code>String</code> - May be <code>null</code>.
@return String with replaced variables. Unknown variables will remain unchanged.
|
[
"Replaces",
"all",
"variables",
"inside",
"a",
"string",
"with",
"values",
"from",
"a",
"map",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L929-L964
|
145,397
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.zipFile
|
private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out) throws IOException {
final byte[] buf = new byte[1024];
try (final InputStream in = new BufferedInputStream(new FileInputStream(srcFile))) {
final ZipEntry zipEntry = new ZipEntry(concatPathAndFilename(destPath, srcFile.getName(), File.separator));
zipEntry.setTime(srcFile.lastModified());
out.putNextEntry(zipEntry);
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
}
}
|
java
|
private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out) throws IOException {
final byte[] buf = new byte[1024];
try (final InputStream in = new BufferedInputStream(new FileInputStream(srcFile))) {
final ZipEntry zipEntry = new ZipEntry(concatPathAndFilename(destPath, srcFile.getName(), File.separator));
zipEntry.setTime(srcFile.lastModified());
out.putNextEntry(zipEntry);
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
}
}
|
[
"private",
"static",
"void",
"zipFile",
"(",
"final",
"File",
"srcFile",
",",
"final",
"String",
"destPath",
",",
"final",
"ZipOutputStream",
"out",
")",
"throws",
"IOException",
"{",
"final",
"byte",
"[",
"]",
"buf",
"=",
"new",
"byte",
"[",
"1024",
"]",
";",
"try",
"(",
"final",
"InputStream",
"in",
"=",
"new",
"BufferedInputStream",
"(",
"new",
"FileInputStream",
"(",
"srcFile",
")",
")",
")",
"{",
"final",
"ZipEntry",
"zipEntry",
"=",
"new",
"ZipEntry",
"(",
"concatPathAndFilename",
"(",
"destPath",
",",
"srcFile",
".",
"getName",
"(",
")",
",",
"File",
".",
"separator",
")",
")",
";",
"zipEntry",
".",
"setTime",
"(",
"srcFile",
".",
"lastModified",
"(",
")",
")",
";",
"out",
".",
"putNextEntry",
"(",
"zipEntry",
")",
";",
"int",
"len",
";",
"while",
"(",
"(",
"len",
"=",
"in",
".",
"read",
"(",
"buf",
")",
")",
">",
"0",
")",
"{",
"out",
".",
"write",
"(",
"buf",
",",
"0",
",",
"len",
")",
";",
"}",
"out",
".",
"closeEntry",
"(",
")",
";",
"}",
"}"
] |
Adds a file to a ZIP output stream.
@param srcFile
File to add - Cannot be <code>null</code>.
@param destPath
Path to use for the file - May be <code>null</code> or empty.
@param out
Destination stream - Cannot be <code>null</code>.
@throws IOException
Error writing to the output stream.
|
[
"Adds",
"a",
"file",
"to",
"a",
"ZIP",
"output",
"stream",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L1297-L1310
|
145,398
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.listFiles
|
private static File[] listFiles(final File srcDir, final FileFilter filter) {
final File[] files;
if (filter == null) {
files = srcDir.listFiles();
} else {
files = srcDir.listFiles(filter);
}
return files;
}
|
java
|
private static File[] listFiles(final File srcDir, final FileFilter filter) {
final File[] files;
if (filter == null) {
files = srcDir.listFiles();
} else {
files = srcDir.listFiles(filter);
}
return files;
}
|
[
"private",
"static",
"File",
"[",
"]",
"listFiles",
"(",
"final",
"File",
"srcDir",
",",
"final",
"FileFilter",
"filter",
")",
"{",
"final",
"File",
"[",
"]",
"files",
";",
"if",
"(",
"filter",
"==",
"null",
")",
"{",
"files",
"=",
"srcDir",
".",
"listFiles",
"(",
")",
";",
"}",
"else",
"{",
"files",
"=",
"srcDir",
".",
"listFiles",
"(",
"filter",
")",
";",
"}",
"return",
"files",
";",
"}"
] |
List all files for a directory.
@param srcDir
Directory to list the files for - Cannot be <code>null</code> and must be a valid directory.
@param filter
Filter or <code>null</code> for all files.
@return List of child entries of the directory.
|
[
"List",
"all",
"files",
"for",
"a",
"directory",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L1322-L1332
|
145,399
|
fuinorg/utils4j
|
src/main/java/org/fuin/utils4j/Utils4J.java
|
Utils4J.zipDir
|
private static void zipDir(final File srcDir, final FileFilter filter, final String destPath, final ZipOutputStream out)
throws IOException {
final File[] files = listFiles(srcDir, filter);
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
zipDir(files[i], filter, concatPathAndFilename(destPath, files[i].getName(), File.separator), out);
} else {
zipFile(files[i], destPath, out);
}
}
}
|
java
|
private static void zipDir(final File srcDir, final FileFilter filter, final String destPath, final ZipOutputStream out)
throws IOException {
final File[] files = listFiles(srcDir, filter);
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
zipDir(files[i], filter, concatPathAndFilename(destPath, files[i].getName(), File.separator), out);
} else {
zipFile(files[i], destPath, out);
}
}
}
|
[
"private",
"static",
"void",
"zipDir",
"(",
"final",
"File",
"srcDir",
",",
"final",
"FileFilter",
"filter",
",",
"final",
"String",
"destPath",
",",
"final",
"ZipOutputStream",
"out",
")",
"throws",
"IOException",
"{",
"final",
"File",
"[",
"]",
"files",
"=",
"listFiles",
"(",
"srcDir",
",",
"filter",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"files",
".",
"length",
";",
"i",
"++",
")",
"{",
"if",
"(",
"files",
"[",
"i",
"]",
".",
"isDirectory",
"(",
")",
")",
"{",
"zipDir",
"(",
"files",
"[",
"i",
"]",
",",
"filter",
",",
"concatPathAndFilename",
"(",
"destPath",
",",
"files",
"[",
"i",
"]",
".",
"getName",
"(",
")",
",",
"File",
".",
"separator",
")",
",",
"out",
")",
";",
"}",
"else",
"{",
"zipFile",
"(",
"files",
"[",
"i",
"]",
",",
"destPath",
",",
"out",
")",
";",
"}",
"}",
"}"
] |
Add a directory to a ZIP output stream.
@param srcDir
Directory to add - Cannot be <code>null</code> and must be a valid directory.
@param filter
Filter or <code>null</code> for all files.
@param destPath
Path to use for the ZIP archive - May be <code>null</code> or an empyt string.
@param out
Destination stream - Cannot be <code>null</code>.
@throws IOException
Error writing to the output stream.
|
[
"Add",
"a",
"directory",
"to",
"a",
"ZIP",
"output",
"stream",
"."
] |
71cf88e0a8d8ed67bbac513bf3cab165cd7e3280
|
https://github.com/fuinorg/utils4j/blob/71cf88e0a8d8ed67bbac513bf3cab165cd7e3280/src/main/java/org/fuin/utils4j/Utils4J.java#L1349-L1361
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.