repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
listlengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
opencb/java-common-libs
commons-datastore/commons-datastore-core/src/main/java/org/opencb/commons/datastore/core/ObjectMap.java
ObjectMap.getAsList
@Deprecated public <T> List<T> getAsList(String field, final Class<T> clazz) { """ Some fields can be a List, this method cast the Object to aList of type T. Gets the value of the given key, casting it to the given {@code Class<T>}. This is useful to avoid having casts in client code, though the effect is the same. So to get the value of a key that is of type String, you would write {@code String name = doc.get("name", String.class)} instead of {@code String name = (String) doc.get("x") }. @param field List field name @param clazz Class to be returned @param <T> Element class @return A List representation of the field """ return getAsList(field, clazz, null); }
java
@Deprecated public <T> List<T> getAsList(String field, final Class<T> clazz) { return getAsList(field, clazz, null); }
[ "@", "Deprecated", "public", "<", "T", ">", "List", "<", "T", ">", "getAsList", "(", "String", "field", ",", "final", "Class", "<", "T", ">", "clazz", ")", "{", "return", "getAsList", "(", "field", ",", "clazz", ",", "null", ")", ";", "}" ]
Some fields can be a List, this method cast the Object to aList of type T. Gets the value of the given key, casting it to the given {@code Class<T>}. This is useful to avoid having casts in client code, though the effect is the same. So to get the value of a key that is of type String, you would write {@code String name = doc.get("name", String.class)} instead of {@code String name = (String) doc.get("x") }. @param field List field name @param clazz Class to be returned @param <T> Element class @return A List representation of the field
[ "Some", "fields", "can", "be", "a", "List", "this", "method", "cast", "the", "Object", "to", "aList", "of", "type", "T", ".", "Gets", "the", "value", "of", "the", "given", "key", "casting", "it", "to", "the", "given", "{", "@code", "Class<T", ">", "}...
train
https://github.com/opencb/java-common-libs/blob/5c97682530d0be55828e1e4e374ff01fceb5f198/commons-datastore/commons-datastore-core/src/main/java/org/opencb/commons/datastore/core/ObjectMap.java#L371-L374
nostra13/Android-Universal-Image-Loader
library/src/main/java/com/nostra13/universalimageloader/utils/IoUtils.java
IoUtils.copyStream
public static boolean copyStream(InputStream is, OutputStream os, CopyListener listener) throws IOException { """ Copies stream, fires progress events by listener, can be interrupted by listener. Uses buffer size = {@value #DEFAULT_BUFFER_SIZE} bytes. @param is Input stream @param os Output stream @param listener null-ok; Listener of copying progress and controller of copying interrupting @return <b>true</b> - if stream copied successfully; <b>false</b> - if copying was interrupted by listener @throws IOException """ return copyStream(is, os, listener, DEFAULT_BUFFER_SIZE); }
java
public static boolean copyStream(InputStream is, OutputStream os, CopyListener listener) throws IOException { return copyStream(is, os, listener, DEFAULT_BUFFER_SIZE); }
[ "public", "static", "boolean", "copyStream", "(", "InputStream", "is", ",", "OutputStream", "os", ",", "CopyListener", "listener", ")", "throws", "IOException", "{", "return", "copyStream", "(", "is", ",", "os", ",", "listener", ",", "DEFAULT_BUFFER_SIZE", ")", ...
Copies stream, fires progress events by listener, can be interrupted by listener. Uses buffer size = {@value #DEFAULT_BUFFER_SIZE} bytes. @param is Input stream @param os Output stream @param listener null-ok; Listener of copying progress and controller of copying interrupting @return <b>true</b> - if stream copied successfully; <b>false</b> - if copying was interrupted by listener @throws IOException
[ "Copies", "stream", "fires", "progress", "events", "by", "listener", "can", "be", "interrupted", "by", "listener", ".", "Uses", "buffer", "size", "=", "{", "@value", "#DEFAULT_BUFFER_SIZE", "}", "bytes", "." ]
train
https://github.com/nostra13/Android-Universal-Image-Loader/blob/fc3c5f6779bb4f702e233653b61bd9d559e345cc/library/src/main/java/com/nostra13/universalimageloader/utils/IoUtils.java#L51-L53
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/sjavac/BuildState.java
BuildState.copyPackagesExcept
public void copyPackagesExcept(BuildState prev, Set<String> recompiled, Set<String> removed) { """ During an incremental compile we need to copy the old javac state information about packages that were not recompiled. """ for (String pkg : prev.packages().keySet()) { // Do not copy recompiled or removed packages. if (recompiled.contains(pkg) || removed.contains(pkg)) continue; Module mnew = findModuleFromPackageName(pkg); Package pprev = prev.packages().get(pkg); mnew.addPackage(pprev); // Do not forget to update the flattened data. packages.put(pkg, pprev); } }
java
public void copyPackagesExcept(BuildState prev, Set<String> recompiled, Set<String> removed) { for (String pkg : prev.packages().keySet()) { // Do not copy recompiled or removed packages. if (recompiled.contains(pkg) || removed.contains(pkg)) continue; Module mnew = findModuleFromPackageName(pkg); Package pprev = prev.packages().get(pkg); mnew.addPackage(pprev); // Do not forget to update the flattened data. packages.put(pkg, pprev); } }
[ "public", "void", "copyPackagesExcept", "(", "BuildState", "prev", ",", "Set", "<", "String", ">", "recompiled", ",", "Set", "<", "String", ">", "removed", ")", "{", "for", "(", "String", "pkg", ":", "prev", ".", "packages", "(", ")", ".", "keySet", "(...
During an incremental compile we need to copy the old javac state information about packages that were not recompiled.
[ "During", "an", "incremental", "compile", "we", "need", "to", "copy", "the", "old", "javac", "state", "information", "about", "packages", "that", "were", "not", "recompiled", "." ]
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/sjavac/BuildState.java#L268-L278
xebia-france/xebia-management-extras
src/main/java/fr/xebia/management/statistics/ServiceStatistics.java
ServiceStatistics.containsThrowableOfType
public static boolean containsThrowableOfType(Throwable throwable, Class<?>... throwableTypes) { """ Returns <code>true</code> if the given <code>throwable</code> or one of its cause is an instance of one of the given <code>throwableTypes</code>. """ List<Throwable> alreadyProcessedThrowables = new ArrayList<Throwable>(); while (true) { if (throwable == null) { // end of the list of causes return false; } else if (alreadyProcessedThrowables.contains(throwable)) { // infinite loop in causes return false; } else { for (Class<?> throwableType : throwableTypes) { if (throwableType.isAssignableFrom(throwable.getClass())) { return true; } } alreadyProcessedThrowables.add(throwable); throwable = throwable.getCause(); } } }
java
public static boolean containsThrowableOfType(Throwable throwable, Class<?>... throwableTypes) { List<Throwable> alreadyProcessedThrowables = new ArrayList<Throwable>(); while (true) { if (throwable == null) { // end of the list of causes return false; } else if (alreadyProcessedThrowables.contains(throwable)) { // infinite loop in causes return false; } else { for (Class<?> throwableType : throwableTypes) { if (throwableType.isAssignableFrom(throwable.getClass())) { return true; } } alreadyProcessedThrowables.add(throwable); throwable = throwable.getCause(); } } }
[ "public", "static", "boolean", "containsThrowableOfType", "(", "Throwable", "throwable", ",", "Class", "<", "?", ">", "...", "throwableTypes", ")", "{", "List", "<", "Throwable", ">", "alreadyProcessedThrowables", "=", "new", "ArrayList", "<", "Throwable", ">", ...
Returns <code>true</code> if the given <code>throwable</code> or one of its cause is an instance of one of the given <code>throwableTypes</code>.
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "given", "<code", ">", "throwable<", "/", "code", ">", "or", "one", "of", "its", "cause", "is", "an", "instance", "of", "one", "of", "the", "given", "<code", ">", "throwableTypes<", "/", ...
train
https://github.com/xebia-france/xebia-management-extras/blob/09f52a0ddb898e402a04f0adfacda74a5d0556e8/src/main/java/fr/xebia/management/statistics/ServiceStatistics.java#L42-L61
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/Statement.java
Statement.writeMethod
public final void writeMethod(int access, Method method, ClassVisitor visitor) { """ Writes this statement to the {@link ClassVisitor} as a method. @param access The access modifiers of the method @param method The method signature @param visitor The class visitor to write it to """ writeMethodTo(new CodeBuilder(access, method, null, visitor)); }
java
public final void writeMethod(int access, Method method, ClassVisitor visitor) { writeMethodTo(new CodeBuilder(access, method, null, visitor)); }
[ "public", "final", "void", "writeMethod", "(", "int", "access", ",", "Method", "method", ",", "ClassVisitor", "visitor", ")", "{", "writeMethodTo", "(", "new", "CodeBuilder", "(", "access", ",", "method", ",", "null", ",", "visitor", ")", ")", ";", "}" ]
Writes this statement to the {@link ClassVisitor} as a method. @param access The access modifiers of the method @param method The method signature @param visitor The class visitor to write it to
[ "Writes", "this", "statement", "to", "the", "{", "@link", "ClassVisitor", "}", "as", "a", "method", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/Statement.java#L124-L126
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/CustomFieldValueReader.java
CustomFieldValueReader.getTypedValue
protected Object getTypedValue(int type, byte[] value) { """ Convert raw value as read from the MPP file into a Java type. @param type MPP value type @param value raw value data @return Java object """ Object result; switch (type) { case 4: // Date { result = MPPUtility.getTimestamp(value, 0); break; } case 6: // Duration { TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits()); result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units); break; } case 9: // Cost { result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100); break; } case 15: // Number { result = Double.valueOf(MPPUtility.getDouble(value, 0)); break; } case 36058: case 21: // Text { result = MPPUtility.getUnicodeString(value, 0); break; } default: { result = value; break; } } return result; }
java
protected Object getTypedValue(int type, byte[] value) { Object result; switch (type) { case 4: // Date { result = MPPUtility.getTimestamp(value, 0); break; } case 6: // Duration { TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits()); result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units); break; } case 9: // Cost { result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100); break; } case 15: // Number { result = Double.valueOf(MPPUtility.getDouble(value, 0)); break; } case 36058: case 21: // Text { result = MPPUtility.getUnicodeString(value, 0); break; } default: { result = value; break; } } return result; }
[ "protected", "Object", "getTypedValue", "(", "int", "type", ",", "byte", "[", "]", "value", ")", "{", "Object", "result", ";", "switch", "(", "type", ")", "{", "case", "4", ":", "// Date", "{", "result", "=", "MPPUtility", ".", "getTimestamp", "(", "va...
Convert raw value as read from the MPP file into a Java type. @param type MPP value type @param value raw value data @return Java object
[ "Convert", "raw", "value", "as", "read", "from", "the", "MPP", "file", "into", "a", "Java", "type", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/CustomFieldValueReader.java#L71-L117
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/msg/ReadWriteMultipleRequest.java
ReadWriteMultipleRequest.readData
public void readData(DataInput input) throws IOException { """ readData -- read the values of the registers to be written, along with the reference and count for the registers to be read. """ readReference = input.readUnsignedShort(); readCount = input.readUnsignedShort(); writeReference = input.readUnsignedShort(); writeCount = input.readUnsignedShort(); int byteCount = input.readUnsignedByte(); if (nonWordDataHandler == null) { byte buffer[] = new byte[byteCount]; input.readFully(buffer, 0, byteCount); int offset = 0; registers = new Register[writeCount]; for (int register = 0; register < writeCount; register++) { registers[register] = new SimpleRegister(buffer[offset], buffer[offset + 1]); offset += 2; } } else { nonWordDataHandler.readData(input, writeReference, writeCount); } }
java
public void readData(DataInput input) throws IOException { readReference = input.readUnsignedShort(); readCount = input.readUnsignedShort(); writeReference = input.readUnsignedShort(); writeCount = input.readUnsignedShort(); int byteCount = input.readUnsignedByte(); if (nonWordDataHandler == null) { byte buffer[] = new byte[byteCount]; input.readFully(buffer, 0, byteCount); int offset = 0; registers = new Register[writeCount]; for (int register = 0; register < writeCount; register++) { registers[register] = new SimpleRegister(buffer[offset], buffer[offset + 1]); offset += 2; } } else { nonWordDataHandler.readData(input, writeReference, writeCount); } }
[ "public", "void", "readData", "(", "DataInput", "input", ")", "throws", "IOException", "{", "readReference", "=", "input", ".", "readUnsignedShort", "(", ")", ";", "readCount", "=", "input", ".", "readUnsignedShort", "(", ")", ";", "writeReference", "=", "inpu...
readData -- read the values of the registers to be written, along with the reference and count for the registers to be read.
[ "readData", "--", "read", "the", "values", "of", "the", "registers", "to", "be", "written", "along", "with", "the", "reference", "and", "count", "for", "the", "registers", "to", "be", "read", "." ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/msg/ReadWriteMultipleRequest.java#L321-L343
qspin/qtaste
kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java
TextUtilities.findWordEnd
public static int findWordEnd(String line, int pos, String noWordSep) { """ Locates the end of the word at the specified position. @param line The text @param pos The position @param noWordSep Characters that are non-alphanumeric, but should be treated as word characters anyway """ return findWordEnd(line, pos, noWordSep, true); }
java
public static int findWordEnd(String line, int pos, String noWordSep) { return findWordEnd(line, pos, noWordSep, true); }
[ "public", "static", "int", "findWordEnd", "(", "String", "line", ",", "int", "pos", ",", "String", "noWordSep", ")", "{", "return", "findWordEnd", "(", "line", ",", "pos", ",", "noWordSep", ",", "true", ")", ";", "}" ]
Locates the end of the word at the specified position. @param line The text @param pos The position @param noWordSep Characters that are non-alphanumeric, but should be treated as word characters anyway
[ "Locates", "the", "end", "of", "the", "word", "at", "the", "specified", "position", "." ]
train
https://github.com/qspin/qtaste/blob/ba45d4d86eb29b92f157c6e98536dee2002ddfdc/kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java#L136-L138
stratosphere/stratosphere
stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/IOManager.java
IOManager.createBlockChannelWriter
public BlockChannelWriter createBlockChannelWriter(Channel.ID channelID, LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException { """ Creates a block channel writer that writes to the given channel. The writer writes asynchronously (write-behind), accepting write request, carrying them out at some time and returning the written segment to the given queue afterwards. @param channelID The descriptor for the channel to write to. @param returnQueue The queue to put the written buffers into. @return A block channel writer that writes to the given channel. @throws IOException Thrown, if the channel for the writer could not be opened. """ if (this.isClosed) { throw new IllegalStateException("I/O-Manger is closed."); } return new BlockChannelWriter(channelID, this.writers[channelID.getThreadNum()].requestQueue, returnQueue, 1); }
java
public BlockChannelWriter createBlockChannelWriter(Channel.ID channelID, LinkedBlockingQueue<MemorySegment> returnQueue) throws IOException { if (this.isClosed) { throw new IllegalStateException("I/O-Manger is closed."); } return new BlockChannelWriter(channelID, this.writers[channelID.getThreadNum()].requestQueue, returnQueue, 1); }
[ "public", "BlockChannelWriter", "createBlockChannelWriter", "(", "Channel", ".", "ID", "channelID", ",", "LinkedBlockingQueue", "<", "MemorySegment", ">", "returnQueue", ")", "throws", "IOException", "{", "if", "(", "this", ".", "isClosed", ")", "{", "throw", "new...
Creates a block channel writer that writes to the given channel. The writer writes asynchronously (write-behind), accepting write request, carrying them out at some time and returning the written segment to the given queue afterwards. @param channelID The descriptor for the channel to write to. @param returnQueue The queue to put the written buffers into. @return A block channel writer that writes to the given channel. @throws IOException Thrown, if the channel for the writer could not be opened.
[ "Creates", "a", "block", "channel", "writer", "that", "writes", "to", "the", "given", "channel", ".", "The", "writer", "writes", "asynchronously", "(", "write", "-", "behind", ")", "accepting", "write", "request", "carrying", "them", "out", "at", "some", "ti...
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-runtime/src/main/java/eu/stratosphere/nephele/services/iomanager/IOManager.java#L243-L252
aehrc/snorocket
snorocket-core/src/main/java/au/csiro/snorocket/core/concurrent/Context.java
Context.processNewEdge
private void processNewEdge(int role, int b) { """ Process new subsumption: a [ role.b @param a @param role @param b """ final RoleSet roleClosure = getRoleClosure(role); processRole(role, b); for (int s = roleClosure.first(); s >= 0; s = roleClosure.next(s + 1)) { if (s == role) continue; processRole(s, b); } }
java
private void processNewEdge(int role, int b) { final RoleSet roleClosure = getRoleClosure(role); processRole(role, b); for (int s = roleClosure.first(); s >= 0; s = roleClosure.next(s + 1)) { if (s == role) continue; processRole(s, b); } }
[ "private", "void", "processNewEdge", "(", "int", "role", ",", "int", "b", ")", "{", "final", "RoleSet", "roleClosure", "=", "getRoleClosure", "(", "role", ")", ";", "processRole", "(", "role", ",", "b", ")", ";", "for", "(", "int", "s", "=", "roleClosu...
Process new subsumption: a [ role.b @param a @param role @param b
[ "Process", "new", "subsumption", ":", "a", "[", "role", ".", "b" ]
train
https://github.com/aehrc/snorocket/blob/e33c1e216f8a66d6502e3a14e80876811feedd8b/snorocket-core/src/main/java/au/csiro/snorocket/core/concurrent/Context.java#L726-L734
liferay/com-liferay-commerce
commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressRestrictionPersistenceImpl.java
CommerceAddressRestrictionPersistenceImpl.findAll
@Override public List<CommerceAddressRestriction> findAll(int start, int end) { """ Returns a range of all the commerce address restrictions. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAddressRestrictionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce address restrictions @param end the upper bound of the range of commerce address restrictions (not inclusive) @return the range of commerce address restrictions """ return findAll(start, end, null); }
java
@Override public List<CommerceAddressRestriction> findAll(int start, int end) { return findAll(start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceAddressRestriction", ">", "findAll", "(", "int", "start", ",", "int", "end", ")", "{", "return", "findAll", "(", "start", ",", "end", ",", "null", ")", ";", "}" ]
Returns a range of all the commerce address restrictions. <p> Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link CommerceAddressRestrictionModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. </p> @param start the lower bound of the range of commerce address restrictions @param end the upper bound of the range of commerce address restrictions (not inclusive) @return the range of commerce address restrictions
[ "Returns", "a", "range", "of", "all", "the", "commerce", "address", "restrictions", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-service/src/main/java/com/liferay/commerce/service/persistence/impl/CommerceAddressRestrictionPersistenceImpl.java#L2046-L2049
Alluxio/alluxio
core/server/common/src/main/java/alluxio/cli/ValidateEnv.java
ValidateEnv.parseArgsAndOptions
private static CommandLine parseArgsAndOptions(Options options, String... args) throws InvalidArgumentException { """ Parses the command line arguments and options in {@code args}. After successful execution of this method, command line arguments can be retrieved by invoking {@link CommandLine#getArgs()}, and options can be retrieved by calling {@link CommandLine#getOptions()}. @param args command line arguments to parse @return {@link CommandLine} object representing the parsing result @throws InvalidArgumentException if command line contains invalid argument(s) """ CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { throw new InvalidArgumentException( "Failed to parse args for validateEnv", e); } return cmd; }
java
private static CommandLine parseArgsAndOptions(Options options, String... args) throws InvalidArgumentException { CommandLineParser parser = new DefaultParser(); CommandLine cmd; try { cmd = parser.parse(options, args); } catch (ParseException e) { throw new InvalidArgumentException( "Failed to parse args for validateEnv", e); } return cmd; }
[ "private", "static", "CommandLine", "parseArgsAndOptions", "(", "Options", "options", ",", "String", "...", "args", ")", "throws", "InvalidArgumentException", "{", "CommandLineParser", "parser", "=", "new", "DefaultParser", "(", ")", ";", "CommandLine", "cmd", ";", ...
Parses the command line arguments and options in {@code args}. After successful execution of this method, command line arguments can be retrieved by invoking {@link CommandLine#getArgs()}, and options can be retrieved by calling {@link CommandLine#getOptions()}. @param args command line arguments to parse @return {@link CommandLine} object representing the parsing result @throws InvalidArgumentException if command line contains invalid argument(s)
[ "Parses", "the", "command", "line", "arguments", "and", "options", "in", "{", "@code", "args", "}", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/cli/ValidateEnv.java#L420-L432
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/watermarker/PartitionLevelWatermarker.java
PartitionLevelWatermarker.getExpectedHighWatermark
@Override public LongWatermark getExpectedHighWatermark(Partition partition, long tableProcessTime, long partitionProcessTime) { """ Get the expected high watermark for this partition {@inheritDoc} @see org.apache.gobblin.data.management.conversion.hive.watermarker.HiveSourceWatermarker#getExpectedHighWatermark(org.apache.hadoop.hive.ql.metadata.Partition, long, long) """ return new LongWatermark(this.expectedHighWatermarks.getPartitionWatermark(tableKey(partition.getTable()), partitionKey(partition))); }
java
@Override public LongWatermark getExpectedHighWatermark(Partition partition, long tableProcessTime, long partitionProcessTime) { return new LongWatermark(this.expectedHighWatermarks.getPartitionWatermark(tableKey(partition.getTable()), partitionKey(partition))); }
[ "@", "Override", "public", "LongWatermark", "getExpectedHighWatermark", "(", "Partition", "partition", ",", "long", "tableProcessTime", ",", "long", "partitionProcessTime", ")", "{", "return", "new", "LongWatermark", "(", "this", ".", "expectedHighWatermarks", ".", "g...
Get the expected high watermark for this partition {@inheritDoc} @see org.apache.gobblin.data.management.conversion.hive.watermarker.HiveSourceWatermarker#getExpectedHighWatermark(org.apache.hadoop.hive.ql.metadata.Partition, long, long)
[ "Get", "the", "expected", "high", "watermark", "for", "this", "partition", "{" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/conversion/hive/watermarker/PartitionLevelWatermarker.java#L357-L361
raphw/byte-buddy
byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByImplementationBenchmark.java
ClassByImplementationBenchmark.benchmarkCglib
@Benchmark public ExampleInterface benchmarkCglib() { """ Performs a benchmark of an interface implementation using cglib. @return The created instance, in order to avoid JIT removal. """ Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); enhancer.setClassLoader(newClassLoader()); enhancer.setSuperclass(baseClass); CallbackHelper callbackHelper = new CallbackHelper(Object.class, new Class[]{baseClass}) { protected Object getCallback(Method method) { if (method.getDeclaringClass() == baseClass) { return new FixedValue() { public Object loadObject() { return null; } }; } else { return NoOp.INSTANCE; } } }; enhancer.setCallbackFilter(callbackHelper); enhancer.setCallbacks(callbackHelper.getCallbacks()); return (ExampleInterface) enhancer.create(); }
java
@Benchmark public ExampleInterface benchmarkCglib() { Enhancer enhancer = new Enhancer(); enhancer.setUseCache(false); enhancer.setClassLoader(newClassLoader()); enhancer.setSuperclass(baseClass); CallbackHelper callbackHelper = new CallbackHelper(Object.class, new Class[]{baseClass}) { protected Object getCallback(Method method) { if (method.getDeclaringClass() == baseClass) { return new FixedValue() { public Object loadObject() { return null; } }; } else { return NoOp.INSTANCE; } } }; enhancer.setCallbackFilter(callbackHelper); enhancer.setCallbacks(callbackHelper.getCallbacks()); return (ExampleInterface) enhancer.create(); }
[ "@", "Benchmark", "public", "ExampleInterface", "benchmarkCglib", "(", ")", "{", "Enhancer", "enhancer", "=", "new", "Enhancer", "(", ")", ";", "enhancer", ".", "setUseCache", "(", "false", ")", ";", "enhancer", ".", "setClassLoader", "(", "newClassLoader", "(...
Performs a benchmark of an interface implementation using cglib. @return The created instance, in order to avoid JIT removal.
[ "Performs", "a", "benchmark", "of", "an", "interface", "implementation", "using", "cglib", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-benchmark/src/main/java/net/bytebuddy/benchmark/ClassByImplementationBenchmark.java#L319-L341
spring-projects/spring-boot
spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java
BuildInfo.generateBuildProperties
@TaskAction public void generateBuildProperties() { """ Generates the {@code build-info.properties} file in the configured {@link #setDestinationDir(File) destination}. """ try { new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties")).writeBuildProperties(new ProjectDetails( this.properties.getGroup(), (this.properties.getArtifact() != null) ? this.properties.getArtifact() : "unspecified", this.properties.getVersion(), this.properties.getName(), this.properties.getTime(), coerceToStringValues(this.properties.getAdditional()))); } catch (IOException ex) { throw new TaskExecutionException(this, ex); } }
java
@TaskAction public void generateBuildProperties() { try { new BuildPropertiesWriter(new File(getDestinationDir(), "build-info.properties")).writeBuildProperties(new ProjectDetails( this.properties.getGroup(), (this.properties.getArtifact() != null) ? this.properties.getArtifact() : "unspecified", this.properties.getVersion(), this.properties.getName(), this.properties.getTime(), coerceToStringValues(this.properties.getAdditional()))); } catch (IOException ex) { throw new TaskExecutionException(this, ex); } }
[ "@", "TaskAction", "public", "void", "generateBuildProperties", "(", ")", "{", "try", "{", "new", "BuildPropertiesWriter", "(", "new", "File", "(", "getDestinationDir", "(", ")", ",", "\"build-info.properties\"", ")", ")", ".", "writeBuildProperties", "(", "new", ...
Generates the {@code build-info.properties} file in the configured {@link #setDestinationDir(File) destination}.
[ "Generates", "the", "{" ]
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot-tools/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/tasks/buildinfo/BuildInfo.java#L53-L68
Azure/azure-sdk-for-java
iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java
IotHubResourcesInner.beginUpdateAsync
public Observable<IotHubDescriptionInner> beginUpdateAsync(String resourceGroupName, String resourceName) { """ Update an existing IoT Hubs tags. Update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method. @param resourceGroupName Resource group identifier. @param resourceName Name of iot hub to update. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IotHubDescriptionInner object """ return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<IotHubDescriptionInner>, IotHubDescriptionInner>() { @Override public IotHubDescriptionInner call(ServiceResponse<IotHubDescriptionInner> response) { return response.body(); } }); }
java
public Observable<IotHubDescriptionInner> beginUpdateAsync(String resourceGroupName, String resourceName) { return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceName).map(new Func1<ServiceResponse<IotHubDescriptionInner>, IotHubDescriptionInner>() { @Override public IotHubDescriptionInner call(ServiceResponse<IotHubDescriptionInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IotHubDescriptionInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "resourceName", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "resourceName", ")", ".", "map", ...
Update an existing IoT Hubs tags. Update an existing IoT Hub tags. to update other fields use the CreateOrUpdate method. @param resourceGroupName Resource group identifier. @param resourceName Name of iot hub to update. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IotHubDescriptionInner object
[ "Update", "an", "existing", "IoT", "Hubs", "tags", ".", "Update", "an", "existing", "IoT", "Hub", "tags", ".", "to", "update", "other", "fields", "use", "the", "CreateOrUpdate", "method", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/iothub/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/implementation/IotHubResourcesInner.java#L860-L867
alkacon/opencms-core
src/org/opencms/jsp/util/CmsJspImageBean.java
CmsJspImageBean.setResource
protected void setResource(CmsObject cms, CmsResource resource) { """ Sets the CmsResource for this image.<p> @param cms the current OpenCms user context, required for wrapping the resource @param resource the VFS resource for this image """ m_resource = CmsJspResourceWrapper.wrap(cms, resource); }
java
protected void setResource(CmsObject cms, CmsResource resource) { m_resource = CmsJspResourceWrapper.wrap(cms, resource); }
[ "protected", "void", "setResource", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ")", "{", "m_resource", "=", "CmsJspResourceWrapper", ".", "wrap", "(", "cms", ",", "resource", ")", ";", "}" ]
Sets the CmsResource for this image.<p> @param cms the current OpenCms user context, required for wrapping the resource @param resource the VFS resource for this image
[ "Sets", "the", "CmsResource", "for", "this", "image", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/util/CmsJspImageBean.java#L1097-L1100
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/config/QuorumConfig.java
QuorumConfig.newRecentlyActiveQuorumConfigBuilder
public static RecentlyActiveQuorumConfigBuilder newRecentlyActiveQuorumConfigBuilder(String name, int size, int toleranceMillis) { """ Returns a builder for a {@link QuorumConfig} with the given {@code name} using a recently-active quorum function for the given quorum {@code size} that is enabled by default. @param name the quorum's name @param size minimum count of members for quorum to be considered present @param toleranceMillis maximum amount of milliseconds that may have passed since last heartbeat was received for a member to be considered present for quorum. @see com.hazelcast.quorum.impl.RecentlyActiveQuorumFunction """ return new RecentlyActiveQuorumConfigBuilder(name, size, toleranceMillis); }
java
public static RecentlyActiveQuorumConfigBuilder newRecentlyActiveQuorumConfigBuilder(String name, int size, int toleranceMillis) { return new RecentlyActiveQuorumConfigBuilder(name, size, toleranceMillis); }
[ "public", "static", "RecentlyActiveQuorumConfigBuilder", "newRecentlyActiveQuorumConfigBuilder", "(", "String", "name", ",", "int", "size", ",", "int", "toleranceMillis", ")", "{", "return", "new", "RecentlyActiveQuorumConfigBuilder", "(", "name", ",", "size", ",", "tol...
Returns a builder for a {@link QuorumConfig} with the given {@code name} using a recently-active quorum function for the given quorum {@code size} that is enabled by default. @param name the quorum's name @param size minimum count of members for quorum to be considered present @param toleranceMillis maximum amount of milliseconds that may have passed since last heartbeat was received for a member to be considered present for quorum. @see com.hazelcast.quorum.impl.RecentlyActiveQuorumFunction
[ "Returns", "a", "builder", "for", "a", "{" ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/config/QuorumConfig.java#L236-L239
alkacon/opencms-core
src-modules/org/opencms/workplace/CmsLogin.java
CmsLogin.setCookieData
public void setCookieData(HttpServletRequest request, HttpServletResponse response) { """ Sets the cookie data.<p> @param request the current request @param response the current response """ setCookieData(m_pcType, m_username, m_oufqn, request, response); }
java
public void setCookieData(HttpServletRequest request, HttpServletResponse response) { setCookieData(m_pcType, m_username, m_oufqn, request, response); }
[ "public", "void", "setCookieData", "(", "HttpServletRequest", "request", ",", "HttpServletResponse", "response", ")", "{", "setCookieData", "(", "m_pcType", ",", "m_username", ",", "m_oufqn", ",", "request", ",", "response", ")", ";", "}" ]
Sets the cookie data.<p> @param request the current request @param response the current response
[ "Sets", "the", "cookie", "data", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/CmsLogin.java#L824-L827
OrienteerBAP/orientdb-oda-birt
org.orienteer.birt.orientdb.ui/src/org/orienteer/birt/orientdb/ui/impl/CustomDataSetWizardPage.java
CustomDataSetWizardPage.savePage
private void savePage( DataSetDesign dataSetDesign ) { """ Saves the user-defined value in this page, and updates the specified dataSetDesign with the latest design definition. """ // save user-defined query text String queryText = getQueryText(); dataSetDesign.setQueryText( queryText ); // obtain query's current runtime metadata, and maps it to the dataSetDesign IConnection customConn = null; try { // instantiate your custom ODA runtime driver class /* Note: You may need to manually update your ODA runtime extension's * plug-in manifest to export its package for visibility here. */ IDriver customDriver = new org.orienteer.birt.orientdb.impl.Driver(); // obtain and open a live connection customConn = customDriver.getConnection( null ); java.util.Properties connProps = DesignSessionUtil.getEffectiveDataSourceProperties( getInitializationDesign().getDataSourceDesign() ); customConn.open( connProps ); // update the data set design with the // query's current runtime metadata updateDesign( dataSetDesign, customConn, queryText ); } catch( OdaException e ) { // not able to get current metadata, reset previous derived metadata dataSetDesign.setResultSets( null ); dataSetDesign.setParameters( null ); e.printStackTrace(); } finally { closeConnection( customConn ); } }
java
private void savePage( DataSetDesign dataSetDesign ) { // save user-defined query text String queryText = getQueryText(); dataSetDesign.setQueryText( queryText ); // obtain query's current runtime metadata, and maps it to the dataSetDesign IConnection customConn = null; try { // instantiate your custom ODA runtime driver class /* Note: You may need to manually update your ODA runtime extension's * plug-in manifest to export its package for visibility here. */ IDriver customDriver = new org.orienteer.birt.orientdb.impl.Driver(); // obtain and open a live connection customConn = customDriver.getConnection( null ); java.util.Properties connProps = DesignSessionUtil.getEffectiveDataSourceProperties( getInitializationDesign().getDataSourceDesign() ); customConn.open( connProps ); // update the data set design with the // query's current runtime metadata updateDesign( dataSetDesign, customConn, queryText ); } catch( OdaException e ) { // not able to get current metadata, reset previous derived metadata dataSetDesign.setResultSets( null ); dataSetDesign.setParameters( null ); e.printStackTrace(); } finally { closeConnection( customConn ); } }
[ "private", "void", "savePage", "(", "DataSetDesign", "dataSetDesign", ")", "{", "// save user-defined query text", "String", "queryText", "=", "getQueryText", "(", ")", ";", "dataSetDesign", ".", "setQueryText", "(", "queryText", ")", ";", "// obtain query's current run...
Saves the user-defined value in this page, and updates the specified dataSetDesign with the latest design definition.
[ "Saves", "the", "user", "-", "defined", "value", "in", "this", "page", "and", "updates", "the", "specified", "dataSetDesign", "with", "the", "latest", "design", "definition", "." ]
train
https://github.com/OrienteerBAP/orientdb-oda-birt/blob/62820c256fa1d221265e68b8ebb60f291a9a1405/org.orienteer.birt.orientdb.ui/src/org/orienteer/birt/orientdb/ui/impl/CustomDataSetWizardPage.java#L229-L268
airbnb/lottie-android
lottie/src/main/java/com/airbnb/lottie/parser/AnimatablePathValueParser.java
AnimatablePathValueParser.parseSplitPath
static AnimatableValue<PointF, PointF> parseSplitPath( JsonReader reader, LottieComposition composition) throws IOException { """ Returns either an {@link AnimatablePathValue} or an {@link AnimatableSplitDimensionPathValue}. """ AnimatablePathValue pathAnimation = null; AnimatableFloatValue xAnimation = null; AnimatableFloatValue yAnimation = null; boolean hasExpressions = false; reader.beginObject(); while (reader.peek() != JsonToken.END_OBJECT) { switch (reader.nextName()) { case "k": pathAnimation = AnimatablePathValueParser.parse(reader, composition); break; case "x": if (reader.peek() == JsonToken.STRING) { hasExpressions = true; reader.skipValue(); } else { xAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; case "y": if (reader.peek() == JsonToken.STRING) { hasExpressions = true; reader.skipValue(); } else { yAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; default: reader.skipValue(); } } reader.endObject(); if (hasExpressions) { composition.addWarning("Lottie doesn't support expressions."); } if (pathAnimation != null) { return pathAnimation; } return new AnimatableSplitDimensionPathValue(xAnimation, yAnimation); }
java
static AnimatableValue<PointF, PointF> parseSplitPath( JsonReader reader, LottieComposition composition) throws IOException { AnimatablePathValue pathAnimation = null; AnimatableFloatValue xAnimation = null; AnimatableFloatValue yAnimation = null; boolean hasExpressions = false; reader.beginObject(); while (reader.peek() != JsonToken.END_OBJECT) { switch (reader.nextName()) { case "k": pathAnimation = AnimatablePathValueParser.parse(reader, composition); break; case "x": if (reader.peek() == JsonToken.STRING) { hasExpressions = true; reader.skipValue(); } else { xAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; case "y": if (reader.peek() == JsonToken.STRING) { hasExpressions = true; reader.skipValue(); } else { yAnimation = AnimatableValueParser.parseFloat(reader, composition); } break; default: reader.skipValue(); } } reader.endObject(); if (hasExpressions) { composition.addWarning("Lottie doesn't support expressions."); } if (pathAnimation != null) { return pathAnimation; } return new AnimatableSplitDimensionPathValue(xAnimation, yAnimation); }
[ "static", "AnimatableValue", "<", "PointF", ",", "PointF", ">", "parseSplitPath", "(", "JsonReader", "reader", ",", "LottieComposition", "composition", ")", "throws", "IOException", "{", "AnimatablePathValue", "pathAnimation", "=", "null", ";", "AnimatableFloatValue", ...
Returns either an {@link AnimatablePathValue} or an {@link AnimatableSplitDimensionPathValue}.
[ "Returns", "either", "an", "{" ]
train
https://github.com/airbnb/lottie-android/blob/126dabdc9f586c87822f85fe1128cdad439d30fa/lottie/src/main/java/com/airbnb/lottie/parser/AnimatablePathValueParser.java#L42-L87
pmwmedia/tinylog
tinylog-impl/src/main/java/org/tinylog/path/DynamicPath.java
DynamicPath.parseSegment
private static Segment parseSegment(final String path, final String token) { """ Parses a token from a pattern as a segment. @param path Full path with patterns @param token Token from a pattern @return Created segment that represents the passed token """ int separator = token.indexOf(':'); String name; String parameter; if (separator == -1) { name = token.trim(); parameter = null; } else { name = token.substring(0, separator).trim(); parameter = token.substring(separator + 1).trim(); } if ("date".equals(name)) { return new DateSegment(parameter == null ? DEFAULT_DATE_FORMAT_PATTERN : parameter); } else if ("count".equals(name) && parameter == null) { return new CountSegment(); } else if ("pid".equals(name) && parameter == null) { return new ProcessIdSegment(); } else { throw new IllegalArgumentException("Invalid token '" + token + "' in '" + path + "'"); } }
java
private static Segment parseSegment(final String path, final String token) { int separator = token.indexOf(':'); String name; String parameter; if (separator == -1) { name = token.trim(); parameter = null; } else { name = token.substring(0, separator).trim(); parameter = token.substring(separator + 1).trim(); } if ("date".equals(name)) { return new DateSegment(parameter == null ? DEFAULT_DATE_FORMAT_PATTERN : parameter); } else if ("count".equals(name) && parameter == null) { return new CountSegment(); } else if ("pid".equals(name) && parameter == null) { return new ProcessIdSegment(); } else { throw new IllegalArgumentException("Invalid token '" + token + "' in '" + path + "'"); } }
[ "private", "static", "Segment", "parseSegment", "(", "final", "String", "path", ",", "final", "String", "token", ")", "{", "int", "separator", "=", "token", ".", "indexOf", "(", "'", "'", ")", ";", "String", "name", ";", "String", "parameter", ";", "if",...
Parses a token from a pattern as a segment. @param path Full path with patterns @param token Token from a pattern @return Created segment that represents the passed token
[ "Parses", "a", "token", "from", "a", "pattern", "as", "a", "segment", "." ]
train
https://github.com/pmwmedia/tinylog/blob/d03d4ef84a1310155037e08ca8822a91697d1086/tinylog-impl/src/main/java/org/tinylog/path/DynamicPath.java#L221-L244
janus-project/guava.janusproject.io
guava/src/com/google/common/base/CharMatcher.java
CharMatcher.replaceFrom
@CheckReturnValue public String replaceFrom(CharSequence sequence, char replacement) { """ Returns a string copy of the input character sequence, with each character that matches this matcher replaced by a given replacement character. For example: <pre> {@code CharMatcher.is('a').replaceFrom("radar", 'o')}</pre> ... returns {@code "rodor"}. <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching character, then iterates the remainder of the sequence calling {@link #matches(char)} for each character. @param sequence the character sequence to replace matching characters in @param replacement the character to append to the result string in place of each matching character in {@code sequence} @return the new string """ String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); chars[pos] = replacement; for (int i = pos + 1; i < chars.length; i++) { if (matches(chars[i])) { chars[i] = replacement; } } return new String(chars); }
java
@CheckReturnValue public String replaceFrom(CharSequence sequence, char replacement) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); chars[pos] = replacement; for (int i = pos + 1; i < chars.length; i++) { if (matches(chars[i])) { chars[i] = replacement; } } return new String(chars); }
[ "@", "CheckReturnValue", "public", "String", "replaceFrom", "(", "CharSequence", "sequence", ",", "char", "replacement", ")", "{", "String", "string", "=", "sequence", ".", "toString", "(", ")", ";", "int", "pos", "=", "indexIn", "(", "string", ")", ";", "...
Returns a string copy of the input character sequence, with each character that matches this matcher replaced by a given replacement character. For example: <pre> {@code CharMatcher.is('a').replaceFrom("radar", 'o')}</pre> ... returns {@code "rodor"}. <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching character, then iterates the remainder of the sequence calling {@link #matches(char)} for each character. @param sequence the character sequence to replace matching characters in @param replacement the character to append to the result string in place of each matching character in {@code sequence} @return the new string
[ "Returns", "a", "string", "copy", "of", "the", "input", "character", "sequence", "with", "each", "character", "that", "matches", "this", "matcher", "replaced", "by", "a", "given", "replacement", "character", ".", "For", "example", ":", "<pre", ">", "{", "@co...
train
https://github.com/janus-project/guava.janusproject.io/blob/1c48fb672c9fdfddf276970570f703fa1115f588/guava/src/com/google/common/base/CharMatcher.java#L1113-L1128
opencb/java-common-libs
commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/GenericDocumentComplexConverter.java
GenericDocumentComplexConverter.replaceDots
public static Document replaceDots(Document document) { """ Replace all the dots in the keys with {@link #TO_REPLACE_DOTS}. MongoDB is not able to store dots in key fields. @param document Document to modify @return Document modified """ return modifyKeys(document, key -> key.replace(".", TO_REPLACE_DOTS), "."); }
java
public static Document replaceDots(Document document) { return modifyKeys(document, key -> key.replace(".", TO_REPLACE_DOTS), "."); }
[ "public", "static", "Document", "replaceDots", "(", "Document", "document", ")", "{", "return", "modifyKeys", "(", "document", ",", "key", "->", "key", ".", "replace", "(", "\".\"", ",", "TO_REPLACE_DOTS", ")", ",", "\".\"", ")", ";", "}" ]
Replace all the dots in the keys with {@link #TO_REPLACE_DOTS}. MongoDB is not able to store dots in key fields. @param document Document to modify @return Document modified
[ "Replace", "all", "the", "dots", "in", "the", "keys", "with", "{", "@link", "#TO_REPLACE_DOTS", "}", "." ]
train
https://github.com/opencb/java-common-libs/blob/5c97682530d0be55828e1e4e374ff01fceb5f198/commons-datastore/commons-datastore-mongodb/src/main/java/org/opencb/commons/datastore/mongodb/GenericDocumentComplexConverter.java#L109-L111
alkacon/opencms-core
src-modules/org/opencms/workplace/commons/CmsLock.java
CmsLock.buildDefaultConfirmationJS
public String buildDefaultConfirmationJS() { """ Returns the html code to build the dialogs default confirmation message js.<p> @return html code """ StringBuffer html = new StringBuffer(512); html.append("<script type='text/javascript'><!--\n"); html.append("function setConfirmationMessage(locks, blockinglocks) {\n"); html.append("\tvar confMsg = document.getElementById('conf-msg');\n"); html.append("\tif (locks > -1) {\n"); if (!getSettings().getUserSettings().getDialogShowLock() && (CmsLock.getDialogAction(getCms()) != CmsLock.TYPE_LOCKS)) { // auto commit if lock dialog disabled html.append("\t\tif (blockinglocks == 0) {\n"); html.append("\t\t\tsubmitAction('"); html.append(CmsDialog.DIALOG_OK); html.append("', null, 'main');\n"); html.append("\t\t\tdocument.forms['main'].submit();\n"); html.append("\t\t\treturn;\n"); html.append("\t\t}\n"); } html.append("\t\tdocument.getElementById('lock-body-id').className = '';\n"); html.append("\t\tif (locks > '0') {\n"); html.append("\t\t\tshowAjaxReportContent();\n"); html.append("\t\t\tconfMsg.innerHTML = '"); html.append(getConfirmationMessage(false)); html.append("';\n"); html.append("\t\t} else {\n"); html.append("\t\t\tshowAjaxOk();\n"); html.append("\t\t\tconfMsg.innerHTML = '"); html.append(getConfirmationMessage(true)); html.append("';\n"); html.append("\t\t}\n"); html.append("\t} else {\n"); html.append("\t\tconfMsg.innerHTML = '"); html.append(key(org.opencms.workplace.Messages.GUI_AJAX_REPORT_WAIT_0)); html.append("';\n"); html.append("\t}\n"); html.append("}\n"); html.append("// -->\n"); html.append("</script>\n"); return html.toString(); }
java
public String buildDefaultConfirmationJS() { StringBuffer html = new StringBuffer(512); html.append("<script type='text/javascript'><!--\n"); html.append("function setConfirmationMessage(locks, blockinglocks) {\n"); html.append("\tvar confMsg = document.getElementById('conf-msg');\n"); html.append("\tif (locks > -1) {\n"); if (!getSettings().getUserSettings().getDialogShowLock() && (CmsLock.getDialogAction(getCms()) != CmsLock.TYPE_LOCKS)) { // auto commit if lock dialog disabled html.append("\t\tif (blockinglocks == 0) {\n"); html.append("\t\t\tsubmitAction('"); html.append(CmsDialog.DIALOG_OK); html.append("', null, 'main');\n"); html.append("\t\t\tdocument.forms['main'].submit();\n"); html.append("\t\t\treturn;\n"); html.append("\t\t}\n"); } html.append("\t\tdocument.getElementById('lock-body-id').className = '';\n"); html.append("\t\tif (locks > '0') {\n"); html.append("\t\t\tshowAjaxReportContent();\n"); html.append("\t\t\tconfMsg.innerHTML = '"); html.append(getConfirmationMessage(false)); html.append("';\n"); html.append("\t\t} else {\n"); html.append("\t\t\tshowAjaxOk();\n"); html.append("\t\t\tconfMsg.innerHTML = '"); html.append(getConfirmationMessage(true)); html.append("';\n"); html.append("\t\t}\n"); html.append("\t} else {\n"); html.append("\t\tconfMsg.innerHTML = '"); html.append(key(org.opencms.workplace.Messages.GUI_AJAX_REPORT_WAIT_0)); html.append("';\n"); html.append("\t}\n"); html.append("}\n"); html.append("// -->\n"); html.append("</script>\n"); return html.toString(); }
[ "public", "String", "buildDefaultConfirmationJS", "(", ")", "{", "StringBuffer", "html", "=", "new", "StringBuffer", "(", "512", ")", ";", "html", ".", "append", "(", "\"<script type='text/javascript'><!--\\n\"", ")", ";", "html", ".", "append", "(", "\"function s...
Returns the html code to build the dialogs default confirmation message js.<p> @return html code
[ "Returns", "the", "html", "code", "to", "build", "the", "dialogs", "default", "confirmation", "message", "js", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-modules/org/opencms/workplace/commons/CmsLock.java#L335-L374
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java
IoUtil.toStream
public static ByteArrayInputStream toStream(String content, String charsetName) { """ String 转为流 @param content 内容 @param charsetName 编码 @return 字节流 """ return toStream(content, CharsetUtil.charset(charsetName)); }
java
public static ByteArrayInputStream toStream(String content, String charsetName) { return toStream(content, CharsetUtil.charset(charsetName)); }
[ "public", "static", "ByteArrayInputStream", "toStream", "(", "String", "content", ",", "String", "charsetName", ")", "{", "return", "toStream", "(", "content", ",", "CharsetUtil", ".", "charset", "(", "charsetName", ")", ")", ";", "}" ]
String 转为流 @param content 内容 @param charsetName 编码 @return 字节流
[ "String", "转为流" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/IoUtil.java#L739-L741
apereo/cas
core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java
ScriptingUtils.executeScriptEngine
public static <T> T executeScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) { """ Execute groovy script engine t. @param <T> the type parameter @param scriptFile the script file @param args the args @param clazz the clazz @return the t """ try { val engineName = getScriptEngineName(scriptFile); val engine = new ScriptEngineManager().getEngineByName(engineName); if (engine == null || StringUtils.isBlank(engineName)) { LOGGER.warn("Script engine is not available for [{}]", engineName); return null; } val resourceFrom = ResourceUtils.getResourceFrom(scriptFile); val theScriptFile = resourceFrom.getFile(); if (theScriptFile.exists()) { LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath()); try (val reader = Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8)) { engine.eval(reader); } val invocable = (Invocable) engine; LOGGER.debug("Executing script's run method, with parameters [{}]", args); val result = invocable.invokeFunction("run", args); LOGGER.debug("Groovy script result is [{}]", result); return getGroovyScriptExecutionResultOrThrow(clazz, result); } LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
java
public static <T> T executeScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) { try { val engineName = getScriptEngineName(scriptFile); val engine = new ScriptEngineManager().getEngineByName(engineName); if (engine == null || StringUtils.isBlank(engineName)) { LOGGER.warn("Script engine is not available for [{}]", engineName); return null; } val resourceFrom = ResourceUtils.getResourceFrom(scriptFile); val theScriptFile = resourceFrom.getFile(); if (theScriptFile.exists()) { LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath()); try (val reader = Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8)) { engine.eval(reader); } val invocable = (Invocable) engine; LOGGER.debug("Executing script's run method, with parameters [{}]", args); val result = invocable.invokeFunction("run", args); LOGGER.debug("Groovy script result is [{}]", result); return getGroovyScriptExecutionResultOrThrow(clazz, result); } LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
[ "public", "static", "<", "T", ">", "T", "executeScriptEngine", "(", "final", "String", "scriptFile", ",", "final", "Object", "[", "]", "args", ",", "final", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "val", "engineName", "=", "getScriptEngine...
Execute groovy script engine t. @param <T> the type parameter @param scriptFile the script file @param args the args @param clazz the clazz @return the t
[ "Execute", "groovy", "script", "engine", "t", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-util-api/src/main/java/org/apereo/cas/util/scripting/ScriptingUtils.java#L337-L365
janvanbesien/java-ipv6
src/main/java/com/googlecode/ipv6/IPv6Address.java
IPv6Address.maskWithNetworkMask
public IPv6Address maskWithNetworkMask(final IPv6NetworkMask networkMask) { """ Mask the address with the given network mask. @param networkMask network mask @return an address of which the last 128 - networkMask.asPrefixLength() bits are zero """ if (networkMask.asPrefixLength() == 128) { return this; } else if (networkMask.asPrefixLength() == 64) { return new IPv6Address(this.highBits, 0); } else if (networkMask.asPrefixLength() == 0) { return new IPv6Address(0, 0); } else if (networkMask.asPrefixLength() > 64) { // apply mask on low bits only final int remainingPrefixLength = networkMask.asPrefixLength() - 64; return new IPv6Address(this.highBits, this.lowBits & (0xFFFFFFFFFFFFFFFFL << (64 - remainingPrefixLength))); } else { // apply mask on high bits, low bits completely 0 return new IPv6Address(this.highBits & (0xFFFFFFFFFFFFFFFFL << (64 - networkMask.asPrefixLength())), 0); } }
java
public IPv6Address maskWithNetworkMask(final IPv6NetworkMask networkMask) { if (networkMask.asPrefixLength() == 128) { return this; } else if (networkMask.asPrefixLength() == 64) { return new IPv6Address(this.highBits, 0); } else if (networkMask.asPrefixLength() == 0) { return new IPv6Address(0, 0); } else if (networkMask.asPrefixLength() > 64) { // apply mask on low bits only final int remainingPrefixLength = networkMask.asPrefixLength() - 64; return new IPv6Address(this.highBits, this.lowBits & (0xFFFFFFFFFFFFFFFFL << (64 - remainingPrefixLength))); } else { // apply mask on high bits, low bits completely 0 return new IPv6Address(this.highBits & (0xFFFFFFFFFFFFFFFFL << (64 - networkMask.asPrefixLength())), 0); } }
[ "public", "IPv6Address", "maskWithNetworkMask", "(", "final", "IPv6NetworkMask", "networkMask", ")", "{", "if", "(", "networkMask", ".", "asPrefixLength", "(", ")", "==", "128", ")", "{", "return", "this", ";", "}", "else", "if", "(", "networkMask", ".", "as...
Mask the address with the given network mask. @param networkMask network mask @return an address of which the last 128 - networkMask.asPrefixLength() bits are zero
[ "Mask", "the", "address", "with", "the", "given", "network", "mask", "." ]
train
https://github.com/janvanbesien/java-ipv6/blob/9af15b4a6c0074f9fa23dfa030027c631b9c2f78/src/main/java/com/googlecode/ipv6/IPv6Address.java#L272-L297
apache/incubator-druid
extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java
ApproximateHistogram.heapDelete
private static int heapDelete(int[] heap, int[] reverseIndex, int count, int heapIndex, float[] values) { """ Deletes an item from the min-heap and updates the reverse index @param heap min-heap stored as indices into the array of values @param reverseIndex reverse index from the array of values into the heap @param count current size of the heap @param heapIndex index of the item to be deleted @param values values stored in the heap """ int end = count - 1; reverseIndex[heap[heapIndex]] = -1; heap[heapIndex] = heap[end]; reverseIndex[heap[heapIndex]] = heapIndex; end--; siftDown(heap, reverseIndex, heapIndex, end, values); return count - 1; }
java
private static int heapDelete(int[] heap, int[] reverseIndex, int count, int heapIndex, float[] values) { int end = count - 1; reverseIndex[heap[heapIndex]] = -1; heap[heapIndex] = heap[end]; reverseIndex[heap[heapIndex]] = heapIndex; end--; siftDown(heap, reverseIndex, heapIndex, end, values); return count - 1; }
[ "private", "static", "int", "heapDelete", "(", "int", "[", "]", "heap", ",", "int", "[", "]", "reverseIndex", ",", "int", "count", ",", "int", "heapIndex", ",", "float", "[", "]", "values", ")", "{", "int", "end", "=", "count", "-", "1", ";", "reve...
Deletes an item from the min-heap and updates the reverse index @param heap min-heap stored as indices into the array of values @param reverseIndex reverse index from the array of values into the heap @param count current size of the heap @param heapIndex index of the item to be deleted @param values values stored in the heap
[ "Deletes", "an", "item", "from", "the", "min", "-", "heap", "and", "updates", "the", "reverse", "index" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/histogram/src/main/java/org/apache/druid/query/aggregation/histogram/ApproximateHistogram.java#L1044-L1056
Appendium/objectlabkit
utils/src/main/java/net/objectlab/kit/util/Util.java
Util.listify
public static List<String> listify(final String str, final String delimiter) { """ helper method to convert a 'delimiter' separated string to a list. This is a VERY basic parsing/creation of CSV, if you seen anything superior then use <a href="http://flatpack.sf.net">FlatPack</a>. @param str the 'delimiter' separated string @param delimiter typically a ',' @return a list @see <a href="http://flatpack.sf.net">FlatPack</a> for more comprehensive parser """ if (str == null) { return Collections.emptyList(); } final StringTokenizer tok = new StringTokenizer(str, delimiter); final List<String> list = new ArrayList<>(); while (tok.hasMoreElements()) { list.add(StringUtil.trim(tok.nextToken())); } return list; }
java
public static List<String> listify(final String str, final String delimiter) { if (str == null) { return Collections.emptyList(); } final StringTokenizer tok = new StringTokenizer(str, delimiter); final List<String> list = new ArrayList<>(); while (tok.hasMoreElements()) { list.add(StringUtil.trim(tok.nextToken())); } return list; }
[ "public", "static", "List", "<", "String", ">", "listify", "(", "final", "String", "str", ",", "final", "String", "delimiter", ")", "{", "if", "(", "str", "==", "null", ")", "{", "return", "Collections", ".", "emptyList", "(", ")", ";", "}", "final", ...
helper method to convert a 'delimiter' separated string to a list. This is a VERY basic parsing/creation of CSV, if you seen anything superior then use <a href="http://flatpack.sf.net">FlatPack</a>. @param str the 'delimiter' separated string @param delimiter typically a ',' @return a list @see <a href="http://flatpack.sf.net">FlatPack</a> for more comprehensive parser
[ "helper", "method", "to", "convert", "a", "delimiter", "separated", "string", "to", "a", "list", ".", "This", "is", "a", "VERY", "basic", "parsing", "/", "creation", "of", "CSV", "if", "you", "seen", "anything", "superior", "then", "use", "<a", "href", "...
train
https://github.com/Appendium/objectlabkit/blob/cd649bce7a32e4e926520e62cb765f3b1d451594/utils/src/main/java/net/objectlab/kit/util/Util.java#L65-L78
mgledi/DRUMS
src/main/java/com/unister/semweb/drums/bucket/BucketSplitter.java
BucketSplitter.moveElements
protected void moveElements(HeaderIndexFile<Data> source, RangeHashFunction targetHashfunction, String workingDir) throws IOException, FileLockException { """ moves elements from the source file to new smaller files. The filenames are generated automatically @param source @param targetHashfunction @param workingDir @throws IOException @throws FileLockException """ ByteBuffer elem = ByteBuffer.allocate(source.getElementSize()); HeaderIndexFile<Data> tmp = null; newBucketIds = new IntArrayList(); long offset = 0; byte[] key = new byte[gp.getKeySize()]; int oldBucket = -1, newBucket; while (offset < source.getFilledUpFromContentStart()) { source.read(offset, elem); elem.rewind(); elem.get(key); newBucket = targetHashfunction.getBucketId(key); if (newBucket != oldBucket) { this.newBucketIds.add(newBucket); if (tmp != null) { tmp.close(); } String fileName = workingDir + "/" + targetHashfunction.getFilename(newBucket); tmp = new HeaderIndexFile<Data>(fileName, AccessMode.READ_WRITE, 100, gp); oldBucket = newBucket; } tmp.append(elem); offset += elem.limit(); } if (tmp != null) tmp.close(); }
java
protected void moveElements(HeaderIndexFile<Data> source, RangeHashFunction targetHashfunction, String workingDir) throws IOException, FileLockException { ByteBuffer elem = ByteBuffer.allocate(source.getElementSize()); HeaderIndexFile<Data> tmp = null; newBucketIds = new IntArrayList(); long offset = 0; byte[] key = new byte[gp.getKeySize()]; int oldBucket = -1, newBucket; while (offset < source.getFilledUpFromContentStart()) { source.read(offset, elem); elem.rewind(); elem.get(key); newBucket = targetHashfunction.getBucketId(key); if (newBucket != oldBucket) { this.newBucketIds.add(newBucket); if (tmp != null) { tmp.close(); } String fileName = workingDir + "/" + targetHashfunction.getFilename(newBucket); tmp = new HeaderIndexFile<Data>(fileName, AccessMode.READ_WRITE, 100, gp); oldBucket = newBucket; } tmp.append(elem); offset += elem.limit(); } if (tmp != null) tmp.close(); }
[ "protected", "void", "moveElements", "(", "HeaderIndexFile", "<", "Data", ">", "source", ",", "RangeHashFunction", "targetHashfunction", ",", "String", "workingDir", ")", "throws", "IOException", ",", "FileLockException", "{", "ByteBuffer", "elem", "=", "ByteBuffer", ...
moves elements from the source file to new smaller files. The filenames are generated automatically @param source @param targetHashfunction @param workingDir @throws IOException @throws FileLockException
[ "moves", "elements", "from", "the", "source", "file", "to", "new", "smaller", "files", ".", "The", "filenames", "are", "generated", "automatically" ]
train
https://github.com/mgledi/DRUMS/blob/a670f17a2186c9a15725f26617d77ce8e444e072/src/main/java/com/unister/semweb/drums/bucket/BucketSplitter.java#L110-L139
sirthias/parboiled
parboiled-core/src/main/java/org/parboiled/support/IndexRange.java
IndexRange.mergedWith
public IndexRange mergedWith(IndexRange other) { """ Created a new IndexRange that spans all characters between the smallest and the highest index of the two ranges. @param other the other range @return a new IndexRange instance """ checkArgNotNull(other, "other"); return new IndexRange(Math.min(start, other.start), Math.max(end, other.end)); }
java
public IndexRange mergedWith(IndexRange other) { checkArgNotNull(other, "other"); return new IndexRange(Math.min(start, other.start), Math.max(end, other.end)); }
[ "public", "IndexRange", "mergedWith", "(", "IndexRange", "other", ")", "{", "checkArgNotNull", "(", "other", ",", "\"other\"", ")", ";", "return", "new", "IndexRange", "(", "Math", ".", "min", "(", "start", ",", "other", ".", "start", ")", ",", "Math", "...
Created a new IndexRange that spans all characters between the smallest and the highest index of the two ranges. @param other the other range @return a new IndexRange instance
[ "Created", "a", "new", "IndexRange", "that", "spans", "all", "characters", "between", "the", "smallest", "and", "the", "highest", "index", "of", "the", "two", "ranges", "." ]
train
https://github.com/sirthias/parboiled/blob/84f3ed43e3e171b4c6ab5e6ca6297d264a9d686a/parboiled-core/src/main/java/org/parboiled/support/IndexRange.java#L112-L115
micronaut-projects/micronaut-core
core/src/main/java/io/micronaut/core/annotation/AnnotationValueBuilder.java
AnnotationValueBuilder.values
public AnnotationValueBuilder<T> values(@Nullable Class<?>... types) { """ Sets the value member to the given type objects. @param types The type[] @return This builder """ return member(AnnotationMetadata.VALUE_MEMBER, types); }
java
public AnnotationValueBuilder<T> values(@Nullable Class<?>... types) { return member(AnnotationMetadata.VALUE_MEMBER, types); }
[ "public", "AnnotationValueBuilder", "<", "T", ">", "values", "(", "@", "Nullable", "Class", "<", "?", ">", "...", "types", ")", "{", "return", "member", "(", "AnnotationMetadata", ".", "VALUE_MEMBER", ",", "types", ")", ";", "}" ]
Sets the value member to the given type objects. @param types The type[] @return This builder
[ "Sets", "the", "value", "member", "to", "the", "given", "type", "objects", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/core/src/main/java/io/micronaut/core/annotation/AnnotationValueBuilder.java#L169-L171
OpenLiberty/open-liberty
dev/com.ibm.ws.install/src/com/ibm/ws/install/RepositoryConfigUtils.java
RepositoryConfigUtils.setProxyAuthenticator
public static void setProxyAuthenticator(final String proxyHost, final String proxyPort, final String proxyUser, final String decodedPwd) { """ Set Proxy Authenticator Default @param proxyHost The proxy host @param proxyPort The proxy port @param proxyUser the proxy username @param decodedPwd the proxy password decoded """ if (proxyUser == null || proxyUser.isEmpty() || decodedPwd == null || decodedPwd.isEmpty()) { return; } //Authenticate proxy credentials Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { if (getRequestingHost().equals(proxyHost) && getRequestingPort() == Integer.valueOf(proxyPort)) { return new PasswordAuthentication(proxyUser, decodedPwd.toCharArray()); } } return null; } }); }
java
public static void setProxyAuthenticator(final String proxyHost, final String proxyPort, final String proxyUser, final String decodedPwd) { if (proxyUser == null || proxyUser.isEmpty() || decodedPwd == null || decodedPwd.isEmpty()) { return; } //Authenticate proxy credentials Authenticator.setDefault(new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { if (getRequestorType() == RequestorType.PROXY) { if (getRequestingHost().equals(proxyHost) && getRequestingPort() == Integer.valueOf(proxyPort)) { return new PasswordAuthentication(proxyUser, decodedPwd.toCharArray()); } } return null; } }); }
[ "public", "static", "void", "setProxyAuthenticator", "(", "final", "String", "proxyHost", ",", "final", "String", "proxyPort", ",", "final", "String", "proxyUser", ",", "final", "String", "decodedPwd", ")", "{", "if", "(", "proxyUser", "==", "null", "||", "pro...
Set Proxy Authenticator Default @param proxyHost The proxy host @param proxyPort The proxy port @param proxyUser the proxy username @param decodedPwd the proxy password decoded
[ "Set", "Proxy", "Authenticator", "Default" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.install/src/com/ibm/ws/install/RepositoryConfigUtils.java#L131-L147
Bedework/bw-util
bw-util-misc/src/main/java/org/bedework/util/misc/Util.java
Util.makeRandomString
public static String makeRandomString(int length, int maxVal) { """ Creates a string of given length where each character comes from a set of values 0-9 followed by A-Z. @param length returned string will be this long. Less than 1k + 1 @param maxVal maximum ordinal value of characters. If < than 0, return null. If > 35, 35 is used instead. @return String the random string """ if (length < 0) { return null; } length = Math.min(length, 1025); if (maxVal < 0) { return null; } maxVal = Math.min(maxVal, 35); StringBuffer res = new StringBuffer(); Random rand = new Random(); for (int i = 0; i <= length; i++) { res.append(randChars[rand.nextInt(maxVal + 1)]); } return res.toString(); }
java
public static String makeRandomString(int length, int maxVal) { if (length < 0) { return null; } length = Math.min(length, 1025); if (maxVal < 0) { return null; } maxVal = Math.min(maxVal, 35); StringBuffer res = new StringBuffer(); Random rand = new Random(); for (int i = 0; i <= length; i++) { res.append(randChars[rand.nextInt(maxVal + 1)]); } return res.toString(); }
[ "public", "static", "String", "makeRandomString", "(", "int", "length", ",", "int", "maxVal", ")", "{", "if", "(", "length", "<", "0", ")", "{", "return", "null", ";", "}", "length", "=", "Math", ".", "min", "(", "length", ",", "1025", ")", ";", "i...
Creates a string of given length where each character comes from a set of values 0-9 followed by A-Z. @param length returned string will be this long. Less than 1k + 1 @param maxVal maximum ordinal value of characters. If < than 0, return null. If > 35, 35 is used instead. @return String the random string
[ "Creates", "a", "string", "of", "given", "length", "where", "each", "character", "comes", "from", "a", "set", "of", "values", "0", "-", "9", "followed", "by", "A", "-", "Z", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-misc/src/main/java/org/bedework/util/misc/Util.java#L456-L477
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/Type1Font.java
Type1Font.getFontDescriptor
public float getFontDescriptor(int key, float fontSize) { """ Gets the font parameter identified by <CODE>key</CODE>. Valid values for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>, <CODE>ITALICANGLE</CODE>, <CODE>BBOXLLX</CODE>, <CODE>BBOXLLY</CODE>, <CODE>BBOXURX</CODE> and <CODE>BBOXURY</CODE>. @param key the parameter to be extracted @param fontSize the font size in points @return the parameter in points """ switch (key) { case AWT_ASCENT: case ASCENT: return Ascender * fontSize / 1000; case CAPHEIGHT: return CapHeight * fontSize / 1000; case AWT_DESCENT: case DESCENT: return Descender * fontSize / 1000; case ITALICANGLE: return ItalicAngle; case BBOXLLX: return llx * fontSize / 1000; case BBOXLLY: return lly * fontSize / 1000; case BBOXURX: return urx * fontSize / 1000; case BBOXURY: return ury * fontSize / 1000; case AWT_LEADING: return 0; case AWT_MAXADVANCE: return (urx - llx) * fontSize / 1000; case UNDERLINE_POSITION: return UnderlinePosition * fontSize / 1000; case UNDERLINE_THICKNESS: return UnderlineThickness * fontSize / 1000; } return 0; }
java
public float getFontDescriptor(int key, float fontSize) { switch (key) { case AWT_ASCENT: case ASCENT: return Ascender * fontSize / 1000; case CAPHEIGHT: return CapHeight * fontSize / 1000; case AWT_DESCENT: case DESCENT: return Descender * fontSize / 1000; case ITALICANGLE: return ItalicAngle; case BBOXLLX: return llx * fontSize / 1000; case BBOXLLY: return lly * fontSize / 1000; case BBOXURX: return urx * fontSize / 1000; case BBOXURY: return ury * fontSize / 1000; case AWT_LEADING: return 0; case AWT_MAXADVANCE: return (urx - llx) * fontSize / 1000; case UNDERLINE_POSITION: return UnderlinePosition * fontSize / 1000; case UNDERLINE_THICKNESS: return UnderlineThickness * fontSize / 1000; } return 0; }
[ "public", "float", "getFontDescriptor", "(", "int", "key", ",", "float", "fontSize", ")", "{", "switch", "(", "key", ")", "{", "case", "AWT_ASCENT", ":", "case", "ASCENT", ":", "return", "Ascender", "*", "fontSize", "/", "1000", ";", "case", "CAPHEIGHT", ...
Gets the font parameter identified by <CODE>key</CODE>. Valid values for <CODE>key</CODE> are <CODE>ASCENT</CODE>, <CODE>CAPHEIGHT</CODE>, <CODE>DESCENT</CODE>, <CODE>ITALICANGLE</CODE>, <CODE>BBOXLLX</CODE>, <CODE>BBOXLLY</CODE>, <CODE>BBOXURX</CODE> and <CODE>BBOXURY</CODE>. @param key the parameter to be extracted @param fontSize the font size in points @return the parameter in points
[ "Gets", "the", "font", "parameter", "identified", "by", "<CODE", ">", "key<", "/", "CODE", ">", ".", "Valid", "values", "for", "<CODE", ">", "key<", "/", "CODE", ">", "are", "<CODE", ">", "ASCENT<", "/", "CODE", ">", "<CODE", ">", "CAPHEIGHT<", "/", ...
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/Type1Font.java#L689-L719
wisdom-framework/wisdom
framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/CachedActionInterceptor.java
CachedActionInterceptor.call
@Override public Result call(Cached configuration, RequestContext context) throws Exception { """ Intercepts a @Cached action method. If the result of the action is cached, returned it immediately without having actually invoked the action method. In this case, the interception chain is cut. <p> If the result is not yet cached, the interception chain continues, and the result is cached to be used during the next invocation. @param configuration the interception configuration @param context the interception context @return the result. @throws Exception something bad happened """ // Can we use the Cached version ? boolean nocache = HeaderNames.NOCACHE_VALUE.equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL)); String key; if (Strings.isNullOrEmpty(configuration.key())) { key = context.request().uri(); } else { key = configuration.key(); } Result result = null; if (!nocache) { result = (Result) cache.get(key); } if (result == null) { result = context.proceed(); } else { LOGGER.info("Returning cached result for {} (key:{})", context.request().uri(), key); return result; } Duration duration; if (configuration.duration() == 0) { // Eternity == 1 year. duration = Duration.standardDays(365); } else { duration = Duration.standardSeconds(configuration.duration()); } cache.set(key, result, duration); LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})", context.request().uri(), configuration.duration(), key); return result; }
java
@Override public Result call(Cached configuration, RequestContext context) throws Exception { // Can we use the Cached version ? boolean nocache = HeaderNames.NOCACHE_VALUE.equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL)); String key; if (Strings.isNullOrEmpty(configuration.key())) { key = context.request().uri(); } else { key = configuration.key(); } Result result = null; if (!nocache) { result = (Result) cache.get(key); } if (result == null) { result = context.proceed(); } else { LOGGER.info("Returning cached result for {} (key:{})", context.request().uri(), key); return result; } Duration duration; if (configuration.duration() == 0) { // Eternity == 1 year. duration = Duration.standardDays(365); } else { duration = Duration.standardSeconds(configuration.duration()); } cache.set(key, result, duration); LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})", context.request().uri(), configuration.duration(), key); return result; }
[ "@", "Override", "public", "Result", "call", "(", "Cached", "configuration", ",", "RequestContext", "context", ")", "throws", "Exception", "{", "// Can we use the Cached version ?", "boolean", "nocache", "=", "HeaderNames", ".", "NOCACHE_VALUE", ".", "equalsIgnoreCase",...
Intercepts a @Cached action method. If the result of the action is cached, returned it immediately without having actually invoked the action method. In this case, the interception chain is cut. <p> If the result is not yet cached, the interception chain continues, and the result is cached to be used during the next invocation. @param configuration the interception configuration @param context the interception context @return the result. @throws Exception something bad happened
[ "Intercepts", "a", "@Cached", "action", "method", ".", "If", "the", "result", "of", "the", "action", "is", "cached", "returned", "it", "immediately", "without", "having", "actually", "invoked", "the", "action", "method", ".", "In", "this", "case", "the", "in...
train
https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/ehcache-cache-service/src/main/java/org/wisdom/cache/ehcache/CachedActionInterceptor.java#L64-L104
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java
DateFormat.getInstanceForSkeleton
public final static DateFormat getInstanceForSkeleton( Calendar cal, String skeleton, ULocale locale) { """ <strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and times in the calendar system specified by <code>cal</code>. @param cal The calendar system for which a date/time format is desired. @param skeleton The skeleton that selects the fields to be formatted. (Uses the {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY}, etc. @param locale The locale for which the date/time format is desired. """ DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale); final String bestPattern = generator.getBestPattern(skeleton); SimpleDateFormat format = new SimpleDateFormat(bestPattern, locale); format.setCalendar(cal); return format; }
java
public final static DateFormat getInstanceForSkeleton( Calendar cal, String skeleton, ULocale locale) { DateTimePatternGenerator generator = DateTimePatternGenerator.getInstance(locale); final String bestPattern = generator.getBestPattern(skeleton); SimpleDateFormat format = new SimpleDateFormat(bestPattern, locale); format.setCalendar(cal); return format; }
[ "public", "final", "static", "DateFormat", "getInstanceForSkeleton", "(", "Calendar", "cal", ",", "String", "skeleton", ",", "ULocale", "locale", ")", "{", "DateTimePatternGenerator", "generator", "=", "DateTimePatternGenerator", ".", "getInstance", "(", "locale", ")"...
<strong>[icu]</strong> Creates a {@link DateFormat} object that can be used to format dates and times in the calendar system specified by <code>cal</code>. @param cal The calendar system for which a date/time format is desired. @param skeleton The skeleton that selects the fields to be formatted. (Uses the {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY}, etc. @param locale The locale for which the date/time format is desired.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Creates", "a", "{", "@link", "DateFormat", "}", "object", "that", "can", "be", "used", "to", "format", "dates", "and", "times", "in", "the", "calendar", "system", "specified", "by", "<code", ">...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L2013-L2020
joniles/mpxj
src/main/java/net/sf/mpxj/Task.java
Task.setCost
public void setCost(int index, Number value) { """ Set a cost value. @param index cost index (1-10) @param value cost value """ set(selectField(TaskFieldLists.CUSTOM_COST, index), value); }
java
public void setCost(int index, Number value) { set(selectField(TaskFieldLists.CUSTOM_COST, index), value); }
[ "public", "void", "setCost", "(", "int", "index", ",", "Number", "value", ")", "{", "set", "(", "selectField", "(", "TaskFieldLists", ".", "CUSTOM_COST", ",", "index", ")", ",", "value", ")", ";", "}" ]
Set a cost value. @param index cost index (1-10) @param value cost value
[ "Set", "a", "cost", "value", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/Task.java#L822-L825
spotbugs/spotbugs
spotbugs/src/main/java/edu/umd/cs/findbugs/MethodAnnotation.java
MethodAnnotation.fromForeignMethod
public static MethodAnnotation fromForeignMethod(@SlashedClassName String className, String methodName, String methodSig, int accessFlags) { """ Factory method to create the MethodAnnotation from the classname, method name, signature, etc. The method tries to look up source line information for the method. @param className name of the class containing the method @param methodName name of the method @param methodSig signature of the method @param accessFlags the access flags of the method @return the MethodAnnotation """ className = ClassName.toDottedClassName(className); // Create MethodAnnotation. // It won't have source lines yet. MethodAnnotation methodAnnotation = new MethodAnnotation(className, methodName, methodSig, (accessFlags & Const.ACC_STATIC) != 0); SourceLineAnnotation sourceLines = SourceLineAnnotation.getSourceAnnotationForMethod(className, methodName, methodSig); methodAnnotation.setSourceLines(sourceLines); return methodAnnotation; }
java
public static MethodAnnotation fromForeignMethod(@SlashedClassName String className, String methodName, String methodSig, int accessFlags) { className = ClassName.toDottedClassName(className); // Create MethodAnnotation. // It won't have source lines yet. MethodAnnotation methodAnnotation = new MethodAnnotation(className, methodName, methodSig, (accessFlags & Const.ACC_STATIC) != 0); SourceLineAnnotation sourceLines = SourceLineAnnotation.getSourceAnnotationForMethod(className, methodName, methodSig); methodAnnotation.setSourceLines(sourceLines); return methodAnnotation; }
[ "public", "static", "MethodAnnotation", "fromForeignMethod", "(", "@", "SlashedClassName", "String", "className", ",", "String", "methodName", ",", "String", "methodSig", ",", "int", "accessFlags", ")", "{", "className", "=", "ClassName", ".", "toDottedClassName", "...
Factory method to create the MethodAnnotation from the classname, method name, signature, etc. The method tries to look up source line information for the method. @param className name of the class containing the method @param methodName name of the method @param methodSig signature of the method @param accessFlags the access flags of the method @return the MethodAnnotation
[ "Factory", "method", "to", "create", "the", "MethodAnnotation", "from", "the", "classname", "method", "name", "signature", "etc", ".", "The", "method", "tries", "to", "look", "up", "source", "line", "information", "for", "the", "method", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/spotbugs/src/main/java/edu/umd/cs/findbugs/MethodAnnotation.java#L181-L195
kkopacz/agiso-tempel
templates/abstract-velocityFileExtendEngine/src/main/java/org/agiso/tempel/engine/VelocityFileExtendEngine.java
VelocityFileExtendEngine.processVelocityResource
protected void processVelocityResource(ITemplateSource source, VelocityContext context, String target) throws Exception { """ Szablon musi być pojedynczym plikiem. Jego przetwarzanie polega na jednorazowym wywołaniu metody {@link #processVelocityFile(ITemplateSourceEntry, VelocityContext, String)} w celu utworzenia pojedynczego zasobu. """ if(!source.isFile()) { throw new RuntimeException("Zasób " + source.getTemplate() + "/"+ source.getResource() + " nie jest plikiem" ); } processVelocityFile(source.getEntry(source.getResource()), context, target); }
java
protected void processVelocityResource(ITemplateSource source, VelocityContext context, String target) throws Exception { if(!source.isFile()) { throw new RuntimeException("Zasób " + source.getTemplate() + "/"+ source.getResource() + " nie jest plikiem" ); } processVelocityFile(source.getEntry(source.getResource()), context, target); }
[ "protected", "void", "processVelocityResource", "(", "ITemplateSource", "source", ",", "VelocityContext", "context", ",", "String", "target", ")", "throws", "Exception", "{", "if", "(", "!", "source", ".", "isFile", "(", ")", ")", "{", "throw", "new", "Runtime...
Szablon musi być pojedynczym plikiem. Jego przetwarzanie polega na jednorazowym wywołaniu metody {@link #processVelocityFile(ITemplateSourceEntry, VelocityContext, String)} w celu utworzenia pojedynczego zasobu.
[ "Szablon", "musi", "być", "pojedynczym", "plikiem", ".", "Jego", "przetwarzanie", "polega", "na", "jednorazowym", "wywołaniu", "metody", "{" ]
train
https://github.com/kkopacz/agiso-tempel/blob/ff7a96153153b6bc07212d776816b87d9538f6fa/templates/abstract-velocityFileExtendEngine/src/main/java/org/agiso/tempel/engine/VelocityFileExtendEngine.java#L69-L77
line/centraldogma
server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java
MetadataService.ensureProjectToken
private static void ensureProjectToken(ProjectMetadata project, String appId) { """ Ensures that the specified {@code appId} is a token of the specified {@code project}. """ requireNonNull(project, "project"); requireNonNull(appId, "appId"); checkArgument(project.tokens().containsKey(appId), appId + " is not a token of the project " + project.name()); }
java
private static void ensureProjectToken(ProjectMetadata project, String appId) { requireNonNull(project, "project"); requireNonNull(appId, "appId"); checkArgument(project.tokens().containsKey(appId), appId + " is not a token of the project " + project.name()); }
[ "private", "static", "void", "ensureProjectToken", "(", "ProjectMetadata", "project", ",", "String", "appId", ")", "{", "requireNonNull", "(", "project", ",", "\"project\"", ")", ";", "requireNonNull", "(", "appId", ",", "\"appId\"", ")", ";", "checkArgument", "...
Ensures that the specified {@code appId} is a token of the specified {@code project}.
[ "Ensures", "that", "the", "specified", "{" ]
train
https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L871-L877
RogerParkinson/madura-objects-parent
madura-rules/src/main/java/nz/co/senanque/rules/OperationsImpl.java
OperationsImpl.match
@InternalFunction() public Boolean match(final List<ProxyField> list,final List<ProxyField> list2) { """ Everything in the first list must be in the second list too But not necessarily the reverse. @param list @param list2 @return true if first list is in the second """ if (list == null) { return Boolean.TRUE; } for (ProxyField proxyField: list) { boolean found = false; for (ProxyField proxyField2: list2) { if (proxyField.getValue().equals(proxyField2.getValue())) { found = true; break; } } if (!found) { return Boolean.FALSE; } } return Boolean.TRUE; }
java
@InternalFunction() public Boolean match(final List<ProxyField> list,final List<ProxyField> list2) { if (list == null) { return Boolean.TRUE; } for (ProxyField proxyField: list) { boolean found = false; for (ProxyField proxyField2: list2) { if (proxyField.getValue().equals(proxyField2.getValue())) { found = true; break; } } if (!found) { return Boolean.FALSE; } } return Boolean.TRUE; }
[ "@", "InternalFunction", "(", ")", "public", "Boolean", "match", "(", "final", "List", "<", "ProxyField", ">", "list", ",", "final", "List", "<", "ProxyField", ">", "list2", ")", "{", "if", "(", "list", "==", "null", ")", "{", "return", "Boolean", ".",...
Everything in the first list must be in the second list too But not necessarily the reverse. @param list @param list2 @return true if first list is in the second
[ "Everything", "in", "the", "first", "list", "must", "be", "in", "the", "second", "list", "too", "But", "not", "necessarily", "the", "reverse", "." ]
train
https://github.com/RogerParkinson/madura-objects-parent/blob/9b5385dd0437611f0ce8506f63646e018d06fb8e/madura-rules/src/main/java/nz/co/senanque/rules/OperationsImpl.java#L300-L324
dropbox/dropbox-sdk-java
examples/longpoll/src/main/java/com/dropbox/core/examples/longpoll/Main.java
Main.createClient
private static DbxClientV2 createClient(DbxAuthInfo auth, StandardHttpRequestor.Config config) { """ Create a new Dropbox client using the given authentication information and HTTP client config. @param auth Authentication information @param config HTTP request configuration @return new Dropbox V2 client """ String clientUserAgentId = "examples-longpoll"; StandardHttpRequestor requestor = new StandardHttpRequestor(config); DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder(clientUserAgentId) .withHttpRequestor(requestor) .build(); return new DbxClientV2(requestConfig, auth.getAccessToken(), auth.getHost()); }
java
private static DbxClientV2 createClient(DbxAuthInfo auth, StandardHttpRequestor.Config config) { String clientUserAgentId = "examples-longpoll"; StandardHttpRequestor requestor = new StandardHttpRequestor(config); DbxRequestConfig requestConfig = DbxRequestConfig.newBuilder(clientUserAgentId) .withHttpRequestor(requestor) .build(); return new DbxClientV2(requestConfig, auth.getAccessToken(), auth.getHost()); }
[ "private", "static", "DbxClientV2", "createClient", "(", "DbxAuthInfo", "auth", ",", "StandardHttpRequestor", ".", "Config", "config", ")", "{", "String", "clientUserAgentId", "=", "\"examples-longpoll\"", ";", "StandardHttpRequestor", "requestor", "=", "new", "Standard...
Create a new Dropbox client using the given authentication information and HTTP client config. @param auth Authentication information @param config HTTP request configuration @return new Dropbox V2 client
[ "Create", "a", "new", "Dropbox", "client", "using", "the", "given", "authentication", "information", "and", "HTTP", "client", "config", "." ]
train
https://github.com/dropbox/dropbox-sdk-java/blob/d86157005fad6233c18b4b0f10f00b8d9d56ae92/examples/longpoll/src/main/java/com/dropbox/core/examples/longpoll/Main.java#L110-L118
bremersee/sms
src/main/java/org/bremersee/sms/GoyyaSmsService.java
GoyyaSmsService.createSendTime
protected String createSendTime(final Date sendTime) { """ Creates the send time URL parameter value. @param sendTime the send time as {@link Date} @return the send time URL parameter value """ if (sendTime == null || new Date(System.currentTimeMillis() + 1000L * 60L).after(sendTime)) { return null; } String customSendTimePattern = StringUtils.isBlank(this.sendTimePattern) ? DEFAULT_SEND_TIME_PATTERN : this.sendTimePattern; SimpleDateFormat sdf = new SimpleDateFormat(customSendTimePattern, Locale.GERMANY); sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); return sdf.format(sendTime); }
java
protected String createSendTime(final Date sendTime) { if (sendTime == null || new Date(System.currentTimeMillis() + 1000L * 60L).after(sendTime)) { return null; } String customSendTimePattern = StringUtils.isBlank(this.sendTimePattern) ? DEFAULT_SEND_TIME_PATTERN : this.sendTimePattern; SimpleDateFormat sdf = new SimpleDateFormat(customSendTimePattern, Locale.GERMANY); sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin")); return sdf.format(sendTime); }
[ "protected", "String", "createSendTime", "(", "final", "Date", "sendTime", ")", "{", "if", "(", "sendTime", "==", "null", "||", "new", "Date", "(", "System", ".", "currentTimeMillis", "(", ")", "+", "1000L", "*", "60L", ")", ".", "after", "(", "sendTime"...
Creates the send time URL parameter value. @param sendTime the send time as {@link Date} @return the send time URL parameter value
[ "Creates", "the", "send", "time", "URL", "parameter", "value", "." ]
train
https://github.com/bremersee/sms/blob/4e5e87ea98616dd316573b544f54cac56750d2f9/src/main/java/org/bremersee/sms/GoyyaSmsService.java#L392-L402
camunda/camunda-commons
typed-values/src/main/java/org/camunda/bpm/engine/variable/Variables.java
Variables.fromMap
public static VariableMap fromMap(Map<String, Object> map) { """ If the given map is not a variable map, adds all its entries as untyped values to a new {@link VariableMap}. If the given map is a {@link VariableMap}, it is returned as is. """ if(map instanceof VariableMap) { return (VariableMap) map; } else { return new VariableMapImpl(map); } }
java
public static VariableMap fromMap(Map<String, Object> map) { if(map instanceof VariableMap) { return (VariableMap) map; } else { return new VariableMapImpl(map); } }
[ "public", "static", "VariableMap", "fromMap", "(", "Map", "<", "String", ",", "Object", ">", "map", ")", "{", "if", "(", "map", "instanceof", "VariableMap", ")", "{", "return", "(", "VariableMap", ")", "map", ";", "}", "else", "{", "return", "new", "Va...
If the given map is not a variable map, adds all its entries as untyped values to a new {@link VariableMap}. If the given map is a {@link VariableMap}, it is returned as is.
[ "If", "the", "given", "map", "is", "not", "a", "variable", "map", "adds", "all", "its", "entries", "as", "untyped", "values", "to", "a", "new", "{" ]
train
https://github.com/camunda/camunda-commons/blob/bd3195db47c92c25717288fe9e6735f8e882f247/typed-values/src/main/java/org/camunda/bpm/engine/variable/Variables.java#L148-L155
iig-uni-freiburg/SEWOL
src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContextProperties.java
ConstraintContextProperties.getConstraintNameIndexes
private Set<Integer> getConstraintNameIndexes() throws PropertyException { """ Returns all used indexes for constraint property names.<br> Constraint names are enumerated (CONSTRAINT_1, CONSTRAINT_2, ...).<br> When new constraints are added, the lowest unused index is used within the new property name. @return The set of indexes in use. @throws PropertyException if existing constraint names are invalid (e.g. due to external file manipulation). """ Set<Integer> result = new HashSet<>(); Set<String> constraintNames = getConstraintNameList(); if(constraintNames.isEmpty()) return result; for(String constraintName: constraintNames){ int separatorIndex = constraintName.lastIndexOf("_"); if(separatorIndex == -1 || (constraintName.length() == separatorIndex + 1)) throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)"); Integer index = null; try { index = Integer.parseInt(constraintName.substring(separatorIndex+1)); } catch(Exception e){ throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)"); } result.add(index); } return result; }
java
private Set<Integer> getConstraintNameIndexes() throws PropertyException{ Set<Integer> result = new HashSet<>(); Set<String> constraintNames = getConstraintNameList(); if(constraintNames.isEmpty()) return result; for(String constraintName: constraintNames){ int separatorIndex = constraintName.lastIndexOf("_"); if(separatorIndex == -1 || (constraintName.length() == separatorIndex + 1)) throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)"); Integer index = null; try { index = Integer.parseInt(constraintName.substring(separatorIndex+1)); } catch(Exception e){ throw new PropertyException(ConstraintContextProperty.CONSTRAINT, constraintName, "Corrupted property file (invalid constraint name)"); } result.add(index); } return result; }
[ "private", "Set", "<", "Integer", ">", "getConstraintNameIndexes", "(", ")", "throws", "PropertyException", "{", "Set", "<", "Integer", ">", "result", "=", "new", "HashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "constraintNames", "=", "getConstrai...
Returns all used indexes for constraint property names.<br> Constraint names are enumerated (CONSTRAINT_1, CONSTRAINT_2, ...).<br> When new constraints are added, the lowest unused index is used within the new property name. @return The set of indexes in use. @throws PropertyException if existing constraint names are invalid (e.g. due to external file manipulation).
[ "Returns", "all", "used", "indexes", "for", "constraint", "property", "names", ".", "<br", ">", "Constraint", "names", "are", "enumerated", "(", "CONSTRAINT_1", "CONSTRAINT_2", "...", ")", ".", "<br", ">", "When", "new", "constraints", "are", "added", "the", ...
train
https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/src/de/uni/freiburg/iig/telematik/sewol/context/constraint/ConstraintContextProperties.java#L153-L171
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/types/RadialGradient.java
RadialGradient.addColorStop
public final RadialGradient addColorStop(final double stop, final IColor color) { """ Add color stop @param stop @param color {@link ColorName} or {@link Color} @return {@link RadialGradient} """ m_jso.addColorStop(stop, color.getColorString()); return this; }
java
public final RadialGradient addColorStop(final double stop, final IColor color) { m_jso.addColorStop(stop, color.getColorString()); return this; }
[ "public", "final", "RadialGradient", "addColorStop", "(", "final", "double", "stop", ",", "final", "IColor", "color", ")", "{", "m_jso", ".", "addColorStop", "(", "stop", ",", "color", ".", "getColorString", "(", ")", ")", ";", "return", "this", ";", "}" ]
Add color stop @param stop @param color {@link ColorName} or {@link Color} @return {@link RadialGradient}
[ "Add", "color", "stop" ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/types/RadialGradient.java#L69-L74
alkacon/opencms-core
src/org/opencms/i18n/CmsEncoder.java
CmsEncoder.escapeSqlLikePattern
public static String escapeSqlLikePattern(String pattern, char escapeChar) { """ Escapes the wildcard characters in a string which will be used as the pattern for a SQL LIKE clause.<p> @param pattern the pattern @param escapeChar the character which should be used as the escape character @return the escaped pattern """ char[] special = new char[] {escapeChar, '%', '_'}; String result = pattern; for (char charToEscape : special) { result = result.replaceAll("" + charToEscape, "" + escapeChar + charToEscape); } return result; }
java
public static String escapeSqlLikePattern(String pattern, char escapeChar) { char[] special = new char[] {escapeChar, '%', '_'}; String result = pattern; for (char charToEscape : special) { result = result.replaceAll("" + charToEscape, "" + escapeChar + charToEscape); } return result; }
[ "public", "static", "String", "escapeSqlLikePattern", "(", "String", "pattern", ",", "char", "escapeChar", ")", "{", "char", "[", "]", "special", "=", "new", "char", "[", "]", "{", "escapeChar", ",", "'", "'", ",", "'", "'", "}", ";", "String", "result...
Escapes the wildcard characters in a string which will be used as the pattern for a SQL LIKE clause.<p> @param pattern the pattern @param escapeChar the character which should be used as the escape character @return the escaped pattern
[ "Escapes", "the", "wildcard", "characters", "in", "a", "string", "which", "will", "be", "used", "as", "the", "pattern", "for", "a", "SQL", "LIKE", "clause", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/i18n/CmsEncoder.java#L678-L686
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java
CmsContainerpageController.getElementForDragAndDropFromContainer
public void getElementForDragAndDropFromContainer( final String clientId, final String containerId, boolean alwaysCopy, final I_CmsSimpleCallback<CmsContainerElementData> callback) { """ Requests the data for a container element specified by the client id for drag and drop from a container. The data will be provided to the given call-back function.<p> @param clientId the element id @param containerId the id of the container from which the element is being dragged @param alwaysCopy <code>true</code> in case reading data for a clipboard element used as a copy group @param callback the call-back to execute with the requested data """ SingleElementAction action = new SingleElementAction(clientId, alwaysCopy, callback); action.setDndContainer(containerId); action.execute(); }
java
public void getElementForDragAndDropFromContainer( final String clientId, final String containerId, boolean alwaysCopy, final I_CmsSimpleCallback<CmsContainerElementData> callback) { SingleElementAction action = new SingleElementAction(clientId, alwaysCopy, callback); action.setDndContainer(containerId); action.execute(); }
[ "public", "void", "getElementForDragAndDropFromContainer", "(", "final", "String", "clientId", ",", "final", "String", "containerId", ",", "boolean", "alwaysCopy", ",", "final", "I_CmsSimpleCallback", "<", "CmsContainerElementData", ">", "callback", ")", "{", "SingleEle...
Requests the data for a container element specified by the client id for drag and drop from a container. The data will be provided to the given call-back function.<p> @param clientId the element id @param containerId the id of the container from which the element is being dragged @param alwaysCopy <code>true</code> in case reading data for a clipboard element used as a copy group @param callback the call-back to execute with the requested data
[ "Requests", "the", "data", "for", "a", "container", "element", "specified", "by", "the", "client", "id", "for", "drag", "and", "drop", "from", "a", "container", ".", "The", "data", "will", "be", "provided", "to", "the", "given", "call", "-", "back", "fun...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageController.java#L1506-L1515
pip-services3-java/pip-services3-commons-java
src/org/pipservices3/commons/reflect/MethodReflector.java
MethodReflector.hasMethod
public static boolean hasMethod(Object obj, String name) { """ Checks if object has a method with specified name.. @param obj an object to introspect. @param name a name of the method to check. @return true if the object has the method and false if it doesn't. """ if (obj == null) throw new NullPointerException("Object cannot be null"); if (name == null) throw new NullPointerException("Method name cannot be null"); Class<?> objClass = obj.getClass(); for (Method method : objClass.getMethods()) { if (matchMethod(method, name)) return true; } return false; }
java
public static boolean hasMethod(Object obj, String name) { if (obj == null) throw new NullPointerException("Object cannot be null"); if (name == null) throw new NullPointerException("Method name cannot be null"); Class<?> objClass = obj.getClass(); for (Method method : objClass.getMethods()) { if (matchMethod(method, name)) return true; } return false; }
[ "public", "static", "boolean", "hasMethod", "(", "Object", "obj", ",", "String", "name", ")", "{", "if", "(", "obj", "==", "null", ")", "throw", "new", "NullPointerException", "(", "\"Object cannot be null\"", ")", ";", "if", "(", "name", "==", "null", ")"...
Checks if object has a method with specified name.. @param obj an object to introspect. @param name a name of the method to check. @return true if the object has the method and false if it doesn't.
[ "Checks", "if", "object", "has", "a", "method", "with", "specified", "name", ".." ]
train
https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/MethodReflector.java#L41-L55
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/container/impl/metadata/BpmPlatformXmlParse.java
BpmPlatformXmlParse.parseRootElement
protected void parseRootElement() { """ We know this is a <code>&lt;bpm-platform ../&gt;</code> element """ JobExecutorXmlImpl jobExecutor = new JobExecutorXmlImpl(); List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>(); for (Element element : rootElement.elements()) { if(JOB_EXECUTOR.equals(element.getTagName())) { parseJobExecutor(element, jobExecutor); } else if(PROCESS_ENGINE.equals(element.getTagName())) { parseProcessEngine(element, processEngines); } } bpmPlatformXml = new BpmPlatformXmlImpl(jobExecutor, processEngines); }
java
protected void parseRootElement() { JobExecutorXmlImpl jobExecutor = new JobExecutorXmlImpl(); List<ProcessEngineXml> processEngines = new ArrayList<ProcessEngineXml>(); for (Element element : rootElement.elements()) { if(JOB_EXECUTOR.equals(element.getTagName())) { parseJobExecutor(element, jobExecutor); } else if(PROCESS_ENGINE.equals(element.getTagName())) { parseProcessEngine(element, processEngines); } } bpmPlatformXml = new BpmPlatformXmlImpl(jobExecutor, processEngines); }
[ "protected", "void", "parseRootElement", "(", ")", "{", "JobExecutorXmlImpl", "jobExecutor", "=", "new", "JobExecutorXmlImpl", "(", ")", ";", "List", "<", "ProcessEngineXml", ">", "processEngines", "=", "new", "ArrayList", "<", "ProcessEngineXml", ">", "(", ")", ...
We know this is a <code>&lt;bpm-platform ../&gt;</code> element
[ "We", "know", "this", "is", "a", "<code", ">", "&lt", ";", "bpm", "-", "platform", "..", "/", "&gt", ";", "<", "/", "code", ">", "element" ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/container/impl/metadata/BpmPlatformXmlParse.java#L59-L77
symphonyoss/messageml-utils
src/main/java/org/symphonyoss/symphony/entityjson/EntityJsonParser.java
EntityJsonParser.parseStructuredObject
public StructuredObject parseStructuredObject(Object instanceSource, Reader instanceReader) throws SchemaValidationException, InvalidInstanceException { """ Parse a single StructuredObject instance from the given URL. Callers may prefer to catch EntityJSONException and treat all failures in the same way. @param instanceSource An object describing the source of the instance, typically an instance of java.net.URL or java.io.File. @param instanceReader A Reader containing the JSON representation of a single StructuredObject instance. @return A StructuredObject instance. @throws SchemaValidationException If the given instance does not meet the general EntityJSON schema. @throws InvalidInstanceException If the given instance is structurally invalid. """ try { return new StructuredObject(validate(STRUCTURED_OBJECT_SCHEMA_URL, instanceSource, instanceReader)); } catch (NoSchemaException | InvalidSchemaException e) { // In theory this cannot happen throw new RuntimeException(e); } }
java
public StructuredObject parseStructuredObject(Object instanceSource, Reader instanceReader) throws SchemaValidationException, InvalidInstanceException { try { return new StructuredObject(validate(STRUCTURED_OBJECT_SCHEMA_URL, instanceSource, instanceReader)); } catch (NoSchemaException | InvalidSchemaException e) { // In theory this cannot happen throw new RuntimeException(e); } }
[ "public", "StructuredObject", "parseStructuredObject", "(", "Object", "instanceSource", ",", "Reader", "instanceReader", ")", "throws", "SchemaValidationException", ",", "InvalidInstanceException", "{", "try", "{", "return", "new", "StructuredObject", "(", "validate", "("...
Parse a single StructuredObject instance from the given URL. Callers may prefer to catch EntityJSONException and treat all failures in the same way. @param instanceSource An object describing the source of the instance, typically an instance of java.net.URL or java.io.File. @param instanceReader A Reader containing the JSON representation of a single StructuredObject instance. @return A StructuredObject instance. @throws SchemaValidationException If the given instance does not meet the general EntityJSON schema. @throws InvalidInstanceException If the given instance is structurally invalid.
[ "Parse", "a", "single", "StructuredObject", "instance", "from", "the", "given", "URL", "." ]
train
https://github.com/symphonyoss/messageml-utils/blob/68daed66267062d144a05b3ee9a9bf4b715e3f95/src/main/java/org/symphonyoss/symphony/entityjson/EntityJsonParser.java#L214-L225
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/SmartsheetFactory.java
SmartsheetFactory.createDefaultClient
public static Smartsheet createDefaultClient(String accessToken) { """ <p>Creates a Smartsheet client with default parameters.</p> @param accessToken @return the Smartsheet client """ SmartsheetImpl smartsheet = new SmartsheetImpl(DEFAULT_BASE_URI, accessToken); return smartsheet; }
java
public static Smartsheet createDefaultClient(String accessToken) { SmartsheetImpl smartsheet = new SmartsheetImpl(DEFAULT_BASE_URI, accessToken); return smartsheet; }
[ "public", "static", "Smartsheet", "createDefaultClient", "(", "String", "accessToken", ")", "{", "SmartsheetImpl", "smartsheet", "=", "new", "SmartsheetImpl", "(", "DEFAULT_BASE_URI", ",", "accessToken", ")", ";", "return", "smartsheet", ";", "}" ]
<p>Creates a Smartsheet client with default parameters.</p> @param accessToken @return the Smartsheet client
[ "<p", ">", "Creates", "a", "Smartsheet", "client", "with", "default", "parameters", ".", "<", "/", "p", ">" ]
train
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/SmartsheetFactory.java#L60-L63
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.ensureSubResourcesOfMovedFoldersPublished
protected void ensureSubResourcesOfMovedFoldersPublished(CmsObject cms, CmsDbContext dbc, CmsPublishList pubList) throws CmsException { """ Tries to add sub-resources of moved folders to the publish list and throws an exception if the publish list still does not contain some sub-resources of the moved folders.<p> @param cms the current CMS context @param dbc the current database context @param pubList the publish list @throws CmsException if something goes wrong """ List<CmsResource> topMovedFolders = pubList.getTopMovedFolders(cms); Iterator<CmsResource> folderIt = topMovedFolders.iterator(); while (folderIt.hasNext()) { CmsResource folder = folderIt.next(); addSubResources(dbc, pubList, folder); } List<CmsResource> missingSubResources = pubList.getMissingSubResources(cms, topMovedFolders); if (missingSubResources.isEmpty()) { return; } StringBuffer pathBuffer = new StringBuffer(); for (CmsResource missing : missingSubResources) { pathBuffer.append(missing.getRootPath()); pathBuffer.append(" "); } throw new CmsVfsException( Messages.get().container(Messages.RPT_CHILDREN_OF_MOVED_FOLDER_NOT_PUBLISHED_1, pathBuffer.toString())); }
java
protected void ensureSubResourcesOfMovedFoldersPublished(CmsObject cms, CmsDbContext dbc, CmsPublishList pubList) throws CmsException { List<CmsResource> topMovedFolders = pubList.getTopMovedFolders(cms); Iterator<CmsResource> folderIt = topMovedFolders.iterator(); while (folderIt.hasNext()) { CmsResource folder = folderIt.next(); addSubResources(dbc, pubList, folder); } List<CmsResource> missingSubResources = pubList.getMissingSubResources(cms, topMovedFolders); if (missingSubResources.isEmpty()) { return; } StringBuffer pathBuffer = new StringBuffer(); for (CmsResource missing : missingSubResources) { pathBuffer.append(missing.getRootPath()); pathBuffer.append(" "); } throw new CmsVfsException( Messages.get().container(Messages.RPT_CHILDREN_OF_MOVED_FOLDER_NOT_PUBLISHED_1, pathBuffer.toString())); }
[ "protected", "void", "ensureSubResourcesOfMovedFoldersPublished", "(", "CmsObject", "cms", ",", "CmsDbContext", "dbc", ",", "CmsPublishList", "pubList", ")", "throws", "CmsException", "{", "List", "<", "CmsResource", ">", "topMovedFolders", "=", "pubList", ".", "getTo...
Tries to add sub-resources of moved folders to the publish list and throws an exception if the publish list still does not contain some sub-resources of the moved folders.<p> @param cms the current CMS context @param dbc the current database context @param pubList the publish list @throws CmsException if something goes wrong
[ "Tries", "to", "add", "sub", "-", "resources", "of", "moved", "folders", "to", "the", "publish", "list", "and", "throws", "an", "exception", "if", "the", "publish", "list", "still", "does", "not", "contain", "some", "sub", "-", "resources", "of", "the", ...
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L10385-L10408
JodaOrg/joda-beans
src/main/java/org/joda/beans/ser/SerIteratorFactory.java
SerIteratorFactory.sortedSet
public static final SerIterable sortedSet(final Class<?> valueType, final List<Class<?>> valueTypeTypes) { """ Gets an iterable wrapper for {@code SortedSet}. @param valueType the value type, not null @param valueTypeTypes the generic parameters of the value type @return the iterable, not null """ final SortedSet<Object> coll = new TreeSet<>(); return set(valueType, valueTypeTypes, coll); }
java
public static final SerIterable sortedSet(final Class<?> valueType, final List<Class<?>> valueTypeTypes) { final SortedSet<Object> coll = new TreeSet<>(); return set(valueType, valueTypeTypes, coll); }
[ "public", "static", "final", "SerIterable", "sortedSet", "(", "final", "Class", "<", "?", ">", "valueType", ",", "final", "List", "<", "Class", "<", "?", ">", ">", "valueTypeTypes", ")", "{", "final", "SortedSet", "<", "Object", ">", "coll", "=", "new", ...
Gets an iterable wrapper for {@code SortedSet}. @param valueType the value type, not null @param valueTypeTypes the generic parameters of the value type @return the iterable, not null
[ "Gets", "an", "iterable", "wrapper", "for", "{", "@code", "SortedSet", "}", "." ]
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/SerIteratorFactory.java#L416-L419
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.validateFalse
public void validateFalse(boolean value, String name) { """ Validates a given value to be false @param value The value to check @param name The name of the field to display the error message """ validateFalse(value, name, messages.get(Validation.FALSE_KEY.name(), name)); }
java
public void validateFalse(boolean value, String name) { validateFalse(value, name, messages.get(Validation.FALSE_KEY.name(), name)); }
[ "public", "void", "validateFalse", "(", "boolean", "value", ",", "String", "name", ")", "{", "validateFalse", "(", "value", ",", "name", ",", "messages", ".", "get", "(", "Validation", ".", "FALSE_KEY", ".", "name", "(", ")", ",", "name", ")", ")", ";"...
Validates a given value to be false @param value The value to check @param name The name of the field to display the error message
[ "Validates", "a", "given", "value", "to", "be", "false" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L465-L467
haraldk/TwelveMonkeys
servlet/src/main/java/com/twelvemonkeys/servlet/ServletUtil.java
ServletUtil.getIntParameter
public static int getIntParameter(final ServletRequest pReq, final String pName, final int pDefault) { """ Gets the value of the given parameter from the request converted to an {@code int}.&nbsp;If the parameter is not set or not parseable, the default value is returned. @param pReq the servlet request @param pName the parameter name @param pDefault the default value @return the value of the parameter converted to an {@code int}, or the default value, if the parameter is not set. """ String str = pReq.getParameter(pName); try { return str != null ? Integer.parseInt(str) : pDefault; } catch (NumberFormatException nfe) { return pDefault; } }
java
public static int getIntParameter(final ServletRequest pReq, final String pName, final int pDefault) { String str = pReq.getParameter(pName); try { return str != null ? Integer.parseInt(str) : pDefault; } catch (NumberFormatException nfe) { return pDefault; } }
[ "public", "static", "int", "getIntParameter", "(", "final", "ServletRequest", "pReq", ",", "final", "String", "pName", ",", "final", "int", "pDefault", ")", "{", "String", "str", "=", "pReq", ".", "getParameter", "(", "pName", ")", ";", "try", "{", "return...
Gets the value of the given parameter from the request converted to an {@code int}.&nbsp;If the parameter is not set or not parseable, the default value is returned. @param pReq the servlet request @param pName the parameter name @param pDefault the default value @return the value of the parameter converted to an {@code int}, or the default value, if the parameter is not set.
[ "Gets", "the", "value", "of", "the", "given", "parameter", "from", "the", "request", "converted", "to", "an", "{", "@code", "int", "}", ".", "&nbsp", ";", "If", "the", "parameter", "is", "not", "set", "or", "not", "parseable", "the", "default", "value", ...
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/ServletUtil.java#L206-L215
snowflakedb/snowflake-jdbc
src/main/java/net/snowflake/client/core/SFStatement.java
SFStatement.setTimeBomb
private void setTimeBomb(ScheduledExecutorService executor) { """ Set a time bomb to cancel the outstanding query when timeout is reached. @param executor object to execute statement cancel request """ class TimeBombTask implements Callable<Void> { private final SFStatement statement; private TimeBombTask(SFStatement statement) { this.statement = statement; } @Override public Void call() throws SQLException { try { statement.cancel(); } catch (SFException ex) { throw new SnowflakeSQLException(ex, ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } return null; } } executor.schedule(new TimeBombTask(this), this.queryTimeout, TimeUnit.SECONDS); }
java
private void setTimeBomb(ScheduledExecutorService executor) { class TimeBombTask implements Callable<Void> { private final SFStatement statement; private TimeBombTask(SFStatement statement) { this.statement = statement; } @Override public Void call() throws SQLException { try { statement.cancel(); } catch (SFException ex) { throw new SnowflakeSQLException(ex, ex.getSqlState(), ex.getVendorCode(), ex.getParams()); } return null; } } executor.schedule(new TimeBombTask(this), this.queryTimeout, TimeUnit.SECONDS); }
[ "private", "void", "setTimeBomb", "(", "ScheduledExecutorService", "executor", ")", "{", "class", "TimeBombTask", "implements", "Callable", "<", "Void", ">", "{", "private", "final", "SFStatement", "statement", ";", "private", "TimeBombTask", "(", "SFStatement", "st...
Set a time bomb to cancel the outstanding query when timeout is reached. @param executor object to execute statement cancel request
[ "Set", "a", "time", "bomb", "to", "cancel", "the", "outstanding", "query", "when", "timeout", "is", "reached", "." ]
train
https://github.com/snowflakedb/snowflake-jdbc/blob/98567b5a57753f29d51446809640b969a099658f/src/main/java/net/snowflake/client/core/SFStatement.java#L316-L346
JodaOrg/joda-beans
src/main/java/org/joda/beans/ser/JodaBeanSer.java
JodaBeanSer.withConverter
public JodaBeanSer withConverter(StringConvert converter) { """ Returns a copy of this serializer with the specified string converter. <p> The default converter can be modified. @param converter the converter, not null @return a copy of this object with the converter changed, not null """ JodaBeanUtils.notNull(converter, "converter"); return new JodaBeanSer(indent, newLine, converter, iteratorFactory, shortTypes, deserializers, includeDerived); }
java
public JodaBeanSer withConverter(StringConvert converter) { JodaBeanUtils.notNull(converter, "converter"); return new JodaBeanSer(indent, newLine, converter, iteratorFactory, shortTypes, deserializers, includeDerived); }
[ "public", "JodaBeanSer", "withConverter", "(", "StringConvert", "converter", ")", "{", "JodaBeanUtils", ".", "notNull", "(", "converter", ",", "\"converter\"", ")", ";", "return", "new", "JodaBeanSer", "(", "indent", ",", "newLine", ",", "converter", ",", "itera...
Returns a copy of this serializer with the specified string converter. <p> The default converter can be modified. @param converter the converter, not null @return a copy of this object with the converter changed, not null
[ "Returns", "a", "copy", "of", "this", "serializer", "with", "the", "specified", "string", "converter", ".", "<p", ">", "The", "default", "converter", "can", "be", "modified", "." ]
train
https://github.com/JodaOrg/joda-beans/blob/f07dbe42947150b23a173f35984c6ab33c5529bf/src/main/java/org/joda/beans/ser/JodaBeanSer.java#L161-L164
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java
RSAUtils.encryptWithPublicKey
public static byte[] encryptWithPublicKey(String base64PublicKeyData, byte[] data, String cipherTransformation, int paddingSizeInBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException { """ Encrypt data with RSA public key. <p> Note: input data is divided into chunks of {@code size = key's size (in bytes) - paddingSizeInBytes}, so that long input data can be encrypted. </p> @param base64PublicKeyData RSA public key in base64 (base64 of {@link RSAPublicKey#getEncoded()}) @param data @param cipherTransformation cipher-transformation to use. If empty, {@link #DEFAULT_CIPHER_TRANSFORMATION} will be used @param paddingSizeInBytes @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException @throws InvalidKeyException @throws NoSuchPaddingException @throws IllegalBlockSizeException @throws BadPaddingException @throws IOException """ RSAPublicKey publicKey = buildPublicKey(base64PublicKeyData); return encrypt(publicKey, data, cipherTransformation, paddingSizeInBytes); }
java
public static byte[] encryptWithPublicKey(String base64PublicKeyData, byte[] data, String cipherTransformation, int paddingSizeInBytes) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException { RSAPublicKey publicKey = buildPublicKey(base64PublicKeyData); return encrypt(publicKey, data, cipherTransformation, paddingSizeInBytes); }
[ "public", "static", "byte", "[", "]", "encryptWithPublicKey", "(", "String", "base64PublicKeyData", ",", "byte", "[", "]", "data", ",", "String", "cipherTransformation", ",", "int", "paddingSizeInBytes", ")", "throws", "NoSuchAlgorithmException", ",", "InvalidKeySpecE...
Encrypt data with RSA public key. <p> Note: input data is divided into chunks of {@code size = key's size (in bytes) - paddingSizeInBytes}, so that long input data can be encrypted. </p> @param base64PublicKeyData RSA public key in base64 (base64 of {@link RSAPublicKey#getEncoded()}) @param data @param cipherTransformation cipher-transformation to use. If empty, {@link #DEFAULT_CIPHER_TRANSFORMATION} will be used @param paddingSizeInBytes @return @throws NoSuchAlgorithmException @throws InvalidKeySpecException @throws InvalidKeyException @throws NoSuchPaddingException @throws IllegalBlockSizeException @throws BadPaddingException @throws IOException
[ "Encrypt", "data", "with", "RSA", "public", "key", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/RSAUtils.java#L496-L502
bwkimmel/jdcp
jdcp-server/src/main/java/ca/eandb/jdcp/server/classmanager/FileClassManager.java
FileClassManager.releaseChildClassManager
private void releaseChildClassManager(FileChildClassManager child) { """ Releases the resources associated with a child <code>ClassManager</code>. @param child The child <code>ClassManager</code> to release. """ for (int i = 0; i < activeChildren.size(); i++) { FileChildClassManager current = activeChildren.get(i); if (current.childIndex == child.childIndex) { FileUtil.deleteRecursive(child.childDirectory); deprecationPendingList.add(child.childIndex); if (i == 0) { Collections.sort(deprecationPendingList); for (int pendingIndex : deprecationPendingList) { if (pendingIndex > current.childIndex) { break; } File pendingDirectory = new File(deprecatedDirectory, Integer.toString(pendingIndex + 1)); FileUtil.deleteRecursive(pendingDirectory); } } } } }
java
private void releaseChildClassManager(FileChildClassManager child) { for (int i = 0; i < activeChildren.size(); i++) { FileChildClassManager current = activeChildren.get(i); if (current.childIndex == child.childIndex) { FileUtil.deleteRecursive(child.childDirectory); deprecationPendingList.add(child.childIndex); if (i == 0) { Collections.sort(deprecationPendingList); for (int pendingIndex : deprecationPendingList) { if (pendingIndex > current.childIndex) { break; } File pendingDirectory = new File(deprecatedDirectory, Integer.toString(pendingIndex + 1)); FileUtil.deleteRecursive(pendingDirectory); } } } } }
[ "private", "void", "releaseChildClassManager", "(", "FileChildClassManager", "child", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "activeChildren", ".", "size", "(", ")", ";", "i", "++", ")", "{", "FileChildClassManager", "current", "=", "ac...
Releases the resources associated with a child <code>ClassManager</code>. @param child The child <code>ClassManager</code> to release.
[ "Releases", "the", "resources", "associated", "with", "a", "child", "<code", ">", "ClassManager<", "/", "code", ">", "." ]
train
https://github.com/bwkimmel/jdcp/blob/630c5150c245054e2556ff370f4bad2ec793dfb7/jdcp-server/src/main/java/ca/eandb/jdcp/server/classmanager/FileClassManager.java#L340-L358
jbossws/jbossws-common
src/main/java/org/jboss/ws/common/integration/WSHelper.java
WSHelper.getOptionalAttachment
public static <A> A getOptionalAttachment( final Deployment dep, final Class< A > key ) { """ Returns optional attachment value from webservice deployment or null if not bound. @param <A> expected value @param dep webservice deployment @param key attachment key @return optional attachment value or null """ return dep.getAttachment( key ); }
java
public static <A> A getOptionalAttachment( final Deployment dep, final Class< A > key ) { return dep.getAttachment( key ); }
[ "public", "static", "<", "A", ">", "A", "getOptionalAttachment", "(", "final", "Deployment", "dep", ",", "final", "Class", "<", "A", ">", "key", ")", "{", "return", "dep", ".", "getAttachment", "(", "key", ")", ";", "}" ]
Returns optional attachment value from webservice deployment or null if not bound. @param <A> expected value @param dep webservice deployment @param key attachment key @return optional attachment value or null
[ "Returns", "optional", "attachment", "value", "from", "webservice", "deployment", "or", "null", "if", "not", "bound", "." ]
train
https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/integration/WSHelper.java#L80-L83
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java
TitlePaneCloseButtonPainter.decodeMarkInterior
private Shape decodeMarkInterior(int width, int height) { """ Create the shape for the mark interior. @param width the width. @param height the height. @return the shape of the mark interior. """ int left = (width - 3) / 2 - 5; int top = (height - 2) / 2 - 5; path.reset(); path.moveTo(left + 1, top + 1); path.lineTo(left + 4, top + 1); path.lineTo(left + 5, top + 3); path.lineTo(left + 7, top + 1); path.lineTo(left + 10, top + 1); path.lineTo(left + 7, top + 4); path.lineTo(left + 7, top + 5); path.lineTo(left + 10, top + 9); path.lineTo(left + 6, top + 8); path.lineTo(left + 5, top + 6); path.lineTo(left + 4, top + 9); path.lineTo(left + 0, top + 9); path.lineTo(left + 4, top + 5); path.lineTo(left + 4, top + 4); path.closePath(); return path; }
java
private Shape decodeMarkInterior(int width, int height) { int left = (width - 3) / 2 - 5; int top = (height - 2) / 2 - 5; path.reset(); path.moveTo(left + 1, top + 1); path.lineTo(left + 4, top + 1); path.lineTo(left + 5, top + 3); path.lineTo(left + 7, top + 1); path.lineTo(left + 10, top + 1); path.lineTo(left + 7, top + 4); path.lineTo(left + 7, top + 5); path.lineTo(left + 10, top + 9); path.lineTo(left + 6, top + 8); path.lineTo(left + 5, top + 6); path.lineTo(left + 4, top + 9); path.lineTo(left + 0, top + 9); path.lineTo(left + 4, top + 5); path.lineTo(left + 4, top + 4); path.closePath(); return path; }
[ "private", "Shape", "decodeMarkInterior", "(", "int", "width", ",", "int", "height", ")", "{", "int", "left", "=", "(", "width", "-", "3", ")", "/", "2", "-", "5", ";", "int", "top", "=", "(", "height", "-", "2", ")", "/", "2", "-", "5", ";", ...
Create the shape for the mark interior. @param width the width. @param height the height. @return the shape of the mark interior.
[ "Create", "the", "shape", "for", "the", "mark", "interior", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java#L305-L327
JOML-CI/JOML
src/org/joml/Matrix4d.java
Matrix4d.rotateLocal
public Matrix4d rotateLocal(double ang, double x, double y, double z, Matrix4d dest) { """ Pre-multiply a rotation to this matrix by rotating the given amount of radians about the specified <code>(x, y, z)</code> axis and store the result in <code>dest</code>. <p> The axis described by the three components needs to be a unit vector. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>R * M</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the rotation will be applied last! <p> In order to set the matrix to a rotation matrix without pre-multiplying the rotation transformation, use {@link #rotation(double, double, double, double) rotation()}. <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> @see #rotation(double, double, double, double) @param ang the angle in radians @param x the x component of the axis @param y the y component of the axis @param z the z component of the axis @param dest will hold the result @return dest """ if ((properties & PROPERTY_IDENTITY) != 0) return dest.rotation(ang, x, y, z); return rotateLocalGeneric(ang, x, y, z, dest); }
java
public Matrix4d rotateLocal(double ang, double x, double y, double z, Matrix4d dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.rotation(ang, x, y, z); return rotateLocalGeneric(ang, x, y, z, dest); }
[ "public", "Matrix4d", "rotateLocal", "(", "double", "ang", ",", "double", "x", ",", "double", "y", ",", "double", "z", ",", "Matrix4d", "dest", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "!=", "0", ")", "return", "dest", "."...
Pre-multiply a rotation to this matrix by rotating the given amount of radians about the specified <code>(x, y, z)</code> axis and store the result in <code>dest</code>. <p> The axis described by the three components needs to be a unit vector. <p> When used with a right-handed coordinate system, the produced rotation will rotate a vector counter-clockwise around the rotation axis, when viewing along the negative axis direction towards the origin. When used with a left-handed coordinate system, the rotation is clockwise. <p> If <code>M</code> is <code>this</code> matrix and <code>R</code> the rotation matrix, then the new matrix will be <code>R * M</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>R * M * v</code>, the rotation will be applied last! <p> In order to set the matrix to a rotation matrix without pre-multiplying the rotation transformation, use {@link #rotation(double, double, double, double) rotation()}. <p> Reference: <a href="http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle">http://en.wikipedia.org</a> @see #rotation(double, double, double, double) @param ang the angle in radians @param x the x component of the axis @param y the y component of the axis @param z the z component of the axis @param dest will hold the result @return dest
[ "Pre", "-", "multiply", "a", "rotation", "to", "this", "matrix", "by", "rotating", "the", "given", "amount", "of", "radians", "about", "the", "specified", "<code", ">", "(", "x", "y", "z", ")", "<", "/", "code", ">", "axis", "and", "store", "the", "r...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4d.java#L5193-L5197
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.deleteInode
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { """ Deletes a single inode from the inode tree by removing it from the parent inode. @param rpcContext the rpc context @param inodePath the {@link LockedInodePath} to delete @param opTimeMs the operation time @throws FileDoesNotExistException if the Inode cannot be retrieved """ Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
java
public void deleteInode(RpcContext rpcContext, LockedInodePath inodePath, long opTimeMs) throws FileDoesNotExistException { Preconditions.checkState(inodePath.getLockPattern() == LockPattern.WRITE_EDGE); Inode inode = inodePath.getInode(); mState.applyAndJournal(rpcContext, DeleteFileEntry.newBuilder() .setId(inode.getId()) .setRecursive(false) .setOpTimeMs(opTimeMs) .build()); if (inode.isFile()) { rpcContext.getBlockDeletionContext().registerBlocksForDeletion(inode.asFile().getBlockIds()); } }
[ "public", "void", "deleteInode", "(", "RpcContext", "rpcContext", ",", "LockedInodePath", "inodePath", ",", "long", "opTimeMs", ")", "throws", "FileDoesNotExistException", "{", "Preconditions", ".", "checkState", "(", "inodePath", ".", "getLockPattern", "(", ")", "=...
Deletes a single inode from the inode tree by removing it from the parent inode. @param rpcContext the rpc context @param inodePath the {@link LockedInodePath} to delete @param opTimeMs the operation time @throws FileDoesNotExistException if the Inode cannot be retrieved
[ "Deletes", "a", "single", "inode", "from", "the", "inode", "tree", "by", "removing", "it", "from", "the", "parent", "inode", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L852-L866
Waikato/moa
moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java
ClusteringFeature.calcKMeansCosts
public double calcKMeansCosts(double[] center, ClusteringFeature points) { """ Calculates the k-means costs of the ClusteringFeature and another ClusteringFeature too a center. @param center the center too calculate the costs @param points the points too calculate the costs @return the costs """ assert (this.sumPoints.length == center.length && this.sumPoints.length == points.sumPoints.length); return (this.sumSquaredLength + points.sumSquaredLength) - 2 * Metric.dotProductWithAddition(this.sumPoints, points.sumPoints, center) + (this.numPoints + points.numPoints) * Metric.dotProduct(center); }
java
public double calcKMeansCosts(double[] center, ClusteringFeature points) { assert (this.sumPoints.length == center.length && this.sumPoints.length == points.sumPoints.length); return (this.sumSquaredLength + points.sumSquaredLength) - 2 * Metric.dotProductWithAddition(this.sumPoints, points.sumPoints, center) + (this.numPoints + points.numPoints) * Metric.dotProduct(center); }
[ "public", "double", "calcKMeansCosts", "(", "double", "[", "]", "center", ",", "ClusteringFeature", "points", ")", "{", "assert", "(", "this", ".", "sumPoints", ".", "length", "==", "center", ".", "length", "&&", "this", ".", "sumPoints", ".", "length", "=...
Calculates the k-means costs of the ClusteringFeature and another ClusteringFeature too a center. @param center the center too calculate the costs @param points the points too calculate the costs @return the costs
[ "Calculates", "the", "k", "-", "means", "costs", "of", "the", "ClusteringFeature", "and", "another", "ClusteringFeature", "too", "a", "center", "." ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/clusterers/kmeanspm/ClusteringFeature.java#L297-L305
phax/ph-commons
ph-json/src/main/java/com/helger/json/serialize/JsonReader.java
JsonReader.parseJson
@Nonnull public static ESuccess parseJson (@Nonnull @WillClose final Reader aReader, @Nonnull final IJsonParserHandler aParserHandler) { """ Simple JSON parse method taking only the most basic parameters. @param aReader The reader to read from. Should be buffered. May not be <code>null</code>. @param aParserHandler The parser handler. May not be <code>null</code>. @return {@link ESuccess} """ return parseJson (aReader, aParserHandler, (IJsonParserCustomizeCallback) null, (IJsonParseExceptionCallback) null); }
java
@Nonnull public static ESuccess parseJson (@Nonnull @WillClose final Reader aReader, @Nonnull final IJsonParserHandler aParserHandler) { return parseJson (aReader, aParserHandler, (IJsonParserCustomizeCallback) null, (IJsonParseExceptionCallback) null); }
[ "@", "Nonnull", "public", "static", "ESuccess", "parseJson", "(", "@", "Nonnull", "@", "WillClose", "final", "Reader", "aReader", ",", "@", "Nonnull", "final", "IJsonParserHandler", "aParserHandler", ")", "{", "return", "parseJson", "(", "aReader", ",", "aParser...
Simple JSON parse method taking only the most basic parameters. @param aReader The reader to read from. Should be buffered. May not be <code>null</code>. @param aParserHandler The parser handler. May not be <code>null</code>. @return {@link ESuccess}
[ "Simple", "JSON", "parse", "method", "taking", "only", "the", "most", "basic", "parameters", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-json/src/main/java/com/helger/json/serialize/JsonReader.java#L114-L119
wmdietl/jsr308-langtools
src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java
Util.copyDocFiles
public static void copyDocFiles(Configuration configuration, PackageDoc pd) { """ Copy the given directory contents from the source package directory to the generated documentation directory. For example for a package java.lang this method find out the source location of the package using {@link SourcePath} and if given directory is found in the source directory structure, copy the entire directory, to the generated documentation hierarchy. @param configuration The configuration of the current doclet. @param path The relative path to the directory to be copied. @param dir The original directory name to copy from. @param overwrite Overwrite files if true. """ copyDocFiles(configuration, DocPath.forPackage(pd).resolve(DocPaths.DOC_FILES)); }
java
public static void copyDocFiles(Configuration configuration, PackageDoc pd) { copyDocFiles(configuration, DocPath.forPackage(pd).resolve(DocPaths.DOC_FILES)); }
[ "public", "static", "void", "copyDocFiles", "(", "Configuration", "configuration", ",", "PackageDoc", "pd", ")", "{", "copyDocFiles", "(", "configuration", ",", "DocPath", ".", "forPackage", "(", "pd", ")", ".", "resolve", "(", "DocPaths", ".", "DOC_FILES", ")...
Copy the given directory contents from the source package directory to the generated documentation directory. For example for a package java.lang this method find out the source location of the package using {@link SourcePath} and if given directory is found in the source directory structure, copy the entire directory, to the generated documentation hierarchy. @param configuration The configuration of the current doclet. @param path The relative path to the directory to be copied. @param dir The original directory name to copy from. @param overwrite Overwrite files if true.
[ "Copy", "the", "given", "directory", "contents", "from", "the", "source", "package", "directory", "to", "the", "generated", "documentation", "directory", ".", "For", "example", "for", "a", "package", "java", ".", "lang", "this", "method", "find", "out", "the",...
train
https://github.com/wmdietl/jsr308-langtools/blob/8812d28c20f4de070a0dd6de1b45602431379834/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Util.java#L204-L206
keyboardsurfer/Crouton
library/src/main/java/de/keyboardsurfer/android/widget/crouton/Crouton.java
Crouton.makeText
public static Crouton makeText(Activity activity, int textResourceId, Style style, int viewGroupResId) { """ Creates a {@link Crouton} with provided text-resource and style for a given activity. @param activity The {@link Activity} that represents the context in which the Crouton should exist. @param textResourceId The resource id of the text you want to display. @param style The style that this {@link Crouton} should be created with. @param viewGroupResId The resource id of the {@link ViewGroup} that this {@link Crouton} should be added to. @return The created {@link Crouton}. """ return makeText(activity, activity.getString(textResourceId), style, (ViewGroup) activity.findViewById(viewGroupResId)); }
java
public static Crouton makeText(Activity activity, int textResourceId, Style style, int viewGroupResId) { return makeText(activity, activity.getString(textResourceId), style, (ViewGroup) activity.findViewById(viewGroupResId)); }
[ "public", "static", "Crouton", "makeText", "(", "Activity", "activity", ",", "int", "textResourceId", ",", "Style", "style", ",", "int", "viewGroupResId", ")", "{", "return", "makeText", "(", "activity", ",", "activity", ".", "getString", "(", "textResourceId", ...
Creates a {@link Crouton} with provided text-resource and style for a given activity. @param activity The {@link Activity} that represents the context in which the Crouton should exist. @param textResourceId The resource id of the text you want to display. @param style The style that this {@link Crouton} should be created with. @param viewGroupResId The resource id of the {@link ViewGroup} that this {@link Crouton} should be added to. @return The created {@link Crouton}.
[ "Creates", "a", "{", "@link", "Crouton", "}", "with", "provided", "text", "-", "resource", "and", "style", "for", "a", "given", "activity", "." ]
train
https://github.com/keyboardsurfer/Crouton/blob/7806b15e4d52793e1f5aeaa4a55b1e220289e619/library/src/main/java/de/keyboardsurfer/android/widget/crouton/Crouton.java#L289-L292
josueeduardo/snappy
snappy/src/main/java/io/joshworks/snappy/SnappyServer.java
SnappyServer.beforeAll
public static synchronized void beforeAll(String url, Consumer<Exchange> consumer) { """ Adds an interceptor that executes before any other handler. Calling {@link Exchange#end()} or {@link Exchange#send(Object)} causes the request to complete. @param url The URL pattern the interceptor will execute, only exact matches and wildcard (*) is allowed @param consumer The code to be executed when a URL matches the provided pattern """ checkStarted(); instance().rootInterceptors.add(new Interceptor(Interceptor.Type.BEFORE, HandlerUtil.parseUrl(url), consumer)); }
java
public static synchronized void beforeAll(String url, Consumer<Exchange> consumer) { checkStarted(); instance().rootInterceptors.add(new Interceptor(Interceptor.Type.BEFORE, HandlerUtil.parseUrl(url), consumer)); }
[ "public", "static", "synchronized", "void", "beforeAll", "(", "String", "url", ",", "Consumer", "<", "Exchange", ">", "consumer", ")", "{", "checkStarted", "(", ")", ";", "instance", "(", ")", ".", "rootInterceptors", ".", "add", "(", "new", "Interceptor", ...
Adds an interceptor that executes before any other handler. Calling {@link Exchange#end()} or {@link Exchange#send(Object)} causes the request to complete. @param url The URL pattern the interceptor will execute, only exact matches and wildcard (*) is allowed @param consumer The code to be executed when a URL matches the provided pattern
[ "Adds", "an", "interceptor", "that", "executes", "before", "any", "other", "handler", ".", "Calling", "{", "@link", "Exchange#end", "()", "}", "or", "{", "@link", "Exchange#send", "(", "Object", ")", "}", "causes", "the", "request", "to", "complete", "." ]
train
https://github.com/josueeduardo/snappy/blob/d95a9e811eda3c24a5e53086369208819884fa49/snappy/src/main/java/io/joshworks/snappy/SnappyServer.java#L275-L278
google/closure-templates
java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java
SoyNodeCompiler.visitCallDelegateNode
@Override protected Statement visitCallDelegateNode(CallDelegateNode node) { """ Given this delcall: {@code {delcall foo.bar variant="$expr" allowemptydefault="true"}} <p>Generate code that looks like: <pre>{@code renderContext.getDeltemplate("foo.bar", <variant-expression>, true) .create(<prepareParameters>, ijParams) .render(appendable, renderContext) }</pre> <p>We share logic with {@link #visitCallBasicNode(CallBasicNode)} around the actual calling convention (setting up detaches, storing the template in a field). As well as the logic for preparing the data record. The only interesting part of delcalls is calculating the {@code variant} and the fact that we have to invoke the {@link RenderContext} runtime to do the deltemplate lookup. """ Label reattachPoint = new Label(); Expression variantExpr; if (node.getDelCalleeVariantExpr() == null) { variantExpr = constant(""); } else { variantExpr = exprCompiler.compile(node.getDelCalleeVariantExpr(), reattachPoint).coerceToString(); } Expression calleeExpression = parameterLookup .getRenderContext() .getDeltemplate( node.getDelCalleeName(), variantExpr, node.allowEmptyDefault(), prepareParamsHelper(node, reattachPoint), parameterLookup.getIjRecord()); return renderCallNode(reattachPoint, node, calleeExpression); }
java
@Override protected Statement visitCallDelegateNode(CallDelegateNode node) { Label reattachPoint = new Label(); Expression variantExpr; if (node.getDelCalleeVariantExpr() == null) { variantExpr = constant(""); } else { variantExpr = exprCompiler.compile(node.getDelCalleeVariantExpr(), reattachPoint).coerceToString(); } Expression calleeExpression = parameterLookup .getRenderContext() .getDeltemplate( node.getDelCalleeName(), variantExpr, node.allowEmptyDefault(), prepareParamsHelper(node, reattachPoint), parameterLookup.getIjRecord()); return renderCallNode(reattachPoint, node, calleeExpression); }
[ "@", "Override", "protected", "Statement", "visitCallDelegateNode", "(", "CallDelegateNode", "node", ")", "{", "Label", "reattachPoint", "=", "new", "Label", "(", ")", ";", "Expression", "variantExpr", ";", "if", "(", "node", ".", "getDelCalleeVariantExpr", "(", ...
Given this delcall: {@code {delcall foo.bar variant="$expr" allowemptydefault="true"}} <p>Generate code that looks like: <pre>{@code renderContext.getDeltemplate("foo.bar", <variant-expression>, true) .create(<prepareParameters>, ijParams) .render(appendable, renderContext) }</pre> <p>We share logic with {@link #visitCallBasicNode(CallBasicNode)} around the actual calling convention (setting up detaches, storing the template in a field). As well as the logic for preparing the data record. The only interesting part of delcalls is calculating the {@code variant} and the fact that we have to invoke the {@link RenderContext} runtime to do the deltemplate lookup.
[ "Given", "this", "delcall", ":", "{", "@code", "{", "delcall", "foo", ".", "bar", "variant", "=", "$expr", "allowemptydefault", "=", "true", "}}" ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/SoyNodeCompiler.java#L820-L840
onelogin/onelogin-java-sdk
src/main/java/com/onelogin/sdk/conn/Client.java
Client.getSessionTokenVerified
public SessionTokenInfo getSessionTokenVerified(String devideId, String stateToken, String otpToken, String allowedOrigin) throws OAuthSystemException, OAuthProblemException, URISyntaxException { """ Verify a one-time password (OTP) value provided for multi-factor authentication (MFA). @param devideId Provide the MFA device_id you are submitting for verification. @param stateToken Provide the state_token associated with the MFA device_id you are submitting for verification. @param otpToken Provide the OTP value for the MFA factor you are submitting for verification. @param allowedOrigin Custom-Allowed-Origin-Header. Required for CORS requests only. Set to the Origin URI from which you are allowed to send a request using CORS. @return Session Token @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/verify-factor">Verify Factor documentation</a> """ return getSessionTokenVerified(devideId, stateToken, otpToken, allowedOrigin, false); }
java
public SessionTokenInfo getSessionTokenVerified(String devideId, String stateToken, String otpToken, String allowedOrigin) throws OAuthSystemException, OAuthProblemException, URISyntaxException { return getSessionTokenVerified(devideId, stateToken, otpToken, allowedOrigin, false); }
[ "public", "SessionTokenInfo", "getSessionTokenVerified", "(", "String", "devideId", ",", "String", "stateToken", ",", "String", "otpToken", ",", "String", "allowedOrigin", ")", "throws", "OAuthSystemException", ",", "OAuthProblemException", ",", "URISyntaxException", "{",...
Verify a one-time password (OTP) value provided for multi-factor authentication (MFA). @param devideId Provide the MFA device_id you are submitting for verification. @param stateToken Provide the state_token associated with the MFA device_id you are submitting for verification. @param otpToken Provide the OTP value for the MFA factor you are submitting for verification. @param allowedOrigin Custom-Allowed-Origin-Header. Required for CORS requests only. Set to the Origin URI from which you are allowed to send a request using CORS. @return Session Token @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/users/verify-factor">Verify Factor documentation</a>
[ "Verify", "a", "one", "-", "time", "password", "(", "OTP", ")", "value", "provided", "for", "multi", "-", "factor", "authentication", "(", "MFA", ")", "." ]
train
https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L960-L962
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/watermark/TimestampWatermark.java
TimestampWatermark.getInterval
private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) { """ recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions @param diffInMilliSecs difference in range @param hourInterval hour interval (ex: 4 hours) @param maxIntervals max number of allowed partitions @return calculated interval in hours """ long totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING); long totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING); if (totalIntervals > maxIntervals) { hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING); } return Ints.checkedCast(hourInterval); }
java
private static int getInterval(long diffInMilliSecs, long hourInterval, int maxIntervals) { long totalHours = DoubleMath.roundToInt((double) diffInMilliSecs / (60 * 60 * 1000), RoundingMode.CEILING); long totalIntervals = DoubleMath.roundToInt((double) totalHours / hourInterval, RoundingMode.CEILING); if (totalIntervals > maxIntervals) { hourInterval = DoubleMath.roundToInt((double) totalHours / maxIntervals, RoundingMode.CEILING); } return Ints.checkedCast(hourInterval); }
[ "private", "static", "int", "getInterval", "(", "long", "diffInMilliSecs", ",", "long", "hourInterval", ",", "int", "maxIntervals", ")", "{", "long", "totalHours", "=", "DoubleMath", ".", "roundToInt", "(", "(", "double", ")", "diffInMilliSecs", "/", "(", "60"...
recalculate interval(in hours) if total number of partitions greater than maximum number of allowed partitions @param diffInMilliSecs difference in range @param hourInterval hour interval (ex: 4 hours) @param maxIntervals max number of allowed partitions @return calculated interval in hours
[ "recalculate", "interval", "(", "in", "hours", ")", "if", "total", "number", "of", "partitions", "greater", "than", "maximum", "number", "of", "allowed", "partitions" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/watermark/TimestampWatermark.java#L125-L133
epam/parso
src/main/java/com/epam/parso/impl/SasFileParser.java
SasFileParser.chooseSubheaderClass
private SubheaderIndexes chooseSubheaderClass(long subheaderSignature, int compression, int type) { """ The function to determine the subheader type by its signature, {@link SubheaderPointer#compression}, and {@link SubheaderPointer#type}. @param subheaderSignature the subheader signature to search for in the {@link SasFileParser#SUBHEADER_SIGNATURE_TO_INDEX} mapping @param compression the type of subheader compression ({@link SubheaderPointer#compression}) @param type the subheader type ({@link SubheaderPointer#type}) @return an element from the {@link SubheaderIndexes} enumeration that defines the type of the current subheader """ SubheaderIndexes subheaderIndex = SUBHEADER_SIGNATURE_TO_INDEX.get(subheaderSignature); if (sasFileProperties.isCompressed() && subheaderIndex == null && (compression == COMPRESSED_SUBHEADER_ID || compression == 0) && type == COMPRESSED_SUBHEADER_TYPE) { subheaderIndex = SubheaderIndexes.DATA_SUBHEADER_INDEX; } return subheaderIndex; }
java
private SubheaderIndexes chooseSubheaderClass(long subheaderSignature, int compression, int type) { SubheaderIndexes subheaderIndex = SUBHEADER_SIGNATURE_TO_INDEX.get(subheaderSignature); if (sasFileProperties.isCompressed() && subheaderIndex == null && (compression == COMPRESSED_SUBHEADER_ID || compression == 0) && type == COMPRESSED_SUBHEADER_TYPE) { subheaderIndex = SubheaderIndexes.DATA_SUBHEADER_INDEX; } return subheaderIndex; }
[ "private", "SubheaderIndexes", "chooseSubheaderClass", "(", "long", "subheaderSignature", ",", "int", "compression", ",", "int", "type", ")", "{", "SubheaderIndexes", "subheaderIndex", "=", "SUBHEADER_SIGNATURE_TO_INDEX", ".", "get", "(", "subheaderSignature", ")", ";",...
The function to determine the subheader type by its signature, {@link SubheaderPointer#compression}, and {@link SubheaderPointer#type}. @param subheaderSignature the subheader signature to search for in the {@link SasFileParser#SUBHEADER_SIGNATURE_TO_INDEX} mapping @param compression the type of subheader compression ({@link SubheaderPointer#compression}) @param type the subheader type ({@link SubheaderPointer#type}) @return an element from the {@link SubheaderIndexes} enumeration that defines the type of the current subheader
[ "The", "function", "to", "determine", "the", "subheader", "type", "by", "its", "signature", "{", "@link", "SubheaderPointer#compression", "}", "and", "{", "@link", "SubheaderPointer#type", "}", "." ]
train
https://github.com/epam/parso/blob/fb132cf943ba099a35b2f5a1490c0a59641e09dc/src/main/java/com/epam/parso/impl/SasFileParser.java#L439-L446
j256/ormlite-android
src/main/java/com/j256/ormlite/android/apptools/OrmLiteSqliteOpenHelper.java
OrmLiteSqliteOpenHelper.getRuntimeExceptionDao
public <D extends RuntimeExceptionDao<T, ?>, T> D getRuntimeExceptionDao(Class<T> clazz) { """ Get a RuntimeExceptionDao for our class. This uses the {@link DaoManager} to cache the DAO for future gets. <p> NOTE: This routing does not return RuntimeExceptionDao&lt;T, ID&gt; because of casting issues if we are assigning it to a custom DAO. Grumble. </p> """ try { Dao<T, ?> dao = getDao(clazz); @SuppressWarnings({ "unchecked", "rawtypes" }) D castDao = (D) new RuntimeExceptionDao(dao); return castDao; } catch (SQLException e) { throw new RuntimeException("Could not create RuntimeExcepitionDao for class " + clazz, e); } }
java
public <D extends RuntimeExceptionDao<T, ?>, T> D getRuntimeExceptionDao(Class<T> clazz) { try { Dao<T, ?> dao = getDao(clazz); @SuppressWarnings({ "unchecked", "rawtypes" }) D castDao = (D) new RuntimeExceptionDao(dao); return castDao; } catch (SQLException e) { throw new RuntimeException("Could not create RuntimeExcepitionDao for class " + clazz, e); } }
[ "public", "<", "D", "extends", "RuntimeExceptionDao", "<", "T", ",", "?", ">", ",", "T", ">", "D", "getRuntimeExceptionDao", "(", "Class", "<", "T", ">", "clazz", ")", "{", "try", "{", "Dao", "<", "T", ",", "?", ">", "dao", "=", "getDao", "(", "c...
Get a RuntimeExceptionDao for our class. This uses the {@link DaoManager} to cache the DAO for future gets. <p> NOTE: This routing does not return RuntimeExceptionDao&lt;T, ID&gt; because of casting issues if we are assigning it to a custom DAO. Grumble. </p>
[ "Get", "a", "RuntimeExceptionDao", "for", "our", "class", ".", "This", "uses", "the", "{", "@link", "DaoManager", "}", "to", "cache", "the", "DAO", "for", "future", "gets", "." ]
train
https://github.com/j256/ormlite-android/blob/e82327a868ae242f994730fe2389f79684d7bcab/src/main/java/com/j256/ormlite/android/apptools/OrmLiteSqliteOpenHelper.java#L291-L300
nakamura5akihito/six-util
src/main/java/jp/go/aist/six/util/core/web/spring/Http.java
Http.postFrom
public static String postFrom( final URL to_url, final InputStream from_stream, final MediaType media_type ) { """ HTTP POST: Reads the contents from the specified stream and sends them to the URL. @return the location, as an URI, where the resource is created. @throws HttpException when an exceptional condition occurred during the HTTP method execution. """ InputStreamRequestCallback callback = new InputStreamRequestCallback( from_stream, media_type ); String location = _execute( to_url, HttpMethod.POST, callback, new LocationHeaderResponseExtractor() ); return location; }
java
public static String postFrom( final URL to_url, final InputStream from_stream, final MediaType media_type ) { InputStreamRequestCallback callback = new InputStreamRequestCallback( from_stream, media_type ); String location = _execute( to_url, HttpMethod.POST, callback, new LocationHeaderResponseExtractor() ); return location; }
[ "public", "static", "String", "postFrom", "(", "final", "URL", "to_url", ",", "final", "InputStream", "from_stream", ",", "final", "MediaType", "media_type", ")", "{", "InputStreamRequestCallback", "callback", "=", "new", "InputStreamRequestCallback", "(", "from_strea...
HTTP POST: Reads the contents from the specified stream and sends them to the URL. @return the location, as an URI, where the resource is created. @throws HttpException when an exceptional condition occurred during the HTTP method execution.
[ "HTTP", "POST", ":", "Reads", "the", "contents", "from", "the", "specified", "stream", "and", "sends", "them", "to", "the", "URL", "." ]
train
https://github.com/nakamura5akihito/six-util/blob/a6db388a345e220cea2b1fa6324d15c80c6278b6/src/main/java/jp/go/aist/six/util/core/web/spring/Http.java#L243-L255
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/theta/ForwardCompatibility.java
ForwardCompatibility.heapify2to3
static final CompactSketch heapify2to3(final Memory srcMem, final long seed) { """ Convert a serialization version (SerVer) 2 sketch to a SerVer 3 HeapCompactOrderedSketch. Note: SerVer 2 sketches can have metadata-longs of 1,2 or 3 and are always stored in a compact ordered form, but with 4 different sketch types. @param srcMem the image of a SerVer 1 sketch @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a>. The seed used for building the sketch image in srcMem @return a SerVer 3 HeapCompactOrderedSketch """ final int memCap = (int) srcMem.getCapacity(); final short seedHash = Util.computeSeedHash(seed); final short memSeedHash = srcMem.getShort(SEED_HASH_SHORT); Util.checkSeedHashes(seedHash, memSeedHash); if (memCap == 8) { //return empty, theta = 1.0 return HeapCompactOrderedSketch .compact(new long[0], true, seedHash, 0, Long.MAX_VALUE); } final int curCount = srcMem.getInt(RETAINED_ENTRIES_INT); //Note: curCount could be zero and theta < 1.0 and be empty or not-empty. final int mdLongs = srcMem.getByte(PREAMBLE_LONGS_BYTE) & 0X3F; //either 2 or 3 final int reqBytesIn = (curCount + mdLongs) << 3; validateInputSize(reqBytesIn, memCap); final long thetaLong = (mdLongs < 3) ? Long.MAX_VALUE : srcMem.getLong(THETA_LONG); boolean empty = (srcMem.getByte(FLAGS_BYTE) & EMPTY_FLAG_MASK) != 0; empty = (curCount == 0) && (thetaLong == Long.MAX_VALUE); //force true final long[] compactOrderedCache = new long[curCount]; srcMem.getLongArray(mdLongs << 3, compactOrderedCache, 0, curCount); return HeapCompactOrderedSketch .compact(compactOrderedCache, empty, seedHash, curCount, thetaLong); }
java
static final CompactSketch heapify2to3(final Memory srcMem, final long seed) { final int memCap = (int) srcMem.getCapacity(); final short seedHash = Util.computeSeedHash(seed); final short memSeedHash = srcMem.getShort(SEED_HASH_SHORT); Util.checkSeedHashes(seedHash, memSeedHash); if (memCap == 8) { //return empty, theta = 1.0 return HeapCompactOrderedSketch .compact(new long[0], true, seedHash, 0, Long.MAX_VALUE); } final int curCount = srcMem.getInt(RETAINED_ENTRIES_INT); //Note: curCount could be zero and theta < 1.0 and be empty or not-empty. final int mdLongs = srcMem.getByte(PREAMBLE_LONGS_BYTE) & 0X3F; //either 2 or 3 final int reqBytesIn = (curCount + mdLongs) << 3; validateInputSize(reqBytesIn, memCap); final long thetaLong = (mdLongs < 3) ? Long.MAX_VALUE : srcMem.getLong(THETA_LONG); boolean empty = (srcMem.getByte(FLAGS_BYTE) & EMPTY_FLAG_MASK) != 0; empty = (curCount == 0) && (thetaLong == Long.MAX_VALUE); //force true final long[] compactOrderedCache = new long[curCount]; srcMem.getLongArray(mdLongs << 3, compactOrderedCache, 0, curCount); return HeapCompactOrderedSketch .compact(compactOrderedCache, empty, seedHash, curCount, thetaLong); }
[ "static", "final", "CompactSketch", "heapify2to3", "(", "final", "Memory", "srcMem", ",", "final", "long", "seed", ")", "{", "final", "int", "memCap", "=", "(", "int", ")", "srcMem", ".", "getCapacity", "(", ")", ";", "final", "short", "seedHash", "=", "...
Convert a serialization version (SerVer) 2 sketch to a SerVer 3 HeapCompactOrderedSketch. Note: SerVer 2 sketches can have metadata-longs of 1,2 or 3 and are always stored in a compact ordered form, but with 4 different sketch types. @param srcMem the image of a SerVer 1 sketch @param seed <a href="{@docRoot}/resources/dictionary.html#seed">See Update Hash Seed</a>. The seed used for building the sketch image in srcMem @return a SerVer 3 HeapCompactOrderedSketch
[ "Convert", "a", "serialization", "version", "(", "SerVer", ")", "2", "sketch", "to", "a", "SerVer", "3", "HeapCompactOrderedSketch", ".", "Note", ":", "SerVer", "2", "sketches", "can", "have", "metadata", "-", "longs", "of", "1", "2", "or", "3", "and", "...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/theta/ForwardCompatibility.java#L75-L101
BlueBrain/bluima
modules/bluima_abbreviations/src/main/java/com/wcohen/ss/abbvGapsHmm/AbbvGapsHmmBackwardsEvaluator.java
AbbvGapsHmmBackwardsEvaluator.getStartedWord
protected static String getStartedWord(String str, int pos) { """ If pos is starting a new word in str, returns this word. Else, returns null. """ assert(pos < str.length() && pos >= 0); if( posIsAtWordStart(str, pos) ){ int nextSpace = findNextNonLetterOrDigit(str, pos); if(nextSpace == -1){ nextSpace = str.length(); } return str.substring(pos, nextSpace); } return null; }
java
protected static String getStartedWord(String str, int pos){ assert(pos < str.length() && pos >= 0); if( posIsAtWordStart(str, pos) ){ int nextSpace = findNextNonLetterOrDigit(str, pos); if(nextSpace == -1){ nextSpace = str.length(); } return str.substring(pos, nextSpace); } return null; }
[ "protected", "static", "String", "getStartedWord", "(", "String", "str", ",", "int", "pos", ")", "{", "assert", "(", "pos", "<", "str", ".", "length", "(", ")", "&&", "pos", ">=", "0", ")", ";", "if", "(", "posIsAtWordStart", "(", "str", ",", "pos", ...
If pos is starting a new word in str, returns this word. Else, returns null.
[ "If", "pos", "is", "starting", "a", "new", "word", "in", "str", "returns", "this", "word", ".", "Else", "returns", "null", "." ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_abbreviations/src/main/java/com/wcohen/ss/abbvGapsHmm/AbbvGapsHmmBackwardsEvaluator.java#L171-L183
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaTransactionalDispatcher.java
SibRaTransactionalDispatcher.createEndpoint
protected MessageEndpoint createEndpoint() throws ResourceException { """ Creates an endpoint. Passes an <code>XAResource</code> on the creation. It is wrapped in a <code>SibRaXaResource</code>. @return the endpoint @throws ResourceException if the endpoint could not be created """ final String methodName = "createEndpoint"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } // Ensure that in non-WAS environments the activation spec used to create // the current connection specified a specific messaging engine. This is // required so that we always connect to the same messaging engine when // using the same activation specification to permit transaction recovery. //chetan liberty change : //getTarget() check is removed since in liberty we have 1 ME per liberty profile if ((_endpointConfiguration.getTargetSignificance().equals(SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED)) && (_endpointConfiguration.getTargetType().equals(SibTrmConstants.TARGET_TYPE_ME))) { _sibXaResource = new SibRaXaResource (getXaResource()); } else { String p0; // Connection property name String p1; // Required connection property value if (!_endpointConfiguration.getTargetSignificance().equals(SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED)) { p0 = SibTrmConstants.TARGET_SIGNIFICANCE; p1 = SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED; } else if (!_endpointConfiguration.getTargetType().equals(SibTrmConstants.TARGET_TYPE_ME)) { p0 = SibTrmConstants.TARGET_TYPE; p1 = SibTrmConstants.TARGET_TYPE_ME; } else { p0 = SibTrmConstants.TARGET_GROUP; p1 = "!null"; } SibTr.error(TRACE, "ME_NAME_REQUIRED_CWSIV0652",new Object[] {p0,p1}); throw new NotSupportedException(NLS.getFormattedMessage("ME_NAME_REQUIRED_CWSIV0652", new Object[] {p0,p1}, null)); } final MessageEndpoint endpoint = _endpointFactory .createEndpoint(_sibXaResource); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName, endpoint); } return endpoint; }
java
protected MessageEndpoint createEndpoint() throws ResourceException { final String methodName = "createEndpoint"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName); } // Ensure that in non-WAS environments the activation spec used to create // the current connection specified a specific messaging engine. This is // required so that we always connect to the same messaging engine when // using the same activation specification to permit transaction recovery. //chetan liberty change : //getTarget() check is removed since in liberty we have 1 ME per liberty profile if ((_endpointConfiguration.getTargetSignificance().equals(SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED)) && (_endpointConfiguration.getTargetType().equals(SibTrmConstants.TARGET_TYPE_ME))) { _sibXaResource = new SibRaXaResource (getXaResource()); } else { String p0; // Connection property name String p1; // Required connection property value if (!_endpointConfiguration.getTargetSignificance().equals(SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED)) { p0 = SibTrmConstants.TARGET_SIGNIFICANCE; p1 = SibTrmConstants.TARGET_SIGNIFICANCE_REQUIRED; } else if (!_endpointConfiguration.getTargetType().equals(SibTrmConstants.TARGET_TYPE_ME)) { p0 = SibTrmConstants.TARGET_TYPE; p1 = SibTrmConstants.TARGET_TYPE_ME; } else { p0 = SibTrmConstants.TARGET_GROUP; p1 = "!null"; } SibTr.error(TRACE, "ME_NAME_REQUIRED_CWSIV0652",new Object[] {p0,p1}); throw new NotSupportedException(NLS.getFormattedMessage("ME_NAME_REQUIRED_CWSIV0652", new Object[] {p0,p1}, null)); } final MessageEndpoint endpoint = _endpointFactory .createEndpoint(_sibXaResource); if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName, endpoint); } return endpoint; }
[ "protected", "MessageEndpoint", "createEndpoint", "(", ")", "throws", "ResourceException", "{", "final", "String", "methodName", "=", "\"createEndpoint\"", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "TRACE", ".", "isEntryEnabled", ...
Creates an endpoint. Passes an <code>XAResource</code> on the creation. It is wrapped in a <code>SibRaXaResource</code>. @return the endpoint @throws ResourceException if the endpoint could not be created
[ "Creates", "an", "endpoint", ".", "Passes", "an", "<code", ">", "XAResource<", "/", "code", ">", "on", "the", "creation", ".", "It", "is", "wrapped", "in", "a", "<code", ">", "SibRaXaResource<", "/", "code", ">", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaTransactionalDispatcher.java#L212-L259
fozziethebeat/S-Space
src/main/java/edu/ucla/sspace/vector/VectorMath.java
VectorMath.addUnmodified
public static Vector addUnmodified(Vector vector1, Vector vector2) { """ Returns a new {@code Vector} which is the summation of {@code vector2} and {@code vector1}. @param vector1 The first vector to used in a summation. @param vector2 The second vector to be used in a summation. @return The summation of {code vector1} and {@code vector2}. """ if (vector2.length() != vector1.length()) throw new IllegalArgumentException( "Vectors of different sizes cannot be added"); return addUnmodified(Vectors.asDouble(vector1), Vectors.asDouble(vector2)); }
java
public static Vector addUnmodified(Vector vector1, Vector vector2) { if (vector2.length() != vector1.length()) throw new IllegalArgumentException( "Vectors of different sizes cannot be added"); return addUnmodified(Vectors.asDouble(vector1), Vectors.asDouble(vector2)); }
[ "public", "static", "Vector", "addUnmodified", "(", "Vector", "vector1", ",", "Vector", "vector2", ")", "{", "if", "(", "vector2", ".", "length", "(", ")", "!=", "vector1", ".", "length", "(", ")", ")", "throw", "new", "IllegalArgumentException", "(", "\"V...
Returns a new {@code Vector} which is the summation of {@code vector2} and {@code vector1}. @param vector1 The first vector to used in a summation. @param vector2 The second vector to be used in a summation. @return The summation of {code vector1} and {@code vector2}.
[ "Returns", "a", "new", "{", "@code", "Vector", "}", "which", "is", "the", "summation", "of", "{", "@code", "vector2", "}", "and", "{", "@code", "vector1", "}", "." ]
train
https://github.com/fozziethebeat/S-Space/blob/a608102737dfd3d59038a9ead33fe60356bc6029/src/main/java/edu/ucla/sspace/vector/VectorMath.java#L150-L156
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java
EventSubscriptionsInner.createOrUpdate
public EventSubscriptionInner createOrUpdate(String scope, String eventSubscriptionName, EventSubscriptionInner eventSubscriptionInfo) { """ Create or update an event subscription. Asynchronously creates a new event subscription or updates an existing event subscription based on the specified scope. @param scope The identifier of the resource to which the event subscription needs to be created or updated. The scope can be a subscription, or a resource group, or a top level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use '/subscriptions/{subscriptionId}/' for a subscription, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for a resource group, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' for a resource, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' for an EventGrid topic. @param eventSubscriptionName Name of the event subscription. Event subscription names must be between 3 and 64 characters in length and should use alphanumeric letters only. @param eventSubscriptionInfo Event subscription properties containing the destination and filter information @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EventSubscriptionInner object if successful. """ return createOrUpdateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionInfo).toBlocking().last().body(); }
java
public EventSubscriptionInner createOrUpdate(String scope, String eventSubscriptionName, EventSubscriptionInner eventSubscriptionInfo) { return createOrUpdateWithServiceResponseAsync(scope, eventSubscriptionName, eventSubscriptionInfo).toBlocking().last().body(); }
[ "public", "EventSubscriptionInner", "createOrUpdate", "(", "String", "scope", ",", "String", "eventSubscriptionName", ",", "EventSubscriptionInner", "eventSubscriptionInfo", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "scope", ",", "eventSubscriptionName"...
Create or update an event subscription. Asynchronously creates a new event subscription or updates an existing event subscription based on the specified scope. @param scope The identifier of the resource to which the event subscription needs to be created or updated. The scope can be a subscription, or a resource group, or a top level resource belonging to a resource provider namespace, or an EventGrid topic. For example, use '/subscriptions/{subscriptionId}/' for a subscription, '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}' for a resource group, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}' for a resource, and '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/topics/{topicName}' for an EventGrid topic. @param eventSubscriptionName Name of the event subscription. Event subscription names must be between 3 and 64 characters in length and should use alphanumeric letters only. @param eventSubscriptionInfo Event subscription properties containing the destination and filter information @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the EventSubscriptionInner object if successful.
[ "Create", "or", "update", "an", "event", "subscription", ".", "Asynchronously", "creates", "a", "new", "event", "subscription", "or", "updates", "an", "existing", "event", "subscription", "based", "on", "the", "specified", "scope", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_05_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_05_01_preview/implementation/EventSubscriptionsInner.java#L235-L237
deeplearning4j/deeplearning4j
datavec/datavec-api/src/main/java/org/datavec/api/conf/Configuration.java
Configuration.getLong
public long getLong(String name, long defaultValue) { """ Get the value of the <code>name</code> property as a <code>long</code>. If no such property is specified, or if the specified value is not a valid <code>long</code>, then <code>defaultValue</code> is returned. @param name property name. @param defaultValue default value. @return property value as a <code>long</code>, or <code>defaultValue</code>. """ String valueString = get(name); if (valueString == null) return defaultValue; try { String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); } catch (NumberFormatException e) { return defaultValue; } }
java
public long getLong(String name, long defaultValue) { String valueString = get(name); if (valueString == null) return defaultValue; try { String hexString = getHexDigits(valueString); if (hexString != null) { return Long.parseLong(hexString, 16); } return Long.parseLong(valueString); } catch (NumberFormatException e) { return defaultValue; } }
[ "public", "long", "getLong", "(", "String", "name", ",", "long", "defaultValue", ")", "{", "String", "valueString", "=", "get", "(", "name", ")", ";", "if", "(", "valueString", "==", "null", ")", "return", "defaultValue", ";", "try", "{", "String", "hexS...
Get the value of the <code>name</code> property as a <code>long</code>. If no such property is specified, or if the specified value is not a valid <code>long</code>, then <code>defaultValue</code> is returned. @param name property name. @param defaultValue default value. @return property value as a <code>long</code>, or <code>defaultValue</code>.
[ "Get", "the", "value", "of", "the", "<code", ">", "name<", "/", "code", ">", "property", "as", "a", "<code", ">", "long<", "/", "code", ">", ".", "If", "no", "such", "property", "is", "specified", "or", "if", "the", "specified", "value", "is", "not",...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-api/src/main/java/org/datavec/api/conf/Configuration.java#L510-L523
ManfredTremmel/gwt-bean-validators
gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/util/ObjectUtils.java
ObjectUtils.nullSafeEquals
public static boolean nullSafeEquals(@Nullable final Object o1, @Nullable final Object o2) { """ Determine if the given objects are equal, returning {@code true} if both are {@code null} or {@code false} if only one is {@code null}. <p> Compares arrays with {@code Arrays.equals}, performing an equality check based on the array elements rather than the array reference. @param o1 first Object to compare @param o2 second Object to compare @return whether the given objects are equal @see Object#equals(Object) @see java.util.Arrays#equals """ if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return ObjectUtils.arrayEquals(o1, o2); } return false; }
java
public static boolean nullSafeEquals(@Nullable final Object o1, @Nullable final Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } if (o1.equals(o2)) { return true; } if (o1.getClass().isArray() && o2.getClass().isArray()) { return ObjectUtils.arrayEquals(o1, o2); } return false; }
[ "public", "static", "boolean", "nullSafeEquals", "(", "@", "Nullable", "final", "Object", "o1", ",", "@", "Nullable", "final", "Object", "o2", ")", "{", "if", "(", "o1", "==", "o2", ")", "{", "return", "true", ";", "}", "if", "(", "o1", "==", "null",...
Determine if the given objects are equal, returning {@code true} if both are {@code null} or {@code false} if only one is {@code null}. <p> Compares arrays with {@code Arrays.equals}, performing an equality check based on the array elements rather than the array reference. @param o1 first Object to compare @param o2 second Object to compare @return whether the given objects are equal @see Object#equals(Object) @see java.util.Arrays#equals
[ "Determine", "if", "the", "given", "objects", "are", "equal", "returning", "{", "@code", "true", "}", "if", "both", "are", "{", "@code", "null", "}", "or", "{", "@code", "false", "}", "if", "only", "one", "is", "{", "@code", "null", "}", ".", "<p", ...
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/gwtp-spring-integration/src/main/super/de/knightsoftnet/gwtp/spring/supersource/org/springframework/util/ObjectUtils.java#L338-L352
geomajas/geomajas-project-client-gwt
common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java
HtmlBuilder.divStyleHtmlContent
public static String divStyleHtmlContent(String style, String... content) { """ Build a HTML DIV with given style for a string. Use this method if given content contains HTML snippets, prepared with {@link HtmlBuilder#htmlEncode(String)}. @param style style for div (plain CSS) @param content content string @return HTML DIV element as string """ return tagStyleHtmlContent(Html.Tag.DIV, style, content); }
java
public static String divStyleHtmlContent(String style, String... content) { return tagStyleHtmlContent(Html.Tag.DIV, style, content); }
[ "public", "static", "String", "divStyleHtmlContent", "(", "String", "style", ",", "String", "...", "content", ")", "{", "return", "tagStyleHtmlContent", "(", "Html", ".", "Tag", ".", "DIV", ",", "style", ",", "content", ")", ";", "}" ]
Build a HTML DIV with given style for a string. Use this method if given content contains HTML snippets, prepared with {@link HtmlBuilder#htmlEncode(String)}. @param style style for div (plain CSS) @param content content string @return HTML DIV element as string
[ "Build", "a", "HTML", "DIV", "with", "given", "style", "for", "a", "string", ".", "Use", "this", "method", "if", "given", "content", "contains", "HTML", "snippets", "prepared", "with", "{", "@link", "HtmlBuilder#htmlEncode", "(", "String", ")", "}", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/common-gwt-smartgwt/src/main/java/org/geomajas/gwt/client/util/HtmlBuilder.java#L215-L217
tvbarthel/Cheerleader
sample/src/main/java/fr/tvbarthel/cheerleader/sampleapp/ArtistActivity.java
ArtistActivity.startActivity
public static void startActivity(Context context, String artistName) { """ Start an ArtistActivity for a given artist name. Start activity pattern. @param context context used to start the activity. @param artistName name of the artist. """ Intent i = new Intent(context, ArtistActivity.class); i.putExtra(BUNDLE_KEY_ARTIST_NAME, artistName); context.startActivity(i); }
java
public static void startActivity(Context context, String artistName) { Intent i = new Intent(context, ArtistActivity.class); i.putExtra(BUNDLE_KEY_ARTIST_NAME, artistName); context.startActivity(i); }
[ "public", "static", "void", "startActivity", "(", "Context", "context", ",", "String", "artistName", ")", "{", "Intent", "i", "=", "new", "Intent", "(", "context", ",", "ArtistActivity", ".", "class", ")", ";", "i", ".", "putExtra", "(", "BUNDLE_KEY_ARTIST_N...
Start an ArtistActivity for a given artist name. Start activity pattern. @param context context used to start the activity. @param artistName name of the artist.
[ "Start", "an", "ArtistActivity", "for", "a", "given", "artist", "name", ".", "Start", "activity", "pattern", "." ]
train
https://github.com/tvbarthel/Cheerleader/blob/f61527e4cc44fcd0ed2e1e98aca285f8c236f24e/sample/src/main/java/fr/tvbarthel/cheerleader/sampleapp/ArtistActivity.java#L85-L89
haraldk/TwelveMonkeys
servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java
ContentNegotiationFilter.findBestFormat
private static String findBestFormat(Map<String, Float> pFormatQuality) { """ Finds the best available format. @param pFormatQuality the format to quality mapping @return the mime type of the best available format """ String acceptable = null; float acceptQuality = 0.0f; for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) { float qValue = entry.getValue(); if (qValue > acceptQuality) { acceptQuality = qValue; acceptable = entry.getKey(); } } //System.out.println("Accepted format: " + acceptable); //System.out.println("Accepted quality: " + acceptQuality); return acceptable; }
java
private static String findBestFormat(Map<String, Float> pFormatQuality) { String acceptable = null; float acceptQuality = 0.0f; for (Map.Entry<String, Float> entry : pFormatQuality.entrySet()) { float qValue = entry.getValue(); if (qValue > acceptQuality) { acceptQuality = qValue; acceptable = entry.getKey(); } } //System.out.println("Accepted format: " + acceptable); //System.out.println("Accepted quality: " + acceptQuality); return acceptable; }
[ "private", "static", "String", "findBestFormat", "(", "Map", "<", "String", ",", "Float", ">", "pFormatQuality", ")", "{", "String", "acceptable", "=", "null", ";", "float", "acceptQuality", "=", "0.0f", ";", "for", "(", "Map", ".", "Entry", "<", "String",...
Finds the best available format. @param pFormatQuality the format to quality mapping @return the mime type of the best available format
[ "Finds", "the", "best", "available", "format", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/servlet/src/main/java/com/twelvemonkeys/servlet/image/ContentNegotiationFilter.java#L275-L289
kotcrab/vis-ui
ui/src/main/java/com/kotcrab/vis/ui/widget/PopupMenu.java
PopupMenu.showMenu
public void showMenu (Stage stage, Actor actor) { """ Shows menu below (or above if not enough space) given actor. @param stage stage instance that this menu is being added to @param actor used to get calculate menu position in stage, menu will be displayed above or below it """ Vector2 pos = actor.localToStageCoordinates(tmpVector.setZero()); float menuY; if (pos.y - getHeight() <= 0) { menuY = pos.y + actor.getHeight() + getHeight() - sizes.borderSize; } else { menuY = pos.y + sizes.borderSize; } showMenu(stage, pos.x, menuY); }
java
public void showMenu (Stage stage, Actor actor) { Vector2 pos = actor.localToStageCoordinates(tmpVector.setZero()); float menuY; if (pos.y - getHeight() <= 0) { menuY = pos.y + actor.getHeight() + getHeight() - sizes.borderSize; } else { menuY = pos.y + sizes.borderSize; } showMenu(stage, pos.x, menuY); }
[ "public", "void", "showMenu", "(", "Stage", "stage", ",", "Actor", "actor", ")", "{", "Vector2", "pos", "=", "actor", ".", "localToStageCoordinates", "(", "tmpVector", ".", "setZero", "(", ")", ")", ";", "float", "menuY", ";", "if", "(", "pos", ".", "y...
Shows menu below (or above if not enough space) given actor. @param stage stage instance that this menu is being added to @param actor used to get calculate menu position in stage, menu will be displayed above or below it
[ "Shows", "menu", "below", "(", "or", "above", "if", "not", "enough", "space", ")", "given", "actor", "." ]
train
https://github.com/kotcrab/vis-ui/blob/3b68f82d94ae32bffa2a3399c63f432e0f4908e0/ui/src/main/java/com/kotcrab/vis/ui/widget/PopupMenu.java#L301-L310
wcm-io/wcm-io-handler
commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java
AbstractElement.setAttributeValueAsInteger
public final T setAttributeValueAsInteger(String name, int value) { """ Sets attribute value as integer. @param name Attribute name @param value Attribute value as integer @return Self reference """ setAttribute(name, Integer.toString(value)); return (T)this; }
java
public final T setAttributeValueAsInteger(String name, int value) { setAttribute(name, Integer.toString(value)); return (T)this; }
[ "public", "final", "T", "setAttributeValueAsInteger", "(", "String", "name", ",", "int", "value", ")", "{", "setAttribute", "(", "name", ",", "Integer", ".", "toString", "(", "value", ")", ")", ";", "return", "(", "T", ")", "this", ";", "}" ]
Sets attribute value as integer. @param name Attribute name @param value Attribute value as integer @return Self reference
[ "Sets", "attribute", "value", "as", "integer", "." ]
train
https://github.com/wcm-io/wcm-io-handler/blob/b0fc1c11a3ceb89efb73826dcfd480d6a00c19af/commons/src/main/java/io/wcm/handler/commons/dom/AbstractElement.java#L123-L126
gallandarakhneorg/afc
core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java
XMLUtil.getAttributeBooleanWithDefault
@Pure public static Boolean getAttributeBooleanWithDefault(Node document, Boolean defaultValue, String... path) { """ Replies the boolean value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the boolean value of the specified attribute or <code>false</code> if it was node found in the document """ assert document != null : AssertMessages.notNullParameter(0); return getAttributeBooleanWithDefault(document, true, defaultValue, path); }
java
@Pure public static Boolean getAttributeBooleanWithDefault(Node document, Boolean defaultValue, String... path) { assert document != null : AssertMessages.notNullParameter(0); return getAttributeBooleanWithDefault(document, true, defaultValue, path); }
[ "@", "Pure", "public", "static", "Boolean", "getAttributeBooleanWithDefault", "(", "Node", "document", ",", "Boolean", "defaultValue", ",", "String", "...", "path", ")", "{", "assert", "document", "!=", "null", ":", "AssertMessages", ".", "notNullParameter", "(", ...
Replies the boolean value that corresponds to the specified attribute's path. <p>The path is an ordered list of tag's names and ended by the name of the attribute. @param document is the XML document to explore. @param defaultValue is the default value to reply. @param path is the list of and ended by the attribute's name. @return the boolean value of the specified attribute or <code>false</code> if it was node found in the document
[ "Replies", "the", "boolean", "value", "that", "corresponds", "to", "the", "specified", "attribute", "s", "path", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/core/inputoutput/src/main/java/org/arakhne/afc/inputoutput/xml/XMLUtil.java#L343-L347
beanshell/beanshell
src/main/java/bsh/Reflect.java
Reflect.resolveJavaField
protected static Invocable resolveJavaField( Class<?> clas, String fieldName, boolean staticOnly ) throws UtilEvalError { """ /* Note: this method and resolveExpectedJavaField should be rewritten to invert this logic so that no exceptions need to be caught unecessarily. This is just a temporary impl. @return the field or null if not found """ try { return resolveExpectedJavaField( clas, fieldName, staticOnly ); } catch ( ReflectError e ) { return null; } }
java
protected static Invocable resolveJavaField( Class<?> clas, String fieldName, boolean staticOnly ) throws UtilEvalError { try { return resolveExpectedJavaField( clas, fieldName, staticOnly ); } catch ( ReflectError e ) { return null; } }
[ "protected", "static", "Invocable", "resolveJavaField", "(", "Class", "<", "?", ">", "clas", ",", "String", "fieldName", ",", "boolean", "staticOnly", ")", "throws", "UtilEvalError", "{", "try", "{", "return", "resolveExpectedJavaField", "(", "clas", ",", "field...
/* Note: this method and resolveExpectedJavaField should be rewritten to invert this logic so that no exceptions need to be caught unecessarily. This is just a temporary impl. @return the field or null if not found
[ "/", "*", "Note", ":", "this", "method", "and", "resolveExpectedJavaField", "should", "be", "rewritten", "to", "invert", "this", "logic", "so", "that", "no", "exceptions", "need", "to", "be", "caught", "unecessarily", ".", "This", "is", "just", "a", "tempora...
train
https://github.com/beanshell/beanshell/blob/fdddee3de948c9e6babb2d1337028f6fd0a2ba5c/src/main/java/bsh/Reflect.java#L257-L265
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java
Shape.getOffsetUnsafe
public static long getOffsetUnsafe(DataBuffer shapeInformation, int dim0, int dim1, int dim2) { """ Identical to {@link Shape#getOffset(DataBuffer, int, int, int)} but without input validation on array rank """ long offset = 0; int size_0 = sizeUnsafe(shapeInformation, 0); int size_1 = sizeUnsafe(shapeInformation, 1); int size_2 = sizeUnsafe(shapeInformation, 2); if (dim0 >= size_0 || dim1 >= size_1 || dim2 >= size_2) throw new IllegalArgumentException("Invalid indices: cannot get [" + dim0 + "," + dim1 + "," + dim2 + "] from a " + Arrays.toString(shape(shapeInformation)) + " NDArray"); if (size_0 != 1) offset += dim0 * strideUnsafe(shapeInformation, 0, 3); if (size_1 != 1) offset += dim1 * strideUnsafe(shapeInformation, 1, 3); if (size_2 != 1) offset += dim2 * strideUnsafe(shapeInformation, 2, 3); return offset; }
java
public static long getOffsetUnsafe(DataBuffer shapeInformation, int dim0, int dim1, int dim2) { long offset = 0; int size_0 = sizeUnsafe(shapeInformation, 0); int size_1 = sizeUnsafe(shapeInformation, 1); int size_2 = sizeUnsafe(shapeInformation, 2); if (dim0 >= size_0 || dim1 >= size_1 || dim2 >= size_2) throw new IllegalArgumentException("Invalid indices: cannot get [" + dim0 + "," + dim1 + "," + dim2 + "] from a " + Arrays.toString(shape(shapeInformation)) + " NDArray"); if (size_0 != 1) offset += dim0 * strideUnsafe(shapeInformation, 0, 3); if (size_1 != 1) offset += dim1 * strideUnsafe(shapeInformation, 1, 3); if (size_2 != 1) offset += dim2 * strideUnsafe(shapeInformation, 2, 3); return offset; }
[ "public", "static", "long", "getOffsetUnsafe", "(", "DataBuffer", "shapeInformation", ",", "int", "dim0", ",", "int", "dim1", ",", "int", "dim2", ")", "{", "long", "offset", "=", "0", ";", "int", "size_0", "=", "sizeUnsafe", "(", "shapeInformation", ",", "...
Identical to {@link Shape#getOffset(DataBuffer, int, int, int)} but without input validation on array rank
[ "Identical", "to", "{" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/shape/Shape.java#L1128-L1145
alkacon/opencms-core
src/org/opencms/util/CmsXmlSaxWriter.java
CmsXmlSaxWriter.resolveName
private String resolveName(String localName, String qualifiedName) { """ Resolves the local vs. the qualified name.<p> If the local name is the empty String "", the qualified name is used.<p> @param localName the local name @param qualifiedName the qualified XML 1.0 name @return the resolved name to use """ if ((localName == null) || (localName.length() == 0)) { return qualifiedName; } else { return localName; } }
java
private String resolveName(String localName, String qualifiedName) { if ((localName == null) || (localName.length() == 0)) { return qualifiedName; } else { return localName; } }
[ "private", "String", "resolveName", "(", "String", "localName", ",", "String", "qualifiedName", ")", "{", "if", "(", "(", "localName", "==", "null", ")", "||", "(", "localName", ".", "length", "(", ")", "==", "0", ")", ")", "{", "return", "qualifiedName"...
Resolves the local vs. the qualified name.<p> If the local name is the empty String "", the qualified name is used.<p> @param localName the local name @param qualifiedName the qualified XML 1.0 name @return the resolved name to use
[ "Resolves", "the", "local", "vs", ".", "the", "qualified", "name", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsXmlSaxWriter.java#L420-L427
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseScsr2csr_compress
public static int cusparseScsr2csr_compress( cusparseHandle handle, int m, int n, cusparseMatDescr descrA, Pointer csrSortedValA, Pointer csrSortedColIndA, Pointer csrSortedRowPtrA, int nnzA, Pointer nnzPerRow, Pointer csrSortedValC, Pointer csrSortedColIndC, Pointer csrSortedRowPtrC, float tol) { """ Description: This routine takes as input a csr form and compresses it to return a compressed csr form """ return checkResult(cusparseScsr2csr_compressNative(handle, m, n, descrA, csrSortedValA, csrSortedColIndA, csrSortedRowPtrA, nnzA, nnzPerRow, csrSortedValC, csrSortedColIndC, csrSortedRowPtrC, tol)); }
java
public static int cusparseScsr2csr_compress( cusparseHandle handle, int m, int n, cusparseMatDescr descrA, Pointer csrSortedValA, Pointer csrSortedColIndA, Pointer csrSortedRowPtrA, int nnzA, Pointer nnzPerRow, Pointer csrSortedValC, Pointer csrSortedColIndC, Pointer csrSortedRowPtrC, float tol) { return checkResult(cusparseScsr2csr_compressNative(handle, m, n, descrA, csrSortedValA, csrSortedColIndA, csrSortedRowPtrA, nnzA, nnzPerRow, csrSortedValC, csrSortedColIndC, csrSortedRowPtrC, tol)); }
[ "public", "static", "int", "cusparseScsr2csr_compress", "(", "cusparseHandle", "handle", ",", "int", "m", ",", "int", "n", ",", "cusparseMatDescr", "descrA", ",", "Pointer", "csrSortedValA", ",", "Pointer", "csrSortedColIndA", ",", "Pointer", "csrSortedRowPtrA", ","...
Description: This routine takes as input a csr form and compresses it to return a compressed csr form
[ "Description", ":", "This", "routine", "takes", "as", "input", "a", "csr", "form", "and", "compresses", "it", "to", "return", "a", "compressed", "csr", "form" ]
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L11039-L11055
sebastiangraf/jSCSI
bundles/commons/src/main/java/org/jscsi/parser/BasicHeaderSegment.java
BasicHeaderSegment.setOperationCode
final void setOperationCode (final ProtocolDataUnit protocolDataUnit, final OperationCode initOperationCode) { """ Set a new operation code for this BHS object. @param protocolDataUnit The reference <code>ProtocolDataUnit</code> instance, which contains this <code>BasicHeaderSegment</code> object. @param initOperationCode The new operation code. """ operationCode = initOperationCode; parser = MessageParserFactory.getParser(protocolDataUnit, initOperationCode); }
java
final void setOperationCode (final ProtocolDataUnit protocolDataUnit, final OperationCode initOperationCode) { operationCode = initOperationCode; parser = MessageParserFactory.getParser(protocolDataUnit, initOperationCode); }
[ "final", "void", "setOperationCode", "(", "final", "ProtocolDataUnit", "protocolDataUnit", ",", "final", "OperationCode", "initOperationCode", ")", "{", "operationCode", "=", "initOperationCode", ";", "parser", "=", "MessageParserFactory", ".", "getParser", "(", "protoc...
Set a new operation code for this BHS object. @param protocolDataUnit The reference <code>ProtocolDataUnit</code> instance, which contains this <code>BasicHeaderSegment</code> object. @param initOperationCode The new operation code.
[ "Set", "a", "new", "operation", "code", "for", "this", "BHS", "object", "." ]
train
https://github.com/sebastiangraf/jSCSI/blob/6169bfe73f0b15de7d6485453555389e782ae888/bundles/commons/src/main/java/org/jscsi/parser/BasicHeaderSegment.java#L340-L344
astrapi69/jaulp-wicket
jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java
WicketComponentExtensions.getParameter
@Deprecated public static String getParameter(final Request request, final String parameterName) { """ Gets the parameter value from given parameter name. Looks in the query and post parameters. @param request the request @param parameterName the parameter name @return the parameter value @deprecated use instead {@link PageParametersExtensions#getParameter(Request, String)} """ return PageParametersExtensions.getParameter(request, parameterName); }
java
@Deprecated public static String getParameter(final Request request, final String parameterName) { return PageParametersExtensions.getParameter(request, parameterName); }
[ "@", "Deprecated", "public", "static", "String", "getParameter", "(", "final", "Request", "request", ",", "final", "String", "parameterName", ")", "{", "return", "PageParametersExtensions", ".", "getParameter", "(", "request", ",", "parameterName", ")", ";", "}" ]
Gets the parameter value from given parameter name. Looks in the query and post parameters. @param request the request @param parameterName the parameter name @return the parameter value @deprecated use instead {@link PageParametersExtensions#getParameter(Request, String)}
[ "Gets", "the", "parameter", "value", "from", "given", "parameter", "name", ".", "Looks", "in", "the", "query", "and", "post", "parameters", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-base/src/main/java/de/alpharogroup/wicket/base/util/WicketComponentExtensions.java#L187-L191
jmxtrans/embedded-jmxtrans
src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java
ResultNameStrategy.resolveExpression
public String resolveExpression(String expression) { """ Replace all the '#' based keywords (e.g. <code>#hostname#</code>) by their value. @param expression the expression to resolve (e.g. <code>"servers.#hostname#."</code>) @return the resolved expression (e.g. <code>"servers.tomcat5"</code>) """ StringBuilder result = new StringBuilder(expression.length()); int position = 0; while (position < expression.length()) { char c = expression.charAt(position); if (c == '#') { int beginningSeparatorPosition = position; int endingSeparatorPosition = expression.indexOf('#', beginningSeparatorPosition + 1); if (endingSeparatorPosition == -1) { throw new IllegalStateException("Invalid expression '" + expression + "', no ending '#' after beginning '#' at position " + beginningSeparatorPosition); } String key = expression.substring(beginningSeparatorPosition + 1, endingSeparatorPosition); Callable<String> expressionProcessor = expressionEvaluators.get(key); String value; if (expressionProcessor == null) { value = "#unsupported_expression#"; logger.info("Unsupported expression '" + key + "'"); } else { try { value = expressionProcessor.call(); } catch (Exception e) { value = "#expression_error#"; logger.warn("Error evaluating expression '" + key + "'", e); } } appendEscapedNonAlphaNumericChars(value, false, result); position = endingSeparatorPosition + 1; } else { result.append(c); position++; } } logger.trace("resolveExpression({}): {}", expression, result); return result.toString(); }
java
public String resolveExpression(String expression) { StringBuilder result = new StringBuilder(expression.length()); int position = 0; while (position < expression.length()) { char c = expression.charAt(position); if (c == '#') { int beginningSeparatorPosition = position; int endingSeparatorPosition = expression.indexOf('#', beginningSeparatorPosition + 1); if (endingSeparatorPosition == -1) { throw new IllegalStateException("Invalid expression '" + expression + "', no ending '#' after beginning '#' at position " + beginningSeparatorPosition); } String key = expression.substring(beginningSeparatorPosition + 1, endingSeparatorPosition); Callable<String> expressionProcessor = expressionEvaluators.get(key); String value; if (expressionProcessor == null) { value = "#unsupported_expression#"; logger.info("Unsupported expression '" + key + "'"); } else { try { value = expressionProcessor.call(); } catch (Exception e) { value = "#expression_error#"; logger.warn("Error evaluating expression '" + key + "'", e); } } appendEscapedNonAlphaNumericChars(value, false, result); position = endingSeparatorPosition + 1; } else { result.append(c); position++; } } logger.trace("resolveExpression({}): {}", expression, result); return result.toString(); }
[ "public", "String", "resolveExpression", "(", "String", "expression", ")", "{", "StringBuilder", "result", "=", "new", "StringBuilder", "(", "expression", ".", "length", "(", ")", ")", ";", "int", "position", "=", "0", ";", "while", "(", "position", "<", "...
Replace all the '#' based keywords (e.g. <code>#hostname#</code>) by their value. @param expression the expression to resolve (e.g. <code>"servers.#hostname#."</code>) @return the resolved expression (e.g. <code>"servers.tomcat5"</code>)
[ "Replace", "all", "the", "#", "based", "keywords", "(", "e", ".", "g", ".", "<code", ">", "#hostname#<", "/", "code", ">", ")", "by", "their", "value", "." ]
train
https://github.com/jmxtrans/embedded-jmxtrans/blob/17224389e7d8323284cabc2a5167fc03bed6d223/src/main/java/org/jmxtrans/embedded/ResultNameStrategy.java#L158-L195
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java
SearchIndex.createSynonymProviderConfigResource
protected InputStream createSynonymProviderConfigResource() throws IOException { """ Creates a file system resource to the synonym provider configuration. @return a file system resource or <code>null</code> if no path was configured. @throws IOException if an exception occurs accessing the file system. """ if (synonymProviderConfigPath != null) { InputStream fsr; // simple sanity check String separator = PrivilegedSystemHelper.getProperty("file.separator"); if (synonymProviderConfigPath.endsWith(PrivilegedSystemHelper.getProperty("file.separator"))) { throw new IOException("Invalid synonymProviderConfigPath: " + synonymProviderConfigPath); } if (cfm == null) { int lastSeparator = synonymProviderConfigPath.lastIndexOf(separator); if (lastSeparator != -1) { File root = new File(path, synonymProviderConfigPath.substring(0, lastSeparator)); fsr = new BufferedInputStream(PrivilegedFileHelper.fileInputStream(new File(root, synonymProviderConfigPath .substring(lastSeparator + 1)))); } else { fsr = new BufferedInputStream(PrivilegedFileHelper.fileInputStream(new File(synonymProviderConfigPath))); } synonymProviderConfigFs = fsr; } else { try { fsr = cfm.getInputStream(synonymProviderConfigPath); } catch (Exception e) { throw new IOException(e.getLocalizedMessage(), e); } } return fsr; } else { // path not configured return null; } }
java
protected InputStream createSynonymProviderConfigResource() throws IOException { if (synonymProviderConfigPath != null) { InputStream fsr; // simple sanity check String separator = PrivilegedSystemHelper.getProperty("file.separator"); if (synonymProviderConfigPath.endsWith(PrivilegedSystemHelper.getProperty("file.separator"))) { throw new IOException("Invalid synonymProviderConfigPath: " + synonymProviderConfigPath); } if (cfm == null) { int lastSeparator = synonymProviderConfigPath.lastIndexOf(separator); if (lastSeparator != -1) { File root = new File(path, synonymProviderConfigPath.substring(0, lastSeparator)); fsr = new BufferedInputStream(PrivilegedFileHelper.fileInputStream(new File(root, synonymProviderConfigPath .substring(lastSeparator + 1)))); } else { fsr = new BufferedInputStream(PrivilegedFileHelper.fileInputStream(new File(synonymProviderConfigPath))); } synonymProviderConfigFs = fsr; } else { try { fsr = cfm.getInputStream(synonymProviderConfigPath); } catch (Exception e) { throw new IOException(e.getLocalizedMessage(), e); } } return fsr; } else { // path not configured return null; } }
[ "protected", "InputStream", "createSynonymProviderConfigResource", "(", ")", "throws", "IOException", "{", "if", "(", "synonymProviderConfigPath", "!=", "null", ")", "{", "InputStream", "fsr", ";", "// simple sanity check", "String", "separator", "=", "PrivilegedSystemHel...
Creates a file system resource to the synonym provider configuration. @return a file system resource or <code>null</code> if no path was configured. @throws IOException if an exception occurs accessing the file system.
[ "Creates", "a", "file", "system", "resource", "to", "the", "synonym", "provider", "configuration", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/SearchIndex.java#L2019-L2066
Impetus/Kundera
src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java
MongoDBClient.instantiateEntity
private Object instantiateEntity(Class entityClass, Object entity) { """ Instantiate entity. @param entityClass the entity class @param entity the entity @return the object """ if (entity == null) { return KunderaCoreUtils.createNewInstance(entityClass); } return entity; }
java
private Object instantiateEntity(Class entityClass, Object entity) { if (entity == null) { return KunderaCoreUtils.createNewInstance(entityClass); } return entity; }
[ "private", "Object", "instantiateEntity", "(", "Class", "entityClass", ",", "Object", "entity", ")", "{", "if", "(", "entity", "==", "null", ")", "{", "return", "KunderaCoreUtils", ".", "createNewInstance", "(", "entityClass", ")", ";", "}", "return", "entity"...
Instantiate entity. @param entityClass the entity class @param entity the entity @return the object
[ "Instantiate", "entity", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-mongo/src/main/java/com/impetus/client/mongodb/MongoDBClient.java#L443-L450
podio/podio-java
src/main/java/com/podio/tag/TagAPI.java
TagAPI.getTagsOnApp
public List<TagCount> getTagsOnApp(int appId, int limit, String text) { """ Returns the tags on the given app. This includes only items. The tags are ordered firstly by the number of uses, secondly by the tag text. @param appId The id of the app to return tags from @param limit limit on number of tags returned (max 250) @param text text of tag to search for @return The list of tags with their count """ MultivaluedMap<String, String> params=new MultivaluedMapImpl(); params.add("limit", new Integer(limit).toString()); if ((text != null) && (!text.isEmpty())) { params.add("text", text); } return getTagsOnApp(appId, params); }
java
public List<TagCount> getTagsOnApp(int appId, int limit, String text) { MultivaluedMap<String, String> params=new MultivaluedMapImpl(); params.add("limit", new Integer(limit).toString()); if ((text != null) && (!text.isEmpty())) { params.add("text", text); } return getTagsOnApp(appId, params); }
[ "public", "List", "<", "TagCount", ">", "getTagsOnApp", "(", "int", "appId", ",", "int", "limit", ",", "String", "text", ")", "{", "MultivaluedMap", "<", "String", ",", "String", ">", "params", "=", "new", "MultivaluedMapImpl", "(", ")", ";", "params", "...
Returns the tags on the given app. This includes only items. The tags are ordered firstly by the number of uses, secondly by the tag text. @param appId The id of the app to return tags from @param limit limit on number of tags returned (max 250) @param text text of tag to search for @return The list of tags with their count
[ "Returns", "the", "tags", "on", "the", "given", "app", ".", "This", "includes", "only", "items", ".", "The", "tags", "are", "ordered", "firstly", "by", "the", "number", "of", "uses", "secondly", "by", "the", "tag", "text", "." ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/tag/TagAPI.java#L140-L147