repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
196
func_name
stringlengths
7
107
whole_func_string
stringlengths
76
3.82k
language
stringclasses
1 value
func_code_string
stringlengths
76
3.82k
func_code_tokens
listlengths
22
717
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
508
split_name
stringclasses
1 value
func_code_url
stringlengths
111
310
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputStream.java
DerInputStream.getLength
static int getLength(int lenByte, InputStream in) throws IOException { int value, tmp; tmp = lenByte; if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum value = tmp; } else { // long form or indefinite tmp &= 0x07f; /* * NOTE: tmp == 0 indicates indefinite length encoded data. * tmp > 4 indicates more than 4Gb of data. */ if (tmp == 0) return -1; if (tmp < 0 || tmp > 4) throw new IOException("DerInputStream.getLength(): lengthTag=" + tmp + ", " + ((tmp < 0) ? "incorrect DER encoding." : "too big.")); for (value = 0; tmp > 0; tmp --) { value <<= 8; value += 0x0ff & in.read(); } if (value < 0) { throw new IOException("DerInputStream.getLength(): " + "Invalid length bytes"); } } return value; }
java
static int getLength(int lenByte, InputStream in) throws IOException { int value, tmp; tmp = lenByte; if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum value = tmp; } else { // long form or indefinite tmp &= 0x07f; /* * NOTE: tmp == 0 indicates indefinite length encoded data. * tmp > 4 indicates more than 4Gb of data. */ if (tmp == 0) return -1; if (tmp < 0 || tmp > 4) throw new IOException("DerInputStream.getLength(): lengthTag=" + tmp + ", " + ((tmp < 0) ? "incorrect DER encoding." : "too big.")); for (value = 0; tmp > 0; tmp --) { value <<= 8; value += 0x0ff & in.read(); } if (value < 0) { throw new IOException("DerInputStream.getLength(): " + "Invalid length bytes"); } } return value; }
[ "static", "int", "getLength", "(", "int", "lenByte", ",", "InputStream", "in", ")", "throws", "IOException", "{", "int", "value", ",", "tmp", ";", "tmp", "=", "lenByte", ";", "if", "(", "(", "tmp", "&", "0x080", ")", "==", "0x00", ")", "{", "// short...
/* Get a length from the input stream, allowing for at most 32 bits of encoding to be used. (Not the same as getting a tagged integer!) @return the length or -1 if indefinite length found. @exception IOException on parsing error or unsupported lengths.
[ "/", "*", "Get", "a", "length", "from", "the", "input", "stream", "allowing", "for", "at", "most", "32", "bits", "of", "encoding", "to", "be", "used", ".", "(", "Not", "the", "same", "as", "getting", "a", "tagged", "integer!", ")" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/security/util/DerInputStream.java#L583-L613
gosu-lang/gosu-lang
gosu-core/src/main/java/gw/internal/gosu/parser/ParseTree.java
ParseTree.setParent
public void setParent( IParseTree l ) { if( l != null && !l.contains( this ) && getLength() > 0 ) { throw new IllegalArgumentException( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." ); } if( _pe != null ) { ParsedElement parentElement = (ParsedElement)_pe.getParent(); if( parentElement != null ) { ParseTree oldParent = parentElement.getLocation(); if( oldParent != null ) { oldParent._children.remove( this ); } } _pe.setParent( l == null ? null : ((ParseTree)l)._pe ); } }
java
public void setParent( IParseTree l ) { if( l != null && !l.contains( this ) && getLength() > 0 ) { throw new IllegalArgumentException( "Attempted set the parent location, but the parent location's area is not a superset of this location's area." ); } if( _pe != null ) { ParsedElement parentElement = (ParsedElement)_pe.getParent(); if( parentElement != null ) { ParseTree oldParent = parentElement.getLocation(); if( oldParent != null ) { oldParent._children.remove( this ); } } _pe.setParent( l == null ? null : ((ParseTree)l)._pe ); } }
[ "public", "void", "setParent", "(", "IParseTree", "l", ")", "{", "if", "(", "l", "!=", "null", "&&", "!", "l", ".", "contains", "(", "this", ")", "&&", "getLength", "(", ")", ">", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Att...
Sets the parent location. Note the parent location must cover a superset of the specified location's area. @param l The parent location.
[ "Sets", "the", "parent", "location", ".", "Note", "the", "parent", "location", "must", "cover", "a", "superset", "of", "the", "specified", "location", "s", "area", "." ]
train
https://github.com/gosu-lang/gosu-lang/blob/d6e9261b137ce66fef3726cabe7826d4a1f946b7/gosu-core/src/main/java/gw/internal/gosu/parser/ParseTree.java#L373-L392
ebean-orm/querybean-agent-now-merged-into-ebean-agent-
src/main/java/io/ebean/typequery/agent/ClassInfo.java
ClassInfo.addField
public void addField(int access, String name, String desc, String signature) { if (((access & Opcodes.ACC_PUBLIC) != 0)) { if (fields == null) { fields = new ArrayList<>(); } if ((access & Opcodes.ACC_STATIC) == 0) { fields.add(new FieldInfo(this, name, desc, signature)); } } }
java
public void addField(int access, String name, String desc, String signature) { if (((access & Opcodes.ACC_PUBLIC) != 0)) { if (fields == null) { fields = new ArrayList<>(); } if ((access & Opcodes.ACC_STATIC) == 0) { fields.add(new FieldInfo(this, name, desc, signature)); } } }
[ "public", "void", "addField", "(", "int", "access", ",", "String", "name", ",", "String", "desc", ",", "String", "signature", ")", "{", "if", "(", "(", "(", "access", "&", "Opcodes", ".", "ACC_PUBLIC", ")", "!=", "0", ")", ")", "{", "if", "(", "fie...
Add the type query bean field. We will create a 'property access' method for each field.
[ "Add", "the", "type", "query", "bean", "field", ".", "We", "will", "create", "a", "property", "access", "method", "for", "each", "field", "." ]
train
https://github.com/ebean-orm/querybean-agent-now-merged-into-ebean-agent-/blob/a063554fabdbed15ff5e10ad0a0b53b67e039006/src/main/java/io/ebean/typequery/agent/ClassInfo.java#L103-L113
redkale/redkale
src/org/redkale/convert/json/JsonByteBufferWriter.java
JsonByteBufferWriter.writeTo
@Override public void writeTo(final boolean quote, final String value) { char[] chs = Utility.charArray(value); writeTo(-1, quote, chs, 0, chs.length); }
java
@Override public void writeTo(final boolean quote, final String value) { char[] chs = Utility.charArray(value); writeTo(-1, quote, chs, 0, chs.length); }
[ "@", "Override", "public", "void", "writeTo", "(", "final", "boolean", "quote", ",", "final", "String", "value", ")", "{", "char", "[", "]", "chs", "=", "Utility", ".", "charArray", "(", "value", ")", ";", "writeTo", "(", "-", "1", ",", "quote", ",",...
<b>注意:</b> 该String值不能为null且不会进行转义, 只用于不含需要转义字符的字符串,例如enum、double、BigInteger转换的String @param quote 是否写入双引号 @param value String值
[ "<b", ">", "注意:<", "/", "b", ">", "该String值不能为null且不会进行转义,", "只用于不含需要转义字符的字符串,例如enum、double、BigInteger转换的String" ]
train
https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/convert/json/JsonByteBufferWriter.java#L240-L244
contentful/contentful-management.java
src/main/java/com/contentful/java/cma/model/CMAWebhook.java
CMAWebhook.setBasicAuthorization
public CMAWebhook setBasicAuthorization(String user, String password) { this.user = user; this.password = password; return this; }
java
public CMAWebhook setBasicAuthorization(String user, String password) { this.user = user; this.password = password; return this; }
[ "public", "CMAWebhook", "setBasicAuthorization", "(", "String", "user", ",", "String", "password", ")", "{", "this", ".", "user", "=", "user", ";", "this", ".", "password", "=", "password", ";", "return", "this", ";", "}" ]
Set authorization parameter for basic HTTP authorization on the url to be called by this webhook. @param user username to be used @param password password to be used (cannot be retrieved, only updated!) @return this webhook for chaining.
[ "Set", "authorization", "parameter", "for", "basic", "HTTP", "authorization", "on", "the", "url", "to", "be", "called", "by", "this", "webhook", "." ]
train
https://github.com/contentful/contentful-management.java/blob/ca310fb9ea9577fcff0ca57949ab7c2315fa2534/src/main/java/com/contentful/java/cma/model/CMAWebhook.java#L132-L136
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java
MutableRoaringBitmap.flip
@Deprecated public void flip(final int rangeStart, final int rangeEnd) { if (rangeStart >= 0) { flip((long) rangeStart, (long) rangeEnd); } else { // rangeStart being -ve and rangeEnd being positive is not expected) // so assume both -ve flip(rangeStart & 0xFFFFFFFFL, rangeEnd & 0xFFFFFFFFL); } }
java
@Deprecated public void flip(final int rangeStart, final int rangeEnd) { if (rangeStart >= 0) { flip((long) rangeStart, (long) rangeEnd); } else { // rangeStart being -ve and rangeEnd being positive is not expected) // so assume both -ve flip(rangeStart & 0xFFFFFFFFL, rangeEnd & 0xFFFFFFFFL); } }
[ "@", "Deprecated", "public", "void", "flip", "(", "final", "int", "rangeStart", ",", "final", "int", "rangeEnd", ")", "{", "if", "(", "rangeStart", ">=", "0", ")", "{", "flip", "(", "(", "long", ")", "rangeStart", ",", "(", "long", ")", "rangeEnd", "...
Modifies the current bitmap by complementing the bits in the given range, from rangeStart (inclusive) rangeEnd (exclusive). @param rangeStart inclusive beginning of range @param rangeEnd exclusive ending of range @deprecated use the version where longs specify the range
[ "Modifies", "the", "current", "bitmap", "by", "complementing", "the", "bits", "in", "the", "given", "range", "from", "rangeStart", "(", "inclusive", ")", "rangeEnd", "(", "exclusive", ")", "." ]
train
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/buffer/MutableRoaringBitmap.java#L1081-L1090
phax/ph-oton
ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload5/FineUploader5DeleteFile.java
FineUploader5DeleteFile.addParam
@Nonnull public FineUploader5DeleteFile addParam (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue) { ValueEnforcer.notEmpty (sKey, "Key"); ValueEnforcer.notNull (sValue, "Value"); m_aDeleteFileParams.put (sKey, sValue); return this; }
java
@Nonnull public FineUploader5DeleteFile addParam (@Nonnull @Nonempty final String sKey, @Nonnull final String sValue) { ValueEnforcer.notEmpty (sKey, "Key"); ValueEnforcer.notNull (sValue, "Value"); m_aDeleteFileParams.put (sKey, sValue); return this; }
[ "@", "Nonnull", "public", "FineUploader5DeleteFile", "addParam", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sKey", ",", "@", "Nonnull", "final", "String", "sValue", ")", "{", "ValueEnforcer", ".", "notEmpty", "(", "sKey", ",", "\"Key\"", ")", ...
Any additional parameters to attach to delete file requests. @param sKey Parameter name @param sValue Parameter value @return this
[ "Any", "additional", "parameters", "to", "attach", "to", "delete", "file", "requests", "." ]
train
https://github.com/phax/ph-oton/blob/f3aaacbbc02a9f3e4f32fe8db8e4adf7b9c1d3ef/ph-oton-uictrls/src/main/java/com/helger/photon/uictrls/fineupload5/FineUploader5DeleteFile.java#L213-L221
yasserg/crawler4j
crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java
WebCrawler.onUnhandledException
protected void onUnhandledException(WebURL webUrl, Throwable e) { if (myController.getConfig().isHaltOnError() && !(e instanceof IOException)) { throw new RuntimeException("unhandled exception", e); } else { String urlStr = (webUrl == null ? "NULL" : webUrl.getURL()); logger.warn("Unhandled exception while fetching {}: {}", urlStr, e.getMessage()); logger.info("Stacktrace: ", e); // Do nothing by default (except basic logging) // Sub-classed can override this to add their custom functionality } }
java
protected void onUnhandledException(WebURL webUrl, Throwable e) { if (myController.getConfig().isHaltOnError() && !(e instanceof IOException)) { throw new RuntimeException("unhandled exception", e); } else { String urlStr = (webUrl == null ? "NULL" : webUrl.getURL()); logger.warn("Unhandled exception while fetching {}: {}", urlStr, e.getMessage()); logger.info("Stacktrace: ", e); // Do nothing by default (except basic logging) // Sub-classed can override this to add their custom functionality } }
[ "protected", "void", "onUnhandledException", "(", "WebURL", "webUrl", ",", "Throwable", "e", ")", "{", "if", "(", "myController", ".", "getConfig", "(", ")", ".", "isHaltOnError", "(", ")", "&&", "!", "(", "e", "instanceof", "IOException", ")", ")", "{", ...
This function is called when a unhandled exception was encountered during fetching @param webUrl URL where a unhandled exception occured
[ "This", "function", "is", "called", "when", "a", "unhandled", "exception", "was", "encountered", "during", "fetching" ]
train
https://github.com/yasserg/crawler4j/blob/4fcddc86414d1831973aff94050af55c7aeff3bc/crawler4j/src/main/java/edu/uci/ics/crawler4j/crawler/WebCrawler.java#L266-L276
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java
Mac.doFinal
public final void doFinal(byte[] output, int outOffset) throws ShortBufferException, IllegalStateException { chooseFirstProvider(); if (initialized == false) { throw new IllegalStateException("MAC not initialized"); } int macLen = getMacLength(); if (output == null || output.length-outOffset < macLen) { throw new ShortBufferException ("Cannot store MAC in output buffer"); } byte[] mac = doFinal(); System.arraycopy(mac, 0, output, outOffset, macLen); return; }
java
public final void doFinal(byte[] output, int outOffset) throws ShortBufferException, IllegalStateException { chooseFirstProvider(); if (initialized == false) { throw new IllegalStateException("MAC not initialized"); } int macLen = getMacLength(); if (output == null || output.length-outOffset < macLen) { throw new ShortBufferException ("Cannot store MAC in output buffer"); } byte[] mac = doFinal(); System.arraycopy(mac, 0, output, outOffset, macLen); return; }
[ "public", "final", "void", "doFinal", "(", "byte", "[", "]", "output", ",", "int", "outOffset", ")", "throws", "ShortBufferException", ",", "IllegalStateException", "{", "chooseFirstProvider", "(", ")", ";", "if", "(", "initialized", "==", "false", ")", "{", ...
Finishes the MAC operation. <p>A call to this method resets this <code>Mac</code> object to the state it was in when previously initialized via a call to <code>init(Key)</code> or <code>init(Key, AlgorithmParameterSpec)</code>. That is, the object is reset and available to generate another MAC from the same key, if desired, via new calls to <code>update</code> and <code>doFinal</code>. (In order to reuse this <code>Mac</code> object with a different key, it must be reinitialized via a call to <code>init(Key)</code> or <code>init(Key, AlgorithmParameterSpec)</code>. <p>The MAC result is stored in <code>output</code>, starting at <code>outOffset</code> inclusive. @param output the buffer where the MAC result is stored @param outOffset the offset in <code>output</code> where the MAC is stored @exception ShortBufferException if the given output buffer is too small to hold the result @exception IllegalStateException if this <code>Mac</code> has not been initialized.
[ "Finishes", "the", "MAC", "operation", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/javax/crypto/Mac.java#L649-L664
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/utils/FileUtils.java
FileUtils.fileRename
public static void fileRename(final File file, final String newPath, final Class clazz) { File newDestFile = new File(newPath); File lockFile = new File(newDestFile.getAbsolutePath() + ".lock"); try { synchronized (clazz) { FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); FileLock lock = channel.lock(); try { try { // Create parent directory structure if necessary FileUtils.mkParentDirs(newDestFile); Files.move(file.toPath(), newDestFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ioe) { throw new CoreException("Unable to move file " + file + " to destination " + newDestFile + ": " + ioe.getMessage()); } } finally { lock.release(); channel.close(); } } } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(System.err); throw new CoreException("Unable to rename file: " + e.getMessage(), e); } }
java
public static void fileRename(final File file, final String newPath, final Class clazz) { File newDestFile = new File(newPath); File lockFile = new File(newDestFile.getAbsolutePath() + ".lock"); try { synchronized (clazz) { FileChannel channel = new RandomAccessFile(lockFile, "rw").getChannel(); FileLock lock = channel.lock(); try { try { // Create parent directory structure if necessary FileUtils.mkParentDirs(newDestFile); Files.move(file.toPath(), newDestFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ioe) { throw new CoreException("Unable to move file " + file + " to destination " + newDestFile + ": " + ioe.getMessage()); } } finally { lock.release(); channel.close(); } } } catch (IOException e) { System.err.println("IOException: " + e.getMessage()); e.printStackTrace(System.err); throw new CoreException("Unable to rename file: " + e.getMessage(), e); } }
[ "public", "static", "void", "fileRename", "(", "final", "File", "file", ",", "final", "String", "newPath", ",", "final", "Class", "clazz", ")", "{", "File", "newDestFile", "=", "new", "File", "(", "newPath", ")", ";", "File", "lockFile", "=", "new", "Fil...
Rename a file. Uses Java's nio library to use a lock. @param file File to rename @param newPath Path for new file name @param clazz Class associated with lock @throws com.dtolabs.rundeck.core.CoreException A CoreException is raised if any underlying I/O operation fails.
[ "Rename", "a", "file", ".", "Uses", "Java", "s", "nio", "library", "to", "use", "a", "lock", "." ]
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/utils/FileUtils.java#L121-L148
mikepenz/FastAdapter
library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java
FastAdapter.notifyAdapterItemRangeChanged
public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } }
java
public void notifyAdapterItemRangeChanged(int position, int itemCount, @Nullable Object payload) { // handle our extensions for (IAdapterExtension<Item> ext : mExtensions.values()) { ext.notifyAdapterItemRangeChanged(position, itemCount, payload); } if (payload == null) { notifyItemRangeChanged(position, itemCount); } else { notifyItemRangeChanged(position, itemCount, payload); } }
[ "public", "void", "notifyAdapterItemRangeChanged", "(", "int", "position", ",", "int", "itemCount", ",", "@", "Nullable", "Object", "payload", ")", "{", "// handle our extensions", "for", "(", "IAdapterExtension", "<", "Item", ">", "ext", ":", "mExtensions", ".", ...
wraps notifyItemRangeChanged @param position the global position @param itemCount the count of items changed @param payload an additional payload
[ "wraps", "notifyItemRangeChanged" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library-core/src/main/java/com/mikepenz/fastadapter/FastAdapter.java#L1363-L1373
opencb/biodata
biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java
ChunkFrequencyManager.cleanConnectionClose
private void cleanConnectionClose(Connection connection, Statement stmt) { try { // clean close if (connection != null) { connection.rollback(); } if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e1) { e1.printStackTrace(); } }
java
private void cleanConnectionClose(Connection connection, Statement stmt) { try { // clean close if (connection != null) { connection.rollback(); } if (stmt != null) { stmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e1) { e1.printStackTrace(); } }
[ "private", "void", "cleanConnectionClose", "(", "Connection", "connection", ",", "Statement", "stmt", ")", "{", "try", "{", "// clean close", "if", "(", "connection", "!=", "null", ")", "{", "connection", ".", "rollback", "(", ")", ";", "}", "if", "(", "st...
Close connection and sql statement in a clean way. @param connection Connection to close. @param stmt Statement to close.
[ "Close", "connection", "and", "sql", "statement", "in", "a", "clean", "way", "." ]
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-tools/src/main/java/org/opencb/biodata/tools/commons/ChunkFrequencyManager.java#L532-L549
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/Validate.java
Validate.validIndex
public static <T> T[] validIndex(final T[] array, final int index) { return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); }
java
public static <T> T[] validIndex(final T[] array, final int index) { return validIndex(array, index, DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE, Integer.valueOf(index)); }
[ "public", "static", "<", "T", ">", "T", "[", "]", "validIndex", "(", "final", "T", "[", "]", "array", ",", "final", "int", "index", ")", "{", "return", "validIndex", "(", "array", ",", "index", ",", "DEFAULT_VALID_INDEX_ARRAY_EX_MESSAGE", ",", "Integer", ...
<p>Validates that the index is within the bounds of the argument array; otherwise throwing an exception.</p> <pre>Validate.validIndex(myArray, 2);</pre> <p>If the array is {@code null}, then the message of the exception is &quot;The validated object is null&quot;.</p> <p>If the index is invalid, then the message of the exception is &quot;The validated array index is invalid: &quot; followed by the index.</p> @param <T> the array type @param array the array to check, validated not null by this method @param index the index to check @return the validated array (never {@code null} for method chaining) @throws NullPointerException if the array is {@code null} @throws IndexOutOfBoundsException if the index is invalid @see #validIndex(Object[], int, String, Object...) @since 3.0
[ "<p", ">", "Validates", "that", "the", "index", "is", "within", "the", "bounds", "of", "the", "argument", "array", ";", "otherwise", "throwing", "an", "exception", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/Validate.java#L668-L670
spotbugs/spotbugs
eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java
MarkerUtil.redisplayMarkers
public static void redisplayMarkers(final IJavaProject javaProject) { final IProject project = javaProject.getProject(); FindBugsJob job = new FindBugsJob("Refreshing SpotBugs markers", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { // TODO in case we removed some of previously available // detectors, we should // throw away bugs reported by them // Get the saved bug collection for the project SortedBugCollection bugs = FindbugsPlugin.getBugCollection(project, monitor); // Remove old markers project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE); // Display warnings createMarkers(javaProject, bugs, project, monitor); } }; job.setRule(project); job.scheduleInteractive(); }
java
public static void redisplayMarkers(final IJavaProject javaProject) { final IProject project = javaProject.getProject(); FindBugsJob job = new FindBugsJob("Refreshing SpotBugs markers", project) { @Override protected void runWithProgress(IProgressMonitor monitor) throws CoreException { // TODO in case we removed some of previously available // detectors, we should // throw away bugs reported by them // Get the saved bug collection for the project SortedBugCollection bugs = FindbugsPlugin.getBugCollection(project, monitor); // Remove old markers project.deleteMarkers(FindBugsMarker.NAME, true, IResource.DEPTH_INFINITE); // Display warnings createMarkers(javaProject, bugs, project, monitor); } }; job.setRule(project); job.scheduleInteractive(); }
[ "public", "static", "void", "redisplayMarkers", "(", "final", "IJavaProject", "javaProject", ")", "{", "final", "IProject", "project", "=", "javaProject", ".", "getProject", "(", ")", ";", "FindBugsJob", "job", "=", "new", "FindBugsJob", "(", "\"Refreshing SpotBug...
Attempt to redisplay FindBugs problem markers for given project. @param javaProject the project
[ "Attempt", "to", "redisplay", "FindBugs", "problem", "markers", "for", "given", "project", "." ]
train
https://github.com/spotbugs/spotbugs/blob/f6365c6eea6515035bded38efa4a7c8b46ccf28c/eclipsePlugin/src/de/tobject/findbugs/reporter/MarkerUtil.java#L552-L571
Azure/azure-sdk-for-java
batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java
TasksImpl.listSubtasks
public CloudTaskListSubtasksResult listSubtasks(String jobId, String taskId, TaskListSubtasksOptions taskListSubtasksOptions) { return listSubtasksWithServiceResponseAsync(jobId, taskId, taskListSubtasksOptions).toBlocking().single().body(); }
java
public CloudTaskListSubtasksResult listSubtasks(String jobId, String taskId, TaskListSubtasksOptions taskListSubtasksOptions) { return listSubtasksWithServiceResponseAsync(jobId, taskId, taskListSubtasksOptions).toBlocking().single().body(); }
[ "public", "CloudTaskListSubtasksResult", "listSubtasks", "(", "String", "jobId", ",", "String", "taskId", ",", "TaskListSubtasksOptions", "taskListSubtasksOptions", ")", "{", "return", "listSubtasksWithServiceResponseAsync", "(", "jobId", ",", "taskId", ",", "taskListSubtas...
Lists all of the subtasks that are associated with the specified multi-instance task. If the task is not a multi-instance task then this returns an empty collection. @param jobId The ID of the job. @param taskId The ID of the task. @param taskListSubtasksOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @throws BatchErrorException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the CloudTaskListSubtasksResult object if successful.
[ "Lists", "all", "of", "the", "subtasks", "that", "are", "associated", "with", "the", "specified", "multi", "-", "instance", "task", ".", "If", "the", "task", "is", "not", "a", "multi", "-", "instance", "task", "then", "this", "returns", "an", "empty", "c...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/TasksImpl.java#L1719-L1721
xvik/dropwizard-guicey
src/main/java/ru/vyarus/dropwizard/guice/module/installer/feature/jersey/AbstractJerseyInstaller.java
AbstractJerseyInstaller.isLazy
protected boolean isLazy(final Class<?> type, final boolean lazy) { if (isHkExtension(type) && lazy) { logger.warn("@LazyBinding is ignored, because @HK2Managed set: {}", type.getName()); return false; } return lazy; }
java
protected boolean isLazy(final Class<?> type, final boolean lazy) { if (isHkExtension(type) && lazy) { logger.warn("@LazyBinding is ignored, because @HK2Managed set: {}", type.getName()); return false; } return lazy; }
[ "protected", "boolean", "isLazy", "(", "final", "Class", "<", "?", ">", "type", ",", "final", "boolean", "lazy", ")", "{", "if", "(", "isHkExtension", "(", "type", ")", "&&", "lazy", ")", "{", "logger", ".", "warn", "(", "\"@LazyBinding is ignored, because...
Checks if lazy flag could be counted (only when extension is managed by guice). Prints warning in case of incorrect lazy marker usage. @param type extension type @param lazy lazy marker (annotation presence) @return lazy marker if guice managed type and false when hk managed.
[ "Checks", "if", "lazy", "flag", "could", "be", "counted", "(", "only", "when", "extension", "is", "managed", "by", "guice", ")", ".", "Prints", "warning", "in", "case", "of", "incorrect", "lazy", "marker", "usage", "." ]
train
https://github.com/xvik/dropwizard-guicey/blob/dd39ad77283555be21f606d5ebf0f11207a733d4/src/main/java/ru/vyarus/dropwizard/guice/module/installer/feature/jersey/AbstractJerseyInstaller.java#L41-L47
apache/groovy
subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java
AstBuilder.visitGstring
@Override public GStringExpression visitGstring(GstringContext ctx) { final List<ConstantExpression> stringLiteralList = new LinkedList<>(); final String begin = ctx.GStringBegin().getText(); final String beginQuotation = beginQuotation(begin); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringBegin(ctx, beginQuotation)), ctx.GStringBegin())); List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> configureAST(new ConstantExpression(parseGStringPart(e, beginQuotation)), e)) .collect(Collectors.toList()); stringLiteralList.addAll(partStrings); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringEnd(ctx, beginQuotation)), ctx.GStringEnd())); List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !hasArrow(e)) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().noneMatch(DefaultGroovyMethods::asBoolean)) { return configureAST(new ConstantExpression(null), e); } return configureAST(this.createCallMethodCallExpression(expression, new ArgumentListExpression(), true), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = stringLiteralList.size(), s = values.size(); i < n; i++) { verbatimText.append(stringLiteralList.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return configureAST(new GStringExpression(verbatimText.toString(), stringLiteralList, values), ctx); }
java
@Override public GStringExpression visitGstring(GstringContext ctx) { final List<ConstantExpression> stringLiteralList = new LinkedList<>(); final String begin = ctx.GStringBegin().getText(); final String beginQuotation = beginQuotation(begin); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringBegin(ctx, beginQuotation)), ctx.GStringBegin())); List<ConstantExpression> partStrings = ctx.GStringPart().stream() .map(e -> configureAST(new ConstantExpression(parseGStringPart(e, beginQuotation)), e)) .collect(Collectors.toList()); stringLiteralList.addAll(partStrings); stringLiteralList.add(configureAST(new ConstantExpression(parseGStringEnd(ctx, beginQuotation)), ctx.GStringEnd())); List<Expression> values = ctx.gstringValue().stream() .map(e -> { Expression expression = this.visitGstringValue(e); if (expression instanceof ClosureExpression && !hasArrow(e)) { List<Statement> statementList = ((BlockStatement) ((ClosureExpression) expression).getCode()).getStatements(); if (statementList.stream().noneMatch(DefaultGroovyMethods::asBoolean)) { return configureAST(new ConstantExpression(null), e); } return configureAST(this.createCallMethodCallExpression(expression, new ArgumentListExpression(), true), e); } return expression; }) .collect(Collectors.toList()); StringBuilder verbatimText = new StringBuilder(ctx.getText().length()); for (int i = 0, n = stringLiteralList.size(), s = values.size(); i < n; i++) { verbatimText.append(stringLiteralList.get(i).getValue()); if (i == s) { continue; } Expression value = values.get(i); if (!asBoolean(value)) { continue; } verbatimText.append(DOLLAR_STR); verbatimText.append(value.getText()); } return configureAST(new GStringExpression(verbatimText.toString(), stringLiteralList, values), ctx); }
[ "@", "Override", "public", "GStringExpression", "visitGstring", "(", "GstringContext", "ctx", ")", "{", "final", "List", "<", "ConstantExpression", ">", "stringLiteralList", "=", "new", "LinkedList", "<>", "(", ")", ";", "final", "String", "begin", "=", "ctx", ...
gstring { --------------------------------------------------------------------
[ "gstring", "{", "--------------------------------------------------------------------" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/parser-antlr4/src/main/java/org/apache/groovy/parser/antlr4/AstBuilder.java#L3568-L3619
looly/hutool
hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java
ServletUtil.write
public static void write(HttpServletResponse response, File file) { final String fileName = file.getName(); final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream"); BufferedInputStream in = null; try { in = FileUtil.getInputStream(file); write(response, in, contentType, fileName); } finally { IoUtil.close(in); } }
java
public static void write(HttpServletResponse response, File file) { final String fileName = file.getName(); final String contentType = ObjectUtil.defaultIfNull(FileUtil.getMimeType(fileName), "application/octet-stream"); BufferedInputStream in = null; try { in = FileUtil.getInputStream(file); write(response, in, contentType, fileName); } finally { IoUtil.close(in); } }
[ "public", "static", "void", "write", "(", "HttpServletResponse", "response", ",", "File", "file", ")", "{", "final", "String", "fileName", "=", "file", ".", "getName", "(", ")", ";", "final", "String", "contentType", "=", "ObjectUtil", ".", "defaultIfNull", ...
返回文件给客户端 @param response 响应对象{@link HttpServletResponse} @param file 写出的文件对象 @since 4.1.15
[ "返回文件给客户端" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-extra/src/main/java/cn/hutool/extra/servlet/ServletUtil.java#L501-L511
LearnLib/automatalib
util/src/main/java/net/automatalib/util/minimizer/BlockMap.java
BlockMap.put
@Override public V put(Block<?, ?> block, V value) { @SuppressWarnings("unchecked") V old = (V) storage[block.getId()]; storage[block.getId()] = value; return old; }
java
@Override public V put(Block<?, ?> block, V value) { @SuppressWarnings("unchecked") V old = (V) storage[block.getId()]; storage[block.getId()] = value; return old; }
[ "@", "Override", "public", "V", "put", "(", "Block", "<", "?", ",", "?", ">", "block", ",", "V", "value", ")", "{", "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "V", "old", "=", "(", "V", ")", "storage", "[", "block", ".", "getId", "(", ")...
Stores a value. @param block the associated block. @param value the value.
[ "Stores", "a", "value", "." ]
train
https://github.com/LearnLib/automatalib/blob/8a462ec52f6eaab9f8996e344f2163a72cb8aa6e/util/src/main/java/net/automatalib/util/minimizer/BlockMap.java#L70-L76
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java
CPInstancePersistenceImpl.findByC_NotST
@Override public List<CPInstance> findByC_NotST(long CPDefinitionId, int status, int start, int end) { return findByC_NotST(CPDefinitionId, status, start, end, null); }
java
@Override public List<CPInstance> findByC_NotST(long CPDefinitionId, int status, int start, int end) { return findByC_NotST(CPDefinitionId, status, start, end, null); }
[ "@", "Override", "public", "List", "<", "CPInstance", ">", "findByC_NotST", "(", "long", "CPDefinitionId", ",", "int", "status", ",", "int", "start", ",", "int", "end", ")", "{", "return", "findByC_NotST", "(", "CPDefinitionId", ",", "status", ",", "start", ...
Returns a range of all the cp instances where CPDefinitionId = &#63; and status &ne; &#63;. <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 CPInstanceModelImpl}. 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 CPDefinitionId the cp definition ID @param status the status @param start the lower bound of the range of cp instances @param end the upper bound of the range of cp instances (not inclusive) @return the range of matching cp instances
[ "Returns", "a", "range", "of", "all", "the", "cp", "instances", "where", "CPDefinitionId", "=", "&#63", ";", "and", "status", "&ne", ";", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPInstancePersistenceImpl.java#L5146-L5150
alkacon/opencms-core
src/org/opencms/xml/containerpage/CmsXmlContainerPage.java
CmsXmlContainerPage.createContainerPageXml
public byte[] createContainerPageXml(CmsObject cms, CmsContainerPageBean cntPage) throws CmsException { // make sure all links are validated writeContainerPage(cms, cntPage); checkLinkConcistency(cms); return marshal(); }
java
public byte[] createContainerPageXml(CmsObject cms, CmsContainerPageBean cntPage) throws CmsException { // make sure all links are validated writeContainerPage(cms, cntPage); checkLinkConcistency(cms); return marshal(); }
[ "public", "byte", "[", "]", "createContainerPageXml", "(", "CmsObject", "cms", ",", "CmsContainerPageBean", "cntPage", ")", "throws", "CmsException", "{", "// make sure all links are validated", "writeContainerPage", "(", "cms", ",", "cntPage", ")", ";", "checkLinkConci...
Saves a container page bean to the in-memory XML structure and returns the changed content.<p> @param cms the current CMS context @param cntPage the container page bean @return the new content for the container page @throws CmsException if something goes wrong
[ "Saves", "a", "container", "page", "bean", "to", "the", "in", "-", "memory", "XML", "structure", "and", "returns", "the", "changed", "content", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/xml/containerpage/CmsXmlContainerPage.java#L225-L232
kuali/ojb-1.0.4
src/java/org/apache/ojb/odmg/TransactionImpl.java
TransactionImpl.setCascadingDelete
public void setCascadingDelete(Class target, boolean doCascade) { ClassDescriptor cld = getBroker().getClassDescriptor(target); List extents = cld.getExtentClasses(); Boolean result = doCascade ? Boolean.TRUE : Boolean.FALSE; setCascadingDelete(cld, result); if(extents != null && extents.size() > 0) { for(int i = 0; i < extents.size(); i++) { Class extent = (Class) extents.get(i); ClassDescriptor tmp = getBroker().getClassDescriptor(extent); setCascadingDelete(tmp, result); } } }
java
public void setCascadingDelete(Class target, boolean doCascade) { ClassDescriptor cld = getBroker().getClassDescriptor(target); List extents = cld.getExtentClasses(); Boolean result = doCascade ? Boolean.TRUE : Boolean.FALSE; setCascadingDelete(cld, result); if(extents != null && extents.size() > 0) { for(int i = 0; i < extents.size(); i++) { Class extent = (Class) extents.get(i); ClassDescriptor tmp = getBroker().getClassDescriptor(extent); setCascadingDelete(tmp, result); } } }
[ "public", "void", "setCascadingDelete", "(", "Class", "target", ",", "boolean", "doCascade", ")", "{", "ClassDescriptor", "cld", "=", "getBroker", "(", ")", ".", "getClassDescriptor", "(", "target", ")", ";", "List", "extents", "=", "cld", ".", "getExtentClass...
Allows to change the <em>cascading delete</em> behavior of all references of the specified class while this transaction is in use - if the specified class is an interface, abstract class or class with "extent" classes the cascading flag will be propagated. @param target The class to change cascading delete behavior of all references. @param doCascade If <em>true</em> cascading delete is enabled, <em>false</em> disabled.
[ "Allows", "to", "change", "the", "<em", ">", "cascading", "delete<", "/", "em", ">", "behavior", "of", "all", "references", "of", "the", "specified", "class", "while", "this", "transaction", "is", "in", "use", "-", "if", "the", "specified", "class", "is", ...
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/odmg/TransactionImpl.java#L1420-L1435
orbisgis/h2gis
h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java
KMLWriterDriver.writeExtendedData
public void writeExtendedData(XMLStreamWriter xmlOut, ResultSet rs) throws XMLStreamException, SQLException { xmlOut.writeStartElement("ExtendedData"); xmlOut.writeStartElement("SchemaData"); xmlOut.writeAttribute("schemaUrl", "#" + tableName); for (Map.Entry<Integer, String> entry : kmlFields.entrySet()) { Integer fieldIndex = entry.getKey(); String fieldName = entry.getValue(); writeSimpleData(xmlOut, fieldName, rs.getString(fieldIndex)); } xmlOut.writeEndElement();//Write SchemaData xmlOut.writeEndElement();//Write ExtendedData }
java
public void writeExtendedData(XMLStreamWriter xmlOut, ResultSet rs) throws XMLStreamException, SQLException { xmlOut.writeStartElement("ExtendedData"); xmlOut.writeStartElement("SchemaData"); xmlOut.writeAttribute("schemaUrl", "#" + tableName); for (Map.Entry<Integer, String> entry : kmlFields.entrySet()) { Integer fieldIndex = entry.getKey(); String fieldName = entry.getValue(); writeSimpleData(xmlOut, fieldName, rs.getString(fieldIndex)); } xmlOut.writeEndElement();//Write SchemaData xmlOut.writeEndElement();//Write ExtendedData }
[ "public", "void", "writeExtendedData", "(", "XMLStreamWriter", "xmlOut", ",", "ResultSet", "rs", ")", "throws", "XMLStreamException", ",", "SQLException", "{", "xmlOut", ".", "writeStartElement", "(", "\"ExtendedData\"", ")", ";", "xmlOut", ".", "writeStartElement", ...
The ExtendedData element offers three techniques for adding custom data to a KML Feature (NetworkLink, Placemark, GroundOverlay, PhotoOverlay, ScreenOverlay, Document, Folder). These techniques are Adding untyped data/value pairs using the <Data> element (basic) Declaring new typed fields using the <Schema> element and then instancing them using the <SchemaData> element (advanced) Referring to XML elements defined in other namespaces by referencing the external namespace within the KML file (basic) These techniques can be combined within a single KML file or Feature for different pieces of data. Syntax : <ExtendedData> <Data name="string"> <displayName>...</displayName> <!-- string --> <value>...</value> <!-- string --> </Data> <SchemaData schemaUrl="anyURI"> <SimpleData name=""> ... </SimpleData> <!-- string --> </SchemaData> <namespace_prefix:other>...</namespace_prefix:other> </ExtendedData> @param xmlOut
[ "The", "ExtendedData", "element", "offers", "three", "techniques", "for", "adding", "custom", "data", "to", "a", "KML", "Feature", "(", "NetworkLink", "Placemark", "GroundOverlay", "PhotoOverlay", "ScreenOverlay", "Document", "Folder", ")", ".", "These", "techniques...
train
https://github.com/orbisgis/h2gis/blob/9cd70b447e6469cecbc2fc64b16774b59491df3b/h2gis-functions/src/main/java/org/h2gis/functions/io/kml/KMLWriterDriver.java#L344-L356
citiususc/hipster
hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/MazeSearch.java
MazeSearch.getMazeStringSolution
public static String getMazeStringSolution(Maze2D maze, Collection<Point> explored, Collection<Point> path) { List<Map<Point, Character>> replacements = new ArrayList<Map<Point, Character>>(); Map<Point, Character> replacement = new HashMap<Point, Character>(); for (Point p : explored) { replacement.put(p, '.'); } replacements.add(replacement); replacement = new HashMap<Point, Character>(); for (Point p : path) { replacement.put(p, '*'); } replacements.add(replacement); return maze.getReplacedMazeString(replacements); }
java
public static String getMazeStringSolution(Maze2D maze, Collection<Point> explored, Collection<Point> path) { List<Map<Point, Character>> replacements = new ArrayList<Map<Point, Character>>(); Map<Point, Character> replacement = new HashMap<Point, Character>(); for (Point p : explored) { replacement.put(p, '.'); } replacements.add(replacement); replacement = new HashMap<Point, Character>(); for (Point p : path) { replacement.put(p, '*'); } replacements.add(replacement); return maze.getReplacedMazeString(replacements); }
[ "public", "static", "String", "getMazeStringSolution", "(", "Maze2D", "maze", ",", "Collection", "<", "Point", ">", "explored", ",", "Collection", "<", "Point", ">", "path", ")", "{", "List", "<", "Map", "<", "Point", ",", "Character", ">", ">", "replaceme...
Returns the maze passed as parameter but replacing some characters to print the path found in the current iteration. @param maze used to search @param explored collection of the points of the maze explored by the iterator @param path current path found by the iterator @return maze with the characters of the explored points and the current path replaced, to print the results in the console
[ "Returns", "the", "maze", "passed", "as", "parameter", "but", "replacing", "some", "characters", "to", "print", "the", "path", "found", "in", "the", "current", "iteration", "." ]
train
https://github.com/citiususc/hipster/blob/9ab1236abb833a27641ae73ba9ca890d5c17598e/hipster-core/src/main/java/es/usc/citius/hipster/util/examples/maze/MazeSearch.java#L134-L147
samskivert/pythagoras
src/main/java/pythagoras/d/Rectangles.java
Rectangles.pointRectDistance
public static double pointRectDistance (IRectangle r, IPoint p) { return Math.sqrt(pointRectDistanceSq(r, p)); }
java
public static double pointRectDistance (IRectangle r, IPoint p) { return Math.sqrt(pointRectDistanceSq(r, p)); }
[ "public", "static", "double", "pointRectDistance", "(", "IRectangle", "r", ",", "IPoint", "p", ")", "{", "return", "Math", ".", "sqrt", "(", "pointRectDistanceSq", "(", "r", ",", "p", ")", ")", ";", "}" ]
Returns the Euclidean distance between the given point and the nearest point inside the bounds of the given rectangle. If the supplied point is inside the rectangle, the distance will be zero.
[ "Returns", "the", "Euclidean", "distance", "between", "the", "given", "point", "and", "the", "nearest", "point", "inside", "the", "bounds", "of", "the", "given", "rectangle", ".", "If", "the", "supplied", "point", "is", "inside", "the", "rectangle", "the", "...
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/d/Rectangles.java#L68-L70
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/base/base_resource.java
base_resource.update_resource
protected base_response update_resource(nitro_service service,options option) throws Exception { if (!service.isLogin() && !this.get_object_type().equals("login")) service.login(); String sessionid = service.get_sessionid(); String request = resource_to_string(service, sessionid, option); return put_data(service,request); }
java
protected base_response update_resource(nitro_service service,options option) throws Exception { if (!service.isLogin() && !this.get_object_type().equals("login")) service.login(); String sessionid = service.get_sessionid(); String request = resource_to_string(service, sessionid, option); return put_data(service,request); }
[ "protected", "base_response", "update_resource", "(", "nitro_service", "service", ",", "options", "option", ")", "throws", "Exception", "{", "if", "(", "!", "service", ".", "isLogin", "(", ")", "&&", "!", "this", ".", "get_object_type", "(", ")", ".", "equal...
Use this method to perform a modify operation on netscaler resource. @param service nitro_service object. @param option options class object. @return status of the operation performed. @throws Exception
[ "Use", "this", "method", "to", "perform", "a", "modify", "operation", "on", "netscaler", "resource", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/base/base_resource.java#L190-L197
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/MatchPatternIterator.java
MatchPatternIterator.acceptNode
public short acceptNode(int n, XPathContext xctxt) { try { xctxt.pushCurrentNode(n); xctxt.pushIteratorRoot(m_context); if(DEBUG) { System.out.println("traverser: "+m_traverser); System.out.print("node: "+n); System.out.println(", "+m_cdtm.getNodeName(n)); // if(m_cdtm.getNodeName(n).equals("near-east")) System.out.println("pattern: "+m_pattern.toString()); m_pattern.debugWhatToShow(m_pattern.getWhatToShow()); } XObject score = m_pattern.execute(xctxt); if(DEBUG) { // System.out.println("analysis: "+Integer.toBinaryString(m_analysis)); System.out.println("score: "+score); System.out.println("skip: "+(score == NodeTest.SCORE_NONE)); } // System.out.println("\n::acceptNode - score: "+score.num()+"::"); return (score == NodeTest.SCORE_NONE) ? DTMIterator.FILTER_SKIP : DTMIterator.FILTER_ACCEPT; } catch (javax.xml.transform.TransformerException se) { // TODO: Fix this. throw new RuntimeException(se.getMessage()); } finally { xctxt.popCurrentNode(); xctxt.popIteratorRoot(); } }
java
public short acceptNode(int n, XPathContext xctxt) { try { xctxt.pushCurrentNode(n); xctxt.pushIteratorRoot(m_context); if(DEBUG) { System.out.println("traverser: "+m_traverser); System.out.print("node: "+n); System.out.println(", "+m_cdtm.getNodeName(n)); // if(m_cdtm.getNodeName(n).equals("near-east")) System.out.println("pattern: "+m_pattern.toString()); m_pattern.debugWhatToShow(m_pattern.getWhatToShow()); } XObject score = m_pattern.execute(xctxt); if(DEBUG) { // System.out.println("analysis: "+Integer.toBinaryString(m_analysis)); System.out.println("score: "+score); System.out.println("skip: "+(score == NodeTest.SCORE_NONE)); } // System.out.println("\n::acceptNode - score: "+score.num()+"::"); return (score == NodeTest.SCORE_NONE) ? DTMIterator.FILTER_SKIP : DTMIterator.FILTER_ACCEPT; } catch (javax.xml.transform.TransformerException se) { // TODO: Fix this. throw new RuntimeException(se.getMessage()); } finally { xctxt.popCurrentNode(); xctxt.popIteratorRoot(); } }
[ "public", "short", "acceptNode", "(", "int", "n", ",", "XPathContext", "xctxt", ")", "{", "try", "{", "xctxt", ".", "pushCurrentNode", "(", "n", ")", ";", "xctxt", ".", "pushIteratorRoot", "(", "m_context", ")", ";", "if", "(", "DEBUG", ")", "{", "Syst...
Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator. This function will be called by the implementation of TreeWalker and NodeIterator; it is not intended to be called directly from user code. @param n The node to check to see if it passes the filter or not. @return a constant to determine whether the node is accepted, rejected, or skipped, as defined above .
[ "Test", "whether", "a", "specified", "node", "is", "visible", "in", "the", "logical", "view", "of", "a", "TreeWalker", "or", "NodeIterator", ".", "This", "function", "will", "be", "called", "by", "the", "implementation", "of", "TreeWalker", "and", "NodeIterato...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/axes/MatchPatternIterator.java#L287-L329
looly/hutool
hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java
BeanUtil.fillBeanWithMap
public static <T> T fillBeanWithMap(Map<?, ?> map, T bean, boolean isToCamelCase, CopyOptions copyOptions) { if (MapUtil.isEmpty(map)) { return bean; } if (isToCamelCase) { map = MapUtil.toCamelCaseMap(map); } return BeanCopier.create(map, bean, copyOptions).copy(); }
java
public static <T> T fillBeanWithMap(Map<?, ?> map, T bean, boolean isToCamelCase, CopyOptions copyOptions) { if (MapUtil.isEmpty(map)) { return bean; } if (isToCamelCase) { map = MapUtil.toCamelCaseMap(map); } return BeanCopier.create(map, bean, copyOptions).copy(); }
[ "public", "static", "<", "T", ">", "T", "fillBeanWithMap", "(", "Map", "<", "?", ",", "?", ">", "map", ",", "T", "bean", ",", "boolean", "isToCamelCase", ",", "CopyOptions", "copyOptions", ")", "{", "if", "(", "MapUtil", ".", "isEmpty", "(", "map", "...
使用Map填充Bean对象 @param <T> Bean类型 @param map Map @param bean Bean @param isToCamelCase 是否将Map中的下划线风格key转换为驼峰风格 @param copyOptions 属性复制选项 {@link CopyOptions} @return Bean @since 3.3.1
[ "使用Map填充Bean对象" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/bean/BeanUtil.java#L423-L431
pravega/pravega
controller/src/main/java/io/pravega/controller/server/SegmentHelper.java
SegmentHelper.readTable
public CompletableFuture<List<TableEntry<byte[], byte[]>>> readTable(final String tableName, final List<TableKey<byte[]>> keys, String delegationToken, final long clientRequestId) { final CompletableFuture<List<TableEntry<byte[], byte[]>>> result = new CompletableFuture<>(); final Controller.NodeUri uri = getTableUri(tableName); final WireCommandType type = WireCommandType.READ_TABLE; final long requestId = (clientRequestId == RequestTag.NON_EXISTENT_ID) ? idGenerator.get() : clientRequestId; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override public void connectionDropped() { log.warn(requestId, "readTable {} Connection dropped", tableName); result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { log.warn(requestId, "readTable {} wrong host", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) { log.warn(requestId, "readTable {} NoSuchSegment", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.SegmentDoesNotExist)); } @Override public void tableRead(WireCommands.TableRead tableRead) { log.debug(requestId, "readTable {} successful.", tableName); List<TableEntry<byte[], byte[]>> tableEntries = tableRead.getEntries().getEntries().stream() .map(e -> new TableEntryImpl<>(convertFromWireCommand(e.getKey()), getArray(e.getValue().getData()))) .collect(Collectors.toList()); result.complete(tableEntries); } @Override public void processingFailure(Exception error) { log.error(requestId, "readTable {} failed", tableName, error); handleError(error, result, type); } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { result.completeExceptionally( new WireCommandFailedException(new AuthenticationException(authTokenCheckFailed.toString()), type, WireCommandFailedException.Reason.AuthFailed)); } }; List<ByteBuf> buffersToRelease = new ArrayList<>(); // the version is always NO_VERSION as read returns the latest version of value. List<WireCommands.TableKey> keyList = keys.stream().map(k -> { ByteBuf buffer = wrappedBuffer(k.getKey()); buffersToRelease.add(buffer); return new WireCommands.TableKey(buffer, WireCommands.TableKey.NO_VERSION); }).collect(Collectors.toList()); WireCommands.ReadTable request = new WireCommands.ReadTable(requestId, tableName, delegationToken, keyList); sendRequestAsync(request, replyProcessor, result, ModelHelper.encode(uri)); return result .whenComplete((r, e) -> release(buffersToRelease)); }
java
public CompletableFuture<List<TableEntry<byte[], byte[]>>> readTable(final String tableName, final List<TableKey<byte[]>> keys, String delegationToken, final long clientRequestId) { final CompletableFuture<List<TableEntry<byte[], byte[]>>> result = new CompletableFuture<>(); final Controller.NodeUri uri = getTableUri(tableName); final WireCommandType type = WireCommandType.READ_TABLE; final long requestId = (clientRequestId == RequestTag.NON_EXISTENT_ID) ? idGenerator.get() : clientRequestId; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override public void connectionDropped() { log.warn(requestId, "readTable {} Connection dropped", tableName); result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { log.warn(requestId, "readTable {} wrong host", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) { log.warn(requestId, "readTable {} NoSuchSegment", tableName); result.completeExceptionally(new WireCommandFailedException(type, WireCommandFailedException.Reason.SegmentDoesNotExist)); } @Override public void tableRead(WireCommands.TableRead tableRead) { log.debug(requestId, "readTable {} successful.", tableName); List<TableEntry<byte[], byte[]>> tableEntries = tableRead.getEntries().getEntries().stream() .map(e -> new TableEntryImpl<>(convertFromWireCommand(e.getKey()), getArray(e.getValue().getData()))) .collect(Collectors.toList()); result.complete(tableEntries); } @Override public void processingFailure(Exception error) { log.error(requestId, "readTable {} failed", tableName, error); handleError(error, result, type); } @Override public void authTokenCheckFailed(WireCommands.AuthTokenCheckFailed authTokenCheckFailed) { result.completeExceptionally( new WireCommandFailedException(new AuthenticationException(authTokenCheckFailed.toString()), type, WireCommandFailedException.Reason.AuthFailed)); } }; List<ByteBuf> buffersToRelease = new ArrayList<>(); // the version is always NO_VERSION as read returns the latest version of value. List<WireCommands.TableKey> keyList = keys.stream().map(k -> { ByteBuf buffer = wrappedBuffer(k.getKey()); buffersToRelease.add(buffer); return new WireCommands.TableKey(buffer, WireCommands.TableKey.NO_VERSION); }).collect(Collectors.toList()); WireCommands.ReadTable request = new WireCommands.ReadTable(requestId, tableName, delegationToken, keyList); sendRequestAsync(request, replyProcessor, result, ModelHelper.encode(uri)); return result .whenComplete((r, e) -> release(buffersToRelease)); }
[ "public", "CompletableFuture", "<", "List", "<", "TableEntry", "<", "byte", "[", "]", ",", "byte", "[", "]", ">", ">", ">", "readTable", "(", "final", "String", "tableName", ",", "final", "List", "<", "TableKey", "<", "byte", "[", "]", ">", ">", "key...
This method sends a WireCommand to read table entries. @param tableName Qualified table name. @param keys List of {@link TableKey}s to be read. {@link TableKey#getVersion()} is not used during this operation and the latest version is read. @param delegationToken The token to be presented to the segmentstore. @param clientRequestId Request id. @return A CompletableFuture that, when completed normally, will contain a list of {@link TableEntry} with a value corresponding to the latest version. The version will be set to {@link KeyVersion#NOT_EXISTS} if the key does not exist. If the operation failed, the future will be failed with the causing exception.
[ "This", "method", "sends", "a", "WireCommand", "to", "read", "table", "entries", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/server/SegmentHelper.java#L946-L1011
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/Workitem.java
Workitem.createEffort
public Effort createEffort(double value, Map<String, Object> attributes) { return createEffort(value, null, null, attributes); }
java
public Effort createEffort(double value, Map<String, Object> attributes) { return createEffort(value, null, null, attributes); }
[ "public", "Effort", "createEffort", "(", "double", "value", ",", "Map", "<", "String", ",", "Object", ">", "attributes", ")", "{", "return", "createEffort", "(", "value", ",", "null", ",", "null", ",", "attributes", ")", ";", "}" ]
Log an effort record against this workitem. @param value of the Effort. @param attributes additional attributes for the Effort record. @return created Effort. @throws IllegalStateException Effort Tracking is not enabled.
[ "Log", "an", "effort", "record", "against", "this", "workitem", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/Workitem.java#L143-L145
reactiverse/reactive-pg-client
src/main/java/io/reactiverse/pgclient/impl/codec/encoder/MessageEncoder.java
MessageEncoder.writeExecute
public void writeExecute(String portal, int rowCount) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(EXECUTE); out.writeInt(0); if (portal != null) { out.writeCharSequence(portal, StandardCharsets.UTF_8); } out.writeByte(0); out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream<Row> out.setInt(pos + 1, out.writerIndex() - pos - 1); }
java
public void writeExecute(String portal, int rowCount) { ensureBuffer(); int pos = out.writerIndex(); out.writeByte(EXECUTE); out.writeInt(0); if (portal != null) { out.writeCharSequence(portal, StandardCharsets.UTF_8); } out.writeByte(0); out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream<Row> out.setInt(pos + 1, out.writerIndex() - pos - 1); }
[ "public", "void", "writeExecute", "(", "String", "portal", ",", "int", "rowCount", ")", "{", "ensureBuffer", "(", ")", ";", "int", "pos", "=", "out", ".", "writerIndex", "(", ")", ";", "out", ".", "writeByte", "(", "EXECUTE", ")", ";", "out", ".", "w...
The message specifies the portal and a maximum row count (zero meaning "fetch all rows") of the result. <p> The row count of the result is only meaningful for portals containing commands that return row sets; in other cases the command is always executed to completion, and the row count of the result is ignored. <p> The possible responses to this message are the same as {@link Query} message, except that it doesn't cause {@link ReadyForQuery} or {@link RowDescription} to be issued. <p> If Execute terminates before completing the execution of a portal, it will send a {@link PortalSuspended} message; the appearance of this message tells the frontend that another Execute should be issued against the same portal to complete the operation. The {@link CommandComplete} message indicating completion of the source SQL command is not sent until the portal's execution is completed. Therefore, This message is always terminated by the appearance of exactly one of these messages: {@link CommandComplete}, {@link EmptyQueryResponse}, {@link ErrorResponse} or {@link PortalSuspended}. @author <a href="mailto:emad.albloushi@gmail.com">Emad Alblueshi</a>
[ "The", "message", "specifies", "the", "portal", "and", "a", "maximum", "row", "count", "(", "zero", "meaning", "fetch", "all", "rows", ")", "of", "the", "result", ".", "<p", ">", "The", "row", "count", "of", "the", "result", "is", "only", "meaningful", ...
train
https://github.com/reactiverse/reactive-pg-client/blob/be75cc5462f0945f81d325f58db5f297403067bf/src/main/java/io/reactiverse/pgclient/impl/codec/encoder/MessageEncoder.java#L256-L267
meraki-analytics/datapipelines-java
src/main/java/com/merakianalytics/datapipelines/DataPipeline.java
DataPipeline.getMany
public <T> CloseableIterator<T> getMany(final Class<T> type, final Map<String, Object> query) { return getMany(type, query, false); }
java
public <T> CloseableIterator<T> getMany(final Class<T> type, final Map<String, Object> query) { return getMany(type, query, false); }
[ "public", "<", "T", ">", "CloseableIterator", "<", "T", ">", "getMany", "(", "final", "Class", "<", "T", ">", "type", ",", "final", "Map", "<", "String", ",", "Object", ">", "query", ")", "{", "return", "getMany", "(", "type", ",", "query", ",", "f...
Gets multiple data elements from the {@link com.merakianalytics.datapipelines.DataPipeline} @param <T> the type of the data that should be retrieved @param type the type of the data that should be retrieved @param query a query specifying the details of what data should fulfill this request @return a {@link com.merakianalytics.datapipelines.iterators.CloseableIterator} of the request type if the query had a result, or null
[ "Gets", "multiple", "data", "elements", "from", "the", "{", "@link", "com", ".", "merakianalytics", ".", "datapipelines", ".", "DataPipeline", "}" ]
train
https://github.com/meraki-analytics/datapipelines-java/blob/376ff1e8e1f7c67f2f2a5521d2a66e91467e56b0/src/main/java/com/merakianalytics/datapipelines/DataPipeline.java#L243-L245
tweea/matrixjavalib-main-common
src/main/java/net/matrix/security/Cryptos.java
Cryptos.aesDecrypt
public static byte[] aesDecrypt(final byte[] input, final byte[] key, final byte[] iv) throws GeneralSecurityException { return aes(input, key, iv, Cipher.DECRYPT_MODE); }
java
public static byte[] aesDecrypt(final byte[] input, final byte[] key, final byte[] iv) throws GeneralSecurityException { return aes(input, key, iv, Cipher.DECRYPT_MODE); }
[ "public", "static", "byte", "[", "]", "aesDecrypt", "(", "final", "byte", "[", "]", "input", ",", "final", "byte", "[", "]", "key", ",", "final", "byte", "[", "]", "iv", ")", "throws", "GeneralSecurityException", "{", "return", "aes", "(", "input", ","...
使用 AES 解密。 @param input 密文 @param key 符合 AES 要求的密钥 @param iv 初始向量 @return 明文 @throws GeneralSecurityException 解密失败
[ "使用", "AES", "解密。" ]
train
https://github.com/tweea/matrixjavalib-main-common/blob/ac8f98322a422e3ef76c3e12d47b98268cec7006/src/main/java/net/matrix/security/Cryptos.java#L192-L195
atomix/catalyst
serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java
Serializer.readByClass
@SuppressWarnings("unchecked") private <T> T readByClass(BufferInput<?> buffer) { String name = buffer.readUTF8(); if (whitelistRequired.get()) throw new SerializationException("cannot deserialize unregistered type: " + name); Class<T> type = (Class<T>) types.get(name); if (type == null) { try { type = (Class<T>) Class.forName(name); if (type == null) throw new SerializationException("cannot deserialize: unknown type"); types.put(name, type); } catch (ClassNotFoundException e) { throw new SerializationException("object class not found: " + name, e); } } TypeSerializer<T> serializer = getSerializer(type); if (serializer == null) throw new SerializationException("cannot deserialize unregistered type: " + name); return serializer.read(type, buffer, this); }
java
@SuppressWarnings("unchecked") private <T> T readByClass(BufferInput<?> buffer) { String name = buffer.readUTF8(); if (whitelistRequired.get()) throw new SerializationException("cannot deserialize unregistered type: " + name); Class<T> type = (Class<T>) types.get(name); if (type == null) { try { type = (Class<T>) Class.forName(name); if (type == null) throw new SerializationException("cannot deserialize: unknown type"); types.put(name, type); } catch (ClassNotFoundException e) { throw new SerializationException("object class not found: " + name, e); } } TypeSerializer<T> serializer = getSerializer(type); if (serializer == null) throw new SerializationException("cannot deserialize unregistered type: " + name); return serializer.read(type, buffer, this); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "<", "T", ">", "T", "readByClass", "(", "BufferInput", "<", "?", ">", "buffer", ")", "{", "String", "name", "=", "buffer", ".", "readUTF8", "(", ")", ";", "if", "(", "whitelistRequired", ".",...
Reads a writable object. @param buffer The buffer from which to read the object. @param <T> The object type. @return The read object.
[ "Reads", "a", "writable", "object", "." ]
train
https://github.com/atomix/catalyst/blob/140e762cb975cd8ee1fd85119043c5b8bf917c5c/serializer/src/main/java/io/atomix/catalyst/serializer/Serializer.java#L1050-L1073
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.findEnclosingNode
@Nullable public static <T> T findEnclosingNode(TreePath path, Class<T> klass) { path = findPathFromEnclosingNodeToTopLevel(path, klass); return (path == null) ? null : klass.cast(path.getLeaf()); }
java
@Nullable public static <T> T findEnclosingNode(TreePath path, Class<T> klass) { path = findPathFromEnclosingNodeToTopLevel(path, klass); return (path == null) ? null : klass.cast(path.getLeaf()); }
[ "@", "Nullable", "public", "static", "<", "T", ">", "T", "findEnclosingNode", "(", "TreePath", "path", ",", "Class", "<", "T", ">", "klass", ")", "{", "path", "=", "findPathFromEnclosingNodeToTopLevel", "(", "path", ",", "klass", ")", ";", "return", "(", ...
Given a TreePath, walks up the tree until it finds a node of the given type. Returns null if no such node is found.
[ "Given", "a", "TreePath", "walks", "up", "the", "tree", "until", "it", "finds", "a", "node", "of", "the", "given", "type", ".", "Returns", "null", "if", "no", "such", "node", "is", "found", "." ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L353-L357
Deep-Symmetry/beat-link
src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java
MetadataFinder.queryMetadata
TrackMetadata queryMetadata(final DataReference track, final CdjStatus.TrackType trackType, final Client client) throws IOException, InterruptedException, TimeoutException { // Send the metadata menu request if (client.tryLockingForMenuOperations(20, TimeUnit.SECONDS)) { try { final Message.KnownType requestType = (trackType == CdjStatus.TrackType.REKORDBOX) ? Message.KnownType.REKORDBOX_METADATA_REQ : Message.KnownType.UNANALYZED_METADATA_REQ; final Message response = client.menuRequestTyped(requestType, Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, new NumberField(track.rekordboxId)); final long count = response.getMenuResultsCount(); if (count == Message.NO_MENU_RESULTS_AVAILABLE) { return null; } // Gather the cue list and all the metadata menu items final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, response); final CueList cueList = getCueList(track.rekordboxId, track.slot, client); return new TrackMetadata(track, trackType, items, cueList); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock the player for menu operations"); } }
java
TrackMetadata queryMetadata(final DataReference track, final CdjStatus.TrackType trackType, final Client client) throws IOException, InterruptedException, TimeoutException { // Send the metadata menu request if (client.tryLockingForMenuOperations(20, TimeUnit.SECONDS)) { try { final Message.KnownType requestType = (trackType == CdjStatus.TrackType.REKORDBOX) ? Message.KnownType.REKORDBOX_METADATA_REQ : Message.KnownType.UNANALYZED_METADATA_REQ; final Message response = client.menuRequestTyped(requestType, Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, new NumberField(track.rekordboxId)); final long count = response.getMenuResultsCount(); if (count == Message.NO_MENU_RESULTS_AVAILABLE) { return null; } // Gather the cue list and all the metadata menu items final List<Message> items = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, track.slot, trackType, response); final CueList cueList = getCueList(track.rekordboxId, track.slot, client); return new TrackMetadata(track, trackType, items, cueList); } finally { client.unlockForMenuOperations(); } } else { throw new TimeoutException("Unable to lock the player for menu operations"); } }
[ "TrackMetadata", "queryMetadata", "(", "final", "DataReference", "track", ",", "final", "CdjStatus", ".", "TrackType", "trackType", ",", "final", "Client", "client", ")", "throws", "IOException", ",", "InterruptedException", ",", "TimeoutException", "{", "// Send the ...
Request metadata for a specific track ID, given a dbserver connection to a player that has already been set up. Separated into its own method so it could be used multiple times with the same connection when gathering all track metadata. @param track uniquely identifies the track whose metadata is desired @param trackType identifies the type of track being requested, which affects the type of metadata request message that must be used @param client the dbserver client that is communicating with the appropriate player @return the retrieved metadata, or {@code null} if there is no such track @throws IOException if there is a communication problem @throws InterruptedException if the thread is interrupted while trying to lock the client for menu operations @throws TimeoutException if we are unable to lock the client for menu operations
[ "Request", "metadata", "for", "a", "specific", "track", "ID", "given", "a", "dbserver", "connection", "to", "a", "player", "that", "has", "already", "been", "set", "up", ".", "Separated", "into", "its", "own", "method", "so", "it", "could", "be", "used", ...
train
https://github.com/Deep-Symmetry/beat-link/blob/f958a2a70e8a87a31a75326d7b4db77c2f0b4212/src/main/java/org/deepsymmetry/beatlink/data/MetadataFinder.java#L150-L175
kiswanij/jk-util
src/main/java/com/jk/util/UserPreferences.java
UserPreferences.getInt
public static int getInt(final String key, final int def) { try { return systemRoot.getInt(fixKey(key), def); } catch (final Exception e) { // just eat the exception to avoid any system crash on system issues return def; } }
java
public static int getInt(final String key, final int def) { try { return systemRoot.getInt(fixKey(key), def); } catch (final Exception e) { // just eat the exception to avoid any system crash on system issues return def; } }
[ "public", "static", "int", "getInt", "(", "final", "String", "key", ",", "final", "int", "def", ")", "{", "try", "{", "return", "systemRoot", ".", "getInt", "(", "fixKey", "(", "key", ")", ",", "def", ")", ";", "}", "catch", "(", "final", "Exception"...
Gets the int. @param key the key @param def the def @return the int @see java.util.prefs.Preferences#getInt(java.lang.String, int)
[ "Gets", "the", "int", "." ]
train
https://github.com/kiswanij/jk-util/blob/8e0c85818423406f769444c76194a748e0a0fc0a/src/main/java/com/jk/util/UserPreferences.java#L153-L160
jmeetsma/Iglu-Util
src/main/java/org/ijsberg/iglu/util/io/BasicChannel.java
BasicChannel.transmit
public synchronized void transmit(Object o, ReceiverQueue t) { if (!closed) { ArrayList<Receiver> toBeRemoved = new ArrayList<Receiver>(); for (Receiver r : receivers) { //cleanup //TODO separate cleanup from transmit // if (r instanceof ReceiverQueue && ((ReceiverQueue)r).isClosed()) { toBeRemoved.add(r); } else { if (echo || r != t) { r.onReceive(o); } } } for (Receiver r : toBeRemoved) { receivers.remove(r); } } }
java
public synchronized void transmit(Object o, ReceiverQueue t) { if (!closed) { ArrayList<Receiver> toBeRemoved = new ArrayList<Receiver>(); for (Receiver r : receivers) { //cleanup //TODO separate cleanup from transmit // if (r instanceof ReceiverQueue && ((ReceiverQueue)r).isClosed()) { toBeRemoved.add(r); } else { if (echo || r != t) { r.onReceive(o); } } } for (Receiver r : toBeRemoved) { receivers.remove(r); } } }
[ "public", "synchronized", "void", "transmit", "(", "Object", "o", ",", "ReceiverQueue", "t", ")", "{", "if", "(", "!", "closed", ")", "{", "ArrayList", "<", "Receiver", ">", "toBeRemoved", "=", "new", "ArrayList", "<", "Receiver", ">", "(", ")", ";", "...
Dispatches an object to all connected receivers. @param o the object to dispatch @param t the transceiver sending the object
[ "Dispatches", "an", "object", "to", "all", "connected", "receivers", "." ]
train
https://github.com/jmeetsma/Iglu-Util/blob/971eb022115247b1e34dc26dd02e7e621e29e910/src/main/java/org/ijsberg/iglu/util/io/BasicChannel.java#L102-L122
zaproxy/zaproxy
src/org/zaproxy/zap/spider/parser/SpiderHtmlFormParser.java
SpiderHtmlFormParser.processGetForm
private void processGetForm(HttpMessage message, int depth, String action, String baseURL, FormData formData) { for (String submitData : formData) { log.debug("Submiting form with GET method and query with form parameters: " + submitData); processURL(message, depth, action + submitData, baseURL); } }
java
private void processGetForm(HttpMessage message, int depth, String action, String baseURL, FormData formData) { for (String submitData : formData) { log.debug("Submiting form with GET method and query with form parameters: " + submitData); processURL(message, depth, action + submitData, baseURL); } }
[ "private", "void", "processGetForm", "(", "HttpMessage", "message", ",", "int", "depth", ",", "String", "action", ",", "String", "baseURL", ",", "FormData", "formData", ")", "{", "for", "(", "String", "submitData", ":", "formData", ")", "{", "log", ".", "d...
Processes the given GET form data into, possibly, several URLs. <p> For each submit field present in the form data is processed one URL, which includes remaining normal fields. @param message the source message @param depth the current depth @param action the action @param baseURL the base URL @param formData the GET form data @see #processURL(HttpMessage, int, String, String)
[ "Processes", "the", "given", "GET", "form", "data", "into", "possibly", "several", "URLs", ".", "<p", ">", "For", "each", "submit", "field", "present", "in", "the", "form", "data", "is", "processed", "one", "URL", "which", "includes", "remaining", "normal", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/spider/parser/SpiderHtmlFormParser.java#L214-L219
lestard/assertj-javafx
src/main/java/eu/lestard/assertj/javafx/api/DoubleBindingAssert.java
DoubleBindingAssert.hasValue
public DoubleBindingAssert hasValue(Double expectedValue, Offset offset){ new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset); return this; }
java
public DoubleBindingAssert hasValue(Double expectedValue, Offset offset){ new ObservableNumberValueAssertions(actual).hasValue(expectedValue, offset); return this; }
[ "public", "DoubleBindingAssert", "hasValue", "(", "Double", "expectedValue", ",", "Offset", "offset", ")", "{", "new", "ObservableNumberValueAssertions", "(", "actual", ")", ".", "hasValue", "(", "expectedValue", ",", "offset", ")", ";", "return", "this", ";", "...
Verifies that the actual observable number has a value that is close to the given one by less then the given offset. @param expectedValue the given value to compare the actual observables value to. @param offset the given positive offset. @return {@code this} assertion object. @throws java.lang.NullPointerException if the given offset is <code>null</code>. @throws java.lang.AssertionError if the actual observables value is not equal to the expected one.
[ "Verifies", "that", "the", "actual", "observable", "number", "has", "a", "value", "that", "is", "close", "to", "the", "given", "one", "by", "less", "then", "the", "given", "offset", "." ]
train
https://github.com/lestard/assertj-javafx/blob/f6b4d22e542a5501c7c1c2fae8700b0f69b956c1/src/main/java/eu/lestard/assertj/javafx/api/DoubleBindingAssert.java#L47-L51
joniles/mpxj
src/main/java/net/sf/mpxj/mpp/PropsBlock.java
PropsBlock.populateMap
private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset) { if (previousItemOffset != null) { int itemSize = itemOffset.intValue() - previousItemOffset.intValue(); byte[] itemData = new byte[itemSize]; System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize); m_map.put(previousItemKey, itemData); } }
java
private void populateMap(byte[] data, Integer previousItemOffset, Integer previousItemKey, Integer itemOffset) { if (previousItemOffset != null) { int itemSize = itemOffset.intValue() - previousItemOffset.intValue(); byte[] itemData = new byte[itemSize]; System.arraycopy(data, previousItemOffset.intValue(), itemData, 0, itemSize); m_map.put(previousItemKey, itemData); } }
[ "private", "void", "populateMap", "(", "byte", "[", "]", "data", ",", "Integer", "previousItemOffset", ",", "Integer", "previousItemKey", ",", "Integer", "itemOffset", ")", "{", "if", "(", "previousItemOffset", "!=", "null", ")", "{", "int", "itemSize", "=", ...
Method used to extract data from the block of properties and insert the key value pair into a map. @param data block of property data @param previousItemOffset previous offset @param previousItemKey item key @param itemOffset current item offset
[ "Method", "used", "to", "extract", "data", "from", "the", "block", "of", "properties", "and", "insert", "the", "key", "value", "pair", "into", "a", "map", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mpp/PropsBlock.java#L83-L92
riversun/d6
src/main/java/org/riversun/d6/core/D6Crud.java
D6Crud.execInsert
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames) { boolean ignoreDuplicate = false; return execInsert(modelObjects, includeExcludeColumnNames, ignoreDuplicate); }
java
public boolean execInsert(D6Model[] modelObjects, D6Inex includeExcludeColumnNames) { boolean ignoreDuplicate = false; return execInsert(modelObjects, includeExcludeColumnNames, ignoreDuplicate); }
[ "public", "boolean", "execInsert", "(", "D6Model", "[", "]", "modelObjects", ",", "D6Inex", "includeExcludeColumnNames", ")", "{", "boolean", "ignoreDuplicate", "=", "false", ";", "return", "execInsert", "(", "modelObjects", ",", "includeExcludeColumnNames", ",", "i...
Insert the specified model object into the DB @param modelObjects @param includeExcludeColumnNames You can select either 'the column name you want to reflected in the database' AND 'the column name you don't want to reflect in the database'. When omitted (null specified) ,reflects all properties in the model class has to be reflected to the database. @return true:DB operation success false:failure
[ "Insert", "the", "specified", "model", "object", "into", "the", "DB" ]
train
https://github.com/riversun/d6/blob/2798bd876b9380dbfea8182d11ad306cb1b0e114/src/main/java/org/riversun/d6/core/D6Crud.java#L507-L510
Stratio/deep-spark
deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java
MongoNativeExtractor.isShardedCollection
private boolean isShardedCollection(DBCollection collection) { DB config = collection.getDB().getMongo().getDB("config"); DBCollection configCollections = config.getCollection("collections"); DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName())); return dbObject != null; }
java
private boolean isShardedCollection(DBCollection collection) { DB config = collection.getDB().getMongo().getDB("config"); DBCollection configCollections = config.getCollection("collections"); DBObject dbObject = configCollections.findOne(new BasicDBObject(MONGO_DEFAULT_ID, collection.getFullName())); return dbObject != null; }
[ "private", "boolean", "isShardedCollection", "(", "DBCollection", "collection", ")", "{", "DB", "config", "=", "collection", ".", "getDB", "(", ")", ".", "getMongo", "(", ")", ".", "getDB", "(", "\"config\"", ")", ";", "DBCollection", "configCollections", "=",...
Is sharded collection. @param collection the collection @return the boolean
[ "Is", "sharded", "collection", "." ]
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-mongodb/src/main/java/com/stratio/deep/mongodb/extractor/MongoNativeExtractor.java#L137-L144
lightblue-platform/lightblue-migrator
facade/src/main/java/com/redhat/lightblue/migrator/facade/ConsistencyChecker.java
ConsistencyChecker.logInconsistency
private void logInconsistency(String parentThreadName, String callToLogInCaseOfInconsistency, String legacyJson, String lightblueJson, String diff) { String logMessage = String.format("[%s] Inconsistency found in %s.%s - diff: %s - legacyJson: %s, lightblueJson: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff, legacyJson, lightblueJson); if (logResponseDataEnabled) { if (logMessage.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(logMessage); } else if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); hugeInconsistencyLog.debug(logMessage); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - payload and diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); hugeInconsistencyLog.debug(logMessage); } } else { if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); } // logData is turned off, log in inconsistency.log for debugging hugeInconsistencyLog.debug(logMessage); } }
java
private void logInconsistency(String parentThreadName, String callToLogInCaseOfInconsistency, String legacyJson, String lightblueJson, String diff) { String logMessage = String.format("[%s] Inconsistency found in %s.%s - diff: %s - legacyJson: %s, lightblueJson: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff, legacyJson, lightblueJson); if (logResponseDataEnabled) { if (logMessage.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(logMessage); } else if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); hugeInconsistencyLog.debug(logMessage); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - payload and diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); hugeInconsistencyLog.debug(logMessage); } } else { if (diff != null && diff.length() <= maxInconsistencyLogLength) { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff: %s", parentThreadName, implementationName, callToLogInCaseOfInconsistency, diff)); } else { inconsistencyLog.warn(String.format("[%s] Inconsistency found in %s.%s - diff is greater than %d bytes!", parentThreadName, implementationName, callToLogInCaseOfInconsistency, maxInconsistencyLogLength)); } // logData is turned off, log in inconsistency.log for debugging hugeInconsistencyLog.debug(logMessage); } }
[ "private", "void", "logInconsistency", "(", "String", "parentThreadName", ",", "String", "callToLogInCaseOfInconsistency", ",", "String", "legacyJson", ",", "String", "lightblueJson", ",", "String", "diff", ")", "{", "String", "logMessage", "=", "String", ".", "form...
/* Log inconsistencies based on following rules: If logResponseDataEnabled=true: - Log message < MAX_INCONSISTENCY_LOG_LENGTH to server.log. - Log message > MAX_INCONSISTENCY_LOG_LENGTH and diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log and full message to inconsistency.log. If logResponseDataEnabled=false: - diff <= MAX_INCONSISTENCY_LOG_LENGTH, log diff to server.log. - Otherwise log method name and parameters to server.log - Always log full message to inconsistency.log Logging inconsistencies at debug level since everything >= info would also appear in server.log
[ "/", "*", "Log", "inconsistencies", "based", "on", "following", "rules", ":" ]
train
https://github.com/lightblue-platform/lightblue-migrator/blob/ec20748557b40d1f7851e1816d1b76dae48d2027/facade/src/main/java/com/redhat/lightblue/migrator/facade/ConsistencyChecker.java#L97-L118
sagiegurari/fax4j
src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java
HylaFaxClientSpi.resumeFaxJobImpl
@Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.resumeFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
java
@Override protected void resumeFaxJobImpl(FaxJob faxJob) { //get fax job HylaFaxJob hylaFaxJob=(HylaFaxJob)faxJob; //get client HylaFAXClient client=this.getHylaFAXClient(); try { this.resumeFaxJob(hylaFaxJob,client); } catch(FaxException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } }
[ "@", "Override", "protected", "void", "resumeFaxJobImpl", "(", "FaxJob", "faxJob", ")", "{", "//get fax job", "HylaFaxJob", "hylaFaxJob", "=", "(", "HylaFaxJob", ")", "faxJob", ";", "//get client", "HylaFAXClient", "client", "=", "this", ".", "getHylaFAXClient", "...
This function will resume an existing fax job. @param faxJob The fax job object containing the needed information
[ "This", "function", "will", "resume", "an", "existing", "fax", "job", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java#L363-L384
albfernandez/itext2
src/main/java/com/lowagie/text/pdf/DefaultFontMapper.java
DefaultFontMapper.insertNames
public void insertNames(Object allNames[], String path) { String names[][] = (String[][])allNames[2]; String main = null; for (int k = 0; k < names.length; ++k) { String name[] = names[k]; if (name[2].equals("1033")) { main = name[3]; break; } } if (main == null) main = names[0][3]; BaseFontParameters p = new BaseFontParameters(path); mapper.put(main, p); for (int k = 0; k < names.length; ++k) { aliases.put(names[k][3], main); } aliases.put(allNames[0], main); }
java
public void insertNames(Object allNames[], String path) { String names[][] = (String[][])allNames[2]; String main = null; for (int k = 0; k < names.length; ++k) { String name[] = names[k]; if (name[2].equals("1033")) { main = name[3]; break; } } if (main == null) main = names[0][3]; BaseFontParameters p = new BaseFontParameters(path); mapper.put(main, p); for (int k = 0; k < names.length; ++k) { aliases.put(names[k][3], main); } aliases.put(allNames[0], main); }
[ "public", "void", "insertNames", "(", "Object", "allNames", "[", "]", ",", "String", "path", ")", "{", "String", "names", "[", "]", "[", "]", "=", "(", "String", "[", "]", "[", "]", ")", "allNames", "[", "2", "]", ";", "String", "main", "=", "nul...
Inserts the names in this map. @param allNames the returned value of calling {@link BaseFont#getAllFontNames(String, String, byte[])} @param path the full path to the font
[ "Inserts", "the", "names", "in", "this", "map", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/DefaultFontMapper.java#L244-L262
cycorp/api-suite
core-api/src/main/java/com/cyc/kb/exception/CreateException.java
CreateException.fromThrowable
public static CreateException fromThrowable(String message, Throwable cause) { return (cause instanceof CreateException && Objects.equals(message, cause.getMessage())) ? (CreateException) cause : new CreateException(message, cause); }
java
public static CreateException fromThrowable(String message, Throwable cause) { return (cause instanceof CreateException && Objects.equals(message, cause.getMessage())) ? (CreateException) cause : new CreateException(message, cause); }
[ "public", "static", "CreateException", "fromThrowable", "(", "String", "message", ",", "Throwable", "cause", ")", "{", "return", "(", "cause", "instanceof", "CreateException", "&&", "Objects", ".", "equals", "(", "message", ",", "cause", ".", "getMessage", "(", ...
Converts a Throwable to a CreateException with the specified detail message. If the Throwable is a CreateException and if the Throwable's message is identical to the one supplied, the Throwable will be passed through unmodified; otherwise, it will be wrapped in a new CreateException with the detail message. @param cause the Throwable to convert @param message the specified detail message @return a CreateException
[ "Converts", "a", "Throwable", "to", "a", "CreateException", "with", "the", "specified", "detail", "message", ".", "If", "the", "Throwable", "is", "a", "CreateException", "and", "if", "the", "Throwable", "s", "message", "is", "identical", "to", "the", "one", ...
train
https://github.com/cycorp/api-suite/blob/1d52affabc4635e3715a059e38741712cbdbf2d5/core-api/src/main/java/com/cyc/kb/exception/CreateException.java#L64-L68
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/util/CollectionUtils.java
CollectionUtils.containsAny
public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){ for(T c: toCheck){ if(collection.contains(c)) return true; } return false; }
java
public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){ for(T c: toCheck){ if(collection.contains(c)) return true; } return false; }
[ "public", "static", "<", "T", ">", "boolean", "containsAny", "(", "Collection", "<", "T", ">", "collection", ",", "Collection", "<", "T", ">", "toCheck", ")", "{", "for", "(", "T", "c", ":", "toCheck", ")", "{", "if", "(", "collection", ".", "contain...
if any item in toCheck is present in collection @param <T> @param collection @param toCheck @return
[ "if", "any", "item", "in", "toCheck", "is", "present", "in", "collection" ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/util/CollectionUtils.java#L757-L764
ltearno/hexa.tools
hexa.core/src/main/java/fr/lteconsulting/hexa/client/datatable/DataTableTools.java
DataTableTools.insertFlatList
public static <T extends IHasIntegerId> void insertFlatList( List<T> list, TableCollectionManager<T> mng, Func1<T, Integer> parentIdGetter ) { HashSet<Integer> inserted = new HashSet<>(); List<T> toInsert = new ArrayList<>( list ); List<T> postPoned = new ArrayList<>(); List<T> inOrder = new ArrayList<>(); int nbInserted; while( ! toInsert.isEmpty() ) { nbInserted = 0; while( ! toInsert.isEmpty() ) { T a = toInsert.remove( 0 ); Integer parentId = parentIdGetter.exec( a ); if( parentId==null || parentId<=0 || inserted.contains( parentId ) || mng.getRowForRecordId( parentId )!=null ) { inOrder.add( a ); inserted.add( a.getId() ); nbInserted++; } else { postPoned.add( a ); } } toInsert = postPoned; postPoned = new ArrayList<>(); if( nbInserted == 0 && ! toInsert.isEmpty() ) { GWT.log("Cannot construct full tree !"); throw new RuntimeException( "Cannot construct full tree !" ); } } for( T t : inOrder ) mng.getDataPlug().updated( t ); }
java
public static <T extends IHasIntegerId> void insertFlatList( List<T> list, TableCollectionManager<T> mng, Func1<T, Integer> parentIdGetter ) { HashSet<Integer> inserted = new HashSet<>(); List<T> toInsert = new ArrayList<>( list ); List<T> postPoned = new ArrayList<>(); List<T> inOrder = new ArrayList<>(); int nbInserted; while( ! toInsert.isEmpty() ) { nbInserted = 0; while( ! toInsert.isEmpty() ) { T a = toInsert.remove( 0 ); Integer parentId = parentIdGetter.exec( a ); if( parentId==null || parentId<=0 || inserted.contains( parentId ) || mng.getRowForRecordId( parentId )!=null ) { inOrder.add( a ); inserted.add( a.getId() ); nbInserted++; } else { postPoned.add( a ); } } toInsert = postPoned; postPoned = new ArrayList<>(); if( nbInserted == 0 && ! toInsert.isEmpty() ) { GWT.log("Cannot construct full tree !"); throw new RuntimeException( "Cannot construct full tree !" ); } } for( T t : inOrder ) mng.getDataPlug().updated( t ); }
[ "public", "static", "<", "T", "extends", "IHasIntegerId", ">", "void", "insertFlatList", "(", "List", "<", "T", ">", "list", ",", "TableCollectionManager", "<", "T", ">", "mng", ",", "Func1", "<", "T", ",", "Integer", ">", "parentIdGetter", ")", "{", "Ha...
Inserts a flat list as a tree in a TableCollectionManager. It does insert data in the right order for the creation of the tree (parents must be inserted first) @param list @param mng @param parentIdGetter
[ "Inserts", "a", "flat", "list", "as", "a", "tree", "in", "a", "TableCollectionManager", ".", "It", "does", "insert", "data", "in", "the", "right", "order", "for", "the", "creation", "of", "the", "tree", "(", "parents", "must", "be", "inserted", "first", ...
train
https://github.com/ltearno/hexa.tools/blob/604c804901b1bb13fe10b3823cc4a639f8993363/hexa.core/src/main/java/fr/lteconsulting/hexa/client/datatable/DataTableTools.java#L27-L69
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/ns/admin_ns_config.java
admin_ns_config.modify
public static admin_ns_config modify(nitro_service client, admin_ns_config resource) throws Exception { resource.validate("modify"); return ((admin_ns_config[]) resource.update_resource(client))[0]; }
java
public static admin_ns_config modify(nitro_service client, admin_ns_config resource) throws Exception { resource.validate("modify"); return ((admin_ns_config[]) resource.update_resource(client))[0]; }
[ "public", "static", "admin_ns_config", "modify", "(", "nitro_service", "client", ",", "admin_ns_config", "resource", ")", "throws", "Exception", "{", "resource", ".", "validate", "(", "\"modify\"", ")", ";", "return", "(", "(", "admin_ns_config", "[", "]", ")", ...
<pre> Use this operation to apply admin configuration on NetScaler Instance. </pre>
[ "<pre", ">", "Use", "this", "operation", "to", "apply", "admin", "configuration", "on", "NetScaler", "Instance", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/ns/admin_ns_config.java#L85-L89
samskivert/samskivert
src/main/java/com/samskivert/servlet/user/UserRepository.java
UserRepository.lookupUsersByEmail
public ArrayList<User> lookupUsersByEmail (String email) throws PersistenceException { return loadAll(_utable, "where email = " + JDBCUtil.escape(email)); }
java
public ArrayList<User> lookupUsersByEmail (String email) throws PersistenceException { return loadAll(_utable, "where email = " + JDBCUtil.escape(email)); }
[ "public", "ArrayList", "<", "User", ">", "lookupUsersByEmail", "(", "String", "email", ")", "throws", "PersistenceException", "{", "return", "loadAll", "(", "_utable", ",", "\"where email = \"", "+", "JDBCUtil", ".", "escape", "(", "email", ")", ")", ";", "}" ...
Lookup a user by email address, something that is not efficient and should really only be done by site admins attempting to look up a user record. @return the user with the specified user id or null if no user with that id exists.
[ "Lookup", "a", "user", "by", "email", "address", "something", "that", "is", "not", "efficient", "and", "should", "really", "only", "be", "done", "by", "site", "admins", "attempting", "to", "look", "up", "a", "user", "record", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/servlet/user/UserRepository.java#L145-L149
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SDVariable.java
SDVariable.lt
public SDVariable lt(String name, SDVariable other){ return sameDiff.lt(name, this, other); }
java
public SDVariable lt(String name, SDVariable other){ return sameDiff.lt(name, this, other); }
[ "public", "SDVariable", "lt", "(", "String", "name", ",", "SDVariable", "other", ")", "{", "return", "sameDiff", ".", "lt", "(", "name", ",", "this", ",", "other", ")", ";", "}" ]
Less than operation: elementwise {@code this < y}<br> If x and y arrays have equal shape, the output shape is the same as the inputs.<br> Supports broadcasting: if x and y have different shapes and are broadcastable, the output shape is broadcast.<br> Returns an array with values 1 where condition is satisfied, or value 0 otherwise. @param name Name of the output variable @param other Variable to compare values against @return Output SDVariable with values 0 (not satisfied) and 1 (where the condition is satisfied)
[ "Less", "than", "operation", ":", "elementwise", "{", "@code", "this", "<", "y", "}", "<br", ">", "If", "x", "and", "y", "arrays", "have", "equal", "shape", "the", "output", "shape", "is", "the", "same", "as", "the", "inputs", ".", "<br", ">", "Suppo...
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SDVariable.java#L504-L506
michael-rapp/AndroidBottomSheet
library/src/main/java/de/mrapp/android/bottomsheet/adapter/DividableGridAdapter.java
DividableGridAdapter.visualizeItem
@SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") private void visualizeItem(@NonNull final Item item, @NonNull final ItemViewHolder viewHolder) { viewHolder.iconImageView.setVisibility(iconCount > 0 ? View.VISIBLE : View.GONE); viewHolder.iconImageView.setEnabled(item.isEnabled()); if (item.getIcon() != null && item.getIcon() instanceof StateListDrawable) { StateListDrawable stateListDrawable = (StateListDrawable) item.getIcon(); try { int[] currentState = viewHolder.iconImageView.getDrawableState(); Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class); Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class); int index = (int) getStateDrawableIndex.invoke(stateListDrawable, currentState); Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable, index); viewHolder.iconImageView.setImageDrawable(drawable); } catch (Exception e) { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } } else { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } viewHolder.titleTextView.setText(item.getTitle()); viewHolder.titleTextView.setEnabled(item.isEnabled()); if (getItemColor() != -1) { viewHolder.titleTextView.setTextColor(getItemColor()); } }
java
@SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") private void visualizeItem(@NonNull final Item item, @NonNull final ItemViewHolder viewHolder) { viewHolder.iconImageView.setVisibility(iconCount > 0 ? View.VISIBLE : View.GONE); viewHolder.iconImageView.setEnabled(item.isEnabled()); if (item.getIcon() != null && item.getIcon() instanceof StateListDrawable) { StateListDrawable stateListDrawable = (StateListDrawable) item.getIcon(); try { int[] currentState = viewHolder.iconImageView.getDrawableState(); Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class); Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class); int index = (int) getStateDrawableIndex.invoke(stateListDrawable, currentState); Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable, index); viewHolder.iconImageView.setImageDrawable(drawable); } catch (Exception e) { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } } else { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } viewHolder.titleTextView.setText(item.getTitle()); viewHolder.titleTextView.setEnabled(item.isEnabled()); if (getItemColor() != -1) { viewHolder.titleTextView.setTextColor(getItemColor()); } }
[ "@", "SuppressWarnings", "(", "\"PrimitiveArrayArgumentToVariableArgMethod\"", ")", "private", "void", "visualizeItem", "(", "@", "NonNull", "final", "Item", "item", ",", "@", "NonNull", "final", "ItemViewHolder", "viewHolder", ")", "{", "viewHolder", ".", "iconImageV...
Visualizes a specific item. @param item The item, which should be visualized, as an instance of the class {@link Item}. The item may not be null @param viewHolder The view holder, which contains the views, which should be used to visualize the item, as an instance of the class {@link ItemViewHolder}. The view holder may not be null
[ "Visualizes", "a", "specific", "item", "." ]
train
https://github.com/michael-rapp/AndroidBottomSheet/blob/6e4690ee9f63b14a7b143d3a3717b5f8a11ca503/library/src/main/java/de/mrapp/android/bottomsheet/adapter/DividableGridAdapter.java#L251-L281
alkacon/opencms-core
src/org/opencms/ade/configuration/CmsADEManager.java
CmsADEManager.saveFavoriteList
public void saveFavoriteList(CmsObject cms, List<CmsContainerElementBean> favoriteList) throws CmsException { saveElementList(cms, favoriteList, ADDINFO_ADE_FAVORITE_LIST); }
java
public void saveFavoriteList(CmsObject cms, List<CmsContainerElementBean> favoriteList) throws CmsException { saveElementList(cms, favoriteList, ADDINFO_ADE_FAVORITE_LIST); }
[ "public", "void", "saveFavoriteList", "(", "CmsObject", "cms", ",", "List", "<", "CmsContainerElementBean", ">", "favoriteList", ")", "throws", "CmsException", "{", "saveElementList", "(", "cms", ",", "favoriteList", ",", "ADDINFO_ADE_FAVORITE_LIST", ")", ";", "}" ]
Saves the favorite list, user based.<p> @param cms the cms context @param favoriteList the element list @throws CmsException if something goes wrong
[ "Saves", "the", "favorite", "list", "user", "based", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsADEManager.java#L1196-L1199
casbin/jcasbin
src/main/java/org/casbin/jcasbin/main/Enforcer.java
Enforcer.hasPermissionForUser
public boolean hasPermissionForUser(String user, List<String> permission) { return hasPermissionForUser(user, permission.toArray(new String[0])); }
java
public boolean hasPermissionForUser(String user, List<String> permission) { return hasPermissionForUser(user, permission.toArray(new String[0])); }
[ "public", "boolean", "hasPermissionForUser", "(", "String", "user", ",", "List", "<", "String", ">", "permission", ")", "{", "return", "hasPermissionForUser", "(", "user", ",", "permission", ".", "toArray", "(", "new", "String", "[", "0", "]", ")", ")", ";...
hasPermissionForUser determines whether a user has a permission. @param user the user. @param permission the permission, usually be (obj, act). It is actually the rule without the subject. @return whether the user has the permission.
[ "hasPermissionForUser", "determines", "whether", "a", "user", "has", "a", "permission", "." ]
train
https://github.com/casbin/jcasbin/blob/b46d7a756b6c39cdb17e0600607e5fcdc66edd11/src/main/java/org/casbin/jcasbin/main/Enforcer.java#L345-L347
RobotiumTech/robotium
robotium-solo/src/main/java/com/robotium/solo/Solo.java
Solo.waitForView
public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForView("+viewClass+", "+minimumNumberOfMatches+", "+timeout+")"); } int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, true); }
java
public <T extends View> boolean waitForView(final Class<T> viewClass, final int minimumNumberOfMatches, final int timeout){ if(config.commandLogging){ Log.d(config.commandLoggingTag, "waitForView("+viewClass+", "+minimumNumberOfMatches+", "+timeout+")"); } int index = minimumNumberOfMatches-1; if(index < 1) index = 0; return waiter.waitForView(viewClass, index, timeout, true); }
[ "public", "<", "T", "extends", "View", ">", "boolean", "waitForView", "(", "final", "Class", "<", "T", ">", "viewClass", ",", "final", "int", "minimumNumberOfMatches", ",", "final", "int", "timeout", ")", "{", "if", "(", "config", ".", "commandLogging", ")...
Waits for a View matching the specified class. @param viewClass the {@link View} class to wait for @param minimumNumberOfMatches the minimum number of matches that are expected to be found. {@code 0} means any number of matches @param timeout the amount of time in milliseconds to wait @return {@code true} if the {@link View} is displayed and {@code false} if it is not displayed before the timeout
[ "Waits", "for", "a", "View", "matching", "the", "specified", "class", "." ]
train
https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L622-L633
hibernate/hibernate-ogm
neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/EmbeddedNeo4jDialect.java
EmbeddedNeo4jDialect.applyProperties
private void applyProperties(AssociationKey associationKey, Tuple associationRow, Relationship relationship) { String[] indexColumns = associationKey.getMetadata().getRowKeyIndexColumnNames(); for ( int i = 0; i < indexColumns.length; i++ ) { String propertyName = indexColumns[i]; Object propertyValue = associationRow.get( propertyName ); relationship.setProperty( propertyName, propertyValue ); } }
java
private void applyProperties(AssociationKey associationKey, Tuple associationRow, Relationship relationship) { String[] indexColumns = associationKey.getMetadata().getRowKeyIndexColumnNames(); for ( int i = 0; i < indexColumns.length; i++ ) { String propertyName = indexColumns[i]; Object propertyValue = associationRow.get( propertyName ); relationship.setProperty( propertyName, propertyValue ); } }
[ "private", "void", "applyProperties", "(", "AssociationKey", "associationKey", ",", "Tuple", "associationRow", ",", "Relationship", "relationship", ")", "{", "String", "[", "]", "indexColumns", "=", "associationKey", ".", "getMetadata", "(", ")", ".", "getRowKeyInde...
The only properties added to a relationship are the columns representing the index of the association.
[ "The", "only", "properties", "added", "to", "a", "relationship", "are", "the", "columns", "representing", "the", "index", "of", "the", "association", "." ]
train
https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/EmbeddedNeo4jDialect.java#L276-L283
cryptomator/cryptofs
src/main/java/org/cryptomator/cryptofs/CryptoFileSystemProvider.java
CryptoFileSystemProvider.changePassphrase
public static void changePassphrase(Path pathToVault, String masterkeyFilename, CharSequence oldPassphrase, CharSequence newPassphrase) throws InvalidPassphraseException, FileSystemNeedsMigrationException, IOException { changePassphrase(pathToVault, masterkeyFilename, new byte[0], oldPassphrase, newPassphrase); }
java
public static void changePassphrase(Path pathToVault, String masterkeyFilename, CharSequence oldPassphrase, CharSequence newPassphrase) throws InvalidPassphraseException, FileSystemNeedsMigrationException, IOException { changePassphrase(pathToVault, masterkeyFilename, new byte[0], oldPassphrase, newPassphrase); }
[ "public", "static", "void", "changePassphrase", "(", "Path", "pathToVault", ",", "String", "masterkeyFilename", ",", "CharSequence", "oldPassphrase", ",", "CharSequence", "newPassphrase", ")", "throws", "InvalidPassphraseException", ",", "FileSystemNeedsMigrationException", ...
Changes the passphrase of a vault at the given path. @param pathToVault Vault directory @param masterkeyFilename Name of the masterkey file @param oldPassphrase Current passphrase @param newPassphrase Future passphrase @throws InvalidPassphraseException If <code>oldPassphrase</code> can not be used to unlock the vault. @throws FileSystemNeedsMigrationException if the vault format needs to get updated. @throws IOException If the masterkey could not be read or written. @see #changePassphrase(Path, String, byte[], CharSequence, CharSequence) @since 1.1.0
[ "Changes", "the", "passphrase", "of", "a", "vault", "at", "the", "given", "path", "." ]
train
https://github.com/cryptomator/cryptofs/blob/67fc1a4950dd1c150cd2e2c75bcabbeb7c9ac82e/src/main/java/org/cryptomator/cryptofs/CryptoFileSystemProvider.java#L202-L205
threerings/nenya
tools/src/main/java/com/threerings/cast/bundle/tools/ComponentBundler.java
ComponentBundler.composePath
protected String composePath (String[] info, String extension) { return (info[0] + "/" + info[1] + "/" + info[2] + extension); }
java
protected String composePath (String[] info, String extension) { return (info[0] + "/" + info[1] + "/" + info[2] + extension); }
[ "protected", "String", "composePath", "(", "String", "[", "]", "info", ",", "String", "extension", ")", "{", "return", "(", "info", "[", "0", "]", "+", "\"/\"", "+", "info", "[", "1", "]", "+", "\"/\"", "+", "info", "[", "2", "]", "+", "extension",...
Composes a triplet of [class, name, action] into the path that should be supplied to the JarEntry that contains the associated image data.
[ "Composes", "a", "triplet", "of", "[", "class", "name", "action", "]", "into", "the", "path", "that", "should", "be", "supplied", "to", "the", "JarEntry", "that", "contains", "the", "associated", "image", "data", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/tools/src/main/java/com/threerings/cast/bundle/tools/ComponentBundler.java#L320-L323
dhanji/sitebricks
sitebricks/src/main/java/com/google/sitebricks/rendering/control/DecorateWidget.java
DecorateWidget.nextDecoratedClassInHierarchy
private Class<?> nextDecoratedClassInHierarchy(Class<?> previousTemplateClass, Class<?> candidate) { if (candidate == previousTemplateClass) { // terminate the recursion return null; } else if (candidate == Object.class) { // this should never happen - we should terminate recursion first throw new IllegalStateException("Did not find previous extension"); } else { boolean isDecorated = candidate.isAnnotationPresent(Decorated.class); if (isDecorated) return candidate; else return nextDecoratedClassInHierarchy(previousTemplateClass, candidate.getSuperclass()); } }
java
private Class<?> nextDecoratedClassInHierarchy(Class<?> previousTemplateClass, Class<?> candidate) { if (candidate == previousTemplateClass) { // terminate the recursion return null; } else if (candidate == Object.class) { // this should never happen - we should terminate recursion first throw new IllegalStateException("Did not find previous extension"); } else { boolean isDecorated = candidate.isAnnotationPresent(Decorated.class); if (isDecorated) return candidate; else return nextDecoratedClassInHierarchy(previousTemplateClass, candidate.getSuperclass()); } }
[ "private", "Class", "<", "?", ">", "nextDecoratedClassInHierarchy", "(", "Class", "<", "?", ">", "previousTemplateClass", ",", "Class", "<", "?", ">", "candidate", ")", "{", "if", "(", "candidate", "==", "previousTemplateClass", ")", "{", "// terminate the recur...
recursively find the next superclass with an @Decorated annotation
[ "recursively", "find", "the", "next", "superclass", "with", "an" ]
train
https://github.com/dhanji/sitebricks/blob/8682029a78bd48fb8566173d970800499e9e5d97/sitebricks/src/main/java/com/google/sitebricks/rendering/control/DecorateWidget.java#L74-L90
elki-project/elki
elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java
MSTSplit.follow
private static int follow(int i, int[] partitions) { int next = partitions[i], tmp; while(i != next) { tmp = next; next = partitions[i] = partitions[next]; i = tmp; } return i; }
java
private static int follow(int i, int[] partitions) { int next = partitions[i], tmp; while(i != next) { tmp = next; next = partitions[i] = partitions[next]; i = tmp; } return i; }
[ "private", "static", "int", "follow", "(", "int", "i", ",", "int", "[", "]", "partitions", ")", "{", "int", "next", "=", "partitions", "[", "i", "]", ",", "tmp", ";", "while", "(", "i", "!=", "next", ")", "{", "tmp", "=", "next", ";", "next", "...
Union-find with simple path compression. @param i Start @param partitions Partitions array @return Partition
[ "Union", "-", "find", "with", "simple", "path", "compression", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-index-mtree/src/main/java/de/lmu/ifi/dbs/elki/index/tree/metrical/mtreevariants/strategies/split/MSTSplit.java#L225-L233
CloudSlang/cs-actions
cs-date-time/src/main/java/io/cloudslang/content/datetime/services/DateTimeService.java
DateTimeService.parseDate
public static String parseDate(final String date, final String dateFormat, final String dateLocaleLang, final String dateLocaleCountry, final String outFormat, final String outLocaleLang, final String outLocaleCountry) throws Exception { if (StringUtils.isBlank(date)) { throw new RuntimeException(Constants.ErrorMessages.DATE_NULL_OR_EMPTY); } DateTimeZone timeZone = DateTimeZone.forID(Constants.Miscellaneous.GMT); DateTime inputDateTime = parseInputDate(date, dateFormat, dateLocaleLang, dateLocaleCountry, timeZone); return changeFormatForDateTime(inputDateTime, outFormat, outLocaleLang, outLocaleCountry); }
java
public static String parseDate(final String date, final String dateFormat, final String dateLocaleLang, final String dateLocaleCountry, final String outFormat, final String outLocaleLang, final String outLocaleCountry) throws Exception { if (StringUtils.isBlank(date)) { throw new RuntimeException(Constants.ErrorMessages.DATE_NULL_OR_EMPTY); } DateTimeZone timeZone = DateTimeZone.forID(Constants.Miscellaneous.GMT); DateTime inputDateTime = parseInputDate(date, dateFormat, dateLocaleLang, dateLocaleCountry, timeZone); return changeFormatForDateTime(inputDateTime, outFormat, outLocaleLang, outLocaleCountry); }
[ "public", "static", "String", "parseDate", "(", "final", "String", "date", ",", "final", "String", "dateFormat", ",", "final", "String", "dateLocaleLang", ",", "final", "String", "dateLocaleCountry", ",", "final", "String", "outFormat", ",", "final", "String", "...
This operation converts the date input value from one date/time format (specified by dateFormat) to another date/time format (specified by outFormat) using locale settings (language and country). You can use the flow "Get Current Date and Time" to check upon the default date/time format from the Java environment. @param date the date to parse/convert @param dateFormat the format of the input date @param dateLocaleLang the locale language for input dateFormat string. It will be ignored if dateFormat is empty. default locale language from the Java environment (which is dependent on the OS locale language) @param dateLocaleCountry the locale country for input dateFormat string. It will be ignored if dateFormat is empty or dateLocaleLang is empty. Default locale country from the Java environment (which is dependent on the OS locale country) @param outFormat The format of the output date/time. Default date/time format from the Java environment (which is dependent on the OS date/time format) @param outLocaleLang The locale language for output string. It will be ignored if outFormat is empty. @param outLocaleCountry The locale country for output string. It will be ignored if outFormat is empty or outLocaleLang is empty. @return The date in the new format
[ "This", "operation", "converts", "the", "date", "input", "value", "from", "one", "date", "/", "time", "format", "(", "specified", "by", "dateFormat", ")", "to", "another", "date", "/", "time", "format", "(", "specified", "by", "outFormat", ")", "using", "l...
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-date-time/src/main/java/io/cloudslang/content/datetime/services/DateTimeService.java#L105-L115
qspin/qtaste
kernel/src/main/java/com/qspin/qtaste/ui/jedit/TextUtilities.java
TextUtilities.findWordStart
public static int findWordStart(String text, int pos, String noWordSep) { return findWordStart(text, pos, noWordSep, true, false); }
java
public static int findWordStart(String text, int pos, String noWordSep) { return findWordStart(text, pos, noWordSep, true, false); }
[ "public", "static", "int", "findWordStart", "(", "String", "text", ",", "int", "pos", ",", "String", "noWordSep", ")", "{", "return", "findWordStart", "(", "text", ",", "pos", ",", "noWordSep", ",", "true", ",", "false", ")", ";", "}" ]
Locates the start of the word at the specified position. @param text the text @param pos The position @param noWordSep Characters that are non-alphanumeric, but should be treated as word characters anyway
[ "Locates", "the", "start", "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#L34-L36
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/framework/website/StorageWebsite.java
StorageWebsite.findPathResource
private File findPathResource(@NonNull String httpPath) { if ("/".equals(httpPath)) { File indexFile = new File(mRootPath, getIndexFileName()); if (indexFile.exists() && indexFile.isFile()) { return indexFile; } } else { File sourceFile = new File(mRootPath, httpPath); if (sourceFile.exists()) { if (sourceFile.isFile()) { return sourceFile; } else { File childIndexFile = new File(sourceFile, getIndexFileName()); if (childIndexFile.exists() && childIndexFile.isFile()) { return childIndexFile; } } } } return null; }
java
private File findPathResource(@NonNull String httpPath) { if ("/".equals(httpPath)) { File indexFile = new File(mRootPath, getIndexFileName()); if (indexFile.exists() && indexFile.isFile()) { return indexFile; } } else { File sourceFile = new File(mRootPath, httpPath); if (sourceFile.exists()) { if (sourceFile.isFile()) { return sourceFile; } else { File childIndexFile = new File(sourceFile, getIndexFileName()); if (childIndexFile.exists() && childIndexFile.isFile()) { return childIndexFile; } } } } return null; }
[ "private", "File", "findPathResource", "(", "@", "NonNull", "String", "httpPath", ")", "{", "if", "(", "\"/\"", ".", "equals", "(", "httpPath", ")", ")", "{", "File", "indexFile", "=", "new", "File", "(", "mRootPath", ",", "getIndexFileName", "(", ")", "...
Find the path specified resource. @param httpPath path. @return return if the file is found.
[ "Find", "the", "path", "specified", "resource", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/framework/website/StorageWebsite.java#L76-L96
podio/podio-java
src/main/java/com/podio/rating/RatingAPI.java
RatingAPI.getRatings
public TypeRating getRatings(Reference reference, RatingType type) { return getResourceFactory().getApiResource( "/rating/" + reference.toURLFragment() + type).get( TypeRating.class); }
java
public TypeRating getRatings(Reference reference, RatingType type) { return getResourceFactory().getApiResource( "/rating/" + reference.toURLFragment() + type).get( TypeRating.class); }
[ "public", "TypeRating", "getRatings", "(", "Reference", "reference", ",", "RatingType", "type", ")", "{", "return", "getResourceFactory", "(", ")", ".", "getApiResource", "(", "\"/rating/\"", "+", "reference", ".", "toURLFragment", "(", ")", "+", "type", ")", ...
Get the rating average (for fivestar) and totals for the given rating type on the specified object. @param reference The reference to the object to get ratings for @param type The type of rating to return @return The ratings for the type
[ "Get", "the", "rating", "average", "(", "for", "fivestar", ")", "and", "totals", "for", "the", "given", "rating", "type", "on", "the", "specified", "object", "." ]
train
https://github.com/podio/podio-java/blob/a520b23bac118c957ce02cdd8ff42a6c7d17b49a/src/main/java/com/podio/rating/RatingAPI.java#L214-L218
networknt/json-schema-validator
src/main/java/com/networknt/schema/TypeValidator.java
TypeValidator.isNumber
public static boolean isNumber(JsonNode node, boolean isTypeLoose) { if (node.isNumber()) { return true; } else if (isTypeLoose) { if (TypeFactory.getValueNodeType(node) == JsonType.STRING) { return isNumeric(node.textValue()); } } return false; }
java
public static boolean isNumber(JsonNode node, boolean isTypeLoose) { if (node.isNumber()) { return true; } else if (isTypeLoose) { if (TypeFactory.getValueNodeType(node) == JsonType.STRING) { return isNumeric(node.textValue()); } } return false; }
[ "public", "static", "boolean", "isNumber", "(", "JsonNode", "node", ",", "boolean", "isTypeLoose", ")", "{", "if", "(", "node", ".", "isNumber", "(", ")", ")", "{", "return", "true", ";", "}", "else", "if", "(", "isTypeLoose", ")", "{", "if", "(", "T...
Check if the type of the JsonNode's value is number based on the status of typeLoose flag. @param node the JsonNode to check @param isTypeLoose The flag to show whether typeLoose is enabled @return boolean to indicate if it is a number
[ "Check", "if", "the", "type", "of", "the", "JsonNode", "s", "value", "is", "number", "based", "on", "the", "status", "of", "typeLoose", "flag", "." ]
train
https://github.com/networknt/json-schema-validator/blob/d2a3a8d2085e72eb5c25c2fd8c8c9e641a62376d/src/main/java/com/networknt/schema/TypeValidator.java#L208-L217
carewebframework/carewebframework-core
org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java
LayoutParser.parseTrigger
private void parseTrigger(Element node, LayoutElement parent) { LayoutTrigger trigger = new LayoutTrigger(); parent.getTriggers().add(trigger); parseChildren(node, trigger, Tag.CONDITION, Tag.ACTION); }
java
private void parseTrigger(Element node, LayoutElement parent) { LayoutTrigger trigger = new LayoutTrigger(); parent.getTriggers().add(trigger); parseChildren(node, trigger, Tag.CONDITION, Tag.ACTION); }
[ "private", "void", "parseTrigger", "(", "Element", "node", ",", "LayoutElement", "parent", ")", "{", "LayoutTrigger", "trigger", "=", "new", "LayoutTrigger", "(", ")", ";", "parent", ".", "getTriggers", "(", ")", ".", "add", "(", "trigger", ")", ";", "pars...
Parse a trigger node. @param node The DOM node. @param parent The parent layout element.
[ "Parse", "a", "trigger", "node", "." ]
train
https://github.com/carewebframework/carewebframework-core/blob/fa3252d4f7541dbe151b92c3d4f6f91433cd1673/org.carewebframework.shell/src/main/java/org/carewebframework/shell/layout/LayoutParser.java#L302-L306
apache/groovy
src/main/groovy/groovy/lang/ExpandoMetaClass.java
ExpandoMetaClass.setProperty
public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) { if (setPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && getJavaClass().isInstance(object)) { setPropertyMethod.invoke(object, new Object[]{name, newValue}); return; } super.setProperty(sender, object, name, newValue, useSuper, fromInsideClass); }
java
public void setProperty(Class sender, Object object, String name, Object newValue, boolean useSuper, boolean fromInsideClass) { if (setPropertyMethod != null && !name.equals(META_CLASS_PROPERTY) && getJavaClass().isInstance(object)) { setPropertyMethod.invoke(object, new Object[]{name, newValue}); return; } super.setProperty(sender, object, name, newValue, useSuper, fromInsideClass); }
[ "public", "void", "setProperty", "(", "Class", "sender", ",", "Object", "object", ",", "String", "name", ",", "Object", "newValue", ",", "boolean", "useSuper", ",", "boolean", "fromInsideClass", ")", "{", "if", "(", "setPropertyMethod", "!=", "null", "&&", "...
Overrides default implementation just in case setProperty method has been overridden by ExpandoMetaClass @see MetaClassImpl#setProperty(Class, Object, String, Object, boolean, boolean)
[ "Overrides", "default", "implementation", "just", "in", "case", "setProperty", "method", "has", "been", "overridden", "by", "ExpandoMetaClass" ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/groovy/groovy/lang/ExpandoMetaClass.java#L1180-L1186
elki-project/elki
elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java
BitsUtil.previousSetBit
public static int previousSetBit(long[] v, int start) { if(start < 0) { return -1; } int wordindex = start >>> LONG_LOG2_SIZE; if(wordindex >= v.length) { return magnitude(v) - 1; } // Initial word final int off = 63 - (start & LONG_LOG2_MASK); long cur = v[wordindex] & (LONG_ALL_BITS >>> off); for(;;) { if(cur != 0) { return wordindex * Long.SIZE + 63 - ((cur == LONG_ALL_BITS) ? 0 : Long.numberOfLeadingZeros(cur)); } if(wordindex == 0) { return -1; } cur = v[--wordindex]; } }
java
public static int previousSetBit(long[] v, int start) { if(start < 0) { return -1; } int wordindex = start >>> LONG_LOG2_SIZE; if(wordindex >= v.length) { return magnitude(v) - 1; } // Initial word final int off = 63 - (start & LONG_LOG2_MASK); long cur = v[wordindex] & (LONG_ALL_BITS >>> off); for(;;) { if(cur != 0) { return wordindex * Long.SIZE + 63 - ((cur == LONG_ALL_BITS) ? 0 : Long.numberOfLeadingZeros(cur)); } if(wordindex == 0) { return -1; } cur = v[--wordindex]; } }
[ "public", "static", "int", "previousSetBit", "(", "long", "[", "]", "v", ",", "int", "start", ")", "{", "if", "(", "start", "<", "0", ")", "{", "return", "-", "1", ";", "}", "int", "wordindex", "=", "start", ">>>", "LONG_LOG2_SIZE", ";", "if", "(",...
Find the previous set bit. @param v Values to process @param start Start position (inclusive) @return Position of previous set bit, or -1.
[ "Find", "the", "previous", "set", "bit", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/datastructures/BitsUtil.java#L1233-L1253
alkacon/opencms-core
src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java
CmsSitemapController.getPath
protected String getPath(CmsClientSitemapEntry entry, String newUrlName) { if (newUrlName.equals("")) { return entry.getSitePath(); } return CmsResource.getParentFolder(entry.getSitePath()) + newUrlName + "/"; }
java
protected String getPath(CmsClientSitemapEntry entry, String newUrlName) { if (newUrlName.equals("")) { return entry.getSitePath(); } return CmsResource.getParentFolder(entry.getSitePath()) + newUrlName + "/"; }
[ "protected", "String", "getPath", "(", "CmsClientSitemapEntry", "entry", ",", "String", "newUrlName", ")", "{", "if", "(", "newUrlName", ".", "equals", "(", "\"\"", ")", ")", "{", "return", "entry", ".", "getSitePath", "(", ")", ";", "}", "return", "CmsRes...
Helper method for getting the full path of a sitemap entry whose URL name is being edited.<p> @param entry the sitemap entry @param newUrlName the new url name of the sitemap entry @return the new full site path of the sitemap entry
[ "Helper", "method", "for", "getting", "the", "full", "path", "of", "a", "sitemap", "entry", "whose", "URL", "name", "is", "being", "edited", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/sitemap/client/control/CmsSitemapController.java#L2228-L2234
mangstadt/biweekly
src/main/java/biweekly/io/ParseContext.java
ParseContext.addDate
public void addDate(ICalDate icalDate, ICalProperty property, ICalParameters parameters) { if (!icalDate.hasTime()) { //dates don't have timezones return; } if (icalDate.getRawComponents().isUtc()) { //it's a UTC date, so it was already parsed under the correct timezone return; } //TODO handle UTC offsets within the date strings (not part of iCal standard) String tzid = parameters.getTimezoneId(); if (tzid == null) { addFloatingDate(property, icalDate); } else { addTimezonedDate(tzid, property, icalDate); } }
java
public void addDate(ICalDate icalDate, ICalProperty property, ICalParameters parameters) { if (!icalDate.hasTime()) { //dates don't have timezones return; } if (icalDate.getRawComponents().isUtc()) { //it's a UTC date, so it was already parsed under the correct timezone return; } //TODO handle UTC offsets within the date strings (not part of iCal standard) String tzid = parameters.getTimezoneId(); if (tzid == null) { addFloatingDate(property, icalDate); } else { addTimezonedDate(tzid, property, icalDate); } }
[ "public", "void", "addDate", "(", "ICalDate", "icalDate", ",", "ICalProperty", "property", ",", "ICalParameters", "parameters", ")", "{", "if", "(", "!", "icalDate", ".", "hasTime", "(", ")", ")", "{", "//dates don't have timezones", "return", ";", "}", "if", ...
Adds a parsed date to this parse context so its timezone can be applied to it after the iCalendar object has been parsed (if it has one). @param icalDate the parsed date @param property the property that the date value belongs to @param parameters the property's parameters
[ "Adds", "a", "parsed", "date", "to", "this", "parse", "context", "so", "its", "timezone", "can", "be", "applied", "to", "it", "after", "the", "iCalendar", "object", "has", "been", "parsed", "(", "if", "it", "has", "one", ")", "." ]
train
https://github.com/mangstadt/biweekly/blob/2e21350f85c13dfff52fdef98fdbebe2976fcf61/src/main/java/biweekly/io/ParseContext.java#L105-L123
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/repo/jdbc/SQLStatement.java
SQLStatement.buildStatement
public String buildStatement(int initialCapacity, FilterValues<S> filterValues) { StringBuilder b = new StringBuilder(initialCapacity); this.appendTo(b, filterValues); return b.toString(); }
java
public String buildStatement(int initialCapacity, FilterValues<S> filterValues) { StringBuilder b = new StringBuilder(initialCapacity); this.appendTo(b, filterValues); return b.toString(); }
[ "public", "String", "buildStatement", "(", "int", "initialCapacity", ",", "FilterValues", "<", "S", ">", "filterValues", ")", "{", "StringBuilder", "b", "=", "new", "StringBuilder", "(", "initialCapacity", ")", ";", "this", ".", "appendTo", "(", "b", ",", "f...
Builds a statement string from the given values. @param initialCapacity expected size of finished string length. Should be value returned from maxLength. @param filterValues values may be needed to build complete statement
[ "Builds", "a", "statement", "string", "from", "the", "given", "values", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/repo/jdbc/SQLStatement.java#L41-L45
dmerkushov/log-helper
src/main/java/ru/dmerkushov/loghelper/LoggerWrapper.java
LoggerWrapper.logDomNodeList
public void logDomNodeList (String msg, NodeList nodeList) { StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement (); String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n"); for (int i = 0; i < nodeList.getLength (); i++) { toLog += domNodeDescription (nodeList.item (i), 0) + "\n"; } if (caller != null) { logger.logp (Level.FINER, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog); } else { logger.logp (Level.FINER, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog); } }
java
public void logDomNodeList (String msg, NodeList nodeList) { StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement (); String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n"); for (int i = 0; i < nodeList.getLength (); i++) { toLog += domNodeDescription (nodeList.item (i), 0) + "\n"; } if (caller != null) { logger.logp (Level.FINER, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog); } else { logger.logp (Level.FINER, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog); } }
[ "public", "void", "logDomNodeList", "(", "String", "msg", ",", "NodeList", "nodeList", ")", "{", "StackTraceElement", "caller", "=", "StackTraceUtils", ".", "getCallerStackTraceElement", "(", ")", ";", "String", "toLog", "=", "(", "msg", "!=", "null", "?", "ms...
Log a DOM node list at the FINER level @param msg The message to show with the list, or null if no message needed @param nodeList @see NodeList
[ "Log", "a", "DOM", "node", "list", "at", "the", "FINER", "level" ]
train
https://github.com/dmerkushov/log-helper/blob/3b7d3d30faa7f1437b27cd07c10fa579a995de23/src/main/java/ru/dmerkushov/loghelper/LoggerWrapper.java#L418-L431
stagemonitor/stagemonitor
stagemonitor-core/src/main/java/org/stagemonitor/core/metrics/metrics2/MetricName.java
MetricName.withTag
public MetricName withTag(String key, String value) { return name(name).tags(tags).tag(key, value).build(); }
java
public MetricName withTag(String key, String value) { return name(name).tags(tags).tag(key, value).build(); }
[ "public", "MetricName", "withTag", "(", "String", "key", ",", "String", "value", ")", "{", "return", "name", "(", "name", ")", ".", "tags", "(", "tags", ")", ".", "tag", "(", "key", ",", "value", ")", ".", "build", "(", ")", ";", "}" ]
Returns a copy of this name and appends a single tag <p> Note that this method does not override existing tags @param key the key of the tag @param value the value of the tag @return a copy of this name including the provided tag
[ "Returns", "a", "copy", "of", "this", "name", "and", "appends", "a", "single", "tag", "<p", ">", "Note", "that", "this", "method", "does", "not", "override", "existing", "tags" ]
train
https://github.com/stagemonitor/stagemonitor/blob/7a1bf6848906f816aa465983f602ea1f1e8f2b7b/stagemonitor-core/src/main/java/org/stagemonitor/core/metrics/metrics2/MetricName.java#L63-L65
jcuda/jcusparse
JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java
JCusparse.cusparseXcsrsv2_zeroPivot
public static int cusparseXcsrsv2_zeroPivot( cusparseHandle handle, csrsv2Info info, Pointer position) { return checkResult(cusparseXcsrsv2_zeroPivotNative(handle, info, position)); }
java
public static int cusparseXcsrsv2_zeroPivot( cusparseHandle handle, csrsv2Info info, Pointer position) { return checkResult(cusparseXcsrsv2_zeroPivotNative(handle, info, position)); }
[ "public", "static", "int", "cusparseXcsrsv2_zeroPivot", "(", "cusparseHandle", "handle", ",", "csrsv2Info", "info", ",", "Pointer", "position", ")", "{", "return", "checkResult", "(", "cusparseXcsrsv2_zeroPivotNative", "(", "handle", ",", "info", ",", "position", ")...
<pre> Description: Solution of triangular linear system op(A) * x = alpha * f, where A is a sparse matrix in CSR storage format, rhs f and solution y are dense vectors. This routine implements algorithm 1 for this problem. Also, it provides a utility function to query size of buffer used. </pre>
[ "<pre", ">", "Description", ":", "Solution", "of", "triangular", "linear", "system", "op", "(", "A", ")", "*", "x", "=", "alpha", "*", "f", "where", "A", "is", "a", "sparse", "matrix", "in", "CSR", "storage", "format", "rhs", "f", "and", "solution", ...
train
https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L2435-L2441
rundeck/rundeck
core/src/main/java/com/dtolabs/rundeck/core/plugins/ScriptDataContextUtil.java
ScriptDataContextUtil.createScriptDataContext
public static DataContext createScriptDataContext(final Framework framework) { BaseDataContext data = new BaseDataContext(); final File vardir = new File(Constants.getBaseVar(framework.getBaseDir().getAbsolutePath())); final File tmpdir = new File(vardir, "tmp"); data.group("plugin").put("vardir", vardir.getAbsolutePath()); data.group("plugin").put("tmpdir", tmpdir.getAbsolutePath()); data.put("rundeck", "base", framework.getBaseDir().getAbsolutePath()); return data; }
java
public static DataContext createScriptDataContext(final Framework framework) { BaseDataContext data = new BaseDataContext(); final File vardir = new File(Constants.getBaseVar(framework.getBaseDir().getAbsolutePath())); final File tmpdir = new File(vardir, "tmp"); data.group("plugin").put("vardir", vardir.getAbsolutePath()); data.group("plugin").put("tmpdir", tmpdir.getAbsolutePath()); data.put("rundeck", "base", framework.getBaseDir().getAbsolutePath()); return data; }
[ "public", "static", "DataContext", "createScriptDataContext", "(", "final", "Framework", "framework", ")", "{", "BaseDataContext", "data", "=", "new", "BaseDataContext", "(", ")", ";", "final", "File", "vardir", "=", "new", "File", "(", "Constants", ".", "getBas...
@return a data context for executing a script plugin or provider, which contains two datasets: plugin: {vardir: [dir], tmpdir: [dir]} and rundeck: {base: [basedir]} @param framework framework
[ "@return", "a", "data", "context", "for", "executing", "a", "script", "plugin", "or", "provider", "which", "contains", "two", "datasets", ":", "plugin", ":", "{", "vardir", ":", "[", "dir", "]", "tmpdir", ":", "[", "dir", "]", "}", "and", "rundeck", ":...
train
https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/rundeck/core/plugins/ScriptDataContextUtil.java#L60-L70
EdwardRaff/JSAT
JSAT/src/jsat/distributions/kernels/RBFKernel.java
RBFKernel.sigmaToGamma
public static double sigmaToGamma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new IllegalArgumentException("sigma must be positive, not " + sigma); return 1/(2*sigma*sigma); }
java
public static double sigmaToGamma(double sigma) { if(sigma <= 0 || Double.isNaN(sigma) || Double.isInfinite(sigma)) throw new IllegalArgumentException("sigma must be positive, not " + sigma); return 1/(2*sigma*sigma); }
[ "public", "static", "double", "sigmaToGamma", "(", "double", "sigma", ")", "{", "if", "(", "sigma", "<=", "0", "||", "Double", ".", "isNaN", "(", "sigma", ")", "||", "Double", ".", "isInfinite", "(", "sigma", ")", ")", "throw", "new", "IllegalArgumentExc...
Another common (equivalent) form of the RBF kernel is k(x, y) = exp(-&gamma;||x-y||<sup>2</sup>). This method converts the &sigma; value used by this class to the equivalent &gamma; value. @param sigma the value of &sigma; @return the equivalent &gamma; value.
[ "Another", "common", "(", "equivalent", ")", "form", "of", "the", "RBF", "kernel", "is", "k", "(", "x", "y", ")", "=", "exp", "(", "-", "&gamma", ";", "||x", "-", "y||<sup", ">", "2<", "/", "sup", ">", ")", ".", "This", "method", "converts", "the...
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/distributions/kernels/RBFKernel.java#L111-L116
Azure/azure-sdk-for-java
datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java
AccountsInner.listSasTokensWithServiceResponseAsync
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> listSasTokensWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final String containerName) { return listSasTokensSinglePageAsync(resourceGroupName, accountName, storageAccountName, containerName) .concatMap(new Func1<ServiceResponse<Page<SasTokenInfoInner>>, Observable<ServiceResponse<Page<SasTokenInfoInner>>>>() { @Override public Observable<ServiceResponse<Page<SasTokenInfoInner>>> call(ServiceResponse<Page<SasTokenInfoInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<SasTokenInfoInner>>> listSasTokensWithServiceResponseAsync(final String resourceGroupName, final String accountName, final String storageAccountName, final String containerName) { return listSasTokensSinglePageAsync(resourceGroupName, accountName, storageAccountName, containerName) .concatMap(new Func1<ServiceResponse<Page<SasTokenInfoInner>>, Observable<ServiceResponse<Page<SasTokenInfoInner>>>>() { @Override public Observable<ServiceResponse<Page<SasTokenInfoInner>>> call(ServiceResponse<Page<SasTokenInfoInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listSasTokensNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "SasTokenInfoInner", ">", ">", ">", "listSasTokensWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "accountName", ",", "final", "String", "storageAccountName...
Gets the SAS token associated with the specified Data Lake Analytics and Azure Storage account and container combination. @param resourceGroupName The name of the Azure resource group that contains the Data Lake Analytics account. @param accountName The name of the Data Lake Analytics account from which an Azure Storage account's SAS token is being requested. @param storageAccountName The name of the Azure storage account for which the SAS token is being requested. @param containerName The name of the Azure storage container for which the SAS token is being requested. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;SasTokenInfoInner&gt; object
[ "Gets", "the", "SAS", "token", "associated", "with", "the", "specified", "Data", "Lake", "Analytics", "and", "Azure", "Storage", "account", "and", "container", "combination", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datalakeanalytics/resource-manager/v2015_10_01_preview/src/main/java/com/microsoft/azure/management/datalakeanalytics/v2015_10_01_preview/implementation/AccountsInner.java#L872-L884
elki-project/elki
elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java
DiSH.weightedDistance
protected static double weightedDistance(NumberVector v1, NumberVector v2, long[] weightVector) { double sqrDist = 0; for(int i = BitsUtil.nextSetBit(weightVector, 0); i >= 0; i = BitsUtil.nextSetBit(weightVector, i + 1)) { double manhattanI = v1.doubleValue(i) - v2.doubleValue(i); sqrDist += manhattanI * manhattanI; } return FastMath.sqrt(sqrDist); }
java
protected static double weightedDistance(NumberVector v1, NumberVector v2, long[] weightVector) { double sqrDist = 0; for(int i = BitsUtil.nextSetBit(weightVector, 0); i >= 0; i = BitsUtil.nextSetBit(weightVector, i + 1)) { double manhattanI = v1.doubleValue(i) - v2.doubleValue(i); sqrDist += manhattanI * manhattanI; } return FastMath.sqrt(sqrDist); }
[ "protected", "static", "double", "weightedDistance", "(", "NumberVector", "v1", ",", "NumberVector", "v2", ",", "long", "[", "]", "weightVector", ")", "{", "double", "sqrDist", "=", "0", ";", "for", "(", "int", "i", "=", "BitsUtil", ".", "nextSetBit", "(",...
Computes the weighted distance between the two specified vectors according to the given preference vector. @param v1 the first vector @param v2 the second vector @param weightVector the preference vector @return the weighted distance between the two specified vectors according to the given preference vector
[ "Computes", "the", "weighted", "distance", "between", "the", "two", "specified", "vectors", "according", "to", "the", "given", "preference", "vector", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/subspace/DiSH.java#L601-L608
lets-blade/blade
src/main/java/com/blade/mvc/ui/template/BladeTemplate.java
BladeTemplate.appendParamValue
private void appendParamValue(StringBuilder param, StringBuilder result) { if (param == null) throw UncheckedTemplateException.invalidArgumentName(param); // Object name is the parameter that should be found in the map. // If it's followed by points, the points remain in the "param" buffer. final String objectName = takeUntilDotOrEnd(param); final Object objectValue = arguments.get(objectName); Object toAppend; if (param.length() != 0) { // If this is a chain object.method1.method2.method3 // we recurse toAppend = valueInChain(objectValue, param); } else { // We evaluate if the obejct is an array // If it's an array we print it nicely toAppend = evaluateIfArray(objectValue); } if (null != toAppend) { result.append(toAppend); } }
java
private void appendParamValue(StringBuilder param, StringBuilder result) { if (param == null) throw UncheckedTemplateException.invalidArgumentName(param); // Object name is the parameter that should be found in the map. // If it's followed by points, the points remain in the "param" buffer. final String objectName = takeUntilDotOrEnd(param); final Object objectValue = arguments.get(objectName); Object toAppend; if (param.length() != 0) { // If this is a chain object.method1.method2.method3 // we recurse toAppend = valueInChain(objectValue, param); } else { // We evaluate if the obejct is an array // If it's an array we print it nicely toAppend = evaluateIfArray(objectValue); } if (null != toAppend) { result.append(toAppend); } }
[ "private", "void", "appendParamValue", "(", "StringBuilder", "param", ",", "StringBuilder", "result", ")", "{", "if", "(", "param", "==", "null", ")", "throw", "UncheckedTemplateException", ".", "invalidArgumentName", "(", "param", ")", ";", "// Object name is the p...
in this case it is obtained by calling recursively the methods on the last obtained object
[ "in", "this", "case", "it", "is", "obtained", "by", "calling", "recursively", "the", "methods", "on", "the", "last", "obtained", "object" ]
train
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/mvc/ui/template/BladeTemplate.java#L194-L217
JOML-CI/JOML
src/org/joml/Matrix4f.java
Matrix4f.lookAtLH
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.setLookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); else if ((properties & PROPERTY_PERSPECTIVE) != 0) return lookAtPerspectiveLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); return lookAtLHGeneric(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); }
java
public Matrix4f lookAtLH(float eyeX, float eyeY, float eyeZ, float centerX, float centerY, float centerZ, float upX, float upY, float upZ, Matrix4f dest) { if ((properties & PROPERTY_IDENTITY) != 0) return dest.setLookAtLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ); else if ((properties & PROPERTY_PERSPECTIVE) != 0) return lookAtPerspectiveLH(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); return lookAtLHGeneric(eyeX, eyeY, eyeZ, centerX, centerY, centerZ, upX, upY, upZ, dest); }
[ "public", "Matrix4f", "lookAtLH", "(", "float", "eyeX", ",", "float", "eyeY", ",", "float", "eyeZ", ",", "float", "centerX", ",", "float", "centerY", ",", "float", "centerZ", ",", "float", "upX", ",", "float", "upY", ",", "float", "upZ", ",", "Matrix4f",...
Apply a "lookat" transformation to this matrix for a left-handed coordinate system, that aligns <code>+z</code> with <code>center - eye</code> and store the result in <code>dest</code>. <p> If <code>M</code> is <code>this</code> matrix and <code>L</code> the lookat matrix, then the new matrix will be <code>M * L</code>. So when transforming a vector <code>v</code> with the new matrix by using <code>M * L * v</code>, the lookat transformation will be applied first! <p> In order to set the matrix to a lookat transformation without post-multiplying it, use {@link #setLookAtLH(float, float, float, float, float, float, float, float, float) setLookAtLH()}. @see #lookAtLH(Vector3fc, Vector3fc, Vector3fc) @see #setLookAtLH(float, float, float, float, float, float, float, float, float) @param eyeX the x-coordinate of the eye/camera location @param eyeY the y-coordinate of the eye/camera location @param eyeZ the z-coordinate of the eye/camera location @param centerX the x-coordinate of the point to look at @param centerY the y-coordinate of the point to look at @param centerZ the z-coordinate of the point to look at @param upX the x-coordinate of the up vector @param upY the y-coordinate of the up vector @param upZ the z-coordinate of the up vector @param dest will hold the result @return dest
[ "Apply", "a", "lookat", "transformation", "to", "this", "matrix", "for", "a", "left", "-", "handed", "coordinate", "system", "that", "aligns", "<code", ">", "+", "z<", "/", "code", ">", "with", "<code", ">", "center", "-", "eye<", "/", "code", ">", "an...
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L8972-L8980
Azure/azure-sdk-for-java
eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java
DomainsInner.createOrUpdateAsync
public Observable<DomainInner> createOrUpdateAsync(String resourceGroupName, String domainName, DomainInner domainInfo) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, domainName, domainInfo).map(new Func1<ServiceResponse<DomainInner>, DomainInner>() { @Override public DomainInner call(ServiceResponse<DomainInner> response) { return response.body(); } }); }
java
public Observable<DomainInner> createOrUpdateAsync(String resourceGroupName, String domainName, DomainInner domainInfo) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, domainName, domainInfo).map(new Func1<ServiceResponse<DomainInner>, DomainInner>() { @Override public DomainInner call(ServiceResponse<DomainInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DomainInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "domainName", ",", "DomainInner", "domainInfo", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "domainN...
Create a domain. Asynchronously creates a new domain with the specified parameters. @param resourceGroupName The name of the resource group within the user's subscription. @param domainName Name of the domain @param domainInfo Domain information @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "a", "domain", ".", "Asynchronously", "creates", "a", "new", "domain", "with", "the", "specified", "parameters", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/eventgrid/resource-manager/v2018_09_15_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2018_09_15_preview/implementation/DomainsInner.java#L246-L253
threerings/gwt-utils
src/main/java/com/threerings/gwt/ui/Popups.java
Popups.newPopup
public static PopupPanel newPopup (String styleName, Widget contents) { PopupPanel panel = new PopupPanel(); panel.setStyleName(styleName); panel.setWidget(contents); return panel; }
java
public static PopupPanel newPopup (String styleName, Widget contents) { PopupPanel panel = new PopupPanel(); panel.setStyleName(styleName); panel.setWidget(contents); return panel; }
[ "public", "static", "PopupPanel", "newPopup", "(", "String", "styleName", ",", "Widget", "contents", ")", "{", "PopupPanel", "panel", "=", "new", "PopupPanel", "(", ")", ";", "panel", ".", "setStyleName", "(", "styleName", ")", ";", "panel", ".", "setWidget"...
Creates and returns a new popup with the specified style name and contents.
[ "Creates", "and", "returns", "a", "new", "popup", "with", "the", "specified", "style", "name", "and", "contents", "." ]
train
https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/Popups.java#L269-L275
Microsoft/spring-data-cosmosdb
src/main/java/com/microsoft/azure/spring/data/cosmosdb/core/generator/AbstractQueryGenerator.java
AbstractQueryGenerator.generateQuery
protected SqlQuerySpec generateQuery(@NonNull DocumentQuery query, @NonNull String queryHead) { Assert.hasText(queryHead, "query head should have text."); final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getValue1(); final SqlParameterCollection sqlParameters = new SqlParameterCollection(); sqlParameters.addAll( parameters.stream() .map(p -> new SqlParameter("@" + p.getValue0(), toDocumentDBValue(p.getValue1()))) .collect(Collectors.toList()) ); return new SqlQuerySpec(queryString, sqlParameters); }
java
protected SqlQuerySpec generateQuery(@NonNull DocumentQuery query, @NonNull String queryHead) { Assert.hasText(queryHead, "query head should have text."); final Pair<String, List<Pair<String, Object>>> queryBody = generateQueryBody(query); final String queryString = String.join(" ", queryHead, queryBody.getValue0(), generateQueryTail(query)); final List<Pair<String, Object>> parameters = queryBody.getValue1(); final SqlParameterCollection sqlParameters = new SqlParameterCollection(); sqlParameters.addAll( parameters.stream() .map(p -> new SqlParameter("@" + p.getValue0(), toDocumentDBValue(p.getValue1()))) .collect(Collectors.toList()) ); return new SqlQuerySpec(queryString, sqlParameters); }
[ "protected", "SqlQuerySpec", "generateQuery", "(", "@", "NonNull", "DocumentQuery", "query", ",", "@", "NonNull", "String", "queryHead", ")", "{", "Assert", ".", "hasText", "(", "queryHead", ",", "\"query head should have text.\"", ")", ";", "final", "Pair", "<", ...
Generate SqlQuerySpec with given DocumentQuery and query head. @param query DocumentQuery represent one query method. @param queryHead @return The SqlQuerySpec for DocumentClient.
[ "Generate", "SqlQuerySpec", "with", "given", "DocumentQuery", "and", "query", "head", "." ]
train
https://github.com/Microsoft/spring-data-cosmosdb/blob/f349fce5892f225794eae865ca9a12191cac243c/src/main/java/com/microsoft/azure/spring/data/cosmosdb/core/generator/AbstractQueryGenerator.java#L210-L225
davidmarquis/fluent-interface-proxy
src/main/java/com/fluentinterface/beans/ObjectWrapper.java
ObjectWrapper.getPropertyOrThrow
private static Property getPropertyOrThrow(Bean bean, String propertyName) { Property property = bean.getProperty(propertyName); if (property == null) { throw new PropertyNotFoundException("Cannot find property with name '" + propertyName + "' in " + bean + "."); } return property; }
java
private static Property getPropertyOrThrow(Bean bean, String propertyName) { Property property = bean.getProperty(propertyName); if (property == null) { throw new PropertyNotFoundException("Cannot find property with name '" + propertyName + "' in " + bean + "."); } return property; }
[ "private", "static", "Property", "getPropertyOrThrow", "(", "Bean", "bean", ",", "String", "propertyName", ")", "{", "Property", "property", "=", "bean", ".", "getProperty", "(", "propertyName", ")", ";", "if", "(", "property", "==", "null", ")", "{", "throw...
Internal: Static version of {@link #getProperty(String)}, throws an exception instead of return null. @param bean the bean object whose property is to be searched @param propertyName the name of the property to search @return the property with the given name, if found @throws NullPointerException if the bean object does not have a property with the given name
[ "Internal", ":", "Static", "version", "of", "{", "@link", "#getProperty", "(", "String", ")", "}", "throws", "an", "exception", "instead", "of", "return", "null", "." ]
train
https://github.com/davidmarquis/fluent-interface-proxy/blob/8e72fff6cd1f496c76a01773269caead994fea65/src/main/java/com/fluentinterface/beans/ObjectWrapper.java#L420-L428
netscaler/sdx_nitro
src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdx_backup_restore.java
sdx_backup_restore.get_nitro_bulk_response
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sdx_backup_restore_responses result = (sdx_backup_restore_responses) service.get_payload_formatter().string_to_resource(sdx_backup_restore_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdx_backup_restore_response_array); } sdx_backup_restore[] result_sdx_backup_restore = new sdx_backup_restore[result.sdx_backup_restore_response_array.length]; for(int i = 0; i < result.sdx_backup_restore_response_array.length; i++) { result_sdx_backup_restore[i] = result.sdx_backup_restore_response_array[i].sdx_backup_restore[0]; } return result_sdx_backup_restore; }
java
protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception { sdx_backup_restore_responses result = (sdx_backup_restore_responses) service.get_payload_formatter().string_to_resource(sdx_backup_restore_responses.class, response); if(result.errorcode != 0) { if (result.errorcode == SESSION_NOT_EXISTS) service.clear_session(); throw new nitro_exception(result.message, result.errorcode, (base_response [])result.sdx_backup_restore_response_array); } sdx_backup_restore[] result_sdx_backup_restore = new sdx_backup_restore[result.sdx_backup_restore_response_array.length]; for(int i = 0; i < result.sdx_backup_restore_response_array.length; i++) { result_sdx_backup_restore[i] = result.sdx_backup_restore_response_array[i].sdx_backup_restore[0]; } return result_sdx_backup_restore; }
[ "protected", "base_resource", "[", "]", "get_nitro_bulk_response", "(", "nitro_service", "service", ",", "String", "response", ")", "throws", "Exception", "{", "sdx_backup_restore_responses", "result", "=", "(", "sdx_backup_restore_responses", ")", "service", ".", "get_...
<pre> Converts API response of bulk operation into object and returns the object array in case of get request. </pre>
[ "<pre", ">", "Converts", "API", "response", "of", "bulk", "operation", "into", "object", "and", "returns", "the", "object", "array", "in", "case", "of", "get", "request", ".", "<", "/", "pre", ">" ]
train
https://github.com/netscaler/sdx_nitro/blob/c840919f1a8f7c0a5634c0f23d34fa14d1765ff1/src/main/java/com/citrix/sdx/nitro/resource/config/mps/sdx_backup_restore.java#L265-L282
google/error-prone-javac
src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java
AbstractExecutableMemberWriter.addInheritedSummaryLink
@Override protected void addInheritedSummaryLink(TypeElement te, Element member, Content linksTree) { linksTree.addContent(writer.getDocLink(MEMBER, te, member, name(member), false)); }
java
@Override protected void addInheritedSummaryLink(TypeElement te, Element member, Content linksTree) { linksTree.addContent(writer.getDocLink(MEMBER, te, member, name(member), false)); }
[ "@", "Override", "protected", "void", "addInheritedSummaryLink", "(", "TypeElement", "te", ",", "Element", "member", ",", "Content", "linksTree", ")", "{", "linksTree", ".", "addContent", "(", "writer", ".", "getDocLink", "(", "MEMBER", ",", "te", ",", "member...
Add the inherited summary link for the member. @param te the type element that we should link to @param member the member being linked to @param linksTree the content tree to which the link will be added
[ "Add", "the", "inherited", "summary", "link", "for", "the", "member", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractExecutableMemberWriter.java#L139-L142
radkovo/CSSBox
src/main/java/org/fit/cssbox/layout/TextBox.java
TextBox.copyTextBox
public TextBox copyTextBox() { TextBox ret = new TextBox(textNode, g, ctx); ret.copyValues(this); return ret; }
java
public TextBox copyTextBox() { TextBox ret = new TextBox(textNode, g, ctx); ret.copyValues(this); return ret; }
[ "public", "TextBox", "copyTextBox", "(", ")", "{", "TextBox", "ret", "=", "new", "TextBox", "(", "textNode", ",", "g", ",", "ctx", ")", ";", "ret", ".", "copyValues", "(", "this", ")", ";", "return", "ret", ";", "}" ]
Create a new box from the same DOM node in the same context @return the new TextBox
[ "Create", "a", "new", "box", "from", "the", "same", "DOM", "node", "in", "the", "same", "context" ]
train
https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/TextBox.java#L156-L161
oasp/oasp4j
modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java
RestServiceExceptionFacade.handleValidationException
protected Response handleValidationException(Throwable exception, Throwable catched) { Throwable t = catched; Map<String, List<String>> errorsMap = null; if (exception instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations(); errorsMap = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { Iterator<Node> it = violation.getPropertyPath().iterator(); String fieldName = null; // Getting fieldname from the exception while (it.hasNext()) { fieldName = it.next().toString(); } List<String> errorsList = errorsMap.get(fieldName); if (errorsList == null) { errorsList = new ArrayList<>(); errorsMap.put(fieldName, errorsList); } errorsList.add(violation.getMessage()); } t = new ValidationException(errorsMap.toString(), catched); } ValidationErrorUserException error = new ValidationErrorUserException(t); return createResponse(t, error, errorsMap); }
java
protected Response handleValidationException(Throwable exception, Throwable catched) { Throwable t = catched; Map<String, List<String>> errorsMap = null; if (exception instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) exception; Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations(); errorsMap = new HashMap<>(); for (ConstraintViolation<?> violation : violations) { Iterator<Node> it = violation.getPropertyPath().iterator(); String fieldName = null; // Getting fieldname from the exception while (it.hasNext()) { fieldName = it.next().toString(); } List<String> errorsList = errorsMap.get(fieldName); if (errorsList == null) { errorsList = new ArrayList<>(); errorsMap.put(fieldName, errorsList); } errorsList.add(violation.getMessage()); } t = new ValidationException(errorsMap.toString(), catched); } ValidationErrorUserException error = new ValidationErrorUserException(t); return createResponse(t, error, errorsMap); }
[ "protected", "Response", "handleValidationException", "(", "Throwable", "exception", ",", "Throwable", "catched", ")", "{", "Throwable", "t", "=", "catched", ";", "Map", "<", "String", ",", "List", "<", "String", ">", ">", "errorsMap", "=", "null", ";", "if"...
Exception handling for validation exception. @param exception the exception to handle @param catched the original exception that was cached. Either same as {@code error} or a (child-) {@link Throwable#getCause() cause} of it. @return the response build from the exception.
[ "Exception", "handling", "for", "validation", "exception", "." ]
train
https://github.com/oasp/oasp4j/blob/03f90132699fad95e52ec8efa54aa391f8d3c7e4/modules/rest/src/main/java/io/oasp/module/rest/service/impl/RestServiceExceptionFacade.java#L326-L359
javagl/CommonUI
src/main/java/de/javagl/common/ui/JTrees.java
JTrees.expandAllRecursively
private static void expandAllRecursively(JTree tree, TreePath treePath) { TreeModel model = tree.getModel(); Object lastPathComponent = treePath.getLastPathComponent(); int childCount = model.getChildCount(lastPathComponent); if (childCount == 0) { return; } tree.expandPath(treePath); for (int i=0; i<childCount; i++) { Object child = model.getChild(lastPathComponent, i); int grandChildCount = model.getChildCount(child); if (grandChildCount > 0) { class LocalTreePath extends TreePath { private static final long serialVersionUID = 0; public LocalTreePath( TreePath parent, Object lastPathComponent) { super(parent, lastPathComponent); } } TreePath nextTreePath = new LocalTreePath(treePath, child); expandAllRecursively(tree, nextTreePath); } } }
java
private static void expandAllRecursively(JTree tree, TreePath treePath) { TreeModel model = tree.getModel(); Object lastPathComponent = treePath.getLastPathComponent(); int childCount = model.getChildCount(lastPathComponent); if (childCount == 0) { return; } tree.expandPath(treePath); for (int i=0; i<childCount; i++) { Object child = model.getChild(lastPathComponent, i); int grandChildCount = model.getChildCount(child); if (grandChildCount > 0) { class LocalTreePath extends TreePath { private static final long serialVersionUID = 0; public LocalTreePath( TreePath parent, Object lastPathComponent) { super(parent, lastPathComponent); } } TreePath nextTreePath = new LocalTreePath(treePath, child); expandAllRecursively(tree, nextTreePath); } } }
[ "private", "static", "void", "expandAllRecursively", "(", "JTree", "tree", ",", "TreePath", "treePath", ")", "{", "TreeModel", "model", "=", "tree", ".", "getModel", "(", ")", ";", "Object", "lastPathComponent", "=", "treePath", ".", "getLastPathComponent", "(",...
Recursively expand all paths in the given tree, starting with the given path @param tree The tree @param treePath The current tree path
[ "Recursively", "expand", "all", "paths", "in", "the", "given", "tree", "starting", "with", "the", "given", "path" ]
train
https://github.com/javagl/CommonUI/blob/b2c7a7637d4e288271392ba148dc17e4c9780255/src/main/java/de/javagl/common/ui/JTrees.java#L126-L155
abel533/Mapper
core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java
SqlHelper.logicDeleteColumnEqualsValue
public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) { String result = ""; if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { result = column.getColumn() + " = " + getLogicDeletedValue(column, isDeleted); } return result; }
java
public static String logicDeleteColumnEqualsValue(EntityColumn column, boolean isDeleted) { String result = ""; if (column.getEntityField().isAnnotationPresent(LogicDelete.class)) { result = column.getColumn() + " = " + getLogicDeletedValue(column, isDeleted); } return result; }
[ "public", "static", "String", "logicDeleteColumnEqualsValue", "(", "EntityColumn", "column", ",", "boolean", "isDeleted", ")", "{", "String", "result", "=", "\"\"", ";", "if", "(", "column", ".", "getEntityField", "(", ")", ".", "isAnnotationPresent", "(", "Logi...
返回格式: column = value <br> 默认isDeletedValue = 1 notDeletedValue = 0 <br> 则返回is_deleted = 1 或 is_deleted = 0 <br> 若没有逻辑删除注解,则返回空字符串 @param column @param isDeleted true 已经逻辑删除 false 未逻辑删除
[ "返回格式", ":", "column", "=", "value", "<br", ">", "默认isDeletedValue", "=", "1", "notDeletedValue", "=", "0", "<br", ">", "则返回is_deleted", "=", "1", "或", "is_deleted", "=", "0", "<br", ">", "若没有逻辑删除注解,则返回空字符串" ]
train
https://github.com/abel533/Mapper/blob/45c3d716583cba3680e03f1f6790fab5e1f4f668/core/src/main/java/tk/mybatis/mapper/mapperhelper/SqlHelper.java#L762-L768
mailin-api/sendinblue-java-mvn
src/main/java/com/sendinblue/Sendinblue.java
Sendinblue.get_senders
public String get_senders(Map<String, String> data) { String option = data.get("option"); String url; if (EMPTY_STRING.equals(option)) { url = "advanced/"; } else { url = "advanced/option/" + option + "/"; } return get(url, EMPTY_STRING); }
java
public String get_senders(Map<String, String> data) { String option = data.get("option"); String url; if (EMPTY_STRING.equals(option)) { url = "advanced/"; } else { url = "advanced/option/" + option + "/"; } return get(url, EMPTY_STRING); }
[ "public", "String", "get_senders", "(", "Map", "<", "String", ",", "String", ">", "data", ")", "{", "String", "option", "=", "data", ".", "get", "(", "\"option\"", ")", ";", "String", "url", ";", "if", "(", "EMPTY_STRING", ".", "equals", "(", "option",...
/* Get Access of created senders information. @param {Object} data contains json objects as a key value pair from HashMap. @options data {String} option: Options to get senders. Possible options – IP-wise, & Domain-wise ( only for dedicated IP clients ). Example: to get senders with specific IP, use $option=’1.2.3.4′, to get senders with specific domain use, $option=’domain.com’, & to get all senders, use $option="" [Optional]
[ "/", "*", "Get", "Access", "of", "created", "senders", "information", "." ]
train
https://github.com/mailin-api/sendinblue-java-mvn/blob/3a186b004003450f18d619aa084adc8d75086183/src/main/java/com/sendinblue/Sendinblue.java#L1037-L1047
paypal/SeLion
client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java
AbstractBaseLocalServerComponent.checkPort
void checkPort(int port, String msg) { StringBuilder message = new StringBuilder().append(" ").append(msg); String portInUseError = String.format("Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different port%s.", port, message); boolean free = false; try { free = PortProber.pollPort(port); } catch (RuntimeException e) { throw new IllegalArgumentException(portInUseError, e); } finally { if (!free) { throw new IllegalArgumentException(portInUseError); } } }
java
void checkPort(int port, String msg) { StringBuilder message = new StringBuilder().append(" ").append(msg); String portInUseError = String.format("Port %d is already in use. Please shutdown the service " + "listening on this port or configure a different port%s.", port, message); boolean free = false; try { free = PortProber.pollPort(port); } catch (RuntimeException e) { throw new IllegalArgumentException(portInUseError, e); } finally { if (!free) { throw new IllegalArgumentException(portInUseError); } } }
[ "void", "checkPort", "(", "int", "port", ",", "String", "msg", ")", "{", "StringBuilder", "message", "=", "new", "StringBuilder", "(", ")", ".", "append", "(", "\" \"", ")", ".", "append", "(", "msg", ")", ";", "String", "portInUseError", "=", "String", ...
Check the port availability @param port the port to check @param msg the text to append to the end of the error message displayed when the port is not available. @throws IllegalArgumentException when the port is not available.
[ "Check", "the", "port", "availability" ]
train
https://github.com/paypal/SeLion/blob/694d12d0df76db48d0360b16192770c6a4fbdfd2/client/src/main/java/com/paypal/selion/internal/platform/grid/AbstractBaseLocalServerComponent.java#L112-L126
codescape/bitvunit
bitvunit-core/src/main/java/de/codescape/bitvunit/util/io/ClassPathResource.java
ClassPathResource.asString
private String asString() { try { return IOUtils.toString(asInputStream()); } catch (IOException e) { throw new RuntimeException("Could not read from file '" + path + "'.", e); } }
java
private String asString() { try { return IOUtils.toString(asInputStream()); } catch (IOException e) { throw new RuntimeException("Could not read from file '" + path + "'.", e); } }
[ "private", "String", "asString", "(", ")", "{", "try", "{", "return", "IOUtils", ".", "toString", "(", "asInputStream", "(", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RuntimeException", "(", "\"Could not read from file ...
Returns a {@link String} that contains the content of the file. @return {@link String} that contains the content of the file
[ "Returns", "a", "{", "@link", "String", "}", "that", "contains", "the", "content", "of", "the", "file", "." ]
train
https://github.com/codescape/bitvunit/blob/cef6d9af60d684e41294981c10b6d92c8f063a4e/bitvunit-core/src/main/java/de/codescape/bitvunit/util/io/ClassPathResource.java#L71-L77
perwendel/spark
src/main/java/spark/TemplateViewRouteImpl.java
TemplateViewRouteImpl.create
public static TemplateViewRouteImpl create(String path, TemplateViewRoute route, TemplateEngine engine) { return create(path, Service.DEFAULT_ACCEPT_TYPE, route, engine); }
java
public static TemplateViewRouteImpl create(String path, TemplateViewRoute route, TemplateEngine engine) { return create(path, Service.DEFAULT_ACCEPT_TYPE, route, engine); }
[ "public", "static", "TemplateViewRouteImpl", "create", "(", "String", "path", ",", "TemplateViewRoute", "route", ",", "TemplateEngine", "engine", ")", "{", "return", "create", "(", "path", ",", "Service", ".", "DEFAULT_ACCEPT_TYPE", ",", "route", ",", "engine", ...
factory method @param path the path @param route the route @param engine the engine @return the wrapper template view route
[ "factory", "method" ]
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/TemplateViewRouteImpl.java#L37-L42
Prototik/HoloEverywhere
library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java
RadialPickerLayout.setItem
private void setItem(int index, int value) { if (index == HOUR_INDEX) { setValueForItem(HOUR_INDEX, value); int hourDegrees = (value % 12) * HOUR_VALUE_TO_DEGREES_STEP_SIZE; mHourRadialSelectorView.setSelection(hourDegrees, isHourInnerCircle(value), false); mHourRadialSelectorView.invalidate(); } else if (index == MINUTE_INDEX) { setValueForItem(MINUTE_INDEX, value); int minuteDegrees = value * MINUTE_VALUE_TO_DEGREES_STEP_SIZE; mMinuteRadialSelectorView.setSelection(minuteDegrees, false, false); mMinuteRadialSelectorView.invalidate(); } }
java
private void setItem(int index, int value) { if (index == HOUR_INDEX) { setValueForItem(HOUR_INDEX, value); int hourDegrees = (value % 12) * HOUR_VALUE_TO_DEGREES_STEP_SIZE; mHourRadialSelectorView.setSelection(hourDegrees, isHourInnerCircle(value), false); mHourRadialSelectorView.invalidate(); } else if (index == MINUTE_INDEX) { setValueForItem(MINUTE_INDEX, value); int minuteDegrees = value * MINUTE_VALUE_TO_DEGREES_STEP_SIZE; mMinuteRadialSelectorView.setSelection(minuteDegrees, false, false); mMinuteRadialSelectorView.invalidate(); } }
[ "private", "void", "setItem", "(", "int", "index", ",", "int", "value", ")", "{", "if", "(", "index", "==", "HOUR_INDEX", ")", "{", "setValueForItem", "(", "HOUR_INDEX", ",", "value", ")", ";", "int", "hourDegrees", "=", "(", "value", "%", "12", ")", ...
Set either the hour or the minute. Will set the internal value, and set the selection.
[ "Set", "either", "the", "hour", "or", "the", "minute", ".", "Will", "set", "the", "internal", "value", "and", "set", "the", "selection", "." ]
train
https://github.com/Prototik/HoloEverywhere/blob/b870abb5ab009a5a6dbab3fb855ec2854e35e125/library/src/org/holoeverywhere/widget/datetimepicker/time/RadialPickerLayout.java#L225-L237
medallia/Word2VecJava
src/main/java/com/medallia/word2vec/util/IO.java
IO.copyAndCloseOutput
public static long copyAndCloseOutput(InputStream input, OutputStream output) throws IOException { try (OutputStream outputStream = output) { return copy(input, outputStream); } }
java
public static long copyAndCloseOutput(InputStream input, OutputStream output) throws IOException { try (OutputStream outputStream = output) { return copy(input, outputStream); } }
[ "public", "static", "long", "copyAndCloseOutput", "(", "InputStream", "input", ",", "OutputStream", "output", ")", "throws", "IOException", "{", "try", "(", "OutputStream", "outputStream", "=", "output", ")", "{", "return", "copy", "(", "input", ",", "outputStre...
Copy input to output and close the output stream before returning
[ "Copy", "input", "to", "output", "and", "close", "the", "output", "stream", "before", "returning" ]
train
https://github.com/medallia/Word2VecJava/blob/eb31fbb99ac6bbab82d7f807b3e2240edca50eb7/src/main/java/com/medallia/word2vec/util/IO.java#L51-L55
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java
LogRecordBrowser.startRecordsInProcess
private OnePidRecordListImpl startRecordsInProcess(long min, long max, IInternalRecordFilter recFilter) { // Find first file of this process records File file = fileBrowser.findByMillis(min); if (file == null) { file = fileBrowser.findNext((File)null, max); } return new OnePidRecordListMintimeImpl(file, min, max, recFilter); }
java
private OnePidRecordListImpl startRecordsInProcess(long min, long max, IInternalRecordFilter recFilter) { // Find first file of this process records File file = fileBrowser.findByMillis(min); if (file == null) { file = fileBrowser.findNext((File)null, max); } return new OnePidRecordListMintimeImpl(file, min, max, recFilter); }
[ "private", "OnePidRecordListImpl", "startRecordsInProcess", "(", "long", "min", ",", "long", "max", ",", "IInternalRecordFilter", "recFilter", ")", "{", "// Find first file of this process records", "File", "file", "=", "fileBrowser", ".", "findByMillis", "(", "min", ")...
list of the records in the process filtered with <code>recFilter</code>
[ "list", "of", "the", "records", "in", "the", "process", "filtered", "with", "<code", ">", "recFilter<", "/", "code", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/ws/logging/hpel/impl/LogRecordBrowser.java#L162-L169
wkgcass/Style
src/main/java/net/cassite/style/aggregation/ListFuncSup.java
ListFuncSup.forEach
public <R> R forEach(RFunc1<R, T> func, int index) { return forEach($(func), index); }
java
public <R> R forEach(RFunc1<R, T> func, int index) { return forEach($(func), index); }
[ "public", "<", "R", ">", "R", "forEach", "(", "RFunc1", "<", "R", ",", "T", ">", "func", ",", "int", "index", ")", "{", "return", "forEach", "(", "$", "(", "func", ")", ",", "index", ")", ";", "}" ]
define a function to deal with each element in the list with given start index @param func a function takes in each element from list and returns last loop value @param index the index where to start iteration @return return 'last loop value'.<br> check <a href="https://github.com/wkgcass/Style/">tutorial</a> for more info about 'last loop value'
[ "define", "a", "function", "to", "deal", "with", "each", "element", "in", "the", "list", "with", "given", "start", "index" ]
train
https://github.com/wkgcass/Style/blob/db3ea64337251f46f734279480e365293bececbd/src/main/java/net/cassite/style/aggregation/ListFuncSup.java#L103-L105
couchbase/couchbase-jvm-core
src/main/java/com/couchbase/client/core/ResponseHandler.java
ResponseHandler.scheduleForRetry
private void scheduleForRetry(final CouchbaseRequest request, final boolean isNotMyVbucket) { CoreEnvironment env = environment; long delayTime; TimeUnit delayUnit; if (request.retryDelay() != null) { Delay delay = request.retryDelay(); if (request.retryCount() == 0) { delayTime = request.retryAfter(); request.incrementRetryCount(); } else { delayTime = delay.calculate(request.incrementRetryCount()); } delayUnit = delay.unit(); if (request.maxRetryDuration() != 0 && ((System.currentTimeMillis()) + delayTime) > request.maxRetryDuration()) { request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling " + "instead of retrying as the maximum retry duration specified by Server has been exceeded")); return; } } else { Delay delay = env.retryDelay(); if (isNotMyVbucket) { boolean hasFastForward = bucketHasFastForwardMap(request.bucket(), configurationProvider.config()); delayTime = request.incrementRetryCount() == 0 && hasFastForward ? 0 : nmvbRetryDelay; delayUnit = TimeUnit.MILLISECONDS; } else { delayTime = delay.calculate(request.incrementRetryCount()); delayUnit = delay.unit(); } } if (traceLoggingEnabled) { LOGGER.trace("Retrying {} with a delay of {} {}", request, delayTime, delayUnit); } final Scheduler.Worker worker = env.scheduler().createWorker(); worker.schedule(new Action0() { @Override public void call() { try { cluster.send(request); } finally { worker.unsubscribe(); } } }, delayTime, delayUnit); }
java
private void scheduleForRetry(final CouchbaseRequest request, final boolean isNotMyVbucket) { CoreEnvironment env = environment; long delayTime; TimeUnit delayUnit; if (request.retryDelay() != null) { Delay delay = request.retryDelay(); if (request.retryCount() == 0) { delayTime = request.retryAfter(); request.incrementRetryCount(); } else { delayTime = delay.calculate(request.incrementRetryCount()); } delayUnit = delay.unit(); if (request.maxRetryDuration() != 0 && ((System.currentTimeMillis()) + delayTime) > request.maxRetryDuration()) { request.observable().onError(new RequestCancelledException("Could not dispatch request, cancelling " + "instead of retrying as the maximum retry duration specified by Server has been exceeded")); return; } } else { Delay delay = env.retryDelay(); if (isNotMyVbucket) { boolean hasFastForward = bucketHasFastForwardMap(request.bucket(), configurationProvider.config()); delayTime = request.incrementRetryCount() == 0 && hasFastForward ? 0 : nmvbRetryDelay; delayUnit = TimeUnit.MILLISECONDS; } else { delayTime = delay.calculate(request.incrementRetryCount()); delayUnit = delay.unit(); } } if (traceLoggingEnabled) { LOGGER.trace("Retrying {} with a delay of {} {}", request, delayTime, delayUnit); } final Scheduler.Worker worker = env.scheduler().createWorker(); worker.schedule(new Action0() { @Override public void call() { try { cluster.send(request); } finally { worker.unsubscribe(); } } }, delayTime, delayUnit); }
[ "private", "void", "scheduleForRetry", "(", "final", "CouchbaseRequest", "request", ",", "final", "boolean", "isNotMyVbucket", ")", "{", "CoreEnvironment", "env", "=", "environment", ";", "long", "delayTime", ";", "TimeUnit", "delayUnit", ";", "if", "(", "request"...
Helper method which schedules the given {@link CouchbaseRequest} with a delay for further retry. @param request the request to retry.
[ "Helper", "method", "which", "schedules", "the", "given", "{", "@link", "CouchbaseRequest", "}", "with", "a", "delay", "for", "further", "retry", "." ]
train
https://github.com/couchbase/couchbase-jvm-core/blob/97f0427112c2168fee1d6499904f5fa0e24c6797/src/main/java/com/couchbase/client/core/ResponseHandler.java#L175-L221