repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
phax/ph-poi
src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java
WorkbookCreationHelper.addMergeRegion
public int addMergeRegion (@Nonnegative final int nFirstRow, @Nonnegative final int nLastRow, @Nonnegative final int nFirstCol, @Nonnegative final int nLastCol) { return m_aLastSheet.addMergedRegion (new CellRangeAddress (nFirstRow, nLastRow, nFirstCol, nLastCol)); }
java
public int addMergeRegion (@Nonnegative final int nFirstRow, @Nonnegative final int nLastRow, @Nonnegative final int nFirstCol, @Nonnegative final int nLastCol) { return m_aLastSheet.addMergedRegion (new CellRangeAddress (nFirstRow, nLastRow, nFirstCol, nLastCol)); }
[ "public", "int", "addMergeRegion", "(", "@", "Nonnegative", "final", "int", "nFirstRow", ",", "@", "Nonnegative", "final", "int", "nLastRow", ",", "@", "Nonnegative", "final", "int", "nFirstCol", ",", "@", "Nonnegative", "final", "int", "nLastCol", ")", "{", ...
Adds a merged region of cells (hence those cells form one) @param nFirstRow Index of first row @param nLastRow Index of last row (inclusive), must be equal to or larger than {@code nFirstRow} @param nFirstCol Index of first column @param nLastCol Index of last column (inclusive), must be equal to or larger than {@code nFirstCol} @return index of this region
[ "Adds", "a", "merged", "region", "of", "cells", "(", "hence", "those", "cells", "form", "one", ")" ]
train
https://github.com/phax/ph-poi/blob/908c5dd434739e6989cf88e55bea48f2f18c6996/src/main/java/com/helger/poi/excel/WorkbookCreationHelper.java#L461-L467
intuit/QuickBooks-V3-Java-SDK
ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java
DataService.download
public <T extends IEntity> InputStream download(T entity) throws FMSException { IntuitMessage intuitMessage = prepareDownload(entity); //execute interceptors executeInterceptors(intuitMessage); String response = intuitMessage.getResponseElements().getDecompressedData(); if (response != null) { try { URL url = new URL(response); return url.openStream(); } catch (Exception e) { throw new FMSException("Exception while downloading the input file from URL.", e); } } return null; }
java
public <T extends IEntity> InputStream download(T entity) throws FMSException { IntuitMessage intuitMessage = prepareDownload(entity); //execute interceptors executeInterceptors(intuitMessage); String response = intuitMessage.getResponseElements().getDecompressedData(); if (response != null) { try { URL url = new URL(response); return url.openStream(); } catch (Exception e) { throw new FMSException("Exception while downloading the input file from URL.", e); } } return null; }
[ "public", "<", "T", "extends", "IEntity", ">", "InputStream", "download", "(", "T", "entity", ")", "throws", "FMSException", "{", "IntuitMessage", "intuitMessage", "=", "prepareDownload", "(", "entity", ")", ";", "//execute interceptors", "executeInterceptors", "(",...
Method to find the record for the given id for the corresponding entity @param entity @return returns the entity @throws FMSException
[ "Method", "to", "find", "the", "record", "for", "the", "given", "id", "for", "the", "corresponding", "entity" ]
train
https://github.com/intuit/QuickBooks-V3-Java-SDK/blob/59f988d0776d46620d0b34711c411b2b5b1da06b/ipp-v3-java-devkit/src/main/java/com/intuit/ipp/services/DataService.java#L508-L526
otto-de/edison-hal
src/main/java/de/otto/edison/hal/traverson/Traverson.java
Traverson.startWith
public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource)); Optional<Link> self = resource.getLinks().getLinkBy("self"); if (self.isPresent()) { this.contextUrl = linkToUrl(self.get()); } else { resource .getLinks() .stream() .filter(link -> !link.getHref().matches("http.*//.*")) .findAny() .ifPresent(link -> {throw new IllegalArgumentException("Unable to construct Traverson from HalRepresentation w/o self link but containing relative links. Please try Traverson.startWith(URL, HalRepresentation)");}); } return this; }
java
public Traverson startWith(final HalRepresentation resource) { this.startWith = null; this.lastResult = singletonList(requireNonNull(resource)); Optional<Link> self = resource.getLinks().getLinkBy("self"); if (self.isPresent()) { this.contextUrl = linkToUrl(self.get()); } else { resource .getLinks() .stream() .filter(link -> !link.getHref().matches("http.*//.*")) .findAny() .ifPresent(link -> {throw new IllegalArgumentException("Unable to construct Traverson from HalRepresentation w/o self link but containing relative links. Please try Traverson.startWith(URL, HalRepresentation)");}); } return this; }
[ "public", "Traverson", "startWith", "(", "final", "HalRepresentation", "resource", ")", "{", "this", ".", "startWith", "=", "null", ";", "this", ".", "lastResult", "=", "singletonList", "(", "requireNonNull", "(", "resource", ")", ")", ";", "Optional", "<", ...
Start traversal at the given HAL resource. <p> It is expected, that the HalRepresentation has an absolute 'self' link, or that all links to other resources are absolute links. If this is not assured, {@link #startWith(URL, HalRepresentation)} must be used, so relative links can be resolved. </p> @param resource the initial HAL resource. @return Traverson initialized with the specified {@link HalRepresentation}.
[ "Start", "traversal", "at", "the", "given", "HAL", "resource", "." ]
train
https://github.com/otto-de/edison-hal/blob/1582d2b49d1f0d9103e03bf742f18afa9d166992/src/main/java/de/otto/edison/hal/traverson/Traverson.java#L301-L316
LearnLib/learnlib
algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/model/ObservationTree.java
ObservationTree.addTrace
public void addTrace(final S state, final ADTNode<S, I, O> adtNode) { final FastMealyState<O> internalState = this.nodeToObservationMap.get(state); ADTNode<S, I, O> adsIter = adtNode; while (adsIter != null) { final Pair<Word<I>, Word<O>> trace = ADTUtil.buildTraceForNode(adsIter); this.addTrace(internalState, trace.getFirst(), trace.getSecond()); adsIter = ADTUtil.getStartOfADS(adsIter).getParent(); } }
java
public void addTrace(final S state, final ADTNode<S, I, O> adtNode) { final FastMealyState<O> internalState = this.nodeToObservationMap.get(state); ADTNode<S, I, O> adsIter = adtNode; while (adsIter != null) { final Pair<Word<I>, Word<O>> trace = ADTUtil.buildTraceForNode(adsIter); this.addTrace(internalState, trace.getFirst(), trace.getSecond()); adsIter = ADTUtil.getStartOfADS(adsIter).getParent(); } }
[ "public", "void", "addTrace", "(", "final", "S", "state", ",", "final", "ADTNode", "<", "S", ",", "I", ",", "O", ">", "adtNode", ")", "{", "final", "FastMealyState", "<", "O", ">", "internalState", "=", "this", ".", "nodeToObservationMap", ".", "get", ...
See {@link #addState(Object, Word, Object)}. Convenience method that stores all information that the traces of the given {@link ADTNode} holds. @param state the hypothesis state for which information should be stored @param adtNode the {@link ADTNode} whose traces should be stored
[ "See", "{", "@link", "#addState", "(", "Object", "Word", "Object", ")", "}", ".", "Convenience", "method", "that", "stores", "all", "information", "that", "the", "traces", "of", "the", "given", "{", "@link", "ADTNode", "}", "holds", "." ]
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/adt/src/main/java/de/learnlib/algorithms/adt/model/ObservationTree.java#L155-L167
BlueBrain/bluima
modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Entity.java
Entity.setEntity_attributes
public void setEntity_attributes(int i, EntityAttribute v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_entity_attributes == null) jcasType.jcas.throwFeatMissing("entity_attributes", "de.julielab.jules.types.ace.Entity"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_entity_attributes), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_entity_attributes), i, jcasType.ll_cas.ll_getFSRef(v));}
java
public void setEntity_attributes(int i, EntityAttribute v) { if (Entity_Type.featOkTst && ((Entity_Type)jcasType).casFeat_entity_attributes == null) jcasType.jcas.throwFeatMissing("entity_attributes", "de.julielab.jules.types.ace.Entity"); jcasType.jcas.checkArrayBounds(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_entity_attributes), i); jcasType.ll_cas.ll_setRefArrayValue(jcasType.ll_cas.ll_getRefValue(addr, ((Entity_Type)jcasType).casFeatCode_entity_attributes), i, jcasType.ll_cas.ll_getFSRef(v));}
[ "public", "void", "setEntity_attributes", "(", "int", "i", ",", "EntityAttribute", "v", ")", "{", "if", "(", "Entity_Type", ".", "featOkTst", "&&", "(", "(", "Entity_Type", ")", "jcasType", ")", ".", "casFeat_entity_attributes", "==", "null", ")", "jcasType", ...
indexed setter for entity_attributes - sets an indexed value - @generated @param i index in the array to set @param v value to set into the array
[ "indexed", "setter", "for", "entity_attributes", "-", "sets", "an", "indexed", "value", "-" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/modules/bluima_typesystem/src/main/java/de/julielab/jules/types/ace/Entity.java#L226-L230
craterdog/java-general-utilities
src/main/java/craterdog/utils/ByteUtils.java
ByteUtils.shortToBytes
static public int shortToBytes(short s, byte[] buffer, int index) { int length = 2; for (int i = 0; i < length; i++) { buffer[index + length - i - 1] = (byte) (s >> (i * 8)); } return length; }
java
static public int shortToBytes(short s, byte[] buffer, int index) { int length = 2; for (int i = 0; i < length; i++) { buffer[index + length - i - 1] = (byte) (s >> (i * 8)); } return length; }
[ "static", "public", "int", "shortToBytes", "(", "short", "s", ",", "byte", "[", "]", "buffer", ",", "int", "index", ")", "{", "int", "length", "=", "2", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", ...
This function converts a short into its corresponding byte format and inserts it into the specified buffer at the specified index. @param s The short to be converted. @param buffer The byte array. @param index The index in the array to begin inserting bytes. @return The number of bytes inserted.
[ "This", "function", "converts", "a", "short", "into", "its", "corresponding", "byte", "format", "and", "inserts", "it", "into", "the", "specified", "buffer", "at", "the", "specified", "index", "." ]
train
https://github.com/craterdog/java-general-utilities/blob/a3ff45eaa00c2b8ed5c53efe9fe5166065fc1f57/src/main/java/craterdog/utils/ByteUtils.java#L128-L134
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/FileLocator.java
FileLocator.matchFile
private static File matchFile(File dirPath, String regex) { if (dirPath != null && dirPath.isDirectory()) { List<File> fileList = FileLocator.getMatchingFiles(dirPath, regex); for (File currentFile : fileList) { if (currentFile.exists()) return currentFile; } } return null; }
java
private static File matchFile(File dirPath, String regex) { if (dirPath != null && dirPath.isDirectory()) { List<File> fileList = FileLocator.getMatchingFiles(dirPath, regex); for (File currentFile : fileList) { if (currentFile.exists()) return currentFile; } } return null; }
[ "private", "static", "File", "matchFile", "(", "File", "dirPath", ",", "String", "regex", ")", "{", "if", "(", "dirPath", "!=", "null", "&&", "dirPath", ".", "isDirectory", "(", ")", ")", "{", "List", "<", "File", ">", "fileList", "=", "FileLocator", "...
Internal method: performs test common to matchFileInNamedPath(String, List) and {@link #matchFileInFilePath(String, Collection) @param dirPath Directory to check for named file @param name The name of the file to find @return The File object if the file is found; null if the dirPath is null, does not exist, or is not a directory.
[ "Internal", "method", ":", "performs", "test", "common", "to", "matchFileInNamedPath", "(", "String", "List", ")", "and", "{", "@link", "#matchFileInFilePath", "(", "String", "Collection", ")" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.service.location/src/com/ibm/ws/kernel/service/location/internal/FileLocator.java#L202-L211
WiQuery/wiquery
wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/tabs/Tabs.java
Tabs.setAjaxBeforeActivateEvent
public Tabs setAjaxBeforeActivateEvent(ITabsAjaxEvent beforeActivateEvent) { this.ajaxEvents.put(TabEvent.beforeActivate, beforeActivateEvent); setBeforeActivateEvent(new TabsAjaxBeforeActivateJsScopeUiEvent(this, TabEvent.beforeActivate, false)); return this; }
java
public Tabs setAjaxBeforeActivateEvent(ITabsAjaxEvent beforeActivateEvent) { this.ajaxEvents.put(TabEvent.beforeActivate, beforeActivateEvent); setBeforeActivateEvent(new TabsAjaxBeforeActivateJsScopeUiEvent(this, TabEvent.beforeActivate, false)); return this; }
[ "public", "Tabs", "setAjaxBeforeActivateEvent", "(", "ITabsAjaxEvent", "beforeActivateEvent", ")", "{", "this", ".", "ajaxEvents", ".", "put", "(", "TabEvent", ".", "beforeActivate", ",", "beforeActivateEvent", ")", ";", "setBeforeActivateEvent", "(", "new", "TabsAjax...
Sets the call-back for the AJAX beforeActivate event. @param beforeActivateEvent The ITabsAjaxEvent.
[ "Sets", "the", "call", "-", "back", "for", "the", "AJAX", "beforeActivate", "event", "." ]
train
https://github.com/WiQuery/wiquery/blob/1b8d60c7a3c37b90fd68c9cd0ff97178fcbcbb08/wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/tabs/Tabs.java#L614-L619
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
SqlQueryStatement.appendClause
protected void appendClause(StringBuffer clause, Criteria crit, StringBuffer stmt) { /** * MBAIRD * when generating the "WHERE/HAVING" clause we need to append the criteria for multi-mapped * tables. We only need to do this for the root classdescriptor and not for joined tables * because we assume you cannot make a relation of the wrong type upon insertion. Of course, * you COULD mess the data up manually and this would cause a problem. */ if (clause != null) { stmt.append(clause.toString()); } if (crit != null) { if (clause == null) { stmt.append(asSQLStatement(crit)); } else { stmt.append(" AND ("); stmt.append(asSQLStatement(crit)); stmt.append(")"); } } }
java
protected void appendClause(StringBuffer clause, Criteria crit, StringBuffer stmt) { /** * MBAIRD * when generating the "WHERE/HAVING" clause we need to append the criteria for multi-mapped * tables. We only need to do this for the root classdescriptor and not for joined tables * because we assume you cannot make a relation of the wrong type upon insertion. Of course, * you COULD mess the data up manually and this would cause a problem. */ if (clause != null) { stmt.append(clause.toString()); } if (crit != null) { if (clause == null) { stmt.append(asSQLStatement(crit)); } else { stmt.append(" AND ("); stmt.append(asSQLStatement(crit)); stmt.append(")"); } } }
[ "protected", "void", "appendClause", "(", "StringBuffer", "clause", ",", "Criteria", "crit", ",", "StringBuffer", "stmt", ")", "{", "/**\r\n * MBAIRD\r\n * when generating the \"WHERE/HAVING\" clause we need to append the criteria for multi-mapped\r\n * tables. We...
appends a WHERE/HAVING-clause to the Statement @param clause @param crit @param stmt
[ "appends", "a", "WHERE", "/", "HAVING", "-", "clause", "to", "the", "Statement" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L581-L609
ben-manes/caffeine
jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java
CacheProxy.setAccessExpirationTime
protected final void setAccessExpirationTime(Expirable<?> expirable, long currentTimeMS) { try { Duration duration = expiry.getExpiryForAccess(); if (duration == null) { return; } else if (duration.isZero()) { expirable.setExpireTimeMS(0L); } else if (duration.isEternal()) { expirable.setExpireTimeMS(Long.MAX_VALUE); } else { if (currentTimeMS == 0L) { currentTimeMS = currentTimeMillis(); } long expireTimeMS = duration.getAdjustedTime(currentTimeMS); expirable.setExpireTimeMS(expireTimeMS); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to set the entry's expiration time", e); } }
java
protected final void setAccessExpirationTime(Expirable<?> expirable, long currentTimeMS) { try { Duration duration = expiry.getExpiryForAccess(); if (duration == null) { return; } else if (duration.isZero()) { expirable.setExpireTimeMS(0L); } else if (duration.isEternal()) { expirable.setExpireTimeMS(Long.MAX_VALUE); } else { if (currentTimeMS == 0L) { currentTimeMS = currentTimeMillis(); } long expireTimeMS = duration.getAdjustedTime(currentTimeMS); expirable.setExpireTimeMS(expireTimeMS); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to set the entry's expiration time", e); } }
[ "protected", "final", "void", "setAccessExpirationTime", "(", "Expirable", "<", "?", ">", "expirable", ",", "long", "currentTimeMS", ")", "{", "try", "{", "Duration", "duration", "=", "expiry", ".", "getExpiryForAccess", "(", ")", ";", "if", "(", "duration", ...
Sets the access expiration time. @param expirable the entry that was operated on @param currentTimeMS the current time, or 0 if not read yet
[ "Sets", "the", "access", "expiration", "time", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/jcache/src/main/java/com/github/benmanes/caffeine/jcache/CacheProxy.java#L1115-L1134
sahan/ZombieLink
zombielink/src/main/java/com/lonepulse/zombielink/util/Is.java
Is.hierarchyTerminal
public static boolean hierarchyTerminal(Class<?> type, List<String> packagePrefixes) { String name = type.getName(); if(packagePrefixes != null && !packagePrefixes.isEmpty()) { for (String packagePrefix : packagePrefixes) { if(name.startsWith(packagePrefix)) { return false; } } return true; } return name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("junit."); }
java
public static boolean hierarchyTerminal(Class<?> type, List<String> packagePrefixes) { String name = type.getName(); if(packagePrefixes != null && !packagePrefixes.isEmpty()) { for (String packagePrefix : packagePrefixes) { if(name.startsWith(packagePrefix)) { return false; } } return true; } return name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("junit."); }
[ "public", "static", "boolean", "hierarchyTerminal", "(", "Class", "<", "?", ">", "type", ",", "List", "<", "String", ">", "packagePrefixes", ")", "{", "String", "name", "=", "type", ".", "getName", "(", ")", ";", "if", "(", "packagePrefixes", "!=", "null...
<p>Determines if the given type terminates an endpoint lookup along an inheritance hierarchy.</p> <p>This evaluation is performed using a basic conditional check which will return {@code true} if the given type is in the specified packages list. If a package list is not provided, the hierarchy is deemed to have terminated if the given type is ina a package whose name starts with, <b>"java."</b>, <b>"javax."</b> or <b>"junit."</b>.</p> <p>Will be rendered obsolete if a future enhancement allows isolation of packages to scan for endpoint injection.</p> @param type the {@link Class} of the type to be checked for hierarchy termination <br><br> @param packagePrefixes the packages prefixes to restrict the inheritance hierarchy to; else {@code null} or {@code empty} to specify the <b>restriction packages</b> as "java.", "javax." or "junit." <br><br> @return {@code true} if this type represents a termination in the hierarchy <br><br> @since 1.2.4
[ "<p", ">", "Determines", "if", "the", "given", "type", "terminates", "an", "endpoint", "lookup", "along", "an", "inheritance", "hierarchy", ".", "<", "/", "p", ">" ]
train
https://github.com/sahan/ZombieLink/blob/a9971add56d4f6919a4a5e84c78e9220011d8982/zombielink/src/main/java/com/lonepulse/zombielink/util/Is.java#L144-L164
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryImpl.java
QueryImpl.populateUsingLucene
protected List<Object> populateUsingLucene(EntityMetadata m, Client client, List<Object> result, String[] columnsToSelect) { Set<Object> uniquePKs = null; MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); if (client.getIndexManager().getIndexer().getClass().getName().equals(IndexingConstants.LUCENE_INDEXER)) { String luceneQ = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata); Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), luceneQ, Constants.INVALID, Constants.INVALID); // Map<String, Object> searchFilter = // client.getIndexManager().search(kunderaMetadata, kunderaQuery, // persistenceDelegeator, m); boolean isEmbeddedId = metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()); if (isEmbeddedId) { return populateEmbeddedIdUsingLucene(m, client, result, searchFilter, metaModel); } Object[] primaryKeys = searchFilter.values().toArray(new Object[] {}); // Object[] primaryKeys = // ((List)searchFilter.get("primaryKeys")).toArray(new Object[] {}); uniquePKs = new HashSet<Object>(Arrays.asList(primaryKeys)); return findUsingLucene(m, client, uniquePKs.toArray()); } else { return populateUsingElasticSearch(client, m); } }
java
protected List<Object> populateUsingLucene(EntityMetadata m, Client client, List<Object> result, String[] columnsToSelect) { Set<Object> uniquePKs = null; MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); if (client.getIndexManager().getIndexer().getClass().getName().equals(IndexingConstants.LUCENE_INDEXER)) { String luceneQ = KunderaCoreUtils.getLuceneQueryFromJPAQuery(kunderaQuery, kunderaMetadata); Map<String, Object> searchFilter = client.getIndexManager().search(m.getEntityClazz(), luceneQ, Constants.INVALID, Constants.INVALID); // Map<String, Object> searchFilter = // client.getIndexManager().search(kunderaMetadata, kunderaQuery, // persistenceDelegeator, m); boolean isEmbeddedId = metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()); if (isEmbeddedId) { return populateEmbeddedIdUsingLucene(m, client, result, searchFilter, metaModel); } Object[] primaryKeys = searchFilter.values().toArray(new Object[] {}); // Object[] primaryKeys = // ((List)searchFilter.get("primaryKeys")).toArray(new Object[] {}); uniquePKs = new HashSet<Object>(Arrays.asList(primaryKeys)); return findUsingLucene(m, client, uniquePKs.toArray()); } else { return populateUsingElasticSearch(client, m); } }
[ "protected", "List", "<", "Object", ">", "populateUsingLucene", "(", "EntityMetadata", "m", ",", "Client", "client", ",", "List", "<", "Object", ">", "result", ",", "String", "[", "]", "columnsToSelect", ")", "{", "Set", "<", "Object", ">", "uniquePKs", "=...
Populate using lucene. @param m the m @param client the client @param result the result @param columnsToSelect List of column names to be selected (rest should be ignored) @return the list
[ "Populate", "using", "lucene", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/query/QueryImpl.java#L414-L450
fabric8io/docker-maven-plugin
src/main/java/io/fabric8/maven/docker/util/EnvUtil.java
EnvUtil.stringJoin
public static String stringJoin(List list, String separator) { StringBuilder ret = new StringBuilder(); boolean first = true; for (Object o : list) { if (!first) { ret.append(separator); } ret.append(o); first = false; } return ret.toString(); }
java
public static String stringJoin(List list, String separator) { StringBuilder ret = new StringBuilder(); boolean first = true; for (Object o : list) { if (!first) { ret.append(separator); } ret.append(o); first = false; } return ret.toString(); }
[ "public", "static", "String", "stringJoin", "(", "List", "list", ",", "String", "separator", ")", "{", "StringBuilder", "ret", "=", "new", "StringBuilder", "(", ")", ";", "boolean", "first", "=", "true", ";", "for", "(", "Object", "o", ":", "list", ")", ...
Join a list of objects to a string with a given separator by calling Object.toString() on the elements. @param list to join @param separator separator to use @return the joined string.
[ "Join", "a", "list", "of", "objects", "to", "a", "string", "with", "a", "given", "separator", "by", "calling", "Object", ".", "toString", "()", "on", "the", "elements", "." ]
train
https://github.com/fabric8io/docker-maven-plugin/blob/70ce4f56125d8efb8ddcf2ad4dbb5d6e2c7642b3/src/main/java/io/fabric8/maven/docker/util/EnvUtil.java#L187-L198
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java
SqlQueryStatement.appendColName
protected boolean appendColName(String attr, String attrAlias, boolean useOuterJoins, UserAlias aUserAlias, StringBuffer buf) { AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses()); TableAlias tableAlias = attrInfo.tableAlias; PathInfo pi = attrInfo.pathInfo; if (pi.suffix != null) { pi.suffix = pi.suffix + " as " + attrAlias; } else { pi.suffix = " as " + attrAlias; } return appendColName(tableAlias, pi, true, buf); }
java
protected boolean appendColName(String attr, String attrAlias, boolean useOuterJoins, UserAlias aUserAlias, StringBuffer buf) { AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses()); TableAlias tableAlias = attrInfo.tableAlias; PathInfo pi = attrInfo.pathInfo; if (pi.suffix != null) { pi.suffix = pi.suffix + " as " + attrAlias; } else { pi.suffix = " as " + attrAlias; } return appendColName(tableAlias, pi, true, buf); }
[ "protected", "boolean", "appendColName", "(", "String", "attr", ",", "String", "attrAlias", ",", "boolean", "useOuterJoins", ",", "UserAlias", "aUserAlias", ",", "StringBuffer", "buf", ")", "{", "AttributeInfo", "attrInfo", "=", "getAttributeInfo", "(", "attr", ",...
Append the appropriate ColumnName to the buffer<br> if a FIELDDESCRIPTOR is found for the Criteria the colName is taken from there otherwise its taken from Criteria. <br> field names in functions (ie: sum(name) ) are tried to resolve ie: name from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br> also resolve pathExpression adress.city or owner.konti.saldo
[ "Append", "the", "appropriate", "ColumnName", "to", "the", "buffer<br", ">", "if", "a", "FIELDDESCRIPTOR", "is", "found", "for", "the", "Criteria", "the", "colName", "is", "taken", "from", "there", "otherwise", "its", "taken", "from", "Criteria", ".", "<br", ...
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L456-L473
raphw/byte-buddy
byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/ClassLoaderResolver.java
ClassLoaderResolver.doResolve
private ClassLoader doResolve(Set<? extends File> classPath) { List<URL> urls = new ArrayList<URL>(classPath.size()); for (File file : classPath) { try { urls.add(file.toURI().toURL()); } catch (MalformedURLException exception) { throw new GradleException("Cannot resolve " + file + " as URL", exception); } } return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader()); }
java
private ClassLoader doResolve(Set<? extends File> classPath) { List<URL> urls = new ArrayList<URL>(classPath.size()); for (File file : classPath) { try { urls.add(file.toURI().toURL()); } catch (MalformedURLException exception) { throw new GradleException("Cannot resolve " + file + " as URL", exception); } } return new URLClassLoader(urls.toArray(new URL[0]), ByteBuddy.class.getClassLoader()); }
[ "private", "ClassLoader", "doResolve", "(", "Set", "<", "?", "extends", "File", ">", "classPath", ")", "{", "List", "<", "URL", ">", "urls", "=", "new", "ArrayList", "<", "URL", ">", "(", "classPath", ".", "size", "(", ")", ")", ";", "for", "(", "F...
Resolves a class path to a class loader. @param classPath The class path to consider. @return A class loader for the supplied class path.
[ "Resolves", "a", "class", "path", "to", "a", "class", "loader", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/ClassLoaderResolver.java#L88-L98
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/BooleanUtils.java
BooleanUtils.toBoolean
public static boolean toBoolean(final int value, final int trueValue, final int falseValue) { if (value == trueValue) { return true; } if (value == falseValue) { return false; } // no match throw new IllegalArgumentException("The Integer did not match either specified value"); }
java
public static boolean toBoolean(final int value, final int trueValue, final int falseValue) { if (value == trueValue) { return true; } if (value == falseValue) { return false; } // no match throw new IllegalArgumentException("The Integer did not match either specified value"); }
[ "public", "static", "boolean", "toBoolean", "(", "final", "int", "value", ",", "final", "int", "trueValue", ",", "final", "int", "falseValue", ")", "{", "if", "(", "value", "==", "trueValue", ")", "{", "return", "true", ";", "}", "if", "(", "value", "=...
<p>Converts an int to a boolean specifying the conversion values.</p> <pre> BooleanUtils.toBoolean(0, 1, 0) = false BooleanUtils.toBoolean(1, 1, 0) = true BooleanUtils.toBoolean(2, 1, 2) = false BooleanUtils.toBoolean(2, 2, 0) = true </pre> @param value the Integer to convert @param trueValue the value to match for {@code true} @param falseValue the value to match for {@code false} @return {@code true} or {@code false} @throws IllegalArgumentException if no match
[ "<p", ">", "Converts", "an", "int", "to", "a", "boolean", "specifying", "the", "conversion", "values", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/BooleanUtils.java#L260-L269
andrehertwig/admintool
admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java
AdminToolFilebrowserServiceImpl.isAllowed
protected boolean isAllowed(File path, boolean write) throws IOException { return isAllowedInternal(path, write, config.isReadOnly()); }
java
protected boolean isAllowed(File path, boolean write) throws IOException { return isAllowedInternal(path, write, config.isReadOnly()); }
[ "protected", "boolean", "isAllowed", "(", "File", "path", ",", "boolean", "write", ")", "throws", "IOException", "{", "return", "isAllowedInternal", "(", "path", ",", "write", ",", "config", ".", "isReadOnly", "(", ")", ")", ";", "}" ]
checks if file is allowed for access @param path @param write @return @throws IOException
[ "checks", "if", "file", "is", "allowed", "for", "access" ]
train
https://github.com/andrehertwig/admintool/blob/6d391e2d26969b70e3ccabfc34202abe8d915080/admin-tools-filebrowser/src/main/java/de/chandre/admintool/filebrowser/AdminToolFilebrowserServiceImpl.java#L516-L518
graphql-java/graphql-java
src/main/java/graphql/GraphQL.java
GraphQL.executeAsync
public CompletableFuture<ExecutionResult> executeAsync(ExecutionInput executionInput) { try { log.debug("Executing request. operation name: '{}'. query: '{}'. variables '{}'", executionInput.getOperationName(), executionInput.getQuery(), executionInput.getVariables()); InstrumentationState instrumentationState = instrumentation.createState(new InstrumentationCreateStateParameters(this.graphQLSchema, executionInput)); InstrumentationExecutionParameters inputInstrumentationParameters = new InstrumentationExecutionParameters(executionInput, this.graphQLSchema, instrumentationState); executionInput = instrumentation.instrumentExecutionInput(executionInput, inputInstrumentationParameters); InstrumentationExecutionParameters instrumentationParameters = new InstrumentationExecutionParameters(executionInput, this.graphQLSchema, instrumentationState); InstrumentationContext<ExecutionResult> executionInstrumentation = instrumentation.beginExecution(instrumentationParameters); GraphQLSchema graphQLSchema = instrumentation.instrumentSchema(this.graphQLSchema, instrumentationParameters); CompletableFuture<ExecutionResult> executionResult = parseValidateAndExecute(executionInput, graphQLSchema, instrumentationState); // // finish up instrumentation executionResult = executionResult.whenComplete(executionInstrumentation::onCompleted); // // allow instrumentation to tweak the result executionResult = executionResult.thenCompose(result -> instrumentation.instrumentExecutionResult(result, instrumentationParameters)); return executionResult; } catch (AbortExecutionException abortException) { return CompletableFuture.completedFuture(abortException.toExecutionResult()); } }
java
public CompletableFuture<ExecutionResult> executeAsync(ExecutionInput executionInput) { try { log.debug("Executing request. operation name: '{}'. query: '{}'. variables '{}'", executionInput.getOperationName(), executionInput.getQuery(), executionInput.getVariables()); InstrumentationState instrumentationState = instrumentation.createState(new InstrumentationCreateStateParameters(this.graphQLSchema, executionInput)); InstrumentationExecutionParameters inputInstrumentationParameters = new InstrumentationExecutionParameters(executionInput, this.graphQLSchema, instrumentationState); executionInput = instrumentation.instrumentExecutionInput(executionInput, inputInstrumentationParameters); InstrumentationExecutionParameters instrumentationParameters = new InstrumentationExecutionParameters(executionInput, this.graphQLSchema, instrumentationState); InstrumentationContext<ExecutionResult> executionInstrumentation = instrumentation.beginExecution(instrumentationParameters); GraphQLSchema graphQLSchema = instrumentation.instrumentSchema(this.graphQLSchema, instrumentationParameters); CompletableFuture<ExecutionResult> executionResult = parseValidateAndExecute(executionInput, graphQLSchema, instrumentationState); // // finish up instrumentation executionResult = executionResult.whenComplete(executionInstrumentation::onCompleted); // // allow instrumentation to tweak the result executionResult = executionResult.thenCompose(result -> instrumentation.instrumentExecutionResult(result, instrumentationParameters)); return executionResult; } catch (AbortExecutionException abortException) { return CompletableFuture.completedFuture(abortException.toExecutionResult()); } }
[ "public", "CompletableFuture", "<", "ExecutionResult", ">", "executeAsync", "(", "ExecutionInput", "executionInput", ")", "{", "try", "{", "log", ".", "debug", "(", "\"Executing request. operation name: '{}'. query: '{}'. variables '{}'\"", ",", "executionInput", ".", "getO...
Executes the graphql query using the provided input object <p> This will return a promise (aka {@link CompletableFuture}) to provide a {@link ExecutionResult} which is the result of executing the provided query. @param executionInput {@link ExecutionInput} @return a promise to an {@link ExecutionResult} which can include errors
[ "Executes", "the", "graphql", "query", "using", "the", "provided", "input", "object", "<p", ">", "This", "will", "return", "a", "promise", "(", "aka", "{", "@link", "CompletableFuture", "}", ")", "to", "provide", "a", "{", "@link", "ExecutionResult", "}", ...
train
https://github.com/graphql-java/graphql-java/blob/9214b6044317849388bd88a14b54fc1c18c9f29f/src/main/java/graphql/GraphQL.java#L482-L507
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/Utils.java
Utils.createFile
public static FileWriter createFile(String name, String outDir) throws IOException { File path = new File(outDir); if (!path.exists()) { if (!path.mkdirs()) throw new IOException("outdir can't be created"); } File file = new File(path.getAbsolutePath() + File.separatorChar + name); if (file.exists()) { if (!file.delete()) throw new IOException("there is exist file, please check"); } return new FileWriter(file); }
java
public static FileWriter createFile(String name, String outDir) throws IOException { File path = new File(outDir); if (!path.exists()) { if (!path.mkdirs()) throw new IOException("outdir can't be created"); } File file = new File(path.getAbsolutePath() + File.separatorChar + name); if (file.exists()) { if (!file.delete()) throw new IOException("there is exist file, please check"); } return new FileWriter(file); }
[ "public", "static", "FileWriter", "createFile", "(", "String", "name", ",", "String", "outDir", ")", "throws", "IOException", "{", "File", "path", "=", "new", "File", "(", "outDir", ")", ";", "if", "(", "!", "path", ".", "exists", "(", ")", ")", "{", ...
Create file @param name The name of the class @param outDir output directory @return The file @throws IOException Thrown if an error occurs
[ "Create", "file" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/Utils.java#L169-L187
ckpoint/CheckPoint
src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java
MsgSettingController.downloadApi
@GetMapping("/setting/download/api/excel") public void downloadApi(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { this.validationSessionComponent.sessionCheck(req); url = new String(Base64.getDecoder().decode(url)); PoiWorkBook workBook = this.msgExcelService.getExcel(method, url); workBook.writeFile("ValidationApis_" + System.currentTimeMillis(), res); }
java
@GetMapping("/setting/download/api/excel") public void downloadApi(HttpServletRequest req, @RequestParam("method") String method, @RequestParam("url") String url, HttpServletResponse res) { this.validationSessionComponent.sessionCheck(req); url = new String(Base64.getDecoder().decode(url)); PoiWorkBook workBook = this.msgExcelService.getExcel(method, url); workBook.writeFile("ValidationApis_" + System.currentTimeMillis(), res); }
[ "@", "GetMapping", "(", "\"/setting/download/api/excel\"", ")", "public", "void", "downloadApi", "(", "HttpServletRequest", "req", ",", "@", "RequestParam", "(", "\"method\"", ")", "String", "method", ",", "@", "RequestParam", "(", "\"url\"", ")", "String", "url",...
Download api. @param req the req @param method the method @param url the url @param res the res
[ "Download", "api", "." ]
train
https://github.com/ckpoint/CheckPoint/blob/2c2b1a87a88485d49ea6afa34acdf16ef4134f19/src/main/java/hsim/checkpoint/setting/controller/MsgSettingController.java#L118-L124
spring-projects/spring-boot
spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java
TomcatEmbeddedContext.doWithThreadContextClassLoader
private void doWithThreadContextClassLoader(ClassLoader classLoader, Runnable code) { ClassLoader existingLoader = (classLoader != null) ? ClassUtils.overrideThreadContextClassLoader(classLoader) : null; try { code.run(); } finally { if (existingLoader != null) { ClassUtils.overrideThreadContextClassLoader(existingLoader); } } }
java
private void doWithThreadContextClassLoader(ClassLoader classLoader, Runnable code) { ClassLoader existingLoader = (classLoader != null) ? ClassUtils.overrideThreadContextClassLoader(classLoader) : null; try { code.run(); } finally { if (existingLoader != null) { ClassUtils.overrideThreadContextClassLoader(existingLoader); } } }
[ "private", "void", "doWithThreadContextClassLoader", "(", "ClassLoader", "classLoader", ",", "Runnable", "code", ")", "{", "ClassLoader", "existingLoader", "=", "(", "classLoader", "!=", "null", ")", "?", "ClassUtils", ".", "overrideThreadContextClassLoader", "(", "cl...
Some older Servlet frameworks (e.g. Struts, BIRT) use the Thread context class loader to create servlet instances in this phase. If they do that and then try to initialize them later the class loader may have changed, so wrap the call to loadOnStartup in what we think its going to be the main webapp classloader at runtime. @param classLoader the class loader to use @param code the code to run
[ "Some", "older", "Servlet", "frameworks", "(", "e", ".", "g", ".", "Struts", "BIRT", ")", "use", "the", "Thread", "context", "class", "loader", "to", "create", "servlet", "instances", "in", "this", "phase", ".", "If", "they", "do", "that", "and", "then",...
train
https://github.com/spring-projects/spring-boot/blob/0b27f7c70e164b2b1a96477f1d9c1acba56790c1/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/web/embedded/tomcat/TomcatEmbeddedContext.java#L104-L115
VoltDB/voltdb
third_party/java/src/org/HdrHistogram_voltpatches/AbstractHistogramLogReader.java
AbstractHistogramLogReader.nextAbsoluteIntervalHistogram
public EncodableHistogram nextAbsoluteIntervalHistogram(final Double absoluteStartTimeSec, final Double absoluteEndTimeSec) { return nextIntervalHistogram(absoluteStartTimeSec, absoluteEndTimeSec, true); }
java
public EncodableHistogram nextAbsoluteIntervalHistogram(final Double absoluteStartTimeSec, final Double absoluteEndTimeSec) { return nextIntervalHistogram(absoluteStartTimeSec, absoluteEndTimeSec, true); }
[ "public", "EncodableHistogram", "nextAbsoluteIntervalHistogram", "(", "final", "Double", "absoluteStartTimeSec", ",", "final", "Double", "absoluteEndTimeSec", ")", "{", "return", "nextIntervalHistogram", "(", "absoluteStartTimeSec", ",", "absoluteEndTimeSec", ",", "true", "...
Read the next interval histogram from the log, if interval falls within an absolute time range <p> Returns a histogram object if an interval line was found with an associated absolute start timestamp value that falls between absoluteStartTimeSec and absoluteEndTimeSec, or null if no such interval line is found. <p> Timestamps are assumed to appear in order in the log file, and as such this method will return a null upon encountering a timestamp larger than rangeEndTimeSec. <p> The histogram returned will have it's timestamp set to the absolute timestamp calculated from adding the interval's indicated timestamp value to the latest [optional] start time found in the log. <p> Absolute timestamps are calculated by adding the timestamp found with the recorded interval to the [latest, optional] start time found in the log. The start time is indicated in the log with a "#[StartTime: " followed by the start time in seconds. <p> Upon encountering any unexpected format errors in reading the next interval from the file, this method will return a null. @param absoluteStartTimeSec The (absolute time) start of the expected time range, in seconds. @param absoluteEndTimeSec The (absolute time) end of the expected time range, in seconds. @return A histogram, or a null if no appropriate interval found
[ "Read", "the", "next", "interval", "histogram", "from", "the", "log", "if", "interval", "falls", "within", "an", "absolute", "time", "range", "<p", ">", "Returns", "a", "histogram", "object", "if", "an", "interval", "line", "was", "found", "with", "an", "a...
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/third_party/java/src/org/HdrHistogram_voltpatches/AbstractHistogramLogReader.java#L135-L138
alkacon/opencms-core
src/org/opencms/ade/containerpage/CmsAddDialogTypeHelper.java
CmsAddDialogTypeHelper.precomputeTypeLists
public void precomputeTypeLists( CmsObject cms, String folderRootPath, String checkViewableReferenceUri, List<CmsElementView> views, I_CmsResourceTypeEnabledCheck check) { Multimap<CmsUUID, CmsResourceTypeBean> result = ArrayListMultimap.create(); // Sort list to make sure that 'Other types' view is processed last, because we may need to display // types filtered / removed from other views, which we only know once we have processed these views Collections.sort(views, new Comparator<CmsElementView>() { public int compare(CmsElementView view0, CmsElementView view1) { return ComparisonChain.start().compareFalseFirst(view0.isOther(), view1.isOther()).result(); } }); for (CmsElementView view : views) { try { result.putAll( view.getId(), getResourceTypes(cms, folderRootPath, checkViewableReferenceUri, view, check)); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } m_cachedTypes = result; }
java
public void precomputeTypeLists( CmsObject cms, String folderRootPath, String checkViewableReferenceUri, List<CmsElementView> views, I_CmsResourceTypeEnabledCheck check) { Multimap<CmsUUID, CmsResourceTypeBean> result = ArrayListMultimap.create(); // Sort list to make sure that 'Other types' view is processed last, because we may need to display // types filtered / removed from other views, which we only know once we have processed these views Collections.sort(views, new Comparator<CmsElementView>() { public int compare(CmsElementView view0, CmsElementView view1) { return ComparisonChain.start().compareFalseFirst(view0.isOther(), view1.isOther()).result(); } }); for (CmsElementView view : views) { try { result.putAll( view.getId(), getResourceTypes(cms, folderRootPath, checkViewableReferenceUri, view, check)); } catch (Exception e) { LOG.error(e.getLocalizedMessage(), e); } } m_cachedTypes = result; }
[ "public", "void", "precomputeTypeLists", "(", "CmsObject", "cms", ",", "String", "folderRootPath", ",", "String", "checkViewableReferenceUri", ",", "List", "<", "CmsElementView", ">", "views", ",", "I_CmsResourceTypeEnabledCheck", "check", ")", "{", "Multimap", "<", ...
Precomputes type lists for multiple views.<p> @param cms the CMS context @param folderRootPath the current folder @param checkViewableReferenceUri the reference uri to use for viewability check @param views the views for which to generate the type lists @param check object to check whether resource types should be enabled
[ "Precomputes", "type", "lists", "for", "multiple", "views", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/containerpage/CmsAddDialogTypeHelper.java#L181-L210
google/closure-templates
java/src/com/google/template/soy/jbcsrc/restricted/SoyExpression.java
SoyExpression.unboxAsMessage
public Expression unboxAsMessage() { if (soyType().getKind() == Kind.NULL) { // If this is a null literal, return a Messaged-typed null literal. return BytecodeUtils.constantNull(BytecodeUtils.MESSAGE_TYPE); } // Attempting to unbox an unboxed proto // (We compare the non-nullable type because being null doesn't impact unboxability, // and if we didn't remove null then isKnownProtoOrUnionOfProtos would fail.) if (soyRuntimeType.asNonNullable().isKnownProtoOrUnionOfProtos() && !isBoxed()) { return this; } if (delegate.isNonNullable()) { return delegate.invoke(MethodRef.SOY_PROTO_VALUE_GET_PROTO); } return new Expression(BytecodeUtils.MESSAGE_TYPE, features()) { @Override protected void doGen(CodeBuilder adapter) { Label end = new Label(); delegate.gen(adapter); BytecodeUtils.nullCoalesce(adapter, end); MethodRef.SOY_PROTO_VALUE_GET_PROTO.invokeUnchecked(adapter); adapter.mark(end); } }; }
java
public Expression unboxAsMessage() { if (soyType().getKind() == Kind.NULL) { // If this is a null literal, return a Messaged-typed null literal. return BytecodeUtils.constantNull(BytecodeUtils.MESSAGE_TYPE); } // Attempting to unbox an unboxed proto // (We compare the non-nullable type because being null doesn't impact unboxability, // and if we didn't remove null then isKnownProtoOrUnionOfProtos would fail.) if (soyRuntimeType.asNonNullable().isKnownProtoOrUnionOfProtos() && !isBoxed()) { return this; } if (delegate.isNonNullable()) { return delegate.invoke(MethodRef.SOY_PROTO_VALUE_GET_PROTO); } return new Expression(BytecodeUtils.MESSAGE_TYPE, features()) { @Override protected void doGen(CodeBuilder adapter) { Label end = new Label(); delegate.gen(adapter); BytecodeUtils.nullCoalesce(adapter, end); MethodRef.SOY_PROTO_VALUE_GET_PROTO.invokeUnchecked(adapter); adapter.mark(end); } }; }
[ "public", "Expression", "unboxAsMessage", "(", ")", "{", "if", "(", "soyType", "(", ")", ".", "getKind", "(", ")", "==", "Kind", ".", "NULL", ")", "{", "// If this is a null literal, return a Messaged-typed null literal.", "return", "BytecodeUtils", ".", "constantNu...
Unboxes this to a {@link SoyExpression} with a Message runtime type. <p>This method is appropriate when you know (likely via inspection of the {@link #soyType()}, or other means) that the value does have the appropriate type but you prefer to interact with it as its unboxed representation.
[ "Unboxes", "this", "to", "a", "{", "@link", "SoyExpression", "}", "with", "a", "Message", "runtime", "type", "." ]
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/jbcsrc/restricted/SoyExpression.java#L562-L587
xiancloud/xian
xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/units/DaoUnit.java
DaoUnit.isTransactional
private boolean isTransactional(SqlAction[] sqlActions, XianTransaction transaction) { int count = 0; for (SqlAction sqlAction : sqlActions) { if (!(sqlAction instanceof ISelect)) { count++; } } return count > 1 || transaction.isBegun(); }
java
private boolean isTransactional(SqlAction[] sqlActions, XianTransaction transaction) { int count = 0; for (SqlAction sqlAction : sqlActions) { if (!(sqlAction instanceof ISelect)) { count++; } } return count > 1 || transaction.isBegun(); }
[ "private", "boolean", "isTransactional", "(", "SqlAction", "[", "]", "sqlActions", ",", "XianTransaction", "transaction", ")", "{", "int", "count", "=", "0", ";", "for", "(", "SqlAction", "sqlAction", ":", "sqlActions", ")", "{", "if", "(", "!", "(", "sqlA...
judge whether we need to begin the transaction. If there are more than one non-query sql actions in this dao unit, a new transaction will be begun. if a transaction is already begun, a nested transaction will be begun. Else no transaction will be begun. @return true if this unit is transacitonal false otherwise.
[ "judge", "whether", "we", "need", "to", "begin", "the", "transaction", ".", "If", "there", "are", "more", "than", "one", "non", "-", "query", "sql", "actions", "in", "this", "dao", "unit", "a", "new", "transaction", "will", "be", "begun", ".", "if", "a...
train
https://github.com/xiancloud/xian/blob/1948e088545553d2745b2c86d8b5a64988bb850e/xian-dao/xian-daocore/src/main/java/info/xiancloud/dao/core/units/DaoUnit.java#L137-L145
AzureAD/azure-activedirectory-library-for-java
src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/JSONHelper.java
JSONHelper.convertJSONObjectToDirectoryObject
public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject) throws Exception { // Get the list of all the field names. Field[] fieldList = destObject.getClass().getDeclaredFields(); // For all the declared field. for (int i = 0; i < fieldList.length; i++) { // If the field is of type String, that is // if it is a simple attribute. if (fieldList[i].getType().equals(String.class)) { // Invoke the corresponding set method of the destObject using // the argument taken from the jsonObject. destObject .getClass() .getMethod(String.format("set%s", WordUtils.capitalize(fieldList[i].getName())), new Class[] { String.class }) .invoke(destObject, new Object[] { jsonObject.optString(fieldList[i].getName()) }); } } }
java
public static <T> void convertJSONObjectToDirectoryObject(JSONObject jsonObject, T destObject) throws Exception { // Get the list of all the field names. Field[] fieldList = destObject.getClass().getDeclaredFields(); // For all the declared field. for (int i = 0; i < fieldList.length; i++) { // If the field is of type String, that is // if it is a simple attribute. if (fieldList[i].getType().equals(String.class)) { // Invoke the corresponding set method of the destObject using // the argument taken from the jsonObject. destObject .getClass() .getMethod(String.format("set%s", WordUtils.capitalize(fieldList[i].getName())), new Class[] { String.class }) .invoke(destObject, new Object[] { jsonObject.optString(fieldList[i].getName()) }); } } }
[ "public", "static", "<", "T", ">", "void", "convertJSONObjectToDirectoryObject", "(", "JSONObject", "jsonObject", ",", "T", "destObject", ")", "throws", "Exception", "{", "// Get the list of all the field names.\r", "Field", "[", "]", "fieldList", "=", "destObject", "...
This is a generic method that copies the simple attribute values from an argument jsonObject to an argument generic object. @param jsonObject The jsonObject from where the attributes are to be copied. @param destObject The object where the attributes should be copied into. @throws Exception Throws a Exception when the operation are unsuccessful.
[ "This", "is", "a", "generic", "method", "that", "copies", "the", "simple", "attribute", "values", "from", "an", "argument", "jsonObject", "to", "an", "argument", "generic", "object", "." ]
train
https://github.com/AzureAD/azure-activedirectory-library-for-java/blob/7f0004fee6faee5818e75623113993a267ceb1c4/src/samples/web-app-samples-for-adal4j/src/main/java/com/microsoft/aad/adal4jsample/JSONHelper.java#L207-L226
litsec/eidas-opensaml
opensaml2/src/main/java/se/litsec/eidas/opensaml2/ext/attributes/impl/CurrentAddressTypeUnmarshaller.java
CurrentAddressTypeUnmarshaller.getNamespaceBindings
private static void getNamespaceBindings(Element element, Map<String, String> namespaceMap) { if (element == null) { return; } NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node node = attrs.item(i); String name = node.getNodeName(); if ((name != null && (XMLConstants.XMLNS_ATTRIBUTE.equals(name) || name.startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")))) { namespaceMap.put(name, node.getNodeValue()); } } Node parent = element.getParentNode(); if (parent instanceof Element) { getNamespaceBindings((Element) parent, namespaceMap); } }
java
private static void getNamespaceBindings(Element element, Map<String, String> namespaceMap) { if (element == null) { return; } NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node node = attrs.item(i); String name = node.getNodeName(); if ((name != null && (XMLConstants.XMLNS_ATTRIBUTE.equals(name) || name.startsWith(XMLConstants.XMLNS_ATTRIBUTE + ":")))) { namespaceMap.put(name, node.getNodeValue()); } } Node parent = element.getParentNode(); if (parent instanceof Element) { getNamespaceBindings((Element) parent, namespaceMap); } }
[ "private", "static", "void", "getNamespaceBindings", "(", "Element", "element", ",", "Map", "<", "String", ",", "String", ">", "namespaceMap", ")", "{", "if", "(", "element", "==", "null", ")", "{", "return", ";", "}", "NamedNodeMap", "attrs", "=", "elemen...
Helper method to {@link #getNamespaceBindings(Element)} @param element the element to parse @param namespaceMap the map to fill
[ "Helper", "method", "to", "{", "@link", "#getNamespaceBindings", "(", "Element", ")", "}" ]
train
https://github.com/litsec/eidas-opensaml/blob/522ba6dba433a9524cb8a02464cc3b087b47a2b7/opensaml2/src/main/java/se/litsec/eidas/opensaml2/ext/attributes/impl/CurrentAddressTypeUnmarshaller.java#L172-L188
baratine/baratine
web/src/main/java/com/caucho/v5/http/protocol/RequestHttpBase.java
RequestHttpBase.getHeaderBuffers
public void getHeaderBuffers(String name, ArrayList<CharSegment> resultList) { String value = header(name); if (value != null) resultList.add(new CharBuffer(value)); }
java
public void getHeaderBuffers(String name, ArrayList<CharSegment> resultList) { String value = header(name); if (value != null) resultList.add(new CharBuffer(value)); }
[ "public", "void", "getHeaderBuffers", "(", "String", "name", ",", "ArrayList", "<", "CharSegment", ">", "resultList", ")", "{", "String", "value", "=", "header", "(", "name", ")", ";", "if", "(", "value", "!=", "null", ")", "resultList", ".", "add", "(",...
Fills the result with a list of the header values as CharSegment values. Most implementations will implement this directly. @param name the header name @param resultList the resulting buffer
[ "Fills", "the", "result", "with", "a", "list", "of", "the", "header", "values", "as", "CharSegment", "values", ".", "Most", "implementations", "will", "implement", "this", "directly", "." ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/web/src/main/java/com/caucho/v5/http/protocol/RequestHttpBase.java#L973-L979
canoo/open-dolphin
subprojects/server/src/main/groovy/org/opendolphin/server/adapter/DolphinServlet.java
DolphinServlet.writeOutput
protected void writeOutput(HttpServletResponse response, String output) throws ServletException, IOException { response.getWriter().print(output); response.getWriter().flush(); }
java
protected void writeOutput(HttpServletResponse response, String output) throws ServletException, IOException { response.getWriter().print(output); response.getWriter().flush(); }
[ "protected", "void", "writeOutput", "(", "HttpServletResponse", "response", ",", "String", "output", ")", "throws", "ServletException", ",", "IOException", "{", "response", ".", "getWriter", "(", ")", ".", "print", "(", "output", ")", ";", "response", ".", "ge...
Writes the encoded outgoing commands to the {@code response}. @param response - an HttpServletResponse object that contains the response the servlet sends to the client @param output - the encoded collection of commands to be sent back to the client @throws IOException - if an input or output error is detected when the servlet handles the request @throws ServletException - if the request for the POST could not be handled
[ "Writes", "the", "encoded", "outgoing", "commands", "to", "the", "{", "@code", "response", "}", "." ]
train
https://github.com/canoo/open-dolphin/blob/50166defc3ef2de473d7a7246c32dc04304d80ef/subprojects/server/src/main/groovy/org/opendolphin/server/adapter/DolphinServlet.java#L237-L240
tango-controls/JTango
server/src/main/java/org/tango/server/ServerManager.java
ServerManager.configureNoDBFile
private void configureNoDBFile(final String argv[], final String arg, final List<String> noDbDevices) throws DevFailed { if (!ArrayUtils.contains(argv, NODB)) { throw DevFailedUtils.newDevFailed(INIT_ERROR, getUsage()); } else { final String name = arg.split("=")[1]; final File file = new File(name); if (!file.exists() && !file.isFile()) { throw DevFailedUtils.newDevFailed(INIT_ERROR, name + " does not exists or is not a file"); } logger.warn("Tango Database is not used - with file {} ", file.getPath()); DatabaseFactory.setDbFile(file, noDbDevices.toArray(new String[0]), lastClass); } }
java
private void configureNoDBFile(final String argv[], final String arg, final List<String> noDbDevices) throws DevFailed { if (!ArrayUtils.contains(argv, NODB)) { throw DevFailedUtils.newDevFailed(INIT_ERROR, getUsage()); } else { final String name = arg.split("=")[1]; final File file = new File(name); if (!file.exists() && !file.isFile()) { throw DevFailedUtils.newDevFailed(INIT_ERROR, name + " does not exists or is not a file"); } logger.warn("Tango Database is not used - with file {} ", file.getPath()); DatabaseFactory.setDbFile(file, noDbDevices.toArray(new String[0]), lastClass); } }
[ "private", "void", "configureNoDBFile", "(", "final", "String", "argv", "[", "]", ",", "final", "String", "arg", ",", "final", "List", "<", "String", ">", "noDbDevices", ")", "throws", "DevFailed", "{", "if", "(", "!", "ArrayUtils", ".", "contains", "(", ...
Configure {@link DatabaseFactory} without a tango db and a file for properties @param argv @param arg @param noDbDevices @throws DevFailed
[ "Configure", "{", "@link", "DatabaseFactory", "}", "without", "a", "tango", "db", "and", "a", "file", "for", "properties" ]
train
https://github.com/tango-controls/JTango/blob/1ccc9dcb83e6de2359a9f1906d170571cacf1345/server/src/main/java/org/tango/server/ServerManager.java#L390-L404
kirgor/enklib
common/src/main/java/com/kirgor/enklib/common/NamingUtils.java
NamingUtils.camelToSnake
public static String camelToSnake(String camel, boolean upper) { StringBuilder stringBuilder = new StringBuilder(); for (char c : camel.toCharArray()) { char nc = upper ? Character.toUpperCase(c) : Character.toLowerCase(c); if (Character.isUpperCase(c)) { stringBuilder.append('_').append(nc); } else { stringBuilder.append(nc); } } return stringBuilder.toString(); }
java
public static String camelToSnake(String camel, boolean upper) { StringBuilder stringBuilder = new StringBuilder(); for (char c : camel.toCharArray()) { char nc = upper ? Character.toUpperCase(c) : Character.toLowerCase(c); if (Character.isUpperCase(c)) { stringBuilder.append('_').append(nc); } else { stringBuilder.append(nc); } } return stringBuilder.toString(); }
[ "public", "static", "String", "camelToSnake", "(", "String", "camel", ",", "boolean", "upper", ")", "{", "StringBuilder", "stringBuilder", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "char", "c", ":", "camel", ".", "toCharArray", "(", ")", ")",...
Converts camel case string (lower or upper/Pascal) to snake case, for example 'helloWorld' or 'HelloWorld' -> 'hello_world'. @param camel Input string. @param upper True if result snake cased string should be upper cased like 'HELLO_WORLD'.
[ "Converts", "camel", "case", "string", "(", "lower", "or", "upper", "/", "Pascal", ")", "to", "snake", "case", "for", "example", "helloWorld", "or", "HelloWorld", "-", ">", "hello_world", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/common/src/main/java/com/kirgor/enklib/common/NamingUtils.java#L30-L41
mbenson/uelbox
src/main/java/uelbox/ELContextWrapper.java
ELContextWrapper.getTypedContext
public final <T> T getTypedContext(Class<T> key, T defaultValue) { return UEL.getContext(this, key, defaultValue); }
java
public final <T> T getTypedContext(Class<T> key, T defaultValue) { return UEL.getContext(this, key, defaultValue); }
[ "public", "final", "<", "T", ">", "T", "getTypedContext", "(", "Class", "<", "T", ">", "key", ",", "T", "defaultValue", ")", "{", "return", "UEL", ".", "getContext", "(", "this", ",", "key", ",", "defaultValue", ")", ";", "}" ]
Convenience method to return a typed context object when key resolves per documented convention to an object of the same type. @param <T> @param key @param defaultValue if absent @return T @see ELContext#getContext(Class)
[ "Convenience", "method", "to", "return", "a", "typed", "context", "object", "when", "key", "resolves", "per", "documented", "convention", "to", "an", "object", "of", "the", "same", "type", "." ]
train
https://github.com/mbenson/uelbox/blob/b0c2df2c738295bddfd3c16a916e67c9c7c512ef/src/main/java/uelbox/ELContextWrapper.java#L151-L153
UrielCh/ovh-java-sdk
ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java
ApiOvhCaasregistry.serviceName_namespaces_namespaceId_DELETE
public void serviceName_namespaces_namespaceId_DELETE(String serviceName, String namespaceId) throws IOException { String qPath = "/caas/registry/{serviceName}/namespaces/{namespaceId}"; StringBuilder sb = path(qPath, serviceName, namespaceId); exec(qPath, "DELETE", sb.toString(), null); }
java
public void serviceName_namespaces_namespaceId_DELETE(String serviceName, String namespaceId) throws IOException { String qPath = "/caas/registry/{serviceName}/namespaces/{namespaceId}"; StringBuilder sb = path(qPath, serviceName, namespaceId); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "serviceName_namespaces_namespaceId_DELETE", "(", "String", "serviceName", ",", "String", "namespaceId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/caas/registry/{serviceName}/namespaces/{namespaceId}\"", ";", "StringBuilder", "sb", "=", ...
Delete namespace REST: DELETE /caas/registry/{serviceName}/namespaces/{namespaceId} @param namespaceId [required] Namespace id @param serviceName [required] Service name API beta
[ "Delete", "namespace" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-caasregistry/src/main/java/net/minidev/ovh/api/ApiOvhCaasregistry.java#L372-L376
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/StreamTokenizer.java
StreamTokenizer.wordChars
public void wordChars(int low, int hi) { if (low < 0) { low = 0; } if (hi > tokenTypes.length) { hi = tokenTypes.length - 1; } for (int i = low; i <= hi; i++) { tokenTypes[i] |= TOKEN_WORD; } }
java
public void wordChars(int low, int hi) { if (low < 0) { low = 0; } if (hi > tokenTypes.length) { hi = tokenTypes.length - 1; } for (int i = low; i <= hi; i++) { tokenTypes[i] |= TOKEN_WORD; } }
[ "public", "void", "wordChars", "(", "int", "low", ",", "int", "hi", ")", "{", "if", "(", "low", "<", "0", ")", "{", "low", "=", "0", ";", "}", "if", "(", "hi", ">", "tokenTypes", ".", "length", ")", "{", "hi", "=", "tokenTypes", ".", "length", ...
Specifies that the characters in the range from {@code low} to {@code hi} shall be treated as word characters by this tokenizer. A word consists of a word character followed by zero or more word or number characters. @param low the first character in the range of word characters. @param hi the last character in the range of word characters.
[ "Specifies", "that", "the", "characters", "in", "the", "range", "from", "{", "@code", "low", "}", "to", "{", "@code", "hi", "}", "shall", "be", "treated", "as", "word", "characters", "by", "this", "tokenizer", ".", "A", "word", "consists", "of", "a", "...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/io/StreamTokenizer.java#L664-L674
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaEndpointActivation.java
SibRaEndpointActivation.closeConnection
protected void closeConnection(final String meUuid, boolean alreadyClosed) { final String methodName = "closeConnection"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object [] { meUuid, alreadyClosed }); } final SibRaMessagingEngineConnection connection; synchronized (_connections) { connection = (SibRaMessagingEngineConnection) _connections .remove(meUuid); } if (connection != null) { connection.close(alreadyClosed); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
java
protected void closeConnection(final String meUuid, boolean alreadyClosed) { final String methodName = "closeConnection"; if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.entry(this, TRACE, methodName, new Object [] { meUuid, alreadyClosed }); } final SibRaMessagingEngineConnection connection; synchronized (_connections) { connection = (SibRaMessagingEngineConnection) _connections .remove(meUuid); } if (connection != null) { connection.close(alreadyClosed); } if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) { SibTr.exit(this, TRACE, methodName); } }
[ "protected", "void", "closeConnection", "(", "final", "String", "meUuid", ",", "boolean", "alreadyClosed", ")", "{", "final", "String", "methodName", "=", "\"closeConnection\"", ";", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "TRACE",...
Closes the connection for the given messaging engine if there is one open. @param meUuid the UUID for the messaging engine to close the connection for @param alreadyClosed if the connection has already been closed
[ "Closes", "the", "connection", "for", "the", "given", "messaging", "engine", "if", "there", "is", "one", "open", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.jms.2.0/src/com/ibm/ws/sib/ra/inbound/impl/SibRaEndpointActivation.java#L522-L545
joniles/mpxj
src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java
MSPDIReader.readCostRateTables
private void readCostRateTables(Resource resource, Rates rates) { if (rates == null) { CostRateTable table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(0, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(1, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(2, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(3, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(4, table); } else { Set<CostRateTable> tables = new HashSet<CostRateTable>(); for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate()) { Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate()); TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat()); Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate()); TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat()); Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse()); Date endDate = rate.getRatesTo(); CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate); int tableIndex = rate.getRateTable().intValue(); CostRateTable table = resource.getCostRateTable(tableIndex); if (table == null) { table = new CostRateTable(); resource.setCostRateTable(tableIndex, table); } table.add(entry); tables.add(table); } for (CostRateTable table : tables) { Collections.sort(table); } } }
java
private void readCostRateTables(Resource resource, Rates rates) { if (rates == null) { CostRateTable table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(0, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(1, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(2, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(3, table); table = new CostRateTable(); table.add(CostRateTableEntry.DEFAULT_ENTRY); resource.setCostRateTable(4, table); } else { Set<CostRateTable> tables = new HashSet<CostRateTable>(); for (net.sf.mpxj.mspdi.schema.Project.Resources.Resource.Rates.Rate rate : rates.getRate()) { Rate standardRate = DatatypeConverter.parseRate(rate.getStandardRate()); TimeUnit standardRateFormat = DatatypeConverter.parseTimeUnit(rate.getStandardRateFormat()); Rate overtimeRate = DatatypeConverter.parseRate(rate.getOvertimeRate()); TimeUnit overtimeRateFormat = DatatypeConverter.parseTimeUnit(rate.getOvertimeRateFormat()); Double costPerUse = DatatypeConverter.parseCurrency(rate.getCostPerUse()); Date endDate = rate.getRatesTo(); CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate); int tableIndex = rate.getRateTable().intValue(); CostRateTable table = resource.getCostRateTable(tableIndex); if (table == null) { table = new CostRateTable(); resource.setCostRateTable(tableIndex, table); } table.add(entry); tables.add(table); } for (CostRateTable table : tables) { Collections.sort(table); } } }
[ "private", "void", "readCostRateTables", "(", "Resource", "resource", ",", "Rates", "rates", ")", "{", "if", "(", "rates", "==", "null", ")", "{", "CostRateTable", "table", "=", "new", "CostRateTable", "(", ")", ";", "table", ".", "add", "(", "CostRateTabl...
Reads the cost rate tables from the file. @param resource parent resource @param rates XML cot rate tables
[ "Reads", "the", "cost", "rate", "tables", "from", "the", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/mspdi/MSPDIReader.java#L1023-L1078
termsuite/termsuite-core
src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java
TermOccurrenceUtils.hasOverlappingOffsets
public static boolean hasOverlappingOffsets(TermOccurrence theOcc, Collection<TermOccurrence> theOccCollection) { for(TermOccurrence o:theOccCollection) if(areOffsetsOverlapping(theOcc, o)) return true; return false; }
java
public static boolean hasOverlappingOffsets(TermOccurrence theOcc, Collection<TermOccurrence> theOccCollection) { for(TermOccurrence o:theOccCollection) if(areOffsetsOverlapping(theOcc, o)) return true; return false; }
[ "public", "static", "boolean", "hasOverlappingOffsets", "(", "TermOccurrence", "theOcc", ",", "Collection", "<", "TermOccurrence", ">", "theOccCollection", ")", "{", "for", "(", "TermOccurrence", "o", ":", "theOccCollection", ")", "if", "(", "areOffsetsOverlapping", ...
True if an occurrence set contains any element overlapping with the param occurrence. @param theOcc @param theOccCollection @return
[ "True", "if", "an", "occurrence", "set", "contains", "any", "element", "overlapping", "with", "the", "param", "occurrence", "." ]
train
https://github.com/termsuite/termsuite-core/blob/731e5d0bc7c14180713c01a9c7dffe1925f26130/src/main/java/fr/univnantes/termsuite/utils/TermOccurrenceUtils.java#L135-L140
jenkinsci/support-core-plugin
src/main/java/com/cloudbees/jenkins/support/util/WordReplacer.java
WordReplacer.replaceWordsIgnoreCase
public static String replaceWordsIgnoreCase(String input, String[] words, String[] replaces) { StringBuilder sb = new StringBuilder(input); replaceWordsIgnoreCase(sb, words, replaces); return sb.toString(); }
java
public static String replaceWordsIgnoreCase(String input, String[] words, String[] replaces) { StringBuilder sb = new StringBuilder(input); replaceWordsIgnoreCase(sb, words, replaces); return sb.toString(); }
[ "public", "static", "String", "replaceWordsIgnoreCase", "(", "String", "input", ",", "String", "[", "]", "words", ",", "String", "[", "]", "replaces", ")", "{", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", "input", ")", ";", "replaceWordsIgnoreCase...
Replace all words in the input by the replaces. The replacements happens only if the texts to replace are not part of a greater word, that is, if the text is a whole word, separated by non {@link Character#isLetterOrDigit(char)} characters. @param input the text where the replacements take place @param words the words to look for and replace @param replaces the new words to use
[ "Replace", "all", "words", "in", "the", "input", "by", "the", "replaces", ".", "The", "replacements", "happens", "only", "if", "the", "texts", "to", "replace", "are", "not", "part", "of", "a", "greater", "word", "that", "is", "if", "the", "text", "is", ...
train
https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/util/WordReplacer.java#L28-L32
Ardesco/selenium-standalone-server-plugin
src/main/java/com/lazerycode/selenium/extract/FileExtractor.java
FileExtractor.untarFile
private String untarFile(InputStream compressedFileInputStream, String extractedToFilePath, BinaryType possibleFilenames) throws IOException, ExpectedFileNotFoundException { LOG.debug("Attempting to extract binary from a .tar file..."); ArchiveEntry currentFile; ArrayList<String> filenamesWeAreSearchingFor = new ArrayList<String>(possibleFilenames.getBinaryFilenames()); try { if (filenamesWeAreSearchingFor.contains("*")) { filenamesWeAreSearchingFor.remove(0); LOG.debug("Extracting full archive"); return this.untarFolder(compressedFileInputStream, extractedToFilePath, filenamesWeAreSearchingFor); } else { ArchiveInputStream archiveInputStream = new TarArchiveInputStream(compressedFileInputStream); while ((currentFile = archiveInputStream.getNextEntry()) != null) { for (String aFilenameWeAreSearchingFor : filenamesWeAreSearchingFor) { if (currentFile.getName().endsWith(aFilenameWeAreSearchingFor)) { LOG.debug("Found: " + currentFile.getName()); return copyFileToDisk(archiveInputStream, extractedToFilePath, aFilenameWeAreSearchingFor); } } } } } finally { compressedFileInputStream.close(); } throw new ExpectedFileNotFoundException( "Unable to find any expected filed for " + possibleFilenames.getBinaryTypeAsString()); }
java
private String untarFile(InputStream compressedFileInputStream, String extractedToFilePath, BinaryType possibleFilenames) throws IOException, ExpectedFileNotFoundException { LOG.debug("Attempting to extract binary from a .tar file..."); ArchiveEntry currentFile; ArrayList<String> filenamesWeAreSearchingFor = new ArrayList<String>(possibleFilenames.getBinaryFilenames()); try { if (filenamesWeAreSearchingFor.contains("*")) { filenamesWeAreSearchingFor.remove(0); LOG.debug("Extracting full archive"); return this.untarFolder(compressedFileInputStream, extractedToFilePath, filenamesWeAreSearchingFor); } else { ArchiveInputStream archiveInputStream = new TarArchiveInputStream(compressedFileInputStream); while ((currentFile = archiveInputStream.getNextEntry()) != null) { for (String aFilenameWeAreSearchingFor : filenamesWeAreSearchingFor) { if (currentFile.getName().endsWith(aFilenameWeAreSearchingFor)) { LOG.debug("Found: " + currentFile.getName()); return copyFileToDisk(archiveInputStream, extractedToFilePath, aFilenameWeAreSearchingFor); } } } } } finally { compressedFileInputStream.close(); } throw new ExpectedFileNotFoundException( "Unable to find any expected filed for " + possibleFilenames.getBinaryTypeAsString()); }
[ "private", "String", "untarFile", "(", "InputStream", "compressedFileInputStream", ",", "String", "extractedToFilePath", ",", "BinaryType", "possibleFilenames", ")", "throws", "IOException", ",", "ExpectedFileNotFoundException", "{", "LOG", ".", "debug", "(", "\"Attemptin...
Untar a decompressed tar file (this will implicitly overwrite any existing files) @param compressedFileInputStream The expanded tar file @param extractedToFilePath Path to extracted file @param possibleFilenames Names of the files we want to extract @return boolean @throws IOException MojoFailureException
[ "Untar", "a", "decompressed", "tar", "file", "(", "this", "will", "implicitly", "overwrite", "any", "existing", "files", ")" ]
train
https://github.com/Ardesco/selenium-standalone-server-plugin/blob/e0ecfad426c1a28115cab60def84731d7a4d7e6f/src/main/java/com/lazerycode/selenium/extract/FileExtractor.java#L122-L148
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/string/StringHelper.java
StringHelper.trimStartAndEnd
@Nullable @CheckReturnValue public static String trimStartAndEnd (@Nullable final String sSrc, final char cValueToTrim) { return trimStartAndEnd (sSrc, cValueToTrim, cValueToTrim); }
java
@Nullable @CheckReturnValue public static String trimStartAndEnd (@Nullable final String sSrc, final char cValueToTrim) { return trimStartAndEnd (sSrc, cValueToTrim, cValueToTrim); }
[ "@", "Nullable", "@", "CheckReturnValue", "public", "static", "String", "trimStartAndEnd", "(", "@", "Nullable", "final", "String", "sSrc", ",", "final", "char", "cValueToTrim", ")", "{", "return", "trimStartAndEnd", "(", "sSrc", ",", "cValueToTrim", ",", "cValu...
Trim the passed lead and tail from the source value. If the source value does not start with the passed trimmed value, nothing happens. @param sSrc The input source string @param cValueToTrim The char to be trimmed of the beginning and the end @return The trimmed string, or the original input string, if the value to trim was not found @see #trimStart(String, String) @see #trimEnd(String, String) @see #trimStartAndEnd(String, String, String)
[ "Trim", "the", "passed", "lead", "and", "tail", "from", "the", "source", "value", ".", "If", "the", "source", "value", "does", "not", "start", "with", "the", "passed", "trimmed", "value", "nothing", "happens", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/string/StringHelper.java#L3516-L3521
UrielCh/ovh-java-sdk
ovh-java-sdk-metrics/src/main/java/net/minidev/ovh/api/ApiOvhMetrics.java
ApiOvhMetrics.serviceName_token_POST
public OvhToken serviceName_token_POST(String serviceName, String description, OvhLabel[] labels, OvhPermissionEnum permission) throws IOException { String qPath = "/metrics/{serviceName}/token"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "labels", labels); addBody(o, "permission", permission); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhToken.class); }
java
public OvhToken serviceName_token_POST(String serviceName, String description, OvhLabel[] labels, OvhPermissionEnum permission) throws IOException { String qPath = "/metrics/{serviceName}/token"; StringBuilder sb = path(qPath, serviceName); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "description", description); addBody(o, "labels", labels); addBody(o, "permission", permission); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhToken.class); }
[ "public", "OvhToken", "serviceName_token_POST", "(", "String", "serviceName", ",", "String", "description", ",", "OvhLabel", "[", "]", "labels", ",", "OvhPermissionEnum", "permission", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/metrics/{serviceName...
Create a token REST: POST /metrics/{serviceName}/token @param description [required] Description for the new token @param labels [required] Labels for the new token @param serviceName [required] Name of your service @param permission [required] Type of the new token. Read or Write API beta
[ "Create", "a", "token" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-metrics/src/main/java/net/minidev/ovh/api/ApiOvhMetrics.java#L214-L223
CubeEngine/Dirigent
src/main/java/org/cubeengine/dirigent/builder/MessageBuilder.java
MessageBuilder.buildAny
protected final void buildAny(Component component, BuilderT builder, Context context) { if (component instanceof ResolvedMacro) { buildResolved((ResolvedMacro)component, builder, context); } else if (component instanceof UnresolvableMacro) { buildUnresolvable((UnresolvableMacro)component, builder, context); } else if (component instanceof TextComponent) { buildText((TextComponent)component, builder, context); } else if (component instanceof ComponentGroup) { buildGroup((ComponentGroup)component, builder, context); } else { buildOther(component, builder, context); } }
java
protected final void buildAny(Component component, BuilderT builder, Context context) { if (component instanceof ResolvedMacro) { buildResolved((ResolvedMacro)component, builder, context); } else if (component instanceof UnresolvableMacro) { buildUnresolvable((UnresolvableMacro)component, builder, context); } else if (component instanceof TextComponent) { buildText((TextComponent)component, builder, context); } else if (component instanceof ComponentGroup) { buildGroup((ComponentGroup)component, builder, context); } else { buildOther(component, builder, context); } }
[ "protected", "final", "void", "buildAny", "(", "Component", "component", ",", "BuilderT", "builder", ",", "Context", "context", ")", "{", "if", "(", "component", "instanceof", "ResolvedMacro", ")", "{", "buildResolved", "(", "(", "ResolvedMacro", ")", "component...
Appends a Component to the builder @param component the component @param builder the builder @param context the context
[ "Appends", "a", "Component", "to", "the", "builder" ]
train
https://github.com/CubeEngine/Dirigent/blob/68587a8202754a6a6b629cc15e14c516806badaa/src/main/java/org/cubeengine/dirigent/builder/MessageBuilder.java#L80-L102
geomajas/geomajas-project-server
command/src/main/java/org/geomajas/command/dto/SearchByLocationRequest.java
SearchByLocationRequest.addLayerWithFilter
public void addLayerWithFilter(String resultTag, String serverLayerId, String filter) { // note: layer filter specification will be overwritten if it already // exists layerFilters.put(resultTag, new LayerFilterSpecification(serverLayerId, filter)); }
java
public void addLayerWithFilter(String resultTag, String serverLayerId, String filter) { // note: layer filter specification will be overwritten if it already // exists layerFilters.put(resultTag, new LayerFilterSpecification(serverLayerId, filter)); }
[ "public", "void", "addLayerWithFilter", "(", "String", "resultTag", ",", "String", "serverLayerId", ",", "String", "filter", ")", "{", "// note: layer filter specification will be overwritten if it already", "// exists", "layerFilters", ".", "put", "(", "resultTag", ",", ...
Add a layer with an optional filter expression which should be applied on the given layer. <p/> If the filter contains a geometry, then this needs to be in layer CRS, it is not converted! @param resultTag tag to make the distinction in the response object between the features for the same serverLayerId but a different filter (e.g. client layer id) @param serverLayerId server layerId layer to set this filter on @param filter filter expression for the specified layer, can be null (==true filter)no client layer specific filtering @since 1.10.0
[ "Add", "a", "layer", "with", "an", "optional", "filter", "expression", "which", "should", "be", "applied", "on", "the", "given", "layer", ".", "<p", "/", ">", "If", "the", "filter", "contains", "a", "geometry", "then", "this", "needs", "to", "be", "in", ...
train
https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/command/src/main/java/org/geomajas/command/dto/SearchByLocationRequest.java#L278-L282
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/TaskInProgress.java
TaskInProgress.alreadyCompletedTask
void alreadyCompletedTask(TaskAttemptID taskid) { // 'KILL' the task completedTask(taskid, TaskStatus.State.KILLED); // Note the reason for the task being 'KILLED' addDiagnosticInfo(taskid, "Already completed TIP"); LOG.info("Already complete TIP " + getTIPId() + " has completed task " + taskid); }
java
void alreadyCompletedTask(TaskAttemptID taskid) { // 'KILL' the task completedTask(taskid, TaskStatus.State.KILLED); // Note the reason for the task being 'KILLED' addDiagnosticInfo(taskid, "Already completed TIP"); LOG.info("Already complete TIP " + getTIPId() + " has completed task " + taskid); }
[ "void", "alreadyCompletedTask", "(", "TaskAttemptID", "taskid", ")", "{", "// 'KILL' the task ", "completedTask", "(", "taskid", ",", "TaskStatus", ".", "State", ".", "KILLED", ")", ";", "// Note the reason for the task being 'KILLED'", "addDiagnosticInfo", "(", "taskid",...
Indicate that one of the taskids in this already-completed TaskInProgress has successfully completed; hence we mark this taskid as {@link TaskStatus.State.KILLED}.
[ "Indicate", "that", "one", "of", "the", "taskids", "in", "this", "already", "-", "completed", "TaskInProgress", "has", "successfully", "completed", ";", "hence", "we", "mark", "this", "taskid", "as", "{" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/TaskInProgress.java#L900-L909
windup/windup
utils/src/main/java/org/jboss/windup/util/ZipUtil.java
ZipUtil.unzipFromClassResource
public static void unzipFromClassResource(Class<?> clazz, String resourcePath, File extractToPath) throws IOException { File inputFile = File.createTempFile("windup-resource-to-unzip-", ".zip"); try { try (final InputStream stream = clazz.getResourceAsStream(resourcePath)) { FileUtils.copyInputStreamToFile(stream, inputFile); } extractToPath.mkdirs(); ZipUtil.unzipToFolder(inputFile, extractToPath); } finally { inputFile.delete(); } }
java
public static void unzipFromClassResource(Class<?> clazz, String resourcePath, File extractToPath) throws IOException { File inputFile = File.createTempFile("windup-resource-to-unzip-", ".zip"); try { try (final InputStream stream = clazz.getResourceAsStream(resourcePath)) { FileUtils.copyInputStreamToFile(stream, inputFile); } extractToPath.mkdirs(); ZipUtil.unzipToFolder(inputFile, extractToPath); } finally { inputFile.delete(); } }
[ "public", "static", "void", "unzipFromClassResource", "(", "Class", "<", "?", ">", "clazz", ",", "String", "resourcePath", ",", "File", "extractToPath", ")", "throws", "IOException", "{", "File", "inputFile", "=", "File", ".", "createTempFile", "(", "\"windup-re...
Unzip a classpath resource using the given {@link Class} as the resource root path.
[ "Unzip", "a", "classpath", "resource", "using", "the", "given", "{" ]
train
https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/utils/src/main/java/org/jboss/windup/util/ZipUtil.java#L39-L55
ManfredTremmel/gwt-commons-lang3
src/main/java/org/apache/commons/lang3/StringUtils.java
StringUtils.lastOrdinalIndexOf
public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, true); }
java
public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { return ordinalIndexOf(str, searchStr, ordinal, true); }
[ "public", "static", "int", "lastOrdinalIndexOf", "(", "final", "CharSequence", "str", ",", "final", "CharSequence", "searchStr", ",", "final", "int", "ordinal", ")", "{", "return", "ordinalIndexOf", "(", "str", ",", "searchStr", ",", "ordinal", ",", "true", ")...
<p>Finds the n-th last index within a String, handling {@code null}. This method uses {@link String#lastIndexOf(String)}.</p> <p>A {@code null} String will return {@code -1}.</p> <pre> StringUtils.lastOrdinalIndexOf(null, *, *) = -1 StringUtils.lastOrdinalIndexOf(*, null, *) = -1 StringUtils.lastOrdinalIndexOf("", "", *) = 0 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1) = 7 StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2) = 6 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1) = 5 StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2) = 2 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1) = 8 StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2) = 8 </pre> <p>Note that 'tail(CharSequence str, int n)' may be implemented as: </p> <pre> str.substring(lastOrdinalIndexOf(str, "\n", n) + 1) </pre> @param str the CharSequence to check, may be null @param searchStr the CharSequence to find, may be null @param ordinal the n-th last {@code searchStr} to find @return the n-th last index of the search CharSequence, {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input @since 2.5 @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int)
[ "<p", ">", "Finds", "the", "n", "-", "th", "last", "index", "within", "a", "String", "handling", "{", "@code", "null", "}", ".", "This", "method", "uses", "{", "@link", "String#lastIndexOf", "(", "String", ")", "}", ".", "<", "/", "p", ">" ]
train
https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/StringUtils.java#L1797-L1799
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java
FastaAFPChainConverter.fastaToAfpChain
public static AFPChain fastaToAfpChain(ProteinSequence sequence1, ProteinSequence sequence2, Structure structure1, Structure structure2) throws StructureException { if (structure1 == null || structure2 == null) { throw new IllegalArgumentException("A structure is null"); } if (sequence1 == null || sequence2 == null) { throw new IllegalArgumentException("A sequence is null"); } Atom[] ca1 = StructureTools.getRepresentativeAtomArray(structure1); Atom[] ca2 = StructureTools.getRepresentativeAtomArray(structure2); ResidueNumber[] residues1 = StructureSequenceMatcher.matchSequenceToStructure(sequence1, structure1); ResidueNumber[] residues2 = StructureSequenceMatcher.matchSequenceToStructure(sequence2, structure2); // nullify ResidueNumbers that have a lowercase sequence character if (sequence1.getUserCollection() != null) { CasePreservingProteinSequenceCreator.setLowercaseToNull(sequence1, residues1); } if (sequence2.getUserCollection() != null) { CasePreservingProteinSequenceCreator.setLowercaseToNull(sequence2, residues2); } return buildAlignment(ca1, ca2, residues1, residues2); }
java
public static AFPChain fastaToAfpChain(ProteinSequence sequence1, ProteinSequence sequence2, Structure structure1, Structure structure2) throws StructureException { if (structure1 == null || structure2 == null) { throw new IllegalArgumentException("A structure is null"); } if (sequence1 == null || sequence2 == null) { throw new IllegalArgumentException("A sequence is null"); } Atom[] ca1 = StructureTools.getRepresentativeAtomArray(structure1); Atom[] ca2 = StructureTools.getRepresentativeAtomArray(structure2); ResidueNumber[] residues1 = StructureSequenceMatcher.matchSequenceToStructure(sequence1, structure1); ResidueNumber[] residues2 = StructureSequenceMatcher.matchSequenceToStructure(sequence2, structure2); // nullify ResidueNumbers that have a lowercase sequence character if (sequence1.getUserCollection() != null) { CasePreservingProteinSequenceCreator.setLowercaseToNull(sequence1, residues1); } if (sequence2.getUserCollection() != null) { CasePreservingProteinSequenceCreator.setLowercaseToNull(sequence2, residues2); } return buildAlignment(ca1, ca2, residues1, residues2); }
[ "public", "static", "AFPChain", "fastaToAfpChain", "(", "ProteinSequence", "sequence1", ",", "ProteinSequence", "sequence2", ",", "Structure", "structure1", ",", "Structure", "structure2", ")", "throws", "StructureException", "{", "if", "(", "structure1", "==", "null"...
Returns an AFPChain corresponding to the alignment between {@code structure1} and {@code structure2}, which is given by the gapped protein sequences {@code sequence1} and {@code sequence2}. The sequences need not correspond to the entire structures, since local alignment is performed to match the sequences to structures. Assumes that a residue is aligned if and only if it is given by an uppercase letter. @param sequence1 <em>Must</em> have {@link ProteinSequence#getUserCollection()} set to document upper- and lower-case as aligned and unaligned; see {@link #getAlignedUserCollection(String)} @throws StructureException
[ "Returns", "an", "AFPChain", "corresponding", "to", "the", "alignment", "between", "{" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/FastaAFPChainConverter.java#L275-L302
Azure/azure-sdk-for-java
authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleDefinitionsInner.java
RoleDefinitionsInner.createOrUpdate
public RoleDefinitionInner createOrUpdate(String scope, String roleDefinitionId, RoleDefinitionProperties properties) { return createOrUpdateWithServiceResponseAsync(scope, roleDefinitionId, properties).toBlocking().single().body(); }
java
public RoleDefinitionInner createOrUpdate(String scope, String roleDefinitionId, RoleDefinitionProperties properties) { return createOrUpdateWithServiceResponseAsync(scope, roleDefinitionId, properties).toBlocking().single().body(); }
[ "public", "RoleDefinitionInner", "createOrUpdate", "(", "String", "scope", ",", "String", "roleDefinitionId", ",", "RoleDefinitionProperties", "properties", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "scope", ",", "roleDefinitionId", ",", "properties...
Creates or updates a role definition. @param scope The scope of the role definition. @param roleDefinitionId The ID of the role definition. @param properties Role definition properties. @throws IllegalArgumentException thrown if parameters fail the validation @throws CloudException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the RoleDefinitionInner object if successful.
[ "Creates", "or", "updates", "a", "role", "definition", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/authorization/resource-manager/v2015_07_01/src/main/java/com/microsoft/azure/management/authorization/v2015_07_01/implementation/RoleDefinitionsInner.java#L348-L350
molgenis/molgenis
molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/repository/impl/MappingProjectRepositoryImpl.java
MappingProjectRepositoryImpl.toMappingProject
private MappingProject toMappingProject(Entity mappingProjectEntity) { String identifier = mappingProjectEntity.getString(MappingProjectMetadata.IDENTIFIER); String name = mappingProjectEntity.getString(MappingProjectMetadata.NAME); int depth = Optional.ofNullable(mappingProjectEntity.getInt(DEPTH)).orElse(3); List<Entity> mappingTargetEntities = Lists.newArrayList( mappingProjectEntity.getEntities(MappingProjectMetadata.MAPPING_TARGETS)); List<MappingTarget> mappingTargets = mappingTargetRepo.toMappingTargets(mappingTargetEntities); return new MappingProject(identifier, name, depth, mappingTargets); }
java
private MappingProject toMappingProject(Entity mappingProjectEntity) { String identifier = mappingProjectEntity.getString(MappingProjectMetadata.IDENTIFIER); String name = mappingProjectEntity.getString(MappingProjectMetadata.NAME); int depth = Optional.ofNullable(mappingProjectEntity.getInt(DEPTH)).orElse(3); List<Entity> mappingTargetEntities = Lists.newArrayList( mappingProjectEntity.getEntities(MappingProjectMetadata.MAPPING_TARGETS)); List<MappingTarget> mappingTargets = mappingTargetRepo.toMappingTargets(mappingTargetEntities); return new MappingProject(identifier, name, depth, mappingTargets); }
[ "private", "MappingProject", "toMappingProject", "(", "Entity", "mappingProjectEntity", ")", "{", "String", "identifier", "=", "mappingProjectEntity", ".", "getString", "(", "MappingProjectMetadata", ".", "IDENTIFIER", ")", ";", "String", "name", "=", "mappingProjectEnt...
Creates a fully reconstructed MappingProject from an Entity retrieved from the repository. @param mappingProjectEntity Entity with {@link MappingProjectMetadata} metadata @return fully reconstructed MappingProject
[ "Creates", "a", "fully", "reconstructed", "MappingProject", "from", "an", "Entity", "retrieved", "from", "the", "repository", "." ]
train
https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-semantic-mapper/src/main/java/org/molgenis/semanticmapper/repository/impl/MappingProjectRepositoryImpl.java#L92-L102
apache/incubator-gobblin
gobblin-restli/gobblin-restli-utils/src/main/java/org/apache/gobblin/restli/EmbeddedRestliServer.java
EmbeddedRestliServer.getListeningURI
public URI getListeningURI() { try { return new URI(this.serverUri.getScheme(), this.serverUri.getUserInfo(), this.serverUri.getHost(), this.port, null, null, null); } catch (URISyntaxException use) { throw new RuntimeException("Invalid URI. This is an error in code.", use); } }
java
public URI getListeningURI() { try { return new URI(this.serverUri.getScheme(), this.serverUri.getUserInfo(), this.serverUri.getHost(), this.port, null, null, null); } catch (URISyntaxException use) { throw new RuntimeException("Invalid URI. This is an error in code.", use); } }
[ "public", "URI", "getListeningURI", "(", ")", "{", "try", "{", "return", "new", "URI", "(", "this", ".", "serverUri", ".", "getScheme", "(", ")", ",", "this", ".", "serverUri", ".", "getUserInfo", "(", ")", ",", "this", ".", "serverUri", ".", "getHost"...
Get the scheme and authority at which this server is listening.
[ "Get", "the", "scheme", "and", "authority", "at", "which", "this", "server", "is", "listening", "." ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-restli/gobblin-restli-utils/src/main/java/org/apache/gobblin/restli/EmbeddedRestliServer.java#L162-L169
UrielCh/ovh-java-sdk
ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java
ApiOvhCloud.project_serviceName_volume_snapshot_snapshotId_DELETE
public void project_serviceName_volume_snapshot_snapshotId_DELETE(String serviceName, String snapshotId) throws IOException { String qPath = "/cloud/project/{serviceName}/volume/snapshot/{snapshotId}"; StringBuilder sb = path(qPath, serviceName, snapshotId); exec(qPath, "DELETE", sb.toString(), null); }
java
public void project_serviceName_volume_snapshot_snapshotId_DELETE(String serviceName, String snapshotId) throws IOException { String qPath = "/cloud/project/{serviceName}/volume/snapshot/{snapshotId}"; StringBuilder sb = path(qPath, serviceName, snapshotId); exec(qPath, "DELETE", sb.toString(), null); }
[ "public", "void", "project_serviceName_volume_snapshot_snapshotId_DELETE", "(", "String", "serviceName", ",", "String", "snapshotId", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/cloud/project/{serviceName}/volume/snapshot/{snapshotId}\"", ";", "StringBuilder", ...
Delete a volume snapshot REST: DELETE /cloud/project/{serviceName}/volume/snapshot/{snapshotId} @param serviceName [required] Project id @param snapshotId [required] Snapshot id
[ "Delete", "a", "volume", "snapshot" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-cloud/src/main/java/net/minidev/ovh/api/ApiOvhCloud.java#L1265-L1269
spockframework/spock
spock-core/src/main/java/org/spockframework/util/inspector/AstInspector.java
AstInspector.load
public void load(File sourceFile) throws CompilationFailedException { reset(); try { classLoader.parseClass(sourceFile); } catch (IOException e) { throw new AstInspectorException("cannot read source file", e); } catch (AstSuccessfullyCaptured e) { indexAstNodes(); return; } throw new AstInspectorException("internal error"); }
java
public void load(File sourceFile) throws CompilationFailedException { reset(); try { classLoader.parseClass(sourceFile); } catch (IOException e) { throw new AstInspectorException("cannot read source file", e); } catch (AstSuccessfullyCaptured e) { indexAstNodes(); return; } throw new AstInspectorException("internal error"); }
[ "public", "void", "load", "(", "File", "sourceFile", ")", "throws", "CompilationFailedException", "{", "reset", "(", ")", ";", "try", "{", "classLoader", ".", "parseClass", "(", "sourceFile", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "thro...
Compiles the source text in the specified file up to the configured compile phase and stores the resulting AST for subsequent inspection. @param sourceFile the file containing the source text to compile @throws CompilationFailedException if an error occurs during compilation @throws AstInspectorException if an IOException occurs when reading from the file
[ "Compiles", "the", "source", "text", "in", "the", "specified", "file", "up", "to", "the", "configured", "compile", "phase", "and", "stores", "the", "resulting", "AST", "for", "subsequent", "inspection", "." ]
train
https://github.com/spockframework/spock/blob/d751a0abd8d5a2ec5338aa10bc2d19371b3b3ad9/spock-core/src/main/java/org/spockframework/util/inspector/AstInspector.java#L160-L173
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.getTimestamp
@Override public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
@Override public Timestamp getTimestamp(String parameterName, Calendar cal) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "Timestamp", "getTimestamp", "(", "String", "parameterName", ",", "Calendar", "cal", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Retrieves the value of a JDBC TIMESTAMP parameter as a java.sql.Timestamp object, using the given Calendar object to construct the Timestamp object.
[ "Retrieves", "the", "value", "of", "a", "JDBC", "TIMESTAMP", "parameter", "as", "a", "java", ".", "sql", ".", "Timestamp", "object", "using", "the", "given", "Calendar", "object", "to", "construct", "the", "Timestamp", "object", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L495-L500
ozimov/cirneco
hamcrest/hamcrest-matchers/src/main/java/it/ozimov/cirneco/hamcrest/collect/IsIterableContainingInOrder.java
IsIterableContainingInOrder.containsInOrder
public static <T> Matcher<Iterable<? extends T>> containsInOrder(final Iterable<T> items) { final Collection<Matcher<? super T>> matchers = new ArrayList<>(); for (final T item : items) { matchers.add(equalTo(item)); } return new IsIterableContainingInOrder<T>(matchers); }
java
public static <T> Matcher<Iterable<? extends T>> containsInOrder(final Iterable<T> items) { final Collection<Matcher<? super T>> matchers = new ArrayList<>(); for (final T item : items) { matchers.add(equalTo(item)); } return new IsIterableContainingInOrder<T>(matchers); }
[ "public", "static", "<", "T", ">", "Matcher", "<", "Iterable", "<", "?", "extends", "T", ">", ">", "containsInOrder", "(", "final", "Iterable", "<", "T", ">", "items", ")", "{", "final", "Collection", "<", "Matcher", "<", "?", "super", "T", ">", ">",...
Creates a matcher for {@linkplain Iterable}s that matches when a single pass over the examined {@linkplain Iterable} yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items. For example:<br /> <pre> //Arrange Iterable<String> actual = Arrays.asList("foo", "bar"); Iterable<String> expected = Arrays.asList("foo", "bar"); //Assert assertThat(actual, containsInOrder(expected)); </pre> @param items the items that must equal the items provided by an examined {@linkplain Iterable}
[ "Creates", "a", "matcher", "for", "{", "@linkplain", "Iterable", "}", "s", "that", "matches", "when", "a", "single", "pass", "over", "the", "examined", "{", "@linkplain", "Iterable", "}", "yields", "a", "series", "of", "items", "each", "logically", "equal", ...
train
https://github.com/ozimov/cirneco/blob/78ad782da0a2256634cfbebb2f97ed78c993b999/hamcrest/hamcrest-matchers/src/main/java/it/ozimov/cirneco/hamcrest/collect/IsIterableContainingInOrder.java#L36-L43
documents4j/documents4j
documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java
ConverterServerBuilder.workerPool
public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { assertNumericArgument(corePoolSize, true); assertNumericArgument(maximumPoolSize, true); assertNumericArgument(corePoolSize + maximumPoolSize, false); assertNumericArgument(keepAliveTime, true); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = unit.toMillis(keepAliveTime); return this; }
java
public ConverterServerBuilder workerPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit) { assertNumericArgument(corePoolSize, true); assertNumericArgument(maximumPoolSize, true); assertNumericArgument(corePoolSize + maximumPoolSize, false); assertNumericArgument(keepAliveTime, true); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.keepAliveTime = unit.toMillis(keepAliveTime); return this; }
[ "public", "ConverterServerBuilder", "workerPool", "(", "int", "corePoolSize", ",", "int", "maximumPoolSize", ",", "long", "keepAliveTime", ",", "TimeUnit", "unit", ")", "{", "assertNumericArgument", "(", "corePoolSize", ",", "true", ")", ";", "assertNumericArgument", ...
Configures a worker pool for the converter. @param corePoolSize The core pool size of the worker pool. @param maximumPoolSize The maximum pool size of the worker pool. @param keepAliveTime The keep alive time of the worker pool. @param unit The time unit of the specified keep alive time. @return This builder instance.
[ "Configures", "a", "worker", "pool", "for", "the", "converter", "." ]
train
https://github.com/documents4j/documents4j/blob/eebb3ede43ffeb5fbfc85b3134f67a9c379a5594/documents4j-server-standalone/src/main/java/com/documents4j/builder/ConverterServerBuilder.java#L119-L128
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssClient.java
LssClient.deleteSession
public DeleteSessionResponse deleteSession(DeleteSessionRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.DELETE, request, LIVE_SESSION, request.getSessionId()); return invokeHttpClient(internalRequest, DeleteSessionResponse.class); }
java
public DeleteSessionResponse deleteSession(DeleteSessionRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getSessionId(), "The parameter sessionId should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethodName.DELETE, request, LIVE_SESSION, request.getSessionId()); return invokeHttpClient(internalRequest, DeleteSessionResponse.class); }
[ "public", "DeleteSessionResponse", "deleteSession", "(", "DeleteSessionRequest", "request", ")", "{", "checkNotNull", "(", "request", ",", "\"The parameter request should NOT be null.\"", ")", ";", "checkStringNotEmpty", "(", "request", ".", "getSessionId", "(", ")", ",",...
Delete your live session by live session id. @param request The request object containing all parameters for deleting live session. @return the response
[ "Delete", "your", "live", "session", "by", "live", "session", "id", "." ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssClient.java#L745-L751
calimero-project/calimero-core
src/tuwien/auto/calimero/mgmt/TransportLayerImpl.java
TransportLayerImpl.createDestination
@Override public Destination createDestination(final IndividualAddress remote, final boolean connectionOriented) { return createDestination(remote, connectionOriented, false, false); }
java
@Override public Destination createDestination(final IndividualAddress remote, final boolean connectionOriented) { return createDestination(remote, connectionOriented, false, false); }
[ "@", "Override", "public", "Destination", "createDestination", "(", "final", "IndividualAddress", "remote", ",", "final", "boolean", "connectionOriented", ")", "{", "return", "createDestination", "(", "remote", ",", "connectionOriented", ",", "false", ",", "false", ...
{@inheritDoc} Only one destination can be created per remote address. If a destination with the supplied remote address already exists for this transport layer, a {@link KNXIllegalArgumentException} is thrown.<br> A transport layer can only handle one connection per destination, because it can't distinguish incoming messages between more than one connection.
[ "{" ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/mgmt/TransportLayerImpl.java#L219-L224
jenkinsci/jenkins
core/src/main/java/hudson/model/AbstractItem.java
AbstractItem.doDoDelete
@RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (req == null || rsp == null) { // CLI return; } List<Ancestor> ancestors = req.getAncestors(); ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size()); String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root while (it.hasPrevious()) { Object a = it.previous().getObject(); if (a instanceof View) { url = ((View) a).getUrl(); break; } else if (a instanceof ViewGroup && a != this) { url = ((ViewGroup) a).getUrl(); break; } } rsp.sendRedirect2(req.getContextPath() + '/' + url); }
java
@RequirePOST public void doDoDelete( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException { delete(); if (req == null || rsp == null) { // CLI return; } List<Ancestor> ancestors = req.getAncestors(); ListIterator<Ancestor> it = ancestors.listIterator(ancestors.size()); String url = getParent().getUrl(); // fallback but we ought to get to Jenkins.instance at the root while (it.hasPrevious()) { Object a = it.previous().getObject(); if (a instanceof View) { url = ((View) a).getUrl(); break; } else if (a instanceof ViewGroup && a != this) { url = ((ViewGroup) a).getUrl(); break; } } rsp.sendRedirect2(req.getContextPath() + '/' + url); }
[ "@", "RequirePOST", "public", "void", "doDoDelete", "(", "StaplerRequest", "req", ",", "StaplerResponse", "rsp", ")", "throws", "IOException", ",", "ServletException", ",", "InterruptedException", "{", "delete", "(", ")", ";", "if", "(", "req", "==", "null", "...
Deletes this item. Note on the funny name: for reasons of historical compatibility, this URL is {@code /doDelete} since it predates {@code <l:confirmationLink>}. {@code /delete} goes to a Jelly page which should now be unused by core but is left in case plugins are still using it.
[ "Deletes", "this", "item", ".", "Note", "on", "the", "funny", "name", ":", "for", "reasons", "of", "historical", "compatibility", "this", "URL", "is", "{" ]
train
https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/model/AbstractItem.java#L643-L663
j-easy/easy-random
easy-random-core/src/main/java/org/jeasy/random/randomizers/range/DoubleRangeRandomizer.java
DoubleRangeRandomizer.aNewDoubleRangeRandomizer
public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed) { return new DoubleRangeRandomizer(min, max, seed); }
java
public static DoubleRangeRandomizer aNewDoubleRangeRandomizer(final Double min, final Double max, final long seed) { return new DoubleRangeRandomizer(min, max, seed); }
[ "public", "static", "DoubleRangeRandomizer", "aNewDoubleRangeRandomizer", "(", "final", "Double", "min", ",", "final", "Double", "max", ",", "final", "long", "seed", ")", "{", "return", "new", "DoubleRangeRandomizer", "(", "min", ",", "max", ",", "seed", ")", ...
Create a new {@link DoubleRangeRandomizer}. @param min min value @param max max value @param seed initial seed @return a new {@link DoubleRangeRandomizer}.
[ "Create", "a", "new", "{", "@link", "DoubleRangeRandomizer", "}", "." ]
train
https://github.com/j-easy/easy-random/blob/816b0d6a74c7288af111e70ae1b0b57d7fe3b59d/easy-random-core/src/main/java/org/jeasy/random/randomizers/range/DoubleRangeRandomizer.java#L90-L92
JOML-CI/JOML
src/org/joml/Vector4d.java
Vector4d.fma
public Vector4d fma(Vector4dc a, Vector4dc b) { return fma(a, b, thisOrNew()); }
java
public Vector4d fma(Vector4dc a, Vector4dc b) { return fma(a, b, thisOrNew()); }
[ "public", "Vector4d", "fma", "(", "Vector4dc", "a", ",", "Vector4dc", "b", ")", "{", "return", "fma", "(", "a", ",", "b", ",", "thisOrNew", "(", ")", ")", ";", "}" ]
Add the component-wise multiplication of <code>a * b</code> to this vector. @param a the first multiplicand @param b the second multiplicand @return a vector holding the result
[ "Add", "the", "component", "-", "wise", "multiplication", "of", "<code", ">", "a", "*", "b<", "/", "code", ">", "to", "this", "vector", "." ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Vector4d.java#L797-L799
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagHeadIncludes.java
CmsJspTagHeadIncludes.getStandardContext
private CmsJspStandardContextBean getStandardContext(CmsObject cms, HttpServletRequest req) throws CmsException { CmsJspStandardContextBean standardContext = CmsJspStandardContextBean.getInstance(req); standardContext.initPage(); return standardContext; }
java
private CmsJspStandardContextBean getStandardContext(CmsObject cms, HttpServletRequest req) throws CmsException { CmsJspStandardContextBean standardContext = CmsJspStandardContextBean.getInstance(req); standardContext.initPage(); return standardContext; }
[ "private", "CmsJspStandardContextBean", "getStandardContext", "(", "CmsObject", "cms", ",", "HttpServletRequest", "req", ")", "throws", "CmsException", "{", "CmsJspStandardContextBean", "standardContext", "=", "CmsJspStandardContextBean", ".", "getInstance", "(", "req", ")"...
Returns the standard context bean.<p> @param cms the current cms context @param req the current request @return the standard context bean @throws CmsException if something goes wrong
[ "Returns", "the", "standard", "context", "bean", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagHeadIncludes.java#L798-L803
arquillian/arquillian-core
container/impl-base/src/main/java/org/jboss/arquillian/container/impl/client/container/ContainerDeployController.java
ContainerDeployController.deployManaged
public void deployManaged(@Observes DeployManagedDeployments event) throws Exception { forEachManagedDeployment(new Operation<Container, Deployment>() { @Inject private Event<DeploymentEvent> event; @Override public void perform(Container container, Deployment deployment) throws Exception { //when a container is manually controlled, the deployment is deployed automatically //once the container is manually started, not now if (!"manual".equals(container.getContainerConfiguration().getMode())) { if (container.getState() != State.STARTED) { throw new IllegalStateException("Trying to deploy a managed deployment " + deployment.getDescription().getName() + " to a non started managed container " + container.getName()); } event.fire(new DeployDeployment(container, deployment)); } } }); }
java
public void deployManaged(@Observes DeployManagedDeployments event) throws Exception { forEachManagedDeployment(new Operation<Container, Deployment>() { @Inject private Event<DeploymentEvent> event; @Override public void perform(Container container, Deployment deployment) throws Exception { //when a container is manually controlled, the deployment is deployed automatically //once the container is manually started, not now if (!"manual".equals(container.getContainerConfiguration().getMode())) { if (container.getState() != State.STARTED) { throw new IllegalStateException("Trying to deploy a managed deployment " + deployment.getDescription().getName() + " to a non started managed container " + container.getName()); } event.fire(new DeployDeployment(container, deployment)); } } }); }
[ "public", "void", "deployManaged", "(", "@", "Observes", "DeployManagedDeployments", "event", ")", "throws", "Exception", "{", "forEachManagedDeployment", "(", "new", "Operation", "<", "Container", ",", "Deployment", ">", "(", ")", "{", "@", "Inject", "private", ...
Deploy all deployments marked as managed = true. @throws Exception
[ "Deploy", "all", "deployments", "marked", "as", "managed", "=", "true", "." ]
train
https://github.com/arquillian/arquillian-core/blob/a85b91789b80cc77e0f0c2e2abac65c2255c0a81/container/impl-base/src/main/java/org/jboss/arquillian/container/impl/client/container/ContainerDeployController.java#L76-L96
cdk/cdk
tool/forcefield/src/main/java/org/openscience/cdk/modeling/builder3d/MM2BasedParameterSetReader.java
MM2BasedParameterSetReader.massNumber
private Integer massNumber(int atomicNumber, double exactMass) throws IOException { String symbol = PeriodicTable.getSymbol(atomicNumber); IIsotope isotope = Isotopes.getInstance().getIsotope(symbol, exactMass, 0.001); return isotope != null ? isotope.getMassNumber() : null; }
java
private Integer massNumber(int atomicNumber, double exactMass) throws IOException { String symbol = PeriodicTable.getSymbol(atomicNumber); IIsotope isotope = Isotopes.getInstance().getIsotope(symbol, exactMass, 0.001); return isotope != null ? isotope.getMassNumber() : null; }
[ "private", "Integer", "massNumber", "(", "int", "atomicNumber", ",", "double", "exactMass", ")", "throws", "IOException", "{", "String", "symbol", "=", "PeriodicTable", ".", "getSymbol", "(", "atomicNumber", ")", ";", "IIsotope", "isotope", "=", "Isotopes", ".",...
Mass number for a atom with a given atomic number and exact mass. @param atomicNumber atomic number @param exactMass exact mass @return the mass number (or null) if no mass number was found @throws IOException isotope configuration could not be loaded
[ "Mass", "number", "for", "a", "atom", "with", "a", "given", "atomic", "number", "and", "exact", "mass", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/forcefield/src/main/java/org/openscience/cdk/modeling/builder3d/MM2BasedParameterSetReader.java#L885-L889
nlalevee/jsourcemap
jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java
MappingList.generatedPositionAfter
private boolean generatedPositionAfter(Mapping mappingA, Mapping mappingB) { // Optimized for most common case int lineA = mappingA.generated.line; int lineB = mappingB.generated.line; int columnA = mappingA.generated.column; int columnB = mappingB.generated.column; return lineB > lineA || lineB == lineA && columnB >= columnA || Util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; }
java
private boolean generatedPositionAfter(Mapping mappingA, Mapping mappingB) { // Optimized for most common case int lineA = mappingA.generated.line; int lineB = mappingB.generated.line; int columnA = mappingA.generated.column; int columnB = mappingB.generated.column; return lineB > lineA || lineB == lineA && columnB >= columnA || Util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; }
[ "private", "boolean", "generatedPositionAfter", "(", "Mapping", "mappingA", ",", "Mapping", "mappingB", ")", "{", "// Optimized for most common case", "int", "lineA", "=", "mappingA", ".", "generated", ".", "line", ";", "int", "lineB", "=", "mappingB", ".", "gener...
Determine whether mappingB is after mappingA with respect to generated position.
[ "Determine", "whether", "mappingB", "is", "after", "mappingA", "with", "respect", "to", "generated", "position", "." ]
train
https://github.com/nlalevee/jsourcemap/blob/361a99c73d51c11afa5579dd83d477c4d0345599/jsourcemap/src/java/org/hibnet/jsourcemap/MappingList.java#L32-L39
SonarSource/sonarqube
server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java
RuleActivator.isSameAsParent
private static boolean isSameAsParent(ActiveRuleChange change, RuleActivationContext context) { ActiveRuleWrapper parentActiveRule = context.getParentActiveRule(); if (parentActiveRule == null) { return false; } if (!StringUtils.equals(change.getSeverity(), parentActiveRule.get().getSeverityString())) { return false; } for (Map.Entry<String, String> entry : change.getParameters().entrySet()) { if (entry.getValue() != null && !entry.getValue().equals(parentActiveRule.getParamValue(entry.getKey()))) { return false; } } return true; }
java
private static boolean isSameAsParent(ActiveRuleChange change, RuleActivationContext context) { ActiveRuleWrapper parentActiveRule = context.getParentActiveRule(); if (parentActiveRule == null) { return false; } if (!StringUtils.equals(change.getSeverity(), parentActiveRule.get().getSeverityString())) { return false; } for (Map.Entry<String, String> entry : change.getParameters().entrySet()) { if (entry.getValue() != null && !entry.getValue().equals(parentActiveRule.getParamValue(entry.getKey()))) { return false; } } return true; }
[ "private", "static", "boolean", "isSameAsParent", "(", "ActiveRuleChange", "change", ",", "RuleActivationContext", "context", ")", "{", "ActiveRuleWrapper", "parentActiveRule", "=", "context", ".", "getParentActiveRule", "(", ")", ";", "if", "(", "parentActiveRule", "...
True if trying to override an inherited rule but with exactly the same values
[ "True", "if", "trying", "to", "override", "an", "inherited", "rule", "but", "with", "exactly", "the", "same", "values" ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-server/src/main/java/org/sonar/server/qualityprofile/RuleActivator.java#L454-L468
pravega/pravega
controller/src/main/java/io/pravega/controller/metrics/TransactionMetrics.java
TransactionMetrics.abortTransactionFailed
public void abortTransactionFailed(String scope, String streamName, String txnId) { DYNAMIC_LOGGER.incCounterValue(globalMetricName(ABORT_TRANSACTION_FAILED), 1); DYNAMIC_LOGGER.incCounterValue(ABORT_TRANSACTION_FAILED, 1, streamTags(scope, streamName)); DYNAMIC_LOGGER.incCounterValue(ABORT_TRANSACTION_FAILED, 1, transactionTags(scope, streamName, txnId)); }
java
public void abortTransactionFailed(String scope, String streamName, String txnId) { DYNAMIC_LOGGER.incCounterValue(globalMetricName(ABORT_TRANSACTION_FAILED), 1); DYNAMIC_LOGGER.incCounterValue(ABORT_TRANSACTION_FAILED, 1, streamTags(scope, streamName)); DYNAMIC_LOGGER.incCounterValue(ABORT_TRANSACTION_FAILED, 1, transactionTags(scope, streamName, txnId)); }
[ "public", "void", "abortTransactionFailed", "(", "String", "scope", ",", "String", "streamName", ",", "String", "txnId", ")", "{", "DYNAMIC_LOGGER", ".", "incCounterValue", "(", "globalMetricName", "(", "ABORT_TRANSACTION_FAILED", ")", ",", "1", ")", ";", "DYNAMIC...
This method increments the global, Stream-related and Transaction-related counters of failed abort operations. @param scope Scope. @param streamName Name of the Stream. @param txnId Transaction id.
[ "This", "method", "increments", "the", "global", "Stream", "-", "related", "and", "Transaction", "-", "related", "counters", "of", "failed", "abort", "operations", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/metrics/TransactionMetrics.java#L111-L115
Appendium/flatpack
flatpack/src/main/java/net/sf/flatpack/AbstractParser.java
AbstractParser.addError
protected void addError(final DefaultDataSet ds, final String errorDesc, final int lineNo, final int errorLevel, final String lineData) { if (errorLevel == 1 && isIgnoreParseWarnings()) { // user has selected to not log warnings in the parser return; } ds.addError(new DataError(errorDesc, lineNo, errorLevel, lineData)); }
java
protected void addError(final DefaultDataSet ds, final String errorDesc, final int lineNo, final int errorLevel, final String lineData) { if (errorLevel == 1 && isIgnoreParseWarnings()) { // user has selected to not log warnings in the parser return; } ds.addError(new DataError(errorDesc, lineNo, errorLevel, lineData)); }
[ "protected", "void", "addError", "(", "final", "DefaultDataSet", "ds", ",", "final", "String", "errorDesc", ",", "final", "int", "lineNo", ",", "final", "int", "errorLevel", ",", "final", "String", "lineData", ")", "{", "if", "(", "errorLevel", "==", "1", ...
Adds a new error to this DataSet. These can be collected, and retrieved after processing @param ds the data set from the parser @param errorDesc String description of error @param lineNo line number error occurred on @param errorLevel errorLevel 1,2,3 1=warning 2=error 3= severe error' @param lineData Data of the line which failed the parse
[ "Adds", "a", "new", "error", "to", "this", "DataSet", ".", "These", "can", "be", "collected", "and", "retrieved", "after", "processing" ]
train
https://github.com/Appendium/flatpack/blob/5e09875d97db7038e3ba6af9468f5313d99b0082/flatpack/src/main/java/net/sf/flatpack/AbstractParser.java#L275-L281
xhsun/gw2wrapper
src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java
AsynchronousRequest.getGuildTreasuryInfo
public void getGuildTreasuryInfo(String id, String api, Callback<List<GuildTreasury>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildTreasuryInfo(id, api).enqueue(callback); }
java
public void getGuildTreasuryInfo(String id, String api, Callback<List<GuildTreasury>> callback) throws GuildWars2Exception, NullPointerException { isParamValid(new ParamChecker(ParamType.GUILD, id), new ParamChecker(ParamType.API, api)); gw2API.getGuildTreasuryInfo(id, api).enqueue(callback); }
[ "public", "void", "getGuildTreasuryInfo", "(", "String", "id", ",", "String", "api", ",", "Callback", "<", "List", "<", "GuildTreasury", ">", ">", "callback", ")", "throws", "GuildWars2Exception", ",", "NullPointerException", "{", "isParamValid", "(", "new", "Pa...
For more info on guild treasury API go <a href="https://wiki.guildwars2.com/wiki/API:2/guild/:id/treasury">here</a><br/> Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions<br/> @param id guild id @param api Guild leader's Guild Wars 2 API key @param callback callback that is going to be used for {@link Call#enqueue(Callback)} @throws NullPointerException if given {@link Callback} is empty @see GuildTreasury guild treasury info
[ "For", "more", "info", "on", "guild", "treasury", "API", "go", "<a", "href", "=", "https", ":", "//", "wiki", ".", "guildwars2", ".", "com", "/", "wiki", "/", "API", ":", "2", "/", "guild", "/", ":", "id", "/", "treasury", ">", "here<", "/", "a",...
train
https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L1569-L1572
stephanenicolas/robospice
robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java
SpiceServiceListenerNotifier.notifyObserversOfRequestProgress
public void notifyObserversOfRequestProgress(CachedSpiceRequest<?> request, RequestProgress requestProgress) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); requestProcessingContext.setRequestProgress(requestProgress); post(new RequestProgressNotifier(request, spiceServiceListenerList, requestProcessingContext)); }
java
public void notifyObserversOfRequestProgress(CachedSpiceRequest<?> request, RequestProgress requestProgress) { RequestProcessingContext requestProcessingContext = new RequestProcessingContext(); requestProcessingContext.setExecutionThread(Thread.currentThread()); requestProcessingContext.setRequestProgress(requestProgress); post(new RequestProgressNotifier(request, spiceServiceListenerList, requestProcessingContext)); }
[ "public", "void", "notifyObserversOfRequestProgress", "(", "CachedSpiceRequest", "<", "?", ">", "request", ",", "RequestProgress", "requestProgress", ")", "{", "RequestProcessingContext", "requestProcessingContext", "=", "new", "RequestProcessingContext", "(", ")", ";", "...
Notify interested observers of request progress. @param request the request in progress. @param requestProgress the progress of the request.
[ "Notify", "interested", "observers", "of", "request", "progress", "." ]
train
https://github.com/stephanenicolas/robospice/blob/8bffde88b3534a961a13cab72a8f07a755f0a0fe/robospice-core-parent/robospice/src/main/java/com/octo/android/robospice/request/notifier/SpiceServiceListenerNotifier.java#L122-L127
dropwizard/dropwizard
dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java
JerseyClientBuilder.buildRx
public <RX extends RxInvokerProvider<?>> Client buildRx(String name, Class<RX> invokerType) { return build(name).register(invokerType); }
java
public <RX extends RxInvokerProvider<?>> Client buildRx(String name, Class<RX> invokerType) { return build(name).register(invokerType); }
[ "public", "<", "RX", "extends", "RxInvokerProvider", "<", "?", ">", ">", "Client", "buildRx", "(", "String", "name", ",", "Class", "<", "RX", ">", "invokerType", ")", "{", "return", "build", "(", "name", ")", ".", "register", "(", "invokerType", ")", "...
Builds the {@link Client} instance with a custom reactive client provider. @return a fully-configured {@link Client}
[ "Builds", "the", "{", "@link", "Client", "}", "instance", "with", "a", "custom", "reactive", "client", "provider", "." ]
train
https://github.com/dropwizard/dropwizard/blob/7ee09a410476b9681e8072ab684788bb440877bd/dropwizard-client/src/main/java/io/dropwizard/client/JerseyClientBuilder.java#L324-L326
google/error-prone
core/src/main/java/com/google/errorprone/bugpatterns/AbstractToString.java
AbstractToString.checkToString
private Description checkToString(ExpressionTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof VarSymbol || sym instanceof MethodSymbol)) { return NO_MATCH; } Type type = ASTHelpers.getType(tree); if (type instanceof MethodType) { type = type.getReturnType(); } Tree parent = state.getPath().getParentPath().getLeaf(); ToStringKind toStringKind = isToString(parent, tree, state); if (toStringKind == ToStringKind.NONE) { return NO_MATCH; } if (!typePredicate().apply(type, state)) { return NO_MATCH; } Optional<Fix> fix; switch (toStringKind) { case IMPLICIT: fix = implicitToStringFix(tree, state); break; case EXPLICIT: fix = toStringFix(parent, tree, state); break; default: throw new AssertionError(toStringKind); } return maybeFix(tree, state, type, fix); }
java
private Description checkToString(ExpressionTree tree, VisitorState state) { Symbol sym = ASTHelpers.getSymbol(tree); if (!(sym instanceof VarSymbol || sym instanceof MethodSymbol)) { return NO_MATCH; } Type type = ASTHelpers.getType(tree); if (type instanceof MethodType) { type = type.getReturnType(); } Tree parent = state.getPath().getParentPath().getLeaf(); ToStringKind toStringKind = isToString(parent, tree, state); if (toStringKind == ToStringKind.NONE) { return NO_MATCH; } if (!typePredicate().apply(type, state)) { return NO_MATCH; } Optional<Fix> fix; switch (toStringKind) { case IMPLICIT: fix = implicitToStringFix(tree, state); break; case EXPLICIT: fix = toStringFix(parent, tree, state); break; default: throw new AssertionError(toStringKind); } return maybeFix(tree, state, type, fix); }
[ "private", "Description", "checkToString", "(", "ExpressionTree", "tree", ",", "VisitorState", "state", ")", "{", "Symbol", "sym", "=", "ASTHelpers", ".", "getSymbol", "(", "tree", ")", ";", "if", "(", "!", "(", "sym", "instanceof", "VarSymbol", "||", "sym",...
Tests if the given expression is converted to a String by its parent (i.e. its parent is a string concat expression, {@code String.format}, or {@code println(Object)}).
[ "Tests", "if", "the", "given", "expression", "is", "converted", "to", "a", "String", "by", "its", "parent", "(", "i", ".", "e", ".", "its", "parent", "is", "a", "string", "concat", "expression", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/core/src/main/java/com/google/errorprone/bugpatterns/AbstractToString.java#L122-L151
jamesagnew/hapi-fhir
hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/conformance/ShExGenerator.java
ShExGenerator.genChoiceEntry
private String genChoiceEntry(StructureDefinition sd, ElementDefinition ed, String id, String base, ElementDefinition.TypeRefComponent typ) { ST shex_choice_entry = tmplt(ELEMENT_TEMPLATE); String ext = typ.getCode(); shex_choice_entry.add("id", "fhir:" + base+Character.toUpperCase(ext.charAt(0)) + ext.substring(1) + " "); shex_choice_entry.add("card", ""); shex_choice_entry.add("defn", genTypeRef(sd, ed, id, typ)); shex_choice_entry.add("comment", " "); return shex_choice_entry.render(); }
java
private String genChoiceEntry(StructureDefinition sd, ElementDefinition ed, String id, String base, ElementDefinition.TypeRefComponent typ) { ST shex_choice_entry = tmplt(ELEMENT_TEMPLATE); String ext = typ.getCode(); shex_choice_entry.add("id", "fhir:" + base+Character.toUpperCase(ext.charAt(0)) + ext.substring(1) + " "); shex_choice_entry.add("card", ""); shex_choice_entry.add("defn", genTypeRef(sd, ed, id, typ)); shex_choice_entry.add("comment", " "); return shex_choice_entry.render(); }
[ "private", "String", "genChoiceEntry", "(", "StructureDefinition", "sd", ",", "ElementDefinition", "ed", ",", "String", "id", ",", "String", "base", ",", "ElementDefinition", ".", "TypeRefComponent", "typ", ")", "{", "ST", "shex_choice_entry", "=", "tmplt", "(", ...
Generate an entry in a choice list @param base base identifier @param typ type/discriminant @return ShEx fragment for choice entry
[ "Generate", "an", "entry", "in", "a", "choice", "list" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-structures-r4/src/main/java/org/hl7/fhir/r4/conformance/ShExGenerator.java#L668-L677
xcesco/kripton
kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/EnumPrefsTransform.java
EnumPrefsTransform.generateWriteProperty
@Override public void generateWriteProperty(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.putString($S,$L.toString() )", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property)); methodBuilder.nextControlFlow("else"); methodBuilder.addStatement("$L.remove($S)", editorName, property.getName()); methodBuilder.endControlFlow(); }
java
@Override public void generateWriteProperty(Builder methodBuilder, String editorName, TypeName beanClass, String beanName, PrefsProperty property) { methodBuilder.beginControlFlow("if ($L!=null) ", getter(beanName, beanClass, property)); methodBuilder.addStatement("$L.putString($S,$L.toString() )", editorName, property.getPreferenceKey(), getter(beanName, beanClass, property)); methodBuilder.nextControlFlow("else"); methodBuilder.addStatement("$L.remove($S)", editorName, property.getName()); methodBuilder.endControlFlow(); }
[ "@", "Override", "public", "void", "generateWriteProperty", "(", "Builder", "methodBuilder", ",", "String", "editorName", ",", "TypeName", "beanClass", ",", "String", "beanName", ",", "PrefsProperty", "property", ")", "{", "methodBuilder", ".", "beginControlFlow", "...
/* (non-Javadoc) @see com.abubusoft.kripton.processor.sharedprefs.transform.PrefsTransform#generateWriteProperty(com.squareup.javapoet.MethodSpec.Builder, java.lang.String, com.squareup.javapoet.TypeName, java.lang.String, com.abubusoft.kripton.processor.sharedprefs.model.PrefsProperty)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/xcesco/kripton/blob/90de2c0523d39b99e81b8d38aa996898762f594a/kripton-processor/src/main/java/com/abubusoft/kripton/processor/sharedprefs/transform/EnumPrefsTransform.java#L94-L102
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/model/ValidationResult.java
ValidationResult.addError
public void addError(String desc, String loc, long value) { iaddError(desc, "" + value, loc); }
java
public void addError(String desc, String loc, long value) { iaddError(desc, "" + value, loc); }
[ "public", "void", "addError", "(", "String", "desc", ",", "String", "loc", ",", "long", "value", ")", "{", "iaddError", "(", "desc", ",", "\"\"", "+", "value", ",", "loc", ")", ";", "}" ]
Adds an error. @param desc Error description @param loc Error Location @param value the integer value that caused the error
[ "Adds", "an", "error", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/model/ValidationResult.java#L105-L107
perwendel/spark
src/main/java/spark/utils/MimeParse.java
MimeParse.fitnessAndQualityParsed
private static FitnessAndQuality fitnessAndQualityParsed(String mimeType, Collection<ParseResults> parsedRanges) { int bestFitness = -1; float bestFitQ = 0; ParseResults target = parseMediaRange(mimeType); for (ParseResults range : parsedRanges) { if ((target.type.equals(range.type) || range.type.equals("*") || target.type.equals("*")) && (target.subType.equals(range.subType) || range.subType.equals("*") || target.subType.equals("*"))) { for (String k : target.params.keySet()) { int paramMatches = 0; if (!k.equals("q") && range.params.containsKey(k) && target.params.get(k).equals(range.params.get(k))) { paramMatches++; } int fitness = (range.type.equals(target.type)) ? 100 : 0; fitness += (range.subType.equals(target.subType)) ? 10 : 0; fitness += paramMatches; if (fitness > bestFitness) { bestFitness = fitness; bestFitQ = toFloat(range.params.get("q"), 0); } } } } return new FitnessAndQuality(bestFitness, bestFitQ); }
java
private static FitnessAndQuality fitnessAndQualityParsed(String mimeType, Collection<ParseResults> parsedRanges) { int bestFitness = -1; float bestFitQ = 0; ParseResults target = parseMediaRange(mimeType); for (ParseResults range : parsedRanges) { if ((target.type.equals(range.type) || range.type.equals("*") || target.type.equals("*")) && (target.subType.equals(range.subType) || range.subType.equals("*") || target.subType.equals("*"))) { for (String k : target.params.keySet()) { int paramMatches = 0; if (!k.equals("q") && range.params.containsKey(k) && target.params.get(k).equals(range.params.get(k))) { paramMatches++; } int fitness = (range.type.equals(target.type)) ? 100 : 0; fitness += (range.subType.equals(target.subType)) ? 10 : 0; fitness += paramMatches; if (fitness > bestFitness) { bestFitness = fitness; bestFitQ = toFloat(range.params.get("q"), 0); } } } } return new FitnessAndQuality(bestFitness, bestFitQ); }
[ "private", "static", "FitnessAndQuality", "fitnessAndQualityParsed", "(", "String", "mimeType", ",", "Collection", "<", "ParseResults", ">", "parsedRanges", ")", "{", "int", "bestFitness", "=", "-", "1", ";", "float", "bestFitQ", "=", "0", ";", "ParseResults", "...
Find the best match for a given mimeType against a list of media_ranges that have already been parsed by MimeParse.parseMediaRange(). Returns a tuple of the fitness value and the value of the 'q' quality parameter of the best match, or (-1, 0) if no match was found. Just as for quality_parsed(), 'parsed_ranges' must be a list of parsed media ranges. @param mimeType @param parsedRanges
[ "Find", "the", "best", "match", "for", "a", "given", "mimeType", "against", "a", "list", "of", "media_ranges", "that", "have", "already", "been", "parsed", "by", "MimeParse", ".", "parseMediaRange", "()", ".", "Returns", "a", "tuple", "of", "the", "fitness",...
train
https://github.com/perwendel/spark/blob/080fb1f9d6e580f6742e9589044c7420d3157b8b/src/main/java/spark/utils/MimeParse.java#L138-L164
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/ui/CmsLockReportDialog.java
CmsLockReportDialog.getMessageForLock
private String getMessageForLock(LockIcon lockIcon, boolean hasLockedChildren) { String result = ""; if (!hasLockedChildren && ((lockIcon == null) || (lockIcon == LockIcon.NONE))) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_NOTHING_LOCKED_0); } else if ((lockIcon == LockIcon.OPEN) || (lockIcon == LockIcon.SHARED_OPEN)) { if (hasLockedChildren) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_UNLOCK_ALL_MESSAGE_0); } else { result = Messages.get().key(Messages.GUI_LOCK_REPORT_UNLOCK_MESSAGE_0); } } else { if (hasLockedChildren) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_STEAL_ALL_LOCKS_MESSAGE_0); } else { result = Messages.get().key(Messages.GUI_LOCK_REPORT_STEAL_LOCK_MESSAGE_0); } } return result; }
java
private String getMessageForLock(LockIcon lockIcon, boolean hasLockedChildren) { String result = ""; if (!hasLockedChildren && ((lockIcon == null) || (lockIcon == LockIcon.NONE))) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_NOTHING_LOCKED_0); } else if ((lockIcon == LockIcon.OPEN) || (lockIcon == LockIcon.SHARED_OPEN)) { if (hasLockedChildren) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_UNLOCK_ALL_MESSAGE_0); } else { result = Messages.get().key(Messages.GUI_LOCK_REPORT_UNLOCK_MESSAGE_0); } } else { if (hasLockedChildren) { result = Messages.get().key(Messages.GUI_LOCK_REPORT_STEAL_ALL_LOCKS_MESSAGE_0); } else { result = Messages.get().key(Messages.GUI_LOCK_REPORT_STEAL_LOCK_MESSAGE_0); } } return result; }
[ "private", "String", "getMessageForLock", "(", "LockIcon", "lockIcon", ",", "boolean", "hasLockedChildren", ")", "{", "String", "result", "=", "\"\"", ";", "if", "(", "!", "hasLockedChildren", "&&", "(", "(", "lockIcon", "==", "null", ")", "||", "(", "lockIc...
Returns the dialog message for the given lock.<p> @param lockIcon the lock icon @param hasLockedChildren <code>true</code> if the given resource has locked children @return the dialog message
[ "Returns", "the", "dialog", "message", "for", "the", "given", "lock", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsLockReportDialog.java#L346-L365
btrplace/scheduler
json/src/main/java/org/btrplace/json/JSONs.java
JSONs.getNode
public static Node getNode(Model mo, int nodeID) throws JSONConverterException { Node n = new Node(nodeID); if (!mo.contains(n)) { throw new JSONConverterException("Undeclared node '" + nodeID + "'"); } return n; }
java
public static Node getNode(Model mo, int nodeID) throws JSONConverterException { Node n = new Node(nodeID); if (!mo.contains(n)) { throw new JSONConverterException("Undeclared node '" + nodeID + "'"); } return n; }
[ "public", "static", "Node", "getNode", "(", "Model", "mo", ",", "int", "nodeID", ")", "throws", "JSONConverterException", "{", "Node", "n", "=", "new", "Node", "(", "nodeID", ")", ";", "if", "(", "!", "mo", ".", "contains", "(", "n", ")", ")", "{", ...
Get a node from its identifier. The node is already a part of the model @param mo the associated model to browse @param nodeID the node identifier @return the resulting node @throws JSONConverterException if there is no model, or if the node is unknown.
[ "Get", "a", "node", "from", "its", "identifier", ".", "The", "node", "is", "already", "a", "part", "of", "the", "model" ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/json/src/main/java/org/btrplace/json/JSONs.java#L394-L400
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java
FSDirectory.getFileInfo
FileStatus getFileInfo(String src, INode targetNode) { String srcs = normalizePath(src); readLock(); try { if (targetNode == null) { return null; } else { return createFileStatus(srcs, targetNode); } } finally { readUnlock(); } }
java
FileStatus getFileInfo(String src, INode targetNode) { String srcs = normalizePath(src); readLock(); try { if (targetNode == null) { return null; } else { return createFileStatus(srcs, targetNode); } } finally { readUnlock(); } }
[ "FileStatus", "getFileInfo", "(", "String", "src", ",", "INode", "targetNode", ")", "{", "String", "srcs", "=", "normalizePath", "(", "src", ")", ";", "readLock", "(", ")", ";", "try", "{", "if", "(", "targetNode", "==", "null", ")", "{", "return", "nu...
Get the file info for a specific file. @param src The string representation of the path to the file @return object containing information regarding the file or null if file not found
[ "Get", "the", "file", "info", "for", "a", "specific", "file", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/FSDirectory.java#L1800-L1813
raydac/java-binary-block-parser
jbbp/src/main/java/com/igormaznitsa/jbbp/model/JBBPFieldStruct.java
JBBPFieldStruct.mapTo
public <T> T mapTo(final Class<T> mappingClass, final int flags) { return mapTo(mappingClass, null, flags); }
java
public <T> T mapTo(final Class<T> mappingClass, final int flags) { return mapTo(mappingClass, null, flags); }
[ "public", "<", "T", ">", "T", "mapTo", "(", "final", "Class", "<", "T", ">", "mappingClass", ",", "final", "int", "flags", ")", "{", "return", "mapTo", "(", "mappingClass", ",", "null", ",", "flags", ")", ";", "}" ]
Map the structure fields to a class fields. @param <T> a class type @param mappingClass a mapping class to be mapped by the structure fields, must not be null and must have the default constructor @param flags special flags to tune mapping @return a mapped instance of the class, must not be null
[ "Map", "the", "structure", "fields", "to", "a", "class", "fields", "." ]
train
https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/model/JBBPFieldStruct.java#L244-L246
google/closure-compiler
src/com/google/javascript/jscomp/DestructuredTarget.java
DestructuredTarget.createTarget
static DestructuredTarget createTarget( JSTypeRegistry registry, Supplier<JSType> destructuringPatternType, Node destructuringChild) { checkArgument(destructuringChild.getParent().isDestructuringPattern(), destructuringChild); Builder builder = new Builder(registry, destructuringChild.getParent(), destructuringPatternType); switch (destructuringChild.getToken()) { case STRING_KEY: // const {objectLiteralKey: x} = ... builder.setObjectPatternKey(destructuringChild); Node value = destructuringChild.getFirstChild(); if (value.isDefaultValue()) { builder.setNode(value.getFirstChild()); builder.setDefaultValue(value.getSecondChild()); } else { builder.setNode(value); } break; case COMPUTED_PROP: // const {['objectLiteralKey']: x} = ... builder.setObjectPatternKey(destructuringChild); value = destructuringChild.getSecondChild(); if (value.isDefaultValue()) { builder.setNode(value.getFirstChild()); builder.setDefaultValue(value.getSecondChild()); } else { builder.setNode(value); } break; case OBJECT_PATTERN: // const [{x}] = ... case ARRAY_PATTERN: // const [[x]] = ... case NAME: // const [x] = ... case GETELEM: // [obj[3]] = ... case GETPROP: // [this.x] = ... builder.setNode(destructuringChild); break; case DEFAULT_VALUE: // const [x = 3] = ... builder.setNode(destructuringChild.getFirstChild()); builder.setDefaultValue(destructuringChild.getSecondChild()); break; case REST: // const [...x] = ... // const {...x} = ... builder.setNode(destructuringChild.getFirstChild()); builder.setIsRest(true); break; default: throw new IllegalArgumentException( "Unexpected child of destructuring pattern " + destructuringChild); } return builder.build(); }
java
static DestructuredTarget createTarget( JSTypeRegistry registry, Supplier<JSType> destructuringPatternType, Node destructuringChild) { checkArgument(destructuringChild.getParent().isDestructuringPattern(), destructuringChild); Builder builder = new Builder(registry, destructuringChild.getParent(), destructuringPatternType); switch (destructuringChild.getToken()) { case STRING_KEY: // const {objectLiteralKey: x} = ... builder.setObjectPatternKey(destructuringChild); Node value = destructuringChild.getFirstChild(); if (value.isDefaultValue()) { builder.setNode(value.getFirstChild()); builder.setDefaultValue(value.getSecondChild()); } else { builder.setNode(value); } break; case COMPUTED_PROP: // const {['objectLiteralKey']: x} = ... builder.setObjectPatternKey(destructuringChild); value = destructuringChild.getSecondChild(); if (value.isDefaultValue()) { builder.setNode(value.getFirstChild()); builder.setDefaultValue(value.getSecondChild()); } else { builder.setNode(value); } break; case OBJECT_PATTERN: // const [{x}] = ... case ARRAY_PATTERN: // const [[x]] = ... case NAME: // const [x] = ... case GETELEM: // [obj[3]] = ... case GETPROP: // [this.x] = ... builder.setNode(destructuringChild); break; case DEFAULT_VALUE: // const [x = 3] = ... builder.setNode(destructuringChild.getFirstChild()); builder.setDefaultValue(destructuringChild.getSecondChild()); break; case REST: // const [...x] = ... // const {...x} = ... builder.setNode(destructuringChild.getFirstChild()); builder.setIsRest(true); break; default: throw new IllegalArgumentException( "Unexpected child of destructuring pattern " + destructuringChild); } return builder.build(); }
[ "static", "DestructuredTarget", "createTarget", "(", "JSTypeRegistry", "registry", ",", "Supplier", "<", "JSType", ">", "destructuringPatternType", ",", "Node", "destructuringChild", ")", "{", "checkArgument", "(", "destructuringChild", ".", "getParent", "(", ")", "."...
Converts a given child of a destructuring pattern (in the AST) to an instance of this class. NOTE: does not accept EMPTY nodes
[ "Converts", "a", "given", "child", "of", "a", "destructuring", "pattern", "(", "in", "the", "AST", ")", "to", "an", "instance", "of", "this", "class", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/DestructuredTarget.java#L169-L225
radkovo/SwingBox
src/main/java/org/fit/cssbox/swingbox/BrowserPane.java
BrowserPane.renderContent
public Graphics2D renderContent() { View view = null; ViewFactory factory = getEditorKit().getViewFactory(); if (factory instanceof SwingBoxViewFactory) { view = ((SwingBoxViewFactory) factory).getViewport(); } if (view != null) { int w = (int) view.getPreferredSpan(View.X_AXIS); int h = (int) view.getPreferredSpan(View.Y_AXIS); Rectangle rec = new Rectangle(w, h); BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); g.setClip(rec); view.paint(g, rec); return g; } return null; }
java
public Graphics2D renderContent() { View view = null; ViewFactory factory = getEditorKit().getViewFactory(); if (factory instanceof SwingBoxViewFactory) { view = ((SwingBoxViewFactory) factory).getViewport(); } if (view != null) { int w = (int) view.getPreferredSpan(View.X_AXIS); int h = (int) view.getPreferredSpan(View.Y_AXIS); Rectangle rec = new Rectangle(w, h); BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g = img.createGraphics(); g.setClip(rec); view.paint(g, rec); return g; } return null; }
[ "public", "Graphics2D", "renderContent", "(", ")", "{", "View", "view", "=", "null", ";", "ViewFactory", "factory", "=", "getEditorKit", "(", ")", ".", "getViewFactory", "(", ")", ";", "if", "(", "factory", "instanceof", "SwingBoxViewFactory", ")", "{", "vie...
Renders current content to graphic context, which is returned. May return null; @return the Graphics2D context @see Graphics2D
[ "Renders", "current", "content", "to", "graphic", "context", "which", "is", "returned", ".", "May", "return", "null", ";" ]
train
https://github.com/radkovo/SwingBox/blob/ff370f3dc54d248e4c8852c17513618c83c25984/src/main/java/org/fit/cssbox/swingbox/BrowserPane.java#L230-L256
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java
LabelProcessor.getBestMatch
public static String getBestMatch(final LabelOrBuilder label, final String alternative) { try { return getBestMatch(Locale.getDefault(), label); } catch (NotAvailableException e) { return alternative; } }
java
public static String getBestMatch(final LabelOrBuilder label, final String alternative) { try { return getBestMatch(Locale.getDefault(), label); } catch (NotAvailableException e) { return alternative; } }
[ "public", "static", "String", "getBestMatch", "(", "final", "LabelOrBuilder", "label", ",", "final", "String", "alternative", ")", "{", "try", "{", "return", "getBestMatch", "(", "Locale", ".", "getDefault", "(", ")", ",", "label", ")", ";", "}", "catch", ...
Get the first label for the default language from a label type. This is equivalent to calling {@link #getLabelByLanguage(String, LabelOrBuilder)} but the language code is extracted from the locale by calling {@link Locale#getDefault()} . If no label matches the languageCode, than the first label of any other provided language is returned. @param label the label type which is searched for labels in the language @param alternative an alternative string which is returned in error case. @return the first label from the label type for the locale or if no label is provided by the {@code label} argument the {@code alternative} is returned.
[ "Get", "the", "first", "label", "for", "the", "default", "language", "from", "a", "label", "type", ".", "This", "is", "equivalent", "to", "calling", "{", "@link", "#getLabelByLanguage", "(", "String", "LabelOrBuilder", ")", "}", "but", "the", "language", "co...
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java#L255-L261
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java
HttpFields.put
public String put(String name,String value) { if (value==null) return remove(name); FieldInfo info=getFieldInfo(name); Field field=getField(info,false); // Look for value to replace. if (field!=null) { String old=(field._version==_version)?field._value:null; field.reset(value,_version); field=field._next; while(field!=null) { field.clear(); field=field._next; } return old; } else { // new value; field=new Field(info,value,_version); int hi=info.hashCode(); if (hi<_index.length) _index[hi]=_fields.size(); _fields.add(field); return null; } }
java
public String put(String name,String value) { if (value==null) return remove(name); FieldInfo info=getFieldInfo(name); Field field=getField(info,false); // Look for value to replace. if (field!=null) { String old=(field._version==_version)?field._value:null; field.reset(value,_version); field=field._next; while(field!=null) { field.clear(); field=field._next; } return old; } else { // new value; field=new Field(info,value,_version); int hi=info.hashCode(); if (hi<_index.length) _index[hi]=_fields.size(); _fields.add(field); return null; } }
[ "public", "String", "put", "(", "String", "name", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", "remove", "(", "name", ")", ";", "FieldInfo", "info", "=", "getFieldInfo", "(", "name", ")", ";", "Field", "field", "...
Set a field. @param name the name of the field @param value the value of the field. If null the field is cleared.
[ "Set", "a", "field", "." ]
train
https://github.com/webmetrics/browsermob-proxy/blob/a9252e62246ac33d55d51b993ba1159404e7d389/src/main/java/org/browsermob/proxy/jetty/http/HttpFields.java#L815-L846
leancloud/java-sdk-all
realtime/src/main/java/cn/leancloud/im/v2/AVIMConversationsQuery.java
AVIMConversationsQuery.whereWithinMiles
public AVIMConversationsQuery whereWithinMiles(String key, AVGeoPoint point, double maxDistance) { conditions.whereWithinMiles(key, point, maxDistance); return this; }
java
public AVIMConversationsQuery whereWithinMiles(String key, AVGeoPoint point, double maxDistance) { conditions.whereWithinMiles(key, point, maxDistance); return this; }
[ "public", "AVIMConversationsQuery", "whereWithinMiles", "(", "String", "key", ",", "AVGeoPoint", "point", ",", "double", "maxDistance", ")", "{", "conditions", ".", "whereWithinMiles", "(", "key", ",", "point", ",", "maxDistance", ")", ";", "return", "this", ";"...
增加一个基于地理位置的近似查询,当conversation的属性中有对应的地址位置与指定的地理位置间距不超过指定距离时返回 @param key @param point 指定的地理位置 @param maxDistance 距离,以英里计算 @return
[ "增加一个基于地理位置的近似查询,当conversation的属性中有对应的地址位置与指定的地理位置间距不超过指定距离时返回" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/realtime/src/main/java/cn/leancloud/im/v2/AVIMConversationsQuery.java#L329-L332
openbase/jul
extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java
LabelProcessor.buildLabel
public static Label buildLabel(final Locale locale, final String label) { return addLabel(Label.newBuilder(), locale.getLanguage(), label).build(); }
java
public static Label buildLabel(final Locale locale, final String label) { return addLabel(Label.newBuilder(), locale.getLanguage(), label).build(); }
[ "public", "static", "Label", "buildLabel", "(", "final", "Locale", "locale", ",", "final", "String", "label", ")", "{", "return", "addLabel", "(", "Label", ".", "newBuilder", "(", ")", ",", "locale", ".", "getLanguage", "(", ")", ",", "label", ")", ".", ...
Create a new labelBuilder and register label with given locale. @param locale the locale from which the language code is extracted for which the label is added @param label the label to be added @return the updated label builder
[ "Create", "a", "new", "labelBuilder", "and", "register", "label", "with", "given", "locale", "." ]
train
https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/LabelProcessor.java#L131-L133
cdk/cdk
legacy/src/main/java/org/openscience/cdk/tools/IonizationPotentialTool.java
IonizationPotentialTool.initiateIonization
private static IAtomContainer initiateIonization(IAtomContainer container, IAtom atom) throws CDKException { IReactionProcess reactionNBE = new ElectronImpactNBEReaction(); IAtomContainerSet setOfReactants = container.getBuilder().newInstance(IAtomContainerSet.class); setOfReactants.addAtomContainer(container); atom.setFlag(CDKConstants.REACTIVE_CENTER, true); List<IParameterReact> paramList = new ArrayList<IParameterReact>(); IParameterReact param = new SetReactionCenter(); param.setParameter(Boolean.TRUE); paramList.add(param); reactionNBE.setParameterList(paramList); /* initiate */ IReactionSet setOfReactions = reactionNBE.initiate(setOfReactants, null); atom.setFlag(CDKConstants.REACTIVE_CENTER, false); if (setOfReactions != null && setOfReactions.getReactionCount() == 1 && setOfReactions.getReaction(0).getProducts().getAtomContainerCount() == 1) return setOfReactions.getReaction(0).getProducts().getAtomContainer(0); else return null; }
java
private static IAtomContainer initiateIonization(IAtomContainer container, IAtom atom) throws CDKException { IReactionProcess reactionNBE = new ElectronImpactNBEReaction(); IAtomContainerSet setOfReactants = container.getBuilder().newInstance(IAtomContainerSet.class); setOfReactants.addAtomContainer(container); atom.setFlag(CDKConstants.REACTIVE_CENTER, true); List<IParameterReact> paramList = new ArrayList<IParameterReact>(); IParameterReact param = new SetReactionCenter(); param.setParameter(Boolean.TRUE); paramList.add(param); reactionNBE.setParameterList(paramList); /* initiate */ IReactionSet setOfReactions = reactionNBE.initiate(setOfReactants, null); atom.setFlag(CDKConstants.REACTIVE_CENTER, false); if (setOfReactions != null && setOfReactions.getReactionCount() == 1 && setOfReactions.getReaction(0).getProducts().getAtomContainerCount() == 1) return setOfReactions.getReaction(0).getProducts().getAtomContainer(0); else return null; }
[ "private", "static", "IAtomContainer", "initiateIonization", "(", "IAtomContainer", "container", ",", "IAtom", "atom", ")", "throws", "CDKException", "{", "IReactionProcess", "reactionNBE", "=", "new", "ElectronImpactNBEReaction", "(", ")", ";", "IAtomContainerSet", "se...
Initiate the reaction ElectronImpactNBE. @param container The IAtomContainer @param atom The IAtom to ionize @return The product resultant @throws CDKException
[ "Initiate", "the", "reaction", "ElectronImpactNBE", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/legacy/src/main/java/org/openscience/cdk/tools/IonizationPotentialTool.java#L461-L482
jMetal/jMetal
jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/MOEADSTM.java
MOEADSTM.calculateDistance
public double calculateDistance(DoubleSolution individual, double[] lambda) { double scale; double distance; double[] vecInd = new double[problem.getNumberOfObjectives()]; double[] vecProj = new double[problem.getNumberOfObjectives()]; // vecInd has been normalized to the range [0,1] for (int i = 0; i < problem.getNumberOfObjectives(); i++) { vecInd[i] = (individual.getObjective(i) - idealPoint.getValue(i)) / (nadirPoint.getValue(i) - idealPoint.getValue(i)); } scale = innerproduct(vecInd, lambda) / innerproduct(lambda, lambda); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { vecProj[i] = vecInd[i] - scale * lambda[i]; } distance = norm_vector(vecProj); return distance; }
java
public double calculateDistance(DoubleSolution individual, double[] lambda) { double scale; double distance; double[] vecInd = new double[problem.getNumberOfObjectives()]; double[] vecProj = new double[problem.getNumberOfObjectives()]; // vecInd has been normalized to the range [0,1] for (int i = 0; i < problem.getNumberOfObjectives(); i++) { vecInd[i] = (individual.getObjective(i) - idealPoint.getValue(i)) / (nadirPoint.getValue(i) - idealPoint.getValue(i)); } scale = innerproduct(vecInd, lambda) / innerproduct(lambda, lambda); for (int i = 0; i < problem.getNumberOfObjectives(); i++) { vecProj[i] = vecInd[i] - scale * lambda[i]; } distance = norm_vector(vecProj); return distance; }
[ "public", "double", "calculateDistance", "(", "DoubleSolution", "individual", ",", "double", "[", "]", "lambda", ")", "{", "double", "scale", ";", "double", "distance", ";", "double", "[", "]", "vecInd", "=", "new", "double", "[", "problem", ".", "getNumberO...
Calculate the perpendicular distance between the solution and reference line
[ "Calculate", "the", "perpendicular", "distance", "between", "the", "solution", "and", "reference", "line" ]
train
https://github.com/jMetal/jMetal/blob/bc981e6aede275d26c5216c9a01227d9675b0cf7/jmetal-algorithm/src/main/java/org/uma/jmetal/algorithm/multiobjective/moead/MOEADSTM.java#L319-L340
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TableHeaderRendererPainter.java
TableHeaderRendererPainter.getTableHeaderColors
private FourColors getTableHeaderColors(CommonControlState type, boolean isSorted) { switch (type) { case DISABLED: return isSorted ? tableHeaderDisabledSorted : tableHeaderDisabled; case ENABLED: return isSorted ? tableHeaderSorted : tableHeaderEnabled; case PRESSED: return tableHeaderPressed; } return null; }
java
private FourColors getTableHeaderColors(CommonControlState type, boolean isSorted) { switch (type) { case DISABLED: return isSorted ? tableHeaderDisabledSorted : tableHeaderDisabled; case ENABLED: return isSorted ? tableHeaderSorted : tableHeaderEnabled; case PRESSED: return tableHeaderPressed; } return null; }
[ "private", "FourColors", "getTableHeaderColors", "(", "CommonControlState", "type", ",", "boolean", "isSorted", ")", "{", "switch", "(", "type", ")", "{", "case", "DISABLED", ":", "return", "isSorted", "?", "tableHeaderDisabledSorted", ":", "tableHeaderDisabled", ";...
DOCUMENT ME! @param type DOCUMENT ME! @param isSorted DOCUMENT ME! @return DOCUMENT ME!
[ "DOCUMENT", "ME!" ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TableHeaderRendererPainter.java#L173-L187
jenetics/jenetics
jenetics.tool/src/main/java/io/jenetics/tool/trial/Gnuplot.java
Gnuplot.create
public void create(final Path data, final Path output) throws IOException { _parameters.put(DATA_NAME, data.toString()); _parameters.put(OUTPUT_NAME, output.toString()); final String params = _parameters.entrySet().stream() .map(Gnuplot::toParamString) .collect(Collectors.joining("; ")); String script = new String(Files.readAllBytes(_template)); for (Map.Entry<String, String> entry : _environment.entrySet()) { final String key = format("${%s}", entry.getKey()); script = script.replace(key, entry.getValue()); } final Path scriptPath = tempPath(); try { IO.write(script, scriptPath); final List<String> command = Arrays. asList("gnuplot", "-e", params, scriptPath.toString()); final Process process = new ProcessBuilder() .command(command) .start(); System.out.println(IO.toText(process.getErrorStream())); try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } finally { deleteIfExists(scriptPath); } }
java
public void create(final Path data, final Path output) throws IOException { _parameters.put(DATA_NAME, data.toString()); _parameters.put(OUTPUT_NAME, output.toString()); final String params = _parameters.entrySet().stream() .map(Gnuplot::toParamString) .collect(Collectors.joining("; ")); String script = new String(Files.readAllBytes(_template)); for (Map.Entry<String, String> entry : _environment.entrySet()) { final String key = format("${%s}", entry.getKey()); script = script.replace(key, entry.getValue()); } final Path scriptPath = tempPath(); try { IO.write(script, scriptPath); final List<String> command = Arrays. asList("gnuplot", "-e", params, scriptPath.toString()); final Process process = new ProcessBuilder() .command(command) .start(); System.out.println(IO.toText(process.getErrorStream())); try { process.waitFor(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } finally { deleteIfExists(scriptPath); } }
[ "public", "void", "create", "(", "final", "Path", "data", ",", "final", "Path", "output", ")", "throws", "IOException", "{", "_parameters", ".", "put", "(", "DATA_NAME", ",", "data", ".", "toString", "(", ")", ")", ";", "_parameters", ".", "put", "(", ...
Generate the Gnuplot graph. @param data the input data file @param output the output path of the graph @throws IOException if the Gnuplot generation fails
[ "Generate", "the", "Gnuplot", "graph", "." ]
train
https://github.com/jenetics/jenetics/blob/ee516770c65ef529b27deb283f071c85f344eff4/jenetics.tool/src/main/java/io/jenetics/tool/trial/Gnuplot.java#L86-L121
FXMisc/RichTextFX
richtextfx/src/main/java/org/fxmisc/richtext/model/ReadOnlyStyledDocumentBuilder.java
ReadOnlyStyledDocumentBuilder.addParagraphs
public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraphs(List<List<SEG>> listOfSegLists, StyleSpans<S> entireDocumentStyleSpans) { return addParagraphList(listOfSegLists, entireDocumentStyleSpans, ignore -> null, Function.identity()); }
java
public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraphs(List<List<SEG>> listOfSegLists, StyleSpans<S> entireDocumentStyleSpans) { return addParagraphList(listOfSegLists, entireDocumentStyleSpans, ignore -> null, Function.identity()); }
[ "public", "ReadOnlyStyledDocumentBuilder", "<", "PS", ",", "SEG", ",", "S", ">", "addParagraphs", "(", "List", "<", "List", "<", "SEG", ">", ">", "listOfSegLists", ",", "StyleSpans", "<", "S", ">", "entireDocumentStyleSpans", ")", "{", "return", "addParagraphL...
Adds multiple paragraphs to the list, using the {@link #defaultParagraphStyle} for each paragraph. For more configuration on each paragraph's paragraph style, use {@link #addParagraphs0(List, StyleSpans)} @param listOfSegLists each item is the list of segments for a single paragraph @param entireDocumentStyleSpans style spans for the entire document. It's length should be equal to the length of all the segments' length combined
[ "Adds", "multiple", "paragraphs", "to", "the", "list", "using", "the", "{", "@link", "#defaultParagraphStyle", "}", "for", "each", "paragraph", ".", "For", "more", "configuration", "on", "each", "paragraph", "s", "paragraph", "style", "use", "{", "@link", "#ad...
train
https://github.com/FXMisc/RichTextFX/blob/bc7cab6a637855e0f37d9b9c12a9172c31545f0b/richtextfx/src/main/java/org/fxmisc/richtext/model/ReadOnlyStyledDocumentBuilder.java#L153-L156
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java
ResourceGroovyMethods.newReader
public static BufferedReader newReader(URL url, Map parameters, String charset) throws MalformedURLException, IOException { return new BufferedReader(new InputStreamReader(configuredInputStream(parameters, url), charset)); }
java
public static BufferedReader newReader(URL url, Map parameters, String charset) throws MalformedURLException, IOException { return new BufferedReader(new InputStreamReader(configuredInputStream(parameters, url), charset)); }
[ "public", "static", "BufferedReader", "newReader", "(", "URL", "url", ",", "Map", "parameters", ",", "String", "charset", ")", "throws", "MalformedURLException", ",", "IOException", "{", "return", "new", "BufferedReader", "(", "new", "InputStreamReader", "(", "con...
Creates a buffered reader for this URL using the given encoding. @param url a URL @param parameters connection parameters @param charset opens the stream with a specified charset @return a BufferedReader for the URL @throws MalformedURLException is thrown if the URL is not well formed @throws IOException if an I/O error occurs while creating the input stream @since 1.8.1
[ "Creates", "a", "buffered", "reader", "for", "this", "URL", "using", "the", "given", "encoding", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2283-L2285
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.addUserToGroup
public void addUserToGroup(CmsRequestContext context, String username, String groupname, boolean readRoles) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(username)); checkRoleForUserModification(dbc, username, role); m_driverManager.addUserToGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(groupname), readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_GROUP_FAILED_2, username, groupname), e); } finally { dbc.clear(); } }
java
public void addUserToGroup(CmsRequestContext context, String username, String groupname, boolean readRoles) throws CmsException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { CmsRole role = CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParentOrganizationalUnit(username)); checkRoleForUserModification(dbc, username, role); m_driverManager.addUserToGroup( dbc, CmsOrganizationalUnit.removeLeadingSeparator(username), CmsOrganizationalUnit.removeLeadingSeparator(groupname), readRoles); } catch (Exception e) { dbc.report(null, Messages.get().container(Messages.ERR_ADD_USER_GROUP_FAILED_2, username, groupname), e); } finally { dbc.clear(); } }
[ "public", "void", "addUserToGroup", "(", "CmsRequestContext", "context", ",", "String", "username", ",", "String", "groupname", ",", "boolean", "readRoles", ")", "throws", "CmsException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "(...
Adds a user to a group.<p> @param context the current request context @param username the name of the user that is to be added to the group @param groupname the name of the group @param readRoles if reading roles or groups @throws CmsException if operation was not successful
[ "Adds", "a", "user", "to", "a", "group", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L278-L295
liferay/com-liferay-commerce
commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java
CommerceNotificationTemplatePersistenceImpl.filterFindByGroupId
@Override public List<CommerceNotificationTemplate> filterFindByGroupId( long groupId, int start, int end) { return filterFindByGroupId(groupId, start, end, null); }
java
@Override public List<CommerceNotificationTemplate> filterFindByGroupId( long groupId, int start, int end) { return filterFindByGroupId(groupId, start, end, null); }
[ "@", "Override", "public", "List", "<", "CommerceNotificationTemplate", ">", "filterFindByGroupId", "(", "long", "groupId", ",", "int", "start", ",", "int", "end", ")", "{", "return", "filterFindByGroupId", "(", "groupId", ",", "start", ",", "end", ",", "null"...
Returns a range of all the commerce notification templates that the user has permission to view where groupId = &#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 CommerceNotificationTemplateModelImpl}. 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 groupId the group ID @param start the lower bound of the range of commerce notification templates @param end the upper bound of the range of commerce notification templates (not inclusive) @return the range of matching commerce notification templates that the user has permission to view
[ "Returns", "a", "range", "of", "all", "the", "commerce", "notification", "templates", "that", "the", "user", "has", "permission", "to", "view", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-service/src/main/java/com/liferay/commerce/notification/service/persistence/impl/CommerceNotificationTemplatePersistenceImpl.java#L1989-L1993
CloudSlang/cs-actions
cs-tesseract/src/main/java/io/cloudslang/content/tesseract/actions/ExtractTextFromImage.java
ExtractTextFromImage.execute
@Action(name = "Extract text from image", description = EXTRACT_TEXT_FROM_IMAGE_DESC, outputs = { @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC), @Output(value = TEXT_STRING, description = TEXT_STRING_DESC), @Output(value = TEXT_JSON, description = TEXT_JSON_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC), }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, isOnFail = true, description = FAILURE_DESC) }) public Map<String, String> execute( @Param(value = FILE_PATH, required = true, description = FILE_PATH_DESC) String filePath, @Param(value = DATA_PATH, required = true, description = DATA_PATH_DESC) String dataPath, @Param(value = LANGUAGE, required = true, description = LANGUAGE_DESC) String language, @Param(value = TEXT_BLOCKS, description = TEXT_BLOCKS_DESC) String textBlocks, @Param(value = DESKEW, description = DESKEW_DESC) String deskew) { dataPath = defaultIfEmpty(dataPath, EMPTY); language = defaultIfEmpty(language, ENG); textBlocks = defaultIfEmpty(textBlocks, FALSE); deskew = defaultIfEmpty(deskew, FALSE); final List<String> exceptionMessages = verifyExtractTextInputs(filePath, dataPath, textBlocks, deskew); if (!exceptionMessages.isEmpty()) { return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE)); } try { final String resultText = extractTextFromImage(filePath, dataPath, language, textBlocks, deskew); final Map<String, String> result = getSuccessResultsMap(resultText); if (Boolean.parseBoolean(textBlocks)) { result.put(TEXT_JSON, resultText); } else { result.put(TEXT_STRING, resultText); } return result; } catch (Exception e) { return getFailureResultsMap(e); } }
java
@Action(name = "Extract text from image", description = EXTRACT_TEXT_FROM_IMAGE_DESC, outputs = { @Output(value = RETURN_CODE, description = RETURN_CODE_DESC), @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC), @Output(value = TEXT_STRING, description = TEXT_STRING_DESC), @Output(value = TEXT_JSON, description = TEXT_JSON_DESC), @Output(value = EXCEPTION, description = EXCEPTION_DESC), }, responses = { @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL, responseType = RESOLVED, description = SUCCESS_DESC), @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL, responseType = ERROR, isOnFail = true, description = FAILURE_DESC) }) public Map<String, String> execute( @Param(value = FILE_PATH, required = true, description = FILE_PATH_DESC) String filePath, @Param(value = DATA_PATH, required = true, description = DATA_PATH_DESC) String dataPath, @Param(value = LANGUAGE, required = true, description = LANGUAGE_DESC) String language, @Param(value = TEXT_BLOCKS, description = TEXT_BLOCKS_DESC) String textBlocks, @Param(value = DESKEW, description = DESKEW_DESC) String deskew) { dataPath = defaultIfEmpty(dataPath, EMPTY); language = defaultIfEmpty(language, ENG); textBlocks = defaultIfEmpty(textBlocks, FALSE); deskew = defaultIfEmpty(deskew, FALSE); final List<String> exceptionMessages = verifyExtractTextInputs(filePath, dataPath, textBlocks, deskew); if (!exceptionMessages.isEmpty()) { return getFailureResultsMap(StringUtilities.join(exceptionMessages, NEW_LINE)); } try { final String resultText = extractTextFromImage(filePath, dataPath, language, textBlocks, deskew); final Map<String, String> result = getSuccessResultsMap(resultText); if (Boolean.parseBoolean(textBlocks)) { result.put(TEXT_JSON, resultText); } else { result.put(TEXT_STRING, resultText); } return result; } catch (Exception e) { return getFailureResultsMap(e); } }
[ "@", "Action", "(", "name", "=", "\"Extract text from image\"", ",", "description", "=", "EXTRACT_TEXT_FROM_IMAGE_DESC", ",", "outputs", "=", "{", "@", "Output", "(", "value", "=", "RETURN_CODE", ",", "description", "=", "RETURN_CODE_DESC", ")", ",", "@", "Outpu...
This operation extracts the text from a specified file given as input using Tesseract's OCR library. @param filePath The path of the file to be extracted. The file must be an image. Most of the common image formats are supported. Required @param dataPath The path to the tessdata folder that contains the tesseract config files. @param language The language that will be used by the OCR engine. This input is taken into consideration only when specifying the dataPath input as well. Default value: 'ENG' @param textBlocks If set to 'true' operation will return a json containing text blocks extracted from image. Valid values: false, true Default value: false Optional @param deskew Improve text recognition if an image does not have a normal text orientation(skewed image). If set to 'true' the image will be rotated to the correct text orientation. Valid values: false, true Default value: false Optional @return a map containing the output of the operation. Keys present in the map are: returnResult - This will contain the extracted text. exception - In case of success response, this result is empty. In case of failure response, this result contains the java stack trace of the runtime exception. textString - The extracted text from image. textJson - A json containing extracted blocks of text from image. returnCode - The returnCode of the operation: 0 for success, -1 for failure.
[ "This", "operation", "extracts", "the", "text", "from", "a", "specified", "file", "given", "as", "input", "using", "Tesseract", "s", "OCR", "library", "." ]
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-tesseract/src/main/java/io/cloudslang/content/tesseract/actions/ExtractTextFromImage.java#L81-L124
apache/spark
launcher/src/main/java/org/apache/spark/launcher/AbstractCommandBuilder.java
AbstractCommandBuilder.buildJavaCommand
List<String> buildJavaCommand(String extraClassPath) throws IOException { List<String> cmd = new ArrayList<>(); String[] candidateJavaHomes = new String[] { javaHome, childEnv.get("JAVA_HOME"), System.getenv("JAVA_HOME"), System.getProperty("java.home") }; for (String javaHome : candidateJavaHomes) { if (javaHome != null) { cmd.add(join(File.separator, javaHome, "bin", "java")); break; } } // Load extra JAVA_OPTS from conf/java-opts, if it exists. File javaOpts = new File(join(File.separator, getConfDir(), "java-opts")); if (javaOpts.isFile()) { try (BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(javaOpts), StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { addOptionString(cmd, line); } } } cmd.add("-cp"); cmd.add(join(File.pathSeparator, buildClassPath(extraClassPath))); return cmd; }
java
List<String> buildJavaCommand(String extraClassPath) throws IOException { List<String> cmd = new ArrayList<>(); String[] candidateJavaHomes = new String[] { javaHome, childEnv.get("JAVA_HOME"), System.getenv("JAVA_HOME"), System.getProperty("java.home") }; for (String javaHome : candidateJavaHomes) { if (javaHome != null) { cmd.add(join(File.separator, javaHome, "bin", "java")); break; } } // Load extra JAVA_OPTS from conf/java-opts, if it exists. File javaOpts = new File(join(File.separator, getConfDir(), "java-opts")); if (javaOpts.isFile()) { try (BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(javaOpts), StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { addOptionString(cmd, line); } } } cmd.add("-cp"); cmd.add(join(File.pathSeparator, buildClassPath(extraClassPath))); return cmd; }
[ "List", "<", "String", ">", "buildJavaCommand", "(", "String", "extraClassPath", ")", "throws", "IOException", "{", "List", "<", "String", ">", "cmd", "=", "new", "ArrayList", "<>", "(", ")", ";", "String", "[", "]", "candidateJavaHomes", "=", "new", "Stri...
Builds a list of arguments to run java. This method finds the java executable to use and appends JVM-specific options for running a class with Spark in the classpath. It also loads options from the "java-opts" file in the configuration directory being used. Callers should still add at least the class to run, as well as any arguments to pass to the class.
[ "Builds", "a", "list", "of", "arguments", "to", "run", "java", "." ]
train
https://github.com/apache/spark/blob/25ee0474f47d9c30d6f553a7892d9549f91071cf/launcher/src/main/java/org/apache/spark/launcher/AbstractCommandBuilder.java#L92-L123
Javacord/Javacord
javacord-core/src/main/java/org/javacord/core/util/FileContainer.java
FileContainer.setFileTypeOrName
public void setFileTypeOrName(String type) { fileTypeOrName = type; if ((fileAsBufferedImage != null) && !ImageIO.getImageWritersByFormatName(getFileType()).hasNext()) { throw new IllegalArgumentException(String.format("No image writer found for format \"%s\"", getFileType())); } }
java
public void setFileTypeOrName(String type) { fileTypeOrName = type; if ((fileAsBufferedImage != null) && !ImageIO.getImageWritersByFormatName(getFileType()).hasNext()) { throw new IllegalArgumentException(String.format("No image writer found for format \"%s\"", getFileType())); } }
[ "public", "void", "setFileTypeOrName", "(", "String", "type", ")", "{", "fileTypeOrName", "=", "type", ";", "if", "(", "(", "fileAsBufferedImage", "!=", "null", ")", "&&", "!", "ImageIO", ".", "getImageWritersByFormatName", "(", "getFileType", "(", ")", ")", ...
Sets the type ("png", "txt", ...) or name ("image.png", "readme.txt", ...) of the file. @param type The type or name of the file.
[ "Sets", "the", "type", "(", "png", "txt", "...", ")", "or", "name", "(", "image", ".", "png", "readme", ".", "txt", "...", ")", "of", "the", "file", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/util/FileContainer.java#L197-L202
alkacon/opencms-core
src/org/opencms/importexport/CmsExport.java
CmsExport.digestElement
protected void digestElement(Element parent, Element output) throws SAXException { m_saxWriter.write(output); parent.remove(output); }
java
protected void digestElement(Element parent, Element output) throws SAXException { m_saxWriter.write(output); parent.remove(output); }
[ "protected", "void", "digestElement", "(", "Element", "parent", ",", "Element", "output", ")", "throws", "SAXException", "{", "m_saxWriter", ".", "write", "(", "output", ")", ";", "parent", ".", "remove", "(", "output", ")", ";", "}" ]
Writes the output element to the XML output writer and detaches it from it's parent element.<p> @param parent the parent element @param output the output element @throws SAXException if something goes wrong processing the manifest.xml
[ "Writes", "the", "output", "element", "to", "the", "XML", "output", "writer", "and", "detaches", "it", "from", "it", "s", "parent", "element", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/importexport/CmsExport.java#L775-L779
beangle/beangle3
orm/hibernate/src/main/java/org/beangle/orm/hibernate/dwr/H4BeanConverter.java
H4BeanConverter.findGetter
protected Method findGetter(Object data, String property) throws IntrospectionException { Class<?> clazz = getClass(data); String key = clazz.getName() + ":" + property; Method method = methods.get(key); if (method == null) { Method newMethod = null; PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (prop.getName().equalsIgnoreCase(property)) { newMethod = prop.getReadMethod(); } } method = methods.putIfAbsent(key, newMethod); if (method == null) { // put succeeded, use new value method = newMethod; } } return method; }
java
protected Method findGetter(Object data, String property) throws IntrospectionException { Class<?> clazz = getClass(data); String key = clazz.getName() + ":" + property; Method method = methods.get(key); if (method == null) { Method newMethod = null; PropertyDescriptor[] props = Introspector.getBeanInfo(clazz).getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (prop.getName().equalsIgnoreCase(property)) { newMethod = prop.getReadMethod(); } } method = methods.putIfAbsent(key, newMethod); if (method == null) { // put succeeded, use new value method = newMethod; } } return method; }
[ "protected", "Method", "findGetter", "(", "Object", "data", ",", "String", "property", ")", "throws", "IntrospectionException", "{", "Class", "<", "?", ">", "clazz", "=", "getClass", "(", "data", ")", ";", "String", "key", "=", "clazz", ".", "getName", "("...
Cache the method if possible, using the classname and property name to allow for similar named methods. @param data The bean to introspect @param property The property to get the accessor for @return The getter method @throws IntrospectionException If Introspector.getBeanInfo() fails
[ "Cache", "the", "method", "if", "possible", "using", "the", "classname", "and", "property", "name", "to", "allow", "for", "similar", "named", "methods", "." ]
train
https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/orm/hibernate/src/main/java/org/beangle/orm/hibernate/dwr/H4BeanConverter.java#L168-L187
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/util/StreamUtil.java
StreamUtil.throwingMerger
public static <T> BinaryOperator<T> throwingMerger() { return (u, v) -> { throw new IllegalArgumentException(String.format("Duplicate key: value %s was already present now %s is added", u, v)); }; }
java
public static <T> BinaryOperator<T> throwingMerger() { return (u, v) -> { throw new IllegalArgumentException(String.format("Duplicate key: value %s was already present now %s is added", u, v)); }; }
[ "public", "static", "<", "T", ">", "BinaryOperator", "<", "T", ">", "throwingMerger", "(", ")", "{", "return", "(", "u", ",", "v", ")", "->", "{", "throw", "new", "IllegalArgumentException", "(", "String", ".", "format", "(", "\"Duplicate key: value %s was a...
Throws is same key is produced. @param <T> type of values. @throws IllegalArgumentException always
[ "Throws", "is", "same", "key", "is", "produced", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/util/StreamUtil.java#L55-L59
alkacon/opencms-core
src/org/opencms/db/CmsDriverManager.java
CmsDriverManager.writeProjectLastModified
public void writeProjectLastModified(CmsDbContext dbc, CmsResource resource, CmsUUID projectId) throws CmsDataAccessException { I_CmsVfsDriver vfsDriver = getVfsDriver(dbc); vfsDriver.writeLastModifiedProjectId(dbc, dbc.currentProject(), projectId, resource); }
java
public void writeProjectLastModified(CmsDbContext dbc, CmsResource resource, CmsUUID projectId) throws CmsDataAccessException { I_CmsVfsDriver vfsDriver = getVfsDriver(dbc); vfsDriver.writeLastModifiedProjectId(dbc, dbc.currentProject(), projectId, resource); }
[ "public", "void", "writeProjectLastModified", "(", "CmsDbContext", "dbc", ",", "CmsResource", "resource", ",", "CmsUUID", "projectId", ")", "throws", "CmsDataAccessException", "{", "I_CmsVfsDriver", "vfsDriver", "=", "getVfsDriver", "(", "dbc", ")", ";", "vfsDriver", ...
Writes a new project into the PROJECT_LASTMODIFIED field of a resource record.<p> @param dbc the current database context @param resource the resource which should be modified @param projectId the project id to write @throws CmsDataAccessException if the database access fails
[ "Writes", "a", "new", "project", "into", "the", "PROJECT_LASTMODIFIED", "field", "of", "a", "resource", "record", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsDriverManager.java#L9961-L9966