repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
204
func_name
stringlengths
5
103
whole_func_string
stringlengths
87
3.44k
language
stringclasses
1 value
func_code_string
stringlengths
87
3.44k
func_code_tokens
listlengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
listlengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
ironjacamar/ironjacamar
codegenerator/src/main/java/org/ironjacamar/codegenerator/code/ConnMetaCodeGen.java
ConnMetaCodeGen.writeClassBody
@Override public void writeClassBody(Definition def, Writer out) throws IOException { out.write("public class " + getClassName(def) + " implements ConnectionMetaData"); writeLeftCurlyBracket(out, 0); int indent = 1; writeDefaultConstructor(def, out, indent); writeEIS(def, out, indent); writeUsername(def, out, indent); writeRightCurlyBracket(out, 0); }
java
@Override public void writeClassBody(Definition def, Writer out) throws IOException { out.write("public class " + getClassName(def) + " implements ConnectionMetaData"); writeLeftCurlyBracket(out, 0); int indent = 1; writeDefaultConstructor(def, out, indent); writeEIS(def, out, indent); writeUsername(def, out, indent); writeRightCurlyBracket(out, 0); }
[ "@", "Override", "public", "void", "writeClassBody", "(", "Definition", "def", ",", "Writer", "out", ")", "throws", "IOException", "{", "out", ".", "write", "(", "\"public class \"", "+", "getClassName", "(", "def", ")", "+", "\" implements ConnectionMetaData\"", ...
Output Metadata class @param def definition @param out Writer @throws IOException ioException
[ "Output", "Metadata", "class" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/codegenerator/src/main/java/org/ironjacamar/codegenerator/code/ConnMetaCodeGen.java#L43-L57
cybazeitalia/emaze-dysfunctional
src/main/java/net/emaze/dysfunctional/Spies.java
Spies.spyRes
public static <T1, T2, T3> TriPredicate<T1, T2, T3> spyRes(TriPredicate<T1, T2, T3> predicate, Box<Boolean> result) { return spy(predicate, result, Box.<T1>empty(), Box.<T2>empty(), Box.<T3>empty()); }
java
public static <T1, T2, T3> TriPredicate<T1, T2, T3> spyRes(TriPredicate<T1, T2, T3> predicate, Box<Boolean> result) { return spy(predicate, result, Box.<T1>empty(), Box.<T2>empty(), Box.<T3>empty()); }
[ "public", "static", "<", "T1", ",", "T2", ",", "T3", ">", "TriPredicate", "<", "T1", ",", "T2", ",", "T3", ">", "spyRes", "(", "TriPredicate", "<", "T1", ",", "T2", ",", "T3", ">", "predicate", ",", "Box", "<", "Boolean", ">", "result", ")", "{",...
Proxies a ternary predicate spying for result. @param <T1> the predicate first parameter type @param <T2> the predicate second parameter type @param <T3> the predicate third parameter type @param predicate the predicate that will be spied @param result a box that will be containing spied result @return the proxied predicate
[ "Proxies", "a", "ternary", "predicate", "spying", "for", "result", "." ]
train
https://github.com/cybazeitalia/emaze-dysfunctional/blob/98115a436e35335c5e8831f9fdc12f6d93d524be/src/main/java/net/emaze/dysfunctional/Spies.java#L401-L403
mfornos/humanize
humanize-icu/src/main/java/humanize/ICUHumanize.java
ICUHumanize.formatPluralCurrency
public static String formatPluralCurrency(final Number value) { DecimalFormat decf = context.get().getPluralCurrencyFormat(); return stripZeros(decf, decf.format(value)); }
java
public static String formatPluralCurrency(final Number value) { DecimalFormat decf = context.get().getPluralCurrencyFormat(); return stripZeros(decf, decf.format(value)); }
[ "public", "static", "String", "formatPluralCurrency", "(", "final", "Number", "value", ")", "{", "DecimalFormat", "decf", "=", "context", ".", "get", "(", ")", ".", "getPluralCurrencyFormat", "(", ")", ";", "return", "stripZeros", "(", "decf", ",", "decf", "...
<p> Formats a monetary amount with currency plural names, for example, "US dollar" or "US dollars" for America. </p> @param value Number to be formatted @return String representing the monetary amount
[ "<p", ">", "Formats", "a", "monetary", "amount", "with", "currency", "plural", "names", "for", "example", "US", "dollar", "or", "US", "dollars", "for", "America", ".", "<", "/", "p", ">" ]
train
https://github.com/mfornos/humanize/blob/59fc103045de9d217c9e77dbcb7621f992f46c63/humanize-icu/src/main/java/humanize/ICUHumanize.java#L965-L969
apache/incubator-druid
extensions-core/druid-bloom-filter/src/main/java/org/apache/druid/query/filter/BloomKFilter.java
BloomKFilter.getNumSetBits
public static int getNumSetBits(ByteBuffer bfBuffer, int start) { ByteBuffer view = bfBuffer.duplicate().order(ByteOrder.BIG_ENDIAN); view.position(start); int numLongs = view.getInt(1 + start); int setBits = 0; for (int i = 0, pos = START_OF_SERIALIZED_LONGS + start; i < numLongs; i++, pos += Long.BYTES) { setBits += Long.bitCount(view.getLong(pos)); } return setBits; }
java
public static int getNumSetBits(ByteBuffer bfBuffer, int start) { ByteBuffer view = bfBuffer.duplicate().order(ByteOrder.BIG_ENDIAN); view.position(start); int numLongs = view.getInt(1 + start); int setBits = 0; for (int i = 0, pos = START_OF_SERIALIZED_LONGS + start; i < numLongs; i++, pos += Long.BYTES) { setBits += Long.bitCount(view.getLong(pos)); } return setBits; }
[ "public", "static", "int", "getNumSetBits", "(", "ByteBuffer", "bfBuffer", ",", "int", "start", ")", "{", "ByteBuffer", "view", "=", "bfBuffer", ".", "duplicate", "(", ")", ".", "order", "(", "ByteOrder", ".", "BIG_ENDIAN", ")", ";", "view", ".", "position...
ByteBuffer based copy of logic of {@link BloomKFilter#getNumSetBits()} @param bfBuffer @param start @return
[ "ByteBuffer", "based", "copy", "of", "logic", "of", "{" ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/extensions-core/druid-bloom-filter/src/main/java/org/apache/druid/query/filter/BloomKFilter.java#L336-L346
umano/AndroidSlidingUpPanel
library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java
ViewDragHelper.forceSettleCapturedViewAt
private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) { final int startLeft = mCapturedView.getLeft(); final int startTop = mCapturedView.getTop(); final int dx = finalLeft - startLeft; final int dy = finalTop - startTop; if (dx == 0 && dy == 0) { // Nothing to do. Send callbacks, be done. mScroller.abortAnimation(); setDragState(STATE_IDLE); return false; } final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel); mScroller.startScroll(startLeft, startTop, dx, dy, duration); setDragState(STATE_SETTLING); return true; }
java
private boolean forceSettleCapturedViewAt(int finalLeft, int finalTop, int xvel, int yvel) { final int startLeft = mCapturedView.getLeft(); final int startTop = mCapturedView.getTop(); final int dx = finalLeft - startLeft; final int dy = finalTop - startTop; if (dx == 0 && dy == 0) { // Nothing to do. Send callbacks, be done. mScroller.abortAnimation(); setDragState(STATE_IDLE); return false; } final int duration = computeSettleDuration(mCapturedView, dx, dy, xvel, yvel); mScroller.startScroll(startLeft, startTop, dx, dy, duration); setDragState(STATE_SETTLING); return true; }
[ "private", "boolean", "forceSettleCapturedViewAt", "(", "int", "finalLeft", ",", "int", "finalTop", ",", "int", "xvel", ",", "int", "yvel", ")", "{", "final", "int", "startLeft", "=", "mCapturedView", ".", "getLeft", "(", ")", ";", "final", "int", "startTop"...
Settle the captured view at the given (left, top) position. @param finalLeft Target left position for the captured view @param finalTop Target top position for the captured view @param xvel Horizontal velocity @param yvel Vertical velocity @return true if animation should continue through {@link #continueSettling(boolean)} calls
[ "Settle", "the", "captured", "view", "at", "the", "given", "(", "left", "top", ")", "position", "." ]
train
https://github.com/umano/AndroidSlidingUpPanel/blob/45a460435b07e764138a700328836cafc1ed5c42/library/src/main/java/com/sothree/slidinguppanel/ViewDragHelper.java#L607-L625
lucee/Lucee
core/src/main/java/lucee/runtime/config/XMLConfigServerFactory.java
XMLConfigServerFactory.newInstance
public static ConfigServerImpl newInstance(CFMLEngineImpl engine, Map<String, CFMLFactory> initContextes, Map<String, CFMLFactory> contextes, Resource configDir) throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, BundleException { boolean isCLI = SystemUtil.isCLICall(); if (isCLI) { Resource logs = configDir.getRealResource("logs"); logs.mkdirs(); Resource out = logs.getRealResource("out"); Resource err = logs.getRealResource("err"); ResourceUtil.touch(out); ResourceUtil.touch(err); if (logs instanceof FileResource) { SystemUtil.setPrintWriter(SystemUtil.OUT, new PrintWriter((FileResource) out)); SystemUtil.setPrintWriter(SystemUtil.ERR, new PrintWriter((FileResource) err)); } else { SystemUtil.setPrintWriter(SystemUtil.OUT, new PrintWriter(IOUtil.getWriter(out, "UTF-8"))); SystemUtil.setPrintWriter(SystemUtil.ERR, new PrintWriter(IOUtil.getWriter(err, "UTF-8"))); } } SystemOut.print(SystemUtil.getPrintWriter(SystemUtil.OUT), "===================================================================\n" + "SERVER CONTEXT\n" + "-------------------------------------------------------------------\n" + "- config:" + configDir + "\n" + "- loader-version:" + SystemUtil.getLoaderVersion() + "\n" + "- core-version:" + engine.getInfo().getVersion() + "\n" + "===================================================================\n" ); int iDoNew = doNew(engine, configDir, false).updateType; boolean doNew = iDoNew != NEW_NONE; Resource configFile = configDir.getRealResource("lucee-server.xml"); if (!configFile.exists()) { configFile.createFile(true); // InputStream in = new TextFile("").getClass().getResourceAsStream("/resource/config/server.xml"); createFileFromResource("/resource/config/server.xml", configFile.getAbsoluteResource(), "tpiasfap"); } Document doc = loadDocumentCreateIfFails(configFile, "server"); // get version Element luceeConfiguration = doc.getDocumentElement(); String strVersion = luceeConfiguration.getAttribute("version"); double version = Caster.toDoubleValue(strVersion, 1.0d); boolean cleanupDatasources = version < 5.0D; ConfigServerImpl config = new ConfigServerImpl(engine, initContextes, contextes, configDir, configFile); load(config, doc, false, doNew); createContextFiles(configDir, config, doNew, cleanupDatasources); ((CFMLEngineImpl) ConfigWebUtil.getEngine(config)).onStart(config, false); return config; }
java
public static ConfigServerImpl newInstance(CFMLEngineImpl engine, Map<String, CFMLFactory> initContextes, Map<String, CFMLFactory> contextes, Resource configDir) throws SAXException, ClassException, PageException, IOException, TagLibException, FunctionLibException, BundleException { boolean isCLI = SystemUtil.isCLICall(); if (isCLI) { Resource logs = configDir.getRealResource("logs"); logs.mkdirs(); Resource out = logs.getRealResource("out"); Resource err = logs.getRealResource("err"); ResourceUtil.touch(out); ResourceUtil.touch(err); if (logs instanceof FileResource) { SystemUtil.setPrintWriter(SystemUtil.OUT, new PrintWriter((FileResource) out)); SystemUtil.setPrintWriter(SystemUtil.ERR, new PrintWriter((FileResource) err)); } else { SystemUtil.setPrintWriter(SystemUtil.OUT, new PrintWriter(IOUtil.getWriter(out, "UTF-8"))); SystemUtil.setPrintWriter(SystemUtil.ERR, new PrintWriter(IOUtil.getWriter(err, "UTF-8"))); } } SystemOut.print(SystemUtil.getPrintWriter(SystemUtil.OUT), "===================================================================\n" + "SERVER CONTEXT\n" + "-------------------------------------------------------------------\n" + "- config:" + configDir + "\n" + "- loader-version:" + SystemUtil.getLoaderVersion() + "\n" + "- core-version:" + engine.getInfo().getVersion() + "\n" + "===================================================================\n" ); int iDoNew = doNew(engine, configDir, false).updateType; boolean doNew = iDoNew != NEW_NONE; Resource configFile = configDir.getRealResource("lucee-server.xml"); if (!configFile.exists()) { configFile.createFile(true); // InputStream in = new TextFile("").getClass().getResourceAsStream("/resource/config/server.xml"); createFileFromResource("/resource/config/server.xml", configFile.getAbsoluteResource(), "tpiasfap"); } Document doc = loadDocumentCreateIfFails(configFile, "server"); // get version Element luceeConfiguration = doc.getDocumentElement(); String strVersion = luceeConfiguration.getAttribute("version"); double version = Caster.toDoubleValue(strVersion, 1.0d); boolean cleanupDatasources = version < 5.0D; ConfigServerImpl config = new ConfigServerImpl(engine, initContextes, contextes, configDir, configFile); load(config, doc, false, doNew); createContextFiles(configDir, config, doNew, cleanupDatasources); ((CFMLEngineImpl) ConfigWebUtil.getEngine(config)).onStart(config, false); return config; }
[ "public", "static", "ConfigServerImpl", "newInstance", "(", "CFMLEngineImpl", "engine", ",", "Map", "<", "String", ",", "CFMLFactory", ">", "initContextes", ",", "Map", "<", "String", ",", "CFMLFactory", ">", "contextes", ",", "Resource", "configDir", ")", "thro...
creates a new ServletConfig Impl Object @param engine @param initContextes @param contextes @param configDir @return new Instance @throws SAXException @throws ClassNotFoundException @throws PageException @throws IOException @throws TagLibException @throws FunctionLibException @throws BundleException
[ "creates", "a", "new", "ServletConfig", "Impl", "Object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/XMLConfigServerFactory.java#L69-L121
BBN-E/bue-common-open
common-core-open/src/main/java/com/bbn/bue/common/primitives/DoubleUtils.java
DoubleUtils.clipRecklessly
public static double clipRecklessly(double val, double bounds) { if (val > bounds) { return bounds; } else if (val < -bounds) { return -bounds; } else { return val; } }
java
public static double clipRecklessly(double val, double bounds) { if (val > bounds) { return bounds; } else if (val < -bounds) { return -bounds; } else { return val; } }
[ "public", "static", "double", "clipRecklessly", "(", "double", "val", ",", "double", "bounds", ")", "{", "if", "(", "val", ">", "bounds", ")", "{", "return", "bounds", ";", "}", "else", "if", "(", "val", "<", "-", "bounds", ")", "{", "return", "-", ...
Clips the given value within the given bounds. If {@code -bounds <= val <= bounds}, {@code val} is returned unchanged. Otherwise, {@code -bounds} is returned if {@code val<bounds} and {@code bounds} is returned if {@code val>bounds}. {@code bounds} must be non-negative, but this is not enforced, so prefer using {@link #clip(double, double)} except in inner-loops. {@code NaN} values will be left unchanged, but positive and negative infinity will be clipped.
[ "Clips", "the", "given", "value", "within", "the", "given", "bounds", ".", "If", "{", "@code", "-", "bounds", "<", "=", "val", "<", "=", "bounds", "}", "{", "@code", "val", "}", "is", "returned", "unchanged", ".", "Otherwise", "{", "@code", "-", "bou...
train
https://github.com/BBN-E/bue-common-open/blob/d618652674d647867306e2e4b987a21b7c29c015/common-core-open/src/main/java/com/bbn/bue/common/primitives/DoubleUtils.java#L300-L308
datumbox/datumbox-framework
datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java
ContinuousDistributions.studentsCdf
public static double studentsCdf(double x, int df) { if(df<=0) { throw new IllegalArgumentException("The degrees of freedom need to be positive."); } double A = df/2.0; double S = A+0.5; double Z = df/(df + x*x); double BT = Math.exp(logGamma(S)-logGamma(0.5)-logGamma(A)+A*Math.log(Z)+0.5*Math.log(1.0-Z)); double betacdf; if (Z<(A+1.0)/(S+2.0)) { betacdf = BT*betinc(Z,A,0.5); } else { betacdf=1-BT*betinc(1.0-Z,0.5,A); } double tcdf; if (x<0) { tcdf=betacdf/2.0; } else { tcdf=1.0-betacdf/2.0; } return tcdf; }
java
public static double studentsCdf(double x, int df) { if(df<=0) { throw new IllegalArgumentException("The degrees of freedom need to be positive."); } double A = df/2.0; double S = A+0.5; double Z = df/(df + x*x); double BT = Math.exp(logGamma(S)-logGamma(0.5)-logGamma(A)+A*Math.log(Z)+0.5*Math.log(1.0-Z)); double betacdf; if (Z<(A+1.0)/(S+2.0)) { betacdf = BT*betinc(Z,A,0.5); } else { betacdf=1-BT*betinc(1.0-Z,0.5,A); } double tcdf; if (x<0) { tcdf=betacdf/2.0; } else { tcdf=1.0-betacdf/2.0; } return tcdf; }
[ "public", "static", "double", "studentsCdf", "(", "double", "x", ",", "int", "df", ")", "{", "if", "(", "df", "<=", "0", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The degrees of freedom need to be positive.\"", ")", ";", "}", "double", "A",...
Calculates the probability from -INF to X under Student's Distribution Ported to PHP from Javascript implementation found at http://www.math.ucla.edu/~tom/distributions/tDist.html @param x @param df @return
[ "Calculates", "the", "probability", "from", "-", "INF", "to", "X", "under", "Student", "s", "Distribution", "Ported", "to", "PHP", "from", "Javascript", "implementation", "found", "at", "http", ":", "//", "www", ".", "math", ".", "ucla", ".", "edu", "/", ...
train
https://github.com/datumbox/datumbox-framework/blob/909dff0476e80834f05ecdde0624dd2390e9b0ca/datumbox-framework-core/src/main/java/com/datumbox/framework/core/statistics/distributions/ContinuousDistributions.java#L160-L186
looly/hutool
hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java
SecureUtil.generatePrivateKey
public static PrivateKey generatePrivateKey(KeyStore keyStore, String alias, char[] password) { return KeyUtil.generatePrivateKey(keyStore, alias, password); }
java
public static PrivateKey generatePrivateKey(KeyStore keyStore, String alias, char[] password) { return KeyUtil.generatePrivateKey(keyStore, alias, password); }
[ "public", "static", "PrivateKey", "generatePrivateKey", "(", "KeyStore", "keyStore", ",", "String", "alias", ",", "char", "[", "]", "password", ")", "{", "return", "KeyUtil", ".", "generatePrivateKey", "(", "keyStore", ",", "alias", ",", "password", ")", ";", ...
生成私钥,仅用于非对称加密 @param keyStore {@link KeyStore} @param alias 别名 @param password 密码 @return 私钥 {@link PrivateKey}
[ "生成私钥,仅用于非对称加密" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-crypto/src/main/java/cn/hutool/crypto/SecureUtil.java#L166-L168
paylogic/java-fogbugz
src/main/java/org/paylogic/fogbugz/FogbugzManager.java
FogbugzManager.getCaseById
public FogbugzCase getCaseById(int id) throws InvalidResponseException, NoSuchCaseException { List<FogbugzCase> caseList = this.searchForCases(Integer.toString(id)); if (caseList.size() > 1) { throw new InvalidResponseException("Expected one case, found multiple, aborting."); } return caseList.get(0); }
java
public FogbugzCase getCaseById(int id) throws InvalidResponseException, NoSuchCaseException { List<FogbugzCase> caseList = this.searchForCases(Integer.toString(id)); if (caseList.size() > 1) { throw new InvalidResponseException("Expected one case, found multiple, aborting."); } return caseList.get(0); }
[ "public", "FogbugzCase", "getCaseById", "(", "int", "id", ")", "throws", "InvalidResponseException", ",", "NoSuchCaseException", "{", "List", "<", "FogbugzCase", ">", "caseList", "=", "this", ".", "searchForCases", "(", "Integer", ".", "toString", "(", "id", ")"...
Retrieves a case using the Fogbugz API by caseId. @param id the id of the case to fetch. @return FogbugzCase if all is well, else null.
[ "Retrieves", "a", "case", "using", "the", "Fogbugz", "API", "by", "caseId", "." ]
train
https://github.com/paylogic/java-fogbugz/blob/75651d82b2476e9ba2a0805311e18ee36882c2df/src/main/java/org/paylogic/fogbugz/FogbugzManager.java#L121-L127
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/KunderaMetadataManager.java
KunderaMetadataManager.getMetamodel
public static MetamodelImpl getMetamodel(final KunderaMetadata kunderaMetadata, String persistenceUnit) { MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(persistenceUnit); return metamodel; }
java
public static MetamodelImpl getMetamodel(final KunderaMetadata kunderaMetadata, String persistenceUnit) { MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata() .getMetamodel(persistenceUnit); return metamodel; }
[ "public", "static", "MetamodelImpl", "getMetamodel", "(", "final", "KunderaMetadata", "kunderaMetadata", ",", "String", "persistenceUnit", ")", "{", "MetamodelImpl", "metamodel", "=", "(", "MetamodelImpl", ")", "kunderaMetadata", ".", "getApplicationMetadata", "(", ")",...
Gets the metamodel. @param persistenceUnit the persistence unit @return the metamodel
[ "Gets", "the", "metamodel", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/metadata/KunderaMetadataManager.java#L64-L70
JDBDT/jdbdt
src/main/java/org/jdbdt/DBSetup.java
DBSetup.doDeleteAll
private static int doDeleteAll(CallInfo callInfo, Table table) { DB db = table.getDB(); return db.access(callInfo, () -> { String sql = DELETE_FROM_ + table.getName(); db.logSetup(callInfo, sql); try (WrappedStatement ws = db.compile(sql)) { return ws.getStatement().executeUpdate(); } }); }
java
private static int doDeleteAll(CallInfo callInfo, Table table) { DB db = table.getDB(); return db.access(callInfo, () -> { String sql = DELETE_FROM_ + table.getName(); db.logSetup(callInfo, sql); try (WrappedStatement ws = db.compile(sql)) { return ws.getStatement().executeUpdate(); } }); }
[ "private", "static", "int", "doDeleteAll", "(", "CallInfo", "callInfo", ",", "Table", "table", ")", "{", "DB", "db", "=", "table", ".", "getDB", "(", ")", ";", "return", "db", ".", "access", "(", "callInfo", ",", "(", ")", "->", "{", "String", "sql",...
Perform a "delete-all" operation. @param callInfo Call info. @param table Table. @return Number of deleted rows.
[ "Perform", "a", "delete", "-", "all", "operation", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/DBSetup.java#L304-L313
upwork/java-upwork
src/com/Upwork/api/Routers/Hr/Contracts.java
Contracts.suspendContract
public JSONObject suspendContract(String reference, HashMap<String, String> params) throws JSONException { return oClient.put("/hr/v2/contracts/" + reference + "/suspend", params); }
java
public JSONObject suspendContract(String reference, HashMap<String, String> params) throws JSONException { return oClient.put("/hr/v2/contracts/" + reference + "/suspend", params); }
[ "public", "JSONObject", "suspendContract", "(", "String", "reference", ",", "HashMap", "<", "String", ",", "String", ">", "params", ")", "throws", "JSONException", "{", "return", "oClient", ".", "put", "(", "\"/hr/v2/contracts/\"", "+", "reference", "+", "\"/sus...
Suspend Contract @param reference Contract reference @param params Parameters @throws JSONException If error occurred @return {@link JSONObject}
[ "Suspend", "Contract" ]
train
https://github.com/upwork/java-upwork/blob/342297161503a74e9e0bddbd381ab5eebf4dc454/src/com/Upwork/api/Routers/Hr/Contracts.java#L54-L56
wcm-io/wcm-io-wcm
parsys/src/main/java/io/wcm/wcm/parsys/componentinfo/impl/AllowedComponentsProviderImpl.java
AllowedComponentsProviderImpl.getAllowedComponents
@Override public @NotNull Set<String> getAllowedComponents(@NotNull String resourcePath, @NotNull ResourceResolver resolver) { PageManager pageManager = AdaptTo.notNull(resolver, PageManager.class); Page page = pageManager.getContainingPage(resourcePath); if (page == null && StringUtils.contains(resourcePath, "/" + JcrConstants.JCR_CONTENT)) { // if resource does not exist (e.g. inherited parsys) get page from resource path manually page = pageManager.getPage(StringUtils.substringBefore(resourcePath, "/" + JcrConstants.JCR_CONTENT)); } if (page == null) { return ImmutableSet.of(); } String relativePath = StringUtils.substringAfter(resourcePath, page.getPath() + "/"); return getAllowedComponents(page, relativePath, null, resolver); }
java
@Override public @NotNull Set<String> getAllowedComponents(@NotNull String resourcePath, @NotNull ResourceResolver resolver) { PageManager pageManager = AdaptTo.notNull(resolver, PageManager.class); Page page = pageManager.getContainingPage(resourcePath); if (page == null && StringUtils.contains(resourcePath, "/" + JcrConstants.JCR_CONTENT)) { // if resource does not exist (e.g. inherited parsys) get page from resource path manually page = pageManager.getPage(StringUtils.substringBefore(resourcePath, "/" + JcrConstants.JCR_CONTENT)); } if (page == null) { return ImmutableSet.of(); } String relativePath = StringUtils.substringAfter(resourcePath, page.getPath() + "/"); return getAllowedComponents(page, relativePath, null, resolver); }
[ "@", "Override", "public", "@", "NotNull", "Set", "<", "String", ">", "getAllowedComponents", "(", "@", "NotNull", "String", "resourcePath", ",", "@", "NotNull", "ResourceResolver", "resolver", ")", "{", "PageManager", "pageManager", "=", "AdaptTo", ".", "notNul...
Get allowed components for given resource path @param resourcePath Resource path inside content page @return Set of component paths (absolute resource types)
[ "Get", "allowed", "components", "for", "given", "resource", "path" ]
train
https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/parsys/src/main/java/io/wcm/wcm/parsys/componentinfo/impl/AllowedComponentsProviderImpl.java#L59-L72
alkacon/opencms-core
src/org/opencms/db/CmsSecurityManager.java
CmsSecurityManager.restoreResource
public void restoreResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.restoreResource(dbc, resource, version); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_RESTORE_RESOURCE_2, context.getSitePath(resource), new Integer(version)), e); } finally { dbc.clear(); } }
java
public void restoreResource(CmsRequestContext context, CmsResource resource, int version) throws CmsException, CmsSecurityException { CmsDbContext dbc = m_dbContextFactory.getDbContext(context); try { checkOfflineProject(dbc); checkPermissions(dbc, resource, CmsPermissionSet.ACCESS_WRITE, true, CmsResourceFilter.ALL); m_driverManager.restoreResource(dbc, resource, version); } catch (Exception e) { dbc.report( null, Messages.get().container( Messages.ERR_RESTORE_RESOURCE_2, context.getSitePath(resource), new Integer(version)), e); } finally { dbc.clear(); } }
[ "public", "void", "restoreResource", "(", "CmsRequestContext", "context", ",", "CmsResource", "resource", ",", "int", "version", ")", "throws", "CmsException", ",", "CmsSecurityException", "{", "CmsDbContext", "dbc", "=", "m_dbContextFactory", ".", "getDbContext", "("...
Restores a resource in the current project with the given version from the historical archive.<p> @param context the current request context @param resource the resource to restore from the archive @param version the version number to restore @throws CmsException if something goes wrong @throws CmsSecurityException if the user has insufficient permission for the given resource (write access permission is required) @see CmsObject#restoreResourceVersion(CmsUUID, int) @see org.opencms.file.types.I_CmsResourceType#restoreResource(CmsObject, CmsSecurityManager, CmsResource, int)
[ "Restores", "a", "resource", "in", "the", "current", "project", "with", "the", "given", "version", "from", "the", "historical", "archive", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSecurityManager.java#L5840-L5859
lets-blade/blade
src/main/java/com/blade/kit/EncryptKit.java
EncryptKit.hmacTemplate
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
java
private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
[ "private", "static", "byte", "[", "]", "hmacTemplate", "(", "byte", "[", "]", "data", ",", "byte", "[", "]", "key", ",", "String", "algorithm", ")", "{", "if", "(", "data", "==", "null", "||", "data", ".", "length", "==", "0", "||", "key", "==", ...
Hmac加密模板 @param data 数据 @param key 秘钥 @param algorithm 加密算法 @return 密文字节数组
[ "Hmac加密模板" ]
train
https://github.com/lets-blade/blade/blob/60624ee528be12122c49a9ad1713e336b959e59a/src/main/java/com/blade/kit/EncryptKit.java#L427-L438
Sciss/abc4j
abc/src/main/java/abc/ui/swing/ScoreTemplate.java
ScoreTemplate.getTextFont
public Font getTextFont(byte field) { FieldInfos fi = getFieldInfos(field); Vector v = new Vector(m_defaultTextFontFamilyNames.length+fi.m_fontFamilyNames.length); Collections.addAll(v, fi.m_fontFamilyNames); Collections.addAll(v, m_defaultTextFontFamilyNames); Iterator it = v.iterator(); Font font = null; String s = ""; int style = getTextStyle(field); int size = (int) getTextSize(field); while (it.hasNext()) { String fontName = (String) it.next(); if (s.length() > 0) s += ", "; s += fontName; if (isFontAvailable(fontName)) { font = new Font(fontName, style, size); break; } } if (font == null) { System.err.println("None of these fonts are available: " + s); font = new Font("Dialog", style, size); } if (fi.m_textAttributes != null) { font = font.deriveFont(fi.m_textAttributes); } return font; }
java
public Font getTextFont(byte field) { FieldInfos fi = getFieldInfos(field); Vector v = new Vector(m_defaultTextFontFamilyNames.length+fi.m_fontFamilyNames.length); Collections.addAll(v, fi.m_fontFamilyNames); Collections.addAll(v, m_defaultTextFontFamilyNames); Iterator it = v.iterator(); Font font = null; String s = ""; int style = getTextStyle(field); int size = (int) getTextSize(field); while (it.hasNext()) { String fontName = (String) it.next(); if (s.length() > 0) s += ", "; s += fontName; if (isFontAvailable(fontName)) { font = new Font(fontName, style, size); break; } } if (font == null) { System.err.println("None of these fonts are available: " + s); font = new Font("Dialog", style, size); } if (fi.m_textAttributes != null) { font = font.deriveFont(fi.m_textAttributes); } return font; }
[ "public", "Font", "getTextFont", "(", "byte", "field", ")", "{", "FieldInfos", "fi", "=", "getFieldInfos", "(", "field", ")", ";", "Vector", "v", "=", "new", "Vector", "(", "m_defaultTextFontFamilyNames", ".", "length", "+", "fi", ".", "m_fontFamilyNames", "...
Returns the styled and sized font for a field. @param field one of {@link ScoreElements} constants
[ "Returns", "the", "styled", "and", "sized", "font", "for", "a", "field", "." ]
train
https://github.com/Sciss/abc4j/blob/117b405642c84a7bfca4e3e13668838258b90ca7/abc/src/main/java/abc/ui/swing/ScoreTemplate.java#L574-L602
aws/aws-sdk-java
aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/WeeklyAutoScalingSchedule.java
WeeklyAutoScalingSchedule.withThursday
public WeeklyAutoScalingSchedule withThursday(java.util.Map<String, String> thursday) { setThursday(thursday); return this; }
java
public WeeklyAutoScalingSchedule withThursday(java.util.Map<String, String> thursday) { setThursday(thursday); return this; }
[ "public", "WeeklyAutoScalingSchedule", "withThursday", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "thursday", ")", "{", "setThursday", "(", "thursday", ")", ";", "return", "this", ";", "}" ]
<p> The schedule for Thursday. </p> @param thursday The schedule for Thursday. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "schedule", "for", "Thursday", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-opsworks/src/main/java/com/amazonaws/services/opsworks/model/WeeklyAutoScalingSchedule.java#L329-L332
roboconf/roboconf-platform
core/roboconf-plugin-file/src/main/java/net/roboconf/plugin/file/internal/PluginFile.java
PluginFile.readProperties
Properties readProperties( Instance instance ) throws PluginException { Properties result = null; File instanceDirectory = InstanceHelpers.findInstanceDirectoryOnAgent( instance ); File file = new File( instanceDirectory, FILE_NAME ); try { if( file.exists()) { result = Utils.readPropertiesFile( file ); } else { this.logger.warning( file + " does not exist or is invalid. There is no instruction for the plugin." ); result = new Properties(); } } catch( IOException e ) { throw new PluginException( e ); } return result; }
java
Properties readProperties( Instance instance ) throws PluginException { Properties result = null; File instanceDirectory = InstanceHelpers.findInstanceDirectoryOnAgent( instance ); File file = new File( instanceDirectory, FILE_NAME ); try { if( file.exists()) { result = Utils.readPropertiesFile( file ); } else { this.logger.warning( file + " does not exist or is invalid. There is no instruction for the plugin." ); result = new Properties(); } } catch( IOException e ) { throw new PluginException( e ); } return result; }
[ "Properties", "readProperties", "(", "Instance", "instance", ")", "throws", "PluginException", "{", "Properties", "result", "=", "null", ";", "File", "instanceDirectory", "=", "InstanceHelpers", ".", "findInstanceDirectoryOnAgent", "(", "instance", ")", ";", "File", ...
Reads the "instructions.properties" file. @param instance the instance @return a non-null properties object (potentially empty) @throws PluginException
[ "Reads", "the", "instructions", ".", "properties", "file", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-plugin-file/src/main/java/net/roboconf/plugin/file/internal/PluginFile.java#L139-L159
jferard/fastods
fastods/src/main/java/com/github/jferard/fastods/util/PositionUtil.java
PositionUtil.toCellAddress
public String toCellAddress(final Table table, final int row, final int col) { return this.getPosition(row, col).toCellAddress(table); }
java
public String toCellAddress(final Table table, final int row, final int col) { return this.getPosition(row, col).toCellAddress(table); }
[ "public", "String", "toCellAddress", "(", "final", "Table", "table", ",", "final", "int", "row", ",", "final", "int", "col", ")", "{", "return", "this", ".", "getPosition", "(", "row", ",", "col", ")", ".", "toCellAddress", "(", "table", ")", ";", "}" ...
the Excel/OO/LO address of a cell, preceeded by the table name @param row the row @param col the col @param table the table @return the Excel/OO/LO address
[ "the", "Excel", "/", "OO", "/", "LO", "address", "of", "a", "cell", "preceeded", "by", "the", "table", "name" ]
train
https://github.com/jferard/fastods/blob/a034d173083ffa602dc525699b97f753082eaef9/fastods/src/main/java/com/github/jferard/fastods/util/PositionUtil.java#L247-L249
PeterisP/LVTagger
src/main/java/edu/stanford/nlp/ie/crf/CRFCliqueTree.java
CRFCliqueTree.condLogProbGivenPrevious
public double condLogProbGivenPrevious(int position, int label, int[] prevLabels) { if (prevLabels.length + 1 == windowSize) { return factorTables[position].conditionalLogProbGivenPrevious(prevLabels, label); } else if (prevLabels.length + 1 < windowSize) { FactorTable ft = factorTables[position].sumOutFront(); while (ft.windowSize() > prevLabels.length + 1) { ft = ft.sumOutFront(); } return ft.conditionalLogProbGivenPrevious(prevLabels, label); } else { int[] p = new int[windowSize - 1]; System.arraycopy(prevLabels, prevLabels.length - p.length, p, 0, p.length); return factorTables[position].conditionalLogProbGivenPrevious(p, label); } }
java
public double condLogProbGivenPrevious(int position, int label, int[] prevLabels) { if (prevLabels.length + 1 == windowSize) { return factorTables[position].conditionalLogProbGivenPrevious(prevLabels, label); } else if (prevLabels.length + 1 < windowSize) { FactorTable ft = factorTables[position].sumOutFront(); while (ft.windowSize() > prevLabels.length + 1) { ft = ft.sumOutFront(); } return ft.conditionalLogProbGivenPrevious(prevLabels, label); } else { int[] p = new int[windowSize - 1]; System.arraycopy(prevLabels, prevLabels.length - p.length, p, 0, p.length); return factorTables[position].conditionalLogProbGivenPrevious(p, label); } }
[ "public", "double", "condLogProbGivenPrevious", "(", "int", "position", ",", "int", "label", ",", "int", "[", "]", "prevLabels", ")", "{", "if", "(", "prevLabels", ".", "length", "+", "1", "==", "windowSize", ")", "{", "return", "factorTables", "[", "posit...
Gives the probability of a tag at a single position conditioned on a sequence of previous labels. @param position Index in sequence @param label Label of item at index @param prevLabels @return conditional log probability
[ "Gives", "the", "probability", "of", "a", "tag", "at", "a", "single", "position", "conditioned", "on", "a", "sequence", "of", "previous", "labels", "." ]
train
https://github.com/PeterisP/LVTagger/blob/b3d44bab9ec07ace0d13612c448a6b7298c1f681/src/main/java/edu/stanford/nlp/ie/crf/CRFCliqueTree.java#L396-L410
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java
ComputerVisionImpl.analyzeImageAsync
public Observable<ImageAnalysis> analyzeImageAsync(String url, AnalyzeImageOptionalParameter analyzeImageOptionalParameter) { return analyzeImageWithServiceResponseAsync(url, analyzeImageOptionalParameter).map(new Func1<ServiceResponse<ImageAnalysis>, ImageAnalysis>() { @Override public ImageAnalysis call(ServiceResponse<ImageAnalysis> response) { return response.body(); } }); }
java
public Observable<ImageAnalysis> analyzeImageAsync(String url, AnalyzeImageOptionalParameter analyzeImageOptionalParameter) { return analyzeImageWithServiceResponseAsync(url, analyzeImageOptionalParameter).map(new Func1<ServiceResponse<ImageAnalysis>, ImageAnalysis>() { @Override public ImageAnalysis call(ServiceResponse<ImageAnalysis> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ImageAnalysis", ">", "analyzeImageAsync", "(", "String", "url", ",", "AnalyzeImageOptionalParameter", "analyzeImageOptionalParameter", ")", "{", "return", "analyzeImageWithServiceResponseAsync", "(", "url", ",", "analyzeImageOptionalParameter", "...
This operation extracts a rich set of visual features based on the image content. Two input methods are supported -- (1) Uploading an image or (2) specifying an image URL. Within your request, there is an optional parameter to allow you to choose which features to return. By default, image categories are returned in the response. @param url Publicly reachable URL of an image @param analyzeImageOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ImageAnalysis object
[ "This", "operation", "extracts", "a", "rich", "set", "of", "visual", "features", "based", "on", "the", "image", "content", ".", "Two", "input", "methods", "are", "supported", "--", "(", "1", ")", "Uploading", "an", "image", "or", "(", "2", ")", "specifyi...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L2266-L2273
openengsb/openengsb
components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/PropertyConnectionCalculator.java
PropertyConnectionCalculator.deleteTemporaryProperties
private void deleteTemporaryProperties(Map<String, Set<String>> map) { Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); if (isTemporaryProperty(key)) { LOGGER.debug("Delete temporary field {} from the connection result", key); iterator.remove(); } } }
java
private void deleteTemporaryProperties(Map<String, Set<String>> map) { Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); if (isTemporaryProperty(key)) { LOGGER.debug("Delete temporary field {} from the connection result", key); iterator.remove(); } } }
[ "private", "void", "deleteTemporaryProperties", "(", "Map", "<", "String", ",", "Set", "<", "String", ">", ">", "map", ")", "{", "Iterator", "<", "String", ">", "iterator", "=", "map", ".", "keySet", "(", ")", ".", "iterator", "(", ")", ";", "while", ...
Iterates over the map entries and removes all temporary properties so that a clean map can be returned to the user which is interested in the property connections.
[ "Iterates", "over", "the", "map", "entries", "and", "removes", "all", "temporary", "properties", "so", "that", "a", "clean", "map", "can", "be", "returned", "to", "the", "user", "which", "is", "interested", "in", "the", "property", "connections", "." ]
train
https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/PropertyConnectionCalculator.java#L144-L153
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java
CPDefinitionLinkPersistenceImpl.countByCP_T
@Override public int countByCP_T(long CProductId, String type) { FinderPath finderPath = FINDER_PATH_COUNT_BY_CP_T; Object[] finderArgs = new Object[] { CProductId, type }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_CPDEFINITIONLINK_WHERE); query.append(_FINDER_COLUMN_CP_T_CPRODUCTID_2); boolean bindType = false; if (type == null) { query.append(_FINDER_COLUMN_CP_T_TYPE_1); } else if (type.equals("")) { query.append(_FINDER_COLUMN_CP_T_TYPE_3); } else { bindType = true; query.append(_FINDER_COLUMN_CP_T_TYPE_2); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(CProductId); if (bindType) { qPos.add(type); } count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
java
@Override public int countByCP_T(long CProductId, String type) { FinderPath finderPath = FINDER_PATH_COUNT_BY_CP_T; Object[] finderArgs = new Object[] { CProductId, type }; Long count = (Long)finderCache.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_CPDEFINITIONLINK_WHERE); query.append(_FINDER_COLUMN_CP_T_CPRODUCTID_2); boolean bindType = false; if (type == null) { query.append(_FINDER_COLUMN_CP_T_TYPE_1); } else if (type.equals("")) { query.append(_FINDER_COLUMN_CP_T_TYPE_3); } else { bindType = true; query.append(_FINDER_COLUMN_CP_T_TYPE_2); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(CProductId); if (bindType) { qPos.add(type); } count = (Long)q.uniqueResult(); finderCache.putResult(finderPath, finderArgs, count); } catch (Exception e) { finderCache.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); }
[ "@", "Override", "public", "int", "countByCP_T", "(", "long", "CProductId", ",", "String", "type", ")", "{", "FinderPath", "finderPath", "=", "FINDER_PATH_COUNT_BY_CP_T", ";", "Object", "[", "]", "finderArgs", "=", "new", "Object", "[", "]", "{", "CProductId",...
Returns the number of cp definition links where CProductId = &#63; and type = &#63;. @param CProductId the c product ID @param type the type @return the number of matching cp definition links
[ "Returns", "the", "number", "of", "cp", "definition", "links", "where", "CProductId", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionLinkPersistenceImpl.java#L3627-L3688
alkacon/opencms-core
src/org/opencms/relations/CmsCategoryService.java
CmsCategoryService.createCategory
public CmsCategory createCategory( CmsObject cms, CmsCategory parent, String name, String title, String description, String referencePath) throws CmsException { List<CmsProperty> properties = new ArrayList<CmsProperty>(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(title)) { properties.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, title, null)); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(description)) { properties.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_DESCRIPTION, description, null)); } String folderPath = ""; if (parent != null) { folderPath += parent.getRootPath(); } else { if (referencePath == null) { folderPath += CmsCategoryService.CENTRALIZED_REPOSITORY; } else { List<String> repositories = getCategoryRepositories(cms, referencePath); // take the last one folderPath = repositories.get(repositories.size() - 1); } } folderPath = cms.getRequestContext().removeSiteRoot(internalCategoryRootPath(folderPath, name)); CmsResource resource; try { resource = cms.createResource(folderPath, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, properties); } catch (CmsVfsResourceNotFoundException e) { // may be is the centralized repository missing, try to create it cms.createResource(CmsCategoryService.CENTRALIZED_REPOSITORY, CmsResourceTypeFolder.RESOURCE_TYPE_ID); // now try again resource = cms.createResource(folderPath, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, properties); } return getCategory(cms, resource); }
java
public CmsCategory createCategory( CmsObject cms, CmsCategory parent, String name, String title, String description, String referencePath) throws CmsException { List<CmsProperty> properties = new ArrayList<CmsProperty>(); if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(title)) { properties.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_TITLE, title, null)); } if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(description)) { properties.add(new CmsProperty(CmsPropertyDefinition.PROPERTY_DESCRIPTION, description, null)); } String folderPath = ""; if (parent != null) { folderPath += parent.getRootPath(); } else { if (referencePath == null) { folderPath += CmsCategoryService.CENTRALIZED_REPOSITORY; } else { List<String> repositories = getCategoryRepositories(cms, referencePath); // take the last one folderPath = repositories.get(repositories.size() - 1); } } folderPath = cms.getRequestContext().removeSiteRoot(internalCategoryRootPath(folderPath, name)); CmsResource resource; try { resource = cms.createResource(folderPath, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, properties); } catch (CmsVfsResourceNotFoundException e) { // may be is the centralized repository missing, try to create it cms.createResource(CmsCategoryService.CENTRALIZED_REPOSITORY, CmsResourceTypeFolder.RESOURCE_TYPE_ID); // now try again resource = cms.createResource(folderPath, CmsResourceTypeFolder.RESOURCE_TYPE_ID, null, properties); } return getCategory(cms, resource); }
[ "public", "CmsCategory", "createCategory", "(", "CmsObject", "cms", ",", "CmsCategory", "parent", ",", "String", "name", ",", "String", "title", ",", "String", "description", ",", "String", "referencePath", ")", "throws", "CmsException", "{", "List", "<", "CmsPr...
Creates a new category.<p> Will use the same category repository as the parent if specified, or the closest category repository to the reference path if specified, or the centralized category repository in all other cases.<p> @param cms the current cms context @param parent the parent category or <code>null</code> for a new top level category @param name the name of the new category @param title the title @param description the description @param referencePath the reference path for the category repository @return the new created category @throws CmsException if something goes wrong
[ "Creates", "a", "new", "category", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/relations/CmsCategoryService.java#L193-L232
aboutsip/pkts
pkts-core/src/main/java/io/pkts/framer/SllFramer.java
SllFramer.accept
@Override public boolean accept(final Buffer buffer) throws IOException { buffer.markReaderIndex(); try { final Buffer test = buffer.readBytes(16); final byte b1 = test.getByte(0); final byte b2 = test.getByte(1); final byte b14 = test.getByte(14); final byte b15 = test.getByte(15); return validatePacketType(b1, b2) && isKnownEtherType(b14, b15); } catch (final IndexOutOfBoundsException e) { return false; } finally { buffer.resetReaderIndex(); } }
java
@Override public boolean accept(final Buffer buffer) throws IOException { buffer.markReaderIndex(); try { final Buffer test = buffer.readBytes(16); final byte b1 = test.getByte(0); final byte b2 = test.getByte(1); final byte b14 = test.getByte(14); final byte b15 = test.getByte(15); return validatePacketType(b1, b2) && isKnownEtherType(b14, b15); } catch (final IndexOutOfBoundsException e) { return false; } finally { buffer.resetReaderIndex(); } }
[ "@", "Override", "public", "boolean", "accept", "(", "final", "Buffer", "buffer", ")", "throws", "IOException", "{", "buffer", ".", "markReaderIndex", "(", ")", ";", "try", "{", "final", "Buffer", "test", "=", "buffer", ".", "readBytes", "(", "16", ")", ...
(taken from pcap/sll.sh) For captures on Linux cooked sockets, we construct a fake header that includes: a 2-byte "packet type" which is one of: LINUX_SLL_HOST packet was sent to us LINUX_SLL_BROADCAST packet was broadcast LINUX_SLL_MULTICAST packet was multicast LINUX_SLL_OTHERHOST packet was sent to somebody else LINUX_SLL_OUTGOING packet was sent *by* us; a 2-byte Ethernet protocol field; a 2-byte link-layer type; a 2-byte link-layer address length; an 8-byte source link-layer address, whose actual length is specified by the previous value. All fields except for the link-layer address are in network byte order. DO NOT change the layout of this structure, or change any of the LINUX_SLL_ values below. If you must change the link-layer header for a "cooked" Linux capture, introduce a new DLT_ type (ask "tcpdump-workers@lists.tcpdump.org" for one, so that you don't give it a value that collides with a value already being used), and use the new header in captures of that type, so that programs that can handle DLT_LINUX_SLL captures will continue to handle them correctly without any change, and so that capture files with different headers can be told apart and programs that read them can dissect the packets in them. {@inheritDoc}
[ "(", "taken", "from", "pcap", "/", "sll", ".", "sh", ")" ]
train
https://github.com/aboutsip/pkts/blob/0f06bb0dac76c812187829f580a8d476ca99a1a1/pkts-core/src/main/java/io/pkts/framer/SllFramer.java#L115-L130
eduarddrenth/ConfigurableReports
src/main/java/com/vectorprint/report/itext/style/css/CssTransformer.java
CssTransformer.transform
public static void transform(InputStream css, OutputStream stylerSetup, boolean validate) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CSSException, IOException { // find and use a SAC parser and document handler String handler = System.getProperty(DOCUMENTHANDLERPROPERTY); CssToBaseStylers ctbs = (CssToBaseStylers) Class.forName((handler==null)?DEFAULTDOCUMENTHANDLER:handler).newInstance(); if (ctbs instanceof CssDocumentHandler) { ((CssDocumentHandler)ctbs).setMustFindStylersForCssNames(validate); } Parser cssParser = new ParserFactory().makeParser(); cssParser.setDocumentHandler(ctbs); cssParser.parseStyleSheet(new InputSource(new InputStreamReader(css))); ctbs.printStylers(stylerSetup); }
java
public static void transform(InputStream css, OutputStream stylerSetup, boolean validate) throws ClassNotFoundException, IllegalAccessException, InstantiationException, CSSException, IOException { // find and use a SAC parser and document handler String handler = System.getProperty(DOCUMENTHANDLERPROPERTY); CssToBaseStylers ctbs = (CssToBaseStylers) Class.forName((handler==null)?DEFAULTDOCUMENTHANDLER:handler).newInstance(); if (ctbs instanceof CssDocumentHandler) { ((CssDocumentHandler)ctbs).setMustFindStylersForCssNames(validate); } Parser cssParser = new ParserFactory().makeParser(); cssParser.setDocumentHandler(ctbs); cssParser.parseStyleSheet(new InputSource(new InputStreamReader(css))); ctbs.printStylers(stylerSetup); }
[ "public", "static", "void", "transform", "(", "InputStream", "css", ",", "OutputStream", "stylerSetup", ",", "boolean", "validate", ")", "throws", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "CSSException", ",", "IOExcept...
Set the system property "org.w3c.css.sac.parser" to point to your {@link Parser} and optionally {@link #DOCUMENTHANDLERPROPERTY} to point to your document handler. @param css @param stylerSetup @param validate when true validate css input (see {@link CssDocumentHandler#setMustFindStylersForCssNames(java.lang.Boolean) }) @throws ClassNotFoundException @throws IllegalAccessException @throws InstantiationException @throws CSSException @throws IOException
[ "Set", "the", "system", "property", "org", ".", "w3c", ".", "css", ".", "sac", ".", "parser", "to", "point", "to", "your", "{", "@link", "Parser", "}", "and", "optionally", "{", "@link", "#DOCUMENTHANDLERPROPERTY", "}", "to", "point", "to", "your", "docu...
train
https://github.com/eduarddrenth/ConfigurableReports/blob/b5fb7a89e16d9b35f557f3bf620594f821fa1552/src/main/java/com/vectorprint/report/itext/style/css/CssTransformer.java#L108-L120
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/subordinate/builder/ExpressionBuilder.java
ExpressionBuilder.lessThan
public ExpressionBuilder lessThan(final SubordinateTrigger trigger, final Object compare) { BooleanExpression exp = new CompareExpression(CompareType.LESS_THAN, trigger, compare); appendExpression(exp); return this; }
java
public ExpressionBuilder lessThan(final SubordinateTrigger trigger, final Object compare) { BooleanExpression exp = new CompareExpression(CompareType.LESS_THAN, trigger, compare); appendExpression(exp); return this; }
[ "public", "ExpressionBuilder", "lessThan", "(", "final", "SubordinateTrigger", "trigger", ",", "final", "Object", "compare", ")", "{", "BooleanExpression", "exp", "=", "new", "CompareExpression", "(", "CompareType", ".", "LESS_THAN", ",", "trigger", ",", "compare", ...
Appends a less than test to the condition. @param trigger the trigger field. @param compare the value to use in the compare. @return this ExpressionBuilder.
[ "Appends", "a", "less", "than", "test", "to", "the", "condition", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/subordinate/builder/ExpressionBuilder.java#L91-L96
JOML-CI/JOML
src/org/joml/Matrix4x3d.java
Matrix4x3d.rotateAround
public Matrix4x3d rotateAround(Quaterniondc quat, double ox, double oy, double oz, Matrix4x3d dest) { if ((properties & PROPERTY_IDENTITY) != 0) return rotationAround(quat, ox, oy, oz); return rotateAroundAffine(quat, ox, oy, oz, dest); }
java
public Matrix4x3d rotateAround(Quaterniondc quat, double ox, double oy, double oz, Matrix4x3d dest) { if ((properties & PROPERTY_IDENTITY) != 0) return rotationAround(quat, ox, oy, oz); return rotateAroundAffine(quat, ox, oy, oz, dest); }
[ "public", "Matrix4x3d", "rotateAround", "(", "Quaterniondc", "quat", ",", "double", "ox", ",", "double", "oy", ",", "double", "oz", ",", "Matrix4x3d", "dest", ")", "{", "if", "(", "(", "properties", "&", "PROPERTY_IDENTITY", ")", "!=", "0", ")", "return", ...
/* (non-Javadoc) @see org.joml.Matrix4x3dc#rotateAround(org.joml.Quaterniondc, double, double, double, org.joml.Matrix4x3d)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4x3d.java#L3395-L3399
google/truth
core/src/main/java/com/google/common/truth/MultimapSubject.java
MultimapSubject.containsExactly
@CanIgnoreReturnValue public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) { return containsExactlyEntriesIn(accumulateMultimap(k0, v0, rest)); }
java
@CanIgnoreReturnValue public Ordered containsExactly(@NullableDecl Object k0, @NullableDecl Object v0, Object... rest) { return containsExactlyEntriesIn(accumulateMultimap(k0, v0, rest)); }
[ "@", "CanIgnoreReturnValue", "public", "Ordered", "containsExactly", "(", "@", "NullableDecl", "Object", "k0", ",", "@", "NullableDecl", "Object", "v0", ",", "Object", "...", "rest", ")", "{", "return", "containsExactlyEntriesIn", "(", "accumulateMultimap", "(", "...
Fails if the multimap does not contain exactly the given set of key/value pairs. <p><b>Warning:</b> the use of varargs means that we cannot guarantee an equal number of key/value pairs at compile time. Please make sure you provide varargs in key/value pairs!
[ "Fails", "if", "the", "multimap", "does", "not", "contain", "exactly", "the", "given", "set", "of", "key", "/", "value", "pairs", "." ]
train
https://github.com/google/truth/blob/60eceffd2e8c3297655d33ed87d965cf5af51108/core/src/main/java/com/google/common/truth/MultimapSubject.java#L296-L299
DataSketches/sketches-core
src/main/java/com/yahoo/sketches/sampling/PreambleUtil.java
PreambleUtil.preambleToString
static String preambleToString(final Memory mem) { final int preLongs = getAndCheckPreLongs(mem); // make sure we can get the assumed preamble final Family family = Family.idToFamily(mem.getByte(FAMILY_BYTE)); switch (family) { case RESERVOIR: case VAROPT: return sketchPreambleToString(mem, family, preLongs); case RESERVOIR_UNION: case VAROPT_UNION: return unionPreambleToString(mem, family, preLongs); default: throw new SketchesArgumentException("Inspecting preamble with Sampling family's " + "PreambleUtil with object of family " + family.getFamilyName()); } }
java
static String preambleToString(final Memory mem) { final int preLongs = getAndCheckPreLongs(mem); // make sure we can get the assumed preamble final Family family = Family.idToFamily(mem.getByte(FAMILY_BYTE)); switch (family) { case RESERVOIR: case VAROPT: return sketchPreambleToString(mem, family, preLongs); case RESERVOIR_UNION: case VAROPT_UNION: return unionPreambleToString(mem, family, preLongs); default: throw new SketchesArgumentException("Inspecting preamble with Sampling family's " + "PreambleUtil with object of family " + family.getFamilyName()); } }
[ "static", "String", "preambleToString", "(", "final", "Memory", "mem", ")", "{", "final", "int", "preLongs", "=", "getAndCheckPreLongs", "(", "mem", ")", ";", "// make sure we can get the assumed preamble", "final", "Family", "family", "=", "Family", ".", "idToFamil...
Returns a human readable string summary of the preamble state of the given Memory. Note: other than making sure that the given Memory size is large enough for just the preamble, this does not do much value checking of the contents of the preamble as this is primarily a tool for debugging the preamble visually. @param mem the given Memory. @return the summary preamble string.
[ "Returns", "a", "human", "readable", "string", "summary", "of", "the", "preamble", "state", "of", "the", "given", "Memory", ".", "Note", ":", "other", "than", "making", "sure", "that", "the", "given", "Memory", "size", "is", "large", "enough", "for", "just...
train
https://github.com/DataSketches/sketches-core/blob/900c8c9668a1e2f1d54d453e956caad54702e540/src/main/java/com/yahoo/sketches/sampling/PreambleUtil.java#L176-L192
grails/grails-core
grails-core/src/main/groovy/org/grails/core/lifecycle/ShutdownOperations.java
ShutdownOperations.addOperation
public static synchronized void addOperation(Runnable runnable, boolean preserveForNextShutdown) { shutdownOperations.add(runnable); if(preserveForNextShutdown) { preservedShutdownOperations.add(runnable); } }
java
public static synchronized void addOperation(Runnable runnable, boolean preserveForNextShutdown) { shutdownOperations.add(runnable); if(preserveForNextShutdown) { preservedShutdownOperations.add(runnable); } }
[ "public", "static", "synchronized", "void", "addOperation", "(", "Runnable", "runnable", ",", "boolean", "preserveForNextShutdown", ")", "{", "shutdownOperations", ".", "add", "(", "runnable", ")", ";", "if", "(", "preserveForNextShutdown", ")", "{", "preservedShutd...
Adds a shutdown operation @param runnable The runnable operation @param preserveForNextShutdown should preserve the operation for subsequent shutdowns, useful in tests
[ "Adds", "a", "shutdown", "operation" ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/core/lifecycle/ShutdownOperations.java#L73-L78
JodaOrg/joda-time
src/main/java/org/joda/time/base/BasePeriod.java
BasePeriod.addFieldInto
protected void addFieldInto(int[] values, DurationFieldType field, int value) { int index = indexOf(field); if (index == -1) { if (value != 0 || field == null) { throw new IllegalArgumentException( "Period does not support field '" + field + "'"); } } else { values[index] = FieldUtils.safeAdd(values[index], value); } }
java
protected void addFieldInto(int[] values, DurationFieldType field, int value) { int index = indexOf(field); if (index == -1) { if (value != 0 || field == null) { throw new IllegalArgumentException( "Period does not support field '" + field + "'"); } } else { values[index] = FieldUtils.safeAdd(values[index], value); } }
[ "protected", "void", "addFieldInto", "(", "int", "[", "]", "values", ",", "DurationFieldType", "field", ",", "int", "value", ")", "{", "int", "index", "=", "indexOf", "(", "field", ")", ";", "if", "(", "index", "==", "-", "1", ")", "{", "if", "(", ...
Adds the value of a field in this period. @param values the array of values to update @param field the field to set @param value the value to set @throws IllegalArgumentException if field is is null or not supported.
[ "Adds", "the", "value", "of", "a", "field", "in", "this", "period", "." ]
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/base/BasePeriod.java#L516-L526
vkostyukov/la4j
src/main/java/org/la4j/matrix/DenseMatrix.java
DenseMatrix.from1DArray
public static DenseMatrix from1DArray(int rows, int columns, double[] array) { return Basic1DMatrix.from1DArray(rows, columns, array); }
java
public static DenseMatrix from1DArray(int rows, int columns, double[] array) { return Basic1DMatrix.from1DArray(rows, columns, array); }
[ "public", "static", "DenseMatrix", "from1DArray", "(", "int", "rows", ",", "int", "columns", ",", "double", "[", "]", "array", ")", "{", "return", "Basic1DMatrix", ".", "from1DArray", "(", "rows", ",", "columns", ",", "array", ")", ";", "}" ]
Creates a {@link DenseMatrix} of the given 1D {@code array} w/o copying the underlying array.
[ "Creates", "a", "{" ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/matrix/DenseMatrix.java#L102-L104
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.getVirtualMachineScaleSetIpConfiguration
public NetworkInterfaceIPConfigurationInner getVirtualMachineScaleSetIpConfiguration(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String ipConfigurationName) { return getVirtualMachineScaleSetIpConfigurationWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName).toBlocking().single().body(); }
java
public NetworkInterfaceIPConfigurationInner getVirtualMachineScaleSetIpConfiguration(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String ipConfigurationName) { return getVirtualMachineScaleSetIpConfigurationWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName).toBlocking().single().body(); }
[ "public", "NetworkInterfaceIPConfigurationInner", "getVirtualMachineScaleSetIpConfiguration", "(", "String", "resourceGroupName", ",", "String", "virtualMachineScaleSetName", ",", "String", "virtualmachineIndex", ",", "String", "networkInterfaceName", ",", "String", "ipConfiguratio...
Get the specified network interface ip configuration in a virtual machine scale set. @param resourceGroupName The name of the resource group. @param virtualMachineScaleSetName The name of the virtual machine scale set. @param virtualmachineIndex The virtual machine index. @param networkInterfaceName The name of the network interface. @param ipConfigurationName The name of the ip configuration. @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 NetworkInterfaceIPConfigurationInner object if successful.
[ "Get", "the", "specified", "network", "interface", "ip", "configuration", "in", "a", "virtual", "machine", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L2216-L2218
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/ExceptionTableSensitiveMethodVisitor.java
ExceptionTableSensitiveMethodVisitor.onVisitLookupSwitchInsn
protected void onVisitLookupSwitchInsn(Label defaultTarget, int[] key, Label[] label) { super.visitLookupSwitchInsn(defaultTarget, key, label); }
java
protected void onVisitLookupSwitchInsn(Label defaultTarget, int[] key, Label[] label) { super.visitLookupSwitchInsn(defaultTarget, key, label); }
[ "protected", "void", "onVisitLookupSwitchInsn", "(", "Label", "defaultTarget", ",", "int", "[", "]", "key", ",", "Label", "[", "]", "label", ")", "{", "super", ".", "visitLookupSwitchInsn", "(", "defaultTarget", ",", "key", ",", "label", ")", ";", "}" ]
Visits a lookup switch instruction. @param defaultTarget The default option. @param key The key values. @param label The targets for each key.
[ "Visits", "a", "lookup", "switch", "instruction", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/visitor/ExceptionTableSensitiveMethodVisitor.java#L279-L281
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java
MapTileTransitionModel.updateTile
private void updateTile(Collection<Tile> resolved, Collection<Tile> toResolve, Tile tile, int ox, int oy) { final int tx = tile.getInTileX(); final int ty = tile.getInTileY(); final Tile neighbor = map.getTile(tx + ox, ty + oy); if (neighbor != null) { updateNeigbor(resolved, toResolve, tile, neighbor, ox, oy); } }
java
private void updateTile(Collection<Tile> resolved, Collection<Tile> toResolve, Tile tile, int ox, int oy) { final int tx = tile.getInTileX(); final int ty = tile.getInTileY(); final Tile neighbor = map.getTile(tx + ox, ty + oy); if (neighbor != null) { updateNeigbor(resolved, toResolve, tile, neighbor, ox, oy); } }
[ "private", "void", "updateTile", "(", "Collection", "<", "Tile", ">", "resolved", ",", "Collection", "<", "Tile", ">", "toResolve", ",", "Tile", "tile", ",", "int", "ox", ",", "int", "oy", ")", "{", "final", "int", "tx", "=", "tile", ".", "getInTileX",...
Update tile. @param resolved The resolved tiles. @param toResolve Tiles to resolve after. @param tile The tile reference. @param ox The horizontal offset to update. @param oy The vertical offset to update.
[ "Update", "tile", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/MapTileTransitionModel.java#L198-L208
aws/aws-sdk-java
aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/ExamplesCustomizer.java
ExamplesCustomizer.applyShapeModifier
private JsonNode applyShapeModifier(JsonNode node, ShapeModifier modifier) { if (node == null || modifier == null) { return node; } if (modifier.getExclude() == null && modifier.getModify() == null) { return node; } if (!node.isObject()) return node; final ObjectNode obj = (ObjectNode) node; ObjectNode modified = MAPPER.createObjectNode(); // Filter any excluded members final List<String> excludes = modifier.getExclude() != null ? modifier.getExclude() : Collections.emptyList(); obj.fieldNames().forEachRemaining(m -> { if (!excludes.contains(m)) { modified.set(m, obj.get(m)); } }); // Apply property renames final List<Map<String, ShapeModifier_ModifyModel>> modify = modifier.getModify() != null ? modifier.getModify() : Collections.emptyList(); modify.forEach(memberMods -> memberMods.entrySet().forEach(memberMod -> { String memberName = memberMod.getKey(); ShapeModifier_ModifyModel modelModify = memberMod.getValue(); if (modelModify.getEmitPropertyName() != null) { String newName = modelModify.getEmitPropertyName(); modified.set(newName, modified.get(memberName)); modified.remove(memberName); memberName = newName; } }) ); return modified; }
java
private JsonNode applyShapeModifier(JsonNode node, ShapeModifier modifier) { if (node == null || modifier == null) { return node; } if (modifier.getExclude() == null && modifier.getModify() == null) { return node; } if (!node.isObject()) return node; final ObjectNode obj = (ObjectNode) node; ObjectNode modified = MAPPER.createObjectNode(); // Filter any excluded members final List<String> excludes = modifier.getExclude() != null ? modifier.getExclude() : Collections.emptyList(); obj.fieldNames().forEachRemaining(m -> { if (!excludes.contains(m)) { modified.set(m, obj.get(m)); } }); // Apply property renames final List<Map<String, ShapeModifier_ModifyModel>> modify = modifier.getModify() != null ? modifier.getModify() : Collections.emptyList(); modify.forEach(memberMods -> memberMods.entrySet().forEach(memberMod -> { String memberName = memberMod.getKey(); ShapeModifier_ModifyModel modelModify = memberMod.getValue(); if (modelModify.getEmitPropertyName() != null) { String newName = modelModify.getEmitPropertyName(); modified.set(newName, modified.get(memberName)); modified.remove(memberName); memberName = newName; } }) ); return modified; }
[ "private", "JsonNode", "applyShapeModifier", "(", "JsonNode", "node", ",", "ShapeModifier", "modifier", ")", "{", "if", "(", "node", "==", "null", "||", "modifier", "==", "null", ")", "{", "return", "node", ";", "}", "if", "(", "modifier", ".", "getExclude...
Apply any shape modifiers to the JSON value. This only takes care of 'exclude' and 'emitPropertyName'. @param node The JSON node. @param modifier The shape modifier. @return The modified node.
[ "Apply", "any", "shape", "modifiers", "to", "the", "JSON", "value", ".", "This", "only", "takes", "care", "of", "exclude", "and", "emitPropertyName", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-code-generator/src/main/java/com/amazonaws/codegen/ExamplesCustomizer.java#L212-L249
alkacon/opencms-core
src/org/opencms/loader/CmsImageLoader.java
CmsImageLoader.getScaledImage
protected CmsFile getScaledImage(CmsObject cms, CmsResource resource, CmsImageScaler scaler) throws IOException, CmsException { String cacheParam = scaler.isValid() ? scaler.toString() : null; String cacheName = m_vfsDiskCache.getCacheName(resource, cacheParam); byte[] content = m_vfsDiskCache.getCacheContent(cacheName); CmsFile file; if (content != null) { if (resource instanceof CmsFile) { // the original file content must be modified (required e.g. for static export) file = (CmsFile)resource; } else { // this is no file, but we don't want to use "upgrade" since we don't need to read the content from the VFS file = new CmsFile(resource); } // save the content in the file file.setContents(content); } else { // we must read the content from the VFS (if this has not been done yet) file = cms.readFile(resource); // upgrade the file (load the content) if (scaler.isValid()) { if (scaler.getType() == 8) { // only need the focal point for mode 8 scaler.setFocalPoint(CmsPreviewService.readFocalPoint(cms, resource)); } // valid scaling parameters found, scale the content content = scaler.scaleImage(file); // exchange the content of the file with the scaled version file.setContents(content); } // save the file content in the cache m_vfsDiskCache.saveCacheFile(cacheName, file.getContents()); } return file; }
java
protected CmsFile getScaledImage(CmsObject cms, CmsResource resource, CmsImageScaler scaler) throws IOException, CmsException { String cacheParam = scaler.isValid() ? scaler.toString() : null; String cacheName = m_vfsDiskCache.getCacheName(resource, cacheParam); byte[] content = m_vfsDiskCache.getCacheContent(cacheName); CmsFile file; if (content != null) { if (resource instanceof CmsFile) { // the original file content must be modified (required e.g. for static export) file = (CmsFile)resource; } else { // this is no file, but we don't want to use "upgrade" since we don't need to read the content from the VFS file = new CmsFile(resource); } // save the content in the file file.setContents(content); } else { // we must read the content from the VFS (if this has not been done yet) file = cms.readFile(resource); // upgrade the file (load the content) if (scaler.isValid()) { if (scaler.getType() == 8) { // only need the focal point for mode 8 scaler.setFocalPoint(CmsPreviewService.readFocalPoint(cms, resource)); } // valid scaling parameters found, scale the content content = scaler.scaleImage(file); // exchange the content of the file with the scaled version file.setContents(content); } // save the file content in the cache m_vfsDiskCache.saveCacheFile(cacheName, file.getContents()); } return file; }
[ "protected", "CmsFile", "getScaledImage", "(", "CmsObject", "cms", ",", "CmsResource", "resource", ",", "CmsImageScaler", "scaler", ")", "throws", "IOException", ",", "CmsException", "{", "String", "cacheParam", "=", "scaler", ".", "isValid", "(", ")", "?", "sca...
Returns a scaled version of the given OpenCms VFS image resource.<p> All results are cached in disk. If the scaled version does not exist in the cache, it is created. Unscaled versions of the images are also stored in the cache.<p> @param cms the current users OpenCms context @param resource the base VFS resource for the image @param scaler the configured image scaler @return a scaled version of the given OpenCms VFS image resource @throws IOException in case of errors accessing the disk based cache @throws CmsException in case of errors accessing the OpenCms VFS
[ "Returns", "a", "scaled", "version", "of", "the", "given", "OpenCms", "VFS", "image", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/loader/CmsImageLoader.java#L342-L378
h2oai/h2o-3
h2o-core/src/main/java/water/api/FramesHandler.java
FramesHandler.deleteAll
@SuppressWarnings("unused") // called through reflection by RequestServer public FramesV3 deleteAll(int version, FramesV3 frames) { final Key[] keys = KeySnapshot.globalKeysOfClass(Frame.class); ArrayList<String> missing = new ArrayList<>(); Futures fs = new Futures(); for (Key key : keys) { try { getFromDKV("(none)", key).delete(null, fs); } catch (IllegalArgumentException iae) { missing.add(key.toString()); } } fs.blockForPending(); if( missing.size() != 0 ) throw new H2OKeysNotFoundArgumentException("(none)", missing.toArray(new String[missing.size()])); return frames; }
java
@SuppressWarnings("unused") // called through reflection by RequestServer public FramesV3 deleteAll(int version, FramesV3 frames) { final Key[] keys = KeySnapshot.globalKeysOfClass(Frame.class); ArrayList<String> missing = new ArrayList<>(); Futures fs = new Futures(); for (Key key : keys) { try { getFromDKV("(none)", key).delete(null, fs); } catch (IllegalArgumentException iae) { missing.add(key.toString()); } } fs.blockForPending(); if( missing.size() != 0 ) throw new H2OKeysNotFoundArgumentException("(none)", missing.toArray(new String[missing.size()])); return frames; }
[ "@", "SuppressWarnings", "(", "\"unused\"", ")", "// called through reflection by RequestServer", "public", "FramesV3", "deleteAll", "(", "int", "version", ",", "FramesV3", "frames", ")", "{", "final", "Key", "[", "]", "keys", "=", "KeySnapshot", ".", "globalKeysOfC...
Remove ALL an unlocked frames. Throws IAE for all deletes that failed (perhaps because the Frames were locked & in-use).
[ "Remove", "ALL", "an", "unlocked", "frames", ".", "Throws", "IAE", "for", "all", "deletes", "that", "failed", "(", "perhaps", "because", "the", "Frames", "were", "locked", "&", "in", "-", "use", ")", "." ]
train
https://github.com/h2oai/h2o-3/blob/845eb49dfeaadf638b6e2f779d82fac996391fad/h2o-core/src/main/java/water/api/FramesHandler.java#L284-L300
Alluxio/alluxio
core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java
InodeTree.lockInodePath
public LockedInodePath lockInodePath(AlluxioURI uri, LockPattern lockPattern) throws InvalidPathException { LockedInodePath inodePath = new LockedInodePath(uri, mInodeStore, mInodeLockManager, getRoot(), lockPattern); try { inodePath.traverse(); } catch (Throwable t) { inodePath.close(); throw t; } return inodePath; }
java
public LockedInodePath lockInodePath(AlluxioURI uri, LockPattern lockPattern) throws InvalidPathException { LockedInodePath inodePath = new LockedInodePath(uri, mInodeStore, mInodeLockManager, getRoot(), lockPattern); try { inodePath.traverse(); } catch (Throwable t) { inodePath.close(); throw t; } return inodePath; }
[ "public", "LockedInodePath", "lockInodePath", "(", "AlluxioURI", "uri", ",", "LockPattern", "lockPattern", ")", "throws", "InvalidPathException", "{", "LockedInodePath", "inodePath", "=", "new", "LockedInodePath", "(", "uri", ",", "mInodeStore", ",", "mInodeLockManager"...
Locks existing inodes on the specified path, in the specified {@link LockPattern}. The target inode is not required to exist. @param uri the uri to lock @param lockPattern the {@link LockPattern} to lock the inodes with @return the {@link LockedInodePath} representing the locked path of inodes @throws InvalidPathException if the path is invalid
[ "Locks", "existing", "inodes", "on", "the", "specified", "path", "in", "the", "specified", "{", "@link", "LockPattern", "}", ".", "The", "target", "inode", "is", "not", "required", "to", "exist", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java#L340-L351
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java
FieldBuilder.buildFieldDoc
public void buildFieldDoc(XMLNode node, Content memberDetailsTree) { if (writer == null) { return; } int size = fields.size(); if (size > 0) { Content fieldDetailsTree = writer.getFieldDetailsTreeHeader( classDoc, memberDetailsTree); for (currentFieldIndex = 0; currentFieldIndex < size; currentFieldIndex++) { Content fieldDocTree = writer.getFieldDocTreeHeader( (FieldDoc) fields.get(currentFieldIndex), fieldDetailsTree); buildChildren(node, fieldDocTree); fieldDetailsTree.addContent(writer.getFieldDoc( fieldDocTree, (currentFieldIndex == size - 1))); } memberDetailsTree.addContent( writer.getFieldDetails(fieldDetailsTree)); } }
java
public void buildFieldDoc(XMLNode node, Content memberDetailsTree) { if (writer == null) { return; } int size = fields.size(); if (size > 0) { Content fieldDetailsTree = writer.getFieldDetailsTreeHeader( classDoc, memberDetailsTree); for (currentFieldIndex = 0; currentFieldIndex < size; currentFieldIndex++) { Content fieldDocTree = writer.getFieldDocTreeHeader( (FieldDoc) fields.get(currentFieldIndex), fieldDetailsTree); buildChildren(node, fieldDocTree); fieldDetailsTree.addContent(writer.getFieldDoc( fieldDocTree, (currentFieldIndex == size - 1))); } memberDetailsTree.addContent( writer.getFieldDetails(fieldDetailsTree)); } }
[ "public", "void", "buildFieldDoc", "(", "XMLNode", "node", ",", "Content", "memberDetailsTree", ")", "{", "if", "(", "writer", "==", "null", ")", "{", "return", ";", "}", "int", "size", "=", "fields", ".", "size", "(", ")", ";", "if", "(", "size", ">...
Build the field documentation. @param node the XML element that specifies which components to document @param memberDetailsTree the content tree to which the documentation will be added
[ "Build", "the", "field", "documentation", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/FieldBuilder.java#L153-L173
jeremybrooks/jinx
src/main/java/net/jeremybrooks/jinx/Jinx.java
Jinx.flickrPost
public <T> T flickrPost(Map<String, String> params, Class<T> tClass, boolean sign) throws JinxException { return callFlickr(params, Method.POST, tClass, sign); }
java
public <T> T flickrPost(Map<String, String> params, Class<T> tClass, boolean sign) throws JinxException { return callFlickr(params, Method.POST, tClass, sign); }
[ "public", "<", "T", ">", "T", "flickrPost", "(", "Map", "<", "String", ",", "String", ">", "params", ",", "Class", "<", "T", ">", "tClass", ",", "boolean", "sign", ")", "throws", "JinxException", "{", "return", "callFlickr", "(", "params", ",", "Method...
Call Flickr, returning the specified class deserialized from the Flickr response. <br> This will make a call to Flickr using http POST. The caller can specify if the request should be signed. <p> Do not call this method directly. The classes in the net.jeremybrooks.jinx.api package will call this. @param params request parameters. @param tClass the class that will be returned. @param <T> type of the class returned. @param sign if true the request will be signed. @return an instance of the specified class containing data from Flickr. @throws JinxException if there are any errors.
[ "Call", "Flickr", "returning", "the", "specified", "class", "deserialized", "from", "the", "Flickr", "response", ".", "<br", ">", "This", "will", "make", "a", "call", "to", "Flickr", "using", "http", "POST", ".", "The", "caller", "can", "specify", "if", "t...
train
https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/Jinx.java#L508-L510
apigee/usergrid-java-sdk
src/main/java/org/usergrid/java/client/Client.java
Client.authorizeAppClient
public ApiResponse authorizeAppClient(String clientId, String clientSecret) { validateNonEmptyParam(clientId, "client identifier"); validateNonEmptyParam(clientSecret, "client secret"); assertValidApplicationId(); loggedInUser = null; accessToken = null; currentOrganization = null; Map<String, Object> formData = new HashMap<String, Object>(); formData.put("grant_type", "client_credentials"); formData.put("client_id", clientId); formData.put("client_secret", clientSecret); ApiResponse response = apiRequest(HttpMethod.POST, formData, null, organizationId, applicationId, "token"); if (response == null) { return response; } if (!isEmpty(response.getAccessToken())) { loggedInUser = null; accessToken = response.getAccessToken(); currentOrganization = null; log.info("Client.authorizeAppClient(): Access token: " + accessToken); } else { log.info("Client.authorizeAppClient(): Response: " + response); } return response; }
java
public ApiResponse authorizeAppClient(String clientId, String clientSecret) { validateNonEmptyParam(clientId, "client identifier"); validateNonEmptyParam(clientSecret, "client secret"); assertValidApplicationId(); loggedInUser = null; accessToken = null; currentOrganization = null; Map<String, Object> formData = new HashMap<String, Object>(); formData.put("grant_type", "client_credentials"); formData.put("client_id", clientId); formData.put("client_secret", clientSecret); ApiResponse response = apiRequest(HttpMethod.POST, formData, null, organizationId, applicationId, "token"); if (response == null) { return response; } if (!isEmpty(response.getAccessToken())) { loggedInUser = null; accessToken = response.getAccessToken(); currentOrganization = null; log.info("Client.authorizeAppClient(): Access token: " + accessToken); } else { log.info("Client.authorizeAppClient(): Response: " + response); } return response; }
[ "public", "ApiResponse", "authorizeAppClient", "(", "String", "clientId", ",", "String", "clientSecret", ")", "{", "validateNonEmptyParam", "(", "clientId", ",", "\"client identifier\"", ")", ";", "validateNonEmptyParam", "(", "clientSecret", ",", "\"client secret\"", "...
Log the app in with it's client id and client secret key. Not recommended for production apps. @param email @param pin @return non-null ApiResponse if request succeeds, check getError() for "invalid_grant" to see if access is denied.
[ "Log", "the", "app", "in", "with", "it", "s", "client", "id", "and", "client", "secret", "key", ".", "Not", "recommended", "for", "production", "apps", "." ]
train
https://github.com/apigee/usergrid-java-sdk/blob/6202745f184754defff13962dfc3d830bc7d8c63/src/main/java/org/usergrid/java/client/Client.java#L502-L528
wanglinsong/thx-webservice
src/main/java/com/tascape/qa/th/ws/comm/WebServiceCommunication.java
WebServiceCommunication.headUri
public static String headUri(String uri, String name) throws IOException { return Stream.of(headUri(uri)).filter(h -> h.getName().equals(name)).findFirst().get().getValue(); }
java
public static String headUri(String uri, String name) throws IOException { return Stream.of(headUri(uri)).filter(h -> h.getName().equals(name)).findFirst().get().getValue(); }
[ "public", "static", "String", "headUri", "(", "String", "uri", ",", "String", "name", ")", "throws", "IOException", "{", "return", "Stream", ".", "of", "(", "headUri", "(", "uri", ")", ")", ".", "filter", "(", "h", "->", "h", ".", "getName", "(", ")"...
Gets the response header value of specified uri. @param uri http/https uri @param name header name @return response header value @throws IOException in case of any IO related issue
[ "Gets", "the", "response", "header", "value", "of", "specified", "uri", "." ]
train
https://github.com/wanglinsong/thx-webservice/blob/29bc084b09ad35b012eb7c6b5c9ee55337ddee28/src/main/java/com/tascape/qa/th/ws/comm/WebServiceCommunication.java#L230-L232
elki-project/elki
addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGArrow.java
SVGArrow.makeArrow
public static Element makeArrow(SVGPlot svgp, Direction dir, double x, double y, double size) { final double hs = size / 2.; switch(dir){ case LEFT: return new SVGPath().drawTo(x + hs, y + hs).drawTo(x - hs, y).drawTo(x + hs, y - hs).drawTo(x + hs, y + hs).close().makeElement(svgp); case DOWN: return new SVGPath().drawTo(x - hs, y - hs).drawTo(x + hs, y - hs).drawTo(x, y + hs).drawTo(x - hs, y - hs).close().makeElement(svgp); case RIGHT: return new SVGPath().drawTo(x - hs, y - hs).drawTo(x + hs, y).drawTo(x - hs, y + hs).drawTo(x - hs, y - hs).close().makeElement(svgp); case UP: return new SVGPath().drawTo(x - hs, y + hs).drawTo(x, y - hs).drawTo(x + hs, y + hs).drawTo(x - hs, y + hs).close().makeElement(svgp); default: throw new IllegalArgumentException("Unexpected direction: " + dir); } }
java
public static Element makeArrow(SVGPlot svgp, Direction dir, double x, double y, double size) { final double hs = size / 2.; switch(dir){ case LEFT: return new SVGPath().drawTo(x + hs, y + hs).drawTo(x - hs, y).drawTo(x + hs, y - hs).drawTo(x + hs, y + hs).close().makeElement(svgp); case DOWN: return new SVGPath().drawTo(x - hs, y - hs).drawTo(x + hs, y - hs).drawTo(x, y + hs).drawTo(x - hs, y - hs).close().makeElement(svgp); case RIGHT: return new SVGPath().drawTo(x - hs, y - hs).drawTo(x + hs, y).drawTo(x - hs, y + hs).drawTo(x - hs, y - hs).close().makeElement(svgp); case UP: return new SVGPath().drawTo(x - hs, y + hs).drawTo(x, y - hs).drawTo(x + hs, y + hs).drawTo(x - hs, y + hs).close().makeElement(svgp); default: throw new IllegalArgumentException("Unexpected direction: " + dir); } }
[ "public", "static", "Element", "makeArrow", "(", "SVGPlot", "svgp", ",", "Direction", "dir", ",", "double", "x", ",", "double", "y", ",", "double", "size", ")", "{", "final", "double", "hs", "=", "size", "/", "2.", ";", "switch", "(", "dir", ")", "{"...
Draw an arrow at the given position. Note: the arrow is an unstyled svg path. You need to apply style afterwards. @param svgp Plot to draw to @param dir Direction to draw @param x Center x coordinate @param y Center y coordinate @param size Arrow size @return SVG Element
[ "Draw", "an", "arrow", "at", "the", "given", "position", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGArrow.java#L66-L81
libgdx/gdx-ai
gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java
PathSmoother.smoothPath
public int smoothPath (SmoothableGraphPath<N, V> path) { int inputPathLength = path.getCount(); // If the path is two nodes long or less, then we can't smooth it if (inputPathLength <= 2) return 0; // Make sure the ray is instantiated if (this.ray == null) { V vec = path.getNodePosition(0); this.ray = new Ray<V>(vec.cpy(), vec.cpy()); } // Keep track of where we are in the smoothed path. // We start at 1, because we must always include the start node in the smoothed path. int outputIndex = 1; // Keep track of where we are in the input path // We start at 2, because we assume two adjacent // nodes will pass the ray cast int inputIndex = 2; // Loop until we find the last item in the input while (inputIndex < inputPathLength) { // Set the ray ray.start.set(path.getNodePosition(outputIndex - 1)); ray.end.set(path.getNodePosition(inputIndex)); // Do the ray cast boolean collides = raycastCollisionDetector.collides(ray); if (collides) { // The ray test failed, swap nodes and consider the next output node path.swapNodes(outputIndex, inputIndex - 1); outputIndex++; } // Consider the next input node inputIndex++; } // Reached the last input node, always add it to the smoothed path. path.swapNodes(outputIndex, inputIndex - 1); path.truncatePath(outputIndex + 1); // Return the number of removed nodes return inputIndex - outputIndex - 1; }
java
public int smoothPath (SmoothableGraphPath<N, V> path) { int inputPathLength = path.getCount(); // If the path is two nodes long or less, then we can't smooth it if (inputPathLength <= 2) return 0; // Make sure the ray is instantiated if (this.ray == null) { V vec = path.getNodePosition(0); this.ray = new Ray<V>(vec.cpy(), vec.cpy()); } // Keep track of where we are in the smoothed path. // We start at 1, because we must always include the start node in the smoothed path. int outputIndex = 1; // Keep track of where we are in the input path // We start at 2, because we assume two adjacent // nodes will pass the ray cast int inputIndex = 2; // Loop until we find the last item in the input while (inputIndex < inputPathLength) { // Set the ray ray.start.set(path.getNodePosition(outputIndex - 1)); ray.end.set(path.getNodePosition(inputIndex)); // Do the ray cast boolean collides = raycastCollisionDetector.collides(ray); if (collides) { // The ray test failed, swap nodes and consider the next output node path.swapNodes(outputIndex, inputIndex - 1); outputIndex++; } // Consider the next input node inputIndex++; } // Reached the last input node, always add it to the smoothed path. path.swapNodes(outputIndex, inputIndex - 1); path.truncatePath(outputIndex + 1); // Return the number of removed nodes return inputIndex - outputIndex - 1; }
[ "public", "int", "smoothPath", "(", "SmoothableGraphPath", "<", "N", ",", "V", ">", "path", ")", "{", "int", "inputPathLength", "=", "path", ".", "getCount", "(", ")", ";", "// If the path is two nodes long or less, then we can't smooth it", "if", "(", "inputPathLen...
Smoothes the given path in place. @param path the path to smooth @return the number of nodes removed from the path.
[ "Smoothes", "the", "given", "path", "in", "place", "." ]
train
https://github.com/libgdx/gdx-ai/blob/2d1523a97193a45e18e11a4837c6800d08f177c5/gdx-ai/src/com/badlogic/gdx/ai/pfa/PathSmoother.java#L59-L105
line/armeria
saml/src/main/java/com/linecorp/armeria/server/saml/SamlDecorator.java
SamlDecorator.createAuthRequest
private AuthnRequest createAuthRequest(SamlIdentityProviderConfig idp, String defaultHostname) { requireNonNull(idp, "idp"); final AuthnRequest authnRequest = build(AuthnRequest.DEFAULT_ELEMENT_NAME); final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(myEntityId); authnRequest.setIssuer(issuer); authnRequest.setIssueInstant(DateTime.now()); authnRequest.setDestination(idp.ssoEndpoint().toUriString()); authnRequest.setID(requestIdManager.newId()); // The ProtocolBinding attribute is mutually exclusive with the AssertionConsumerServiceIndex attribute // and is typically accompanied by the AssertionConsumerServiceURL attribute. final SamlPortConfig portConfig = portConfigHolder.config().get(); final SamlEndpoint acsEndpoint = idp.acsEndpoint() .orElse(sp.defaultAcsConfig().endpoint()); authnRequest.setAssertionConsumerServiceURL(acsEndpoint.toUriString(portConfig.scheme().uriText(), defaultHostname, portConfig.port())); authnRequest.setProtocolBinding(acsEndpoint.bindingProtocol().urn()); final SamlNameIdPolicy policy = idp.nameIdPolicy(); final NameIDPolicy nameIdPolicy = build(NameIDPolicy.DEFAULT_ELEMENT_NAME); nameIdPolicy.setFormat(policy.format().urn()); nameIdPolicy.setAllowCreate(policy.isCreatable()); authnRequest.setNameIDPolicy(nameIdPolicy); final AuthnContextClassRef passwordAuthnCtxRef = build(AuthnContextClassRef.DEFAULT_ELEMENT_NAME); passwordAuthnCtxRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX); final RequestedAuthnContext requestedAuthnContext = build(RequestedAuthnContext.DEFAULT_ELEMENT_NAME); requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT); requestedAuthnContext.getAuthnContextClassRefs().add(passwordAuthnCtxRef); authnRequest.setRequestedAuthnContext(requestedAuthnContext); return authnRequest; }
java
private AuthnRequest createAuthRequest(SamlIdentityProviderConfig idp, String defaultHostname) { requireNonNull(idp, "idp"); final AuthnRequest authnRequest = build(AuthnRequest.DEFAULT_ELEMENT_NAME); final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME); issuer.setValue(myEntityId); authnRequest.setIssuer(issuer); authnRequest.setIssueInstant(DateTime.now()); authnRequest.setDestination(idp.ssoEndpoint().toUriString()); authnRequest.setID(requestIdManager.newId()); // The ProtocolBinding attribute is mutually exclusive with the AssertionConsumerServiceIndex attribute // and is typically accompanied by the AssertionConsumerServiceURL attribute. final SamlPortConfig portConfig = portConfigHolder.config().get(); final SamlEndpoint acsEndpoint = idp.acsEndpoint() .orElse(sp.defaultAcsConfig().endpoint()); authnRequest.setAssertionConsumerServiceURL(acsEndpoint.toUriString(portConfig.scheme().uriText(), defaultHostname, portConfig.port())); authnRequest.setProtocolBinding(acsEndpoint.bindingProtocol().urn()); final SamlNameIdPolicy policy = idp.nameIdPolicy(); final NameIDPolicy nameIdPolicy = build(NameIDPolicy.DEFAULT_ELEMENT_NAME); nameIdPolicy.setFormat(policy.format().urn()); nameIdPolicy.setAllowCreate(policy.isCreatable()); authnRequest.setNameIDPolicy(nameIdPolicy); final AuthnContextClassRef passwordAuthnCtxRef = build(AuthnContextClassRef.DEFAULT_ELEMENT_NAME); passwordAuthnCtxRef.setAuthnContextClassRef(AuthnContext.PASSWORD_AUTHN_CTX); final RequestedAuthnContext requestedAuthnContext = build(RequestedAuthnContext.DEFAULT_ELEMENT_NAME); requestedAuthnContext.setComparison(AuthnContextComparisonTypeEnumeration.EXACT); requestedAuthnContext.getAuthnContextClassRefs().add(passwordAuthnCtxRef); authnRequest.setRequestedAuthnContext(requestedAuthnContext); return authnRequest; }
[ "private", "AuthnRequest", "createAuthRequest", "(", "SamlIdentityProviderConfig", "idp", ",", "String", "defaultHostname", ")", "{", "requireNonNull", "(", "idp", ",", "\"idp\"", ")", ";", "final", "AuthnRequest", "authnRequest", "=", "build", "(", "AuthnRequest", ...
Returns an {@link AuthnRequest} which is mapped to the specified identity provider.
[ "Returns", "an", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/saml/src/main/java/com/linecorp/armeria/server/saml/SamlDecorator.java#L184-L223
enasequence/sequencetools
src/main/java/uk/ac/ebi/embl/flatfile/FlatFileUtils.java
FlatFileUtils.trimRight
public static String trimRight( String string, int pos ) { int i = string.length(); for( ; i > pos; --i ) { char charAt = string.charAt( i - 1 ); if( charAt != ' ' && charAt != '\t' && charAt != '\n' && charAt != '\r' ) { break; } } if( i <= pos ) { return ""; } return ( 0 == pos && i == string.length() ) ? string : string.substring( pos, i ); }
java
public static String trimRight( String string, int pos ) { int i = string.length(); for( ; i > pos; --i ) { char charAt = string.charAt( i - 1 ); if( charAt != ' ' && charAt != '\t' && charAt != '\n' && charAt != '\r' ) { break; } } if( i <= pos ) { return ""; } return ( 0 == pos && i == string.length() ) ? string : string.substring( pos, i ); }
[ "public", "static", "String", "trimRight", "(", "String", "string", ",", "int", "pos", ")", "{", "int", "i", "=", "string", ".", "length", "(", ")", ";", "for", "(", ";", "i", ">", "pos", ";", "--", "i", ")", "{", "char", "charAt", "=", "string",...
Removes all whitespace characters from the end of the string starting from the given position.
[ "Removes", "all", "whitespace", "characters", "from", "the", "end", "of", "the", "string", "starting", "from", "the", "given", "position", "." ]
train
https://github.com/enasequence/sequencetools/blob/4127f5e1a17540239f5810136153fbd6737fa262/src/main/java/uk/ac/ebi/embl/flatfile/FlatFileUtils.java#L95-L118
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BucketMap.java
BucketMap.release
public synchronized void release(int key, T value) { LinkedEntry<T> bucket = mMap.get(key); if (bucket == null) { bucket = new LinkedEntry<T>(null, key, new LinkedList<T>(), null); mMap.put(key, bucket); } bucket.value.addLast(value); moveToFront(bucket); }
java
public synchronized void release(int key, T value) { LinkedEntry<T> bucket = mMap.get(key); if (bucket == null) { bucket = new LinkedEntry<T>(null, key, new LinkedList<T>(), null); mMap.put(key, bucket); } bucket.value.addLast(value); moveToFront(bucket); }
[ "public", "synchronized", "void", "release", "(", "int", "key", ",", "T", "value", ")", "{", "LinkedEntry", "<", "T", ">", "bucket", "=", "mMap", ".", "get", "(", "key", ")", ";", "if", "(", "bucket", "==", "null", ")", "{", "bucket", "=", "new", ...
Associates the object with the specified key and puts it into the {@link BucketMap}. Does not overwrite the previous object, if any. @param key
[ "Associates", "the", "object", "with", "the", "specified", "key", "and", "puts", "it", "into", "the", "{" ]
train
https://github.com/facebook/fresco/blob/0b85879d51c5036d5e46e627a6651afefc0b971a/imagepipeline/src/main/java/com/facebook/imagepipeline/memory/BucketMap.java#L68-L78
jmchilton/galaxy-bootstrap
src/main/java/com/github/jmchilton/galaxybootstrap/BootStrapper.java
BootStrapper.buildLogPath
private String buildLogPath(File bootstrapLogDir, String logFileName) { return new File(bootstrapLogDir, logFileName).getAbsolutePath(); }
java
private String buildLogPath(File bootstrapLogDir, String logFileName) { return new File(bootstrapLogDir, logFileName).getAbsolutePath(); }
[ "private", "String", "buildLogPath", "(", "File", "bootstrapLogDir", ",", "String", "logFileName", ")", "{", "return", "new", "File", "(", "bootstrapLogDir", ",", "logFileName", ")", ".", "getAbsolutePath", "(", ")", ";", "}" ]
Constructs a path of a file under the bootstrap log directory. @param bootstrapLogDir The File defining the log directory. @param logFileName The name of the log file. @return The full path to the log file.
[ "Constructs", "a", "path", "of", "a", "file", "under", "the", "bootstrap", "log", "directory", "." ]
train
https://github.com/jmchilton/galaxy-bootstrap/blob/4a899f5e6ec0c9f6f4b9b21d5a0320e5925ec649/src/main/java/com/github/jmchilton/galaxybootstrap/BootStrapper.java#L71-L73
sahan/RoboZombie
robozombie/src/main/java/com/lonepulse/robozombie/util/Entities.java
Entities.resolve
public static final Class<?> resolve(Class<?> genericType) { assertNotNull(genericType); try { Class<?> entityType = HttpEntity.class.isAssignableFrom(genericType)? HttpEntity.class : (byte[].class.isAssignableFrom(genericType) || Byte[].class.isAssignableFrom(genericType))? ByteArrayEntity.class: File.class.isAssignableFrom(genericType)? FileEntity.class : InputStream.class.isAssignableFrom(genericType)? BufferedHttpEntity.class : CharSequence.class.isAssignableFrom(genericType)? StringEntity.class : Serializable.class.isAssignableFrom(genericType)? SerializableEntity.class: null; if(entityType == null) { throw new EntityResolutionFailedException(genericType); } return entityType; } catch(Exception e) { throw (e instanceof EntityResolutionFailedException)? (EntityResolutionFailedException)e :new EntityResolutionFailedException(genericType, e); } }
java
public static final Class<?> resolve(Class<?> genericType) { assertNotNull(genericType); try { Class<?> entityType = HttpEntity.class.isAssignableFrom(genericType)? HttpEntity.class : (byte[].class.isAssignableFrom(genericType) || Byte[].class.isAssignableFrom(genericType))? ByteArrayEntity.class: File.class.isAssignableFrom(genericType)? FileEntity.class : InputStream.class.isAssignableFrom(genericType)? BufferedHttpEntity.class : CharSequence.class.isAssignableFrom(genericType)? StringEntity.class : Serializable.class.isAssignableFrom(genericType)? SerializableEntity.class: null; if(entityType == null) { throw new EntityResolutionFailedException(genericType); } return entityType; } catch(Exception e) { throw (e instanceof EntityResolutionFailedException)? (EntityResolutionFailedException)e :new EntityResolutionFailedException(genericType, e); } }
[ "public", "static", "final", "Class", "<", "?", ">", "resolve", "(", "Class", "<", "?", ">", "genericType", ")", "{", "assertNotNull", "(", "genericType", ")", ";", "try", "{", "Class", "<", "?", ">", "entityType", "=", "HttpEntity", ".", "class", ".",...
<p>Discovers the {@link HttpEntity} which is suitable for wrapping an instance of the given {@link Class}. This discovery proceeds in the following order by checking the provided generic type:</p> <ol> <li>org.apache.http.{@link HttpEntity} --&gt; returned as-is.</li> <li>{@code byte[]}, {@link Byte}[] --&gt; {@link ByteArrayEntity}</li> <li>java.io.{@link File} --&gt; {@link FileEntity}</li> <li>java.io.{@link InputStream} --&gt; {@link BufferedHttpEntity}</li> <li>{@link CharSequence} --&gt; {@link StringEntity}</li> <li>java.io.{@link Serializable} --&gt; {@link SerializableEntity} (with an internal buffer)</li> </ol> @param genericType a generic {@link Class} to be translated to an {@link HttpEntity} type <br><br> @return the {@link Class} of the translated {@link HttpEntity} <br><br> @throws NullPointerException if the supplied generic type was {@code null} <br><br> @throws EntityResolutionFailedException if the given generic {@link Class} failed to be translated to an {@link HttpEntity} type <br><br> @since 1.3.0
[ "<p", ">", "Discovers", "the", "{", "@link", "HttpEntity", "}", "which", "is", "suitable", "for", "wrapping", "an", "instance", "of", "the", "given", "{", "@link", "Class", "}", ".", "This", "discovery", "proceeds", "in", "the", "following", "order", "by",...
train
https://github.com/sahan/RoboZombie/blob/2e02f0d41647612e9d89360c5c48811ea86b33c8/robozombie/src/main/java/com/lonepulse/robozombie/util/Entities.java#L161-L187
google/closure-templates
java/src/com/google/template/soy/msgs/internal/SoyMsgIdComputer.java
SoyMsgIdComputer.computeMsgIdUsingBracedPhs
static long computeMsgIdUsingBracedPhs( ImmutableList<SoyMsgPart> msgParts, @Nullable String meaning, @Nullable String contentType) { return computeMsgIdHelper(msgParts, true, meaning, contentType); }
java
static long computeMsgIdUsingBracedPhs( ImmutableList<SoyMsgPart> msgParts, @Nullable String meaning, @Nullable String contentType) { return computeMsgIdHelper(msgParts, true, meaning, contentType); }
[ "static", "long", "computeMsgIdUsingBracedPhs", "(", "ImmutableList", "<", "SoyMsgPart", ">", "msgParts", ",", "@", "Nullable", "String", "meaning", ",", "@", "Nullable", "String", "contentType", ")", "{", "return", "computeMsgIdHelper", "(", "msgParts", ",", "tru...
Computes an alternate unique message id for a message, given the message parts, the meaning string (if any), and the content type (if any). These are the only elements incorporated into the message id. <p>In particular, note that the id of a message does not change when its desc changes. <p>Important: This is an alternate message id computation using braced placeholders. Only use this function instead of {@link #computeMsgId} if you know that you need this alternate format. @param msgParts The parts of the message. @param meaning The meaning string, or null if none (usually null). @param contentType Content type of the document that this message will appear in (e.g. "{@code text/html}", or null if not used.. @return The computed message id.
[ "Computes", "an", "alternate", "unique", "message", "id", "for", "a", "message", "given", "the", "message", "parts", "the", "meaning", "string", "(", "if", "any", ")", "and", "the", "content", "type", "(", "if", "any", ")", ".", "These", "are", "the", ...
train
https://github.com/google/closure-templates/blob/cc61e1dff70ae97f24f417a57410081bc498bd56/java/src/com/google/template/soy/msgs/internal/SoyMsgIdComputer.java#L70-L73
Azure/azure-sdk-for-java
network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java
NetworkInterfacesInner.getVirtualMachineScaleSetIpConfigurationAsync
public Observable<NetworkInterfaceIPConfigurationInner> getVirtualMachineScaleSetIpConfigurationAsync(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String ipConfigurationName) { return getVirtualMachineScaleSetIpConfigurationWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName).map(new Func1<ServiceResponse<NetworkInterfaceIPConfigurationInner>, NetworkInterfaceIPConfigurationInner>() { @Override public NetworkInterfaceIPConfigurationInner call(ServiceResponse<NetworkInterfaceIPConfigurationInner> response) { return response.body(); } }); }
java
public Observable<NetworkInterfaceIPConfigurationInner> getVirtualMachineScaleSetIpConfigurationAsync(String resourceGroupName, String virtualMachineScaleSetName, String virtualmachineIndex, String networkInterfaceName, String ipConfigurationName) { return getVirtualMachineScaleSetIpConfigurationWithServiceResponseAsync(resourceGroupName, virtualMachineScaleSetName, virtualmachineIndex, networkInterfaceName, ipConfigurationName).map(new Func1<ServiceResponse<NetworkInterfaceIPConfigurationInner>, NetworkInterfaceIPConfigurationInner>() { @Override public NetworkInterfaceIPConfigurationInner call(ServiceResponse<NetworkInterfaceIPConfigurationInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "NetworkInterfaceIPConfigurationInner", ">", "getVirtualMachineScaleSetIpConfigurationAsync", "(", "String", "resourceGroupName", ",", "String", "virtualMachineScaleSetName", ",", "String", "virtualmachineIndex", ",", "String", "networkInterfaceName", ...
Get the specified network interface ip configuration in a virtual machine scale set. @param resourceGroupName The name of the resource group. @param virtualMachineScaleSetName The name of the virtual machine scale set. @param virtualmachineIndex The virtual machine index. @param networkInterfaceName The name of the network interface. @param ipConfigurationName The name of the ip configuration. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the NetworkInterfaceIPConfigurationInner object
[ "Get", "the", "specified", "network", "interface", "ip", "configuration", "in", "a", "virtual", "machine", "scale", "set", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/NetworkInterfacesInner.java#L2247-L2254
alkacon/opencms-core
src/org/opencms/ui/login/CmsLoginHelper.java
CmsLoginHelper.getPreDefOuFqn
private static String getPreDefOuFqn(CmsObject cms, HttpServletRequest request, boolean logout) { if (logout && (request.getAttribute(PARAM_PREDEF_OUFQN) == null)) { String oufqn = cms.getRequestContext().getOuFqn(); if (!oufqn.startsWith(CmsOrganizationalUnit.SEPARATOR)) { oufqn = CmsOrganizationalUnit.SEPARATOR + oufqn; } request.setAttribute(CmsLoginHelper.PARAM_PREDEF_OUFQN, oufqn); } return (String)request.getAttribute(PARAM_PREDEF_OUFQN); }
java
private static String getPreDefOuFqn(CmsObject cms, HttpServletRequest request, boolean logout) { if (logout && (request.getAttribute(PARAM_PREDEF_OUFQN) == null)) { String oufqn = cms.getRequestContext().getOuFqn(); if (!oufqn.startsWith(CmsOrganizationalUnit.SEPARATOR)) { oufqn = CmsOrganizationalUnit.SEPARATOR + oufqn; } request.setAttribute(CmsLoginHelper.PARAM_PREDEF_OUFQN, oufqn); } return (String)request.getAttribute(PARAM_PREDEF_OUFQN); }
[ "private", "static", "String", "getPreDefOuFqn", "(", "CmsObject", "cms", ",", "HttpServletRequest", "request", ",", "boolean", "logout", ")", "{", "if", "(", "logout", "&&", "(", "request", ".", "getAttribute", "(", "PARAM_PREDEF_OUFQN", ")", "==", "null", ")...
Returns the pre defined ou fqn.<p> @param cms the cms context @param request the request @param logout in case of a logout @return the ou fqn
[ "Returns", "the", "pre", "defined", "ou", "fqn", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/login/CmsLoginHelper.java#L704-L714
apache/reef
lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/evaluator/task/TaskClientCodeException.java
TaskClientCodeException.getTaskId
public static String getTaskId(final Configuration config) { try { return Tang.Factory.getTang().newInjector(config).getNamedInstance(TaskConfigurationOptions.Identifier.class); } catch (final InjectionException ex) { throw new RuntimeException("Unable to determine task identifier. Giving up.", ex); } }
java
public static String getTaskId(final Configuration config) { try { return Tang.Factory.getTang().newInjector(config).getNamedInstance(TaskConfigurationOptions.Identifier.class); } catch (final InjectionException ex) { throw new RuntimeException("Unable to determine task identifier. Giving up.", ex); } }
[ "public", "static", "String", "getTaskId", "(", "final", "Configuration", "config", ")", "{", "try", "{", "return", "Tang", ".", "Factory", ".", "getTang", "(", ")", ".", "newInjector", "(", "config", ")", ".", "getNamedInstance", "(", "TaskConfigurationOption...
Extracts a task id from the given configuration. @param config @return the task id in the given configuration. @throws RuntimeException if the configuration can't be parsed.
[ "Extracts", "a", "task", "id", "from", "the", "given", "configuration", "." ]
train
https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-common/src/main/java/org/apache/reef/runtime/common/evaluator/task/TaskClientCodeException.java#L56-L62
Waikato/moa
moa/src/main/java/moa/classifiers/oneclass/HSTrees.java
HSTrees.buildForest
private void buildForest(Instance inst) { this.dimensions = inst.numAttributes(); double[]max = new double[dimensions]; double[]min = new double[dimensions]; double sq; for (int i = 0 ; i < this.numTrees ; i++) { for(int j = 0 ; j < this.dimensions ; j++) { sq = this.classifierRandom.nextDouble(); min[j] = sq - (2.0*Math.max(sq, 1.0-sq)); max[j] = sq + (2.0*Math.max(sq, 1.0-sq)); } forest[i] = new HSTreeNode(min, max, 1, maxDepth); } }
java
private void buildForest(Instance inst) { this.dimensions = inst.numAttributes(); double[]max = new double[dimensions]; double[]min = new double[dimensions]; double sq; for (int i = 0 ; i < this.numTrees ; i++) { for(int j = 0 ; j < this.dimensions ; j++) { sq = this.classifierRandom.nextDouble(); min[j] = sq - (2.0*Math.max(sq, 1.0-sq)); max[j] = sq + (2.0*Math.max(sq, 1.0-sq)); } forest[i] = new HSTreeNode(min, max, 1, maxDepth); } }
[ "private", "void", "buildForest", "(", "Instance", "inst", ")", "{", "this", ".", "dimensions", "=", "inst", ".", "numAttributes", "(", ")", ";", "double", "[", "]", "max", "=", "new", "double", "[", "dimensions", "]", ";", "double", "[", "]", "min", ...
Build the forest of Streaming Half-Space Trees @param inst an example instance
[ "Build", "the", "forest", "of", "Streaming", "Half", "-", "Space", "Trees" ]
train
https://github.com/Waikato/moa/blob/395982e5100bfe75a3a4d26115462ce2cc74cbb0/moa/src/main/java/moa/classifiers/oneclass/HSTrees.java#L166-L184
apache/incubator-gobblin
gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/replication/ConfigBasedDatasetsFinder.java
ConfigBasedDatasetsFinder.findDatasets
@Override public List<Dataset> findDatasets() throws IOException { Set<URI> leafDatasets = getValidDatasetURIs(this.commonRoot); if (leafDatasets.isEmpty()) { return ImmutableList.of(); } // Parallel execution for copyDataset for performance consideration. final List<Dataset> result = new CopyOnWriteArrayList<>(); Iterator<Callable<Void>> callableIterator = Iterators.transform(leafDatasets.iterator(), new Function<URI, Callable<Void>>() { @Override public Callable<Void> apply(final URI datasetURI) { return findDatasetsCallable(configClient, datasetURI, props, blacklistPatterns, result); } }); this.executeItertorExecutor(callableIterator); log.info("found {} datasets in ConfigBasedDatasetsFinder", result.size()); return result; }
java
@Override public List<Dataset> findDatasets() throws IOException { Set<URI> leafDatasets = getValidDatasetURIs(this.commonRoot); if (leafDatasets.isEmpty()) { return ImmutableList.of(); } // Parallel execution for copyDataset for performance consideration. final List<Dataset> result = new CopyOnWriteArrayList<>(); Iterator<Callable<Void>> callableIterator = Iterators.transform(leafDatasets.iterator(), new Function<URI, Callable<Void>>() { @Override public Callable<Void> apply(final URI datasetURI) { return findDatasetsCallable(configClient, datasetURI, props, blacklistPatterns, result); } }); this.executeItertorExecutor(callableIterator); log.info("found {} datasets in ConfigBasedDatasetsFinder", result.size()); return result; }
[ "@", "Override", "public", "List", "<", "Dataset", ">", "findDatasets", "(", ")", "throws", "IOException", "{", "Set", "<", "URI", ">", "leafDatasets", "=", "getValidDatasetURIs", "(", "this", ".", "commonRoot", ")", ";", "if", "(", "leafDatasets", ".", "i...
Based on the {@link #whitelistTag}, find all URI which imports the tag. Then filter out 1. disabled dataset URI 2. None leaf dataset URI Then created {@link ConfigBasedDataset} based on the {@link Config} of the URIs
[ "Based", "on", "the", "{", "@link", "#whitelistTag", "}", "find", "all", "URI", "which", "imports", "the", "tag", ".", "Then", "filter", "out" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-data-management/src/main/java/org/apache/gobblin/data/management/copy/replication/ConfigBasedDatasetsFinder.java#L262-L282
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Notification.java
Notification.getCooldownExpirationByTriggerAndMetric
public long getCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.cooldownExpirationByTriggerAndMetric.containsKey(key) ? this.cooldownExpirationByTriggerAndMetric.get(key) : 0; }
java
public long getCooldownExpirationByTriggerAndMetric(Trigger trigger, Metric metric) { String key = _hashTriggerAndMetric(trigger, metric); return this.cooldownExpirationByTriggerAndMetric.containsKey(key) ? this.cooldownExpirationByTriggerAndMetric.get(key) : 0; }
[ "public", "long", "getCooldownExpirationByTriggerAndMetric", "(", "Trigger", "trigger", ",", "Metric", "metric", ")", "{", "String", "key", "=", "_hashTriggerAndMetric", "(", "trigger", ",", "metric", ")", ";", "return", "this", ".", "cooldownExpirationByTriggerAndMet...
Returns the cool down expiration time of the notification given a metric,trigger combination. @param trigger The trigger @param metric The metric @return cool down expiration time in milliseconds
[ "Returns", "the", "cool", "down", "expiration", "time", "of", "the", "notification", "given", "a", "metric", "trigger", "combination", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Notification.java#L498-L501
CenturyLinkCloud/mdw
mdw-workflow/src/com/centurylink/mdw/workflow/adapter/ObjectAdapterActivity.java
ObjectAdapterActivity.directInvoke
public Response directInvoke(ActivityRuntimeContext runtimeContext, Object request) throws AdapterException, ConnectionException { prepare(runtimeContext); if (isStubMode()) { logger.info("Adapter is running in StubMode. AdapterName:" + this.getClass().getName()); return getStubbedResponse(request); } else { Object connection = null; try { connection = openConnection(); if (doLogging()){ String requestString = externalRequestToString(request); logRequest(requestString); } Object responseObj = invoke(connection, request); String responseString = externalResponseToString(responseObj); if (responseObj != null && doLogging()) { responseString = externalResponseToString(responseObj); logResponse(responseString); } Response response = new Response(); response.setObject(responseObj); response.setContent(responseString); return response; } finally { if (connection != null) closeConnection(connection); } } }
java
public Response directInvoke(ActivityRuntimeContext runtimeContext, Object request) throws AdapterException, ConnectionException { prepare(runtimeContext); if (isStubMode()) { logger.info("Adapter is running in StubMode. AdapterName:" + this.getClass().getName()); return getStubbedResponse(request); } else { Object connection = null; try { connection = openConnection(); if (doLogging()){ String requestString = externalRequestToString(request); logRequest(requestString); } Object responseObj = invoke(connection, request); String responseString = externalResponseToString(responseObj); if (responseObj != null && doLogging()) { responseString = externalResponseToString(responseObj); logResponse(responseString); } Response response = new Response(); response.setObject(responseObj); response.setContent(responseString); return response; } finally { if (connection != null) closeConnection(connection); } } }
[ "public", "Response", "directInvoke", "(", "ActivityRuntimeContext", "runtimeContext", ",", "Object", "request", ")", "throws", "AdapterException", ",", "ConnectionException", "{", "prepare", "(", "runtimeContext", ")", ";", "if", "(", "isStubMode", "(", ")", ")", ...
This method is used for directly invoke the adapter activity from code, rather than as part of process execution flow. If logging is desired, extenders should override logMessage(). @param request request message @return response message @throws AdapterException @throws ConnectionException
[ "This", "method", "is", "used", "for", "directly", "invoke", "the", "adapter", "activity", "from", "code", "rather", "than", "as", "part", "of", "process", "execution", "flow", ".", "If", "logging", "is", "desired", "extenders", "should", "override", "logMessa...
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-workflow/src/com/centurylink/mdw/workflow/adapter/ObjectAdapterActivity.java#L609-L642
aws/aws-sdk-java
aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/AuthorizerDescription.java
AuthorizerDescription.withTokenSigningPublicKeys
public AuthorizerDescription withTokenSigningPublicKeys(java.util.Map<String, String> tokenSigningPublicKeys) { setTokenSigningPublicKeys(tokenSigningPublicKeys); return this; }
java
public AuthorizerDescription withTokenSigningPublicKeys(java.util.Map<String, String> tokenSigningPublicKeys) { setTokenSigningPublicKeys(tokenSigningPublicKeys); return this; }
[ "public", "AuthorizerDescription", "withTokenSigningPublicKeys", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tokenSigningPublicKeys", ")", "{", "setTokenSigningPublicKeys", "(", "tokenSigningPublicKeys", ")", ";", "return", "this", ";", ...
<p> The public keys used to validate the token signature returned by your custom authentication service. </p> @param tokenSigningPublicKeys The public keys used to validate the token signature returned by your custom authentication service. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "public", "keys", "used", "to", "validate", "the", "token", "signature", "returned", "by", "your", "custom", "authentication", "service", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-iot/src/main/java/com/amazonaws/services/iot/model/AuthorizerDescription.java#L272-L275
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/JobApi.java
JobApi.downloadArtifactsFile
public File downloadArtifactsFile(Object projectIdOrPath, Integer jobId, ArtifactsFile artifactsFile, File directory) throws GitLabApiException { Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", artifactsFile.getFilename()); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = artifactsFile.getFilename(); File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }
java
public File downloadArtifactsFile(Object projectIdOrPath, Integer jobId, ArtifactsFile artifactsFile, File directory) throws GitLabApiException { Response response = get(Response.Status.OK, getDefaultPerPageParam(), "projects", getProjectIdOrPath(projectIdOrPath), "jobs", jobId, "artifacts", artifactsFile.getFilename()); try { if (directory == null) directory = new File(System.getProperty("java.io.tmpdir")); String filename = artifactsFile.getFilename(); File file = new File(directory, filename); InputStream in = response.readEntity(InputStream.class); Files.copy(in, file.toPath(), StandardCopyOption.REPLACE_EXISTING); return (file); } catch (IOException ioe) { throw new GitLabApiException(ioe); } }
[ "public", "File", "downloadArtifactsFile", "(", "Object", "projectIdOrPath", ",", "Integer", "jobId", ",", "ArtifactsFile", "artifactsFile", ",", "File", "directory", ")", "throws", "GitLabApiException", "{", "Response", "response", "=", "get", "(", "Response", ".",...
Download a single artifact file from within the job's artifacts archive. Only a single file is going to be extracted from the archive and streamed to a client. <pre><code>GitLab Endpoint: GET /projects/:id/jobs/:job_id/artifacts/*artifact_path</code></pre> @param projectIdOrPath id, path of the project, or a Project instance holding the project ID or path @param jobId the unique job identifier @param artifactsFile an ArtifactsFile instance for the artifact to download @param directory the File instance of the directory to save the file to, if null will use "java.io.tmpdir" @return a File instance pointing to the download of the specified artifacts file @throws GitLabApiException if any exception occurs
[ "Download", "a", "single", "artifact", "file", "from", "within", "the", "job", "s", "artifacts", "archive", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/JobApi.java#L318-L337
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/util/MBeanUtil.java
MBeanUtil.registerMBean
public String registerMBean(Object bean, String name) throws MalformedObjectNameException, NotCompliantMBeanException, MBeanRegistrationException { return registerMBean(bean, name, false); }
java
public String registerMBean(Object bean, String name) throws MalformedObjectNameException, NotCompliantMBeanException, MBeanRegistrationException { return registerMBean(bean, name, false); }
[ "public", "String", "registerMBean", "(", "Object", "bean", ",", "String", "name", ")", "throws", "MalformedObjectNameException", ",", "NotCompliantMBeanException", ",", "MBeanRegistrationException", "{", "return", "registerMBean", "(", "bean", ",", "name", ",", "fals...
Overloaded method with 'replace' parameter set to false. See: {@link MBeanUtil#registerMBean(Object, String, boolean)}
[ "Overloaded", "method", "with", "replace", "parameter", "set", "to", "false", ".", "See", ":", "{" ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/util/MBeanUtil.java#L99-L102
alkacon/opencms-core
src/org/opencms/jsp/CmsJspTagProperty.java
CmsJspTagProperty.propertyTagAction
public static String propertyTagAction( String property, String action, String defaultValue, boolean escape, ServletRequest req) throws CmsException { return propertyTagAction(property, action, defaultValue, escape, req, null); }
java
public static String propertyTagAction( String property, String action, String defaultValue, boolean escape, ServletRequest req) throws CmsException { return propertyTagAction(property, action, defaultValue, escape, req, null); }
[ "public", "static", "String", "propertyTagAction", "(", "String", "property", ",", "String", "action", ",", "String", "defaultValue", ",", "boolean", "escape", ",", "ServletRequest", "req", ")", "throws", "CmsException", "{", "return", "propertyTagAction", "(", "p...
Internal action method.<p> @param property the property to look up @param action the search action @param defaultValue the default value @param escape if the result html should be escaped or not @param req the current request @return the value of the property or <code>null</code> if not found (and no defaultValue was provided) @throws CmsException if something goes wrong
[ "Internal", "action", "method", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspTagProperty.java#L303-L312
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Flash.java
Flash.put
public void put(String key, String value) { if (validCharacters(key) && validCharacters(value)) { this.values.put(key, value); } }
java
public void put(String key, String value) { if (validCharacters(key) && validCharacters(value)) { this.values.put(key, value); } }
[ "public", "void", "put", "(", "String", "key", ",", "String", "value", ")", "{", "if", "(", "validCharacters", "(", "key", ")", "&&", "validCharacters", "(", "value", ")", ")", "{", "this", ".", "values", ".", "put", "(", "key", ",", "value", ")", ...
Adds a value with a specific key to the flash overwriting an existing value @param key The key @param value The value
[ "Adds", "a", "value", "with", "a", "specific", "key", "to", "the", "flash", "overwriting", "an", "existing", "value" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Flash.java#L86-L90
apache/fluo
modules/api/src/main/java/org/apache/fluo/api/data/Bytes.java
Bytes.contentEquals
public boolean contentEquals(byte[] bytes, int offset, int len) { Preconditions.checkArgument(len >= 0 && offset >= 0 && offset + len <= bytes.length); return contentEqualsUnchecked(bytes, offset, len); }
java
public boolean contentEquals(byte[] bytes, int offset, int len) { Preconditions.checkArgument(len >= 0 && offset >= 0 && offset + len <= bytes.length); return contentEqualsUnchecked(bytes, offset, len); }
[ "public", "boolean", "contentEquals", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "len", ")", "{", "Preconditions", ".", "checkArgument", "(", "len", ">=", "0", "&&", "offset", ">=", "0", "&&", "offset", "+", "len", "<=", "bytes",...
Returns true if this Bytes object equals another. This method checks it's arguments. @since 1.2.0
[ "Returns", "true", "if", "this", "Bytes", "object", "equals", "another", ".", "This", "method", "checks", "it", "s", "arguments", "." ]
train
https://github.com/apache/fluo/blob/8e06204d4167651e2d3b5219b8c1397644e6ba6e/modules/api/src/main/java/org/apache/fluo/api/data/Bytes.java#L298-L301
groupon/monsoon
history/src/main/java/com/groupon/lex/metrics/history/xdr/support/FileUtil.java
FileUtil.createTempFile
public static FileChannel createTempFile(String prefix, String suffix) throws IOException { return createTempFile(TMPDIR, prefix, suffix); }
java
public static FileChannel createTempFile(String prefix, String suffix) throws IOException { return createTempFile(TMPDIR, prefix, suffix); }
[ "public", "static", "FileChannel", "createTempFile", "(", "String", "prefix", ",", "String", "suffix", ")", "throws", "IOException", "{", "return", "createTempFile", "(", "TMPDIR", ",", "prefix", ",", "suffix", ")", ";", "}" ]
Create a temporary file that will be removed when it is closed, in the tmpdir location.
[ "Create", "a", "temporary", "file", "that", "will", "be", "removed", "when", "it", "is", "closed", "in", "the", "tmpdir", "location", "." ]
train
https://github.com/groupon/monsoon/blob/eb68d72ba4c01fe018dc981097dbee033908f5c7/history/src/main/java/com/groupon/lex/metrics/history/xdr/support/FileUtil.java#L66-L68
michel-kraemer/citeproc-java
citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/StringJsonBuilder.java
StringJsonBuilder.toJson
private static Object toJson(JsonObject obj, JsonBuilderFactory factory) { return obj.toJson(factory.createJsonBuilder()); }
java
private static Object toJson(JsonObject obj, JsonBuilderFactory factory) { return obj.toJson(factory.createJsonBuilder()); }
[ "private", "static", "Object", "toJson", "(", "JsonObject", "obj", ",", "JsonBuilderFactory", "factory", ")", "{", "return", "obj", ".", "toJson", "(", "factory", ".", "createJsonBuilder", "(", ")", ")", ";", "}" ]
Converts a {@link JsonObject} to a JSON string @param obj the object to convert @param factory a factory used to create JSON builders @return the JSON string
[ "Converts", "a", "{" ]
train
https://github.com/michel-kraemer/citeproc-java/blob/1d5bf0e7bbb2bdc47309530babf0ecaba838bf10/citeproc-java/src/main/java/de/undercouch/citeproc/helper/json/StringJsonBuilder.java#L152-L154
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeParserBucket.java
DateTimeParserBucket.parseMillis
public long parseMillis(DateTimeParser parser, CharSequence text) { reset(); return doParseMillis(DateTimeParserInternalParser.of(parser), text); }
java
public long parseMillis(DateTimeParser parser, CharSequence text) { reset(); return doParseMillis(DateTimeParserInternalParser.of(parser), text); }
[ "public", "long", "parseMillis", "(", "DateTimeParser", "parser", ",", "CharSequence", "text", ")", "{", "reset", "(", ")", ";", "return", "doParseMillis", "(", "DateTimeParserInternalParser", ".", "of", "(", "parser", ")", ",", "text", ")", ";", "}" ]
Parses a datetime from the given text, returning the number of milliseconds since the epoch, 1970-01-01T00:00:00Z. <p> This parses the text using the parser into this bucket. The bucket is reset before parsing begins, allowing the bucket to be re-used. The bucket must not be shared between threads. @param parser the parser to use, see {@link DateTimeFormatter#getParser()}, not null @param text text to parse, not null @return parsed value expressed in milliseconds since the epoch @throws UnsupportedOperationException if parsing is not supported @throws IllegalArgumentException if the text to parse is invalid @since 2.4
[ "Parses", "a", "datetime", "from", "the", "given", "text", "returning", "the", "number", "of", "milliseconds", "since", "the", "epoch", "1970", "-", "01", "-", "01T00", ":", "00", ":", "00Z", ".", "<p", ">", "This", "parses", "the", "text", "using", "t...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeParserBucket.java#L173-L176
line/armeria
saml/src/main/java/com/linecorp/armeria/server/saml/SamlEndpoint.java
SamlEndpoint.toUriString
String toUriString(String defaultScheme, String defaultHostname, int defaultPort) { requireNonNull(defaultScheme, "defaultScheme"); requireNonNull(defaultHostname, "defaultHostname"); validatePort(defaultPort); final StringBuilder sb = new StringBuilder(); sb.append(firstNonNull(uri.getScheme(), defaultScheme)).append("://") .append(firstNonNull(uri.getHost(), defaultHostname)).append(':') .append(uri.getPort() > 0 ? uri.getPort() : defaultPort) .append(uri.getPath()); return sb.toString(); }
java
String toUriString(String defaultScheme, String defaultHostname, int defaultPort) { requireNonNull(defaultScheme, "defaultScheme"); requireNonNull(defaultHostname, "defaultHostname"); validatePort(defaultPort); final StringBuilder sb = new StringBuilder(); sb.append(firstNonNull(uri.getScheme(), defaultScheme)).append("://") .append(firstNonNull(uri.getHost(), defaultHostname)).append(':') .append(uri.getPort() > 0 ? uri.getPort() : defaultPort) .append(uri.getPath()); return sb.toString(); }
[ "String", "toUriString", "(", "String", "defaultScheme", ",", "String", "defaultHostname", ",", "int", "defaultPort", ")", "{", "requireNonNull", "(", "defaultScheme", ",", "\"defaultScheme\"", ")", ";", "requireNonNull", "(", "defaultHostname", ",", "\"defaultHostnam...
Returns a {@link URI} of this endpoint as a string. The omitted values in the {@link URI} will be replaced with the specified default values, such as {@code defaultScheme}, {@code defaultHostname} and {@code defaultPort}.
[ "Returns", "a", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/saml/src/main/java/com/linecorp/armeria/server/saml/SamlEndpoint.java#L102-L113
Netflix/servo
servo-core/src/main/java/com/netflix/servo/monitor/TimedInterface.java
TimedInterface.newProxy
@SuppressWarnings("unchecked") public static <T> T newProxy(Class<T> ctype, T concrete, String id) { final InvocationHandler handler = new TimedHandler<>(ctype, concrete, id); final Class<?>[] types = new Class[]{ctype, CompositeMonitor.class}; return (T) Proxy.newProxyInstance(ctype.getClassLoader(), types, handler); }
java
@SuppressWarnings("unchecked") public static <T> T newProxy(Class<T> ctype, T concrete, String id) { final InvocationHandler handler = new TimedHandler<>(ctype, concrete, id); final Class<?>[] types = new Class[]{ctype, CompositeMonitor.class}; return (T) Proxy.newProxyInstance(ctype.getClassLoader(), types, handler); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "newProxy", "(", "Class", "<", "T", ">", "ctype", ",", "T", "concrete", ",", "String", "id", ")", "{", "final", "InvocationHandler", "handler", "=", "new", "Timed...
Creates a new TimedInterface for a given interface <code>ctype</code> with a concrete class <code>concrete</code> and a specific id. The id can be used to distinguish among multiple objects with the same concrete class.
[ "Creates", "a", "new", "TimedInterface", "for", "a", "given", "interface", "<code", ">", "ctype<", "/", "code", ">", "with", "a", "concrete", "class", "<code", ">", "concrete<", "/", "code", ">", "and", "a", "specific", "id", ".", "The", "id", "can", "...
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/monitor/TimedInterface.java#L135-L140
ben-manes/caffeine
simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/WindowTinyLfuPolicy.java
WindowTinyLfuPolicy.onMiss
private void onMiss(long key) { admittor.record(key); Node node = new Node(key, Status.WINDOW); node.appendToTail(headWindow); data.put(key, node); sizeWindow++; evict(); }
java
private void onMiss(long key) { admittor.record(key); Node node = new Node(key, Status.WINDOW); node.appendToTail(headWindow); data.put(key, node); sizeWindow++; evict(); }
[ "private", "void", "onMiss", "(", "long", "key", ")", "{", "admittor", ".", "record", "(", "key", ")", ";", "Node", "node", "=", "new", "Node", "(", "key", ",", "Status", ".", "WINDOW", ")", ";", "node", ".", "appendToTail", "(", "headWindow", ")", ...
Adds the entry to the admission window, evicting if necessary.
[ "Adds", "the", "entry", "to", "the", "admission", "window", "evicting", "if", "necessary", "." ]
train
https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/policy/sketch/WindowTinyLfuPolicy.java#L118-L126
sualeh/magnetictrackparser
src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java
Track1FormatB.from
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
java
public static Track1FormatB from(final String rawTrackData) { final Matcher matcher = track1FormatBPattern .matcher(trimToEmpty(rawTrackData)); final String rawTrack1Data; final AccountNumber pan; final ExpirationDate expirationDate; final Name name; final ServiceCode serviceCode; final String formatCode; final String discretionaryData; if (matcher.matches()) { rawTrack1Data = getGroup(matcher, 1); formatCode = getGroup(matcher, 2); pan = new AccountNumber(getGroup(matcher, 3)); name = new Name(getGroup(matcher, 4)); expirationDate = new ExpirationDate(getGroup(matcher, 5)); serviceCode = new ServiceCode(getGroup(matcher, 6)); discretionaryData = getGroup(matcher, 7); } else { rawTrack1Data = null; formatCode = ""; pan = new AccountNumber(); name = new Name(); expirationDate = new ExpirationDate(); serviceCode = new ServiceCode(); discretionaryData = ""; } return new Track1FormatB(rawTrack1Data, pan, expirationDate, name, serviceCode, formatCode, discretionaryData); }
[ "public", "static", "Track1FormatB", "from", "(", "final", "String", "rawTrackData", ")", "{", "final", "Matcher", "matcher", "=", "track1FormatBPattern", ".", "matcher", "(", "trimToEmpty", "(", "rawTrackData", ")", ")", ";", "final", "String", "rawTrack1Data", ...
Parses magnetic track 1 format B data into a Track1FormatB object. @param rawTrackData Raw track data as a string. Can include newlines, and other tracks as well. @return A Track1FormatB instance, corresponding to the parsed data.
[ "Parses", "magnetic", "track", "1", "format", "B", "data", "into", "a", "Track1FormatB", "object", "." ]
train
https://github.com/sualeh/magnetictrackparser/blob/1da8ff20ac6269b1d523875157278978ba71d260/src/main/java/us/fatehi/magnetictrack/bankcard/Track1FormatB.java#L78-L119
Impetus/Kundera
src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java
ESResponseWrapper.getAggregatedResult
private Object getAggregatedResult(InternalAggregations internalAggs, String identifier, Expression exp) { switch (identifier) { case Expression.MIN: return (((InternalMin) internalAggs.get(exp.toParsedText())).getValue()); case Expression.MAX: return (((InternalMax) internalAggs.get(exp.toParsedText())).getValue()); case Expression.AVG: return (((InternalAvg) internalAggs.get(exp.toParsedText())).getValue()); case Expression.SUM: return (((InternalSum) internalAggs.get(exp.toParsedText())).getValue()); case Expression.COUNT: return (((InternalValueCount) internalAggs.get(exp.toParsedText())).getValue()); } throw new KunderaException("No support for " + identifier + " aggregation."); }
java
private Object getAggregatedResult(InternalAggregations internalAggs, String identifier, Expression exp) { switch (identifier) { case Expression.MIN: return (((InternalMin) internalAggs.get(exp.toParsedText())).getValue()); case Expression.MAX: return (((InternalMax) internalAggs.get(exp.toParsedText())).getValue()); case Expression.AVG: return (((InternalAvg) internalAggs.get(exp.toParsedText())).getValue()); case Expression.SUM: return (((InternalSum) internalAggs.get(exp.toParsedText())).getValue()); case Expression.COUNT: return (((InternalValueCount) internalAggs.get(exp.toParsedText())).getValue()); } throw new KunderaException("No support for " + identifier + " aggregation."); }
[ "private", "Object", "getAggregatedResult", "(", "InternalAggregations", "internalAggs", ",", "String", "identifier", ",", "Expression", "exp", ")", "{", "switch", "(", "identifier", ")", "{", "case", "Expression", ".", "MIN", ":", "return", "(", "(", "(", "In...
Gets the aggregated result. @param internalAggs the internal aggs @param identifier the identifier @param exp the exp @return the aggregated result
[ "Gets", "the", "aggregated", "result", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-elastic-search/src/main/java/com/impetus/client/es/utils/ESResponseWrapper.java#L555-L576
BioPAX/Paxtools
paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java
BioPAXIOHandlerAdapter.resourceFixes
protected Object resourceFixes(BioPAXElement bpe, Object value) { if (this.isFixReusedPEPs() && value instanceof physicalEntityParticipant) { value = this.getReusedPEPHelper().fixReusedPEP((physicalEntityParticipant) value, bpe); } return value; }
java
protected Object resourceFixes(BioPAXElement bpe, Object value) { if (this.isFixReusedPEPs() && value instanceof physicalEntityParticipant) { value = this.getReusedPEPHelper().fixReusedPEP((physicalEntityParticipant) value, bpe); } return value; }
[ "protected", "Object", "resourceFixes", "(", "BioPAXElement", "bpe", ",", "Object", "value", ")", "{", "if", "(", "this", ".", "isFixReusedPEPs", "(", ")", "&&", "value", "instanceof", "physicalEntityParticipant", ")", "{", "value", "=", "this", ".", "getReuse...
This method currently only fixes reusedPEPs if the option is set. As L2 is becoming obsolete this method will be slated for deprecation. @param bpe to be bound @param value to be assigned. @return a "fixed" value.
[ "This", "method", "currently", "only", "fixes", "reusedPEPs", "if", "the", "option", "is", "set", ".", "As", "L2", "is", "becoming", "obsolete", "this", "method", "will", "be", "slated", "for", "deprecation", "." ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/paxtools-core/src/main/java/org/biopax/paxtools/io/BioPAXIOHandlerAdapter.java#L295-L302
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/types/Transform.java
Transform.createViewportTransform
public static Transform createViewportTransform(double x, double y, final double width, final double height, final double viewportWidth, final double viewportHeight) { if ((width <= 0) || (height <= 0)) { return null; } final double scaleX = viewportWidth / width; final double scaleY = viewportHeight / height; double scale; if (scaleX > scaleY) { // use scaleY scale = scaleY; final double dw = (viewportWidth / scale) - width; x -= dw / 2; } else { scale = scaleX; final double dh = (viewportHeight / scale) - height; y -= dh / 2; } // x' = m[0] + x*m[1] y' = m[2] + y*m[3] final double m02 = -x * scale; final double m12 = -y * scale; return new Transform(scale, 0, 0, scale, m02, m12); }
java
public static Transform createViewportTransform(double x, double y, final double width, final double height, final double viewportWidth, final double viewportHeight) { if ((width <= 0) || (height <= 0)) { return null; } final double scaleX = viewportWidth / width; final double scaleY = viewportHeight / height; double scale; if (scaleX > scaleY) { // use scaleY scale = scaleY; final double dw = (viewportWidth / scale) - width; x -= dw / 2; } else { scale = scaleX; final double dh = (viewportHeight / scale) - height; y -= dh / 2; } // x' = m[0] + x*m[1] y' = m[2] + y*m[3] final double m02 = -x * scale; final double m12 = -y * scale; return new Transform(scale, 0, 0, scale, m02, m12); }
[ "public", "static", "Transform", "createViewportTransform", "(", "double", "x", ",", "double", "y", ",", "final", "double", "width", ",", "final", "double", "height", ",", "final", "double", "viewportWidth", ",", "final", "double", "viewportHeight", ")", "{", ...
Creates a Transform for a viewport. The visible area is defined by the rectangle [x, y, width, height] and the viewport's width and height. @param x X coordinate of the top-left corner of the new view area. @param y Y coordinate of the top-left corner of the new view area. @param width Width of the new view area. @param height Height of the new View area. @param viewportWidth Width of the Viewport. @param viewportHeight Height of the Viewport. @return Transform
[ "Creates", "a", "Transform", "for", "a", "viewport", ".", "The", "visible", "area", "is", "defined", "by", "the", "rectangle", "[", "x", "y", "width", "height", "]", "and", "the", "viewport", "s", "width", "and", "height", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/types/Transform.java#L469-L506
unbescape/unbescape
src/main/java/org/unbescape/java/JavaEscape.java
JavaEscape.escapeJava
public static String escapeJava(final String text, final JavaEscapeLevel level) { if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } return JavaEscapeUtil.escape(text, level); }
java
public static String escapeJava(final String text, final JavaEscapeLevel level) { if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } return JavaEscapeUtil.escape(text, level); }
[ "public", "static", "String", "escapeJava", "(", "final", "String", "text", ",", "final", "JavaEscapeLevel", "level", ")", "{", "if", "(", "level", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The 'level' argument cannot be null\"", ...
<p> Perform a (configurable) Java <strong>escape</strong> operation on a <tt>String</tt> input. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.java.JavaEscapeLevel} argument value. </p> <p> All other <tt>String</tt>-based <tt>escapeJava*(...)</tt> methods call this one with preconfigured <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be escaped. @param level the escape level to be applied, see {@link org.unbescape.java.JavaEscapeLevel}. @return The escaped result <tt>String</tt>. As a memory-performance improvement, will return the exact same object as the <tt>text</tt> input argument if no escaping modifications were required (and no additional <tt>String</tt> objects will be created during processing). Will return <tt>null</tt> if input is <tt>null</tt>.
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "Java", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "will", "perfo...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/java/JavaEscape.java#L334-L342
OpenLiberty/open-liberty
dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java
AuditEvent.setReason
public void setReason(Map<String, Object> reason) { removeEntriesStartingWith(REASON); eventMap.putAll(reason); }
java
public void setReason(Map<String, Object> reason) { removeEntriesStartingWith(REASON); eventMap.putAll(reason); }
[ "public", "void", "setReason", "(", "Map", "<", "String", ",", "Object", ">", "reason", ")", "{", "removeEntriesStartingWith", "(", "REASON", ")", ";", "eventMap", ".", "putAll", "(", "reason", ")", ";", "}" ]
Set the reason keys/values. The provided Map will completely replace the existing reason, i.e. all current reason keys/values will be removed and the new reason keys/values will be added. @param reason
[ "Set", "the", "reason", "keys", "/", "values", ".", "The", "provided", "Map", "will", "completely", "replace", "the", "existing", "reason", "i", ".", "e", ".", "all", "current", "reason", "keys", "/", "values", "will", "be", "removed", "and", "the", "new...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.websphere.security/src/com/ibm/websphere/security/audit/AuditEvent.java#L371-L374
hawkular/hawkular-inventory
hawkular-inventory-api/src/main/java/org/hawkular/inventory/base/Traversal.java
Traversal.isApplicable
protected boolean isApplicable(AbstractElement<?, ?> result) { ResultFilter filter = context.configuration.getResultFilter(); return filter == null || filter.isApplicable(result); }
java
protected boolean isApplicable(AbstractElement<?, ?> result) { ResultFilter filter = context.configuration.getResultFilter(); return filter == null || filter.isApplicable(result); }
[ "protected", "boolean", "isApplicable", "(", "AbstractElement", "<", "?", ",", "?", ">", "result", ")", "{", "ResultFilter", "filter", "=", "context", ".", "configuration", ".", "getResultFilter", "(", ")", ";", "return", "filter", "==", "null", "||", "filte...
If the inventory configuration provided a {@link ResultFilter}, this calls it to tell whether provided element is applicable. If the result filter is not provided by the configuration, true will always be returned. @param result the potential result to be checked for applicability in the result set @return true or false (!!!)
[ "If", "the", "inventory", "configuration", "provided", "a", "{", "@link", "ResultFilter", "}", "this", "calls", "it", "to", "tell", "whether", "provided", "element", "is", "applicable", ".", "If", "the", "result", "filter", "is", "not", "provided", "by", "th...
train
https://github.com/hawkular/hawkular-inventory/blob/f56dc10323dca21777feb5b609a9e9cc70ffaf62/hawkular-inventory-api/src/main/java/org/hawkular/inventory/base/Traversal.java#L49-L52
bitcoinj/bitcoinj
core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java
TransactionSignature.calcSigHashValue
public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) { Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated int sighashFlags = mode.value; if (anyoneCanPay) sighashFlags |= Transaction.SigHash.ANYONECANPAY.value; return sighashFlags; }
java
public static int calcSigHashValue(Transaction.SigHash mode, boolean anyoneCanPay) { Preconditions.checkArgument(SigHash.ALL == mode || SigHash.NONE == mode || SigHash.SINGLE == mode); // enforce compatibility since this code was made before the SigHash enum was updated int sighashFlags = mode.value; if (anyoneCanPay) sighashFlags |= Transaction.SigHash.ANYONECANPAY.value; return sighashFlags; }
[ "public", "static", "int", "calcSigHashValue", "(", "Transaction", ".", "SigHash", "mode", ",", "boolean", "anyoneCanPay", ")", "{", "Preconditions", ".", "checkArgument", "(", "SigHash", ".", "ALL", "==", "mode", "||", "SigHash", ".", "NONE", "==", "mode", ...
Calculates the byte used in the protocol to represent the combination of mode and anyoneCanPay.
[ "Calculates", "the", "byte", "used", "in", "the", "protocol", "to", "represent", "the", "combination", "of", "mode", "and", "anyoneCanPay", "." ]
train
https://github.com/bitcoinj/bitcoinj/blob/9cf13d29315014ed59cf4fc5944e5f227e8df9a6/core/src/main/java/org/bitcoinj/crypto/TransactionSignature.java#L71-L77
kaazing/gateway
service/http.directory/src/main/java/org/kaazing/gateway/service/http/directory/cachecontrol/ConflictResolverUtils.java
ConflictResolverUtils.resolveConflicts
public static void resolveConflicts(PatternCacheControl specificPattern, PatternCacheControl generalPattern) { for (Entry<Directive, String> entry : generalPattern.getDirectives().entrySet()) { Directive generalDirective = entry.getKey(); String generalValue = entry.getValue(); if (generalValue == EMPTY_STRING_VALUE) { specificPattern.setDirective(generalDirective, EMPTY_STRING_VALUE); } else { resolveValueConflicts(generalDirective, generalValue, specificPattern); } } }
java
public static void resolveConflicts(PatternCacheControl specificPattern, PatternCacheControl generalPattern) { for (Entry<Directive, String> entry : generalPattern.getDirectives().entrySet()) { Directive generalDirective = entry.getKey(); String generalValue = entry.getValue(); if (generalValue == EMPTY_STRING_VALUE) { specificPattern.setDirective(generalDirective, EMPTY_STRING_VALUE); } else { resolveValueConflicts(generalDirective, generalValue, specificPattern); } } }
[ "public", "static", "void", "resolveConflicts", "(", "PatternCacheControl", "specificPattern", ",", "PatternCacheControl", "generalPattern", ")", "{", "for", "(", "Entry", "<", "Directive", ",", "String", ">", "entry", ":", "generalPattern", ".", "getDirectives", "(...
Resolves directive conflicts between two PatternCacheControl objects @param specificPattern - the pattern which can be included in the second one @param generalPattern - the pattern which includes the first one
[ "Resolves", "directive", "conflicts", "between", "two", "PatternCacheControl", "objects" ]
train
https://github.com/kaazing/gateway/blob/06017b19273109b3b992e528e702586446168d57/service/http.directory/src/main/java/org/kaazing/gateway/service/http/directory/cachecontrol/ConflictResolverUtils.java#L52-L62
pravega/pravega
common/src/main/java/io/pravega/common/concurrent/ExecutorServiceHelpers.java
ExecutorServiceHelpers.getThreadFactory
public static ThreadFactory getThreadFactory(String groupName) { return new ThreadFactory() { final AtomicInteger threadCount = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, groupName + "-" + threadCount.incrementAndGet()); thread.setDaemon(true); return thread; } }; }
java
public static ThreadFactory getThreadFactory(String groupName) { return new ThreadFactory() { final AtomicInteger threadCount = new AtomicInteger(); @Override public Thread newThread(Runnable r) { Thread thread = new Thread(r, groupName + "-" + threadCount.incrementAndGet()); thread.setDaemon(true); return thread; } }; }
[ "public", "static", "ThreadFactory", "getThreadFactory", "(", "String", "groupName", ")", "{", "return", "new", "ThreadFactory", "(", ")", "{", "final", "AtomicInteger", "threadCount", "=", "new", "AtomicInteger", "(", ")", ";", "@", "Override", "public", "Threa...
Creates and returns a thread factory that will create threads with the given name prefix. @param groupName the name of the threads @return a thread factory
[ "Creates", "and", "returns", "a", "thread", "factory", "that", "will", "create", "threads", "with", "the", "given", "name", "prefix", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/common/src/main/java/io/pravega/common/concurrent/ExecutorServiceHelpers.java#L52-L63
ThreeTen/threetenbp
src/main/java/org/threeten/bp/chrono/JapaneseEra.java
JapaneseEra.registerEra
public static JapaneseEra registerEra(LocalDate since, String name) { JapaneseEra[] known = KNOWN_ERAS.get(); if (known.length > 4) { throw new DateTimeException("Only one additional Japanese era can be added"); } Jdk8Methods.requireNonNull(since, "since"); Jdk8Methods.requireNonNull(name, "name"); if (!since.isAfter(HEISEI.since)) { throw new DateTimeException("Invalid since date for additional Japanese era, must be after Heisei"); } JapaneseEra era = new JapaneseEra(ADDITIONAL_VALUE, since, name); JapaneseEra[] newArray = Arrays.copyOf(known, 5); newArray[4] = era; if (!KNOWN_ERAS.compareAndSet(known, newArray)) { throw new DateTimeException("Only one additional Japanese era can be added"); } return era; }
java
public static JapaneseEra registerEra(LocalDate since, String name) { JapaneseEra[] known = KNOWN_ERAS.get(); if (known.length > 4) { throw new DateTimeException("Only one additional Japanese era can be added"); } Jdk8Methods.requireNonNull(since, "since"); Jdk8Methods.requireNonNull(name, "name"); if (!since.isAfter(HEISEI.since)) { throw new DateTimeException("Invalid since date for additional Japanese era, must be after Heisei"); } JapaneseEra era = new JapaneseEra(ADDITIONAL_VALUE, since, name); JapaneseEra[] newArray = Arrays.copyOf(known, 5); newArray[4] = era; if (!KNOWN_ERAS.compareAndSet(known, newArray)) { throw new DateTimeException("Only one additional Japanese era can be added"); } return era; }
[ "public", "static", "JapaneseEra", "registerEra", "(", "LocalDate", "since", ",", "String", "name", ")", "{", "JapaneseEra", "[", "]", "known", "=", "KNOWN_ERAS", ".", "get", "(", ")", ";", "if", "(", "known", ".", "length", ">", "4", ")", "{", "throw"...
Registers an additional instance of {@code JapaneseEra}. <p> A new Japanese era can begin at any time. This method allows one new era to be registered without the need for a new library version. If needed, callers should assign the result to a static variable accessible across the application. This must be done once, in early startup code. <p> NOTE: This method does not exist in Java SE 8. @param since the date representing the first date of the era, validated not null @param name the name @return the {@code JapaneseEra} singleton, not null @throws DateTimeException if an additional era has already been registered
[ "Registers", "an", "additional", "instance", "of", "{", "@code", "JapaneseEra", "}", ".", "<p", ">", "A", "new", "Japanese", "era", "can", "begin", "at", "any", "time", ".", "This", "method", "allows", "one", "new", "era", "to", "be", "registered", "with...
train
https://github.com/ThreeTen/threetenbp/blob/5f05b649f89f205aabd96b2f83c36796ec616fe6/src/main/java/org/threeten/bp/chrono/JapaneseEra.java#L173-L190
hdbeukel/james-core
src/main/java/org/jamesframework/core/subset/neigh/SinglePerturbationNeighbourhood.java
SinglePerturbationNeighbourhood.getAllMoves
@Override public List<SubsetMove> getAllMoves(SubsetSolution solution) { // get set of candidate IDs for deletion and addition (fixed IDs are discarded) Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // create empty list of moves List<SubsetMove> moves = new ArrayList<>(); // generate all addition moves, if valid if(canAdd(solution, addCandidates)){ // create addition move for each add candidate addCandidates.forEach(add -> moves.add(new AdditionMove(add))); } // generate all deletion moves, if valid if(canRemove(solution, removeCandidates)){ // create deletion move for each remove candidate removeCandidates.forEach(remove -> moves.add(new DeletionMove(remove))); } // generate all swap moves, if valid if(canSwap(solution, addCandidates, removeCandidates)){ // create swap move for each combination of add and remove candidate addCandidates.forEach(add -> { removeCandidates.forEach(remove -> { moves.add(new SwapMove(add, remove)); }); }); } // return generated moves return moves; }
java
@Override public List<SubsetMove> getAllMoves(SubsetSolution solution) { // get set of candidate IDs for deletion and addition (fixed IDs are discarded) Set<Integer> removeCandidates = getRemoveCandidates(solution); Set<Integer> addCandidates = getAddCandidates(solution); // create empty list of moves List<SubsetMove> moves = new ArrayList<>(); // generate all addition moves, if valid if(canAdd(solution, addCandidates)){ // create addition move for each add candidate addCandidates.forEach(add -> moves.add(new AdditionMove(add))); } // generate all deletion moves, if valid if(canRemove(solution, removeCandidates)){ // create deletion move for each remove candidate removeCandidates.forEach(remove -> moves.add(new DeletionMove(remove))); } // generate all swap moves, if valid if(canSwap(solution, addCandidates, removeCandidates)){ // create swap move for each combination of add and remove candidate addCandidates.forEach(add -> { removeCandidates.forEach(remove -> { moves.add(new SwapMove(add, remove)); }); }); } // return generated moves return moves; }
[ "@", "Override", "public", "List", "<", "SubsetMove", ">", "getAllMoves", "(", "SubsetSolution", "solution", ")", "{", "// get set of candidate IDs for deletion and addition (fixed IDs are discarded)", "Set", "<", "Integer", ">", "removeCandidates", "=", "getRemoveCandidates"...
Generate all valid swap, deletion and addition moves that transform the given subset solution into a neighbour within the minimum and maximum allowed subset size. The returned list may be empty, if no valid moves exist. If any fixed IDs have been specified, these will not be considered for deletion nor addition. @param solution solution for which a set of all valid moves is generated @return list of all valid swap, deletion and addition moves
[ "Generate", "all", "valid", "swap", "deletion", "and", "addition", "moves", "that", "transform", "the", "given", "subset", "solution", "into", "a", "neighbour", "within", "the", "minimum", "and", "maximum", "allowed", "subset", "size", ".", "The", "returned", ...
train
https://github.com/hdbeukel/james-core/blob/4e85c20c142902373e5b5e8b5d12a2558650f66d/src/main/java/org/jamesframework/core/subset/neigh/SinglePerturbationNeighbourhood.java#L184-L212
strator-dev/greenpepper
greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/IOUtils.java
IOUtils.copyFile
public static void copyFile(File srcFile, File destFile) throws IOException { InputStream reader = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[2048]; int n = 0; while (-1 != (n = reader.read(buffer))) { out.write(buffer, 0, n); } } finally { org.apache.commons.io.IOUtils.closeQuietly(out); org.apache.commons.io.IOUtils.closeQuietly(reader); } }
java
public static void copyFile(File srcFile, File destFile) throws IOException { InputStream reader = new FileInputStream(srcFile); OutputStream out = new FileOutputStream(destFile); try { byte[] buffer = new byte[2048]; int n = 0; while (-1 != (n = reader.read(buffer))) { out.write(buffer, 0, n); } } finally { org.apache.commons.io.IOUtils.closeQuietly(out); org.apache.commons.io.IOUtils.closeQuietly(reader); } }
[ "public", "static", "void", "copyFile", "(", "File", "srcFile", ",", "File", "destFile", ")", "throws", "IOException", "{", "InputStream", "reader", "=", "new", "FileInputStream", "(", "srcFile", ")", ";", "OutputStream", "out", "=", "new", "FileOutputStream", ...
<p>copyFile.</p> @param srcFile a {@link java.io.File} object. @param destFile a {@link java.io.File} object. @throws java.io.IOException if any.
[ "<p", ">", "copyFile", ".", "<", "/", "p", ">" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper/greenpepper-client/src/main/java/com/greenpepper/util/IOUtils.java#L25-L43
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/painter/VectorTilePainter.java
VectorTilePainter.deleteShape
public void deleteShape(Paintable paintable, Object group, MapContext context) { VectorTile tile = (VectorTile) paintable; context.getVectorContext().deleteGroup(tile.getFeatureContent()); context.getVectorContext().deleteGroup(tile.getLabelContent()); context.getRasterContext().deleteGroup(tile.getFeatureContent()); context.getRasterContext().deleteGroup(tile.getLabelContent()); }
java
public void deleteShape(Paintable paintable, Object group, MapContext context) { VectorTile tile = (VectorTile) paintable; context.getVectorContext().deleteGroup(tile.getFeatureContent()); context.getVectorContext().deleteGroup(tile.getLabelContent()); context.getRasterContext().deleteGroup(tile.getFeatureContent()); context.getRasterContext().deleteGroup(tile.getLabelContent()); }
[ "public", "void", "deleteShape", "(", "Paintable", "paintable", ",", "Object", "group", ",", "MapContext", "context", ")", "{", "VectorTile", "tile", "=", "(", "VectorTile", ")", "paintable", ";", "context", ".", "getVectorContext", "(", ")", ".", "deleteGroup...
Delete a {@link Paintable} object from the given {@link MapContext}. It the object does not exist, nothing will be done. @param paintable The object to be painted. @param group The group where the object resides in (optional). @param context The context to paint on.
[ "Delete", "a", "{", "@link", "Paintable", "}", "object", "from", "the", "given", "{", "@link", "MapContext", "}", ".", "It", "the", "object", "does", "not", "exist", "nothing", "will", "be", "done", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/painter/VectorTilePainter.java#L105-L111
alkacon/opencms-core
src/org/opencms/flex/CmsFlexRequest.java
CmsFlexRequest.getRequestDispatcherToExternal
public CmsFlexRequestDispatcher getRequestDispatcherToExternal(String vfs_target, String ext_target) { return new CmsFlexRequestDispatcher( m_controller.getTopRequest().getRequestDispatcher(ext_target), CmsLinkManager.getAbsoluteUri(vfs_target, m_controller.getCmsObject().getRequestContext().getUri()), ext_target); }
java
public CmsFlexRequestDispatcher getRequestDispatcherToExternal(String vfs_target, String ext_target) { return new CmsFlexRequestDispatcher( m_controller.getTopRequest().getRequestDispatcher(ext_target), CmsLinkManager.getAbsoluteUri(vfs_target, m_controller.getCmsObject().getRequestContext().getUri()), ext_target); }
[ "public", "CmsFlexRequestDispatcher", "getRequestDispatcherToExternal", "(", "String", "vfs_target", ",", "String", "ext_target", ")", "{", "return", "new", "CmsFlexRequestDispatcher", "(", "m_controller", ".", "getTopRequest", "(", ")", ".", "getRequestDispatcher", "(", ...
Replacement for the standard servlet API getRequestDispatcher() method.<p> This variation is used if an external file (probably JSP) is dispatched to. This external file must have a "mirror" version, i.e. a file in the OpenCms VFS that represents the external file.<p> @param vfs_target the OpenCms file that is a "mirror" version of the external file @param ext_target the external file (outside the OpenCms VFS) @return the constructed CmsFlexRequestDispatcher
[ "Replacement", "for", "the", "standard", "servlet", "API", "getRequestDispatcher", "()", "method", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/flex/CmsFlexRequest.java#L565-L571
Stratio/cassandra-lucene-index
plugin/src/main/java/com/stratio/cassandra/lucene/common/GeoDistance.java
GeoDistance.parse
@JsonCreator public static GeoDistance parse(String json) { try { String unit = null; for (GeoDistanceUnit geoDistanceUnit : GeoDistanceUnit.values()) { for (String name : geoDistanceUnit.getNames()) { if (json.endsWith(name) && (unit == null || unit.length() < name.length())) { unit = name; } } } if (unit != null) { double value = Double.parseDouble(json.substring(0, json.indexOf(unit))); return new GeoDistance(value, GeoDistanceUnit.create(unit)); } double value = Double.parseDouble(json); return new GeoDistance(value, GeoDistanceUnit.METRES); } catch (Exception e) { throw new IndexException(e, "Unparseable distance: {}", json); } }
java
@JsonCreator public static GeoDistance parse(String json) { try { String unit = null; for (GeoDistanceUnit geoDistanceUnit : GeoDistanceUnit.values()) { for (String name : geoDistanceUnit.getNames()) { if (json.endsWith(name) && (unit == null || unit.length() < name.length())) { unit = name; } } } if (unit != null) { double value = Double.parseDouble(json.substring(0, json.indexOf(unit))); return new GeoDistance(value, GeoDistanceUnit.create(unit)); } double value = Double.parseDouble(json); return new GeoDistance(value, GeoDistanceUnit.METRES); } catch (Exception e) { throw new IndexException(e, "Unparseable distance: {}", json); } }
[ "@", "JsonCreator", "public", "static", "GeoDistance", "parse", "(", "String", "json", ")", "{", "try", "{", "String", "unit", "=", "null", ";", "for", "(", "GeoDistanceUnit", "geoDistanceUnit", ":", "GeoDistanceUnit", ".", "values", "(", ")", ")", "{", "f...
Returns the {@link GeoDistance} represented by the specified JSON {@code String}. @param json A {@code String} containing a JSON encoded {@link GeoDistance}. @return The {@link GeoDistance} represented by the specified JSON {@code String}.
[ "Returns", "the", "{", "@link", "GeoDistance", "}", "represented", "by", "the", "specified", "JSON", "{", "@code", "String", "}", "." ]
train
https://github.com/Stratio/cassandra-lucene-index/blob/a94a4d9af6c25d40e1108729974c35c27c54441c/plugin/src/main/java/com/stratio/cassandra/lucene/common/GeoDistance.java#L73-L93
lessthanoptimal/ejml
main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java
CommonOps_DSCC.permuteRowInv
public static void permuteRowInv(int permInv[], DMatrixSparseCSC input, DMatrixSparseCSC output) { if( input.numRows > permInv.length ) throw new IllegalArgumentException("permutation vector must have at least as many elements as input has rows"); output.reshape(input.numRows,input.numCols,input.nz_length); output.nz_length = input.nz_length; output.indicesSorted = false; System.arraycopy(input.nz_values,0,output.nz_values,0,input.nz_length); System.arraycopy(input.col_idx,0,output.col_idx,0,input.numCols+1); int idx0 = 0; for (int i = 0; i < input.numCols; i++) { int idx1 = output.col_idx[i+1]; for (int j = idx0; j < idx1; j++) { output.nz_rows[j] = permInv[input.nz_rows[j]]; } idx0 = idx1; } }
java
public static void permuteRowInv(int permInv[], DMatrixSparseCSC input, DMatrixSparseCSC output) { if( input.numRows > permInv.length ) throw new IllegalArgumentException("permutation vector must have at least as many elements as input has rows"); output.reshape(input.numRows,input.numCols,input.nz_length); output.nz_length = input.nz_length; output.indicesSorted = false; System.arraycopy(input.nz_values,0,output.nz_values,0,input.nz_length); System.arraycopy(input.col_idx,0,output.col_idx,0,input.numCols+1); int idx0 = 0; for (int i = 0; i < input.numCols; i++) { int idx1 = output.col_idx[i+1]; for (int j = idx0; j < idx1; j++) { output.nz_rows[j] = permInv[input.nz_rows[j]]; } idx0 = idx1; } }
[ "public", "static", "void", "permuteRowInv", "(", "int", "permInv", "[", "]", ",", "DMatrixSparseCSC", "input", ",", "DMatrixSparseCSC", "output", ")", "{", "if", "(", "input", ".", "numRows", ">", "permInv", ".", "length", ")", "throw", "new", "IllegalArgum...
Applies the row permutation specified by the vector to the input matrix and save the results in the output matrix. output[perm[j],:] = input[j,:] @param permInv (Input) Inverse permutation vector. Specifies new order of the rows. @param input (Input) Matrix which is to be permuted @param output (Output) Matrix which has the permutation stored in it. Is reshaped.
[ "Applies", "the", "row", "permutation", "specified", "by", "the", "vector", "to", "the", "input", "matrix", "and", "save", "the", "results", "in", "the", "output", "matrix", ".", "output", "[", "perm", "[", "j", "]", ":", "]", "=", "input", "[", "j", ...
train
https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-dsparse/src/org/ejml/sparse/csc/CommonOps_DSCC.java#L886-L906
Azure/azure-sdk-for-java
sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobStepsInner.java
JobStepsInner.listByVersionWithServiceResponseAsync
public Observable<ServiceResponse<Page<JobStepInner>>> listByVersionWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName, final int jobVersion) { return listByVersionSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName, jobVersion) .concatMap(new Func1<ServiceResponse<Page<JobStepInner>>, Observable<ServiceResponse<Page<JobStepInner>>>>() { @Override public Observable<ServiceResponse<Page<JobStepInner>>> call(ServiceResponse<Page<JobStepInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVersionNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<JobStepInner>>> listByVersionWithServiceResponseAsync(final String resourceGroupName, final String serverName, final String jobAgentName, final String jobName, final int jobVersion) { return listByVersionSinglePageAsync(resourceGroupName, serverName, jobAgentName, jobName, jobVersion) .concatMap(new Func1<ServiceResponse<Page<JobStepInner>>, Observable<ServiceResponse<Page<JobStepInner>>>>() { @Override public Observable<ServiceResponse<Page<JobStepInner>>> call(ServiceResponse<Page<JobStepInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByVersionNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "JobStepInner", ">", ">", ">", "listByVersionWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "serverName", ",", "final", "String", "jobAgentName", ",", ...
Gets all job steps in the specified job version. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param jobAgentName The name of the job agent. @param jobName The name of the job to get. @param jobVersion The version of the job to get. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;JobStepInner&gt; object
[ "Gets", "all", "job", "steps", "in", "the", "specified", "job", "version", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/JobStepsInner.java#L177-L189
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/inject/annotation/AbstractAnnotationMetadataBuilder.java
AbstractAnnotationMetadataBuilder.validateAnnotationValue
protected void validateAnnotationValue(T originatingElement, String annotationName, T member, String memberName, Object resolvedValue) { final AnnotatedElementValidator elementValidator = getElementValidator(); if (elementValidator != null && !erroneousElements.contains(member)) { final boolean shouldValidate = !(annotationName.equals(AliasFor.class.getName())) && (!(resolvedValue instanceof String) || !resolvedValue.toString().contains("${")); if (shouldValidate) { final Set<String> errors = elementValidator.validatedAnnotatedElement(new AnnotatedElement() { AnnotationMetadata metadata = buildDeclared(member); @Nonnull @Override public String getName() { return memberName; } @Override public AnnotationMetadata getAnnotationMetadata() { return metadata; } }, resolvedValue); if (CollectionUtils.isNotEmpty(errors)) { erroneousElements.add(member); for (String error : errors) { error = "@" + NameUtils.getSimpleName(annotationName) + "." + memberName + ": " + error; addError(originatingElement, error); } } } } }
java
protected void validateAnnotationValue(T originatingElement, String annotationName, T member, String memberName, Object resolvedValue) { final AnnotatedElementValidator elementValidator = getElementValidator(); if (elementValidator != null && !erroneousElements.contains(member)) { final boolean shouldValidate = !(annotationName.equals(AliasFor.class.getName())) && (!(resolvedValue instanceof String) || !resolvedValue.toString().contains("${")); if (shouldValidate) { final Set<String> errors = elementValidator.validatedAnnotatedElement(new AnnotatedElement() { AnnotationMetadata metadata = buildDeclared(member); @Nonnull @Override public String getName() { return memberName; } @Override public AnnotationMetadata getAnnotationMetadata() { return metadata; } }, resolvedValue); if (CollectionUtils.isNotEmpty(errors)) { erroneousElements.add(member); for (String error : errors) { error = "@" + NameUtils.getSimpleName(annotationName) + "." + memberName + ": " + error; addError(originatingElement, error); } } } } }
[ "protected", "void", "validateAnnotationValue", "(", "T", "originatingElement", ",", "String", "annotationName", ",", "T", "member", ",", "String", "memberName", ",", "Object", "resolvedValue", ")", "{", "final", "AnnotatedElementValidator", "elementValidator", "=", "...
Validates an annotation value. @param originatingElement The originating element @param annotationName The annotation name @param member The member @param memberName The member name @param resolvedValue The resolved value
[ "Validates", "an", "annotation", "value", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/inject/annotation/AbstractAnnotationMetadataBuilder.java#L266-L297
xdcrafts/flower
flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java
MapDotApi.dotGetMapUnsafe
public static <A, B> Map<A, B> dotGetMapUnsafe(final Map map, final String pathString) { return dotGetUnsafe(map, Map.class, pathString); }
java
public static <A, B> Map<A, B> dotGetMapUnsafe(final Map map, final String pathString) { return dotGetUnsafe(map, Map.class, pathString); }
[ "public", "static", "<", "A", ",", "B", ">", "Map", "<", "A", ",", "B", ">", "dotGetMapUnsafe", "(", "final", "Map", "map", ",", "final", "String", "pathString", ")", "{", "return", "dotGetUnsafe", "(", "map", ",", "Map", ".", "class", ",", "pathStri...
Get map value by path. @param <A> map key type @param <B> map value type @param map subject @param pathString nodes to walk in map @return value
[ "Get", "map", "value", "by", "path", "." ]
train
https://github.com/xdcrafts/flower/blob/96a8e49102fea434bd383a3c7852f0ee9545f999/flower-tools/src/main/java/com/github/xdcrafts/flower/tools/map/MapDotApi.java#L192-L194
apollographql/apollo-android
apollo-runtime/src/main/java/com/apollographql/apollo/internal/ApolloCallTracker.java
ApolloCallTracker.activePrefetchCalls
@NotNull Set<ApolloPrefetch> activePrefetchCalls(@NotNull OperationName operationName) { return activeCalls(activePrefetchCalls, operationName); }
java
@NotNull Set<ApolloPrefetch> activePrefetchCalls(@NotNull OperationName operationName) { return activeCalls(activePrefetchCalls, operationName); }
[ "@", "NotNull", "Set", "<", "ApolloPrefetch", ">", "activePrefetchCalls", "(", "@", "NotNull", "OperationName", "operationName", ")", "{", "return", "activeCalls", "(", "activePrefetchCalls", ",", "operationName", ")", ";", "}" ]
Returns currently active {@link ApolloPrefetch} calls by operation name. @param operationName prefetch operation name @return set of active prefetch calls
[ "Returns", "currently", "active", "{", "@link", "ApolloPrefetch", "}", "calls", "by", "operation", "name", "." ]
train
https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-runtime/src/main/java/com/apollographql/apollo/internal/ApolloCallTracker.java#L113-L115
apache/incubator-zipkin
zipkin/src/main/java/zipkin2/Call.java
Call.flatMap
public final <R> Call<R> flatMap(FlatMapper<V, R> flatMapper) { return new FlatMapping<>(flatMapper, this); }
java
public final <R> Call<R> flatMap(FlatMapper<V, R> flatMapper) { return new FlatMapping<>(flatMapper, this); }
[ "public", "final", "<", "R", ">", "Call", "<", "R", ">", "flatMap", "(", "FlatMapper", "<", "V", ",", "R", ">", "flatMapper", ")", "{", "return", "new", "FlatMapping", "<>", "(", "flatMapper", ",", "this", ")", ";", "}" ]
Maps the result of this call into another, as defined by the {@code flatMapper} function. This is used to chain two remote calls together. For example, you could use this to chain a list IDs call to a get by IDs call. <pre>{@code getTracesCall = getIdsCall.flatMap(ids -> getTraces(ids)); // this would now invoke the chain traces = getTracesCall.enqueue(tracesCallback); }</pre> Cancelation propagates to the mapped call. <p>This method intends to be used for chaining. That means "this" instance should be discarded in favor of the result of this method.
[ "Maps", "the", "result", "of", "this", "call", "into", "another", "as", "defined", "by", "the", "{", "@code", "flatMapper", "}", "function", ".", "This", "is", "used", "to", "chain", "two", "remote", "calls", "together", ".", "For", "example", "you", "co...
train
https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin/src/main/java/zipkin2/Call.java#L110-L112
landawn/AbacusUtil
src/com/landawn/abacus/util/DateUtil.java
DateUtil.addMilliseconds
public static <T extends java.util.Date> T addMilliseconds(final T date, final int amount) { return roll(date, amount, CalendarUnit.MILLISECOND); }
java
public static <T extends java.util.Date> T addMilliseconds(final T date, final int amount) { return roll(date, amount, CalendarUnit.MILLISECOND); }
[ "public", "static", "<", "T", "extends", "java", ".", "util", ".", "Date", ">", "T", "addMilliseconds", "(", "final", "T", "date", ",", "final", "int", "amount", ")", "{", "return", "roll", "(", "date", ",", "amount", ",", "CalendarUnit", ".", "MILLISE...
Adds a number of milliseconds to a date returning a new object. The original {@code Date} is unchanged. @param date the date, not null @param amount the amount to add, may be negative @return the new {@code Date} with the amount added @throws IllegalArgumentException if the date is null
[ "Adds", "a", "number", "of", "milliseconds", "to", "a", "date", "returning", "a", "new", "object", ".", "The", "original", "{", "@code", "Date", "}", "is", "unchanged", "." ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/DateUtil.java#L1049-L1051
opencb/biodata
biodata-formats/src/main/java/org/opencb/biodata/formats/variant/vcf4/VariantVcfFactory.java
VariantVcfFactory.mapToMultiallelicIndex
public static int mapToMultiallelicIndex (int parsedAllele, int numAllele) { int correctedAllele = parsedAllele; if (parsedAllele > 0) { if (parsedAllele == numAllele + 1) { correctedAllele = 1; } else if (parsedAllele < numAllele + 1) { correctedAllele = parsedAllele + 1; } } return correctedAllele; }
java
public static int mapToMultiallelicIndex (int parsedAllele, int numAllele) { int correctedAllele = parsedAllele; if (parsedAllele > 0) { if (parsedAllele == numAllele + 1) { correctedAllele = 1; } else if (parsedAllele < numAllele + 1) { correctedAllele = parsedAllele + 1; } } return correctedAllele; }
[ "public", "static", "int", "mapToMultiallelicIndex", "(", "int", "parsedAllele", ",", "int", "numAllele", ")", "{", "int", "correctedAllele", "=", "parsedAllele", ";", "if", "(", "parsedAllele", ">", "0", ")", "{", "if", "(", "parsedAllele", "==", "numAllele",...
In multiallelic variants, we have a list of alternates, where numAllele is the one whose variant we are parsing now. If we are parsing the first variant (numAllele == 0) A1 refers to first alternative, (i.e. alternateAlleles[0]), A2 to second alternative (alternateAlleles[1]), and so on. However, if numAllele == 1, A1 refers to second alternate (alternateAlleles[1]), A2 to first (alternateAlleles[0]) and higher alleles remain unchanged. Moreover, if NumAllele == 2, A1 is third alternate, A2 is first alternate and A3 is second alternate. It's also assumed that A0 would be the reference, so it remains unchanged too. This pattern of the first allele moving along (and swapping) is what describes this function. Also, look VariantVcfFactory.getSecondaryAlternates(). @param parsedAllele the value of parsed alleles. e.g. 1 if genotype was "A1" (first allele). @param numAllele current variant of the alternates. @return the correct allele index depending on numAllele.
[ "In", "multiallelic", "variants", "we", "have", "a", "list", "of", "alternates", "where", "numAllele", "is", "the", "one", "whose", "variant", "we", "are", "parsing", "now", ".", "If", "we", "are", "parsing", "the", "first", "variant", "(", "numAllele", "=...
train
https://github.com/opencb/biodata/blob/21b3d51d71f578efab908422aca4bab7a73097b1/biodata-formats/src/main/java/org/opencb/biodata/formats/variant/vcf4/VariantVcfFactory.java#L281-L291
Azure/azure-sdk-for-java
compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java
VirtualMachineImagesInner.listOffers
public List<VirtualMachineImageResourceInner> listOffers(String location, String publisherName) { return listOffersWithServiceResponseAsync(location, publisherName).toBlocking().single().body(); }
java
public List<VirtualMachineImageResourceInner> listOffers(String location, String publisherName) { return listOffersWithServiceResponseAsync(location, publisherName).toBlocking().single().body(); }
[ "public", "List", "<", "VirtualMachineImageResourceInner", ">", "listOffers", "(", "String", "location", ",", "String", "publisherName", ")", "{", "return", "listOffersWithServiceResponseAsync", "(", "location", ",", "publisherName", ")", ".", "toBlocking", "(", ")", ...
Gets a list of virtual machine image offers for the specified location and publisher. @param location The name of a supported Azure region. @param publisherName A valid image publisher. @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 List&lt;VirtualMachineImageResourceInner&gt; object if successful.
[ "Gets", "a", "list", "of", "virtual", "machine", "image", "offers", "for", "the", "specified", "location", "and", "publisher", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/compute/resource-manager/v2017_12_01/src/main/java/com/microsoft/azure/management/compute/v2017_12_01/implementation/VirtualMachineImagesInner.java#L402-L404
tomgibara/bits
src/main/java/com/tomgibara/bits/Bits.java
Bits.readerFrom
public static BitReader readerFrom(FileChannel channel, ByteBuffer buffer) { if (channel == null) throw new IllegalArgumentException("null channel"); if (buffer == null) throw new IllegalArgumentException("null buffer"); return new FileChannelBitReader(channel, buffer); }
java
public static BitReader readerFrom(FileChannel channel, ByteBuffer buffer) { if (channel == null) throw new IllegalArgumentException("null channel"); if (buffer == null) throw new IllegalArgumentException("null buffer"); return new FileChannelBitReader(channel, buffer); }
[ "public", "static", "BitReader", "readerFrom", "(", "FileChannel", "channel", ",", "ByteBuffer", "buffer", ")", "{", "if", "(", "channel", "==", "null", ")", "throw", "new", "IllegalArgumentException", "(", "\"null channel\"", ")", ";", "if", "(", "buffer", "=...
A {@link BitReader} that sources bits from a <code>FileChannel</code>. This stream operates with a byte buffer. This will generally improve performance in applications that skip forwards or backwards across the file. Note that using a direct ByteBuffer should generally yield better performance. @param channel the file channel from which bits are to be read @param buffer the buffer used to store file data @return a bit reader over the channel
[ "A", "{", "@link", "BitReader", "}", "that", "sources", "bits", "from", "a", "<code", ">", "FileChannel<", "/", "code", ">", ".", "This", "stream", "operates", "with", "a", "byte", "buffer", ".", "This", "will", "generally", "improve", "performance", "in",...
train
https://github.com/tomgibara/bits/blob/56c32c0a30efd3d7c4e7c6600a0ca39e51eecc97/src/main/java/com/tomgibara/bits/Bits.java#L782-L786
j256/ormlite-core
src/main/java/com/j256/ormlite/stmt/SelectIterator.java
SelectIterator.hasNext
@Override public boolean hasNext() { try { return hasNextThrow(); } catch (SQLException e) { last = null; closeQuietly(); // unfortunately, can't propagate back the SQLException throw new IllegalStateException("Errors getting more results of " + dataClass, e); } }
java
@Override public boolean hasNext() { try { return hasNextThrow(); } catch (SQLException e) { last = null; closeQuietly(); // unfortunately, can't propagate back the SQLException throw new IllegalStateException("Errors getting more results of " + dataClass, e); } }
[ "@", "Override", "public", "boolean", "hasNext", "(", ")", "{", "try", "{", "return", "hasNextThrow", "(", ")", ";", "}", "catch", "(", "SQLException", "e", ")", "{", "last", "=", "null", ";", "closeQuietly", "(", ")", ";", "// unfortunately, can't propaga...
Returns whether or not there are any remaining objects in the table. Can be called before next(). @throws IllegalStateException If there was a problem getting more results via SQL.
[ "Returns", "whether", "or", "not", "there", "are", "any", "remaining", "objects", "in", "the", "table", ".", "Can", "be", "called", "before", "next", "()", "." ]
train
https://github.com/j256/ormlite-core/blob/154d85bbb9614a0ea65a012251257831fb4fba21/src/main/java/com/j256/ormlite/stmt/SelectIterator.java#L98-L108
ReactiveX/RxJavaFX
src/main/java/io/reactivex/rxjavafx/transformers/FxFlowableTransformers.java
FxFlowableTransformers.doOnErrorCount
public static <T> FlowableTransformer<T,T> doOnErrorCount(Consumer<Integer> onError) { return obs -> obs.lift(new FlowableEmissionCounter<>(new CountObserver(null,null,onError))); }
java
public static <T> FlowableTransformer<T,T> doOnErrorCount(Consumer<Integer> onError) { return obs -> obs.lift(new FlowableEmissionCounter<>(new CountObserver(null,null,onError))); }
[ "public", "static", "<", "T", ">", "FlowableTransformer", "<", "T", ",", "T", ">", "doOnErrorCount", "(", "Consumer", "<", "Integer", ">", "onError", ")", "{", "return", "obs", "->", "obs", ".", "lift", "(", "new", "FlowableEmissionCounter", "<>", "(", "...
Performs an action on onError with the provided emission count @param onError @param <T>
[ "Performs", "an", "action", "on", "onError", "with", "the", "provided", "emission", "count" ]
train
https://github.com/ReactiveX/RxJavaFX/blob/8f44d4cc1caba9a8919f01cb1897aaea5514c7e5/src/main/java/io/reactivex/rxjavafx/transformers/FxFlowableTransformers.java#L132-L134