repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
buschmais/jqa-maven3-plugin | src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java | MavenModelScannerPlugin.addDevelopers | private void addDevelopers(MavenPomDescriptor pomDescriptor, Model model, Store store) {
List<Developer> developers = model.getDevelopers();
for (Developer developer : developers) {
MavenDeveloperDescriptor developerDescriptor = store.create(MavenDeveloperDescriptor.class);
developerDescriptor.setId(developer.getId());
addCommonParticipantAttributes(developerDescriptor, developer, store);
pomDescriptor.getDevelopers().add(developerDescriptor);
}
} | java | private void addDevelopers(MavenPomDescriptor pomDescriptor, Model model, Store store) {
List<Developer> developers = model.getDevelopers();
for (Developer developer : developers) {
MavenDeveloperDescriptor developerDescriptor = store.create(MavenDeveloperDescriptor.class);
developerDescriptor.setId(developer.getId());
addCommonParticipantAttributes(developerDescriptor, developer, store);
pomDescriptor.getDevelopers().add(developerDescriptor);
}
} | [
"private",
"void",
"addDevelopers",
"(",
"MavenPomDescriptor",
"pomDescriptor",
",",
"Model",
"model",
",",
"Store",
"store",
")",
"{",
"List",
"<",
"Developer",
">",
"developers",
"=",
"model",
".",
"getDevelopers",
"(",
")",
";",
"for",
"(",
"Developer",
"... | Adds information about developers.
@param pomDescriptor
The descriptor for the current POM.
@param model
The Maven Model.
@param store
The database. | [
"Adds",
"information",
"about",
"developers",
"."
] | train | https://github.com/buschmais/jqa-maven3-plugin/blob/6c6e2dca56de6d5b8ceeb2f28982fb6d7c98778f/src/main/java/com/buschmais/jqassistant/plugin/maven3/impl/scanner/MavenModelScannerPlugin.java#L361-L371 |
Canadensys/canadensys-core | src/main/java/net/canadensys/utils/LangUtils.java | LangUtils.getClassAnnotationValue | public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) {
String value = null;
Annotation annotation = classType.getAnnotation(annotationType);
if (annotation != null) {
try {
value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);
} catch (Exception ex) {}
}
return value;
} | java | public static <T, A extends Annotation> String getClassAnnotationValue(Class<T> classType, Class<A> annotationType, String attributeName) {
String value = null;
Annotation annotation = classType.getAnnotation(annotationType);
if (annotation != null) {
try {
value = (String) annotation.annotationType().getMethod(attributeName).invoke(annotation);
} catch (Exception ex) {}
}
return value;
} | [
"public",
"static",
"<",
"T",
",",
"A",
"extends",
"Annotation",
">",
"String",
"getClassAnnotationValue",
"(",
"Class",
"<",
"T",
">",
"classType",
",",
"Class",
"<",
"A",
">",
"annotationType",
",",
"String",
"attributeName",
")",
"{",
"String",
"value",
... | Get the value of a Annotation in a class declaration.
@param classType
@param annotationType
@param attributeName
@return the value of the annotation as String or null if something goes wrong | [
"Get",
"the",
"value",
"of",
"a",
"Annotation",
"in",
"a",
"class",
"declaration",
"."
] | train | https://github.com/Canadensys/canadensys-core/blob/5e13569f7c0f4cdc7080da72643ff61123ad76fd/src/main/java/net/canadensys/utils/LangUtils.java#L19-L28 |
netty/netty | common/src/main/java/io/netty/util/internal/NativeLibraryUtil.java | NativeLibraryUtil.loadLibrary | public static void loadLibrary(String libName, boolean absolute) {
if (absolute) {
System.load(libName);
} else {
System.loadLibrary(libName);
}
} | java | public static void loadLibrary(String libName, boolean absolute) {
if (absolute) {
System.load(libName);
} else {
System.loadLibrary(libName);
}
} | [
"public",
"static",
"void",
"loadLibrary",
"(",
"String",
"libName",
",",
"boolean",
"absolute",
")",
"{",
"if",
"(",
"absolute",
")",
"{",
"System",
".",
"load",
"(",
"libName",
")",
";",
"}",
"else",
"{",
"System",
".",
"loadLibrary",
"(",
"libName",
... | Delegate the calling to {@link System#load(String)} or {@link System#loadLibrary(String)}.
@param libName - The native library path or name
@param absolute - Whether the native library will be loaded by path or by name | [
"Delegate",
"the",
"calling",
"to",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/common/src/main/java/io/netty/util/internal/NativeLibraryUtil.java#L34-L40 |
sarl/sarl | main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/extralanguage/preferences/ExtraLanguagePreferenceAccess.java | ExtraLanguagePreferenceAccess.getString | public String getString(String preferenceContainerID, IProject project, String preferenceName) {
final IProject prj = ifSpecificConfiguration(preferenceContainerID, project);
final IPreferenceStore store = getPreferenceStore(prj);
return getString(store, preferenceContainerID, preferenceName);
} | java | public String getString(String preferenceContainerID, IProject project, String preferenceName) {
final IProject prj = ifSpecificConfiguration(preferenceContainerID, project);
final IPreferenceStore store = getPreferenceStore(prj);
return getString(store, preferenceContainerID, preferenceName);
} | [
"public",
"String",
"getString",
"(",
"String",
"preferenceContainerID",
",",
"IProject",
"project",
",",
"String",
"preferenceName",
")",
"{",
"final",
"IProject",
"prj",
"=",
"ifSpecificConfiguration",
"(",
"preferenceContainerID",
",",
"project",
")",
";",
"final... | Replies the preference value.
<p>This function takes care of the specific options that are associated to the given project.
If the given project is {@code null} or has no specific options, according to
{@link #ifSpecificConfiguration(String, IProject)}, then the global preferences are used.
@param preferenceContainerID the identifier of the generator's preference container.
@param project the context. If {@code null}, the global context is assumed.
@param preferenceName the name of the preference.
@return the value.
@since 0.8 | [
"Replies",
"the",
"preference",
"value",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.ui/src/io/sarl/lang/ui/extralanguage/preferences/ExtraLanguagePreferenceAccess.java#L138-L142 |
hdecarne/java-default | src/main/java/de/carne/util/Strings.java | Strings.encodeHtml | public static StringBuilder encodeHtml(StringBuilder buffer, CharSequence chars) {
chars.chars().forEach(c -> {
switch (c) {
case '<':
buffer.append("<");
break;
case '>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
case '"':
buffer.append(""");
break;
case '\'':
buffer.append("'");
break;
default:
if (Character.isAlphabetic(c)) {
buffer.append((char) c);
} else {
buffer.append("&#").append(c).append(';');
}
}
});
return buffer;
} | java | public static StringBuilder encodeHtml(StringBuilder buffer, CharSequence chars) {
chars.chars().forEach(c -> {
switch (c) {
case '<':
buffer.append("<");
break;
case '>':
buffer.append(">");
break;
case '&':
buffer.append("&");
break;
case '"':
buffer.append(""");
break;
case '\'':
buffer.append("'");
break;
default:
if (Character.isAlphabetic(c)) {
buffer.append((char) c);
} else {
buffer.append("&#").append(c).append(';');
}
}
});
return buffer;
} | [
"public",
"static",
"StringBuilder",
"encodeHtml",
"(",
"StringBuilder",
"buffer",
",",
"CharSequence",
"chars",
")",
"{",
"chars",
".",
"chars",
"(",
")",
".",
"forEach",
"(",
"c",
"->",
"{",
"switch",
"(",
"c",
")",
"{",
"case",
"'",
"'",
":",
"buffe... | Encodes a {@linkplain CharSequence} to a HTML conform representation by quoting special characters.
@param buffer the {@linkplain StringBuilder} to encode into.
@param chars the {@linkplain CharSequence} to encode.
@return the encoded characters. | [
"Encodes",
"a",
"{",
"@linkplain",
"CharSequence",
"}",
"to",
"a",
"HTML",
"conform",
"representation",
"by",
"quoting",
"special",
"characters",
"."
] | train | https://github.com/hdecarne/java-default/blob/ca16f6fdb0436e90e9e2df3106055e320bb3c9e3/src/main/java/de/carne/util/Strings.java#L424-L451 |
jmxtrans/jmxtrans | jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java | Server.getEnvironment | @JsonIgnore
public ImmutableMap<String, ?> getEnvironment() {
if (getProtocolProviderPackages() != null && getProtocolProviderPackages().contains("weblogic")) {
ImmutableMap.Builder<String, String> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
environment.put(PROTOCOL_PROVIDER_PACKAGES, getProtocolProviderPackages());
environment.put(SECURITY_PRINCIPAL, username);
environment.put(SECURITY_CREDENTIALS, password);
}
return environment.build();
}
ImmutableMap.Builder<String, Object> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
String[] credentials = new String[] {
username,
password
};
environment.put(JMXConnector.CREDENTIALS, credentials);
}
JmxTransRMIClientSocketFactory rmiClientSocketFactory = new JmxTransRMIClientSocketFactory(DEFAULT_SOCKET_SO_TIMEOUT_MILLIS, ssl);
// The following is required when JMX is secured with SSL
// with com.sun.management.jmxremote.ssl=true
// as shown in http://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html#gdfvq
environment.put(RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, rmiClientSocketFactory);
// The following is required when JNDI Registry is secured with SSL
// with com.sun.management.jmxremote.registry.ssl=true
// This property is defined in com.sun.jndi.rmi.registry.RegistryContext.SOCKET_FACTORY
environment.put("com.sun.jndi.rmi.factory.socket", rmiClientSocketFactory);
return environment.build();
} | java | @JsonIgnore
public ImmutableMap<String, ?> getEnvironment() {
if (getProtocolProviderPackages() != null && getProtocolProviderPackages().contains("weblogic")) {
ImmutableMap.Builder<String, String> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
environment.put(PROTOCOL_PROVIDER_PACKAGES, getProtocolProviderPackages());
environment.put(SECURITY_PRINCIPAL, username);
environment.put(SECURITY_CREDENTIALS, password);
}
return environment.build();
}
ImmutableMap.Builder<String, Object> environment = ImmutableMap.builder();
if ((username != null) && (password != null)) {
String[] credentials = new String[] {
username,
password
};
environment.put(JMXConnector.CREDENTIALS, credentials);
}
JmxTransRMIClientSocketFactory rmiClientSocketFactory = new JmxTransRMIClientSocketFactory(DEFAULT_SOCKET_SO_TIMEOUT_MILLIS, ssl);
// The following is required when JMX is secured with SSL
// with com.sun.management.jmxremote.ssl=true
// as shown in http://docs.oracle.com/javase/8/docs/technotes/guides/management/agent.html#gdfvq
environment.put(RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, rmiClientSocketFactory);
// The following is required when JNDI Registry is secured with SSL
// with com.sun.management.jmxremote.registry.ssl=true
// This property is defined in com.sun.jndi.rmi.registry.RegistryContext.SOCKET_FACTORY
environment.put("com.sun.jndi.rmi.factory.socket", rmiClientSocketFactory);
return environment.build();
} | [
"@",
"JsonIgnore",
"public",
"ImmutableMap",
"<",
"String",
",",
"?",
">",
"getEnvironment",
"(",
")",
"{",
"if",
"(",
"getProtocolProviderPackages",
"(",
")",
"!=",
"null",
"&&",
"getProtocolProviderPackages",
"(",
")",
".",
"contains",
"(",
"\"weblogic\"",
"... | Generates the proper username/password environment for JMX connections. | [
"Generates",
"the",
"proper",
"username",
"/",
"password",
"environment",
"for",
"JMX",
"connections",
"."
] | train | https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/model/Server.java#L305-L337 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java | UtilColor.getWeightedColor | public static ColorRgba getWeightedColor(ImageBuffer surface, int sx, int sy, int width, int height)
{
Check.notNull(surface);
int r = 0;
int g = 0;
int b = 0;
int count = 0;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
final ColorRgba color = new ColorRgba(surface.getRgb(sx + x, sy + y));
if (color.getAlpha() > 0)
{
r += color.getRed();
g += color.getGreen();
b += color.getBlue();
count++;
}
}
}
if (count == 0)
{
return ColorRgba.TRANSPARENT;
}
return new ColorRgba((int) Math.floor(r / (double) count),
(int) Math.floor(g / (double) count),
(int) Math.floor(b / (double) count));
} | java | public static ColorRgba getWeightedColor(ImageBuffer surface, int sx, int sy, int width, int height)
{
Check.notNull(surface);
int r = 0;
int g = 0;
int b = 0;
int count = 0;
for (int x = 0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
final ColorRgba color = new ColorRgba(surface.getRgb(sx + x, sy + y));
if (color.getAlpha() > 0)
{
r += color.getRed();
g += color.getGreen();
b += color.getBlue();
count++;
}
}
}
if (count == 0)
{
return ColorRgba.TRANSPARENT;
}
return new ColorRgba((int) Math.floor(r / (double) count),
(int) Math.floor(g / (double) count),
(int) Math.floor(b / (double) count));
} | [
"public",
"static",
"ColorRgba",
"getWeightedColor",
"(",
"ImageBuffer",
"surface",
",",
"int",
"sx",
",",
"int",
"sy",
",",
"int",
"width",
",",
"int",
"height",
")",
"{",
"Check",
".",
"notNull",
"(",
"surface",
")",
";",
"int",
"r",
"=",
"0",
";",
... | Get the weighted color of an area.
@param surface The surface reference (must not be <code>null</code>).
@param sx The starting horizontal location.
@param sy The starting vertical location.
@param width The area width.
@param height The area height.
@return The weighted color. | [
"Get",
"the",
"weighted",
"color",
"of",
"an",
"area",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/UtilColor.java#L119-L148 |
tomgibara/bits | src/main/java/com/tomgibara/bits/LongBitStore.java | LongBitStore.writeBits | static void writeBits(WriteStream writer, long bits, int count) {
for (int i = (count - 1) & ~7; i >= 0; i -= 8) {
writer.writeByte((byte) (bits >>> i));
}
} | java | static void writeBits(WriteStream writer, long bits, int count) {
for (int i = (count - 1) & ~7; i >= 0; i -= 8) {
writer.writeByte((byte) (bits >>> i));
}
} | [
"static",
"void",
"writeBits",
"(",
"WriteStream",
"writer",
",",
"long",
"bits",
",",
"int",
"count",
")",
"{",
"for",
"(",
"int",
"i",
"=",
"(",
"count",
"-",
"1",
")",
"&",
"~",
"7",
";",
"i",
">=",
"0",
";",
"i",
"-=",
"8",
")",
"{",
"wri... | not does not mask off the supplied long - that is responsibility of caller | [
"not",
"does",
"not",
"mask",
"off",
"the",
"supplied",
"long",
"-",
"that",
"is",
"responsibility",
"of",
"caller"
] | train | https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/LongBitStore.java#L58-L62 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_easyPabx_serviceName_PUT | public void billingAccount_easyPabx_serviceName_PUT(String billingAccount, String serviceName, OvhEasyPabx body) throws IOException {
String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | java | public void billingAccount_easyPabx_serviceName_PUT(String billingAccount, String serviceName, OvhEasyPabx body) throws IOException {
String qPath = "/telephony/{billingAccount}/easyPabx/{serviceName}";
StringBuilder sb = path(qPath, billingAccount, serviceName);
exec(qPath, "PUT", sb.toString(), body);
} | [
"public",
"void",
"billingAccount_easyPabx_serviceName_PUT",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"OvhEasyPabx",
"body",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/easyPabx/{serviceName}\"",
";",
... | Alter this object properties
REST: PUT /telephony/{billingAccount}/easyPabx/{serviceName}
@param body [required] New object properties
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"Alter",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L3649-L3653 |
igniterealtime/Smack | smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java | JmfMediaManager.setupJMF | public static void setupJMF() {
// .jmf is the place where we store the jmf.properties file used
// by JMF. if the directory does not exist or it does not contain
// a jmf.properties file. or if the jmf.properties file has 0 length
// then this is the first time we're running and should continue to
// with JMFInit
String homeDir = System.getProperty("user.home");
File jmfDir = new File(homeDir, ".jmf");
String classpath = System.getProperty("java.class.path");
classpath += System.getProperty("path.separator")
+ jmfDir.getAbsolutePath();
System.setProperty("java.class.path", classpath);
if (!jmfDir.exists())
jmfDir.mkdir();
File jmfProperties = new File(jmfDir, "jmf.properties");
if (!jmfProperties.exists()) {
try {
jmfProperties.createNewFile();
}
catch (IOException ex) {
LOGGER.log(Level.FINE, "Failed to create jmf.properties", ex);
}
}
// if we're running on linux checkout that libjmutil.so is where it
// should be and put it there.
runLinuxPreInstall();
// if (jmfProperties.length() == 0) {
new JMFInit(null, false);
// }
} | java | public static void setupJMF() {
// .jmf is the place where we store the jmf.properties file used
// by JMF. if the directory does not exist or it does not contain
// a jmf.properties file. or if the jmf.properties file has 0 length
// then this is the first time we're running and should continue to
// with JMFInit
String homeDir = System.getProperty("user.home");
File jmfDir = new File(homeDir, ".jmf");
String classpath = System.getProperty("java.class.path");
classpath += System.getProperty("path.separator")
+ jmfDir.getAbsolutePath();
System.setProperty("java.class.path", classpath);
if (!jmfDir.exists())
jmfDir.mkdir();
File jmfProperties = new File(jmfDir, "jmf.properties");
if (!jmfProperties.exists()) {
try {
jmfProperties.createNewFile();
}
catch (IOException ex) {
LOGGER.log(Level.FINE, "Failed to create jmf.properties", ex);
}
}
// if we're running on linux checkout that libjmutil.so is where it
// should be and put it there.
runLinuxPreInstall();
// if (jmfProperties.length() == 0) {
new JMFInit(null, false);
// }
} | [
"public",
"static",
"void",
"setupJMF",
"(",
")",
"{",
"// .jmf is the place where we store the jmf.properties file used",
"// by JMF. if the directory does not exist or it does not contain",
"// a jmf.properties file. or if the jmf.properties file has 0 length",
"// then this is the first time ... | Runs JMFInit the first time the application is started so that capture
devices are properly detected and initialized by JMF. | [
"Runs",
"JMFInit",
"the",
"first",
"time",
"the",
"application",
"is",
"started",
"so",
"that",
"capture",
"devices",
"are",
"properly",
"detected",
"and",
"initialized",
"by",
"JMF",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-jingle-old/src/main/java/org/jivesoftware/smackx/jingleold/mediaimpl/jmf/JmfMediaManager.java#L124-L159 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java | NetworkEnvironmentConfiguration.calculateNewNetworkBufferMemory | private static long calculateNewNetworkBufferMemory(Configuration config, long networkBufSize, long maxJvmHeapMemory) {
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufMin = MemorySize.parse(config.getString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN)).getBytes();
long networkBufMax = MemorySize.parse(config.getString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX)).getBytes();
int pageSize = getPageSize(config);
checkNewNetworkConfig(pageSize, networkBufFraction, networkBufMin, networkBufMax);
long networkBufBytes = Math.min(networkBufMax, Math.max(networkBufMin, networkBufSize));
ConfigurationParserUtils.checkConfigParameter(networkBufBytes < maxJvmHeapMemory,
"(" + networkBufFraction + ", " + networkBufMin + ", " + networkBufMax + ")",
"(" + TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION.key() + ", " +
TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN.key() + ", " +
TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX.key() + ")",
"Network buffer memory size too large: " + networkBufBytes + " >= " +
maxJvmHeapMemory + " (maximum JVM memory size)");
return networkBufBytes;
} | java | private static long calculateNewNetworkBufferMemory(Configuration config, long networkBufSize, long maxJvmHeapMemory) {
float networkBufFraction = config.getFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION);
long networkBufMin = MemorySize.parse(config.getString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN)).getBytes();
long networkBufMax = MemorySize.parse(config.getString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX)).getBytes();
int pageSize = getPageSize(config);
checkNewNetworkConfig(pageSize, networkBufFraction, networkBufMin, networkBufMax);
long networkBufBytes = Math.min(networkBufMax, Math.max(networkBufMin, networkBufSize));
ConfigurationParserUtils.checkConfigParameter(networkBufBytes < maxJvmHeapMemory,
"(" + networkBufFraction + ", " + networkBufMin + ", " + networkBufMax + ")",
"(" + TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION.key() + ", " +
TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN.key() + ", " +
TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX.key() + ")",
"Network buffer memory size too large: " + networkBufBytes + " >= " +
maxJvmHeapMemory + " (maximum JVM memory size)");
return networkBufBytes;
} | [
"private",
"static",
"long",
"calculateNewNetworkBufferMemory",
"(",
"Configuration",
"config",
",",
"long",
"networkBufSize",
",",
"long",
"maxJvmHeapMemory",
")",
"{",
"float",
"networkBufFraction",
"=",
"config",
".",
"getFloat",
"(",
"TaskManagerOptions",
".",
"NE... | Calculates the amount of memory used for network buffers based on the total memory to use and
the according configuration parameters.
<p>The following configuration parameters are involved:
<ul>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_FRACTION},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MIN},</li>
<li>{@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MAX}</li>
</ul>.
@param config configuration object
@param networkBufSize memory of network buffers based on JVM memory size and network fraction
@param maxJvmHeapMemory maximum memory used for checking the results of network memory
@return memory to use for network buffers (in bytes) | [
"Calculates",
"the",
"amount",
"of",
"memory",
"used",
"for",
"network",
"buffers",
"based",
"on",
"the",
"total",
"memory",
"to",
"use",
"and",
"the",
"according",
"configuration",
"parameters",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/taskmanager/NetworkEnvironmentConfiguration.java#L278-L298 |
JOML-CI/JOML | src/org/joml/Matrix4x3f.java | Matrix4x3f.orthoSymmetricLH | public Matrix4x3f orthoSymmetricLH(float width, float height, float zNear, float zFar) {
return orthoSymmetricLH(width, height, zNear, zFar, false, this);
} | java | public Matrix4x3f orthoSymmetricLH(float width, float height, float zNear, float zFar) {
return orthoSymmetricLH(width, height, zNear, zFar, false, this);
} | [
"public",
"Matrix4x3f",
"orthoSymmetricLH",
"(",
"float",
"width",
",",
"float",
"height",
",",
"float",
"zNear",
",",
"float",
"zFar",
")",
"{",
"return",
"orthoSymmetricLH",
"(",
"width",
",",
"height",
",",
"zNear",
",",
"zFar",
",",
"false",
",",
"this... | Apply a symmetric orthographic projection transformation for a left-handed coordinate system
using OpenGL's NDC z range of <code>[-1..+1]</code> to this matrix.
<p>
This method is equivalent to calling {@link #orthoLH(float, float, float, float, float, float) orthoLH()} with
<code>left=-width/2</code>, <code>right=+width/2</code>, <code>bottom=-height/2</code> and <code>top=+height/2</code>.
<p>
If <code>M</code> is <code>this</code> matrix and <code>O</code> the orthographic projection matrix,
then the new matrix will be <code>M * O</code>. So when transforming a
vector <code>v</code> with the new matrix by using <code>M * O * v</code>, the
orthographic projection transformation will be applied first!
<p>
In order to set the matrix to a symmetric orthographic projection without post-multiplying it,
use {@link #setOrthoSymmetricLH(float, float, float, float) setOrthoSymmetricLH()}.
<p>
Reference: <a href="http://www.songho.ca/opengl/gl_projectionmatrix.html#ortho">http://www.songho.ca</a>
@see #setOrthoSymmetricLH(float, float, float, float)
@param width
the distance between the right and left frustum edges
@param height
the distance between the top and bottom frustum edges
@param zNear
near clipping plane distance
@param zFar
far clipping plane distance
@return this | [
"Apply",
"a",
"symmetric",
"orthographic",
"projection",
"transformation",
"for",
"a",
"left",
"-",
"handed",
"coordinate",
"system",
"using",
"OpenGL",
"s",
"NDC",
"z",
"range",
"of",
"<code",
">",
"[",
"-",
"1",
"..",
"+",
"1",
"]",
"<",
"/",
"code",
... | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3f.java#L5520-L5522 |
sshtools/j2ssh-maverick | j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java | SftpClient.get | public SftpFileAttributes get(String remote, OutputStream local,
long position) throws SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, position);
} | java | public SftpFileAttributes get(String remote, OutputStream local,
long position) throws SftpStatusException, SshException,
TransferCancelledException {
return get(remote, local, null, position);
} | [
"public",
"SftpFileAttributes",
"get",
"(",
"String",
"remote",
",",
"OutputStream",
"local",
",",
"long",
"position",
")",
"throws",
"SftpStatusException",
",",
"SshException",
",",
"TransferCancelledException",
"{",
"return",
"get",
"(",
"remote",
",",
"local",
... | Download the remote file into an OutputStream.
@param remote
@param local
@param position
the position from which to start reading the remote file
@return the downloaded file's attributes
@throws SftpStatusException
@throws SshException
@throws TransferCancelledException | [
"Download",
"the",
"remote",
"file",
"into",
"an",
"OutputStream",
"."
] | train | https://github.com/sshtools/j2ssh-maverick/blob/ce11ceaf0aa0b129b54327a6891973e1e34689f7/j2ssh-maverick/src/main/java/com/sshtools/sftp/SftpClient.java#L1556-L1560 |
citrusframework/citrus | modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/SftpClient.java | SftpClient.createDir | protected FtpMessage createDir(CommandType ftpCommand) {
try {
sftp.mkdir(ftpCommand.getArguments());
return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true);
} catch (SftpException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
} | java | protected FtpMessage createDir(CommandType ftpCommand) {
try {
sftp.mkdir(ftpCommand.getArguments());
return FtpMessage.result(FTPReply.PATHNAME_CREATED, "Pathname created", true);
} catch (SftpException e) {
throw new CitrusRuntimeException("Failed to execute ftp command", e);
}
} | [
"protected",
"FtpMessage",
"createDir",
"(",
"CommandType",
"ftpCommand",
")",
"{",
"try",
"{",
"sftp",
".",
"mkdir",
"(",
"ftpCommand",
".",
"getArguments",
"(",
")",
")",
";",
"return",
"FtpMessage",
".",
"result",
"(",
"FTPReply",
".",
"PATHNAME_CREATED",
... | Execute mkDir command and create new directory.
@param ftpCommand
@return | [
"Execute",
"mkDir",
"command",
"and",
"create",
"new",
"directory",
"."
] | train | https://github.com/citrusframework/citrus/blob/55c58ef74c01d511615e43646ca25c1b2301c56d/modules/citrus-ftp/src/main/java/com/consol/citrus/ftp/client/SftpClient.java#L97-L104 |
airlift/slice | src/main/java/io/airlift/slice/SliceUtf8.java | SliceUtf8.getCodePointBefore | public static int getCodePointBefore(Slice utf8, int position)
{
byte unsignedByte = utf8.getByte(position - 1);
if (!isContinuationByte(unsignedByte)) {
return unsignedByte & 0xFF;
}
if (!isContinuationByte(utf8.getByte(position - 2))) {
return getCodePointAt(utf8, position - 2);
}
if (!isContinuationByte(utf8.getByte(position - 3))) {
return getCodePointAt(utf8, position - 3);
}
if (!isContinuationByte(utf8.getByte(position - 4))) {
return getCodePointAt(utf8, position - 4);
}
// Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal
throw new InvalidUtf8Exception("UTF-8 is not well formed");
} | java | public static int getCodePointBefore(Slice utf8, int position)
{
byte unsignedByte = utf8.getByte(position - 1);
if (!isContinuationByte(unsignedByte)) {
return unsignedByte & 0xFF;
}
if (!isContinuationByte(utf8.getByte(position - 2))) {
return getCodePointAt(utf8, position - 2);
}
if (!isContinuationByte(utf8.getByte(position - 3))) {
return getCodePointAt(utf8, position - 3);
}
if (!isContinuationByte(utf8.getByte(position - 4))) {
return getCodePointAt(utf8, position - 4);
}
// Per RFC3629, UTF-8 is limited to 4 bytes, so more bytes are illegal
throw new InvalidUtf8Exception("UTF-8 is not well formed");
} | [
"public",
"static",
"int",
"getCodePointBefore",
"(",
"Slice",
"utf8",
",",
"int",
"position",
")",
"{",
"byte",
"unsignedByte",
"=",
"utf8",
".",
"getByte",
"(",
"position",
"-",
"1",
")",
";",
"if",
"(",
"!",
"isContinuationByte",
"(",
"unsignedByte",
")... | Gets the UTF-8 encoded code point before the {@code position}.
<p>
Note: This method does not explicitly check for valid UTF-8, and may
return incorrect results or throw an exception for invalid UTF-8. | [
"Gets",
"the",
"UTF",
"-",
"8",
"encoded",
"code",
"point",
"before",
"the",
"{"
] | train | https://github.com/airlift/slice/blob/7166cb0319e3655f8ba15f5a7ccf3d2f721c1242/src/main/java/io/airlift/slice/SliceUtf8.java#L1020-L1038 |
alkacon/opencms-core | src/org/opencms/webdav/CmsWebdavServlet.java | CmsWebdavServlet.addElement | public static Element addElement(Element parent, String name) {
return parent.addElement(new QName(name, Namespace.get("D", DEFAULT_NAMESPACE)));
} | java | public static Element addElement(Element parent, String name) {
return parent.addElement(new QName(name, Namespace.get("D", DEFAULT_NAMESPACE)));
} | [
"public",
"static",
"Element",
"addElement",
"(",
"Element",
"parent",
",",
"String",
"name",
")",
"{",
"return",
"parent",
".",
"addElement",
"(",
"new",
"QName",
"(",
"name",
",",
"Namespace",
".",
"get",
"(",
"\"D\"",
",",
"DEFAULT_NAMESPACE",
")",
")",... | Adds an xml element to the given parent and sets the appropriate namespace and
prefix.<p>
@param parent the parent node to add the element
@param name the name of the new element
@return the created element with the given name which was added to the given parent | [
"Adds",
"an",
"xml",
"element",
"to",
"the",
"given",
"parent",
"and",
"sets",
"the",
"appropriate",
"namespace",
"and",
"prefix",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/webdav/CmsWebdavServlet.java#L406-L409 |
aicer/hibiscus-http-client | src/main/java/org/aicer/hibiscus/http/client/HttpClient.java | HttpClient.addNameValuePair | public final HttpClient addNameValuePair(final String param, final Integer value) {
return addNameValuePair(param, value.toString());
} | java | public final HttpClient addNameValuePair(final String param, final Integer value) {
return addNameValuePair(param, value.toString());
} | [
"public",
"final",
"HttpClient",
"addNameValuePair",
"(",
"final",
"String",
"param",
",",
"final",
"Integer",
"value",
")",
"{",
"return",
"addNameValuePair",
"(",
"param",
",",
"value",
".",
"toString",
"(",
")",
")",
";",
"}"
] | Used by Entity-Enclosing HTTP Requests to send Name-Value pairs in the body of the request
@param param Name of Parameter
@param value Value of Parameter
@return | [
"Used",
"by",
"Entity",
"-",
"Enclosing",
"HTTP",
"Requests",
"to",
"send",
"Name",
"-",
"Value",
"pairs",
"in",
"the",
"body",
"of",
"the",
"request"
] | train | https://github.com/aicer/hibiscus-http-client/blob/a037e3cf8d4bb862d38a55a090778736a48d67cc/src/main/java/org/aicer/hibiscus/http/client/HttpClient.java#L269-L271 |
k3po/k3po | lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java | FunctionMapper.resolveFunction | public Method resolveFunction(String prefix, String localName) {
FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi(prefix);
return functionMapperSpi.resolveFunction(localName);
} | java | public Method resolveFunction(String prefix, String localName) {
FunctionMapperSpi functionMapperSpi = findFunctionMapperSpi(prefix);
return functionMapperSpi.resolveFunction(localName);
} | [
"public",
"Method",
"resolveFunction",
"(",
"String",
"prefix",
",",
"String",
"localName",
")",
"{",
"FunctionMapperSpi",
"functionMapperSpi",
"=",
"findFunctionMapperSpi",
"(",
"prefix",
")",
";",
"return",
"functionMapperSpi",
".",
"resolveFunction",
"(",
"localNam... | Resolves a Function via prefix and local name.
@param prefix of the function
@param localName of the function
@return an instance of a Method | [
"Resolves",
"a",
"Function",
"via",
"prefix",
"and",
"local",
"name",
"."
] | train | https://github.com/k3po/k3po/blob/3ca4fd31ab4a397893aa640c62ada0e485c8bbd4/lang/src/main/java/org/kaazing/k3po/lang/el/FunctionMapper.java#L66-L69 |
UrielCh/ovh-java-sdk | ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java | ApiOvhTelephony.billingAccount_line_serviceName_block_POST | public void billingAccount_line_serviceName_block_POST(String billingAccount, String serviceName, OvhLineBlockingMode mode) throws IOException {
String qPath = "/telephony/{billingAccount}/line/{serviceName}/block";
StringBuilder sb = path(qPath, billingAccount, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "mode", mode);
exec(qPath, "POST", sb.toString(), o);
} | java | public void billingAccount_line_serviceName_block_POST(String billingAccount, String serviceName, OvhLineBlockingMode mode) throws IOException {
String qPath = "/telephony/{billingAccount}/line/{serviceName}/block";
StringBuilder sb = path(qPath, billingAccount, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "mode", mode);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"billingAccount_line_serviceName_block_POST",
"(",
"String",
"billingAccount",
",",
"String",
"serviceName",
",",
"OvhLineBlockingMode",
"mode",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/telephony/{billingAccount}/line/{serviceName}/block\... | Block the line. By default it will block incoming and outgoing calls (except for emergency numbers)
REST: POST /telephony/{billingAccount}/line/{serviceName}/block
@param mode [required] The block mode : outgoing, incoming, both (default: both)
@param billingAccount [required] The name of your billingAccount
@param serviceName [required] | [
"Block",
"the",
"line",
".",
"By",
"default",
"it",
"will",
"block",
"incoming",
"and",
"outgoing",
"calls",
"(",
"except",
"for",
"emergency",
"numbers",
")"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-telephony/src/main/java/net/minidev/ovh/api/ApiOvhTelephony.java#L1900-L1906 |
ralscha/wampspring | src/main/java/ch/rasc/wampspring/config/WampSession.java | WampSession.registerDestructionCallback | public void registerDestructionCallback(String name, Runnable callback) {
synchronized (getSessionMutex()) {
if (isSessionCompleted()) {
throw new IllegalStateException(
"Session id=" + getWebSocketSessionId() + " already completed");
}
setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name, callback);
}
} | java | public void registerDestructionCallback(String name, Runnable callback) {
synchronized (getSessionMutex()) {
if (isSessionCompleted()) {
throw new IllegalStateException(
"Session id=" + getWebSocketSessionId() + " already completed");
}
setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name, callback);
}
} | [
"public",
"void",
"registerDestructionCallback",
"(",
"String",
"name",
",",
"Runnable",
"callback",
")",
"{",
"synchronized",
"(",
"getSessionMutex",
"(",
")",
")",
"{",
"if",
"(",
"isSessionCompleted",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalStateException... | Register a callback to execute on destruction of the specified attribute. The
callback is executed when the session is closed.
@param name the name of the attribute to register the callback for
@param callback the destruction callback to be executed | [
"Register",
"a",
"callback",
"to",
"execute",
"on",
"destruction",
"of",
"the",
"specified",
"attribute",
".",
"The",
"callback",
"is",
"executed",
"when",
"the",
"session",
"is",
"closed",
"."
] | train | https://github.com/ralscha/wampspring/blob/7571bb6773b848c580b29890587eb35397bfe5b5/src/main/java/ch/rasc/wampspring/config/WampSession.java#L108-L116 |
deeplearning4j/deeplearning4j | datavec/datavec-api/src/main/java/org/datavec/api/records/reader/impl/transform/TransformProcessRecordReader.java | TransformProcessRecordReader.initialize | @Override
public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException {
recordReader.initialize(conf, split);
} | java | @Override
public void initialize(Configuration conf, InputSplit split) throws IOException, InterruptedException {
recordReader.initialize(conf, split);
} | [
"@",
"Override",
"public",
"void",
"initialize",
"(",
"Configuration",
"conf",
",",
"InputSplit",
"split",
")",
"throws",
"IOException",
",",
"InterruptedException",
"{",
"recordReader",
".",
"initialize",
"(",
"conf",
",",
"split",
")",
";",
"}"
] | Called once at initialization.
@param conf a configuration for initialization
@param split the split that defines the range of records to read
@throws IOException
@throws InterruptedException | [
"Called",
"once",
"at",
"initialization",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/records/reader/impl/transform/TransformProcessRecordReader.java#L78-L81 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/Step.java | Step.updateDateValidated | protected void updateDateValidated(PageElement pageElement, String dateType, String date) throws TechnicalException, FailureException {
logger.debug("updateDateValidated with elementName={}, dateType={} and date={}", pageElement, dateType, date);
final DateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT);
final Date today = Calendar.getInstance().getTime();
try {
final Date valideDate = formatter.parse(date);
if ("any".equals(dateType)) {
logger.debug("update Date with any date: {}", date);
updateText(pageElement, date);
} else if (formatter.format(today).equals(date) && ("future".equals(dateType) || "today".equals(dateType))) {
logger.debug("update Date with today");
updateText(pageElement, date);
} else if (valideDate.after(Calendar.getInstance().getTime()) && ("future".equals(dateType) || "future_strict".equals(dateType))) {
logger.debug("update Date with a date after today: {}", date);
updateText(pageElement, date);
} else {
new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNEXPECTED_DATE), Messages.getMessage(Messages.DATE_GREATER_THAN_TODAY)), true,
pageElement.getPage().getCallBack());
}
} catch (final ParseException e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), pageElement, date), false, pageElement.getPage().getCallBack());
}
} | java | protected void updateDateValidated(PageElement pageElement, String dateType, String date) throws TechnicalException, FailureException {
logger.debug("updateDateValidated with elementName={}, dateType={} and date={}", pageElement, dateType, date);
final DateFormat formatter = new SimpleDateFormat(Constants.DATE_FORMAT);
final Date today = Calendar.getInstance().getTime();
try {
final Date valideDate = formatter.parse(date);
if ("any".equals(dateType)) {
logger.debug("update Date with any date: {}", date);
updateText(pageElement, date);
} else if (formatter.format(today).equals(date) && ("future".equals(dateType) || "today".equals(dateType))) {
logger.debug("update Date with today");
updateText(pageElement, date);
} else if (valideDate.after(Calendar.getInstance().getTime()) && ("future".equals(dateType) || "future_strict".equals(dateType))) {
logger.debug("update Date with a date after today: {}", date);
updateText(pageElement, date);
} else {
new Result.Failure<>(date, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_UNEXPECTED_DATE), Messages.getMessage(Messages.DATE_GREATER_THAN_TODAY)), true,
pageElement.getPage().getCallBack());
}
} catch (final ParseException e) {
new Result.Failure<>(e.getMessage(), Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_WRONG_DATE_FORMAT), pageElement, date), false, pageElement.getPage().getCallBack());
}
} | [
"protected",
"void",
"updateDateValidated",
"(",
"PageElement",
"pageElement",
",",
"String",
"dateType",
",",
"String",
"date",
")",
"throws",
"TechnicalException",
",",
"FailureException",
"{",
"logger",
".",
"debug",
"(",
"\"updateDateValidated with elementName={}, dat... | Update a html input text value with a date.
@param pageElement
Is target element
@param dateType
"any", "future", "today", "future_strict"
@param date
Is the new data (date)
@throws TechnicalException
is thrown if you have a technical error (format, configuration, datas, ...) in NoraUi.
Exception with {@value com.github.noraui.utils.Messages#FAIL_MESSAGE_WRONG_DATE_FORMAT} message (no screenshot, no exception) or with
{@value com.github.noraui.utils.Messages#FAIL_MESSAGE_UNEXPECTED_DATE} message
(with screenshot, no exception)
@throws FailureException
if the scenario encounters a functional error | [
"Update",
"a",
"html",
"input",
"text",
"value",
"with",
"a",
"date",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/Step.java#L506-L529 |
thorstenwagner/TraJ | src/main/java/de/biomedical_imaging/traj/math/TrajectorySplineFit.java | TrajectorySplineFit.minDistancePointSpline | public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){
double minDistance = Double.MAX_VALUE;
Point2D.Double minDistancePoint = null;
int numberOfSplines = spline.getN();
double[] knots = spline.getKnots();
for(int i = 0; i < numberOfSplines; i++){
double x = knots[i];
double stopx = knots[i+1];
double dx = (stopx-x)/nPointsPerSegment;
for(int j = 0; j < nPointsPerSegment; j++){
Point2D.Double candidate = new Point2D.Double(x, spline.value(x));
double d = p.distance(candidate);
if(d<minDistance){
minDistance = d;
minDistancePoint = candidate;
}
x += dx;
}
}
return minDistancePoint;
} | java | public Point2D.Double minDistancePointSpline(Point2D.Double p, int nPointsPerSegment){
double minDistance = Double.MAX_VALUE;
Point2D.Double minDistancePoint = null;
int numberOfSplines = spline.getN();
double[] knots = spline.getKnots();
for(int i = 0; i < numberOfSplines; i++){
double x = knots[i];
double stopx = knots[i+1];
double dx = (stopx-x)/nPointsPerSegment;
for(int j = 0; j < nPointsPerSegment; j++){
Point2D.Double candidate = new Point2D.Double(x, spline.value(x));
double d = p.distance(candidate);
if(d<minDistance){
minDistance = d;
minDistancePoint = candidate;
}
x += dx;
}
}
return minDistancePoint;
} | [
"public",
"Point2D",
".",
"Double",
"minDistancePointSpline",
"(",
"Point2D",
".",
"Double",
"p",
",",
"int",
"nPointsPerSegment",
")",
"{",
"double",
"minDistance",
"=",
"Double",
".",
"MAX_VALUE",
";",
"Point2D",
".",
"Double",
"minDistancePoint",
"=",
"null",... | Finds to a given point p the point on the spline with minimum distance.
@param p Point where the nearest distance is searched for
@param nPointsPerSegment Number of interpolation points between two support points
@return Point spline which has the minimum distance to p | [
"Finds",
"to",
"a",
"given",
"point",
"p",
"the",
"point",
"on",
"the",
"spline",
"with",
"minimum",
"distance",
"."
] | train | https://github.com/thorstenwagner/TraJ/blob/505fafb1f2f77a2d67bb2a089a2fdebe2c9bc7cb/src/main/java/de/biomedical_imaging/traj/math/TrajectorySplineFit.java#L538-L560 |
EdwardRaff/JSAT | JSAT/src/jsat/classifiers/trees/DecisionStump.java | DecisionStump.distributMissing | static protected <T> void distributMissing(List<ClassificationDataSet> splits, double[] fracs, ClassificationDataSet source, IntList hadMissing)
{
for (int i : hadMissing)
{
DataPoint dp = source.getDataPoint(i);
for (int j = 0; j < fracs.length; j++)
{
double nw = fracs[j] * source.getWeight(i);
if (Double.isNaN(nw))//happens when no weight is available
continue;
if (nw <= 1e-13)
continue;
splits.get(j).addDataPoint(dp, source.getDataPointCategory(i), nw);
}
}
} | java | static protected <T> void distributMissing(List<ClassificationDataSet> splits, double[] fracs, ClassificationDataSet source, IntList hadMissing)
{
for (int i : hadMissing)
{
DataPoint dp = source.getDataPoint(i);
for (int j = 0; j < fracs.length; j++)
{
double nw = fracs[j] * source.getWeight(i);
if (Double.isNaN(nw))//happens when no weight is available
continue;
if (nw <= 1e-13)
continue;
splits.get(j).addDataPoint(dp, source.getDataPointCategory(i), nw);
}
}
} | [
"static",
"protected",
"<",
"T",
">",
"void",
"distributMissing",
"(",
"List",
"<",
"ClassificationDataSet",
">",
"splits",
",",
"double",
"[",
"]",
"fracs",
",",
"ClassificationDataSet",
"source",
",",
"IntList",
"hadMissing",
")",
"{",
"for",
"(",
"int",
"... | Distributes a list of datapoints that had missing values to each split, re-weighted by the indicated fractions
@param <T>
@param splits a list of lists, where each inner list is a split
@param fracs the fraction of weight to each split, should sum to one
@param source
@param hadMissing the list of datapoints that had missing values | [
"Distributes",
"a",
"list",
"of",
"datapoints",
"that",
"had",
"missing",
"values",
"to",
"each",
"split",
"re",
"-",
"weighted",
"by",
"the",
"indicated",
"fractions"
] | train | https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/trees/DecisionStump.java#L723-L740 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java | FDistort.init | public FDistort init(ImageBase input, ImageBase output) {
this.input = input;
this.output = output;
inputType = input.getImageType();
interp(InterpolationType.BILINEAR);
border(0);
cached = false;
distorter = null;
outputToInput = null;
return this;
} | java | public FDistort init(ImageBase input, ImageBase output) {
this.input = input;
this.output = output;
inputType = input.getImageType();
interp(InterpolationType.BILINEAR);
border(0);
cached = false;
distorter = null;
outputToInput = null;
return this;
} | [
"public",
"FDistort",
"init",
"(",
"ImageBase",
"input",
",",
"ImageBase",
"output",
")",
"{",
"this",
".",
"input",
"=",
"input",
";",
"this",
".",
"output",
"=",
"output",
";",
"inputType",
"=",
"input",
".",
"getImageType",
"(",
")",
";",
"interp",
... | Specifies the input and output image and sets interpolation to BILINEAR, black image border, cache is off. | [
"Specifies",
"the",
"input",
"and",
"output",
"image",
"and",
"sets",
"interpolation",
"to",
"BILINEAR",
"black",
"image",
"border",
"cache",
"is",
"off",
"."
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/abst/distort/FDistort.java#L97-L110 |
BranchMetrics/android-branch-deep-linking | Branch-SDK/src/io/branch/referral/AnimatedDialog.java | AnimatedDialog.slideClose | private void slideClose() {
if (!isClosing_) {
isClosing_ = true;
TranslateAnimation slideDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1f);
slideDown.setDuration(500);
slideDown.setInterpolator(new DecelerateInterpolator());
((ViewGroup) getWindow().getDecorView()).getChildAt(0).startAnimation(slideDown);
slideDown.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
dismiss();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
} | java | private void slideClose() {
if (!isClosing_) {
isClosing_ = true;
TranslateAnimation slideDown = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1f);
slideDown.setDuration(500);
slideDown.setInterpolator(new DecelerateInterpolator());
((ViewGroup) getWindow().getDecorView()).getChildAt(0).startAnimation(slideDown);
slideDown.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
dismiss();
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
} | [
"private",
"void",
"slideClose",
"(",
")",
"{",
"if",
"(",
"!",
"isClosing_",
")",
"{",
"isClosing_",
"=",
"true",
";",
"TranslateAnimation",
"slideDown",
"=",
"new",
"TranslateAnimation",
"(",
"Animation",
".",
"RELATIVE_TO_SELF",
",",
"0",
",",
"Animation",
... | </p> Closes the dialog with a translation animation to the content view </p> | [
"<",
"/",
"p",
">",
"Closes",
"the",
"dialog",
"with",
"a",
"translation",
"animation",
"to",
"the",
"content",
"view",
"<",
"/",
"p",
">"
] | train | https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/AnimatedDialog.java#L122-L145 |
j256/simplecsv | src/main/java/com/j256/simplecsv/processor/CsvProcessor.java | CsvProcessor.processRow | public T processRow(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
try {
return processRow(line, null, parseError, 1);
} catch (IOException e) {
// this won't happen because processRow won't do any IO
return null;
}
} | java | public T processRow(String line, ParseError parseError) throws ParseException {
checkEntityConfig();
try {
return processRow(line, null, parseError, 1);
} catch (IOException e) {
// this won't happen because processRow won't do any IO
return null;
}
} | [
"public",
"T",
"processRow",
"(",
"String",
"line",
",",
"ParseError",
"parseError",
")",
"throws",
"ParseException",
"{",
"checkEntityConfig",
"(",
")",
";",
"try",
"{",
"return",
"processRow",
"(",
"line",
",",
"null",
",",
"parseError",
",",
"1",
")",
"... | Read and process a line and return the associated entity.
@param line
to process to build our entity.
@param parseError
If not null, this will be set with the first parse error and it will return null. If this is null then
a ParseException will be thrown instead.
@return Returns a processed entity or null if an error and parseError has been set.
@throws ParseException
Thrown on any parsing problems. If parseError is not null then the error will be added there and an
exception should not be thrown. | [
"Read",
"and",
"process",
"a",
"line",
"and",
"return",
"the",
"associated",
"entity",
"."
] | train | https://github.com/j256/simplecsv/blob/964fe53073c43e2a311341e3f8fd2c94372f60cb/src/main/java/com/j256/simplecsv/processor/CsvProcessor.java#L388-L396 |
radkovo/jStyleParser | src/main/java/cz/vutbr/web/css/MediaSpec.java | MediaSpec.valueMatches | protected boolean valueMatches(Integer required, int current, boolean min, boolean max)
{
if (required != null)
{
if (min)
return (current >= required);
else if (max)
return (current <= required);
else
return current == required;
}
else
return false; //invalid values don't match
} | java | protected boolean valueMatches(Integer required, int current, boolean min, boolean max)
{
if (required != null)
{
if (min)
return (current >= required);
else if (max)
return (current <= required);
else
return current == required;
}
else
return false; //invalid values don't match
} | [
"protected",
"boolean",
"valueMatches",
"(",
"Integer",
"required",
",",
"int",
"current",
",",
"boolean",
"min",
",",
"boolean",
"max",
")",
"{",
"if",
"(",
"required",
"!=",
"null",
")",
"{",
"if",
"(",
"min",
")",
"return",
"(",
"current",
">=",
"re... | Checks whether a value coresponds to the given criteria.
@param required the required value
@param current the tested value or {@code null} for invalid value
@param min {@code true} when the required value is the minimal one
@param max {@code true} when the required value is the maximal one
@return {@code true} when the value matches the criteria. | [
"Checks",
"whether",
"a",
"value",
"coresponds",
"to",
"the",
"given",
"criteria",
"."
] | train | https://github.com/radkovo/jStyleParser/blob/8ab049ac6866aa52c4d7deee25c9e294e7191957/src/main/java/cz/vutbr/web/css/MediaSpec.java#L537-L550 |
chhh/MSFTBX | MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzxml/MZXMLPeaksDecoder.java | MZXMLPeaksDecoder.decode | public static DecodedData decode(byte[] bytesIn, int precision, PeaksCompression compression)
throws FileParsingException, IOException, DataFormatException {
return decode(bytesIn, bytesIn.length, precision, compression);
} | java | public static DecodedData decode(byte[] bytesIn, int precision, PeaksCompression compression)
throws FileParsingException, IOException, DataFormatException {
return decode(bytesIn, bytesIn.length, precision, compression);
} | [
"public",
"static",
"DecodedData",
"decode",
"(",
"byte",
"[",
"]",
"bytesIn",
",",
"int",
"precision",
",",
"PeaksCompression",
"compression",
")",
"throws",
"FileParsingException",
",",
"IOException",
",",
"DataFormatException",
"{",
"return",
"decode",
"(",
"by... | Convenience shortcut, which assumes the whole {@code bytesIn} array is useful data. | [
"Convenience",
"shortcut",
"which",
"assumes",
"the",
"whole",
"{"
] | train | https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/fileio/filetypes/mzxml/MZXMLPeaksDecoder.java#L42-L45 |
msgpack/msgpack-java | msgpack-core/src/main/java/org/msgpack/core/buffer/MessageBuffer.java | MessageBuffer.newInstance | private static MessageBuffer newInstance(Constructor<?> constructor, Object... args)
{
try {
// We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be
// generated to resolve one of the method references when two or more classes overrides the method.
return (MessageBuffer) constructor.newInstance(args);
}
catch (InstantiationException e) {
// should never happen
throw new IllegalStateException(e);
}
catch (IllegalAccessException e) {
// should never happen unless security manager restricts this reflection
throw new IllegalStateException(e);
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException) {
// underlying constructor may throw RuntimeException
throw (RuntimeException) e.getCause();
}
else if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
}
// should never happen
throw new IllegalStateException(e.getCause());
}
} | java | private static MessageBuffer newInstance(Constructor<?> constructor, Object... args)
{
try {
// We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method. TypeProfile will be
// generated to resolve one of the method references when two or more classes overrides the method.
return (MessageBuffer) constructor.newInstance(args);
}
catch (InstantiationException e) {
// should never happen
throw new IllegalStateException(e);
}
catch (IllegalAccessException e) {
// should never happen unless security manager restricts this reflection
throw new IllegalStateException(e);
}
catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException) {
// underlying constructor may throw RuntimeException
throw (RuntimeException) e.getCause();
}
else if (e.getCause() instanceof Error) {
throw (Error) e.getCause();
}
// should never happen
throw new IllegalStateException(e.getCause());
}
} | [
"private",
"static",
"MessageBuffer",
"newInstance",
"(",
"Constructor",
"<",
"?",
">",
"constructor",
",",
"Object",
"...",
"args",
")",
"{",
"try",
"{",
"// We need to use reflection to create MessageBuffer instances in order to prevent TypeProfile generation for getInt method.... | Creates a new MessageBuffer instance
@param constructor A MessageBuffer constructor
@return new MessageBuffer instance | [
"Creates",
"a",
"new",
"MessageBuffer",
"instance"
] | train | https://github.com/msgpack/msgpack-java/blob/16e370e348215a72a14c210b42d448d513aee015/msgpack-core/src/main/java/org/msgpack/core/buffer/MessageBuffer.java#L303-L329 |
prometheus/client_java | simpleclient_dropwizard/src/main/java/io/prometheus/client/dropwizard/DropwizardExports.java | DropwizardExports.fromSnapshotAndCount | MetricFamilySamples fromSnapshotAndCount(String dropwizardName, Snapshot snapshot, long count, double factor, String helpMessage) {
List<MetricFamilySamples.Sample> samples = Arrays.asList(
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.5"), snapshot.getMedian() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.75"), snapshot.get75thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.95"), snapshot.get95thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.98"), snapshot.get98thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.99"), snapshot.get99thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.999"), snapshot.get999thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "_count", new ArrayList<String>(), new ArrayList<String>(), count)
);
return new MetricFamilySamples(samples.get(0).name, Type.SUMMARY, helpMessage, samples);
} | java | MetricFamilySamples fromSnapshotAndCount(String dropwizardName, Snapshot snapshot, long count, double factor, String helpMessage) {
List<MetricFamilySamples.Sample> samples = Arrays.asList(
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.5"), snapshot.getMedian() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.75"), snapshot.get75thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.95"), snapshot.get95thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.98"), snapshot.get98thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.99"), snapshot.get99thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "", Arrays.asList("quantile"), Arrays.asList("0.999"), snapshot.get999thPercentile() * factor),
sampleBuilder.createSample(dropwizardName, "_count", new ArrayList<String>(), new ArrayList<String>(), count)
);
return new MetricFamilySamples(samples.get(0).name, Type.SUMMARY, helpMessage, samples);
} | [
"MetricFamilySamples",
"fromSnapshotAndCount",
"(",
"String",
"dropwizardName",
",",
"Snapshot",
"snapshot",
",",
"long",
"count",
",",
"double",
"factor",
",",
"String",
"helpMessage",
")",
"{",
"List",
"<",
"MetricFamilySamples",
".",
"Sample",
">",
"samples",
"... | Export a histogram snapshot as a prometheus SUMMARY.
@param dropwizardName metric name.
@param snapshot the histogram snapshot.
@param count the total sample count for this snapshot.
@param factor a factor to apply to histogram values. | [
"Export",
"a",
"histogram",
"snapshot",
"as",
"a",
"prometheus",
"SUMMARY",
"."
] | train | https://github.com/prometheus/client_java/blob/4e0e7527b048f1ffd0382dcb74c0b9dab23b4d9f/simpleclient_dropwizard/src/main/java/io/prometheus/client/dropwizard/DropwizardExports.java#L86-L97 |
groundupworks/wings | wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java | FacebookEndpoint.requestAccounts | boolean requestAccounts(Callback callback) {
boolean isSuccessful = false;
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Construct fields to request.
Bundle params = new Bundle();
params.putString(ACCOUNTS_LISTING_FEILDS_KEY, ACCOUNTS_LISTING_FIELDS_VALUE);
// Construct and execute albums listing request.
Request request = new Request(session, ACCOUNTS_LISTING_GRAPH_PATH, params, HttpMethod.GET, callback);
request.executeAsync();
isSuccessful = true;
}
return isSuccessful;
} | java | boolean requestAccounts(Callback callback) {
boolean isSuccessful = false;
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Construct fields to request.
Bundle params = new Bundle();
params.putString(ACCOUNTS_LISTING_FEILDS_KEY, ACCOUNTS_LISTING_FIELDS_VALUE);
// Construct and execute albums listing request.
Request request = new Request(session, ACCOUNTS_LISTING_GRAPH_PATH, params, HttpMethod.GET, callback);
request.executeAsync();
isSuccessful = true;
}
return isSuccessful;
} | [
"boolean",
"requestAccounts",
"(",
"Callback",
"callback",
")",
"{",
"boolean",
"isSuccessful",
"=",
"false",
";",
"Session",
"session",
"=",
"Session",
".",
"getActiveSession",
"(",
")",
";",
"if",
"(",
"session",
"!=",
"null",
"&&",
"session",
".",
"isOpen... | Asynchronously requests the Page accounts associated with the linked account. Requires an opened active {@link Session}.
@param callback a {@link Callback} when the request completes.
@return true if the request is made; false if no opened {@link Session} is active. | [
"Asynchronously",
"requests",
"the",
"Page",
"accounts",
"associated",
"with",
"the",
"linked",
"account",
".",
"Requires",
"an",
"opened",
"active",
"{",
"@link",
"Session",
"}",
"."
] | train | https://github.com/groundupworks/wings/blob/03d2827c30ef55f2db4e23f7500e016c7771fa39/wings-facebook/src/main/java/com/groundupworks/wings/facebook/FacebookEndpoint.java#L675-L691 |
katharsis-project/katharsis-framework | katharsis-rs/src/main/java/io/katharsis/rs/JsonApiResponseFilter.java | JsonApiResponseFilter.filter | @Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
Object response = responseContext.getEntity();
if (response == null) {
return;
}
// only modify responses which contain a single or a list of Katharsis resources
if (isResourceResponse(response)) {
KatharsisBoot boot = feature.getBoot();
ResourceRegistry resourceRegistry = boot.getResourceRegistry();
DocumentMapper documentMapper = boot.getDocumentMapper();
ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider();
try {
UriInfo uriInfo = requestContext.getUriInfo();
if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo);
}
JsonApiResponse jsonApiResponse = new JsonApiResponse();
jsonApiResponse.setEntity(response);
// use the Katharsis document mapper to create a JSON API response
responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null));
responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API));
}
finally {
if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished();
}
}
}
} | java | @Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
Object response = responseContext.getEntity();
if (response == null) {
return;
}
// only modify responses which contain a single or a list of Katharsis resources
if (isResourceResponse(response)) {
KatharsisBoot boot = feature.getBoot();
ResourceRegistry resourceRegistry = boot.getResourceRegistry();
DocumentMapper documentMapper = boot.getDocumentMapper();
ServiceUrlProvider serviceUrlProvider = resourceRegistry.getServiceUrlProvider();
try {
UriInfo uriInfo = requestContext.getUriInfo();
if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestStarted(uriInfo);
}
JsonApiResponse jsonApiResponse = new JsonApiResponse();
jsonApiResponse.setEntity(response);
// use the Katharsis document mapper to create a JSON API response
responseContext.setEntity(documentMapper.toDocument(jsonApiResponse, null));
responseContext.getHeaders().put("Content-Type", Arrays.asList((Object)JsonApiMediaType.APPLICATION_JSON_API));
}
finally {
if (serviceUrlProvider instanceof UriInfoServiceUrlProvider) {
((UriInfoServiceUrlProvider) serviceUrlProvider).onRequestFinished();
}
}
}
} | [
"@",
"Override",
"public",
"void",
"filter",
"(",
"ContainerRequestContext",
"requestContext",
",",
"ContainerResponseContext",
"responseContext",
")",
"throws",
"IOException",
"{",
"Object",
"response",
"=",
"responseContext",
".",
"getEntity",
"(",
")",
";",
"if",
... | Creates JSON API responses for custom JAX-RS actions returning Katharsis resources. | [
"Creates",
"JSON",
"API",
"responses",
"for",
"custom",
"JAX",
"-",
"RS",
"actions",
"returning",
"Katharsis",
"resources",
"."
] | train | https://github.com/katharsis-project/katharsis-framework/blob/73d1a8763c49c5cf4643d43e2dbfedb647630c46/katharsis-rs/src/main/java/io/katharsis/rs/JsonApiResponseFilter.java#L37-L70 |
TheHortonMachine/hortonmachine | gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java | FileUtilities.writeFile | public static void writeFile( List<String> lines, File file ) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for( String line : lines ) {
bw.write(line);
bw.write("\n"); //$NON-NLS-1$
}
}
} | java | public static void writeFile( List<String> lines, File file ) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for( String line : lines ) {
bw.write(line);
bw.write("\n"); //$NON-NLS-1$
}
}
} | [
"public",
"static",
"void",
"writeFile",
"(",
"List",
"<",
"String",
">",
"lines",
",",
"File",
"file",
")",
"throws",
"IOException",
"{",
"try",
"(",
"BufferedWriter",
"bw",
"=",
"new",
"BufferedWriter",
"(",
"new",
"FileWriter",
"(",
"file",
")",
")",
... | Write a list of lines to a file.
@param lines the list of lines to write.
@param file the file to write to.
@throws IOException | [
"Write",
"a",
"list",
"of",
"lines",
"to",
"a",
"file",
"."
] | train | https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/files/FileUtilities.java#L245-L252 |
twilio/authy-java | src/main/java/com/authy/AuthyUtil.java | AuthyUtil.validateSignatureForPost | public static boolean validateSignatureForPost(String body, Map<String, String> headers, String url, String apiKey) throws OneTouchException, UnsupportedEncodingException {
HashMap<String, String> params = new HashMap<>();
if (body == null || body.isEmpty())
throw new OneTouchException("'PARAMS' are missing.");
extract("", new JSONObject(body), params);
return validateSignature(params, headers, "POST", url, apiKey);
} | java | public static boolean validateSignatureForPost(String body, Map<String, String> headers, String url, String apiKey) throws OneTouchException, UnsupportedEncodingException {
HashMap<String, String> params = new HashMap<>();
if (body == null || body.isEmpty())
throw new OneTouchException("'PARAMS' are missing.");
extract("", new JSONObject(body), params);
return validateSignature(params, headers, "POST", url, apiKey);
} | [
"public",
"static",
"boolean",
"validateSignatureForPost",
"(",
"String",
"body",
",",
"Map",
"<",
"String",
",",
"String",
">",
"headers",
",",
"String",
"url",
",",
"String",
"apiKey",
")",
"throws",
"OneTouchException",
",",
"UnsupportedEncodingException",
"{",... | Validates the request information to
@param body The body of the request in case of a POST method
@param headers The headers of the request
@param url The url of the request.
@param apiKey the security token from the authy library
@return true if the signature ios valid, false otherwise
@throws com.authy.OneTouchException
@throws UnsupportedEncodingException if the string parameters have problems with UTF-8 encoding. | [
"Validates",
"the",
"request",
"information",
"to"
] | train | https://github.com/twilio/authy-java/blob/55e3a5ff57a93b3eb36f5b59e8824e60af2b8b91/src/main/java/com/authy/AuthyUtil.java#L183-L189 |
Azure/azure-sdk-for-java | eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java | EventProcessorHost.registerEventProcessorFactory | public CompletableFuture<Void> registerEventProcessorFactory(IEventProcessorFactory<?> factory, EventProcessorOptions processorOptions) {
if (this.unregistered != null) {
throw new IllegalStateException("Register cannot be called on an EventProcessorHost after unregister. Please create a new EventProcessorHost instance.");
}
if (this.hostContext.getEventProcessorFactory() != null) {
throw new IllegalStateException("Register has already been called on this EventProcessorHost");
}
this.hostContext.setEventProcessorFactory(factory);
this.hostContext.setEventProcessorOptions(processorOptions);
if (this.executorService.isShutdown() || this.executorService.isTerminated()) {
TRACE_LOGGER.warn(this.hostContext.withHost("Calling registerEventProcessor/Factory after executor service has been shut down."));
throw new RejectedExecutionException("EventProcessorHost executor service has been shut down");
}
if (this.initializeLeaseManager) {
try {
((AzureStorageCheckpointLeaseManager) this.hostContext.getLeaseManager()).initialize(this.hostContext);
} catch (InvalidKeyException | URISyntaxException | StorageException e) {
TRACE_LOGGER.error(this.hostContext.withHost("Failure initializing default lease and checkpoint manager."));
throw new RuntimeException("Failure initializing Storage lease manager", e);
}
}
TRACE_LOGGER.info(this.hostContext.withHost("Starting event processing."));
return this.partitionManager.initialize();
} | java | public CompletableFuture<Void> registerEventProcessorFactory(IEventProcessorFactory<?> factory, EventProcessorOptions processorOptions) {
if (this.unregistered != null) {
throw new IllegalStateException("Register cannot be called on an EventProcessorHost after unregister. Please create a new EventProcessorHost instance.");
}
if (this.hostContext.getEventProcessorFactory() != null) {
throw new IllegalStateException("Register has already been called on this EventProcessorHost");
}
this.hostContext.setEventProcessorFactory(factory);
this.hostContext.setEventProcessorOptions(processorOptions);
if (this.executorService.isShutdown() || this.executorService.isTerminated()) {
TRACE_LOGGER.warn(this.hostContext.withHost("Calling registerEventProcessor/Factory after executor service has been shut down."));
throw new RejectedExecutionException("EventProcessorHost executor service has been shut down");
}
if (this.initializeLeaseManager) {
try {
((AzureStorageCheckpointLeaseManager) this.hostContext.getLeaseManager()).initialize(this.hostContext);
} catch (InvalidKeyException | URISyntaxException | StorageException e) {
TRACE_LOGGER.error(this.hostContext.withHost("Failure initializing default lease and checkpoint manager."));
throw new RuntimeException("Failure initializing Storage lease manager", e);
}
}
TRACE_LOGGER.info(this.hostContext.withHost("Starting event processing."));
return this.partitionManager.initialize();
} | [
"public",
"CompletableFuture",
"<",
"Void",
">",
"registerEventProcessorFactory",
"(",
"IEventProcessorFactory",
"<",
"?",
">",
"factory",
",",
"EventProcessorOptions",
"processorOptions",
")",
"{",
"if",
"(",
"this",
".",
"unregistered",
"!=",
"null",
")",
"{",
"... | Register user-supplied event processor factory and start processing.
<p>
This overload takes user-specified options.
<p>
The returned CompletableFuture completes when host initialization is finished. Initialization failures are
reported by completing the future with an exception, so it is important to call get() on the future and handle
any exceptions thrown.
@param factory User-supplied event processor factory object.
@param processorOptions Options for the processor host and event processor(s).
@return Future that completes when initialization is finished. | [
"Register",
"user",
"-",
"supplied",
"event",
"processor",
"factory",
"and",
"start",
"processing",
".",
"<p",
">",
"This",
"overload",
"takes",
"user",
"-",
"specified",
"options",
".",
"<p",
">",
"The",
"returned",
"CompletableFuture",
"completes",
"when",
"... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventhubs/data-plane/azure-eventhubs-eph/src/main/java/com/microsoft/azure/eventprocessorhost/EventProcessorHost.java#L464-L492 |
Grasia/phatsim | phat-core/src/main/java/phat/util/SpatialFactory.java | SpatialFactory.attachAName | public static BitmapText attachAName(Node node, String name) {
checkInit();
BitmapFont guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
BitmapText ch = new BitmapText(guiFont, false);
ch.setName("BitmapText");
ch.setSize(guiFont.getCharSet().getRenderedSize() * 0.02f);
ch.setText(name); // crosshairs
ch.setColor(new ColorRGBA(0f, 0f, 0f, 1f));
ch.getLocalScale().divideLocal(node.getLocalScale());
// controlador para que los objetos miren a la cámara.
BillboardControl control = new BillboardControl();
ch.addControl(control);
node.attachChild(ch);
return ch;
} | java | public static BitmapText attachAName(Node node, String name) {
checkInit();
BitmapFont guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
BitmapText ch = new BitmapText(guiFont, false);
ch.setName("BitmapText");
ch.setSize(guiFont.getCharSet().getRenderedSize() * 0.02f);
ch.setText(name); // crosshairs
ch.setColor(new ColorRGBA(0f, 0f, 0f, 1f));
ch.getLocalScale().divideLocal(node.getLocalScale());
// controlador para que los objetos miren a la cámara.
BillboardControl control = new BillboardControl();
ch.addControl(control);
node.attachChild(ch);
return ch;
} | [
"public",
"static",
"BitmapText",
"attachAName",
"(",
"Node",
"node",
",",
"String",
"name",
")",
"{",
"checkInit",
"(",
")",
";",
"BitmapFont",
"guiFont",
"=",
"assetManager",
".",
"loadFont",
"(",
"\"Interface/Fonts/Default.fnt\"",
")",
";",
"BitmapText",
"ch"... | Creates a geometry with the same name of the given node. It adds a
controller called BillboardControl that turns the name of the node in
order to look at the camera.
Letter's size can be changed using setSize() method, the text with
setText() method and the color using setColor() method.
@param node
@return | [
"Creates",
"a",
"geometry",
"with",
"the",
"same",
"name",
"of",
"the",
"given",
"node",
".",
"It",
"adds",
"a",
"controller",
"called",
"BillboardControl",
"that",
"turns",
"the",
"name",
"of",
"the",
"node",
"in",
"order",
"to",
"look",
"at",
"the",
"c... | train | https://github.com/Grasia/phatsim/blob/2d4fc8189be9730b34c8e3e1a08fb4800e01c5df/phat-core/src/main/java/phat/util/SpatialFactory.java#L153-L168 |
ops4j/org.ops4j.pax.wicket | spi/blueprint/src/main/java/org/ops4j/pax/wicket/spi/blueprint/injection/blueprint/AbstractBlueprintBeanDefinitionParser.java | AbstractBlueprintBeanDefinitionParser.createStringValue | protected ValueMetadata createStringValue(ParserContext context, String str) {
MutableValueMetadata value = context.createMetadata(MutableValueMetadata.class);
value.setStringValue(str);
return value;
} | java | protected ValueMetadata createStringValue(ParserContext context, String str) {
MutableValueMetadata value = context.createMetadata(MutableValueMetadata.class);
value.setStringValue(str);
return value;
} | [
"protected",
"ValueMetadata",
"createStringValue",
"(",
"ParserContext",
"context",
",",
"String",
"str",
")",
"{",
"MutableValueMetadata",
"value",
"=",
"context",
".",
"createMetadata",
"(",
"MutableValueMetadata",
".",
"class",
")",
";",
"value",
".",
"setStringV... | <p>createStringValue.</p>
@param context a {@link org.apache.aries.blueprint.ParserContext} object.
@param str a {@link java.lang.String} object.
@return a {@link org.osgi.service.blueprint.reflect.ValueMetadata} object. | [
"<p",
">",
"createStringValue",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ops4j/org.ops4j.pax.wicket/blob/ef7cb4bdf918e9e61ec69789b9c690567616faa9/spi/blueprint/src/main/java/org/ops4j/pax/wicket/spi/blueprint/injection/blueprint/AbstractBlueprintBeanDefinitionParser.java#L174-L178 |
jamesagnew/hapi-fhir | hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/SearchBuilder.java | SearchBuilder.calculateFuzzAmount | static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) {
if (cmpValue == ParamPrefixEnum.APPROXIMATE) {
return theValue.multiply(new BigDecimal(0.1));
} else {
String plainString = theValue.toPlainString();
int dotIdx = plainString.indexOf('.');
if (dotIdx == -1) {
return new BigDecimal(0.5);
}
int precision = plainString.length() - (dotIdx);
double mul = Math.pow(10, -precision);
double val = mul * 5.0d;
return new BigDecimal(val);
}
} | java | static BigDecimal calculateFuzzAmount(ParamPrefixEnum cmpValue, BigDecimal theValue) {
if (cmpValue == ParamPrefixEnum.APPROXIMATE) {
return theValue.multiply(new BigDecimal(0.1));
} else {
String plainString = theValue.toPlainString();
int dotIdx = plainString.indexOf('.');
if (dotIdx == -1) {
return new BigDecimal(0.5);
}
int precision = plainString.length() - (dotIdx);
double mul = Math.pow(10, -precision);
double val = mul * 5.0d;
return new BigDecimal(val);
}
} | [
"static",
"BigDecimal",
"calculateFuzzAmount",
"(",
"ParamPrefixEnum",
"cmpValue",
",",
"BigDecimal",
"theValue",
")",
"{",
"if",
"(",
"cmpValue",
"==",
"ParamPrefixEnum",
".",
"APPROXIMATE",
")",
"{",
"return",
"theValue",
".",
"multiply",
"(",
"new",
"BigDecimal... | Figures out the tolerance for a search. For example, if the user is searching for <code>4.00</code>, this method
returns <code>0.005</code> because we shold actually match values which are
<code>4 (+/-) 0.005</code> according to the FHIR specs. | [
"Figures",
"out",
"the",
"tolerance",
"for",
"a",
"search",
".",
"For",
"example",
"if",
"the",
"user",
"is",
"searching",
"for",
"<code",
">",
"4",
".",
"00<",
"/",
"code",
">",
"this",
"method",
"returns",
"<code",
">",
"0",
".",
"005<",
"/",
"code... | train | https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/dao/SearchBuilder.java#L2695-L2710 |
dropbox/dropbox-sdk-java | src/main/java/com/dropbox/core/v1/DbxClientV1.java | DbxClientV1.disableAccessToken | public void disableAccessToken()
throws DbxException
{
String host = this.host.getApi();
String apiPath = "1/disable_access_token";
doPost(host, apiPath, null, null, new DbxRequestUtil.ResponseHandler</*@Nullable*/Void>() {
@Override
public /*@Nullable*/Void handle(HttpRequestor.Response response) throws DbxException
{
if (response.getStatusCode() != 200) {
String requestId = DbxRequestUtil.getRequestId(response);
throw new BadResponseException(requestId, "unexpected response code: " + response.getStatusCode());
}
return null;
}
});
} | java | public void disableAccessToken()
throws DbxException
{
String host = this.host.getApi();
String apiPath = "1/disable_access_token";
doPost(host, apiPath, null, null, new DbxRequestUtil.ResponseHandler</*@Nullable*/Void>() {
@Override
public /*@Nullable*/Void handle(HttpRequestor.Response response) throws DbxException
{
if (response.getStatusCode() != 200) {
String requestId = DbxRequestUtil.getRequestId(response);
throw new BadResponseException(requestId, "unexpected response code: " + response.getStatusCode());
}
return null;
}
});
} | [
"public",
"void",
"disableAccessToken",
"(",
")",
"throws",
"DbxException",
"{",
"String",
"host",
"=",
"this",
".",
"host",
".",
"getApi",
"(",
")",
";",
"String",
"apiPath",
"=",
"\"1/disable_access_token\"",
";",
"doPost",
"(",
"host",
",",
"apiPath",
","... | Disable the access token that you constructed this {@code DbxClientV1}
with. After calling this, API calls made with this {@code DbxClientV1} will
fail. | [
"Disable",
"the",
"access",
"token",
"that",
"you",
"constructed",
"this",
"{"
] | train | https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/src/main/java/com/dropbox/core/v1/DbxClientV1.java#L374-L391 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java | HttpFileUploadManager.requestSlot | public Slot requestSlot(String filename, long fileSize, String contentType, DomainBareJid uploadServiceAddress)
throws SmackException, InterruptedException, XMPPException.XMPPErrorException {
final XMPPConnection connection = connection();
final UploadService defaultUploadService = this.defaultUploadService;
// The upload service we are going to use.
UploadService uploadService;
if (uploadServiceAddress == null) {
uploadService = defaultUploadService;
} else {
if (defaultUploadService != null && defaultUploadService.getAddress().equals(uploadServiceAddress)) {
// Avoid performing a service discovery if we already know about the given service.
uploadService = defaultUploadService;
} else {
DiscoverInfo discoverInfo = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(uploadServiceAddress);
if (!containsHttpFileUploadNamespace(discoverInfo)) {
throw new IllegalArgumentException("There is no HTTP upload service running at the given address '"
+ uploadServiceAddress + '\'');
}
uploadService = uploadServiceFrom(discoverInfo);
}
}
if (uploadService == null) {
throw new SmackException.SmackMessageException("No upload service specified and also none discovered.");
}
if (!uploadService.acceptsFileOfSize(fileSize)) {
throw new IllegalArgumentException(
"Requested file size " + fileSize + " is greater than max allowed size " + uploadService.getMaxFileSize());
}
SlotRequest slotRequest;
switch (uploadService.getVersion()) {
case v0_3:
slotRequest = new SlotRequest(uploadService.getAddress(), filename, fileSize, contentType);
break;
case v0_2:
slotRequest = new SlotRequest_V0_2(uploadService.getAddress(), filename, fileSize, contentType);
break;
default:
throw new AssertionError();
}
return connection.createStanzaCollectorAndSend(slotRequest).nextResultOrThrow();
} | java | public Slot requestSlot(String filename, long fileSize, String contentType, DomainBareJid uploadServiceAddress)
throws SmackException, InterruptedException, XMPPException.XMPPErrorException {
final XMPPConnection connection = connection();
final UploadService defaultUploadService = this.defaultUploadService;
// The upload service we are going to use.
UploadService uploadService;
if (uploadServiceAddress == null) {
uploadService = defaultUploadService;
} else {
if (defaultUploadService != null && defaultUploadService.getAddress().equals(uploadServiceAddress)) {
// Avoid performing a service discovery if we already know about the given service.
uploadService = defaultUploadService;
} else {
DiscoverInfo discoverInfo = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(uploadServiceAddress);
if (!containsHttpFileUploadNamespace(discoverInfo)) {
throw new IllegalArgumentException("There is no HTTP upload service running at the given address '"
+ uploadServiceAddress + '\'');
}
uploadService = uploadServiceFrom(discoverInfo);
}
}
if (uploadService == null) {
throw new SmackException.SmackMessageException("No upload service specified and also none discovered.");
}
if (!uploadService.acceptsFileOfSize(fileSize)) {
throw new IllegalArgumentException(
"Requested file size " + fileSize + " is greater than max allowed size " + uploadService.getMaxFileSize());
}
SlotRequest slotRequest;
switch (uploadService.getVersion()) {
case v0_3:
slotRequest = new SlotRequest(uploadService.getAddress(), filename, fileSize, contentType);
break;
case v0_2:
slotRequest = new SlotRequest_V0_2(uploadService.getAddress(), filename, fileSize, contentType);
break;
default:
throw new AssertionError();
}
return connection.createStanzaCollectorAndSend(slotRequest).nextResultOrThrow();
} | [
"public",
"Slot",
"requestSlot",
"(",
"String",
"filename",
",",
"long",
"fileSize",
",",
"String",
"contentType",
",",
"DomainBareJid",
"uploadServiceAddress",
")",
"throws",
"SmackException",
",",
"InterruptedException",
",",
"XMPPException",
".",
"XMPPErrorException"... | Request a new upload slot with optional content type from custom upload service.
When you get slot you should upload file to PUT URL and share GET URL.
Note that this is a synchronous call -- Smack must wait for the server response.
@param filename name of file to be uploaded
@param fileSize file size in bytes.
@param contentType file content-type or null
@param uploadServiceAddress the address of the upload service to use or null for default one
@return file upload Slot in case of success
@throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
supported by the service.
@throws SmackException
@throws InterruptedException
@throws XMPPException.XMPPErrorException | [
"Request",
"a",
"new",
"upload",
"slot",
"with",
"optional",
"content",
"type",
"from",
"custom",
"upload",
"service",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java#L328-L374 |
real-logic/agrona | agrona/src/main/java/org/agrona/PrintBufferUtil.java | PrintBufferUtil.appendPrettyHexDump | public static void appendPrettyHexDump(final StringBuilder dump, final DirectBuffer buffer)
{
appendPrettyHexDump(dump, buffer, 0, buffer.capacity());
} | java | public static void appendPrettyHexDump(final StringBuilder dump, final DirectBuffer buffer)
{
appendPrettyHexDump(dump, buffer, 0, buffer.capacity());
} | [
"public",
"static",
"void",
"appendPrettyHexDump",
"(",
"final",
"StringBuilder",
"dump",
",",
"final",
"DirectBuffer",
"buffer",
")",
"{",
"appendPrettyHexDump",
"(",
"dump",
",",
"buffer",
",",
"0",
",",
"buffer",
".",
"capacity",
"(",
")",
")",
";",
"}"
] | Appends the prettified multi-line hexadecimal dump of the specified {@link DirectBuffer} to the specified
{@link StringBuilder} that is easy to read by humans.
@param dump where should we append string representation of the buffer
@param buffer dumped buffer | [
"Appends",
"the",
"prettified",
"multi",
"-",
"line",
"hexadecimal",
"dump",
"of",
"the",
"specified",
"{",
"@link",
"DirectBuffer",
"}",
"to",
"the",
"specified",
"{",
"@link",
"StringBuilder",
"}",
"that",
"is",
"easy",
"to",
"read",
"by",
"humans",
"."
] | train | https://github.com/real-logic/agrona/blob/d1ea76e6e3598cd6a0d34879687652ef123f639b/agrona/src/main/java/org/agrona/PrintBufferUtil.java#L135-L138 |
lessthanoptimal/BoofCV | main/boofcv-ip/src/main/java/boofcv/alg/color/ColorHsv.java | ColorHsv.rgbToHsv | public static void rgbToHsv( double r , double g , double b , double []hsv ) {
// Maximum value
double max = r > g ? ( r > b ? r : b) : ( g > b ? g : b );
// Minimum value
double min = r < g ? ( r < b ? r : b) : ( g < b ? g : b );
double delta = max - min;
hsv[2] = max;
if( max != 0 )
hsv[1] = delta / max;
else {
hsv[0] = Double.NaN;
hsv[1] = 0;
return;
}
double h;
if( r == max )
h = ( g - b ) / delta;
else if( g == max )
h = 2 + ( b - r ) / delta;
else
h = 4 + ( r - g ) / delta;
h *= d60_F64;
if( h < 0 )
h += PI2_F64;
hsv[0] = h;
} | java | public static void rgbToHsv( double r , double g , double b , double []hsv ) {
// Maximum value
double max = r > g ? ( r > b ? r : b) : ( g > b ? g : b );
// Minimum value
double min = r < g ? ( r < b ? r : b) : ( g < b ? g : b );
double delta = max - min;
hsv[2] = max;
if( max != 0 )
hsv[1] = delta / max;
else {
hsv[0] = Double.NaN;
hsv[1] = 0;
return;
}
double h;
if( r == max )
h = ( g - b ) / delta;
else if( g == max )
h = 2 + ( b - r ) / delta;
else
h = 4 + ( r - g ) / delta;
h *= d60_F64;
if( h < 0 )
h += PI2_F64;
hsv[0] = h;
} | [
"public",
"static",
"void",
"rgbToHsv",
"(",
"double",
"r",
",",
"double",
"g",
",",
"double",
"b",
",",
"double",
"[",
"]",
"hsv",
")",
"{",
"// Maximum value",
"double",
"max",
"=",
"r",
">",
"g",
"?",
"(",
"r",
">",
"b",
"?",
"r",
":",
"b",
... | Convert RGB color into HSV color
@param r red
@param g green
@param b blue
@param hsv (Output) HSV value. | [
"Convert",
"RGB",
"color",
"into",
"HSV",
"color"
] | train | https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/color/ColorHsv.java#L207-L237 |
exoplatform/jcr | exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LinkGenerator.java | LinkGenerator.simpleWriteString | private void simpleWriteString(String outString, OutputStream outStream) throws IOException
{
for (int i = 0; i < outString.length(); i++)
{
int charCode = outString.charAt(i);
outStream.write(charCode & 0xFF);
outStream.write((charCode >> 8) & 0xFF);
}
} | java | private void simpleWriteString(String outString, OutputStream outStream) throws IOException
{
for (int i = 0; i < outString.length(); i++)
{
int charCode = outString.charAt(i);
outStream.write(charCode & 0xFF);
outStream.write((charCode >> 8) & 0xFF);
}
} | [
"private",
"void",
"simpleWriteString",
"(",
"String",
"outString",
",",
"OutputStream",
"outStream",
")",
"throws",
"IOException",
"{",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"outString",
".",
"length",
"(",
")",
";",
"i",
"++",
")",
"{",
"i... | Writes string into stream.
@param outString string
@param outStream stream
@throws IOException {@link IOException} | [
"Writes",
"string",
"into",
"stream",
"."
] | train | https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/lnkproducer/LinkGenerator.java#L333-L341 |
google/closure-templates | java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java | TranslateToPyExprVisitor.genCodeForKeyAccess | private static String genCodeForKeyAccess(
String containerExpr,
PyExpr key,
NotFoundBehavior notFoundBehavior,
CoerceKeyToString coerceKeyToString) {
if (coerceKeyToString == CoerceKeyToString.YES) {
key = new PyFunctionExprBuilder("runtime.maybe_coerce_key_to_string").addArg(key).asPyExpr();
}
switch (notFoundBehavior.getType()) {
case RETURN_NONE:
return new PyFunctionExprBuilder("runtime.key_safe_data_access")
.addArg(new PyExpr(containerExpr, Integer.MAX_VALUE))
.addArg(key)
.build();
case THROW:
return new PyFunctionExprBuilder(containerExpr + ".get").addArg(key).build();
case DEFAULT_VALUE:
return new PyFunctionExprBuilder(containerExpr + ".get")
.addArg(key)
.addArg(notFoundBehavior.getDefaultValue())
.build();
}
throw new AssertionError(notFoundBehavior.getType());
} | java | private static String genCodeForKeyAccess(
String containerExpr,
PyExpr key,
NotFoundBehavior notFoundBehavior,
CoerceKeyToString coerceKeyToString) {
if (coerceKeyToString == CoerceKeyToString.YES) {
key = new PyFunctionExprBuilder("runtime.maybe_coerce_key_to_string").addArg(key).asPyExpr();
}
switch (notFoundBehavior.getType()) {
case RETURN_NONE:
return new PyFunctionExprBuilder("runtime.key_safe_data_access")
.addArg(new PyExpr(containerExpr, Integer.MAX_VALUE))
.addArg(key)
.build();
case THROW:
return new PyFunctionExprBuilder(containerExpr + ".get").addArg(key).build();
case DEFAULT_VALUE:
return new PyFunctionExprBuilder(containerExpr + ".get")
.addArg(key)
.addArg(notFoundBehavior.getDefaultValue())
.build();
}
throw new AssertionError(notFoundBehavior.getType());
} | [
"private",
"static",
"String",
"genCodeForKeyAccess",
"(",
"String",
"containerExpr",
",",
"PyExpr",
"key",
",",
"NotFoundBehavior",
"notFoundBehavior",
",",
"CoerceKeyToString",
"coerceKeyToString",
")",
"{",
"if",
"(",
"coerceKeyToString",
"==",
"CoerceKeyToString",
"... | Generates the code for key access given the name of a variable to be used as a key, e.g. {@code
.get(key)}.
@param key an expression to be used as a key
@param notFoundBehavior What should happen if the key is not in the structure.
@param coerceKeyToString Whether or not the key should be coerced to a string. | [
"Generates",
"the",
"code",
"for",
"key",
"access",
"given",
"the",
"name",
"of",
"a",
"variable",
"to",
"be",
"used",
"as",
"a",
"key",
"e",
".",
"g",
".",
"{",
"@code",
".",
"get",
"(",
"key",
")",
"}",
"."
] | train | https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/pysrc/internal/TranslateToPyExprVisitor.java#L591-L614 |
xwiki/xwiki-rendering | xwiki-rendering-macros/xwiki-rendering-macro-toc/src/main/java/org/xwiki/rendering/internal/macro/toc/TocTreeBuilder.java | TocTreeBuilder.addItemBlock | private Block addItemBlock(Block currentBlock, HeaderBlock headerBlock, String documentReference)
{
ListItemBlock itemBlock =
headerBlock == null ? createEmptyTocEntry() : createTocEntry(headerBlock, documentReference);
currentBlock.addChild(itemBlock);
return itemBlock;
} | java | private Block addItemBlock(Block currentBlock, HeaderBlock headerBlock, String documentReference)
{
ListItemBlock itemBlock =
headerBlock == null ? createEmptyTocEntry() : createTocEntry(headerBlock, documentReference);
currentBlock.addChild(itemBlock);
return itemBlock;
} | [
"private",
"Block",
"addItemBlock",
"(",
"Block",
"currentBlock",
",",
"HeaderBlock",
"headerBlock",
",",
"String",
"documentReference",
")",
"{",
"ListItemBlock",
"itemBlock",
"=",
"headerBlock",
"==",
"null",
"?",
"createEmptyTocEntry",
"(",
")",
":",
"createTocEn... | Add a {@link ListItemBlock} in the current toc tree block and return the new {@link ListItemBlock}.
@param currentBlock the current block in the toc tree.
@param headerBlock the {@link HeaderBlock} to use to generate toc anchor label.
@return the new {@link ListItemBlock}. | [
"Add",
"a",
"{",
"@link",
"ListItemBlock",
"}",
"in",
"the",
"current",
"toc",
"tree",
"block",
"and",
"return",
"the",
"new",
"{",
"@link",
"ListItemBlock",
"}",
"."
] | train | https://github.com/xwiki/xwiki-rendering/blob/a21cdfcb64ef5b76872e3eedf78c530f26d7beb0/xwiki-rendering-macros/xwiki-rendering-macro-toc/src/main/java/org/xwiki/rendering/internal/macro/toc/TocTreeBuilder.java#L163-L171 |
cdk/cdk | base/standard/src/main/java/org/openscience/cdk/geometry/GeometryUtil.java | GeometryUtil.getScaleFactor | public static double getScaleFactor(IAtomContainer container, double bondLength) {
double currentAverageBondLength = getBondLengthMedian(container);
if (currentAverageBondLength == 0 || Double.isNaN(currentAverageBondLength)) return 1;
return bondLength / currentAverageBondLength;
} | java | public static double getScaleFactor(IAtomContainer container, double bondLength) {
double currentAverageBondLength = getBondLengthMedian(container);
if (currentAverageBondLength == 0 || Double.isNaN(currentAverageBondLength)) return 1;
return bondLength / currentAverageBondLength;
} | [
"public",
"static",
"double",
"getScaleFactor",
"(",
"IAtomContainer",
"container",
",",
"double",
"bondLength",
")",
"{",
"double",
"currentAverageBondLength",
"=",
"getBondLengthMedian",
"(",
"container",
")",
";",
"if",
"(",
"currentAverageBondLength",
"==",
"0",
... | Determines the scale factor for displaying a structure loaded from disk in a frame. An
average of all bond length values is produced and a scale factor is determined which would
scale the given molecule such that its See comment for center(IAtomContainer atomCon,
Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
@param container The AtomContainer for which the ScaleFactor is to be calculated
@param bondLength The target bond length
@return The ScaleFactor with which the AtomContainer must be scaled to have the target bond
length | [
"Determines",
"the",
"scale",
"factor",
"for",
"displaying",
"a",
"structure",
"loaded",
"from",
"disk",
"in",
"a",
"frame",
".",
"An",
"average",
"of",
"all",
"bond",
"length",
"values",
"is",
"produced",
"and",
"a",
"scale",
"factor",
"is",
"determined",
... | train | https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/standard/src/main/java/org/openscience/cdk/geometry/GeometryUtil.java#L898-L902 |
ixa-ehu/ixa-pipe-pos | src/main/java/eus/ixa/ixa/pipe/pos/StatisticalTagger.java | StatisticalTagger.loadModel | private POSModel loadModel(final String lang, final String modelName, final Boolean useModelCache) {
final long lStartTime = new Date().getTime();
POSModel model = null;
try {
if (useModelCache) {
synchronized (posModels) {
if (!posModels.containsKey(lang)) {
model = new POSModel(new FileInputStream(modelName));
posModels.put(lang, model);
}
}
} else {
model = new POSModel(new FileInputStream(modelName));
}
} catch (final IOException e) {
e.printStackTrace();
}
final long lEndTime = new Date().getTime();
final long difference = lEndTime - lStartTime;
System.err.println("ixa-pipe-pos model loaded in: " + difference
+ " miliseconds ... [DONE]");
return model;
} | java | private POSModel loadModel(final String lang, final String modelName, final Boolean useModelCache) {
final long lStartTime = new Date().getTime();
POSModel model = null;
try {
if (useModelCache) {
synchronized (posModels) {
if (!posModels.containsKey(lang)) {
model = new POSModel(new FileInputStream(modelName));
posModels.put(lang, model);
}
}
} else {
model = new POSModel(new FileInputStream(modelName));
}
} catch (final IOException e) {
e.printStackTrace();
}
final long lEndTime = new Date().getTime();
final long difference = lEndTime - lStartTime;
System.err.println("ixa-pipe-pos model loaded in: " + difference
+ " miliseconds ... [DONE]");
return model;
} | [
"private",
"POSModel",
"loadModel",
"(",
"final",
"String",
"lang",
",",
"final",
"String",
"modelName",
",",
"final",
"Boolean",
"useModelCache",
")",
"{",
"final",
"long",
"lStartTime",
"=",
"new",
"Date",
"(",
")",
".",
"getTime",
"(",
")",
";",
"POSMod... | Loads statically the probabilistic model. Every instance of this finder
will share the same model.
@param lang
the language
@param modelName
the model to be loaded
@param useModelCache
whether to cache the model in memory
@return the model as a {@link POSModel} object | [
"Loads",
"statically",
"the",
"probabilistic",
"model",
".",
"Every",
"instance",
"of",
"this",
"finder",
"will",
"share",
"the",
"same",
"model",
"."
] | train | https://github.com/ixa-ehu/ixa-pipe-pos/blob/083c986103f95ae8063b8ddc89a2caa8047d29b9/src/main/java/eus/ixa/ixa/pipe/pos/StatisticalTagger.java#L152-L174 |
raphw/byte-buddy | byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java | MethodHandle.ofLoaded | public static MethodHandle ofLoaded(Object methodHandle, Object lookup) {
if (!JavaType.METHOD_HANDLE.isInstance(methodHandle)) {
throw new IllegalArgumentException("Expected method handle object: " + methodHandle);
} else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) {
throw new IllegalArgumentException("Expected method handle lookup object: " + lookup);
}
Dispatcher dispatcher = DISPATCHER.initialize();
Object methodHandleInfo = dispatcher.reveal(lookup, methodHandle);
Object methodType = dispatcher.getMethodType(methodHandleInfo);
return new MethodHandle(HandleType.of(dispatcher.getReferenceKind(methodHandleInfo)),
TypeDescription.ForLoadedType.of(dispatcher.getDeclaringClass(methodHandleInfo)),
dispatcher.getName(methodHandleInfo),
TypeDescription.ForLoadedType.of(dispatcher.returnType(methodType)),
new TypeList.ForLoadedTypes(dispatcher.parameterArray(methodType)));
} | java | public static MethodHandle ofLoaded(Object methodHandle, Object lookup) {
if (!JavaType.METHOD_HANDLE.isInstance(methodHandle)) {
throw new IllegalArgumentException("Expected method handle object: " + methodHandle);
} else if (!JavaType.METHOD_HANDLES_LOOKUP.isInstance(lookup)) {
throw new IllegalArgumentException("Expected method handle lookup object: " + lookup);
}
Dispatcher dispatcher = DISPATCHER.initialize();
Object methodHandleInfo = dispatcher.reveal(lookup, methodHandle);
Object methodType = dispatcher.getMethodType(methodHandleInfo);
return new MethodHandle(HandleType.of(dispatcher.getReferenceKind(methodHandleInfo)),
TypeDescription.ForLoadedType.of(dispatcher.getDeclaringClass(methodHandleInfo)),
dispatcher.getName(methodHandleInfo),
TypeDescription.ForLoadedType.of(dispatcher.returnType(methodType)),
new TypeList.ForLoadedTypes(dispatcher.parameterArray(methodType)));
} | [
"public",
"static",
"MethodHandle",
"ofLoaded",
"(",
"Object",
"methodHandle",
",",
"Object",
"lookup",
")",
"{",
"if",
"(",
"!",
"JavaType",
".",
"METHOD_HANDLE",
".",
"isInstance",
"(",
"methodHandle",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",... | Creates a method handles representation of a loaded method handle which is analyzed using the given lookup context.
A method handle can only be analyzed on virtual machines that support the corresponding API (Java 7+). For virtual machines before Java 8+,
a method handle instance can only be analyzed by taking advantage of private APIs what might require a access context.
@param methodHandle The loaded method handle to represent.
@param lookup The lookup object to use for analyzing the method handle.
@return A representation of the loaded method handle | [
"Creates",
"a",
"method",
"handles",
"representation",
"of",
"a",
"loaded",
"method",
"handle",
"which",
"is",
"analyzed",
"using",
"the",
"given",
"lookup",
"context",
".",
"A",
"method",
"handle",
"can",
"only",
"be",
"analyzed",
"on",
"virtual",
"machines",... | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L503-L517 |
Alexey1Gavrilov/ExpectIt | expectit-core/src/main/java/net/sf/expectit/ExpectBuilder.java | ExpectBuilder.withTimeout | public final ExpectBuilder withTimeout(long duration, TimeUnit unit) {
validateDuration(duration);
this.timeout = unit.toMillis(duration);
return this;
} | java | public final ExpectBuilder withTimeout(long duration, TimeUnit unit) {
validateDuration(duration);
this.timeout = unit.toMillis(duration);
return this;
} | [
"public",
"final",
"ExpectBuilder",
"withTimeout",
"(",
"long",
"duration",
",",
"TimeUnit",
"unit",
")",
"{",
"validateDuration",
"(",
"duration",
")",
";",
"this",
".",
"timeout",
"=",
"unit",
".",
"toMillis",
"(",
"duration",
")",
";",
"return",
"this",
... | Sets the default timeout in the given unit for expect operations. Optional,
the default value is 30 seconds.
@param duration the timeout value
@param unit the time unit
@return this
@throws java.lang.IllegalArgumentException if the timeout {@code <= 0} | [
"Sets",
"the",
"default",
"timeout",
"in",
"the",
"given",
"unit",
"for",
"expect",
"operations",
".",
"Optional",
"the",
"default",
"value",
"is",
"30",
"seconds",
"."
] | train | https://github.com/Alexey1Gavrilov/ExpectIt/blob/5acbe1f8f895fe1dbd63e29bf3ab8e5bbf0873c3/expectit-core/src/main/java/net/sf/expectit/ExpectBuilder.java#L104-L108 |
amzn/ion-java | src/com/amazon/ion/impl/_Private_Utils.java | _Private_Utils.iterate | public static Iterator<IonValue> iterate(ValueFactory valueFactory,
IonReader input)
{
return new IonIteratorImpl(valueFactory, input);
} | java | public static Iterator<IonValue> iterate(ValueFactory valueFactory,
IonReader input)
{
return new IonIteratorImpl(valueFactory, input);
} | [
"public",
"static",
"Iterator",
"<",
"IonValue",
">",
"iterate",
"(",
"ValueFactory",
"valueFactory",
",",
"IonReader",
"input",
")",
"{",
"return",
"new",
"IonIteratorImpl",
"(",
"valueFactory",
",",
"input",
")",
";",
"}"
] | Create a value iterator from a reader.
Primarily a trampoline for access permission. | [
"Create",
"a",
"value",
"iterator",
"from",
"a",
"reader",
".",
"Primarily",
"a",
"trampoline",
"for",
"access",
"permission",
"."
] | train | https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/impl/_Private_Utils.java#L661-L665 |
xsonorg/xson | src/main/java/org/xson/core/asm/ClassReader.java | ClassReader.readConst | public Object readConst(final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
return Type.getObjectType(readUTF8(index, buf));
// case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
} | java | public Object readConst(final int item, final char[] buf) {
int index = items[item];
switch (b[index - 1]) {
case ClassWriter.INT:
return new Integer(readInt(index));
case ClassWriter.FLOAT:
return new Float(Float.intBitsToFloat(readInt(index)));
case ClassWriter.LONG:
return new Long(readLong(index));
case ClassWriter.DOUBLE:
return new Double(Double.longBitsToDouble(readLong(index)));
case ClassWriter.CLASS:
return Type.getObjectType(readUTF8(index, buf));
// case ClassWriter.STR:
default:
return readUTF8(index, buf);
}
} | [
"public",
"Object",
"readConst",
"(",
"final",
"int",
"item",
",",
"final",
"char",
"[",
"]",
"buf",
")",
"{",
"int",
"index",
"=",
"items",
"[",
"item",
"]",
";",
"switch",
"(",
"b",
"[",
"index",
"-",
"1",
"]",
")",
"{",
"case",
"ClassWriter",
... | Reads a numeric or string constant pool item in {@link #b b}. <i>This
method is intended for {@link Attribute} sub classes, and is normally not
needed by class generators or adapters.</i>
@param item the index of a constant pool item.
@param buf buffer to be used to read the item. This buffer must be
sufficiently large. It is not automatically resized.
@return the {@link Integer}, {@link Float}, {@link Long},
{@link Double}, {@link String} or {@link Type} corresponding to
the given constant pool item. | [
"Reads",
"a",
"numeric",
"or",
"string",
"constant",
"pool",
"item",
"in",
"{",
"@link",
"#b",
"b",
"}",
".",
"<i",
">",
"This",
"method",
"is",
"intended",
"for",
"{",
"@link",
"Attribute",
"}",
"sub",
"classes",
"and",
"is",
"normally",
"not",
"neede... | train | https://github.com/xsonorg/xson/blob/ce1e197ec4ef9be448ed6ca96513e886151f83a9/src/main/java/org/xson/core/asm/ClassReader.java#L1991-L2008 |
OpenTSDB/opentsdb | src/tsd/HttpJsonSerializer.java | HttpJsonSerializer.parsePutV1 | @Override
public List<IncomingDataPoint> parsePutV1() {
if (!query.hasContent()) {
throw new BadRequestException("Missing request content");
}
// convert to a string so we can handle character encoding properly
final String content = query.getContent().trim();
final int firstbyte = content.charAt(0);
try {
if (firstbyte == '{') {
final IncomingDataPoint dp =
JSON.parseToObject(content, IncomingDataPoint.class);
final ArrayList<IncomingDataPoint> dps =
new ArrayList<IncomingDataPoint>(1);
dps.add(dp);
return dps;
} else {
return JSON.parseToObject(content, TR_INCOMING);
}
} catch (IllegalArgumentException iae) {
throw new BadRequestException("Unable to parse the given JSON", iae);
}
} | java | @Override
public List<IncomingDataPoint> parsePutV1() {
if (!query.hasContent()) {
throw new BadRequestException("Missing request content");
}
// convert to a string so we can handle character encoding properly
final String content = query.getContent().trim();
final int firstbyte = content.charAt(0);
try {
if (firstbyte == '{') {
final IncomingDataPoint dp =
JSON.parseToObject(content, IncomingDataPoint.class);
final ArrayList<IncomingDataPoint> dps =
new ArrayList<IncomingDataPoint>(1);
dps.add(dp);
return dps;
} else {
return JSON.parseToObject(content, TR_INCOMING);
}
} catch (IllegalArgumentException iae) {
throw new BadRequestException("Unable to parse the given JSON", iae);
}
} | [
"@",
"Override",
"public",
"List",
"<",
"IncomingDataPoint",
">",
"parsePutV1",
"(",
")",
"{",
"if",
"(",
"!",
"query",
".",
"hasContent",
"(",
")",
")",
"{",
"throw",
"new",
"BadRequestException",
"(",
"\"Missing request content\"",
")",
";",
"}",
"// conve... | Parses one or more data points for storage
@return an array of data points to process for storage
@throws JSONException if parsing failed
@throws BadRequestException if the content was missing or parsing failed | [
"Parses",
"one",
"or",
"more",
"data",
"points",
"for",
"storage"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tsd/HttpJsonSerializer.java#L136-L159 |
igniterealtime/Smack | smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java | HttpFileUploadManager.requestSlot | public Slot requestSlot(String filename, long fileSize) throws InterruptedException,
XMPPException.XMPPErrorException, SmackException {
return requestSlot(filename, fileSize, null, null);
} | java | public Slot requestSlot(String filename, long fileSize) throws InterruptedException,
XMPPException.XMPPErrorException, SmackException {
return requestSlot(filename, fileSize, null, null);
} | [
"public",
"Slot",
"requestSlot",
"(",
"String",
"filename",
",",
"long",
"fileSize",
")",
"throws",
"InterruptedException",
",",
"XMPPException",
".",
"XMPPErrorException",
",",
"SmackException",
"{",
"return",
"requestSlot",
"(",
"filename",
",",
"fileSize",
",",
... | Request a new upload slot from default upload service (if discovered). When you get slot you should upload file
to PUT URL and share GET URL. Note that this is a synchronous call -- Smack must wait for the server response.
@param filename name of file to be uploaded
@param fileSize file size in bytes.
@return file upload Slot in case of success
@throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
supported by the service.
@throws InterruptedException
@throws XMPPException.XMPPErrorException
@throws SmackException.NotConnectedException
@throws SmackException.NoResponseException | [
"Request",
"a",
"new",
"upload",
"slot",
"from",
"default",
"upload",
"service",
"(",
"if",
"discovered",
")",
".",
"When",
"you",
"get",
"slot",
"you",
"should",
"upload",
"file",
"to",
"PUT",
"URL",
"and",
"share",
"GET",
"URL",
".",
"Note",
"that",
... | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-experimental/src/main/java/org/jivesoftware/smackx/httpfileupload/HttpFileUploadManager.java#L283-L286 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java | IoUtil.read | public static String read(FileChannel fileChannel, String charsetName) throws IORuntimeException {
return read(fileChannel, CharsetUtil.charset(charsetName));
} | java | public static String read(FileChannel fileChannel, String charsetName) throws IORuntimeException {
return read(fileChannel, CharsetUtil.charset(charsetName));
} | [
"public",
"static",
"String",
"read",
"(",
"FileChannel",
"fileChannel",
",",
"String",
"charsetName",
")",
"throws",
"IORuntimeException",
"{",
"return",
"read",
"(",
"fileChannel",
",",
"CharsetUtil",
".",
"charset",
"(",
"charsetName",
")",
")",
";",
"}"
] | 从FileChannel中读取内容,读取完毕后并不关闭Channel
@param fileChannel 文件管道
@param charsetName 字符集
@return 内容
@throws IORuntimeException IO异常 | [
"从FileChannel中读取内容,读取完毕后并不关闭Channel"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L493-L495 |
javalite/activejdbc | javalite-common/src/main/java/org/javalite/common/Inflector.java | Inflector.getOtherName | public static String getOtherName(String source, String target){
String other;
if (target.contains(source) && !target.equals(source)) {
int start = target.indexOf(source);
other = start == 0 ? target.substring(source.length()) : target.substring(0, start);
}
else{
return null;
}
if(other.startsWith("_")){
other = other.replaceFirst("_", " ");
}
if(other.endsWith("_")){
byte[] otherb = other.getBytes();
otherb[otherb.length - 1] = ' ';
other = new String(otherb);
}
return other.trim();
} | java | public static String getOtherName(String source, String target){
String other;
if (target.contains(source) && !target.equals(source)) {
int start = target.indexOf(source);
other = start == 0 ? target.substring(source.length()) : target.substring(0, start);
}
else{
return null;
}
if(other.startsWith("_")){
other = other.replaceFirst("_", " ");
}
if(other.endsWith("_")){
byte[] otherb = other.getBytes();
otherb[otherb.length - 1] = ' ';
other = new String(otherb);
}
return other.trim();
} | [
"public",
"static",
"String",
"getOtherName",
"(",
"String",
"source",
",",
"String",
"target",
")",
"{",
"String",
"other",
";",
"if",
"(",
"target",
".",
"contains",
"(",
"source",
")",
"&&",
"!",
"target",
".",
"equals",
"(",
"source",
")",
")",
"{"... | If a table name is made of two other table names (as is typical for many to many relationships),
this method retrieves a name of "another" table from a join table name.
For instance, if a source table is "payer" and the target is "player_game", then the returned value
will be "game".
@param source known table name. It may or may not exist in the target table name.
@param target this is a potential "join" table name.
@return a name of "another" table from a join table name. | [
"If",
"a",
"table",
"name",
"is",
"made",
"of",
"two",
"other",
"table",
"names",
"(",
"as",
"is",
"typical",
"for",
"many",
"to",
"many",
"relationships",
")",
"this",
"method",
"retrieves",
"a",
"name",
"of",
"another",
"table",
"from",
"a",
"join",
... | train | https://github.com/javalite/activejdbc/blob/ffcf5457cace19622a8f71e856cbbbe9e7dd5fcc/javalite-common/src/main/java/org/javalite/common/Inflector.java#L265-L285 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java | ConfigurationReader.parseModeConfig | private void parseModeConfig(final Node node, final ConfigSettings config)
{
String name;
Integer value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING,
value);
}
else if (name.equals(KEY_COUNTER_FULL_REVISION)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.COUNTER_FULL_REVISION, value);
}
}
} | java | private void parseModeConfig(final Node node, final ConfigSettings config)
{
String name;
Integer value;
Node nnode;
NodeList list = node.getChildNodes();
int length = list.getLength();
for (int i = 0; i < length; i++) {
nnode = list.item(i);
name = nnode.getNodeName().toUpperCase();
if (name.equals(KEY_VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.VALUE_MINIMUM_LONGEST_COMMON_SUBSTRING,
value);
}
else if (name.equals(KEY_COUNTER_FULL_REVISION)) {
value = Integer.parseInt(nnode.getChildNodes().item(0)
.getNodeValue());
config.setConfigParameter(
ConfigurationKeys.COUNTER_FULL_REVISION, value);
}
}
} | [
"private",
"void",
"parseModeConfig",
"(",
"final",
"Node",
"node",
",",
"final",
"ConfigSettings",
"config",
")",
"{",
"String",
"name",
";",
"Integer",
"value",
";",
"Node",
"nnode",
";",
"NodeList",
"list",
"=",
"node",
".",
"getChildNodes",
"(",
")",
"... | Parses the mode parameter section.
@param node
Reference to the current used xml node
@param config
Reference to the ConfigSettings | [
"Parses",
"the",
"mode",
"parameter",
"section",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/config/ConfigurationReader.java#L331-L362 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java | ArrayFunctions.arrayPrepend | public static Expression arrayPrepend(JsonArray array, Expression value) {
return arrayPrepend(x(array), value);
} | java | public static Expression arrayPrepend(JsonArray array, Expression value) {
return arrayPrepend(x(array), value);
} | [
"public",
"static",
"Expression",
"arrayPrepend",
"(",
"JsonArray",
"array",
",",
"Expression",
"value",
")",
"{",
"return",
"arrayPrepend",
"(",
"x",
"(",
"array",
")",
",",
"value",
")",
";",
"}"
] | Returned expression results in the new array with value pre-pended. | [
"Returned",
"expression",
"results",
"in",
"the",
"new",
"array",
"with",
"value",
"pre",
"-",
"pended",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/ArrayFunctions.java#L296-L298 |
Waikato/moa | moa/src/main/java/moa/clusterers/clustree/ClusTree.java | ClusTree.insertBreadthFirst | private Entry insertBreadthFirst(ClusKernel newPoint, Budget budget, long timestamp) {
//check all leaf nodes and get the one with the closest entry to newPoint
Node bestFit = findBestLeafNode(newPoint);
bestFit.makeOlder(timestamp, negLambda);
Entry parent = bestFit.getEntries()[0].getParentEntry();
// Search for an Entry with a weight under the threshold.
Entry irrelevantEntry = bestFit.getIrrelevantEntry(this.weightThreshold);
int numFreeEntries = bestFit.numFreeEntries();
Entry newEntry = new Entry(newPoint.getCenter().length,
newPoint, timestamp, parent, bestFit);
//if there is space, add it to the node ( doesn't ever occur, since nodes are created with 3 entries)
if (numFreeEntries>0){
bestFit.addEntry(newEntry, timestamp);
}
//if outdated cluster in this best fitting node, replace it
else if (irrelevantEntry != null) {
irrelevantEntry.overwriteOldEntry(newEntry);
}
//if there is space/outdated cluster on path to top, split. Else merge without split
else {
if (existsOutdatedEntryOnPath(bestFit)||!this.hasMaximalSize()){
// We have to split.
insertHereWithSplit(newEntry, bestFit, timestamp);
}
else {
mergeEntryWithoutSplit(bestFit, newEntry,
timestamp);
}
}
//update all nodes on path to top.
if (bestFit.getEntries()[0].getParentEntry()!=null)
updateToTop(bestFit.getEntries()[0].getParentEntry().getNode());
return null;
} | java | private Entry insertBreadthFirst(ClusKernel newPoint, Budget budget, long timestamp) {
//check all leaf nodes and get the one with the closest entry to newPoint
Node bestFit = findBestLeafNode(newPoint);
bestFit.makeOlder(timestamp, negLambda);
Entry parent = bestFit.getEntries()[0].getParentEntry();
// Search for an Entry with a weight under the threshold.
Entry irrelevantEntry = bestFit.getIrrelevantEntry(this.weightThreshold);
int numFreeEntries = bestFit.numFreeEntries();
Entry newEntry = new Entry(newPoint.getCenter().length,
newPoint, timestamp, parent, bestFit);
//if there is space, add it to the node ( doesn't ever occur, since nodes are created with 3 entries)
if (numFreeEntries>0){
bestFit.addEntry(newEntry, timestamp);
}
//if outdated cluster in this best fitting node, replace it
else if (irrelevantEntry != null) {
irrelevantEntry.overwriteOldEntry(newEntry);
}
//if there is space/outdated cluster on path to top, split. Else merge without split
else {
if (existsOutdatedEntryOnPath(bestFit)||!this.hasMaximalSize()){
// We have to split.
insertHereWithSplit(newEntry, bestFit, timestamp);
}
else {
mergeEntryWithoutSplit(bestFit, newEntry,
timestamp);
}
}
//update all nodes on path to top.
if (bestFit.getEntries()[0].getParentEntry()!=null)
updateToTop(bestFit.getEntries()[0].getParentEntry().getNode());
return null;
} | [
"private",
"Entry",
"insertBreadthFirst",
"(",
"ClusKernel",
"newPoint",
",",
"Budget",
"budget",
",",
"long",
"timestamp",
")",
"{",
"//check all leaf nodes and get the one with the closest entry to newPoint",
"Node",
"bestFit",
"=",
"findBestLeafNode",
"(",
"newPoint",
")... | insert newPoint into the tree using the BreadthFirst strategy, i.e.: insert into
the closest entry in a leaf node.
@param newPoint
@param budget
@param timestamp
@return | [
"insert",
"newPoint",
"into",
"the",
"tree",
"using",
"the",
"BreadthFirst",
"strategy",
"i",
".",
"e",
".",
":",
"insert",
"into",
"the",
"closest",
"entry",
"in",
"a",
"leaf",
"node",
"."
] | train | https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/clustree/ClusTree.java#L214-L247 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SupervisorEndpoint.java | SupervisorEndpoint.registerForMetricsUpdates | @Path("/remote")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response registerForMetricsUpdates(@PathParam("accountSid") final String accountSid,
@Context UriInfo info,
@HeaderParam("Accept") String accept) {
return registerForUpdates(accountSid, info, retrieveMediaType(accept));
} | java | @Path("/remote")
@POST
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public Response registerForMetricsUpdates(@PathParam("accountSid") final String accountSid,
@Context UriInfo info,
@HeaderParam("Accept") String accept) {
return registerForUpdates(accountSid, info, retrieveMediaType(accept));
} | [
"@",
"Path",
"(",
"\"/remote\"",
")",
"@",
"POST",
"@",
"Produces",
"(",
"{",
"MediaType",
".",
"APPLICATION_XML",
",",
"MediaType",
".",
"APPLICATION_JSON",
"}",
")",
"public",
"Response",
"registerForMetricsUpdates",
"(",
"@",
"PathParam",
"(",
"\"accountSid\"... | Register a remote location where Restcomm will send monitoring updates | [
"Register",
"a",
"remote",
"location",
"where",
"Restcomm",
"will",
"send",
"monitoring",
"updates"
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/SupervisorEndpoint.java#L314-L321 |
drewnoakes/metadata-extractor | Source/com/drew/metadata/exif/ExifReader.java | ExifReader.extract | public void extract(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata, int readerOffset, @Nullable Directory parentDirectory)
{
ExifTiffHandler exifTiffHandler = new ExifTiffHandler(metadata, parentDirectory);
try {
// Read the TIFF-formatted Exif data
new TiffReader().processTiff(
reader,
exifTiffHandler,
readerOffset
);
} catch (TiffProcessingException e) {
exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
// TODO what do to with this error state?
e.printStackTrace(System.err);
} catch (IOException e) {
exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
// TODO what do to with this error state?
e.printStackTrace(System.err);
}
} | java | public void extract(@NotNull final RandomAccessReader reader, @NotNull final Metadata metadata, int readerOffset, @Nullable Directory parentDirectory)
{
ExifTiffHandler exifTiffHandler = new ExifTiffHandler(metadata, parentDirectory);
try {
// Read the TIFF-formatted Exif data
new TiffReader().processTiff(
reader,
exifTiffHandler,
readerOffset
);
} catch (TiffProcessingException e) {
exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
// TODO what do to with this error state?
e.printStackTrace(System.err);
} catch (IOException e) {
exifTiffHandler.error("Exception processing TIFF data: " + e.getMessage());
// TODO what do to with this error state?
e.printStackTrace(System.err);
}
} | [
"public",
"void",
"extract",
"(",
"@",
"NotNull",
"final",
"RandomAccessReader",
"reader",
",",
"@",
"NotNull",
"final",
"Metadata",
"metadata",
",",
"int",
"readerOffset",
",",
"@",
"Nullable",
"Directory",
"parentDirectory",
")",
"{",
"ExifTiffHandler",
"exifTif... | Reads TIFF formatted Exif data at a specified offset within a {@link RandomAccessReader}. | [
"Reads",
"TIFF",
"formatted",
"Exif",
"data",
"at",
"a",
"specified",
"offset",
"within",
"a",
"{"
] | train | https://github.com/drewnoakes/metadata-extractor/blob/a958e0b61b50e590731b3be1dca8df8e21ebd43c/Source/com/drew/metadata/exif/ExifReader.java#L81-L101 |
loadcoder/chart-extensions | src/main/java/com/loadcoder/load/jfreechartfixes/XYLineAndShapeRendererExtention.java | XYLineAndShapeRendererExtention.getLegendItem | @Override
public LegendItem getLegendItem(int datasetIndex, int series) {
XYPlot plot = getPlot();
if (plot == null) {
return null;
}
XYDataset dataset = plot.getDataset(datasetIndex);
if (dataset == null) {
return null;
}
//jfreechart diff: set the line paint with the implementation of abstract getLinePaint
Paint linePaint = getLinePaint(series);
String label = getLegendItemLabelGenerator().generateLabel(dataset,
series);
String description = label;
String toolTipText = null;
if (getLegendItemToolTipGenerator() != null) {
toolTipText = getLegendItemToolTipGenerator().generateLabel(
dataset, series);
}
String urlText = null;
if (getLegendItemURLGenerator() != null) {
urlText = getLegendItemURLGenerator().generateLabel(dataset,
series);
}
boolean shapeIsVisible = getItemShapeVisible(series, 0);
Shape shape = lookupLegendShape(series);
boolean shapeIsFilled = getItemShapeFilled(series, 0);
Paint fillPaint = (this.getUseFillPaint() ? lookupSeriesFillPaint(series)
: linePaint);
boolean shapeOutlineVisible = this.getDrawOutlines();
Paint outlinePaint = (this.getUseOutlinePaint() ? lookupSeriesOutlinePaint(
series) : linePaint);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
boolean lineVisible = getItemLineVisible(series, 0);
Stroke lineStroke = lookupSeriesStroke(series);
LegendItem result = new LegendItem(label, description, toolTipText, urlText, shapeIsVisible, shape,
shapeIsFilled, fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible,
this.getLegendLine(), lineStroke, linePaint);
result.setLabelFont(lookupLegendTextFont(series));
Paint labelPaint = lookupLegendTextPaint(series);
if (labelPaint != null) {
result.setLabelPaint(labelPaint);
}
result.setSeriesKey(dataset.getSeriesKey(series));
result.setSeriesIndex(series);
result.setDataset(dataset);
result.setDatasetIndex(datasetIndex);
return result;
} | java | @Override
public LegendItem getLegendItem(int datasetIndex, int series) {
XYPlot plot = getPlot();
if (plot == null) {
return null;
}
XYDataset dataset = plot.getDataset(datasetIndex);
if (dataset == null) {
return null;
}
//jfreechart diff: set the line paint with the implementation of abstract getLinePaint
Paint linePaint = getLinePaint(series);
String label = getLegendItemLabelGenerator().generateLabel(dataset,
series);
String description = label;
String toolTipText = null;
if (getLegendItemToolTipGenerator() != null) {
toolTipText = getLegendItemToolTipGenerator().generateLabel(
dataset, series);
}
String urlText = null;
if (getLegendItemURLGenerator() != null) {
urlText = getLegendItemURLGenerator().generateLabel(dataset,
series);
}
boolean shapeIsVisible = getItemShapeVisible(series, 0);
Shape shape = lookupLegendShape(series);
boolean shapeIsFilled = getItemShapeFilled(series, 0);
Paint fillPaint = (this.getUseFillPaint() ? lookupSeriesFillPaint(series)
: linePaint);
boolean shapeOutlineVisible = this.getDrawOutlines();
Paint outlinePaint = (this.getUseOutlinePaint() ? lookupSeriesOutlinePaint(
series) : linePaint);
Stroke outlineStroke = lookupSeriesOutlineStroke(series);
boolean lineVisible = getItemLineVisible(series, 0);
Stroke lineStroke = lookupSeriesStroke(series);
LegendItem result = new LegendItem(label, description, toolTipText, urlText, shapeIsVisible, shape,
shapeIsFilled, fillPaint, shapeOutlineVisible, outlinePaint, outlineStroke, lineVisible,
this.getLegendLine(), lineStroke, linePaint);
result.setLabelFont(lookupLegendTextFont(series));
Paint labelPaint = lookupLegendTextPaint(series);
if (labelPaint != null) {
result.setLabelPaint(labelPaint);
}
result.setSeriesKey(dataset.getSeriesKey(series));
result.setSeriesIndex(series);
result.setDataset(dataset);
result.setDatasetIndex(datasetIndex);
return result;
} | [
"@",
"Override",
"public",
"LegendItem",
"getLegendItem",
"(",
"int",
"datasetIndex",
",",
"int",
"series",
")",
"{",
"XYPlot",
"plot",
"=",
"getPlot",
"(",
")",
";",
"if",
"(",
"plot",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"XYDataset",
"... | /*
The purpose of this override is to change the behaviour for the visibility of the legend
and how the color of the legend is set. | [
"/",
"*",
"The",
"purpose",
"of",
"this",
"override",
"is",
"to",
"change",
"the",
"behaviour",
"for",
"the",
"visibility",
"of",
"the",
"legend",
"and",
"how",
"the",
"color",
"of",
"the",
"legend",
"is",
"set",
"."
] | train | https://github.com/loadcoder/chart-extensions/blob/ded73ad337d18072b3fd4b1b4e3b7a581567d76d/src/main/java/com/loadcoder/load/jfreechartfixes/XYLineAndShapeRendererExtention.java#L59-L112 |
netty/netty | codec-http2/src/main/java/io/netty/handler/codec/http2/CompressorHttp2ConnectionEncoder.java | CompressorHttp2ConnectionEncoder.newCompressionChannel | private EmbeddedChannel newCompressionChannel(final ChannelHandlerContext ctx, ZlibWrapper wrapper) {
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibEncoder(wrapper, compressionLevel, windowBits,
memLevel));
} | java | private EmbeddedChannel newCompressionChannel(final ChannelHandlerContext ctx, ZlibWrapper wrapper) {
return new EmbeddedChannel(ctx.channel().id(), ctx.channel().metadata().hasDisconnect(),
ctx.channel().config(), ZlibCodecFactory.newZlibEncoder(wrapper, compressionLevel, windowBits,
memLevel));
} | [
"private",
"EmbeddedChannel",
"newCompressionChannel",
"(",
"final",
"ChannelHandlerContext",
"ctx",
",",
"ZlibWrapper",
"wrapper",
")",
"{",
"return",
"new",
"EmbeddedChannel",
"(",
"ctx",
".",
"channel",
"(",
")",
".",
"id",
"(",
")",
",",
"ctx",
".",
"chann... | Generate a new instance of an {@link EmbeddedChannel} capable of compressing data
@param ctx the context.
@param wrapper Defines what type of encoder should be used | [
"Generate",
"a",
"new",
"instance",
"of",
"an",
"{"
] | train | https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http2/src/main/java/io/netty/handler/codec/http2/CompressorHttp2ConnectionEncoder.java#L222-L226 |
ironjacamar/ironjacamar | codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AsCodeGen.java | AsCodeGen.writeImport | @Override
public void writeImport(Definition def, Writer out) throws IOException
{
out.write("package " + def.getRaPackage() + ".inflow;\n\n");
importLogging(def, out);
if (def.isUseAnnotation())
{
out.write("import javax.resource.spi.Activation;");
writeEol(out);
}
out.write("import javax.resource.spi.ActivationSpec;\n");
if (def.isUseAnnotation())
{
importConfigProperty(def, out);
}
out.write("import javax.resource.spi.InvalidPropertyException;\n");
out.write("import javax.resource.spi.ResourceAdapter;\n");
if (def.isUseAnnotation())
{
for (int i = 0; i < getConfigProps(def).size(); i++)
{
if (getConfigProps(def).get(i).isRequired())
{
out.write("import javax.validation.constraints.NotNull;\n");
break;
}
}
}
} | java | @Override
public void writeImport(Definition def, Writer out) throws IOException
{
out.write("package " + def.getRaPackage() + ".inflow;\n\n");
importLogging(def, out);
if (def.isUseAnnotation())
{
out.write("import javax.resource.spi.Activation;");
writeEol(out);
}
out.write("import javax.resource.spi.ActivationSpec;\n");
if (def.isUseAnnotation())
{
importConfigProperty(def, out);
}
out.write("import javax.resource.spi.InvalidPropertyException;\n");
out.write("import javax.resource.spi.ResourceAdapter;\n");
if (def.isUseAnnotation())
{
for (int i = 0; i < getConfigProps(def).size(); i++)
{
if (getConfigProps(def).get(i).isRequired())
{
out.write("import javax.validation.constraints.NotNull;\n");
break;
}
}
}
} | [
"@",
"Override",
"public",
"void",
"writeImport",
"(",
"Definition",
"def",
",",
"Writer",
"out",
")",
"throws",
"IOException",
"{",
"out",
".",
"write",
"(",
"\"package \"",
"+",
"def",
".",
"getRaPackage",
"(",
")",
"+",
"\".inflow;\\n\\n\"",
")",
";",
"... | Output class import
@param def definition
@param out Writer
@throws IOException ioException | [
"Output",
"class",
"import"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/AsCodeGen.java#L146-L176 |
gallandarakhneorg/afc | core/vmutils/src/main/java/org/arakhne/afc/vmutil/Resources.java | Resources.getResourceAsStream | @Pure
public static InputStream getResourceAsStream(ClassLoader classLoader, Package packagename, String path) {
if (packagename == null || path == null) {
return null;
}
final StringBuilder b = new StringBuilder();
b.append(packagename.getName().replaceAll(
Pattern.quote("."), //$NON-NLS-1$
Matcher.quoteReplacement(NAME_SEPARATOR)));
if (!path.startsWith(NAME_SEPARATOR)) {
b.append(NAME_SEPARATOR);
}
b.append(path);
ClassLoader cl = classLoader;
if (cl == null) {
cl = packagename.getClass().getClassLoader();
}
return getResourceAsStream(cl, b.toString());
} | java | @Pure
public static InputStream getResourceAsStream(ClassLoader classLoader, Package packagename, String path) {
if (packagename == null || path == null) {
return null;
}
final StringBuilder b = new StringBuilder();
b.append(packagename.getName().replaceAll(
Pattern.quote("."), //$NON-NLS-1$
Matcher.quoteReplacement(NAME_SEPARATOR)));
if (!path.startsWith(NAME_SEPARATOR)) {
b.append(NAME_SEPARATOR);
}
b.append(path);
ClassLoader cl = classLoader;
if (cl == null) {
cl = packagename.getClass().getClassLoader();
}
return getResourceAsStream(cl, b.toString());
} | [
"@",
"Pure",
"public",
"static",
"InputStream",
"getResourceAsStream",
"(",
"ClassLoader",
"classLoader",
",",
"Package",
"packagename",
",",
"String",
"path",
")",
"{",
"if",
"(",
"packagename",
"==",
"null",
"||",
"path",
"==",
"null",
")",
"{",
"return",
... | Replies the input stream of a resource.
<p>You may use Unix-like syntax to write the resource path, ie.
you may use slashes to separate filenames.
<p>The name of {@code packagename} is translated into a resource
path (by replacing the dots by slashes) and the given path
is append to. For example, the two following codes are equivalent:<pre><code>
Resources.getResources(Package.getPackage("org.arakhne.afc"), "/a/b/c/d.png");
Resources.getResources("org/arakhne/afc/a/b/c/d.png");
</code></pre>
<p>If the {@code classLoader} parameter is <code>null</code>,
the class loader replied by {@link ClassLoaderFinder} is used.
If this last is <code>null</code>, the class loader of
the Resources class is used.
@param classLoader is the research scope. If <code>null</code>,
the class loader replied by {@link ClassLoaderFinder} is used.
@param packagename is the package in which the resource should be located.
@param path is the relative path of the resource in the package.
@return the url of the resource or <code>null</code> if the resource was
not found in class paths.
@since 6.2 | [
"Replies",
"the",
"input",
"stream",
"of",
"a",
"resource",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/vmutils/src/main/java/org/arakhne/afc/vmutil/Resources.java#L244-L262 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/tai/TAISubjectUtils.java | TAISubjectUtils.createResult | @FFDCIgnore(SettingCustomPropertiesException.class)
public TAIResult createResult(HttpServletResponse res, SocialLoginConfig clientConfig) throws WebTrustAssociationFailedException, SocialLoginException {
Hashtable<String, Object> customProperties = new Hashtable<String, Object>();
try {
customProperties = setAllCustomProperties(clientConfig);
} catch (SettingCustomPropertiesException e) {
// Error occurred populating subject builder properties; any error should have already been logged, so just return the result
return taiWebUtils.sendToErrorPage(res, TAIResult.create(HttpServletResponse.SC_UNAUTHORIZED));
}
Subject subject = buildSubject(clientConfig, customProperties);
return TAIResult.create(HttpServletResponse.SC_OK, username, subject);
} | java | @FFDCIgnore(SettingCustomPropertiesException.class)
public TAIResult createResult(HttpServletResponse res, SocialLoginConfig clientConfig) throws WebTrustAssociationFailedException, SocialLoginException {
Hashtable<String, Object> customProperties = new Hashtable<String, Object>();
try {
customProperties = setAllCustomProperties(clientConfig);
} catch (SettingCustomPropertiesException e) {
// Error occurred populating subject builder properties; any error should have already been logged, so just return the result
return taiWebUtils.sendToErrorPage(res, TAIResult.create(HttpServletResponse.SC_UNAUTHORIZED));
}
Subject subject = buildSubject(clientConfig, customProperties);
return TAIResult.create(HttpServletResponse.SC_OK, username, subject);
} | [
"@",
"FFDCIgnore",
"(",
"SettingCustomPropertiesException",
".",
"class",
")",
"public",
"TAIResult",
"createResult",
"(",
"HttpServletResponse",
"res",
",",
"SocialLoginConfig",
"clientConfig",
")",
"throws",
"WebTrustAssociationFailedException",
",",
"SocialLoginException",... | Populates a series of custom properties based on the user API response tokens/string and JWT used to instantiate the
object, builds a subject using those custom properties as private credentials, and returns a TAIResult with the produced
username and subject. | [
"Populates",
"a",
"series",
"of",
"custom",
"properties",
"based",
"on",
"the",
"user",
"API",
"response",
"tokens",
"/",
"string",
"and",
"JWT",
"used",
"to",
"instantiate",
"the",
"object",
"builds",
"a",
"subject",
"using",
"those",
"custom",
"properties",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/tai/TAISubjectUtils.java#L87-L98 |
apache/flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/legacy/files/StaticFileServerHandler.java | StaticFileServerHandler.sendNotModified | public static void sendNotModified(ChannelHandlerContext ctx) {
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
setDateHeader(response);
// close the connection as soon as the error message is sent.
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} | java | public static void sendNotModified(ChannelHandlerContext ctx) {
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, NOT_MODIFIED);
setDateHeader(response);
// close the connection as soon as the error message is sent.
ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
} | [
"public",
"static",
"void",
"sendNotModified",
"(",
"ChannelHandlerContext",
"ctx",
")",
"{",
"FullHttpResponse",
"response",
"=",
"new",
"DefaultFullHttpResponse",
"(",
"HTTP_1_1",
",",
"NOT_MODIFIED",
")",
";",
"setDateHeader",
"(",
"response",
")",
";",
"// close... | Send the "304 Not Modified" response. This response can be used when the
file timestamp is the same as what the browser is sending up.
@param ctx The channel context to write the response to. | [
"Send",
"the",
"304",
"Not",
"Modified",
"response",
".",
"This",
"response",
"can",
"be",
"used",
"when",
"the",
"file",
"timestamp",
"is",
"the",
"same",
"as",
"what",
"the",
"browser",
"is",
"sending",
"up",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/rest/handler/legacy/files/StaticFileServerHandler.java#L324-L330 |
OpenLiberty/open-liberty | dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/processor/ClientInjectionBinding.java | ClientInjectionBinding.getInjectionTarget | public static InjectionTarget getInjectionTarget(ComponentNameSpaceConfiguration compNSConfig, ClientInjection injection)
throws InjectionException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getInjectionTarget: " + injection);
// Create a temporary InjectionBinding in order to resolve the target.
ClientInjectionBinding binding = new ClientInjectionBinding(compNSConfig, injection);
Class<?> injectionType = binding.loadClass(injection.getInjectionTypeName());
String targetName = injection.getTargetName();
String targetClassName = injection.getTargetClassName();
// Add a single injection target and then retrieve it.
binding.addInjectionTarget(injectionType, targetName, targetClassName);
InjectionTarget target = InjectionProcessorContextImpl.getInjectionTargets(binding).get(0);
binding.metadataProcessingComplete(); // d681767
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "getInjectionTarget: " + target);
return target;
} | java | public static InjectionTarget getInjectionTarget(ComponentNameSpaceConfiguration compNSConfig, ClientInjection injection)
throws InjectionException
{
final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
if (isTraceOn && tc.isEntryEnabled())
Tr.entry(tc, "getInjectionTarget: " + injection);
// Create a temporary InjectionBinding in order to resolve the target.
ClientInjectionBinding binding = new ClientInjectionBinding(compNSConfig, injection);
Class<?> injectionType = binding.loadClass(injection.getInjectionTypeName());
String targetName = injection.getTargetName();
String targetClassName = injection.getTargetClassName();
// Add a single injection target and then retrieve it.
binding.addInjectionTarget(injectionType, targetName, targetClassName);
InjectionTarget target = InjectionProcessorContextImpl.getInjectionTargets(binding).get(0);
binding.metadataProcessingComplete(); // d681767
if (isTraceOn && tc.isEntryEnabled())
Tr.exit(tc, "getInjectionTarget: " + target);
return target;
} | [
"public",
"static",
"InjectionTarget",
"getInjectionTarget",
"(",
"ComponentNameSpaceConfiguration",
"compNSConfig",
",",
"ClientInjection",
"injection",
")",
"throws",
"InjectionException",
"{",
"final",
"boolean",
"isTraceOn",
"=",
"TraceComponent",
".",
"isAnyTracingEnable... | Acquires an InjectionTarget for the specified ClientInjection.
@param compNSConfig the minimal namespace configuration
@param injection the injection target descriptor
@return the injection target
@throws InjectionException if the target cannot be acquired | [
"Acquires",
"an",
"InjectionTarget",
"for",
"the",
"specified",
"ClientInjection",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.injection.core/src/com/ibm/ws/injectionengine/processor/ClientInjectionBinding.java#L49-L70 |
lightblueseas/vintage-time | src/main/java/de/alpharogroup/date/CalculateDateExtensions.java | CalculateDateExtensions.addMonths | public static Date addMonths(final Date date, final int addMonths)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.MONTH, addMonths);
return dateOnCalendar.getTime();
} | java | public static Date addMonths(final Date date, final int addMonths)
{
final Calendar dateOnCalendar = Calendar.getInstance();
dateOnCalendar.setTime(date);
dateOnCalendar.add(Calendar.MONTH, addMonths);
return dateOnCalendar.getTime();
} | [
"public",
"static",
"Date",
"addMonths",
"(",
"final",
"Date",
"date",
",",
"final",
"int",
"addMonths",
")",
"{",
"final",
"Calendar",
"dateOnCalendar",
"=",
"Calendar",
".",
"getInstance",
"(",
")",
";",
"dateOnCalendar",
".",
"setTime",
"(",
"date",
")",
... | Adds months to the given Date object and returns it. Note: you can add negative values too
for get date in past.
@param date
The Date object to add the years.
@param addMonths
The months to add.
@return The resulted Date object. | [
"Adds",
"months",
"to",
"the",
"given",
"Date",
"object",
"and",
"returns",
"it",
".",
"Note",
":",
"you",
"can",
"add",
"negative",
"values",
"too",
"for",
"get",
"date",
"in",
"past",
"."
] | train | https://github.com/lightblueseas/vintage-time/blob/fbf201e679d9f9b92e7b5771f3eea1413cc2e113/src/main/java/de/alpharogroup/date/CalculateDateExtensions.java#L128-L134 |
alipay/sofa-rpc | extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/ProviderInfoWeightManager.java | ProviderInfoWeightManager.recoverOriginWeight | public static void recoverOriginWeight(ProviderInfo providerInfo, int originWeight) {
providerInfo.setStatus(ProviderStatus.AVAILABLE);
providerInfo.setWeight(originWeight);
} | java | public static void recoverOriginWeight(ProviderInfo providerInfo, int originWeight) {
providerInfo.setStatus(ProviderStatus.AVAILABLE);
providerInfo.setWeight(originWeight);
} | [
"public",
"static",
"void",
"recoverOriginWeight",
"(",
"ProviderInfo",
"providerInfo",
",",
"int",
"originWeight",
")",
"{",
"providerInfo",
".",
"setStatus",
"(",
"ProviderStatus",
".",
"AVAILABLE",
")",
";",
"providerInfo",
".",
"setWeight",
"(",
"originWeight",
... | Recover weight of provider info, and set default status
@param providerInfo ProviderInfo
@param originWeight origin weight | [
"Recover",
"weight",
"of",
"provider",
"info",
"and",
"set",
"default",
"status"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/fault-tolerance/src/main/java/com/alipay/sofa/rpc/client/aft/ProviderInfoWeightManager.java#L61-L64 |
greengerong/prerender-java | src/main/java/com/github/greengerong/PrerenderSeoService.java | PrerenderSeoService.responseEntity | private void responseEntity(String html, HttpServletResponse servletResponse)
throws IOException {
PrintWriter printWriter = servletResponse.getWriter();
try {
printWriter.write(html);
printWriter.flush();
} finally {
closeQuietly(printWriter);
}
} | java | private void responseEntity(String html, HttpServletResponse servletResponse)
throws IOException {
PrintWriter printWriter = servletResponse.getWriter();
try {
printWriter.write(html);
printWriter.flush();
} finally {
closeQuietly(printWriter);
}
} | [
"private",
"void",
"responseEntity",
"(",
"String",
"html",
",",
"HttpServletResponse",
"servletResponse",
")",
"throws",
"IOException",
"{",
"PrintWriter",
"printWriter",
"=",
"servletResponse",
".",
"getWriter",
"(",
")",
";",
"try",
"{",
"printWriter",
".",
"wr... | Copy response body data (the entity) from the proxy to the servlet client. | [
"Copy",
"response",
"body",
"data",
"(",
"the",
"entity",
")",
"from",
"the",
"proxy",
"to",
"the",
"servlet",
"client",
"."
] | train | https://github.com/greengerong/prerender-java/blob/f7fc7a5e9adea8cf556c653a87bbac2cfcac3d06/src/main/java/com/github/greengerong/PrerenderSeoService.java#L256-L265 |
allengeorge/libraft | libraft-samples/kayvee/src/main/java/io/libraft/kayvee/resources/KeyResource.java | KeyResource.update | @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public @Nullable KeyValue update(SetValue setValue) throws Exception {
if (!setValue.hasNewValue() && !setValue.hasExpectedValue()) {
throw new IllegalArgumentException(String.format("key:%s - bad request: expectedValue and newValue not set", key));
}
if (setValue.hasExpectedValue()) {
return compareAndSet(setValue);
} else {
return set(setValue);
}
} | java | @PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public @Nullable KeyValue update(SetValue setValue) throws Exception {
if (!setValue.hasNewValue() && !setValue.hasExpectedValue()) {
throw new IllegalArgumentException(String.format("key:%s - bad request: expectedValue and newValue not set", key));
}
if (setValue.hasExpectedValue()) {
return compareAndSet(setValue);
} else {
return set(setValue);
}
} | [
"@",
"PUT",
"@",
"Consumes",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"@",
"Produces",
"(",
"MediaType",
".",
"APPLICATION_JSON",
")",
"public",
"@",
"Nullable",
"KeyValue",
"update",
"(",
"SetValue",
"setValue",
")",
"throws",
"Exception",
"{",
"if",
... | Perform a {@code SET} or {@code CAS} on the {@link KeyResource#key} represented by this resource.
<p/>
The rules for {@code SET} and {@code CAS} are
described in the KayVee README.md. Additional validation of
{@code setValue} is performed to ensure that its
fields meet the preconditions for these operations.
@param setValue valid instance of {@code SetValue} with fields set
appropriately for the invoked operation
@return new value associated with the {@link KeyResource#key} represented by this resource.
May be null if this key was deleted from replicated storage
@throws CannotSubmitCommandException if this server is not the
leader of the Raft cluster and cannot submit commands to the cluster
@throws Exception if this operation cannot be replicated to the Raft cluster. If an exception is
thrown this operation is in an <strong>unknown</strong> state, and should be retried
@see KayVeeCommand | [
"Perform",
"a",
"{",
"@code",
"SET",
"}",
"or",
"{",
"@code",
"CAS",
"}",
"on",
"the",
"{",
"@link",
"KeyResource#key",
"}",
"represented",
"by",
"this",
"resource",
".",
"<p",
"/",
">",
"The",
"rules",
"for",
"{",
"@code",
"SET",
"}",
"and",
"{",
... | train | https://github.com/allengeorge/libraft/blob/00d68bb5e68d4020af59df3c8a9a14380108ac89/libraft-samples/kayvee/src/main/java/io/libraft/kayvee/resources/KeyResource.java#L149-L162 |
BorderTech/wcomponents | wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WDropdownOptionsExample.java | WDropdownOptionsExample.getDropDownControls | private WFieldSet getDropDownControls() {
WFieldSet fieldSet = new WFieldSet("Drop down configuration");
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
fieldSet.add(layout);
rbsDDType.setButtonLayout(WRadioButtonSelect.LAYOUT_FLAT);
rbsDDType.setSelected(WDropdown.DropdownType.NATIVE);
rbsDDType.setFrameless(true);
layout.addField("Dropdown Type", rbsDDType);
nfWidth.setMinValue(0);
nfWidth.setDecimalPlaces(0);
layout.addField("Width", nfWidth);
layout.addField("ToolTip", tfToolTip);
layout.addField("Include null option", cbNullOption);
rgDefaultOption.setButtonLayout(WRadioButtonSelect.LAYOUT_COLUMNS);
rgDefaultOption.setButtonColumns(2);
rgDefaultOption.setSelected(NONE);
rgDefaultOption.setFrameless(true);
layout.addField("Default Option", rgDefaultOption);
layout.addField("Action on change", cbActionOnChange);
layout.addField("Ajax", cbAjax);
WField subField = layout.addField("Subordinate", cbSubordinate);
//.getLabel().setHint("Does not work with Dropdown Type COMBO");
layout.addField("Submit on change", cbSubmitOnChange);
layout.addField("Visible", cbVisible);
layout.addField("Disabled", cbDisabled);
// Apply Button
WButton apply = new WButton("Apply");
fieldSet.add(apply);
WSubordinateControl subSubControl = new WSubordinateControl();
Rule rule = new Rule();
subSubControl.addRule(rule);
rule.setCondition(new Equal(rbsDDType, WDropdown.DropdownType.COMBO));
rule.addActionOnTrue(new Disable(subField));
rule.addActionOnFalse(new Enable(subField));
fieldSet.add(subSubControl);
apply.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
applySettings();
}
});
return fieldSet;
} | java | private WFieldSet getDropDownControls() {
WFieldSet fieldSet = new WFieldSet("Drop down configuration");
WFieldLayout layout = new WFieldLayout();
layout.setLabelWidth(25);
fieldSet.add(layout);
rbsDDType.setButtonLayout(WRadioButtonSelect.LAYOUT_FLAT);
rbsDDType.setSelected(WDropdown.DropdownType.NATIVE);
rbsDDType.setFrameless(true);
layout.addField("Dropdown Type", rbsDDType);
nfWidth.setMinValue(0);
nfWidth.setDecimalPlaces(0);
layout.addField("Width", nfWidth);
layout.addField("ToolTip", tfToolTip);
layout.addField("Include null option", cbNullOption);
rgDefaultOption.setButtonLayout(WRadioButtonSelect.LAYOUT_COLUMNS);
rgDefaultOption.setButtonColumns(2);
rgDefaultOption.setSelected(NONE);
rgDefaultOption.setFrameless(true);
layout.addField("Default Option", rgDefaultOption);
layout.addField("Action on change", cbActionOnChange);
layout.addField("Ajax", cbAjax);
WField subField = layout.addField("Subordinate", cbSubordinate);
//.getLabel().setHint("Does not work with Dropdown Type COMBO");
layout.addField("Submit on change", cbSubmitOnChange);
layout.addField("Visible", cbVisible);
layout.addField("Disabled", cbDisabled);
// Apply Button
WButton apply = new WButton("Apply");
fieldSet.add(apply);
WSubordinateControl subSubControl = new WSubordinateControl();
Rule rule = new Rule();
subSubControl.addRule(rule);
rule.setCondition(new Equal(rbsDDType, WDropdown.DropdownType.COMBO));
rule.addActionOnTrue(new Disable(subField));
rule.addActionOnFalse(new Enable(subField));
fieldSet.add(subSubControl);
apply.setAction(new Action() {
@Override
public void execute(final ActionEvent event) {
applySettings();
}
});
return fieldSet;
} | [
"private",
"WFieldSet",
"getDropDownControls",
"(",
")",
"{",
"WFieldSet",
"fieldSet",
"=",
"new",
"WFieldSet",
"(",
"\"Drop down configuration\"",
")",
";",
"WFieldLayout",
"layout",
"=",
"new",
"WFieldLayout",
"(",
")",
";",
"layout",
".",
"setLabelWidth",
"(",
... | build the drop down controls.
@return a field set containing the dropdown controls. | [
"build",
"the",
"drop",
"down",
"controls",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WDropdownOptionsExample.java#L161-L213 |
gallandarakhneorg/afc | advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java | MapComposedElement.addPoint | public int addPoint(double x, double y) {
int pointIndex;
if (this.pointCoordinates == null) {
this.pointCoordinates = new double[] {x, y};
this.partIndexes = null;
pointIndex = 0;
} else {
double[] pts = new double[this.pointCoordinates.length + 2];
System.arraycopy(this.pointCoordinates, 0, pts, 0, this.pointCoordinates.length);
pointIndex = pts.length - 2;
pts[pointIndex] = x;
pts[pointIndex + 1] = y;
this.pointCoordinates = pts;
pts = null;
pointIndex /= 2;
}
fireShapeChanged();
fireElementChanged();
return pointIndex;
} | java | public int addPoint(double x, double y) {
int pointIndex;
if (this.pointCoordinates == null) {
this.pointCoordinates = new double[] {x, y};
this.partIndexes = null;
pointIndex = 0;
} else {
double[] pts = new double[this.pointCoordinates.length + 2];
System.arraycopy(this.pointCoordinates, 0, pts, 0, this.pointCoordinates.length);
pointIndex = pts.length - 2;
pts[pointIndex] = x;
pts[pointIndex + 1] = y;
this.pointCoordinates = pts;
pts = null;
pointIndex /= 2;
}
fireShapeChanged();
fireElementChanged();
return pointIndex;
} | [
"public",
"int",
"addPoint",
"(",
"double",
"x",
",",
"double",
"y",
")",
"{",
"int",
"pointIndex",
";",
"if",
"(",
"this",
".",
"pointCoordinates",
"==",
"null",
")",
"{",
"this",
".",
"pointCoordinates",
"=",
"new",
"double",
"[",
"]",
"{",
"x",
",... | Add the specified point at the end of the last group.
@param x x coordinate
@param y y coordinate
@return the index of the new point in the element. | [
"Add",
"the",
"specified",
"point",
"at",
"the",
"end",
"of",
"the",
"last",
"group",
"."
] | train | https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscore/src/main/java/org/arakhne/afc/gis/mapelement/MapComposedElement.java#L559-L582 |
sdl/odata | odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java | AtomDataWriter.marshallStructured | private void marshallStructured(final Object object, StructuredType structuredType)
throws ODataRenderException, XMLStreamException {
LOG.trace("Start structured value of type: {}", structuredType);
if (object != null) {
visitProperties(entityDataModel, structuredType, property -> {
try {
if (!(property instanceof NavigationProperty)) {
marshallStructuralProperty(object, property);
}
} catch (XMLStreamException e) {
throw new ODataRenderException("Error while writing property: " + property.getName(), e);
}
});
} else {
LOG.trace("Structured value is null");
}
LOG.trace("End structured value of type: {}", structuredType);
} | java | private void marshallStructured(final Object object, StructuredType structuredType)
throws ODataRenderException, XMLStreamException {
LOG.trace("Start structured value of type: {}", structuredType);
if (object != null) {
visitProperties(entityDataModel, structuredType, property -> {
try {
if (!(property instanceof NavigationProperty)) {
marshallStructuralProperty(object, property);
}
} catch (XMLStreamException e) {
throw new ODataRenderException("Error while writing property: " + property.getName(), e);
}
});
} else {
LOG.trace("Structured value is null");
}
LOG.trace("End structured value of type: {}", structuredType);
} | [
"private",
"void",
"marshallStructured",
"(",
"final",
"Object",
"object",
",",
"StructuredType",
"structuredType",
")",
"throws",
"ODataRenderException",
",",
"XMLStreamException",
"{",
"LOG",
".",
"trace",
"(",
"\"Start structured value of type: {}\"",
",",
"structuredT... | Marshall an object that is of an OData structured type (entity type or complex type).
@param object The object to marshall. Can be {@code null}.
@param structuredType The structured type.
@throws ODataRenderException If an error occurs while rendering.
@throws XMLStreamException If an error occurs while rendering. | [
"Marshall",
"an",
"object",
"that",
"is",
"of",
"an",
"OData",
"structured",
"type",
"(",
"entity",
"type",
"or",
"complex",
"type",
")",
"."
] | train | https://github.com/sdl/odata/blob/eb747d73e9af0f4e59a25b82ed656e526a7e2189/odata_renderer/src/main/java/com/sdl/odata/renderer/atom/writer/AtomDataWriter.java#L159-L179 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java | MapCircuitExtractor.getCircuitType | private static CircuitType getCircuitType(String groupIn, Collection<String> neighborGroups)
{
final boolean[] bits = new boolean[CircuitType.BITS];
int i = CircuitType.BITS - 1;
for (final String neighborGroup : neighborGroups)
{
bits[i] = groupIn.equals(neighborGroup);
i--;
}
return CircuitType.from(bits);
} | java | private static CircuitType getCircuitType(String groupIn, Collection<String> neighborGroups)
{
final boolean[] bits = new boolean[CircuitType.BITS];
int i = CircuitType.BITS - 1;
for (final String neighborGroup : neighborGroups)
{
bits[i] = groupIn.equals(neighborGroup);
i--;
}
return CircuitType.from(bits);
} | [
"private",
"static",
"CircuitType",
"getCircuitType",
"(",
"String",
"groupIn",
",",
"Collection",
"<",
"String",
">",
"neighborGroups",
")",
"{",
"final",
"boolean",
"[",
"]",
"bits",
"=",
"new",
"boolean",
"[",
"CircuitType",
".",
"BITS",
"]",
";",
"int",
... | Get the circuit type from one group to another.
@param groupIn The group in.
@param neighborGroups The neighbor groups.
@return The tile circuit. | [
"Get",
"the",
"circuit",
"type",
"from",
"one",
"group",
"to",
"another",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java#L75-L85 |
javagl/ND | nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java | LongTuples.asList | public static List<Long> asList(final MutableLongTuple t)
{
if (t == null)
{
throw new NullPointerException("The tuple may not be null");
}
return new AbstractList<Long>()
{
@Override
public Long get(int index)
{
return t.get(index);
}
@Override
public int size()
{
return t.getSize();
}
@Override
public Long set(int index, Long element)
{
long oldValue = t.get(index);
t.set(index, element);
return oldValue;
}
};
} | java | public static List<Long> asList(final MutableLongTuple t)
{
if (t == null)
{
throw new NullPointerException("The tuple may not be null");
}
return new AbstractList<Long>()
{
@Override
public Long get(int index)
{
return t.get(index);
}
@Override
public int size()
{
return t.getSize();
}
@Override
public Long set(int index, Long element)
{
long oldValue = t.get(index);
t.set(index, element);
return oldValue;
}
};
} | [
"public",
"static",
"List",
"<",
"Long",
">",
"asList",
"(",
"final",
"MutableLongTuple",
"t",
")",
"{",
"if",
"(",
"t",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"The tuple may not be null\"",
")",
";",
"}",
"return",
"new",
"... | Returns a <i>view</i> on the given tuple as a list that does not
allow <i>structural</i> modifications. Changes in the list will
write through to the given tuple. Changes in the backing tuple
will be visible in the returned list. The list will not permit
<code>null</code> elements.
@param t The tuple
@return The list
@throws NullPointerException If the given tuple is <code>null</code> | [
"Returns",
"a",
"<i",
">",
"view<",
"/",
"i",
">",
"on",
"the",
"given",
"tuple",
"as",
"a",
"list",
"that",
"does",
"not",
"allow",
"<i",
">",
"structural<",
"/",
"i",
">",
"modifications",
".",
"Changes",
"in",
"the",
"list",
"will",
"write",
"thro... | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-tuples/src/main/java/de/javagl/nd/tuples/j/LongTuples.java#L315-L343 |
carewebframework/carewebframework-core | org.carewebframework.help-parent/org.carewebframework.help.ohj/src/main/java/org/carewebframework/help/ohj/HelpView.java | HelpView.initTopicTree | private void initTopicTree(HelpTopicNode htnParent, List<?> children) {
if (children != null) {
for (Object node : children) {
TopicTreeNode ttnChild = (TopicTreeNode) node;
Topic topic = ttnChild.getTopic();
Target target = topic.getTarget();
String source = view.getBook().getBookTitle();
URL url = null;
try {
url = target == null ? null : target.getURL();
} catch (MalformedURLException e) {}
HelpTopic ht = new HelpTopic(url, topic.getLabel(), source);
HelpTopicNode htnChild = new HelpTopicNode(ht);
htnParent.addChild(htnChild);
initTopicTree(htnChild, ttnChild);
}
}
} | java | private void initTopicTree(HelpTopicNode htnParent, List<?> children) {
if (children != null) {
for (Object node : children) {
TopicTreeNode ttnChild = (TopicTreeNode) node;
Topic topic = ttnChild.getTopic();
Target target = topic.getTarget();
String source = view.getBook().getBookTitle();
URL url = null;
try {
url = target == null ? null : target.getURL();
} catch (MalformedURLException e) {}
HelpTopic ht = new HelpTopic(url, topic.getLabel(), source);
HelpTopicNode htnChild = new HelpTopicNode(ht);
htnParent.addChild(htnChild);
initTopicTree(htnChild, ttnChild);
}
}
} | [
"private",
"void",
"initTopicTree",
"(",
"HelpTopicNode",
"htnParent",
",",
"List",
"<",
"?",
">",
"children",
")",
"{",
"if",
"(",
"children",
"!=",
"null",
")",
"{",
"for",
"(",
"Object",
"node",
":",
"children",
")",
"{",
"TopicTreeNode",
"ttnChild",
... | Initialize the topic tree. Converts the Oracle help TopicTreeNode-based tree to a
HelpTopicNode-based tree.
@param htnParent Current help topic node.
@param children List of child nodes. | [
"Initialize",
"the",
"topic",
"tree",
".",
"Converts",
"the",
"Oracle",
"help",
"TopicTreeNode",
"-",
"based",
"tree",
"to",
"a",
"HelpTopicNode",
"-",
"based",
"tree",
"."
] | train | https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.help-parent/org.carewebframework.help.ohj/src/main/java/org/carewebframework/help/ohj/HelpView.java#L117-L136 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/NetUtils.java | NetUtils.hostAndPortToUrlString | public static String hostAndPortToUrlString(String host, int port) throws UnknownHostException {
return ipAddressAndPortToUrlString(InetAddress.getByName(host), port);
} | java | public static String hostAndPortToUrlString(String host, int port) throws UnknownHostException {
return ipAddressAndPortToUrlString(InetAddress.getByName(host), port);
} | [
"public",
"static",
"String",
"hostAndPortToUrlString",
"(",
"String",
"host",
",",
"int",
"port",
")",
"throws",
"UnknownHostException",
"{",
"return",
"ipAddressAndPortToUrlString",
"(",
"InetAddress",
".",
"getByName",
"(",
"host",
")",
",",
"port",
")",
";",
... | Normalizes and encodes a hostname and port to be included in URL.
In particular, this method makes sure that IPv6 address literals have the proper
formatting to be included in URLs.
@param host The address to be included in the URL.
@param port The port for the URL address.
@return The proper URL string encoded IP address and port.
@throws java.net.UnknownHostException Thrown, if the hostname cannot be translated into a URL. | [
"Normalizes",
"and",
"encodes",
"a",
"hostname",
"and",
"port",
"to",
"be",
"included",
"in",
"URL",
".",
"In",
"particular",
"this",
"method",
"makes",
"sure",
"that",
"IPv6",
"address",
"literals",
"have",
"the",
"proper",
"formatting",
"to",
"be",
"includ... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/NetUtils.java#L229-L231 |
unbescape/unbescape | src/main/java/org/unbescape/csv/CsvEscape.java | CsvEscape.escapeCsv | public static void escapeCsv(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.escape(new InternalStringReader(text), writer);
} | java | public static void escapeCsv(final String text, final Writer writer)
throws IOException {
if (writer == null) {
throw new IllegalArgumentException("Argument 'writer' cannot be null");
}
CsvEscapeUtil.escape(new InternalStringReader(text), writer);
} | [
"public",
"static",
"void",
"escapeCsv",
"(",
"final",
"String",
"text",
",",
"final",
"Writer",
"writer",
")",
"throws",
"IOException",
"{",
"if",
"(",
"writer",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"Argument 'writer' canno... | <p>
Perform a CSV <strong>escape</strong> operation on a <tt>String</tt> input, writing results to
a <tt>Writer</tt>.
</p>
<p>
This method is <strong>thread-safe</strong>.
</p>
@param text the <tt>String</tt> to be escaped.
@param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will
be written at all to this writer if input is <tt>null</tt>.
@throws IOException if an input/output exception occurs
@since 1.1.2 | [
"<p",
">",
"Perform",
"a",
"CSV",
"<strong",
">",
"escape<",
"/",
"strong",
">",
"operation",
"on",
"a",
"<tt",
">",
"String<",
"/",
"tt",
">",
"input",
"writing",
"results",
"to",
"a",
"<tt",
">",
"Writer<",
"/",
"tt",
">",
".",
"<",
"/",
"p",
"... | train | https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/csv/CsvEscape.java#L157-L165 |
Samsung/GearVRf | GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTransform.java | GVRTransform.rotate | public void rotate(float w, float x, float y, float z) {
NativeTransform.rotate(getNative(), w, x, y, z);
} | java | public void rotate(float w, float x, float y, float z) {
NativeTransform.rotate(getNative(), w, x, y, z);
} | [
"public",
"void",
"rotate",
"(",
"float",
"w",
",",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
")",
"{",
"NativeTransform",
".",
"rotate",
"(",
"getNative",
"(",
")",
",",
"w",
",",
"x",
",",
"y",
",",
"z",
")",
";",
"}"
] | Modify the tranform's current rotation in quaternion terms.
@param w
'W' component of the quaternion.
@param x
'X' component of the quaternion.
@param y
'Y' component of the quaternion.
@param z
'Z' component of the quaternion. | [
"Modify",
"the",
"tranform",
"s",
"current",
"rotation",
"in",
"quaternion",
"terms",
"."
] | train | https://github.com/Samsung/GearVRf/blob/05034d465a7b0a494fabb9e9f2971ac19392f32d/GVRf/Framework/framework/src/main/java/org/gearvrf/GVRTransform.java#L428-L430 |
pietermartin/sqlg | sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Partition.java | Partition.createRangeSubPartitionWithPartition | private static Partition createRangeSubPartitionWithPartition(
SqlgGraph sqlgGraph,
Partition parentPartition,
String name,
String from,
String to,
PartitionType partitionType,
String partitionExpression) {
Preconditions.checkArgument(!parentPartition.getAbstractLabel().getSchema().isSqlgSchema(), "createRangeSubPartitionWithPartition may not be called for \"%s\"", Topology.SQLG_SCHEMA);
Partition partition = new Partition(sqlgGraph, parentPartition, name, from, to, partitionType, partitionExpression);
partition.createRangePartitionOnDb();
TopologyManager.addSubPartition(sqlgGraph, partition);
partition.committed = false;
return partition;
} | java | private static Partition createRangeSubPartitionWithPartition(
SqlgGraph sqlgGraph,
Partition parentPartition,
String name,
String from,
String to,
PartitionType partitionType,
String partitionExpression) {
Preconditions.checkArgument(!parentPartition.getAbstractLabel().getSchema().isSqlgSchema(), "createRangeSubPartitionWithPartition may not be called for \"%s\"", Topology.SQLG_SCHEMA);
Partition partition = new Partition(sqlgGraph, parentPartition, name, from, to, partitionType, partitionExpression);
partition.createRangePartitionOnDb();
TopologyManager.addSubPartition(sqlgGraph, partition);
partition.committed = false;
return partition;
} | [
"private",
"static",
"Partition",
"createRangeSubPartitionWithPartition",
"(",
"SqlgGraph",
"sqlgGraph",
",",
"Partition",
"parentPartition",
",",
"String",
"name",
",",
"String",
"from",
",",
"String",
"to",
",",
"PartitionType",
"partitionType",
",",
"String",
"part... | Create a range partition on an existing {@link Partition}
@param sqlgGraph
@param parentPartition
@param name
@param from
@param to
@return | [
"Create",
"a",
"range",
"partition",
"on",
"an",
"existing",
"{",
"@link",
"Partition",
"}"
] | train | https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-core/src/main/java/org/umlg/sqlg/structure/topology/Partition.java#L353-L368 |
banq/jdonframework | src/main/java/com/jdon/util/ObjectCreator.java | ObjectCreator.createObject | public static Object createObject(Class classObject, Object[] params) throws Exception {
Constructor[] constructors = classObject.getConstructors();
Object object = null;
for (int counter = 0; counter < constructors.length; counter++) {
try {
object = constructors[counter].newInstance(params);
} catch (Exception e) {
if (e instanceof InvocationTargetException)
((InvocationTargetException) e).getTargetException().printStackTrace();
// do nothing, try the next constructor
}
}
if (object == null)
throw new InstantiationException();
return object;
} | java | public static Object createObject(Class classObject, Object[] params) throws Exception {
Constructor[] constructors = classObject.getConstructors();
Object object = null;
for (int counter = 0; counter < constructors.length; counter++) {
try {
object = constructors[counter].newInstance(params);
} catch (Exception e) {
if (e instanceof InvocationTargetException)
((InvocationTargetException) e).getTargetException().printStackTrace();
// do nothing, try the next constructor
}
}
if (object == null)
throw new InstantiationException();
return object;
} | [
"public",
"static",
"Object",
"createObject",
"(",
"Class",
"classObject",
",",
"Object",
"[",
"]",
"params",
")",
"throws",
"Exception",
"{",
"Constructor",
"[",
"]",
"constructors",
"=",
"classObject",
".",
"getConstructors",
"(",
")",
";",
"Object",
"object... | Instantaite an Object instance, requires a constractor with parameters
@param classObject
, Class object representing the object type to be instantiated
@param params
an array including the required parameters to instantaite the
object
@return the instantaied Object
@exception java.lang.Exception
if instantiation failed | [
"Instantaite",
"an",
"Object",
"instance",
"requires",
"a",
"constractor",
"with",
"parameters"
] | train | https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/ObjectCreator.java#L75-L90 |
haifengl/smile | plot/src/main/java/smile/plot/PlotCanvas.java | PlotCanvas.screeplot | public static PlotCanvas screeplot(PCA pca) {
int n = pca.getVarianceProportion().length;
double[] lowerBound = {0, 0.0};
double[] upperBound = {n + 1, 1.0};
PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false);
canvas.setAxisLabels("Principal Component", "Proportion of Variance");
String[] labels = new String[n];
double[] x = new double[n];
double[][] data = new double[n][2];
double[][] data2 = new double[n][2];
for (int i = 0; i < n; i++) {
labels[i] = "PC" + (i + 1);
x[i] = i + 1;
data[i][0] = x[i];
data[i][1] = pca.getVarianceProportion()[i];
data2[i][0] = x[i];
data2[i][1] = pca.getCumulativeVarianceProportion()[i];
}
LinePlot plot = new LinePlot(data);
plot.setID("Variance");
plot.setColor(Color.RED);
plot.setLegend('@');
canvas.add(plot);
canvas.getAxis(0).addLabel(labels, x);
LinePlot plot2 = new LinePlot(data2);
plot2.setID("Cumulative Variance");
plot2.setColor(Color.BLUE);
plot2.setLegend('@');
canvas.add(plot2);
return canvas;
} | java | public static PlotCanvas screeplot(PCA pca) {
int n = pca.getVarianceProportion().length;
double[] lowerBound = {0, 0.0};
double[] upperBound = {n + 1, 1.0};
PlotCanvas canvas = new PlotCanvas(lowerBound, upperBound, false);
canvas.setAxisLabels("Principal Component", "Proportion of Variance");
String[] labels = new String[n];
double[] x = new double[n];
double[][] data = new double[n][2];
double[][] data2 = new double[n][2];
for (int i = 0; i < n; i++) {
labels[i] = "PC" + (i + 1);
x[i] = i + 1;
data[i][0] = x[i];
data[i][1] = pca.getVarianceProportion()[i];
data2[i][0] = x[i];
data2[i][1] = pca.getCumulativeVarianceProportion()[i];
}
LinePlot plot = new LinePlot(data);
plot.setID("Variance");
plot.setColor(Color.RED);
plot.setLegend('@');
canvas.add(plot);
canvas.getAxis(0).addLabel(labels, x);
LinePlot plot2 = new LinePlot(data2);
plot2.setID("Cumulative Variance");
plot2.setColor(Color.BLUE);
plot2.setLegend('@');
canvas.add(plot2);
return canvas;
} | [
"public",
"static",
"PlotCanvas",
"screeplot",
"(",
"PCA",
"pca",
")",
"{",
"int",
"n",
"=",
"pca",
".",
"getVarianceProportion",
"(",
")",
".",
"length",
";",
"double",
"[",
"]",
"lowerBound",
"=",
"{",
"0",
",",
"0.0",
"}",
";",
"double",
"[",
"]",... | Create a scree plot for PCA.
@param pca principal component analysis object. | [
"Create",
"a",
"scree",
"plot",
"for",
"PCA",
"."
] | train | https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/plot/src/main/java/smile/plot/PlotCanvas.java#L2249-L2285 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/util/blockdata/BlockDataMessage.java | BlockDataMessage.sendBlockData | public static void sendBlockData(Chunk chunk, String identifier, ByteBuf data, EntityPlayerMP player)
{
MalisisCore.network.sendTo(new Packet(chunk, identifier, data), player);
} | java | public static void sendBlockData(Chunk chunk, String identifier, ByteBuf data, EntityPlayerMP player)
{
MalisisCore.network.sendTo(new Packet(chunk, identifier, data), player);
} | [
"public",
"static",
"void",
"sendBlockData",
"(",
"Chunk",
"chunk",
",",
"String",
"identifier",
",",
"ByteBuf",
"data",
",",
"EntityPlayerMP",
"player",
")",
"{",
"MalisisCore",
".",
"network",
".",
"sendTo",
"(",
"new",
"Packet",
"(",
"chunk",
",",
"identi... | Sends the data to the specified {@link EntityPlayerMP}.
@param chunk the chunk
@param identifier the identifier
@param data the data
@param player the player | [
"Sends",
"the",
"data",
"to",
"the",
"specified",
"{",
"@link",
"EntityPlayerMP",
"}",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/util/blockdata/BlockDataMessage.java#L65-L68 |
thrau/jarchivelib | src/main/java/org/rauschig/jarchivelib/IOUtils.java | IOUtils.requireDirectory | public static void requireDirectory(File destination) throws IOException, IllegalArgumentException {
if (destination.isFile()) {
throw new IllegalArgumentException(destination + " exists and is a file, directory or path expected.");
} else if (!destination.exists()) {
destination.mkdirs();
}
if (!destination.canWrite()) {
throw new IllegalArgumentException("Can not write to destination " + destination);
}
} | java | public static void requireDirectory(File destination) throws IOException, IllegalArgumentException {
if (destination.isFile()) {
throw new IllegalArgumentException(destination + " exists and is a file, directory or path expected.");
} else if (!destination.exists()) {
destination.mkdirs();
}
if (!destination.canWrite()) {
throw new IllegalArgumentException("Can not write to destination " + destination);
}
} | [
"public",
"static",
"void",
"requireDirectory",
"(",
"File",
"destination",
")",
"throws",
"IOException",
",",
"IllegalArgumentException",
"{",
"if",
"(",
"destination",
".",
"isFile",
"(",
")",
")",
"{",
"throw",
"new",
"IllegalArgumentException",
"(",
"destinati... | Makes sure that the given {@link File} is either a writable directory, or that it does not exist and a directory
can be created at its path.
<br>
Will throw an exception if the given {@link File} is actually an existing file, or the directory is not writable
@param destination the directory which to ensure its existence for
@throws IOException if an I/O error occurs e.g. when attempting to create the destination directory
@throws IllegalArgumentException if the destination is an existing file, or the directory is not writable | [
"Makes",
"sure",
"that",
"the",
"given",
"{",
"@link",
"File",
"}",
"is",
"either",
"a",
"writable",
"directory",
"or",
"that",
"it",
"does",
"not",
"exist",
"and",
"a",
"directory",
"can",
"be",
"created",
"at",
"its",
"path",
".",
"<br",
">",
"Will",... | train | https://github.com/thrau/jarchivelib/blob/8afee5124c588f589306796985b722d63572bbfa/src/main/java/org/rauschig/jarchivelib/IOUtils.java#L117-L126 |
kite-sdk/kite | kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/DataModelUtil.java | DataModelUtil.createRecord | @SuppressWarnings("unchecked")
public static <E> E createRecord(Class<E> type, Schema schema) {
// Don't instantiate SpecificRecords or interfaces.
if (isGeneric(type) && !type.isInterface()) {
if (GenericData.Record.class.equals(type)) {
return (E) GenericData.get().newRecord(null, schema);
}
return (E) ReflectData.newInstance(type, schema);
}
return null;
} | java | @SuppressWarnings("unchecked")
public static <E> E createRecord(Class<E> type, Schema schema) {
// Don't instantiate SpecificRecords or interfaces.
if (isGeneric(type) && !type.isInterface()) {
if (GenericData.Record.class.equals(type)) {
return (E) GenericData.get().newRecord(null, schema);
}
return (E) ReflectData.newInstance(type, schema);
}
return null;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"static",
"<",
"E",
">",
"E",
"createRecord",
"(",
"Class",
"<",
"E",
">",
"type",
",",
"Schema",
"schema",
")",
"{",
"// Don't instantiate SpecificRecords or interfaces.",
"if",
"(",
"isGeneric",
"("... | If E implements GenericRecord, but does not implement SpecificRecord, then
create a new instance of E using reflection so that GenericDataumReader
will use the expected type.
Implementations of GenericRecord that require a {@link Schema} parameter
in the constructor should implement SpecificData.SchemaConstructable.
Otherwise, your implementation must have a no-args constructor.
@param <E> The entity type
@param type The Java class of the entity type
@param schema The reader schema
@return An instance of E, or null if the data model is specific or reflect | [
"If",
"E",
"implements",
"GenericRecord",
"but",
"does",
"not",
"implement",
"SpecificRecord",
"then",
"create",
"a",
"new",
"instance",
"of",
"E",
"using",
"reflection",
"so",
"that",
"GenericDataumReader",
"will",
"use",
"the",
"expected",
"type",
"."
] | train | https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-data/kite-data-core/src/main/java/org/kitesdk/data/spi/DataModelUtil.java#L221-L232 |
wmdietl/jsr308-langtools | src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ProfileSummaryBuilder.java | ProfileSummaryBuilder.buildErrorSummary | public void buildErrorSummary(XMLNode node, Content packageSummaryContentTree) {
String errorTableSummary =
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Error_Summary"),
configuration.getText("doclet.errors"));
String[] errorTableHeader = new String[] {
configuration.getText("doclet.Error"),
configuration.getText("doclet.Description")
};
ClassDoc[] errors = pkg.errors();
if (errors.length > 0) {
profileWriter.addClassesSummary(
errors,
configuration.getText("doclet.Error_Summary"),
errorTableSummary, errorTableHeader, packageSummaryContentTree);
}
} | java | public void buildErrorSummary(XMLNode node, Content packageSummaryContentTree) {
String errorTableSummary =
configuration.getText("doclet.Member_Table_Summary",
configuration.getText("doclet.Error_Summary"),
configuration.getText("doclet.errors"));
String[] errorTableHeader = new String[] {
configuration.getText("doclet.Error"),
configuration.getText("doclet.Description")
};
ClassDoc[] errors = pkg.errors();
if (errors.length > 0) {
profileWriter.addClassesSummary(
errors,
configuration.getText("doclet.Error_Summary"),
errorTableSummary, errorTableHeader, packageSummaryContentTree);
}
} | [
"public",
"void",
"buildErrorSummary",
"(",
"XMLNode",
"node",
",",
"Content",
"packageSummaryContentTree",
")",
"{",
"String",
"errorTableSummary",
"=",
"configuration",
".",
"getText",
"(",
"\"doclet.Member_Table_Summary\"",
",",
"configuration",
".",
"getText",
"(",
... | Build the summary for the errors in the package.
@param node the XML element that specifies which components to document
@param packageSummaryContentTree the tree to which the error summary will
be added | [
"Build",
"the",
"summary",
"for",
"the",
"errors",
"in",
"the",
"package",
"."
] | train | https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/builders/ProfileSummaryBuilder.java#L285-L301 |
RuedigerMoeller/kontraktor | modules/service-suppport/src/main/java/org/nustaq/kontraktor/services/ServiceActor.java | ServiceActor.RunTCP | public static ServiceActor RunTCP( String args[], Class<? extends ServiceActor> serviceClazz, Class<? extends ServiceArgs> argsClazz) {
ServiceActor myService = AsActor(serviceClazz);
ServiceArgs options = null;
try {
options = ServiceRegistry.parseCommandLine(args, null, argsClazz.newInstance());
} catch (Exception e) {
FSTUtil.rethrow(e);
}
TCPConnectable connectable = new TCPConnectable(ServiceRegistry.class, options.getRegistryHost(), options.getRegistryPort());
myService.init( connectable, options, true).await(30_000);
Log.Info(myService.getClass(), "Init finished");
return myService;
} | java | public static ServiceActor RunTCP( String args[], Class<? extends ServiceActor> serviceClazz, Class<? extends ServiceArgs> argsClazz) {
ServiceActor myService = AsActor(serviceClazz);
ServiceArgs options = null;
try {
options = ServiceRegistry.parseCommandLine(args, null, argsClazz.newInstance());
} catch (Exception e) {
FSTUtil.rethrow(e);
}
TCPConnectable connectable = new TCPConnectable(ServiceRegistry.class, options.getRegistryHost(), options.getRegistryPort());
myService.init( connectable, options, true).await(30_000);
Log.Info(myService.getClass(), "Init finished");
return myService;
} | [
"public",
"static",
"ServiceActor",
"RunTCP",
"(",
"String",
"args",
"[",
"]",
",",
"Class",
"<",
"?",
"extends",
"ServiceActor",
">",
"serviceClazz",
",",
"Class",
"<",
"?",
"extends",
"ServiceArgs",
">",
"argsClazz",
")",
"{",
"ServiceActor",
"myService",
... | run & connect a service with given cmdline args and classes
@param args
@param serviceClazz
@param argsClazz
@return
@throws IllegalAccessException
@throws InstantiationException | [
"run",
"&",
"connect",
"a",
"service",
"with",
"given",
"cmdline",
"args",
"and",
"classes"
] | train | https://github.com/RuedigerMoeller/kontraktor/blob/d5f3817f9476f3786187b8ef00400b7a4f25a404/modules/service-suppport/src/main/java/org/nustaq/kontraktor/services/ServiceActor.java#L36-L50 |
alibaba/jstorm | jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JstormYarnUtils.java | JstormYarnUtils.isPortAvailable | public static boolean isPortAvailable(String host, int port) {
try {
Socket socket = new Socket(host, port);
socket.close();
return false;
} catch (IOException e) {
return true;
}
} | java | public static boolean isPortAvailable(String host, int port) {
try {
Socket socket = new Socket(host, port);
socket.close();
return false;
} catch (IOException e) {
return true;
}
} | [
"public",
"static",
"boolean",
"isPortAvailable",
"(",
"String",
"host",
",",
"int",
"port",
")",
"{",
"try",
"{",
"Socket",
"socket",
"=",
"new",
"Socket",
"(",
"host",
",",
"port",
")",
";",
"socket",
".",
"close",
"(",
")",
";",
"return",
"false",
... | See if a port is available for listening on by trying connect to it
and seeing if that works or fails
@param host
@param port
@return | [
"See",
"if",
"a",
"port",
"is",
"available",
"for",
"listening",
"on",
"by",
"trying",
"connect",
"to",
"it",
"and",
"seeing",
"if",
"that",
"works",
"or",
"fails"
] | train | https://github.com/alibaba/jstorm/blob/5d6cde22dbca7df3d6e6830bf94f98a6639ab559/jstorm-on-yarn/src/main/java/com/alibaba/jstorm/yarn/utils/JstormYarnUtils.java#L121-L129 |
apache/groovy | src/main/java/org/codehaus/groovy/ast/tools/BeanUtils.java | BeanUtils.getAllProperties | public static List<PropertyNode> getAllProperties(ClassNode type, boolean includeSuperProperties, boolean includeStatic, boolean includePseudoGetters, boolean includePseudoSetters, boolean superFirst) {
return getAllProperties(type, type, new HashSet<String>(), includeSuperProperties, includeStatic, includePseudoGetters, includePseudoSetters, superFirst);
} | java | public static List<PropertyNode> getAllProperties(ClassNode type, boolean includeSuperProperties, boolean includeStatic, boolean includePseudoGetters, boolean includePseudoSetters, boolean superFirst) {
return getAllProperties(type, type, new HashSet<String>(), includeSuperProperties, includeStatic, includePseudoGetters, includePseudoSetters, superFirst);
} | [
"public",
"static",
"List",
"<",
"PropertyNode",
">",
"getAllProperties",
"(",
"ClassNode",
"type",
",",
"boolean",
"includeSuperProperties",
",",
"boolean",
"includeStatic",
",",
"boolean",
"includePseudoGetters",
",",
"boolean",
"includePseudoSetters",
",",
"boolean",... | Get all properties including JavaBean pseudo properties matching JavaBean getter or setter conventions.
@param type the ClassNode
@param includeSuperProperties whether to include super properties
@param includeStatic whether to include static properties
@param includePseudoGetters whether to include JavaBean pseudo (getXXX/isYYY) properties with no corresponding field
@param includePseudoSetters whether to include JavaBean pseudo (setXXX) properties with no corresponding field
@param superFirst are properties gathered first from parent classes
@return the list of found property nodes | [
"Get",
"all",
"properties",
"including",
"JavaBean",
"pseudo",
"properties",
"matching",
"JavaBean",
"getter",
"or",
"setter",
"conventions",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/ast/tools/BeanUtils.java#L66-L68 |
grails/grails-core | grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java | GrailsASTUtils.hasAnnotation | public static boolean hasAnnotation(final ClassNode classNode, final Class<? extends Annotation> annotationClass) {
return !classNode.getAnnotations(new ClassNode(annotationClass)).isEmpty();
} | java | public static boolean hasAnnotation(final ClassNode classNode, final Class<? extends Annotation> annotationClass) {
return !classNode.getAnnotations(new ClassNode(annotationClass)).isEmpty();
} | [
"public",
"static",
"boolean",
"hasAnnotation",
"(",
"final",
"ClassNode",
"classNode",
",",
"final",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
")",
"{",
"return",
"!",
"classNode",
".",
"getAnnotations",
"(",
"new",
"ClassNode",
"(",
... | Returns true if classNode is marked with annotationClass
@param classNode A ClassNode to inspect
@param annotationClass an annotation to look for
@return true if classNode is marked with annotationClass, otherwise false | [
"Returns",
"true",
"if",
"classNode",
"is",
"marked",
"with",
"annotationClass"
] | train | https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java#L945-L947 |
dustin/java-memcached-client | src/main/java/net/spy/memcached/compat/log/AbstractLogger.java | AbstractLogger.error | public void error(String message, Object... args) {
error(String.format(message, args), getThrowable(args));
} | java | public void error(String message, Object... args) {
error(String.format(message, args), getThrowable(args));
} | [
"public",
"void",
"error",
"(",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"error",
"(",
"String",
".",
"format",
"(",
"message",
",",
"args",
")",
",",
"getThrowable",
"(",
"args",
")",
")",
";",
"}"
] | Log a formatted message at debug level.
@param message the message to log
@param args the arguments for that message | [
"Log",
"a",
"formatted",
"message",
"at",
"debug",
"level",
"."
] | train | https://github.com/dustin/java-memcached-client/blob/c232307ad8e0c7ccc926e495dd7d5aad2d713318/src/main/java/net/spy/memcached/compat/log/AbstractLogger.java#L219-L221 |
softindex/datakernel | core-eventloop/src/main/java/io/datakernel/util/ReflectionUtils.java | ReflectionUtils.getAnnotationString | public static String getAnnotationString(Annotation annotation) throws ReflectiveOperationException {
Class<? extends Annotation> annotationType = annotation.annotationType();
StringBuilder annotationString = new StringBuilder();
Method[] annotationElements = filterNonEmptyElements(annotation);
if (annotationElements.length == 0) {
// annotation without elements
annotationString.append(annotationType.getSimpleName());
return annotationString.toString();
}
if (annotationElements.length == 1 && annotationElements[0].getName().equals("value")) {
// annotation with single element which has name "value"
annotationString.append(annotationType.getSimpleName());
Object value = fetchAnnotationElementValue(annotation, annotationElements[0]);
annotationString.append('(').append(value.toString()).append(')');
return annotationString.toString();
}
// annotation with one or more custom elements
annotationString.append('(');
for (Method annotationParameter : annotationElements) {
Object value = fetchAnnotationElementValue(annotation, annotationParameter);
String nameKey = annotationParameter.getName();
String nameValue = value.toString();
annotationString.append(nameKey).append('=').append(nameValue).append(',');
}
assert annotationString.substring(annotationString.length() - 1).equals(",");
annotationString = new StringBuilder(annotationString.substring(0, annotationString.length() - 1));
annotationString.append(')');
return annotationString.toString();
} | java | public static String getAnnotationString(Annotation annotation) throws ReflectiveOperationException {
Class<? extends Annotation> annotationType = annotation.annotationType();
StringBuilder annotationString = new StringBuilder();
Method[] annotationElements = filterNonEmptyElements(annotation);
if (annotationElements.length == 0) {
// annotation without elements
annotationString.append(annotationType.getSimpleName());
return annotationString.toString();
}
if (annotationElements.length == 1 && annotationElements[0].getName().equals("value")) {
// annotation with single element which has name "value"
annotationString.append(annotationType.getSimpleName());
Object value = fetchAnnotationElementValue(annotation, annotationElements[0]);
annotationString.append('(').append(value.toString()).append(')');
return annotationString.toString();
}
// annotation with one or more custom elements
annotationString.append('(');
for (Method annotationParameter : annotationElements) {
Object value = fetchAnnotationElementValue(annotation, annotationParameter);
String nameKey = annotationParameter.getName();
String nameValue = value.toString();
annotationString.append(nameKey).append('=').append(nameValue).append(',');
}
assert annotationString.substring(annotationString.length() - 1).equals(",");
annotationString = new StringBuilder(annotationString.substring(0, annotationString.length() - 1));
annotationString.append(')');
return annotationString.toString();
} | [
"public",
"static",
"String",
"getAnnotationString",
"(",
"Annotation",
"annotation",
")",
"throws",
"ReflectiveOperationException",
"{",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationType",
"=",
"annotation",
".",
"annotationType",
"(",
")",
";",
"Str... | Builds string representation of annotation with its elements.
The string looks differently depending on the number of elements, that an annotation has.
If annotation has no elements, string looks like this : "AnnotationName"
If annotation has a single element with the name "value", string looks like this : "AnnotationName(someValue)"
If annotation has one or more custom elements, string looks like this : "(key1=value1,key2=value2)"
@param annotation
@return String representation of annotation with its elements
@throws ReflectiveOperationException | [
"Builds",
"string",
"representation",
"of",
"annotation",
"with",
"its",
"elements",
".",
"The",
"string",
"looks",
"differently",
"depending",
"on",
"the",
"number",
"of",
"elements",
"that",
"an",
"annotation",
"has",
".",
"If",
"annotation",
"has",
"no",
"e... | train | https://github.com/softindex/datakernel/blob/090ca1116416c14d463d49d275cb1daaafa69c56/core-eventloop/src/main/java/io/datakernel/util/ReflectionUtils.java#L336-L366 |
structurizr/java | structurizr-core/src/com/structurizr/model/DeploymentNode.java | DeploymentNode.uses | public Relationship uses(DeploymentNode destination, String description, String technology, InteractionStyle interactionStyle) {
return getModel().addRelationship(this, destination, description, technology, interactionStyle);
} | java | public Relationship uses(DeploymentNode destination, String description, String technology, InteractionStyle interactionStyle) {
return getModel().addRelationship(this, destination, description, technology, interactionStyle);
} | [
"public",
"Relationship",
"uses",
"(",
"DeploymentNode",
"destination",
",",
"String",
"description",
",",
"String",
"technology",
",",
"InteractionStyle",
"interactionStyle",
")",
"{",
"return",
"getModel",
"(",
")",
".",
"addRelationship",
"(",
"this",
",",
"des... | Adds a relationship between this and another deployment node.
@param destination the destination DeploymentNode
@param description a short description of the relationship
@param technology the technology
@param interactionStyle the interation style (Synchronous vs Asynchronous)
@return a Relationship object | [
"Adds",
"a",
"relationship",
"between",
"this",
"and",
"another",
"deployment",
"node",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/model/DeploymentNode.java#L141-L143 |
maxschuster/Vaadin-SignatureField | vaadin-signaturefield/src/main/java/eu/maxschuster/vaadin/signaturefield/SignatureField.java | SignatureField.setInternalValue | protected void setInternalValue(String newValue, boolean repaintIsNotNeeded) {
super.setInternalValue(newValue);
extension.setSignature(newValue, changingVariables || repaintIsNotNeeded);
} | java | protected void setInternalValue(String newValue, boolean repaintIsNotNeeded) {
super.setInternalValue(newValue);
extension.setSignature(newValue, changingVariables || repaintIsNotNeeded);
} | [
"protected",
"void",
"setInternalValue",
"(",
"String",
"newValue",
",",
"boolean",
"repaintIsNotNeeded",
")",
"{",
"super",
".",
"setInternalValue",
"(",
"newValue",
")",
";",
"extension",
".",
"setSignature",
"(",
"newValue",
",",
"changingVariables",
"||",
"rep... | Sets the internal field value. May sends the value to the client-side.
@param newValue
the new value to be set.
@param repaintIsNotNeeded
the new value should not be send to the client-side | [
"Sets",
"the",
"internal",
"field",
"value",
".",
"May",
"sends",
"the",
"value",
"to",
"the",
"client",
"-",
"side",
"."
] | train | https://github.com/maxschuster/Vaadin-SignatureField/blob/b6f6b7042ea9c46060af54bd92d21770abfcccee/vaadin-signaturefield/src/main/java/eu/maxschuster/vaadin/signaturefield/SignatureField.java#L205-L208 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowManagedObject.java | PageFlowManagedObject.create | public synchronized void create( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext )
throws Exception
{
reinitialize( request, response, servletContext );
JavaControlUtils.initJavaControls( request, response, servletContext, this );
onCreate();
} | java | public synchronized void create( HttpServletRequest request, HttpServletResponse response, ServletContext servletContext )
throws Exception
{
reinitialize( request, response, servletContext );
JavaControlUtils.initJavaControls( request, response, servletContext, this );
onCreate();
} | [
"public",
"synchronized",
"void",
"create",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"ServletContext",
"servletContext",
")",
"throws",
"Exception",
"{",
"reinitialize",
"(",
"request",
",",
"response",
",",
"servletContext",
... | Initialize after object creation. This is a framework-invoked method; it should not normally be called directly. | [
"Initialize",
"after",
"object",
"creation",
".",
"This",
"is",
"a",
"framework",
"-",
"invoked",
"method",
";",
"it",
"should",
"not",
"normally",
"be",
"called",
"directly",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/PageFlowManagedObject.java#L90-L96 |
sdaschner/jaxrs-analyzer | src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java | JavaUtils.isAssignableTo | public static boolean isAssignableTo(final String leftType, final String rightType) {
if (leftType.equals(rightType))
return true;
final boolean firstTypeArray = leftType.charAt(0) == '[';
if (firstTypeArray ^ rightType.charAt(0) == '[') {
return false;
}
final Class<?> leftClass = loadClassFromType(leftType);
final Class<?> rightClass = loadClassFromType(rightType);
if (leftClass == null || rightClass == null)
return false;
final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);
return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));
} | java | public static boolean isAssignableTo(final String leftType, final String rightType) {
if (leftType.equals(rightType))
return true;
final boolean firstTypeArray = leftType.charAt(0) == '[';
if (firstTypeArray ^ rightType.charAt(0) == '[') {
return false;
}
final Class<?> leftClass = loadClassFromType(leftType);
final Class<?> rightClass = loadClassFromType(rightType);
if (leftClass == null || rightClass == null)
return false;
final boolean bothTypesParameterized = hasTypeParameters(leftType) && hasTypeParameters(rightType);
return rightClass.isAssignableFrom(leftClass) && (firstTypeArray || !bothTypesParameterized || getTypeParameters(leftType).equals(getTypeParameters(rightType)));
} | [
"public",
"static",
"boolean",
"isAssignableTo",
"(",
"final",
"String",
"leftType",
",",
"final",
"String",
"rightType",
")",
"{",
"if",
"(",
"leftType",
".",
"equals",
"(",
"rightType",
")",
")",
"return",
"true",
";",
"final",
"boolean",
"firstTypeArray",
... | Checks if the left type is assignable to the right type, i.e. the right type is of the same or a sub-type. | [
"Checks",
"if",
"the",
"left",
"type",
"is",
"assignable",
"to",
"the",
"right",
"type",
"i",
".",
"e",
".",
"the",
"right",
"type",
"is",
"of",
"the",
"same",
"or",
"a",
"sub",
"-",
"type",
"."
] | train | https://github.com/sdaschner/jaxrs-analyzer/blob/4ac62942202d05632977d6c14d3cd7e2d27e2b9b/src/main/java/com/sebastian_daschner/jaxrs_analyzer/model/JavaUtils.java#L201-L217 |
Alluxio/alluxio | core/common/src/main/java/alluxio/collections/LockCache.java | LockCache.tryGet | public Optional<LockResource> tryGet(K key, LockMode mode) {
ValNode valNode = getValNode(key);
ReentrantReadWriteLock lock = valNode.mValue;
Lock innerLock;
switch (mode) {
case READ:
innerLock = lock.readLock();
break;
case WRITE:
innerLock = lock.writeLock();
break;
default:
throw new IllegalStateException("Unknown lock mode: " + mode);
}
if (!innerLock.tryLock()) {
return Optional.empty();
}
return Optional.of(new RefCountLockResource(innerLock, false, valNode.mRefCount));
} | java | public Optional<LockResource> tryGet(K key, LockMode mode) {
ValNode valNode = getValNode(key);
ReentrantReadWriteLock lock = valNode.mValue;
Lock innerLock;
switch (mode) {
case READ:
innerLock = lock.readLock();
break;
case WRITE:
innerLock = lock.writeLock();
break;
default:
throw new IllegalStateException("Unknown lock mode: " + mode);
}
if (!innerLock.tryLock()) {
return Optional.empty();
}
return Optional.of(new RefCountLockResource(innerLock, false, valNode.mRefCount));
} | [
"public",
"Optional",
"<",
"LockResource",
">",
"tryGet",
"(",
"K",
"key",
",",
"LockMode",
"mode",
")",
"{",
"ValNode",
"valNode",
"=",
"getValNode",
"(",
"key",
")",
";",
"ReentrantReadWriteLock",
"lock",
"=",
"valNode",
".",
"mValue",
";",
"Lock",
"inne... | Attempts to take a lock on the given key.
@param key the key to lock
@param mode lockMode to acquire
@return either empty or a lock resource which must be closed to unlock the key | [
"Attempts",
"to",
"take",
"a",
"lock",
"on",
"the",
"given",
"key",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/common/src/main/java/alluxio/collections/LockCache.java#L143-L161 |
lettuce-io/lettuce-core | src/main/java/io/lettuce/core/masterslave/MasterSlave.java | MasterSlave.connectAsync | public static <K, V> CompletableFuture<StatefulRedisMasterSlaveConnection<K, V>> connectAsync(RedisClient redisClient,
RedisCodec<K, V> codec, RedisURI redisURI) {
return transformAsyncConnectionException(connectAsyncSentinelOrAutodiscovery(redisClient, codec, redisURI), redisURI);
} | java | public static <K, V> CompletableFuture<StatefulRedisMasterSlaveConnection<K, V>> connectAsync(RedisClient redisClient,
RedisCodec<K, V> codec, RedisURI redisURI) {
return transformAsyncConnectionException(connectAsyncSentinelOrAutodiscovery(redisClient, codec, redisURI), redisURI);
} | [
"public",
"static",
"<",
"K",
",",
"V",
">",
"CompletableFuture",
"<",
"StatefulRedisMasterSlaveConnection",
"<",
"K",
",",
"V",
">",
">",
"connectAsync",
"(",
"RedisClient",
"redisClient",
",",
"RedisCodec",
"<",
"K",
",",
"V",
">",
"codec",
",",
"RedisURI"... | Open asynchronously a new connection to a Redis Master-Slave server/servers using the supplied {@link RedisURI} and the
supplied {@link RedisCodec codec} to encode/decode keys.
<p>
This {@link MasterSlave} performs auto-discovery of nodes using either Redis Sentinel or Master/Slave. A {@link RedisURI}
can point to either a master or a replica host.
</p>
@param redisClient the Redis client.
@param codec Use this codec to encode/decode keys and values, must not be {@literal null}.
@param redisURI the Redis server to connect to, must not be {@literal null}.
@param <K> Key type.
@param <V> Value type.
@return {@link CompletableFuture} that is notified once the connect is finished.
@since | [
"Open",
"asynchronously",
"a",
"new",
"connection",
"to",
"a",
"Redis",
"Master",
"-",
"Slave",
"server",
"/",
"servers",
"using",
"the",
"supplied",
"{",
"@link",
"RedisURI",
"}",
"and",
"the",
"supplied",
"{",
"@link",
"RedisCodec",
"codec",
"}",
"to",
"... | train | https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/MasterSlave.java#L138-L141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.