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
sequencelengths
21
714
func_documentation_string
stringlengths
61
1.95k
func_documentation_tokens
sequencelengths
1
482
split_name
stringclasses
1 value
func_code_url
stringlengths
102
309
jcuda/jcuda
JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java
JCudaDriver.cuDeviceComputeCapability
@Deprecated public static int cuDeviceComputeCapability(int major[], int minor[], CUdevice dev) { return checkResult(cuDeviceComputeCapabilityNative(major, minor, dev)); }
java
@Deprecated public static int cuDeviceComputeCapability(int major[], int minor[], CUdevice dev) { return checkResult(cuDeviceComputeCapabilityNative(major, minor, dev)); }
[ "@", "Deprecated", "public", "static", "int", "cuDeviceComputeCapability", "(", "int", "major", "[", "]", ",", "int", "minor", "[", "]", ",", "CUdevice", "dev", ")", "{", "return", "checkResult", "(", "cuDeviceComputeCapabilityNative", "(", "major", ",", "minor", ",", "dev", ")", ")", ";", "}" ]
Returns the compute capability of the device. <pre> CUresult cuDeviceComputeCapability ( int* major, int* minor, CUdevice dev ) </pre> <div> <p>Returns the compute capability of the device. DeprecatedThis function was deprecated as of CUDA 5.0 and its functionality superceded by cuDeviceGetAttribute(). </p> <p>Returns in <tt>*major</tt> and <tt>*minor</tt> the major and minor revision numbers that define the compute capability of the device <tt>dev</tt>. </p> <div> <span>Note:</span> <p>Note that this function may also return error codes from previous, asynchronous launches. </p> </div> </p> </div> @param major Major revision number @param minor Minor revision number @param dev Device handle @return CUDA_SUCCESS, CUDA_ERROR_DEINITIALIZED, CUDA_ERROR_NOT_INITIALIZED, CUDA_ERROR_INVALID_CONTEXT, CUDA_ERROR_INVALID_VALUE, CUDA_ERROR_INVALID_DEVICE @see JCudaDriver#cuDeviceGetAttribute @see JCudaDriver#cuDeviceGetCount @see JCudaDriver#cuDeviceGetName @see JCudaDriver#cuDeviceGet @see JCudaDriver#cuDeviceTotalMem @deprecated Deprecated as of CUDA 5.0, replaced with {@link JCudaDriver#cuDeviceGetAttribute(int[], int, CUdevice)}
[ "Returns", "the", "compute", "capability", "of", "the", "device", "." ]
train
https://github.com/jcuda/jcuda/blob/468528b5b9b37dfceb6ed83fcfd889e9b359f984/JCudaJava/src/main/java/jcuda/driver/JCudaDriver.java#L763-L767
baratine/baratine
kraken/src/main/java/com/caucho/v5/kraken/table/WatchServiceImpl.java
WatchServiceImpl.notifyWatch
@Override public void notifyWatch(TableKraken table, byte []key) { WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.REMOTE); } }
java
@Override public void notifyWatch(TableKraken table, byte []key) { WatchTable watchTable = _tableMap.get(table); if (watchTable != null) { watchTable.onPut(key, TableListener.TypePut.REMOTE); } }
[ "@", "Override", "public", "void", "notifyWatch", "(", "TableKraken", "table", ",", "byte", "[", "]", "key", ")", "{", "WatchTable", "watchTable", "=", "_tableMap", ".", "get", "(", "table", ")", ";", "if", "(", "watchTable", "!=", "null", ")", "{", "watchTable", ".", "onPut", "(", "key", ",", "TableListener", ".", "TypePut", ".", "REMOTE", ")", ";", "}", "}" ]
Notify local and remote watches for the given table and key @param table the table with the updated row @param key the key for the updated row
[ "Notify", "local", "and", "remote", "watches", "for", "the", "given", "table", "and", "key" ]
train
https://github.com/baratine/baratine/blob/db34b45c03c5a5e930d8142acc72319125569fcf/kraken/src/main/java/com/caucho/v5/kraken/table/WatchServiceImpl.java#L212-L220
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.hosting_web_serviceName_cdn_duration_POST
public OvhOrder hosting_web_serviceName_cdn_duration_POST(String serviceName, String duration, OvhCdnOfferEnum offer) throws IOException { String qPath = "/order/hosting/web/{serviceName}/cdn/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "offer", offer); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder hosting_web_serviceName_cdn_duration_POST(String serviceName, String duration, OvhCdnOfferEnum offer) throws IOException { String qPath = "/order/hosting/web/{serviceName}/cdn/{duration}"; StringBuilder sb = path(qPath, serviceName, duration); HashMap<String, Object>o = new HashMap<String, Object>(); addBody(o, "offer", offer); String resp = exec(qPath, "POST", sb.toString(), o); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "hosting_web_serviceName_cdn_duration_POST", "(", "String", "serviceName", ",", "String", "duration", ",", "OvhCdnOfferEnum", "offer", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/hosting/web/{serviceName}/cdn/{duration}\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ",", "serviceName", ",", "duration", ")", ";", "HashMap", "<", "String", ",", "Object", ">", "o", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "addBody", "(", "o", ",", "\"offer\"", ",", "offer", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"POST\"", ",", "sb", ".", "toString", "(", ")", ",", "o", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhOrder", ".", "class", ")", ";", "}" ]
Create order REST: POST /order/hosting/web/{serviceName}/cdn/{duration} @param offer [required] Cdn offers you can add to your hosting @param serviceName [required] The internal name of your hosting @param duration [required] Duration
[ "Create", "order" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L5013-L5020
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/KnowledgeBasesClient.java
KnowledgeBasesClient.createKnowledgeBase
public final KnowledgeBase createKnowledgeBase(ProjectName parent, KnowledgeBase knowledgeBase) { CreateKnowledgeBaseRequest request = CreateKnowledgeBaseRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setKnowledgeBase(knowledgeBase) .build(); return createKnowledgeBase(request); }
java
public final KnowledgeBase createKnowledgeBase(ProjectName parent, KnowledgeBase knowledgeBase) { CreateKnowledgeBaseRequest request = CreateKnowledgeBaseRequest.newBuilder() .setParent(parent == null ? null : parent.toString()) .setKnowledgeBase(knowledgeBase) .build(); return createKnowledgeBase(request); }
[ "public", "final", "KnowledgeBase", "createKnowledgeBase", "(", "ProjectName", "parent", ",", "KnowledgeBase", "knowledgeBase", ")", "{", "CreateKnowledgeBaseRequest", "request", "=", "CreateKnowledgeBaseRequest", ".", "newBuilder", "(", ")", ".", "setParent", "(", "parent", "==", "null", "?", "null", ":", "parent", ".", "toString", "(", ")", ")", ".", "setKnowledgeBase", "(", "knowledgeBase", ")", ".", "build", "(", ")", ";", "return", "createKnowledgeBase", "(", "request", ")", ";", "}" ]
Creates a knowledge base. <p>Sample code: <pre><code> try (KnowledgeBasesClient knowledgeBasesClient = KnowledgeBasesClient.create()) { ProjectName parent = ProjectName.of("[PROJECT]"); KnowledgeBase knowledgeBase = KnowledgeBase.newBuilder().build(); KnowledgeBase response = knowledgeBasesClient.createKnowledgeBase(parent, knowledgeBase); } </code></pre> @param parent Required. The project to create a knowledge base for. Format: `projects/&lt;Project ID&gt;`. @param knowledgeBase Required. The knowledge base to create. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Creates", "a", "knowledge", "base", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2beta1/KnowledgeBasesClient.java#L405-L413
jparsec/jparsec
jparsec/src/main/java/org/jparsec/Parser.java
Parser.ifelse
public final <R> Parser<R> ifelse(Parser<? extends R> consequence, Parser<? extends R> alternative) { return ifelse(__ -> consequence, alternative); }
java
public final <R> Parser<R> ifelse(Parser<? extends R> consequence, Parser<? extends R> alternative) { return ifelse(__ -> consequence, alternative); }
[ "public", "final", "<", "R", ">", "Parser", "<", "R", ">", "ifelse", "(", "Parser", "<", "?", "extends", "R", ">", "consequence", ",", "Parser", "<", "?", "extends", "R", ">", "alternative", ")", "{", "return", "ifelse", "(", "__", "->", "consequence", ",", "alternative", ")", ";", "}" ]
A {@link Parser} that runs {@code consequence} if {@code this} succeeds, or {@code alternative} otherwise.
[ "A", "{" ]
train
https://github.com/jparsec/jparsec/blob/df1280259f5da9eb5ffc537437569dddba66cb94/jparsec/src/main/java/org/jparsec/Parser.java#L447-L449
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java
DisasterRecoveryConfigurationsInner.beginFailoverAllowDataLoss
public void beginFailoverAllowDataLoss(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) { beginFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).toBlocking().single().body(); }
java
public void beginFailoverAllowDataLoss(String resourceGroupName, String serverName, String disasterRecoveryConfigurationName) { beginFailoverAllowDataLossWithServiceResponseAsync(resourceGroupName, serverName, disasterRecoveryConfigurationName).toBlocking().single().body(); }
[ "public", "void", "beginFailoverAllowDataLoss", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "disasterRecoveryConfigurationName", ")", "{", "beginFailoverAllowDataLossWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "disasterRecoveryConfigurationName", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Fails over from the current primary server to this server. This operation might result in data loss. @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 disasterRecoveryConfigurationName The name of the disaster recovery configuration to failover forcefully. @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
[ "Fails", "over", "from", "the", "current", "primary", "server", "to", "this", "server", ".", "This", "operation", "might", "result", "in", "data", "loss", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DisasterRecoveryConfigurationsInner.java#L877-L879
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java
POIUtils.buildNameArea
public static AreaReference buildNameArea(final String sheetName, final Point startPosition, final Point endPosition, SpreadsheetVersion sheetVersion) { ArgUtils.notEmpty(sheetName, "sheetName"); ArgUtils.notNull(startPosition, "startPosition"); ArgUtils.notNull(endPosition, "endPosition"); final CellReference firstRefs = new CellReference(sheetName, startPosition.y, startPosition.x, true, true); final CellReference lastRefs = new CellReference(sheetName, endPosition.y, endPosition.x, true, true); return new AreaReference(firstRefs, lastRefs, sheetVersion); }
java
public static AreaReference buildNameArea(final String sheetName, final Point startPosition, final Point endPosition, SpreadsheetVersion sheetVersion) { ArgUtils.notEmpty(sheetName, "sheetName"); ArgUtils.notNull(startPosition, "startPosition"); ArgUtils.notNull(endPosition, "endPosition"); final CellReference firstRefs = new CellReference(sheetName, startPosition.y, startPosition.x, true, true); final CellReference lastRefs = new CellReference(sheetName, endPosition.y, endPosition.x, true, true); return new AreaReference(firstRefs, lastRefs, sheetVersion); }
[ "public", "static", "AreaReference", "buildNameArea", "(", "final", "String", "sheetName", ",", "final", "Point", "startPosition", ",", "final", "Point", "endPosition", ",", "SpreadsheetVersion", "sheetVersion", ")", "{", "ArgUtils", ".", "notEmpty", "(", "sheetName", ",", "\"sheetName\"", ")", ";", "ArgUtils", ".", "notNull", "(", "startPosition", ",", "\"startPosition\"", ")", ";", "ArgUtils", ".", "notNull", "(", "endPosition", ",", "\"endPosition\"", ")", ";", "final", "CellReference", "firstRefs", "=", "new", "CellReference", "(", "sheetName", ",", "startPosition", ".", "y", ",", "startPosition", ".", "x", ",", "true", ",", "true", ")", ";", "final", "CellReference", "lastRefs", "=", "new", "CellReference", "(", "sheetName", ",", "endPosition", ".", "y", ",", "endPosition", ".", "x", ",", "true", ",", "true", ")", ";", "return", "new", "AreaReference", "(", "firstRefs", ",", "lastRefs", ",", "sheetVersion", ")", ";", "}" ]
名前の範囲の形式を組み立てる。 <code>シート名!$A$1:$A:$5</code> @param sheetName シート名 @param startPosition 設定するセルの開始位置 @param endPosition 設定するセルの終了位置 @param sheetVersion シートの形式 @return
[ "名前の範囲の形式を組み立てる。", "<code", ">", "シート名!$A$1", ":", "$A", ":", "$5<", "/", "code", ">" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/util/POIUtils.java#L847-L858
phoenixnap/springmvc-raml-plugin
src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/helpers/SchemaHelper.java
SchemaHelper.extractTopItem
private static String extractTopItem(String searchString, String schema, int startIdx) { String extracted = null; int propIdx = schema.indexOf("\"properties\"", startIdx); if (propIdx == -1) { propIdx = Integer.MAX_VALUE; } // check for second int idIdx = schema.indexOf("\"" + searchString + "\"", startIdx); int secondIdIdx = schema.indexOf("\"" + searchString + "\"", idIdx + 1); if (secondIdIdx != -1 && propIdx > secondIdIdx) { idIdx = secondIdIdx; } if (idIdx != -1 && propIdx > idIdx) { // make sure we're not in a nested // id // find the 1st and second " after the idx int valueStartIdx = schema.indexOf("\"", idIdx + (searchString.length() + 2)); int valueEndIdx = schema.indexOf("\"", valueStartIdx + 1); extracted = schema.substring(valueStartIdx + 1, valueEndIdx); } return extracted; }
java
private static String extractTopItem(String searchString, String schema, int startIdx) { String extracted = null; int propIdx = schema.indexOf("\"properties\"", startIdx); if (propIdx == -1) { propIdx = Integer.MAX_VALUE; } // check for second int idIdx = schema.indexOf("\"" + searchString + "\"", startIdx); int secondIdIdx = schema.indexOf("\"" + searchString + "\"", idIdx + 1); if (secondIdIdx != -1 && propIdx > secondIdIdx) { idIdx = secondIdIdx; } if (idIdx != -1 && propIdx > idIdx) { // make sure we're not in a nested // id // find the 1st and second " after the idx int valueStartIdx = schema.indexOf("\"", idIdx + (searchString.length() + 2)); int valueEndIdx = schema.indexOf("\"", valueStartIdx + 1); extracted = schema.substring(valueStartIdx + 1, valueEndIdx); } return extracted; }
[ "private", "static", "String", "extractTopItem", "(", "String", "searchString", ",", "String", "schema", ",", "int", "startIdx", ")", "{", "String", "extracted", "=", "null", ";", "int", "propIdx", "=", "schema", ".", "indexOf", "(", "\"\\\"properties\\\"\"", ",", "startIdx", ")", ";", "if", "(", "propIdx", "==", "-", "1", ")", "{", "propIdx", "=", "Integer", ".", "MAX_VALUE", ";", "}", "// check for second", "int", "idIdx", "=", "schema", ".", "indexOf", "(", "\"\\\"\"", "+", "searchString", "+", "\"\\\"\"", ",", "startIdx", ")", ";", "int", "secondIdIdx", "=", "schema", ".", "indexOf", "(", "\"\\\"\"", "+", "searchString", "+", "\"\\\"\"", ",", "idIdx", "+", "1", ")", ";", "if", "(", "secondIdIdx", "!=", "-", "1", "&&", "propIdx", ">", "secondIdIdx", ")", "{", "idIdx", "=", "secondIdIdx", ";", "}", "if", "(", "idIdx", "!=", "-", "1", "&&", "propIdx", ">", "idIdx", ")", "{", "// make sure we're not in a nested", "// id", "// find the 1st and second \" after the idx", "int", "valueStartIdx", "=", "schema", ".", "indexOf", "(", "\"\\\"\"", ",", "idIdx", "+", "(", "searchString", ".", "length", "(", ")", "+", "2", ")", ")", ";", "int", "valueEndIdx", "=", "schema", ".", "indexOf", "(", "\"\\\"\"", ",", "valueStartIdx", "+", "1", ")", ";", "extracted", "=", "schema", ".", "substring", "(", "valueStartIdx", "+", "1", ",", "valueEndIdx", ")", ";", "}", "return", "extracted", ";", "}" ]
Extracts the value of a specified parameter in a schema @param searchString element to search for @param schema Schema as a string @return the value or null if not found
[ "Extracts", "the", "value", "of", "a", "specified", "parameter", "in", "a", "schema" ]
train
https://github.com/phoenixnap/springmvc-raml-plugin/blob/6387072317cd771eb7d6f30943f556ac20dd3c84/src/main/java/com/phoenixnap/oss/ramlplugin/raml2code/helpers/SchemaHelper.java#L261-L281
cdk/cdk
tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomTetrahedralLigandPlacer3D.java
AtomTetrahedralLigandPlacer3D.getPlacedAtomsInAtomContainer
public IAtomContainer getPlacedAtomsInAtomContainer(IAtom atom, IAtomContainer ac) { List bonds = ac.getConnectedBondsList(atom); IAtomContainer connectedAtoms = atom.getBuilder().newInstance(IAtomContainer.class); IAtom connectedAtom = null; for (int i = 0; i < bonds.size(); i++) { connectedAtom = ((IBond) bonds.get(i)).getOther(atom); if (connectedAtom.getFlag(CDKConstants.ISPLACED)) { connectedAtoms.addAtom(connectedAtom); } } return connectedAtoms; }
java
public IAtomContainer getPlacedAtomsInAtomContainer(IAtom atom, IAtomContainer ac) { List bonds = ac.getConnectedBondsList(atom); IAtomContainer connectedAtoms = atom.getBuilder().newInstance(IAtomContainer.class); IAtom connectedAtom = null; for (int i = 0; i < bonds.size(); i++) { connectedAtom = ((IBond) bonds.get(i)).getOther(atom); if (connectedAtom.getFlag(CDKConstants.ISPLACED)) { connectedAtoms.addAtom(connectedAtom); } } return connectedAtoms; }
[ "public", "IAtomContainer", "getPlacedAtomsInAtomContainer", "(", "IAtom", "atom", ",", "IAtomContainer", "ac", ")", "{", "List", "bonds", "=", "ac", ".", "getConnectedBondsList", "(", "atom", ")", ";", "IAtomContainer", "connectedAtoms", "=", "atom", ".", "getBuilder", "(", ")", ".", "newInstance", "(", "IAtomContainer", ".", "class", ")", ";", "IAtom", "connectedAtom", "=", "null", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bonds", ".", "size", "(", ")", ";", "i", "++", ")", "{", "connectedAtom", "=", "(", "(", "IBond", ")", "bonds", ".", "get", "(", "i", ")", ")", ".", "getOther", "(", "atom", ")", ";", "if", "(", "connectedAtom", ".", "getFlag", "(", "CDKConstants", ".", "ISPLACED", ")", ")", "{", "connectedAtoms", ".", "addAtom", "(", "connectedAtom", ")", ";", "}", "}", "return", "connectedAtoms", ";", "}" ]
Gets all placed neighbouring atoms of a atom. @param atom central atom (Atom) @param ac the molecule @return all connected and placed atoms to the central atom ((AtomContainer)
[ "Gets", "all", "placed", "neighbouring", "atoms", "of", "a", "atom", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/tool/builder3d/src/main/java/org/openscience/cdk/modeling/builder3d/AtomTetrahedralLigandPlacer3D.java#L816-L828
kcthota/emoji4j
src/main/java/emoji4j/AbstractEmoji.java
AbstractEmoji.htmlifyHelper
protected static String htmlifyHelper(String text, boolean isHex, boolean isSurrogate) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < text.length(); i++) { int ch = text.codePointAt(i); if (ch <= 128) { sb.appendCodePoint(ch); } else if (ch > 128 && (ch < 159 || (ch >= 55296 && ch <= 57343))) { // don't write illegal html characters // refer // http://en.wikipedia.org/wiki/Character_encodings_in_HTML // Illegal characters section continue; } else { if (isHex) { sb.append("&#x" + Integer.toHexString(ch) + ";"); } else { if(isSurrogate) { double H = Math.floor((ch - 0x10000) / 0x400) + 0xD800; double L = ((ch - 0x10000) % 0x400) + 0xDC00; sb.append("&#"+String.format("%.0f", H)+";&#"+String.format("%.0f", L)+";"); } else { sb.append("&#" + ch + ";"); } } } } return sb.toString(); }
java
protected static String htmlifyHelper(String text, boolean isHex, boolean isSurrogate) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < text.length(); i++) { int ch = text.codePointAt(i); if (ch <= 128) { sb.appendCodePoint(ch); } else if (ch > 128 && (ch < 159 || (ch >= 55296 && ch <= 57343))) { // don't write illegal html characters // refer // http://en.wikipedia.org/wiki/Character_encodings_in_HTML // Illegal characters section continue; } else { if (isHex) { sb.append("&#x" + Integer.toHexString(ch) + ";"); } else { if(isSurrogate) { double H = Math.floor((ch - 0x10000) / 0x400) + 0xD800; double L = ((ch - 0x10000) % 0x400) + 0xDC00; sb.append("&#"+String.format("%.0f", H)+";&#"+String.format("%.0f", L)+";"); } else { sb.append("&#" + ch + ";"); } } } } return sb.toString(); }
[ "protected", "static", "String", "htmlifyHelper", "(", "String", "text", ",", "boolean", "isHex", ",", "boolean", "isSurrogate", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "text", ".", "length", "(", ")", ";", "i", "++", ")", "{", "int", "ch", "=", "text", ".", "codePointAt", "(", "i", ")", ";", "if", "(", "ch", "<=", "128", ")", "{", "sb", ".", "appendCodePoint", "(", "ch", ")", ";", "}", "else", "if", "(", "ch", ">", "128", "&&", "(", "ch", "<", "159", "||", "(", "ch", ">=", "55296", "&&", "ch", "<=", "57343", ")", ")", ")", "{", "// don't write illegal html characters", "// refer", "// http://en.wikipedia.org/wiki/Character_encodings_in_HTML", "// Illegal characters section", "continue", ";", "}", "else", "{", "if", "(", "isHex", ")", "{", "sb", ".", "append", "(", "\"&#x\"", "+", "Integer", ".", "toHexString", "(", "ch", ")", "+", "\";\"", ")", ";", "}", "else", "{", "if", "(", "isSurrogate", ")", "{", "double", "H", "=", "Math", ".", "floor", "(", "(", "ch", "-", "0x10000", ")", "/", "0x400", ")", "+", "0xD800", ";", "double", "L", "=", "(", "(", "ch", "-", "0x10000", ")", "%", "0x400", ")", "+", "0xDC00", ";", "sb", ".", "append", "(", "\"&#\"", "+", "String", ".", "format", "(", "\"%.0f\"", ",", "H", ")", "+", "\";&#\"", "+", "String", ".", "format", "(", "\"%.0f\"", ",", "L", ")", "+", "\";\"", ")", ";", "}", "else", "{", "sb", ".", "append", "(", "\"&#\"", "+", "ch", "+", "\";\"", ")", ";", "}", "}", "}", "}", "return", "sb", ".", "toString", "(", ")", ";", "}" ]
Helper to convert emoji characters to html entities in a string @param text String to htmlify @param isHex isHex @return htmlified string
[ "Helper", "to", "convert", "emoji", "characters", "to", "html", "entities", "in", "a", "string" ]
train
https://github.com/kcthota/emoji4j/blob/b8cc0c60b8d804cfd7f3369689576b9a93ea1e6f/src/main/java/emoji4j/AbstractEmoji.java#L29-L61
operasoftware/operaprestodriver
src/com/opera/core/systems/scope/WaitState.java
WaitState.pollResultItem
private ResultItem pollResultItem(long timeout, boolean idle) { ResultItem result = getResult(); if (result != null) { result.remainingIdleTimeout = timeout; } if (result == null && timeout > 0) { long start = System.currentTimeMillis(); internalWait(timeout); long end = System.currentTimeMillis(); result = getResult(); if (result != null) { result.remainingIdleTimeout = timeout - (end - start); logger.finest("Remaining timeout: " + result.remainingIdleTimeout); } } if (result == null) { if (idle) { throw new ResponseNotReceivedException("No idle response in a timely fashion"); } else { throw new ResponseNotReceivedException("No response in a timely fashion"); } } return result; }
java
private ResultItem pollResultItem(long timeout, boolean idle) { ResultItem result = getResult(); if (result != null) { result.remainingIdleTimeout = timeout; } if (result == null && timeout > 0) { long start = System.currentTimeMillis(); internalWait(timeout); long end = System.currentTimeMillis(); result = getResult(); if (result != null) { result.remainingIdleTimeout = timeout - (end - start); logger.finest("Remaining timeout: " + result.remainingIdleTimeout); } } if (result == null) { if (idle) { throw new ResponseNotReceivedException("No idle response in a timely fashion"); } else { throw new ResponseNotReceivedException("No response in a timely fashion"); } } return result; }
[ "private", "ResultItem", "pollResultItem", "(", "long", "timeout", ",", "boolean", "idle", ")", "{", "ResultItem", "result", "=", "getResult", "(", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "result", ".", "remainingIdleTimeout", "=", "timeout", ";", "}", "if", "(", "result", "==", "null", "&&", "timeout", ">", "0", ")", "{", "long", "start", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "internalWait", "(", "timeout", ")", ";", "long", "end", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "result", "=", "getResult", "(", ")", ";", "if", "(", "result", "!=", "null", ")", "{", "result", ".", "remainingIdleTimeout", "=", "timeout", "-", "(", "end", "-", "start", ")", ";", "logger", ".", "finest", "(", "\"Remaining timeout: \"", "+", "result", ".", "remainingIdleTimeout", ")", ";", "}", "}", "if", "(", "result", "==", "null", ")", "{", "if", "(", "idle", ")", "{", "throw", "new", "ResponseNotReceivedException", "(", "\"No idle response in a timely fashion\"", ")", ";", "}", "else", "{", "throw", "new", "ResponseNotReceivedException", "(", "\"No response in a timely fashion\"", ")", ";", "}", "}", "return", "result", ";", "}" ]
Checks for a result item. <p/> If no result item is available this method will wait for timeout milliseconds and try again. If still no result if available then a ResponseNotReceivedException is thrown. @param timeout time in milliseconds to wait before retrying. @param idle whether you are waiting for an Idle event. Changes error message. @return the result
[ "Checks", "for", "a", "result", "item", ".", "<p", "/", ">", "If", "no", "result", "item", "is", "available", "this", "method", "will", "wait", "for", "timeout", "milliseconds", "and", "try", "again", ".", "If", "still", "no", "result", "if", "available", "then", "a", "ResponseNotReceivedException", "is", "thrown", "." ]
train
https://github.com/operasoftware/operaprestodriver/blob/1ccceda80f1c1a0489171d17dcaa6e7b18fb4c01/src/com/opera/core/systems/scope/WaitState.java#L428-L454
eurekaclinical/eurekaclinical-common
src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java
EurekaClinicalClient.doPost
protected <T> T doPost(String path, MultivaluedMap<String, String> formParams, GenericType<T> genericType) throws ClientException { return doPost(path, formParams, genericType, null); }
java
protected <T> T doPost(String path, MultivaluedMap<String, String> formParams, GenericType<T> genericType) throws ClientException { return doPost(path, formParams, genericType, null); }
[ "protected", "<", "T", ">", "T", "doPost", "(", "String", "path", ",", "MultivaluedMap", "<", "String", ",", "String", ">", "formParams", ",", "GenericType", "<", "T", ">", "genericType", ")", "throws", "ClientException", "{", "return", "doPost", "(", "path", ",", "formParams", ",", "genericType", ",", "null", ")", ";", "}" ]
Submits a form and gets back a JSON object. Adds appropriate Accepts and Content Type headers. @param <T> the type of object that is expected in the response. @param path the API to call. @param formParams the form parameters to send. @param genericType the type of object that is expected in the response. @return the object in the response. @throws ClientException if a status code other than 200 (OK) is returned.
[ "Submits", "a", "form", "and", "gets", "back", "a", "JSON", "object", ".", "Adds", "appropriate", "Accepts", "and", "Content", "Type", "headers", "." ]
train
https://github.com/eurekaclinical/eurekaclinical-common/blob/1867102ff43fe94e519f76a074d5f5923e9be61c/src/main/java/org/eurekaclinical/common/comm/clients/EurekaClinicalClient.java#L487-L489
OpenBEL/openbel-framework
org.openbel.framework.common/src/main/java/org/openbel/framework/common/protonetwork/model/ProtoNodeTable.java
ProtoNodeTable.addNode
public Integer addNode(final int termIndex, final String label) { if (label == null) { throw new InvalidArgument("label", label); } // if we have already seen this term index, return Integer visitedIndex = termNodeIndex.get(termIndex); if (visitedIndex != null) { return visitedIndex; } // add this new proto node int pnIndex = protoNodes.size(); protoNodes.add(label); // bi-directionally map term index to node index termNodeIndex.put(termIndex, pnIndex); nodeTermIndex.put(pnIndex, termIndex); getEquivalences().put(pnIndex, getEquivalences().size()); return pnIndex; }
java
public Integer addNode(final int termIndex, final String label) { if (label == null) { throw new InvalidArgument("label", label); } // if we have already seen this term index, return Integer visitedIndex = termNodeIndex.get(termIndex); if (visitedIndex != null) { return visitedIndex; } // add this new proto node int pnIndex = protoNodes.size(); protoNodes.add(label); // bi-directionally map term index to node index termNodeIndex.put(termIndex, pnIndex); nodeTermIndex.put(pnIndex, termIndex); getEquivalences().put(pnIndex, getEquivalences().size()); return pnIndex; }
[ "public", "Integer", "addNode", "(", "final", "int", "termIndex", ",", "final", "String", "label", ")", "{", "if", "(", "label", "==", "null", ")", "{", "throw", "new", "InvalidArgument", "(", "\"label\"", ",", "label", ")", ";", "}", "// if we have already seen this term index, return", "Integer", "visitedIndex", "=", "termNodeIndex", ".", "get", "(", "termIndex", ")", ";", "if", "(", "visitedIndex", "!=", "null", ")", "{", "return", "visitedIndex", ";", "}", "// add this new proto node", "int", "pnIndex", "=", "protoNodes", ".", "size", "(", ")", ";", "protoNodes", ".", "add", "(", "label", ")", ";", "// bi-directionally map term index to node index", "termNodeIndex", ".", "put", "(", "termIndex", ",", "pnIndex", ")", ";", "nodeTermIndex", ".", "put", "(", "pnIndex", ",", "termIndex", ")", ";", "getEquivalences", "(", ")", ".", "put", "(", "pnIndex", ",", "getEquivalences", "(", ")", ".", "size", "(", ")", ")", ";", "return", "pnIndex", ";", "}" ]
Adds a proto node {@link String label} for a specific {@link Integer term index}. If the {@link Integer term index} has already been added then its {@link Integer proto node index} will be returned. <p> This operation maintains the {@link Map map} of term index to node index. </p> @param termIndex {@link Integer} the term index created from the addition to the {@link TermTable term table} @param label {@link String} the placeholder label from the {@link TermTable term table} @return the {@link Integer proto node index} @throws InvalidArgument Thrown if {@code label} is {@code null}
[ "Adds", "a", "proto", "node", "{", "@link", "String", "label", "}", "for", "a", "specific", "{", "@link", "Integer", "term", "index", "}", ".", "If", "the", "{", "@link", "Integer", "term", "index", "}", "has", "already", "been", "added", "then", "its", "{", "@link", "Integer", "proto", "node", "index", "}", "will", "be", "returned", ".", "<p", ">", "This", "operation", "maintains", "the", "{", "@link", "Map", "map", "}", "of", "term", "index", "to", "node", "index", ".", "<", "/", "p", ">" ]
train
https://github.com/OpenBEL/openbel-framework/blob/149f80b1d6eabb15ab15815b6f745b0afa9fd2d3/org.openbel.framework.common/src/main/java/org/openbel/framework/common/protonetwork/model/ProtoNodeTable.java#L112-L133
BorderTech/wcomponents
wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WEditableImageRenderer.java
WEditableImageRenderer.doRender
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WEditableImage editableImage = (WEditableImage) component; XmlStringBuilder xml = renderContext.getWriter(); // No image set if (editableImage.getImage() == null && editableImage.getImageUrl() == null) { return; } WImageRenderer.renderTagOpen(editableImage, xml); WComponent uploader = editableImage.getEditUploader(); if (uploader != null) { xml.appendAttribute("data-wc-editor", uploader.getId()); } xml.appendEnd(); }
java
@Override public void doRender(final WComponent component, final WebXmlRenderContext renderContext) { WEditableImage editableImage = (WEditableImage) component; XmlStringBuilder xml = renderContext.getWriter(); // No image set if (editableImage.getImage() == null && editableImage.getImageUrl() == null) { return; } WImageRenderer.renderTagOpen(editableImage, xml); WComponent uploader = editableImage.getEditUploader(); if (uploader != null) { xml.appendAttribute("data-wc-editor", uploader.getId()); } xml.appendEnd(); }
[ "@", "Override", "public", "void", "doRender", "(", "final", "WComponent", "component", ",", "final", "WebXmlRenderContext", "renderContext", ")", "{", "WEditableImage", "editableImage", "=", "(", "WEditableImage", ")", "component", ";", "XmlStringBuilder", "xml", "=", "renderContext", ".", "getWriter", "(", ")", ";", "// No image set", "if", "(", "editableImage", ".", "getImage", "(", ")", "==", "null", "&&", "editableImage", ".", "getImageUrl", "(", ")", "==", "null", ")", "{", "return", ";", "}", "WImageRenderer", ".", "renderTagOpen", "(", "editableImage", ",", "xml", ")", ";", "WComponent", "uploader", "=", "editableImage", ".", "getEditUploader", "(", ")", ";", "if", "(", "uploader", "!=", "null", ")", "{", "xml", ".", "appendAttribute", "(", "\"data-wc-editor\"", ",", "uploader", ".", "getId", "(", ")", ")", ";", "}", "xml", ".", "appendEnd", "(", ")", ";", "}" ]
Paints the given {@link WEditableImage}. @param component the WEditableImage to paint. @param renderContext the RenderContext to paint to.
[ "Paints", "the", "given", "{", "@link", "WEditableImage", "}", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/render/webxml/WEditableImageRenderer.java#L23-L39
OpenLiberty/open-liberty
dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanLifeCycleInfo.java
TEBeanLifeCycleInfo.traceBeanState
public static void traceBeanState(int oldState, String oldString, int newState, String newString) // d167264 { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { StringBuffer sbuf = new StringBuffer(); sbuf .append(BeanLifeCycle_State_Type_Str).append(DataDelimiter) .append(BeanLifeCycle_State_Type).append(DataDelimiter) .append(oldState).append(DataDelimiter) // d167264 .append(oldString).append(DataDelimiter) // d167264 .append(newState).append(DataDelimiter) // d167264 .append(newString).append(DataDelimiter) // d167264 ; Tr.debug(tc, sbuf.toString()); } }
java
public static void traceBeanState(int oldState, String oldString, int newState, String newString) // d167264 { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { StringBuffer sbuf = new StringBuffer(); sbuf .append(BeanLifeCycle_State_Type_Str).append(DataDelimiter) .append(BeanLifeCycle_State_Type).append(DataDelimiter) .append(oldState).append(DataDelimiter) // d167264 .append(oldString).append(DataDelimiter) // d167264 .append(newState).append(DataDelimiter) // d167264 .append(newString).append(DataDelimiter) // d167264 ; Tr.debug(tc, sbuf.toString()); } }
[ "public", "static", "void", "traceBeanState", "(", "int", "oldState", ",", "String", "oldString", ",", "int", "newState", ",", "String", "newString", ")", "// d167264", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isDebugEnabled", "(", ")", ")", "{", "StringBuffer", "sbuf", "=", "new", "StringBuffer", "(", ")", ";", "sbuf", ".", "append", "(", "BeanLifeCycle_State_Type_Str", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "BeanLifeCycle_State_Type", ")", ".", "append", "(", "DataDelimiter", ")", ".", "append", "(", "oldState", ")", ".", "append", "(", "DataDelimiter", ")", "// d167264", ".", "append", "(", "oldString", ")", ".", "append", "(", "DataDelimiter", ")", "// d167264", ".", "append", "(", "newState", ")", ".", "append", "(", "DataDelimiter", ")", "// d167264", ".", "append", "(", "newString", ")", ".", "append", "(", "DataDelimiter", ")", "// d167264", ";", "Tr", ".", "debug", "(", "tc", ",", "sbuf", ".", "toString", "(", ")", ")", ";", "}", "}" ]
This is called by the EJB container server code to write a ejb bean state record to the trace log, if enabled.
[ "This", "is", "called", "by", "the", "EJB", "container", "server", "code", "to", "write", "a", "ejb", "bean", "state", "record", "to", "the", "trace", "log", "if", "enabled", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ws/traceinfo/ejbcontainer/TEBeanLifeCycleInfo.java#L68-L85
jbundle/jbundle
base/base/src/main/java/org/jbundle/base/db/QueryRecord.java
QueryRecord.addRelationship
public void addRelationship(int linkType, Record recLeft, Record recRight, String fldLeft1, String fldRight1, String fldLeft2, String fldRight2, String fldLeft3, String fldRight3) { new TableLink(this, linkType, recLeft, recRight, fldLeft1, fldRight1, fldLeft2, fldRight2, fldLeft3, fldRight3); }
java
public void addRelationship(int linkType, Record recLeft, Record recRight, String fldLeft1, String fldRight1, String fldLeft2, String fldRight2, String fldLeft3, String fldRight3) { new TableLink(this, linkType, recLeft, recRight, fldLeft1, fldRight1, fldLeft2, fldRight2, fldLeft3, fldRight3); }
[ "public", "void", "addRelationship", "(", "int", "linkType", ",", "Record", "recLeft", ",", "Record", "recRight", ",", "String", "fldLeft1", ",", "String", "fldRight1", ",", "String", "fldLeft2", ",", "String", "fldRight2", ",", "String", "fldLeft3", ",", "String", "fldRight3", ")", "{", "new", "TableLink", "(", "this", ",", "linkType", ",", "recLeft", ",", "recRight", ",", "fldLeft1", ",", "fldRight1", ",", "fldLeft2", ",", "fldRight2", ",", "fldLeft3", ",", "fldRight3", ")", ";", "}" ]
Add this table link to this query. Creates a new tablelink and adds it to the link list.
[ "Add", "this", "table", "link", "to", "this", "query", ".", "Creates", "a", "new", "tablelink", "and", "adds", "it", "to", "the", "link", "list", "." ]
train
https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/base/src/main/java/org/jbundle/base/db/QueryRecord.java#L176-L179
igniterealtime/Smack
smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java
AgentSession.getAgentHistory
public AgentChatHistory getAgentHistory(EntityBareJid jid, int maxSessions, Date startDate) throws XMPPException, NotConnectedException, InterruptedException { AgentChatHistory request; if (startDate != null) { request = new AgentChatHistory(jid, maxSessions, startDate); } else { request = new AgentChatHistory(jid, maxSessions); } request.setType(IQ.Type.get); request.setTo(workgroupJID); AgentChatHistory response = connection.createStanzaCollectorAndSend( request).nextResult(); return response; }
java
public AgentChatHistory getAgentHistory(EntityBareJid jid, int maxSessions, Date startDate) throws XMPPException, NotConnectedException, InterruptedException { AgentChatHistory request; if (startDate != null) { request = new AgentChatHistory(jid, maxSessions, startDate); } else { request = new AgentChatHistory(jid, maxSessions); } request.setType(IQ.Type.get); request.setTo(workgroupJID); AgentChatHistory response = connection.createStanzaCollectorAndSend( request).nextResult(); return response; }
[ "public", "AgentChatHistory", "getAgentHistory", "(", "EntityBareJid", "jid", ",", "int", "maxSessions", ",", "Date", "startDate", ")", "throws", "XMPPException", ",", "NotConnectedException", ",", "InterruptedException", "{", "AgentChatHistory", "request", ";", "if", "(", "startDate", "!=", "null", ")", "{", "request", "=", "new", "AgentChatHistory", "(", "jid", ",", "maxSessions", ",", "startDate", ")", ";", "}", "else", "{", "request", "=", "new", "AgentChatHistory", "(", "jid", ",", "maxSessions", ")", ";", "}", "request", ".", "setType", "(", "IQ", ".", "Type", ".", "get", ")", ";", "request", ".", "setTo", "(", "workgroupJID", ")", ";", "AgentChatHistory", "response", "=", "connection", ".", "createStanzaCollectorAndSend", "(", "request", ")", ".", "nextResult", "(", ")", ";", "return", "response", ";", "}" ]
Retrieves the AgentChatHistory associated with a particular agent jid. @param jid the jid of the agent. @param maxSessions the max number of sessions to retrieve. @param startDate point in time from which on history should get retrieved. @return the chat history associated with a given jid. @throws XMPPException if an error occurs while retrieving the AgentChatHistory. @throws NotConnectedException @throws InterruptedException
[ "Retrieves", "the", "AgentChatHistory", "associated", "with", "a", "particular", "agent", "jid", "." ]
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-legacy/src/main/java/org/jivesoftware/smackx/workgroup/agent/AgentSession.java#L896-L912
jhunters/jprotobuf
src/main/java/com/baidu/bjf/remoting/protobuf/code/CodedConstant.java
CodedConstant.getRequiredCheck
public static String getRequiredCheck(int order, Field field) { String fieldName = getFieldName(order); String code = "if (" + fieldName + "== null) {\n"; code += "throw new UninitializedMessageException(CodedConstant.asList(\"" + field.getName() + "\"))" + ClassCode.JAVA_LINE_BREAK; code += "}\n"; return code; }
java
public static String getRequiredCheck(int order, Field field) { String fieldName = getFieldName(order); String code = "if (" + fieldName + "== null) {\n"; code += "throw new UninitializedMessageException(CodedConstant.asList(\"" + field.getName() + "\"))" + ClassCode.JAVA_LINE_BREAK; code += "}\n"; return code; }
[ "public", "static", "String", "getRequiredCheck", "(", "int", "order", ",", "Field", "field", ")", "{", "String", "fieldName", "=", "getFieldName", "(", "order", ")", ";", "String", "code", "=", "\"if (\"", "+", "fieldName", "+", "\"== null) {\\n\"", ";", "code", "+=", "\"throw new UninitializedMessageException(CodedConstant.asList(\\\"\"", "+", "field", ".", "getName", "(", ")", "+", "\"\\\"))\"", "+", "ClassCode", ".", "JAVA_LINE_BREAK", ";", "code", "+=", "\"}\\n\"", ";", "return", "code", ";", "}" ]
get required field check java expression. @param order field order @param field java field @return full java expression
[ "get", "required", "field", "check", "java", "expression", "." ]
train
https://github.com/jhunters/jprotobuf/blob/55832c9b4792afb128e5b35139d8a3891561d8a3/src/main/java/com/baidu/bjf/remoting/protobuf/code/CodedConstant.java#L477-L485
lessthanoptimal/BoofCV
examples/src/main/java/boofcv/examples/features/ExampleFeatureSurf.java
ExampleFeatureSurf.harder
public static <II extends ImageGray<II>> void harder(GrayF32 image ) { // SURF works off of integral images Class<II> integralType = GIntegralImageOps.getIntegralType(GrayF32.class); // define the feature detection algorithm NonMaxSuppression extractor = FactoryFeatureExtractor.nonmax(new ConfigExtract(2, 0, 5, true)); FastHessianFeatureDetector<II> detector = new FastHessianFeatureDetector<>(extractor, 200, 2, 9, 4, 4, 6); // estimate orientation OrientationIntegral<II> orientation = FactoryOrientationAlgs.sliding_ii(null, integralType); DescribePointSurf<II> descriptor = FactoryDescribePointAlgs.<II>surfStability(null,integralType); // compute the integral image of 'image' II integral = GeneralizedImageOps.createSingleBand(integralType,image.width,image.height); GIntegralImageOps.transform(image, integral); // detect fast hessian features detector.detect(integral); // tell algorithms which image to process orientation.setImage(integral); descriptor.setImage(integral); List<ScalePoint> points = detector.getFoundPoints(); List<BrightFeature> descriptions = new ArrayList<>(); for( ScalePoint p : points ) { // estimate orientation orientation.setObjectRadius( p.scale*BoofDefaults.SURF_SCALE_TO_RADIUS); double angle = orientation.compute(p.x,p.y); // extract the SURF description for this region BrightFeature desc = descriptor.createDescription(); descriptor.describe(p.x,p.y,angle,p.scale,desc); // save everything for processing later on descriptions.add(desc); } System.out.println("Found Features: "+points.size()); System.out.println("First descriptor's first value: "+descriptions.get(0).value[0]); }
java
public static <II extends ImageGray<II>> void harder(GrayF32 image ) { // SURF works off of integral images Class<II> integralType = GIntegralImageOps.getIntegralType(GrayF32.class); // define the feature detection algorithm NonMaxSuppression extractor = FactoryFeatureExtractor.nonmax(new ConfigExtract(2, 0, 5, true)); FastHessianFeatureDetector<II> detector = new FastHessianFeatureDetector<>(extractor, 200, 2, 9, 4, 4, 6); // estimate orientation OrientationIntegral<II> orientation = FactoryOrientationAlgs.sliding_ii(null, integralType); DescribePointSurf<II> descriptor = FactoryDescribePointAlgs.<II>surfStability(null,integralType); // compute the integral image of 'image' II integral = GeneralizedImageOps.createSingleBand(integralType,image.width,image.height); GIntegralImageOps.transform(image, integral); // detect fast hessian features detector.detect(integral); // tell algorithms which image to process orientation.setImage(integral); descriptor.setImage(integral); List<ScalePoint> points = detector.getFoundPoints(); List<BrightFeature> descriptions = new ArrayList<>(); for( ScalePoint p : points ) { // estimate orientation orientation.setObjectRadius( p.scale*BoofDefaults.SURF_SCALE_TO_RADIUS); double angle = orientation.compute(p.x,p.y); // extract the SURF description for this region BrightFeature desc = descriptor.createDescription(); descriptor.describe(p.x,p.y,angle,p.scale,desc); // save everything for processing later on descriptions.add(desc); } System.out.println("Found Features: "+points.size()); System.out.println("First descriptor's first value: "+descriptions.get(0).value[0]); }
[ "public", "static", "<", "II", "extends", "ImageGray", "<", "II", ">", ">", "void", "harder", "(", "GrayF32", "image", ")", "{", "// SURF works off of integral images", "Class", "<", "II", ">", "integralType", "=", "GIntegralImageOps", ".", "getIntegralType", "(", "GrayF32", ".", "class", ")", ";", "// define the feature detection algorithm", "NonMaxSuppression", "extractor", "=", "FactoryFeatureExtractor", ".", "nonmax", "(", "new", "ConfigExtract", "(", "2", ",", "0", ",", "5", ",", "true", ")", ")", ";", "FastHessianFeatureDetector", "<", "II", ">", "detector", "=", "new", "FastHessianFeatureDetector", "<>", "(", "extractor", ",", "200", ",", "2", ",", "9", ",", "4", ",", "4", ",", "6", ")", ";", "// estimate orientation", "OrientationIntegral", "<", "II", ">", "orientation", "=", "FactoryOrientationAlgs", ".", "sliding_ii", "(", "null", ",", "integralType", ")", ";", "DescribePointSurf", "<", "II", ">", "descriptor", "=", "FactoryDescribePointAlgs", ".", "<", "II", ">", "surfStability", "(", "null", ",", "integralType", ")", ";", "// compute the integral image of 'image'", "II", "integral", "=", "GeneralizedImageOps", ".", "createSingleBand", "(", "integralType", ",", "image", ".", "width", ",", "image", ".", "height", ")", ";", "GIntegralImageOps", ".", "transform", "(", "image", ",", "integral", ")", ";", "// detect fast hessian features", "detector", ".", "detect", "(", "integral", ")", ";", "// tell algorithms which image to process", "orientation", ".", "setImage", "(", "integral", ")", ";", "descriptor", ".", "setImage", "(", "integral", ")", ";", "List", "<", "ScalePoint", ">", "points", "=", "detector", ".", "getFoundPoints", "(", ")", ";", "List", "<", "BrightFeature", ">", "descriptions", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "ScalePoint", "p", ":", "points", ")", "{", "// estimate orientation", "orientation", ".", "setObjectRadius", "(", "p", ".", "scale", "*", "BoofDefaults", ".", "SURF_SCALE_TO_RADIUS", ")", ";", "double", "angle", "=", "orientation", ".", "compute", "(", "p", ".", "x", ",", "p", ".", "y", ")", ";", "// extract the SURF description for this region", "BrightFeature", "desc", "=", "descriptor", ".", "createDescription", "(", ")", ";", "descriptor", ".", "describe", "(", "p", ".", "x", ",", "p", ".", "y", ",", "angle", ",", "p", ".", "scale", ",", "desc", ")", ";", "// save everything for processing later on", "descriptions", ".", "add", "(", "desc", ")", ";", "}", "System", ".", "out", ".", "println", "(", "\"Found Features: \"", "+", "points", ".", "size", "(", ")", ")", ";", "System", ".", "out", ".", "println", "(", "\"First descriptor's first value: \"", "+", "descriptions", ".", "get", "(", "0", ")", ".", "value", "[", "0", "]", ")", ";", "}" ]
Configured exactly the same as the easy example above, but require a lot more code and a more in depth understanding of how SURF works and is configured. Instead of TupleDesc_F64, SurfFeature are computed in this case. They are almost the same as TupleDesc_F64, but contain the Laplacian's sign which can be used to speed up association. That is an example of how using less generalized interfaces can improve performance. @param image Input image type. DOES NOT NEED TO BE GrayF32, GrayU8 works too
[ "Configured", "exactly", "the", "same", "as", "the", "easy", "example", "above", "but", "require", "a", "lot", "more", "code", "and", "a", "more", "in", "depth", "understanding", "of", "how", "SURF", "works", "and", "is", "configured", ".", "Instead", "of", "TupleDesc_F64", "SurfFeature", "are", "computed", "in", "this", "case", ".", "They", "are", "almost", "the", "same", "as", "TupleDesc_F64", "but", "contain", "the", "Laplacian", "s", "sign", "which", "can", "be", "used", "to", "speed", "up", "association", ".", "That", "is", "an", "example", "of", "how", "using", "less", "generalized", "interfaces", "can", "improve", "performance", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/examples/src/main/java/boofcv/examples/features/ExampleFeatureSurf.java#L79-L124
google/closure-compiler
src/com/google/javascript/rhino/TypeDeclarationsIR.java
TypeDeclarationsIR.functionType
public static TypeDeclarationNode functionType( Node returnType, LinkedHashMap<String, TypeDeclarationNode> requiredParams, LinkedHashMap<String, TypeDeclarationNode> optionalParams, String restName, TypeDeclarationNode restType) { TypeDeclarationNode node = new TypeDeclarationNode(Token.FUNCTION_TYPE, returnType); checkNotNull(requiredParams); checkNotNull(optionalParams); for (Map.Entry<String, TypeDeclarationNode> param : requiredParams.entrySet()) { Node name = IR.name(param.getKey()); node.addChildToBack(maybeAddType(name, param.getValue())); } for (Map.Entry<String, TypeDeclarationNode> param : optionalParams.entrySet()) { Node name = IR.name(param.getKey()); name.putBooleanProp(Node.OPT_ES6_TYPED, true); node.addChildToBack(maybeAddType(name, param.getValue())); } if (restName != null) { Node rest = new Node(Token.REST, IR.name(restName)); node.addChildToBack(maybeAddType(rest, restType)); } return node; }
java
public static TypeDeclarationNode functionType( Node returnType, LinkedHashMap<String, TypeDeclarationNode> requiredParams, LinkedHashMap<String, TypeDeclarationNode> optionalParams, String restName, TypeDeclarationNode restType) { TypeDeclarationNode node = new TypeDeclarationNode(Token.FUNCTION_TYPE, returnType); checkNotNull(requiredParams); checkNotNull(optionalParams); for (Map.Entry<String, TypeDeclarationNode> param : requiredParams.entrySet()) { Node name = IR.name(param.getKey()); node.addChildToBack(maybeAddType(name, param.getValue())); } for (Map.Entry<String, TypeDeclarationNode> param : optionalParams.entrySet()) { Node name = IR.name(param.getKey()); name.putBooleanProp(Node.OPT_ES6_TYPED, true); node.addChildToBack(maybeAddType(name, param.getValue())); } if (restName != null) { Node rest = new Node(Token.REST, IR.name(restName)); node.addChildToBack(maybeAddType(rest, restType)); } return node; }
[ "public", "static", "TypeDeclarationNode", "functionType", "(", "Node", "returnType", ",", "LinkedHashMap", "<", "String", ",", "TypeDeclarationNode", ">", "requiredParams", ",", "LinkedHashMap", "<", "String", ",", "TypeDeclarationNode", ">", "optionalParams", ",", "String", "restName", ",", "TypeDeclarationNode", "restType", ")", "{", "TypeDeclarationNode", "node", "=", "new", "TypeDeclarationNode", "(", "Token", ".", "FUNCTION_TYPE", ",", "returnType", ")", ";", "checkNotNull", "(", "requiredParams", ")", ";", "checkNotNull", "(", "optionalParams", ")", ";", "for", "(", "Map", ".", "Entry", "<", "String", ",", "TypeDeclarationNode", ">", "param", ":", "requiredParams", ".", "entrySet", "(", ")", ")", "{", "Node", "name", "=", "IR", ".", "name", "(", "param", ".", "getKey", "(", ")", ")", ";", "node", ".", "addChildToBack", "(", "maybeAddType", "(", "name", ",", "param", ".", "getValue", "(", ")", ")", ")", ";", "}", "for", "(", "Map", ".", "Entry", "<", "String", ",", "TypeDeclarationNode", ">", "param", ":", "optionalParams", ".", "entrySet", "(", ")", ")", "{", "Node", "name", "=", "IR", ".", "name", "(", "param", ".", "getKey", "(", ")", ")", ";", "name", ".", "putBooleanProp", "(", "Node", ".", "OPT_ES6_TYPED", ",", "true", ")", ";", "node", ".", "addChildToBack", "(", "maybeAddType", "(", "name", ",", "param", ".", "getValue", "(", ")", ")", ")", ";", "}", "if", "(", "restName", "!=", "null", ")", "{", "Node", "rest", "=", "new", "Node", "(", "Token", ".", "REST", ",", "IR", ".", "name", "(", "restName", ")", ")", ";", "node", ".", "addChildToBack", "(", "maybeAddType", "(", "rest", ",", "restType", ")", ")", ";", "}", "return", "node", ";", "}" ]
Represents a function type. Closure has syntax like {@code {function(string, boolean):number}} Closure doesn't include parameter names. If the parameter types are unnamed, arbitrary names can be substituted, eg. p1, p2, etc. <p>Example: <pre> FUNCTION_TYPE NUMBER_TYPE STRING_KEY p1 [declared_type_expr: STRING_TYPE] STRING_KEY p2 [declared_type_expr: BOOLEAN_TYPE] </pre> @param returnType the type returned by the function, possibly ANY_TYPE @param requiredParams the names and types of the required parameters. @param optionalParams the names and types of the optional parameters. @param restName the name of the rest parameter, if any. @param restType the type of the rest parameter, if any.
[ "Represents", "a", "function", "type", ".", "Closure", "has", "syntax", "like", "{", "@code", "{", "function", "(", "string", "boolean", ")", ":", "number", "}}", "Closure", "doesn", "t", "include", "parameter", "names", ".", "If", "the", "parameter", "types", "are", "unnamed", "arbitrary", "names", "can", "be", "substituted", "eg", ".", "p1", "p2", "etc", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/TypeDeclarationsIR.java#L188-L212
finmath/finmath-lib
src/main/java/net/finmath/montecarlo/interestrate/products/components/IndexedValue.java
IndexedValue.getValue
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { double evaluationTimeUnderlying = Math.max(evaluationTime, exerciseDate); RandomVariable underlyingValues = underlying.getValue(evaluationTimeUnderlying, model); RandomVariable indexValues = index.getValue(exerciseDate, model); // Make index measurable w.r.t time exerciseDate if(indexValues.getFiltrationTime() > exerciseDate && exerciseDate > evaluationTime) { MonteCarloConditionalExpectationRegression condExpEstimator = new MonteCarloConditionalExpectationRegression(getRegressionBasisFunctions(exerciseDate, model)); // Calculate cond. expectation. indexValues = condExpEstimator.getConditionalExpectation(indexValues); } // Form product underlyingValues = underlyingValues.mult(indexValues); // Discount to evaluation time if necessary if(evaluationTime != evaluationTimeUnderlying) { RandomVariable numeraireAtEval = model.getNumeraire(evaluationTime); RandomVariable numeraire = model.getNumeraire(evaluationTimeUnderlying); underlyingValues = underlyingValues.div(numeraire).mult(numeraireAtEval); } // Return values return underlyingValues; }
java
@Override public RandomVariable getValue(double evaluationTime, LIBORModelMonteCarloSimulationModel model) throws CalculationException { double evaluationTimeUnderlying = Math.max(evaluationTime, exerciseDate); RandomVariable underlyingValues = underlying.getValue(evaluationTimeUnderlying, model); RandomVariable indexValues = index.getValue(exerciseDate, model); // Make index measurable w.r.t time exerciseDate if(indexValues.getFiltrationTime() > exerciseDate && exerciseDate > evaluationTime) { MonteCarloConditionalExpectationRegression condExpEstimator = new MonteCarloConditionalExpectationRegression(getRegressionBasisFunctions(exerciseDate, model)); // Calculate cond. expectation. indexValues = condExpEstimator.getConditionalExpectation(indexValues); } // Form product underlyingValues = underlyingValues.mult(indexValues); // Discount to evaluation time if necessary if(evaluationTime != evaluationTimeUnderlying) { RandomVariable numeraireAtEval = model.getNumeraire(evaluationTime); RandomVariable numeraire = model.getNumeraire(evaluationTimeUnderlying); underlyingValues = underlyingValues.div(numeraire).mult(numeraireAtEval); } // Return values return underlyingValues; }
[ "@", "Override", "public", "RandomVariable", "getValue", "(", "double", "evaluationTime", ",", "LIBORModelMonteCarloSimulationModel", "model", ")", "throws", "CalculationException", "{", "double", "evaluationTimeUnderlying", "=", "Math", ".", "max", "(", "evaluationTime", ",", "exerciseDate", ")", ";", "RandomVariable", "underlyingValues", "=", "underlying", ".", "getValue", "(", "evaluationTimeUnderlying", ",", "model", ")", ";", "RandomVariable", "indexValues", "=", "index", ".", "getValue", "(", "exerciseDate", ",", "model", ")", ";", "// Make index measurable w.r.t time exerciseDate", "if", "(", "indexValues", ".", "getFiltrationTime", "(", ")", ">", "exerciseDate", "&&", "exerciseDate", ">", "evaluationTime", ")", "{", "MonteCarloConditionalExpectationRegression", "condExpEstimator", "=", "new", "MonteCarloConditionalExpectationRegression", "(", "getRegressionBasisFunctions", "(", "exerciseDate", ",", "model", ")", ")", ";", "// Calculate cond. expectation.", "indexValues", "=", "condExpEstimator", ".", "getConditionalExpectation", "(", "indexValues", ")", ";", "}", "// Form product", "underlyingValues", "=", "underlyingValues", ".", "mult", "(", "indexValues", ")", ";", "// Discount to evaluation time if necessary", "if", "(", "evaluationTime", "!=", "evaluationTimeUnderlying", ")", "{", "RandomVariable", "numeraireAtEval", "=", "model", ".", "getNumeraire", "(", "evaluationTime", ")", ";", "RandomVariable", "numeraire", "=", "model", ".", "getNumeraire", "(", "evaluationTimeUnderlying", ")", ";", "underlyingValues", "=", "underlyingValues", ".", "div", "(", "numeraire", ")", ".", "mult", "(", "numeraireAtEval", ")", ";", "}", "// Return values", "return", "underlyingValues", ";", "}" ]
This method returns the value random variable of the product within the specified model, evaluated at a given evalutationTime. Note: For a lattice this is often the value conditional to evalutationTime, for a Monte-Carlo simulation this is the (sum of) value discounted to evaluation time. Cash flows prior evaluationTime are not considered. @param evaluationTime The time on which this products value should be observed. @param model The model used to price the product. @return The random variable representing the value of the product discounted to evaluation time @throws net.finmath.exception.CalculationException Thrown if the valuation fails, specific cause may be available via the <code>cause()</code> method.
[ "This", "method", "returns", "the", "value", "random", "variable", "of", "the", "product", "within", "the", "specified", "model", "evaluated", "at", "a", "given", "evalutationTime", ".", "Note", ":", "For", "a", "lattice", "this", "is", "often", "the", "value", "conditional", "to", "evalutationTime", "for", "a", "Monte", "-", "Carlo", "simulation", "this", "is", "the", "(", "sum", "of", ")", "value", "discounted", "to", "evaluation", "time", ".", "Cash", "flows", "prior", "evaluationTime", "are", "not", "considered", "." ]
train
https://github.com/finmath/finmath-lib/blob/a3c067d52dd33feb97d851df6cab130e4116759f/src/main/java/net/finmath/montecarlo/interestrate/products/components/IndexedValue.java#L73-L101
apereo/cas
core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/principal/resolvers/PersonDirectoryPrincipalResolver.java
PersonDirectoryPrincipalResolver.extractPrincipalId
protected String extractPrincipalId(final Credential credential, final Optional<Principal> currentPrincipal) { LOGGER.debug("Extracting credential id based on existing credential [{}]", credential); val id = credential.getId(); if (currentPrincipal != null && currentPrincipal.isPresent()) { val principal = currentPrincipal.get(); LOGGER.debug("Principal is currently resolved as [{}]", principal); if (useCurrentPrincipalId) { LOGGER.debug("Using the existing resolved principal id [{}]", principal.getId()); return principal.getId(); } else { LOGGER.debug("CAS will NOT be using the identifier from the resolved principal [{}] as it's not " + "configured to use the currently-resolved principal id and will fall back onto using the identifier " + "for the credential, that is [{}], for principal resolution", principal, id); } } else { LOGGER.debug("No principal is currently resolved and available. Falling back onto using the identifier " + " for the credential, that is [{}], for principal resolution", id); } LOGGER.debug("Extracted principal id [{}]", id); return id; }
java
protected String extractPrincipalId(final Credential credential, final Optional<Principal> currentPrincipal) { LOGGER.debug("Extracting credential id based on existing credential [{}]", credential); val id = credential.getId(); if (currentPrincipal != null && currentPrincipal.isPresent()) { val principal = currentPrincipal.get(); LOGGER.debug("Principal is currently resolved as [{}]", principal); if (useCurrentPrincipalId) { LOGGER.debug("Using the existing resolved principal id [{}]", principal.getId()); return principal.getId(); } else { LOGGER.debug("CAS will NOT be using the identifier from the resolved principal [{}] as it's not " + "configured to use the currently-resolved principal id and will fall back onto using the identifier " + "for the credential, that is [{}], for principal resolution", principal, id); } } else { LOGGER.debug("No principal is currently resolved and available. Falling back onto using the identifier " + " for the credential, that is [{}], for principal resolution", id); } LOGGER.debug("Extracted principal id [{}]", id); return id; }
[ "protected", "String", "extractPrincipalId", "(", "final", "Credential", "credential", ",", "final", "Optional", "<", "Principal", ">", "currentPrincipal", ")", "{", "LOGGER", ".", "debug", "(", "\"Extracting credential id based on existing credential [{}]\"", ",", "credential", ")", ";", "val", "id", "=", "credential", ".", "getId", "(", ")", ";", "if", "(", "currentPrincipal", "!=", "null", "&&", "currentPrincipal", ".", "isPresent", "(", ")", ")", "{", "val", "principal", "=", "currentPrincipal", ".", "get", "(", ")", ";", "LOGGER", ".", "debug", "(", "\"Principal is currently resolved as [{}]\"", ",", "principal", ")", ";", "if", "(", "useCurrentPrincipalId", ")", "{", "LOGGER", ".", "debug", "(", "\"Using the existing resolved principal id [{}]\"", ",", "principal", ".", "getId", "(", ")", ")", ";", "return", "principal", ".", "getId", "(", ")", ";", "}", "else", "{", "LOGGER", ".", "debug", "(", "\"CAS will NOT be using the identifier from the resolved principal [{}] as it's not \"", "+", "\"configured to use the currently-resolved principal id and will fall back onto using the identifier \"", "+", "\"for the credential, that is [{}], for principal resolution\"", ",", "principal", ",", "id", ")", ";", "}", "}", "else", "{", "LOGGER", ".", "debug", "(", "\"No principal is currently resolved and available. Falling back onto using the identifier \"", "+", "\" for the credential, that is [{}], for principal resolution\"", ",", "id", ")", ";", "}", "LOGGER", ".", "debug", "(", "\"Extracted principal id [{}]\"", ",", "id", ")", ";", "return", "id", ";", "}" ]
Extracts the id of the user from the provided credential. This method should be overridden by subclasses to achieve more sophisticated strategies for producing a principal ID from a credential. @param credential the credential provided by the user. @param currentPrincipal the current principal @return the username, or null if it could not be resolved.
[ "Extracts", "the", "id", "of", "the", "user", "from", "the", "provided", "credential", ".", "This", "method", "should", "be", "overridden", "by", "subclasses", "to", "achieve", "more", "sophisticated", "strategies", "for", "producing", "a", "principal", "ID", "from", "a", "credential", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-authentication-api/src/main/java/org/apereo/cas/authentication/principal/resolvers/PersonDirectoryPrincipalResolver.java#L262-L282
inferred/FreeBuilder
src/main/java/org/inferred/freebuilder/processor/Analyser.java
Analyser.tryFindBuilder
private Optional<DeclaredType> tryFindBuilder( final QualifiedName superclass, TypeElement valueType) { TypeElement builderType = typesIn(valueType.getEnclosedElements()) .stream() .filter(element -> element.getSimpleName().contentEquals(USER_BUILDER_NAME)) .findAny() .orElse(null); if (builderType == null) { if (valueType.getKind() == INTERFACE) { messager.printMessage( NOTE, "Add \"class Builder extends " + superclass.getSimpleName() + " {}\" to your interface to enable the FreeBuilder API", valueType); } else { messager.printMessage( NOTE, "Add \"public static class Builder extends " + superclass.getSimpleName() + " {}\" to your class to enable the FreeBuilder API", valueType); } return Optional.empty(); } boolean extendsSuperclass = new IsSubclassOfGeneratedTypeVisitor(superclass, valueType.getTypeParameters()) .visit(builderType.getSuperclass()); if (!extendsSuperclass) { messager.printMessage( ERROR, "Builder extends the wrong type (should be " + superclass.getSimpleName() + ")", builderType); return Optional.empty(); } if (builderType.getTypeParameters().size() != valueType.getTypeParameters().size()) { if (builderType.getTypeParameters().isEmpty()) { messager.printMessage(ERROR, "Builder must be generic", builderType); } else { messager.printMessage(ERROR, "Builder has the wrong type parameters", builderType); } return Optional.empty(); } DeclaredType declaredValueType = (DeclaredType) valueType.asType(); DeclaredType declaredBuilderType = types.getDeclaredType( builderType, declaredValueType.getTypeArguments().toArray(new TypeMirror[0])); return Optional.of(declaredBuilderType); }
java
private Optional<DeclaredType> tryFindBuilder( final QualifiedName superclass, TypeElement valueType) { TypeElement builderType = typesIn(valueType.getEnclosedElements()) .stream() .filter(element -> element.getSimpleName().contentEquals(USER_BUILDER_NAME)) .findAny() .orElse(null); if (builderType == null) { if (valueType.getKind() == INTERFACE) { messager.printMessage( NOTE, "Add \"class Builder extends " + superclass.getSimpleName() + " {}\" to your interface to enable the FreeBuilder API", valueType); } else { messager.printMessage( NOTE, "Add \"public static class Builder extends " + superclass.getSimpleName() + " {}\" to your class to enable the FreeBuilder API", valueType); } return Optional.empty(); } boolean extendsSuperclass = new IsSubclassOfGeneratedTypeVisitor(superclass, valueType.getTypeParameters()) .visit(builderType.getSuperclass()); if (!extendsSuperclass) { messager.printMessage( ERROR, "Builder extends the wrong type (should be " + superclass.getSimpleName() + ")", builderType); return Optional.empty(); } if (builderType.getTypeParameters().size() != valueType.getTypeParameters().size()) { if (builderType.getTypeParameters().isEmpty()) { messager.printMessage(ERROR, "Builder must be generic", builderType); } else { messager.printMessage(ERROR, "Builder has the wrong type parameters", builderType); } return Optional.empty(); } DeclaredType declaredValueType = (DeclaredType) valueType.asType(); DeclaredType declaredBuilderType = types.getDeclaredType( builderType, declaredValueType.getTypeArguments().toArray(new TypeMirror[0])); return Optional.of(declaredBuilderType); }
[ "private", "Optional", "<", "DeclaredType", ">", "tryFindBuilder", "(", "final", "QualifiedName", "superclass", ",", "TypeElement", "valueType", ")", "{", "TypeElement", "builderType", "=", "typesIn", "(", "valueType", ".", "getEnclosedElements", "(", ")", ")", ".", "stream", "(", ")", ".", "filter", "(", "element", "->", "element", ".", "getSimpleName", "(", ")", ".", "contentEquals", "(", "USER_BUILDER_NAME", ")", ")", ".", "findAny", "(", ")", ".", "orElse", "(", "null", ")", ";", "if", "(", "builderType", "==", "null", ")", "{", "if", "(", "valueType", ".", "getKind", "(", ")", "==", "INTERFACE", ")", "{", "messager", ".", "printMessage", "(", "NOTE", ",", "\"Add \\\"class Builder extends \"", "+", "superclass", ".", "getSimpleName", "(", ")", "+", "\" {}\\\" to your interface to enable the FreeBuilder API\"", ",", "valueType", ")", ";", "}", "else", "{", "messager", ".", "printMessage", "(", "NOTE", ",", "\"Add \\\"public static class Builder extends \"", "+", "superclass", ".", "getSimpleName", "(", ")", "+", "\" {}\\\" to your class to enable the FreeBuilder API\"", ",", "valueType", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}", "boolean", "extendsSuperclass", "=", "new", "IsSubclassOfGeneratedTypeVisitor", "(", "superclass", ",", "valueType", ".", "getTypeParameters", "(", ")", ")", ".", "visit", "(", "builderType", ".", "getSuperclass", "(", ")", ")", ";", "if", "(", "!", "extendsSuperclass", ")", "{", "messager", ".", "printMessage", "(", "ERROR", ",", "\"Builder extends the wrong type (should be \"", "+", "superclass", ".", "getSimpleName", "(", ")", "+", "\")\"", ",", "builderType", ")", ";", "return", "Optional", ".", "empty", "(", ")", ";", "}", "if", "(", "builderType", ".", "getTypeParameters", "(", ")", ".", "size", "(", ")", "!=", "valueType", ".", "getTypeParameters", "(", ")", ".", "size", "(", ")", ")", "{", "if", "(", "builderType", ".", "getTypeParameters", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "messager", ".", "printMessage", "(", "ERROR", ",", "\"Builder must be generic\"", ",", "builderType", ")", ";", "}", "else", "{", "messager", ".", "printMessage", "(", "ERROR", ",", "\"Builder has the wrong type parameters\"", ",", "builderType", ")", ";", "}", "return", "Optional", ".", "empty", "(", ")", ";", "}", "DeclaredType", "declaredValueType", "=", "(", "DeclaredType", ")", "valueType", ".", "asType", "(", ")", ";", "DeclaredType", "declaredBuilderType", "=", "types", ".", "getDeclaredType", "(", "builderType", ",", "declaredValueType", ".", "getTypeArguments", "(", ")", ".", "toArray", "(", "new", "TypeMirror", "[", "0", "]", ")", ")", ";", "return", "Optional", ".", "of", "(", "declaredBuilderType", ")", ";", "}" ]
Looks for a nested type in {@code valueType} called Builder, and verifies it extends the autogenerated {@code superclass}. <p>If the value type is generic, the builder type must match, and the returned DeclaredType will be parameterized with the type variables from the <b>value type</b>, not the builder. (This makes type checking massively easier.) <p>Issues an error if the wrong type is being subclassed&mdash;a typical copy-and-paste error when renaming an existing &#64;FreeBuilder type, or using one as a template.
[ "Looks", "for", "a", "nested", "type", "in", "{", "@code", "valueType", "}", "called", "Builder", "and", "verifies", "it", "extends", "the", "autogenerated", "{", "@code", "superclass", "}", "." ]
train
https://github.com/inferred/FreeBuilder/blob/d5a222f90648aece135da4b971c55a60afe8649c/src/main/java/org/inferred/freebuilder/processor/Analyser.java#L332-L383
EasyinnovaSL/Tiff-Library-4J
src/main/java/com/easyinnova/tiff/profiles/TiffITProfile.java
TiffITProfile.checkRequiredTag
private boolean checkRequiredTag(IfdTags metadata, String tagName, int cardinality) { return checkRequiredTag(metadata, tagName, cardinality, null); }
java
private boolean checkRequiredTag(IfdTags metadata, String tagName, int cardinality) { return checkRequiredTag(metadata, tagName, cardinality, null); }
[ "private", "boolean", "checkRequiredTag", "(", "IfdTags", "metadata", ",", "String", "tagName", ",", "int", "cardinality", ")", "{", "return", "checkRequiredTag", "(", "metadata", ",", "tagName", ",", "cardinality", ",", "null", ")", ";", "}" ]
Check a required tag is present. @param metadata the metadata @param tagName the name of the mandatory tag @param cardinality the mandatory cardinality @return true, if tag is present
[ "Check", "a", "required", "tag", "is", "present", "." ]
train
https://github.com/EasyinnovaSL/Tiff-Library-4J/blob/682605d3ed207a66213278c054c98f1b909472b7/src/main/java/com/easyinnova/tiff/profiles/TiffITProfile.java#L661-L663
googleapis/google-cloud-java
google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/EntityTypesClient.java
EntityTypesClient.updateEntityType
public final EntityType updateEntityType(EntityType entityType, String languageCode) { UpdateEntityTypeRequest request = UpdateEntityTypeRequest.newBuilder() .setEntityType(entityType) .setLanguageCode(languageCode) .build(); return updateEntityType(request); }
java
public final EntityType updateEntityType(EntityType entityType, String languageCode) { UpdateEntityTypeRequest request = UpdateEntityTypeRequest.newBuilder() .setEntityType(entityType) .setLanguageCode(languageCode) .build(); return updateEntityType(request); }
[ "public", "final", "EntityType", "updateEntityType", "(", "EntityType", "entityType", ",", "String", "languageCode", ")", "{", "UpdateEntityTypeRequest", "request", "=", "UpdateEntityTypeRequest", ".", "newBuilder", "(", ")", ".", "setEntityType", "(", "entityType", ")", ".", "setLanguageCode", "(", "languageCode", ")", ".", "build", "(", ")", ";", "return", "updateEntityType", "(", "request", ")", ";", "}" ]
Updates the specified entity type. <p>Sample code: <pre><code> try (EntityTypesClient entityTypesClient = EntityTypesClient.create()) { EntityType entityType = EntityType.newBuilder().build(); String languageCode = ""; EntityType response = entityTypesClient.updateEntityType(entityType, languageCode); } </code></pre> @param entityType Required. The entity type to update. @param languageCode Optional. The language of entity synonyms defined in `entity_type`. If not specified, the agent's default language is used. [Many languages](https://cloud.google.com/dialogflow-enterprise/docs/reference/language) are supported. Note: languages must be enabled in the agent before they can be used. @throws com.google.api.gax.rpc.ApiException if the remote call fails
[ "Updates", "the", "specified", "entity", "type", "." ]
train
https://github.com/googleapis/google-cloud-java/blob/d2f0bc64a53049040fe9c9d338b12fab3dd1ad6a/google-cloud-clients/google-cloud-dialogflow/src/main/java/com/google/cloud/dialogflow/v2/EntityTypesClient.java#L768-L776
Azure/azure-sdk-for-java
appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java
AppServiceEnvironmentsInner.createOrUpdate
public AppServiceEnvironmentResourceInner createOrUpdate(String resourceGroupName, String name, AppServiceEnvironmentResourceInner hostingEnvironmentEnvelope) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, name, hostingEnvironmentEnvelope).toBlocking().last().body(); }
java
public AppServiceEnvironmentResourceInner createOrUpdate(String resourceGroupName, String name, AppServiceEnvironmentResourceInner hostingEnvironmentEnvelope) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, name, hostingEnvironmentEnvelope).toBlocking().last().body(); }
[ "public", "AppServiceEnvironmentResourceInner", "createOrUpdate", "(", "String", "resourceGroupName", ",", "String", "name", ",", "AppServiceEnvironmentResourceInner", "hostingEnvironmentEnvelope", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "name", ",", "hostingEnvironmentEnvelope", ")", ".", "toBlocking", "(", ")", ".", "last", "(", ")", ".", "body", "(", ")", ";", "}" ]
Create or update an App Service Environment. Create or update an App Service Environment. @param resourceGroupName Name of the resource group to which the resource belongs. @param name Name of the App Service Environment. @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. @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 AppServiceEnvironmentResourceInner object if successful.
[ "Create", "or", "update", "an", "App", "Service", "Environment", ".", "Create", "or", "update", "an", "App", "Service", "Environment", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2016_09_01/src/main/java/com/microsoft/azure/management/appservice/v2016_09_01/implementation/AppServiceEnvironmentsInner.java#L686-L688
OpenLiberty/open-liberty
dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/productinfo/ProductInfo.java
ProductInfo.getVersionFilesByProdExtension
public static Map<String, File[]> getVersionFilesByProdExtension(File installDir) { Map<String, File[]> versionFiles = new TreeMap<String, File[]>(); Iterator<ProductExtensionInfo> productExtensions = ProductExtension.getProductExtensions().iterator(); while (productExtensions != null && productExtensions.hasNext()) { ProductExtensionInfo prodExt = productExtensions.next(); String prodExtName = prodExt.getName(); if (0 != prodExtName.length()) { String prodExtLocation = prodExt.getLocation(); if (prodExtLocation != null) { String normalizedProdExtLoc = FileUtils.normalize(prodExtLocation); if (FileUtils.pathIsAbsolute(normalizedProdExtLoc) == false) { String parentPath = installDir.getParentFile().getAbsolutePath(); normalizedProdExtLoc = FileUtils.normalize(parentPath + "/" + prodExtLocation + "/"); } File prodExtVersionDir = new File(normalizedProdExtLoc, VERSION_PROPERTY_DIRECTORY); if (prodExtVersionDir.exists()) { versionFiles.put(prodExtName, prodExtVersionDir.listFiles(versionFileFilter)); } } } } return versionFiles; }
java
public static Map<String, File[]> getVersionFilesByProdExtension(File installDir) { Map<String, File[]> versionFiles = new TreeMap<String, File[]>(); Iterator<ProductExtensionInfo> productExtensions = ProductExtension.getProductExtensions().iterator(); while (productExtensions != null && productExtensions.hasNext()) { ProductExtensionInfo prodExt = productExtensions.next(); String prodExtName = prodExt.getName(); if (0 != prodExtName.length()) { String prodExtLocation = prodExt.getLocation(); if (prodExtLocation != null) { String normalizedProdExtLoc = FileUtils.normalize(prodExtLocation); if (FileUtils.pathIsAbsolute(normalizedProdExtLoc) == false) { String parentPath = installDir.getParentFile().getAbsolutePath(); normalizedProdExtLoc = FileUtils.normalize(parentPath + "/" + prodExtLocation + "/"); } File prodExtVersionDir = new File(normalizedProdExtLoc, VERSION_PROPERTY_DIRECTORY); if (prodExtVersionDir.exists()) { versionFiles.put(prodExtName, prodExtVersionDir.listFiles(versionFileFilter)); } } } } return versionFiles; }
[ "public", "static", "Map", "<", "String", ",", "File", "[", "]", ">", "getVersionFilesByProdExtension", "(", "File", "installDir", ")", "{", "Map", "<", "String", ",", "File", "[", "]", ">", "versionFiles", "=", "new", "TreeMap", "<", "String", ",", "File", "[", "]", ">", "(", ")", ";", "Iterator", "<", "ProductExtensionInfo", ">", "productExtensions", "=", "ProductExtension", ".", "getProductExtensions", "(", ")", ".", "iterator", "(", ")", ";", "while", "(", "productExtensions", "!=", "null", "&&", "productExtensions", ".", "hasNext", "(", ")", ")", "{", "ProductExtensionInfo", "prodExt", "=", "productExtensions", ".", "next", "(", ")", ";", "String", "prodExtName", "=", "prodExt", ".", "getName", "(", ")", ";", "if", "(", "0", "!=", "prodExtName", ".", "length", "(", ")", ")", "{", "String", "prodExtLocation", "=", "prodExt", ".", "getLocation", "(", ")", ";", "if", "(", "prodExtLocation", "!=", "null", ")", "{", "String", "normalizedProdExtLoc", "=", "FileUtils", ".", "normalize", "(", "prodExtLocation", ")", ";", "if", "(", "FileUtils", ".", "pathIsAbsolute", "(", "normalizedProdExtLoc", ")", "==", "false", ")", "{", "String", "parentPath", "=", "installDir", ".", "getParentFile", "(", ")", ".", "getAbsolutePath", "(", ")", ";", "normalizedProdExtLoc", "=", "FileUtils", ".", "normalize", "(", "parentPath", "+", "\"/\"", "+", "prodExtLocation", "+", "\"/\"", ")", ";", "}", "File", "prodExtVersionDir", "=", "new", "File", "(", "normalizedProdExtLoc", ",", "VERSION_PROPERTY_DIRECTORY", ")", ";", "if", "(", "prodExtVersionDir", ".", "exists", "(", ")", ")", "{", "versionFiles", ".", "put", "(", "prodExtName", ",", "prodExtVersionDir", ".", "listFiles", "(", "versionFileFilter", ")", ")", ";", "}", "}", "}", "}", "return", "versionFiles", ";", "}" ]
Retrieves the product extension jar bundles pointed to by the properties file in etc/extensions. @return The array of product extension jar bundles
[ "Retrieves", "the", "product", "extension", "jar", "bundles", "pointed", "to", "by", "the", "properties", "file", "in", "etc", "/", "extensions", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.kernel.boot.core/src/com/ibm/ws/kernel/productinfo/ProductInfo.java#L254-L280
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/objectManager/ManagedObject.java
ManagedObject.setState
private void setState(int[] nextState) throws StateErrorException { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, "setState", new Object[] { nextState, new Integer(state), stateNames[state] }); synchronized (stateLock) { previousState = state; // Capture the previous state for dump. state = nextState[state]; // Make the state change. } // synchronized (stateLock) if (state == stateError) { StateErrorException stateErrorException = new StateErrorException(this, previousState, stateNames[previousState]); ObjectManager.ffdc.processException(this, cclass, "setState", stateErrorException, "1:2016:1.34"); if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this, cclass, "setState", new Object[] { stateErrorException, new Integer(state), stateNames[state] }); throw stateErrorException; } // if (state == stateError). if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this , cclass , "setState" , "state=" + state + "(int) " + stateNames[state] + "(String)" ); }
java
private void setState(int[] nextState) throws StateErrorException { if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, cclass, "setState", new Object[] { nextState, new Integer(state), stateNames[state] }); synchronized (stateLock) { previousState = state; // Capture the previous state for dump. state = nextState[state]; // Make the state change. } // synchronized (stateLock) if (state == stateError) { StateErrorException stateErrorException = new StateErrorException(this, previousState, stateNames[previousState]); ObjectManager.ffdc.processException(this, cclass, "setState", stateErrorException, "1:2016:1.34"); if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this, cclass, "setState", new Object[] { stateErrorException, new Integer(state), stateNames[state] }); throw stateErrorException; } // if (state == stateError). if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.exit(this , cclass , "setState" , "state=" + state + "(int) " + stateNames[state] + "(String)" ); }
[ "private", "void", "setState", "(", "int", "[", "]", "nextState", ")", "throws", "StateErrorException", "{", "if", "(", "Tracing", ".", "isAnyTracingEnabled", "(", ")", "&&", "trace", ".", "isEntryEnabled", "(", ")", ")", "trace", ".", "entry", "(", "this", ",", "cclass", ",", "\"setState\"", ",", "new", "Object", "[", "]", "{", "nextState", ",", "new", "Integer", "(", "state", ")", ",", "stateNames", "[", "state", "]", "}", ")", ";", "synchronized", "(", "stateLock", ")", "{", "previousState", "=", "state", ";", "// Capture the previous state for dump. ", "state", "=", "nextState", "[", "state", "]", ";", "// Make the state change. ", "}", "// synchronized (stateLock) ", "if", "(", "state", "==", "stateError", ")", "{", "StateErrorException", "stateErrorException", "=", "new", "StateErrorException", "(", "this", ",", "previousState", ",", "stateNames", "[", "previousState", "]", ")", ";", "ObjectManager", ".", "ffdc", ".", "processException", "(", "this", ",", "cclass", ",", "\"setState\"", ",", "stateErrorException", ",", "\"1:2016:1.34\"", ")", ";", "if", "(", "Tracing", ".", "isAnyTracingEnabled", "(", ")", "&&", "trace", ".", "isEntryEnabled", "(", ")", ")", "trace", ".", "exit", "(", "this", ",", "cclass", ",", "\"setState\"", ",", "new", "Object", "[", "]", "{", "stateErrorException", ",", "new", "Integer", "(", "state", ")", ",", "stateNames", "[", "state", "]", "}", ")", ";", "throw", "stateErrorException", ";", "}", "// if (state == stateError). ", "if", "(", "Tracing", ".", "isAnyTracingEnabled", "(", ")", "&&", "trace", ".", "isEntryEnabled", "(", ")", ")", "trace", ".", "exit", "(", "this", ",", "cclass", ",", "\"setState\"", ",", "\"state=\"", "+", "state", "+", "\"(int) \"", "+", "stateNames", "[", "state", "]", "+", "\"(String)\"", ")", ";", "}" ]
Makes a state transition. @param nextState maps the current stte to the new one. @throws StateErrorException if the transition is invalid.
[ "Makes", "a", "state", "transition", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.msgstore/src/com/ibm/ws/objectManager/ManagedObject.java#L1997-L2033
super-csv/super-csv
super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/FmtDuration.java
FmtDuration.execute
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value instanceof Duration)) { throw new SuperCsvCellProcessorException(Duration.class, value, context, this); } final Duration duration = (Duration) value; final String result = duration.toString(); return next.execute(result, context); }
java
public Object execute(final Object value, final CsvContext context) { validateInputNotNull(value, context); if (!(value instanceof Duration)) { throw new SuperCsvCellProcessorException(Duration.class, value, context, this); } final Duration duration = (Duration) value; final String result = duration.toString(); return next.execute(result, context); }
[ "public", "Object", "execute", "(", "final", "Object", "value", ",", "final", "CsvContext", "context", ")", "{", "validateInputNotNull", "(", "value", ",", "context", ")", ";", "if", "(", "!", "(", "value", "instanceof", "Duration", ")", ")", "{", "throw", "new", "SuperCsvCellProcessorException", "(", "Duration", ".", "class", ",", "value", ",", "context", ",", "this", ")", ";", "}", "final", "Duration", "duration", "=", "(", "Duration", ")", "value", ";", "final", "String", "result", "=", "duration", ".", "toString", "(", ")", ";", "return", "next", ".", "execute", "(", "result", ",", "context", ")", ";", "}" ]
{@inheritDoc} @throws SuperCsvCellProcessorException if value is null or not a Duration
[ "{", "@inheritDoc", "}" ]
train
https://github.com/super-csv/super-csv/blob/f18db724674dc1c4116e25142c1b5403ebf43e96/super-csv-joda/src/main/java/org/supercsv/cellprocessor/joda/FmtDuration.java#L63-L72
defei/codelogger-utils
src/main/java/org/codelogger/utils/StringUtils.java
StringUtils.indexOfIgnoreCase
public static int indexOfIgnoreCase(final String source, final String target) { int targetIndex = source.indexOf(target); if (targetIndex == INDEX_OF_NOT_FOUND) { String sourceLowerCase = source.toLowerCase(); String targetLowerCase = target.toLowerCase(); targetIndex = sourceLowerCase.indexOf(targetLowerCase); return targetIndex; } else { return targetIndex; } }
java
public static int indexOfIgnoreCase(final String source, final String target) { int targetIndex = source.indexOf(target); if (targetIndex == INDEX_OF_NOT_FOUND) { String sourceLowerCase = source.toLowerCase(); String targetLowerCase = target.toLowerCase(); targetIndex = sourceLowerCase.indexOf(targetLowerCase); return targetIndex; } else { return targetIndex; } }
[ "public", "static", "int", "indexOfIgnoreCase", "(", "final", "String", "source", ",", "final", "String", "target", ")", "{", "int", "targetIndex", "=", "source", ".", "indexOf", "(", "target", ")", ";", "if", "(", "targetIndex", "==", "INDEX_OF_NOT_FOUND", ")", "{", "String", "sourceLowerCase", "=", "source", ".", "toLowerCase", "(", ")", ";", "String", "targetLowerCase", "=", "target", ".", "toLowerCase", "(", ")", ";", "targetIndex", "=", "sourceLowerCase", ".", "indexOf", "(", "targetLowerCase", ")", ";", "return", "targetIndex", ";", "}", "else", "{", "return", "targetIndex", ";", "}", "}" ]
Returns the index within given source string of the first occurrence of the specified target string with ignore case sensitive. @param source source string to be tested. @param target target string to be tested. @return index number if found, -1 otherwise.
[ "Returns", "the", "index", "within", "given", "source", "string", "of", "the", "first", "occurrence", "of", "the", "specified", "target", "string", "with", "ignore", "case", "sensitive", "." ]
train
https://github.com/defei/codelogger-utils/blob/d906f5d217b783c7ae3e53442cd6fb87b20ecc0a/src/main/java/org/codelogger/utils/StringUtils.java#L125-L136
apache/flink
flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java
DateTimeUtils.parseFraction
private static int parseFraction(String v, int multiplier) { int r = 0; for (int i = 0; i < v.length(); i++) { char c = v.charAt(i); int x = c < '0' || c > '9' ? 0 : (c - '0'); r += multiplier * x; if (multiplier < 10) { // We're at the last digit. Check for rounding. if (i + 1 < v.length() && v.charAt(i + 1) >= '5') { ++r; } break; } multiplier /= 10; } return r; }
java
private static int parseFraction(String v, int multiplier) { int r = 0; for (int i = 0; i < v.length(); i++) { char c = v.charAt(i); int x = c < '0' || c > '9' ? 0 : (c - '0'); r += multiplier * x; if (multiplier < 10) { // We're at the last digit. Check for rounding. if (i + 1 < v.length() && v.charAt(i + 1) >= '5') { ++r; } break; } multiplier /= 10; } return r; }
[ "private", "static", "int", "parseFraction", "(", "String", "v", ",", "int", "multiplier", ")", "{", "int", "r", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "v", ".", "length", "(", ")", ";", "i", "++", ")", "{", "char", "c", "=", "v", ".", "charAt", "(", "i", ")", ";", "int", "x", "=", "c", "<", "'", "'", "||", "c", ">", "'", "'", "?", "0", ":", "(", "c", "-", "'", "'", ")", ";", "r", "+=", "multiplier", "*", "x", ";", "if", "(", "multiplier", "<", "10", ")", "{", "// We're at the last digit. Check for rounding.", "if", "(", "i", "+", "1", "<", "v", ".", "length", "(", ")", "&&", "v", ".", "charAt", "(", "i", "+", "1", ")", ">=", "'", "'", ")", "{", "++", "r", ";", "}", "break", ";", "}", "multiplier", "/=", "10", ";", "}", "return", "r", ";", "}" ]
Parses a fraction, multiplying the first character by {@code multiplier}, the second character by {@code multiplier / 10}, the third character by {@code multiplier / 100}, and so forth. <p>For example, {@code parseFraction("1234", 100)} yields {@code 123}.
[ "Parses", "a", "fraction", "multiplying", "the", "first", "character", "by", "{", "@code", "multiplier", "}", "the", "second", "character", "by", "{", "@code", "multiplier", "/", "10", "}", "the", "third", "character", "by", "{", "@code", "multiplier", "/", "100", "}", "and", "so", "forth", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-table/flink-table-planner-blink/src/main/java/org/apache/calcite/avatica/util/DateTimeUtils.java#L838-L855
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptPropertySet.java
AptPropertySet.initProperties
protected ArrayList<AptProperty> initProperties() { ArrayList<AptProperty> properties = new ArrayList<AptProperty>(); if (_propertySet == null || _propertySet.getMethods() == null ) return properties; // Add all declared method, but ignore the mystery <clinit> methods for (MethodDeclaration methodDecl : _propertySet.getMethods()) if (!methodDecl.toString().equals("<clinit>()")) properties.add( new AptProperty(this,(AnnotationTypeElementDeclaration)methodDecl,_ap)); return properties; }
java
protected ArrayList<AptProperty> initProperties() { ArrayList<AptProperty> properties = new ArrayList<AptProperty>(); if (_propertySet == null || _propertySet.getMethods() == null ) return properties; // Add all declared method, but ignore the mystery <clinit> methods for (MethodDeclaration methodDecl : _propertySet.getMethods()) if (!methodDecl.toString().equals("<clinit>()")) properties.add( new AptProperty(this,(AnnotationTypeElementDeclaration)methodDecl,_ap)); return properties; }
[ "protected", "ArrayList", "<", "AptProperty", ">", "initProperties", "(", ")", "{", "ArrayList", "<", "AptProperty", ">", "properties", "=", "new", "ArrayList", "<", "AptProperty", ">", "(", ")", ";", "if", "(", "_propertySet", "==", "null", "||", "_propertySet", ".", "getMethods", "(", ")", "==", "null", ")", "return", "properties", ";", "// Add all declared method, but ignore the mystery <clinit> methods", "for", "(", "MethodDeclaration", "methodDecl", ":", "_propertySet", ".", "getMethods", "(", ")", ")", "if", "(", "!", "methodDecl", ".", "toString", "(", ")", ".", "equals", "(", "\"<clinit>()\"", ")", ")", "properties", ".", "add", "(", "new", "AptProperty", "(", "this", ",", "(", "AnnotationTypeElementDeclaration", ")", "methodDecl", ",", "_ap", ")", ")", ";", "return", "properties", ";", "}" ]
Initializes the list of ControlProperties associated with this ControlPropertySet
[ "Initializes", "the", "list", "of", "ControlProperties", "associated", "with", "this", "ControlPropertySet" ]
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/generator/AptPropertySet.java#L67-L81
mgm-tp/jfunk
jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java
WebDriverTool.getElementText
public String getElementText(final By by, final boolean normalizeSpace) { WebElement element = findElement(by); String text = element.getText(); return normalizeSpace ? JFunkUtils.normalizeSpace(text) : text; }
java
public String getElementText(final By by, final boolean normalizeSpace) { WebElement element = findElement(by); String text = element.getText(); return normalizeSpace ? JFunkUtils.normalizeSpace(text) : text; }
[ "public", "String", "getElementText", "(", "final", "By", "by", ",", "final", "boolean", "normalizeSpace", ")", "{", "WebElement", "element", "=", "findElement", "(", "by", ")", ";", "String", "text", "=", "element", ".", "getText", "(", ")", ";", "return", "normalizeSpace", "?", "JFunkUtils", ".", "normalizeSpace", "(", "text", ")", ":", "text", ";", "}" ]
Delegates to {@link #findElement(By)} and then calls {@link WebElement#getText() getText()} on the returned element. If {@code normalizeSpace} is {@code true}, the element's text is passed to {@link JFunkUtils#normalizeSpace(String)}. @param by the {@link By} used to locate the element @param normalizeSpace specifies whether whitespace in the element text are to be normalized @return the text
[ "Delegates", "to", "{", "@link", "#findElement", "(", "By", ")", "}", "and", "then", "calls", "{", "@link", "WebElement#getText", "()", "getText", "()", "}", "on", "the", "returned", "element", ".", "If", "{", "@code", "normalizeSpace", "}", "is", "{", "@code", "true", "}", "the", "element", "s", "text", "is", "passed", "to", "{", "@link", "JFunkUtils#normalizeSpace", "(", "String", ")", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-web/src/main/java/com/mgmtp/jfunk/web/util/WebDriverTool.java#L572-L576
google/closure-compiler
src/com/google/javascript/rhino/jstype/JSTypeRegistry.java
JSTypeRegistry.createTemplateTypeMap
public TemplateTypeMap createTemplateTypeMap( ImmutableList<TemplateType> templateKeys, ImmutableList<JSType> templateValues) { if (templateKeys == null) { templateKeys = ImmutableList.of(); } if (templateValues == null) { templateValues = ImmutableList.of(); } return (templateKeys.isEmpty() && templateValues.isEmpty()) ? emptyTemplateTypeMap : new TemplateTypeMap(this, templateKeys, templateValues); }
java
public TemplateTypeMap createTemplateTypeMap( ImmutableList<TemplateType> templateKeys, ImmutableList<JSType> templateValues) { if (templateKeys == null) { templateKeys = ImmutableList.of(); } if (templateValues == null) { templateValues = ImmutableList.of(); } return (templateKeys.isEmpty() && templateValues.isEmpty()) ? emptyTemplateTypeMap : new TemplateTypeMap(this, templateKeys, templateValues); }
[ "public", "TemplateTypeMap", "createTemplateTypeMap", "(", "ImmutableList", "<", "TemplateType", ">", "templateKeys", ",", "ImmutableList", "<", "JSType", ">", "templateValues", ")", "{", "if", "(", "templateKeys", "==", "null", ")", "{", "templateKeys", "=", "ImmutableList", ".", "of", "(", ")", ";", "}", "if", "(", "templateValues", "==", "null", ")", "{", "templateValues", "=", "ImmutableList", ".", "of", "(", ")", ";", "}", "return", "(", "templateKeys", ".", "isEmpty", "(", ")", "&&", "templateValues", ".", "isEmpty", "(", ")", ")", "?", "emptyTemplateTypeMap", ":", "new", "TemplateTypeMap", "(", "this", ",", "templateKeys", ",", "templateValues", ")", ";", "}" ]
Creates a template type map from the specified list of template keys and template value types.
[ "Creates", "a", "template", "type", "map", "from", "the", "specified", "list", "of", "template", "keys", "and", "template", "value", "types", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/rhino/jstype/JSTypeRegistry.java#L1855-L1867
google/error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
ASTHelpers.constValue
@Nullable public static <T> T constValue(Tree tree, Class<? extends T> clazz) { Object value = constValue(tree); return clazz.isInstance(value) ? clazz.cast(value) : null; }
java
@Nullable public static <T> T constValue(Tree tree, Class<? extends T> clazz) { Object value = constValue(tree); return clazz.isInstance(value) ? clazz.cast(value) : null; }
[ "@", "Nullable", "public", "static", "<", "T", ">", "T", "constValue", "(", "Tree", "tree", ",", "Class", "<", "?", "extends", "T", ">", "clazz", ")", "{", "Object", "value", "=", "constValue", "(", "tree", ")", ";", "return", "clazz", ".", "isInstance", "(", "value", ")", "?", "clazz", ".", "cast", "(", "value", ")", ":", "null", ";", "}" ]
Returns the compile-time constant value of a tree if it is of type clazz, or {@code null}.
[ "Returns", "the", "compile", "-", "time", "constant", "value", "of", "a", "tree", "if", "it", "is", "of", "type", "clazz", "or", "{" ]
train
https://github.com/google/error-prone/blob/fe2e3cc2cf1958cb7c487bfe89852bb4c225ba9d/check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java#L931-L935
LearnLib/learnlib
oracles/equivalence-oracles/src/main/java/de/learnlib/oracle/equivalence/SampleSetEQOracle.java
SampleSetEQOracle.addAll
@SafeVarargs public final SampleSetEQOracle<I, D> addAll(MembershipOracle<I, D> oracle, Word<I>... words) { return addAll(oracle, Arrays.asList(words)); }
java
@SafeVarargs public final SampleSetEQOracle<I, D> addAll(MembershipOracle<I, D> oracle, Word<I>... words) { return addAll(oracle, Arrays.asList(words)); }
[ "@", "SafeVarargs", "public", "final", "SampleSetEQOracle", "<", "I", ",", "D", ">", "addAll", "(", "MembershipOracle", "<", "I", ",", "D", ">", "oracle", ",", "Word", "<", "I", ">", "...", "words", ")", "{", "return", "addAll", "(", "oracle", ",", "Arrays", ".", "asList", "(", "words", ")", ")", ";", "}" ]
Adds several query words to the sample set. The expected output is determined by means of the specified membership oracle. @param oracle the membership oracle used to determine expected outputs @param words the words to be added to the sample set @return {@code this}, to enable chained {@code add} or {@code addAll} calls
[ "Adds", "several", "query", "words", "to", "the", "sample", "set", ".", "The", "expected", "output", "is", "determined", "by", "means", "of", "the", "specified", "membership", "oracle", "." ]
train
https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/oracles/equivalence-oracles/src/main/java/de/learnlib/oracle/equivalence/SampleSetEQOracle.java#L100-L103
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java
TimestampUtils.appendTime
private static void appendTime(StringBuilder sb, int hours, int minutes, int seconds, int nanos) { sb.append(NUMBERS[hours]); sb.append(':'); sb.append(NUMBERS[minutes]); sb.append(':'); sb.append(NUMBERS[seconds]); // Add nanoseconds. // This won't work for server versions < 7.2 which only want // a two digit fractional second, but we don't need to support 7.1 // anymore and getting the version number here is difficult. // if (nanos < 1000) { return; } sb.append('.'); int len = sb.length(); sb.append(nanos / 1000); // append microseconds int needZeros = 6 - (sb.length() - len); if (needZeros > 0) { sb.insert(len, ZEROS, 0, needZeros); } int end = sb.length() - 1; while (sb.charAt(end) == '0') { sb.deleteCharAt(end); end--; } }
java
private static void appendTime(StringBuilder sb, int hours, int minutes, int seconds, int nanos) { sb.append(NUMBERS[hours]); sb.append(':'); sb.append(NUMBERS[minutes]); sb.append(':'); sb.append(NUMBERS[seconds]); // Add nanoseconds. // This won't work for server versions < 7.2 which only want // a two digit fractional second, but we don't need to support 7.1 // anymore and getting the version number here is difficult. // if (nanos < 1000) { return; } sb.append('.'); int len = sb.length(); sb.append(nanos / 1000); // append microseconds int needZeros = 6 - (sb.length() - len); if (needZeros > 0) { sb.insert(len, ZEROS, 0, needZeros); } int end = sb.length() - 1; while (sb.charAt(end) == '0') { sb.deleteCharAt(end); end--; } }
[ "private", "static", "void", "appendTime", "(", "StringBuilder", "sb", ",", "int", "hours", ",", "int", "minutes", ",", "int", "seconds", ",", "int", "nanos", ")", "{", "sb", ".", "append", "(", "NUMBERS", "[", "hours", "]", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "NUMBERS", "[", "minutes", "]", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "sb", ".", "append", "(", "NUMBERS", "[", "seconds", "]", ")", ";", "// Add nanoseconds.", "// This won't work for server versions < 7.2 which only want", "// a two digit fractional second, but we don't need to support 7.1", "// anymore and getting the version number here is difficult.", "//", "if", "(", "nanos", "<", "1000", ")", "{", "return", ";", "}", "sb", ".", "append", "(", "'", "'", ")", ";", "int", "len", "=", "sb", ".", "length", "(", ")", ";", "sb", ".", "append", "(", "nanos", "/", "1000", ")", ";", "// append microseconds", "int", "needZeros", "=", "6", "-", "(", "sb", ".", "length", "(", ")", "-", "len", ")", ";", "if", "(", "needZeros", ">", "0", ")", "{", "sb", ".", "insert", "(", "len", ",", "ZEROS", ",", "0", ",", "needZeros", ")", ";", "}", "int", "end", "=", "sb", ".", "length", "(", ")", "-", "1", ";", "while", "(", "sb", ".", "charAt", "(", "end", ")", "==", "'", "'", ")", "{", "sb", ".", "deleteCharAt", "(", "end", ")", ";", "end", "--", ";", "}", "}" ]
Appends time part to the {@code StringBuilder} in PostgreSQL-compatible format. The function truncates {@param nanos} to microseconds. The value is expected to be rounded beforehand. @param sb destination @param hours hours @param minutes minutes @param seconds seconds @param nanos nanoseconds
[ "Appends", "time", "part", "to", "the", "{" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java#L690-L720
micronaut-projects/micronaut-core
http-client/src/main/java/io/micronaut/http/client/interceptor/HttpClientIntroductionAdvice.java
HttpClientIntroductionAdvice.resolveTemplate
private String resolveTemplate(AnnotationValue<Client> clientAnnotation, String templateString) { String path = clientAnnotation.get("path", String.class).orElse(null); if (StringUtils.isNotEmpty(path)) { return path + templateString; } else { String value = clientAnnotation.getValue(String.class).orElse(null); if (StringUtils.isNotEmpty(value)) { if (value.startsWith("/")) { return value + templateString; } } return templateString; } }
java
private String resolveTemplate(AnnotationValue<Client> clientAnnotation, String templateString) { String path = clientAnnotation.get("path", String.class).orElse(null); if (StringUtils.isNotEmpty(path)) { return path + templateString; } else { String value = clientAnnotation.getValue(String.class).orElse(null); if (StringUtils.isNotEmpty(value)) { if (value.startsWith("/")) { return value + templateString; } } return templateString; } }
[ "private", "String", "resolveTemplate", "(", "AnnotationValue", "<", "Client", ">", "clientAnnotation", ",", "String", "templateString", ")", "{", "String", "path", "=", "clientAnnotation", ".", "get", "(", "\"path\"", ",", "String", ".", "class", ")", ".", "orElse", "(", "null", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "path", ")", ")", "{", "return", "path", "+", "templateString", ";", "}", "else", "{", "String", "value", "=", "clientAnnotation", ".", "getValue", "(", "String", ".", "class", ")", ".", "orElse", "(", "null", ")", ";", "if", "(", "StringUtils", ".", "isNotEmpty", "(", "value", ")", ")", "{", "if", "(", "value", ".", "startsWith", "(", "\"/\"", ")", ")", "{", "return", "value", "+", "templateString", ";", "}", "}", "return", "templateString", ";", "}", "}" ]
Resolve the template for the client annotation. @param clientAnnotation client annotation reference @param templateString template to be applied @return resolved template contents
[ "Resolve", "the", "template", "for", "the", "client", "annotation", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/http-client/src/main/java/io/micronaut/http/client/interceptor/HttpClientIntroductionAdvice.java#L580-L593
dnsjava/dnsjava
org/xbill/DNS/TSIG.java
TSIG.verify
public int verify(Message m, byte [] b, TSIGRecord old) { return verify(m, b, b.length, old); }
java
public int verify(Message m, byte [] b, TSIGRecord old) { return verify(m, b, b.length, old); }
[ "public", "int", "verify", "(", "Message", "m", ",", "byte", "[", "]", "b", ",", "TSIGRecord", "old", ")", "{", "return", "verify", "(", "m", ",", "b", ",", "b", ".", "length", ",", "old", ")", ";", "}" ]
Verifies a TSIG record on an incoming message. Since this is only called in the context where a TSIG is expected to be present, it is an error if one is not present. After calling this routine, Message.isVerified() may be called on this message. @param m The message @param b The message in unparsed form. This is necessary since TSIG signs the message in wire format, and we can't recreate the exact wire format (with the same name compression). @param old If this message is a response, the TSIG from the request @return The result of the verification (as an Rcode) @see Rcode
[ "Verifies", "a", "TSIG", "record", "on", "an", "incoming", "message", ".", "Since", "this", "is", "only", "called", "in", "the", "context", "where", "a", "TSIG", "is", "expected", "to", "be", "present", "it", "is", "an", "error", "if", "one", "is", "not", "present", ".", "After", "calling", "this", "routine", "Message", ".", "isVerified", "()", "may", "be", "called", "on", "this", "message", "." ]
train
https://github.com/dnsjava/dnsjava/blob/d97b6a0685d59143372bb392ab591dd8dd840b61/org/xbill/DNS/TSIG.java#L526-L529
aws/aws-sdk-java
aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/DescribeSigningJobResult.java
DescribeSigningJobResult.withSigningParameters
public DescribeSigningJobResult withSigningParameters(java.util.Map<String, String> signingParameters) { setSigningParameters(signingParameters); return this; }
java
public DescribeSigningJobResult withSigningParameters(java.util.Map<String, String> signingParameters) { setSigningParameters(signingParameters); return this; }
[ "public", "DescribeSigningJobResult", "withSigningParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "signingParameters", ")", "{", "setSigningParameters", "(", "signingParameters", ")", ";", "return", "this", ";", "}" ]
<p> Map of user-assigned key-value pairs used during signing. These values contain any information that you specified for use in your signing job. </p> @param signingParameters Map of user-assigned key-value pairs used during signing. These values contain any information that you specified for use in your signing job. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Map", "of", "user", "-", "assigned", "key", "-", "value", "pairs", "used", "during", "signing", ".", "These", "values", "contain", "any", "information", "that", "you", "specified", "for", "use", "in", "your", "signing", "job", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-signer/src/main/java/com/amazonaws/services/signer/model/DescribeSigningJobResult.java#L387-L390
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.updateView
public JenkinsServer updateView(String viewName, String viewXml) throws IOException { return this.updateView(viewName, viewXml, true); }
java
public JenkinsServer updateView(String viewName, String viewXml) throws IOException { return this.updateView(viewName, viewXml, true); }
[ "public", "JenkinsServer", "updateView", "(", "String", "viewName", ",", "String", "viewXml", ")", "throws", "IOException", "{", "return", "this", ".", "updateView", "(", "viewName", ",", "viewXml", ",", "true", ")", ";", "}" ]
Update the xml description of an existing view @param viewName name of the view. @param viewXml the view configuration. @throws IOException in case of an error.
[ "Update", "the", "xml", "description", "of", "an", "existing", "view" ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L581-L583
lessthanoptimal/BoofCV
main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java
LinearContourLabelChang2004.handleStep2
private void handleStep2(GrayS32 labeled, int label) { // if the blob is not labeled and in this state it cannot be against the left side of the image if( label == 0 ) label = labeled.data[indexOut-1]; ContourPacked c = contours.get(label-1); c.internalIndexes.add( packedPoints.size() ); packedPoints.grow(); tracer.setMaxContourSize(saveInternalContours?maxContourSize:0); tracer.trace(label,x,y,false); // See if the inner contour exceeded the maximum or minimum size. If so free its points if( packedPoints.sizeOfTail() >= maxContourSize || packedPoints.sizeOfTail() < minContourSize ) { packedPoints.removeTail(); packedPoints.grow(); } }
java
private void handleStep2(GrayS32 labeled, int label) { // if the blob is not labeled and in this state it cannot be against the left side of the image if( label == 0 ) label = labeled.data[indexOut-1]; ContourPacked c = contours.get(label-1); c.internalIndexes.add( packedPoints.size() ); packedPoints.grow(); tracer.setMaxContourSize(saveInternalContours?maxContourSize:0); tracer.trace(label,x,y,false); // See if the inner contour exceeded the maximum or minimum size. If so free its points if( packedPoints.sizeOfTail() >= maxContourSize || packedPoints.sizeOfTail() < minContourSize ) { packedPoints.removeTail(); packedPoints.grow(); } }
[ "private", "void", "handleStep2", "(", "GrayS32", "labeled", ",", "int", "label", ")", "{", "// if the blob is not labeled and in this state it cannot be against the left side of the image", "if", "(", "label", "==", "0", ")", "label", "=", "labeled", ".", "data", "[", "indexOut", "-", "1", "]", ";", "ContourPacked", "c", "=", "contours", ".", "get", "(", "label", "-", "1", ")", ";", "c", ".", "internalIndexes", ".", "add", "(", "packedPoints", ".", "size", "(", ")", ")", ";", "packedPoints", ".", "grow", "(", ")", ";", "tracer", ".", "setMaxContourSize", "(", "saveInternalContours", "?", "maxContourSize", ":", "0", ")", ";", "tracer", ".", "trace", "(", "label", ",", "x", ",", "y", ",", "false", ")", ";", "// See if the inner contour exceeded the maximum or minimum size. If so free its points", "if", "(", "packedPoints", ".", "sizeOfTail", "(", ")", ">=", "maxContourSize", "||", "packedPoints", ".", "sizeOfTail", "(", ")", "<", "minContourSize", ")", "{", "packedPoints", ".", "removeTail", "(", ")", ";", "packedPoints", ".", "grow", "(", ")", ";", "}", "}" ]
Step 2: If the pixel below is unmarked and white then it must be an internal contour Same behavior it the pixel in question has been labeled or not already
[ "Step", "2", ":", "If", "the", "pixel", "below", "is", "unmarked", "and", "white", "then", "it", "must", "be", "an", "internal", "contour", "Same", "behavior", "it", "the", "pixel", "in", "question", "has", "been", "labeled", "or", "not", "already" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-ip/src/main/java/boofcv/alg/filter/binary/LinearContourLabelChang2004.java#L194-L210
roboconf/roboconf-platform
core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java
Ec2IaasHandler.createEc2Client
public static AmazonEC2 createEc2Client( Map<String,String> targetProperties ) throws TargetException { parseProperties( targetProperties ); // Configure the IaaS client AWSCredentials credentials = new BasicAWSCredentials( targetProperties.get(Ec2Constants.EC2_ACCESS_KEY), targetProperties.get(Ec2Constants.EC2_SECRET_KEY)); AmazonEC2 ec2 = new AmazonEC2Client( credentials ); ec2.setEndpoint( targetProperties.get(Ec2Constants.EC2_ENDPOINT )); return ec2; }
java
public static AmazonEC2 createEc2Client( Map<String,String> targetProperties ) throws TargetException { parseProperties( targetProperties ); // Configure the IaaS client AWSCredentials credentials = new BasicAWSCredentials( targetProperties.get(Ec2Constants.EC2_ACCESS_KEY), targetProperties.get(Ec2Constants.EC2_SECRET_KEY)); AmazonEC2 ec2 = new AmazonEC2Client( credentials ); ec2.setEndpoint( targetProperties.get(Ec2Constants.EC2_ENDPOINT )); return ec2; }
[ "public", "static", "AmazonEC2", "createEc2Client", "(", "Map", "<", "String", ",", "String", ">", "targetProperties", ")", "throws", "TargetException", "{", "parseProperties", "(", "targetProperties", ")", ";", "// Configure the IaaS client", "AWSCredentials", "credentials", "=", "new", "BasicAWSCredentials", "(", "targetProperties", ".", "get", "(", "Ec2Constants", ".", "EC2_ACCESS_KEY", ")", ",", "targetProperties", ".", "get", "(", "Ec2Constants", ".", "EC2_SECRET_KEY", ")", ")", ";", "AmazonEC2", "ec2", "=", "new", "AmazonEC2Client", "(", "credentials", ")", ";", "ec2", ".", "setEndpoint", "(", "targetProperties", ".", "get", "(", "Ec2Constants", ".", "EC2_ENDPOINT", ")", ")", ";", "return", "ec2", ";", "}" ]
Creates a client for EC2. @param targetProperties the target properties (not null) @return a non-null client @throws TargetException if properties are invalid
[ "Creates", "a", "client", "for", "EC2", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-target-iaas-ec2/src/main/java/net/roboconf/target/ec2/internal/Ec2IaasHandler.java#L268-L281
smurn/jPLY
jply/src/main/java/org/smurn/jply/util/RectBounds.java
RectBounds.addPoint
public void addPoint(final double x, final double y, final double z) { minX = Math.min(minX, x); minY = Math.min(minY, y); minZ = Math.min(minZ, z); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); maxZ = Math.max(maxZ, z); }
java
public void addPoint(final double x, final double y, final double z) { minX = Math.min(minX, x); minY = Math.min(minY, y); minZ = Math.min(minZ, z); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y); maxZ = Math.max(maxZ, z); }
[ "public", "void", "addPoint", "(", "final", "double", "x", ",", "final", "double", "y", ",", "final", "double", "z", ")", "{", "minX", "=", "Math", ".", "min", "(", "minX", ",", "x", ")", ";", "minY", "=", "Math", ".", "min", "(", "minY", ",", "y", ")", ";", "minZ", "=", "Math", ".", "min", "(", "minZ", ",", "z", ")", ";", "maxX", "=", "Math", ".", "max", "(", "maxX", ",", "x", ")", ";", "maxY", "=", "Math", ".", "max", "(", "maxY", ",", "y", ")", ";", "maxZ", "=", "Math", ".", "max", "(", "maxZ", ",", "z", ")", ";", "}" ]
Increases the bounds to include a given point. <p>If the point is already in the interior of the bounded area the bounds are not changed.</p> @param x Coordinate of the point to include. @param y Coordinate of the point to include. @param z Coordinate of the point to include.
[ "Increases", "the", "bounds", "to", "include", "a", "given", "point", ".", "<p", ">", "If", "the", "point", "is", "already", "in", "the", "interior", "of", "the", "bounded", "area", "the", "bounds", "are", "not", "changed", ".", "<", "/", "p", ">" ]
train
https://github.com/smurn/jPLY/blob/77cb8c47fff7549ae1da8d8568ad8bdf374fe89f/jply/src/main/java/org/smurn/jply/util/RectBounds.java#L70-L77
mirage-sql/mirage
src/main/java/com/miragesql/miragesql/SqlExecutor.java
SqlExecutor.fillIdentityPrimaryKeys
@SuppressWarnings("unchecked") protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException { BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.IDENTITY){ if(rs.next()){ Class<?> propertyType = propertyDesc.getPropertyType(); @SuppressWarnings("rawtypes") ValueType valueType = MirageUtil.getValueType(propertyType, propertyDesc, dialect, valueTypes); if(valueType != null){ propertyDesc.setValue(entity, valueType.get(propertyType, rs, 1)); } } } } }
java
@SuppressWarnings("unchecked") protected void fillIdentityPrimaryKeys(Object entity, ResultSet rs) throws SQLException { BeanDesc beanDesc = beanDescFactory.getBeanDesc(entity.getClass()); int size = beanDesc.getPropertyDescSize(); for(int i=0; i < size; i++){ PropertyDesc propertyDesc = beanDesc.getPropertyDesc(i); PrimaryKey primaryKey = propertyDesc.getAnnotation(PrimaryKey.class); if(primaryKey != null && primaryKey.generationType() == GenerationType.IDENTITY){ if(rs.next()){ Class<?> propertyType = propertyDesc.getPropertyType(); @SuppressWarnings("rawtypes") ValueType valueType = MirageUtil.getValueType(propertyType, propertyDesc, dialect, valueTypes); if(valueType != null){ propertyDesc.setValue(entity, valueType.get(propertyType, rs, 1)); } } } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "protected", "void", "fillIdentityPrimaryKeys", "(", "Object", "entity", ",", "ResultSet", "rs", ")", "throws", "SQLException", "{", "BeanDesc", "beanDesc", "=", "beanDescFactory", ".", "getBeanDesc", "(", "entity", ".", "getClass", "(", ")", ")", ";", "int", "size", "=", "beanDesc", ".", "getPropertyDescSize", "(", ")", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "size", ";", "i", "++", ")", "{", "PropertyDesc", "propertyDesc", "=", "beanDesc", ".", "getPropertyDesc", "(", "i", ")", ";", "PrimaryKey", "primaryKey", "=", "propertyDesc", ".", "getAnnotation", "(", "PrimaryKey", ".", "class", ")", ";", "if", "(", "primaryKey", "!=", "null", "&&", "primaryKey", ".", "generationType", "(", ")", "==", "GenerationType", ".", "IDENTITY", ")", "{", "if", "(", "rs", ".", "next", "(", ")", ")", "{", "Class", "<", "?", ">", "propertyType", "=", "propertyDesc", ".", "getPropertyType", "(", ")", ";", "@", "SuppressWarnings", "(", "\"rawtypes\"", ")", "ValueType", "valueType", "=", "MirageUtil", ".", "getValueType", "(", "propertyType", ",", "propertyDesc", ",", "dialect", ",", "valueTypes", ")", ";", "if", "(", "valueType", "!=", "null", ")", "{", "propertyDesc", ".", "setValue", "(", "entity", ",", "valueType", ".", "get", "(", "propertyType", ",", "rs", ",", "1", ")", ")", ";", "}", "}", "}", "}", "}" ]
Sets GenerationType.IDENTITY properties value. @param entity the entity @param rs the result set @throws SQLException if something goes wrong.
[ "Sets", "GenerationType", ".", "IDENTITY", "properties", "value", "." ]
train
https://github.com/mirage-sql/mirage/blob/29a44b7ad267b5a48bc250cd0ef7d74813d46889/src/main/java/com/miragesql/miragesql/SqlExecutor.java#L437-L457
astrapi69/jaulp-wicket
jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/ajax/editable/tabs/AjaxAddableTabbedPanel.java
AjaxAddableTabbedPanel.newAddTabButtonLabel
protected Label newAddTabButtonLabel(final String id, final IModel<String> model) { return ComponentFactory.newLabel(id, model); }
java
protected Label newAddTabButtonLabel(final String id, final IModel<String> model) { return ComponentFactory.newLabel(id, model); }
[ "protected", "Label", "newAddTabButtonLabel", "(", "final", "String", "id", ",", "final", "IModel", "<", "String", ">", "model", ")", "{", "return", "ComponentFactory", ".", "newLabel", "(", "id", ",", "model", ")", ";", "}" ]
Factory method for creating the new label of the button. @param id the id @param model the model @return the new label of the button.
[ "Factory", "method", "for", "creating", "the", "new", "label", "of", "the", "button", "." ]
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-components/src/main/java/de/alpharogroup/wicket/components/ajax/editable/tabs/AjaxAddableTabbedPanel.java#L315-L318
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/stat/cmp/cmppolicy_stats.java
cmppolicy_stats.get
public static cmppolicy_stats get(nitro_service service, String name) throws Exception{ cmppolicy_stats obj = new cmppolicy_stats(); obj.set_name(name); cmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service); return response; }
java
public static cmppolicy_stats get(nitro_service service, String name) throws Exception{ cmppolicy_stats obj = new cmppolicy_stats(); obj.set_name(name); cmppolicy_stats response = (cmppolicy_stats) obj.stat_resource(service); return response; }
[ "public", "static", "cmppolicy_stats", "get", "(", "nitro_service", "service", ",", "String", "name", ")", "throws", "Exception", "{", "cmppolicy_stats", "obj", "=", "new", "cmppolicy_stats", "(", ")", ";", "obj", ".", "set_name", "(", "name", ")", ";", "cmppolicy_stats", "response", "=", "(", "cmppolicy_stats", ")", "obj", ".", "stat_resource", "(", "service", ")", ";", "return", "response", ";", "}" ]
Use this API to fetch statistics of cmppolicy_stats resource of given name .
[ "Use", "this", "API", "to", "fetch", "statistics", "of", "cmppolicy_stats", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/stat/cmp/cmppolicy_stats.java#L169-L174
hudson3-plugins/warnings-plugin
src/main/java/hudson/plugins/warnings/parser/MsBuildParser.java
MsBuildParser.determinePriority
private Priority determinePriority(final Matcher matcher) { if (isOfType(matcher, "note") || isOfType(matcher, "info")) { return Priority.LOW; } else if (isOfType(matcher, "warning")) { return Priority.NORMAL; } return Priority.HIGH; }
java
private Priority determinePriority(final Matcher matcher) { if (isOfType(matcher, "note") || isOfType(matcher, "info")) { return Priority.LOW; } else if (isOfType(matcher, "warning")) { return Priority.NORMAL; } return Priority.HIGH; }
[ "private", "Priority", "determinePriority", "(", "final", "Matcher", "matcher", ")", "{", "if", "(", "isOfType", "(", "matcher", ",", "\"note\"", ")", "||", "isOfType", "(", "matcher", ",", "\"info\"", ")", ")", "{", "return", "Priority", ".", "LOW", ";", "}", "else", "if", "(", "isOfType", "(", "matcher", ",", "\"warning\"", ")", ")", "{", "return", "Priority", ".", "NORMAL", ";", "}", "return", "Priority", ".", "HIGH", ";", "}" ]
Determines the priority of the warning. @param matcher the matcher to get the matches from @return the priority of the warning
[ "Determines", "the", "priority", "of", "the", "warning", "." ]
train
https://github.com/hudson3-plugins/warnings-plugin/blob/462c9f3dffede9120173935567392b22520b0966/src/main/java/hudson/plugins/warnings/parser/MsBuildParser.java#L91-L99
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/V1InstanceCreator.java
V1InstanceCreator.buildRun
public BuildRun buildRun(BuildProject buildProject, String name, DateTime date) { return buildRun(buildProject, name, date, null); }
java
public BuildRun buildRun(BuildProject buildProject, String name, DateTime date) { return buildRun(buildProject, name, date, null); }
[ "public", "BuildRun", "buildRun", "(", "BuildProject", "buildProject", ",", "String", "name", ",", "DateTime", "date", ")", "{", "return", "buildRun", "(", "buildProject", ",", "name", ",", "date", ",", "null", ")", ";", "}" ]
Create a new Build Run in the given Build Project with a name and date. @param buildProject The Build Project this Build Run belongs to. @param name Name of the build project. @param date The Date this Build Run ran. @return A newly minted Build Run that exists in the VersionOne system.
[ "Create", "a", "new", "Build", "Run", "in", "the", "given", "Build", "Project", "with", "a", "name", "and", "date", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/V1InstanceCreator.java#L896-L899
alkacon/opencms-core
src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java
CmsContainerpageHandler.createRawMenuEntry
protected CmsContextMenuEntry createRawMenuEntry(CmsUUID structureId, final Runnable action) { CmsContextMenuEntry entry = new CmsContextMenuEntry(this, structureId, new I_CmsContextMenuCommand() { public void execute( CmsUUID innerStructureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { if (action != null) { action.run(); } } public A_CmsContextMenuItem getItemWidget( CmsUUID innerStructureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }); return entry; }
java
protected CmsContextMenuEntry createRawMenuEntry(CmsUUID structureId, final Runnable action) { CmsContextMenuEntry entry = new CmsContextMenuEntry(this, structureId, new I_CmsContextMenuCommand() { public void execute( CmsUUID innerStructureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { if (action != null) { action.run(); } } public A_CmsContextMenuItem getItemWidget( CmsUUID innerStructureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) { return null; } public boolean hasItemWidget() { return false; } }); return entry; }
[ "protected", "CmsContextMenuEntry", "createRawMenuEntry", "(", "CmsUUID", "structureId", ",", "final", "Runnable", "action", ")", "{", "CmsContextMenuEntry", "entry", "=", "new", "CmsContextMenuEntry", "(", "this", ",", "structureId", ",", "new", "I_CmsContextMenuCommand", "(", ")", "{", "public", "void", "execute", "(", "CmsUUID", "innerStructureId", ",", "I_CmsContextMenuHandler", "handler", ",", "CmsContextMenuEntryBean", "bean", ")", "{", "if", "(", "action", "!=", "null", ")", "{", "action", ".", "run", "(", ")", ";", "}", "}", "public", "A_CmsContextMenuItem", "getItemWidget", "(", "CmsUUID", "innerStructureId", ",", "I_CmsContextMenuHandler", "handler", ",", "CmsContextMenuEntryBean", "bean", ")", "{", "return", "null", ";", "}", "public", "boolean", "hasItemWidget", "(", ")", "{", "return", "false", ";", "}", "}", ")", ";", "return", "entry", ";", "}" ]
Creates a menu entry based on a structure id and action without anything else.<p> @param structureId the structure id @param action the action for the menu entry @return the new menu entry
[ "Creates", "a", "menu", "entry", "based", "on", "a", "structure", "id", "and", "action", "without", "anything", "else", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/containerpage/client/CmsContainerpageHandler.java#L1266-L1295
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/io/SwapFile.java
SwapFile.get
public static SwapFile get(final File parent, final String child) throws IOException { return get(parent, child, SpoolConfig.getDefaultSpoolConfig().fileCleaner); }
java
public static SwapFile get(final File parent, final String child) throws IOException { return get(parent, child, SpoolConfig.getDefaultSpoolConfig().fileCleaner); }
[ "public", "static", "SwapFile", "get", "(", "final", "File", "parent", ",", "final", "String", "child", ")", "throws", "IOException", "{", "return", "get", "(", "parent", ",", "child", ",", "SpoolConfig", ".", "getDefaultSpoolConfig", "(", ")", ".", "fileCleaner", ")", ";", "}" ]
Obtain SwapFile by parent file and name. @param parent - parent File @param child - String with file name @return SwapFile swap file @throws IOException I/O error
[ "Obtain", "SwapFile", "by", "parent", "file", "and", "name", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/util/io/SwapFile.java#L109-L113
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.assertTableDoesNotExist
@SafeVarargs public static void assertTableDoesNotExist(String message, DB db, String... tableNames) throws DBAssertionError { multipleTableExistenceAssertions(CallInfo.create(message), db, tableNames, false); }
java
@SafeVarargs public static void assertTableDoesNotExist(String message, DB db, String... tableNames) throws DBAssertionError { multipleTableExistenceAssertions(CallInfo.create(message), db, tableNames, false); }
[ "@", "SafeVarargs", "public", "static", "void", "assertTableDoesNotExist", "(", "String", "message", ",", "DB", "db", ",", "String", "...", "tableNames", ")", "throws", "DBAssertionError", "{", "multipleTableExistenceAssertions", "(", "CallInfo", ".", "create", "(", "message", ")", ",", "db", ",", "tableNames", ",", "false", ")", ";", "}" ]
Assert that tables do not exist in a database (error message variant). @param message Error message. @param db Database. @param tableNames Table names. @throws DBAssertionError If the assertion fails. @see #assertTableExists(String, DB, String...) @see #drop(Table...) @since 1.2
[ "Assert", "that", "tables", "do", "not", "exist", "in", "a", "database", "(", "error", "message", "variant", ")", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L842-L845
wildfly/wildfly-core
controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java
ExtensionRegistry.initializeParsers
public final void initializeParsers(final Extension extension, final String moduleName, final XMLMapper xmlMapper) { ExtensionParsingContextImpl parsingContext = new ExtensionParsingContextImpl(moduleName, xmlMapper); extension.initializeParsers(parsingContext); parsingContext.attemptCurrentParserInitialization(); }
java
public final void initializeParsers(final Extension extension, final String moduleName, final XMLMapper xmlMapper) { ExtensionParsingContextImpl parsingContext = new ExtensionParsingContextImpl(moduleName, xmlMapper); extension.initializeParsers(parsingContext); parsingContext.attemptCurrentParserInitialization(); }
[ "public", "final", "void", "initializeParsers", "(", "final", "Extension", "extension", ",", "final", "String", "moduleName", ",", "final", "XMLMapper", "xmlMapper", ")", "{", "ExtensionParsingContextImpl", "parsingContext", "=", "new", "ExtensionParsingContextImpl", "(", "moduleName", ",", "xmlMapper", ")", ";", "extension", ".", "initializeParsers", "(", "parsingContext", ")", ";", "parsingContext", ".", "attemptCurrentParserInitialization", "(", ")", ";", "}" ]
Ask the given {@code extension} to {@link Extension#initializeParsers(ExtensionParsingContext) initialize its parsers}. Should be used in preference to calling {@link #getExtensionParsingContext(String, XMLMapper)} and passing the returned value to {@code Extension#initializeParsers(context)} as this method allows the registry to take additional action when the extension is done. @param extension the extension. Cannot be {@code null} @param moduleName the name of the extension's module. Cannot be {@code null} @param xmlMapper the {@link XMLMapper} handling the extension parsing. Can be {@code null} if there won't be any actual parsing (e.g. in a slave Host Controller or in a server in a managed domain)
[ "Ask", "the", "given", "{", "@code", "extension", "}", "to", "{", "@link", "Extension#initializeParsers", "(", "ExtensionParsingContext", ")", "initialize", "its", "parsers", "}", ".", "Should", "be", "used", "in", "preference", "to", "calling", "{", "@link", "#getExtensionParsingContext", "(", "String", "XMLMapper", ")", "}", "and", "passing", "the", "returned", "value", "to", "{", "@code", "Extension#initializeParsers", "(", "context", ")", "}", "as", "this", "method", "allows", "the", "registry", "to", "take", "additional", "action", "when", "the", "extension", "is", "done", "." ]
train
https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/extension/ExtensionRegistry.java#L246-L250
DataArt/CalculationEngine
calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DependencyExtractors.java
DependencyExtractors.toDataModel
static IDataModel toDataModel(final IDataModel book, final ICellAddress address) { return toDataModel(DataModelConverters.toWorkbook(book), address); }
java
static IDataModel toDataModel(final IDataModel book, final ICellAddress address) { return toDataModel(DataModelConverters.toWorkbook(book), address); }
[ "static", "IDataModel", "toDataModel", "(", "final", "IDataModel", "book", ",", "final", "ICellAddress", "address", ")", "{", "return", "toDataModel", "(", "DataModelConverters", ".", "toWorkbook", "(", "book", ")", ",", "address", ")", ";", "}" ]
Invokes {@link #toDataModel(Workbook, ICellAddress)} with {@link IDataModel} converted to {@link Workbook}.
[ "Invokes", "{" ]
train
https://github.com/DataArt/CalculationEngine/blob/34ce1d9c1f9b57a502906b274311d28580b134e5/calculation-engine/engine-converters/src/main/java/com/dataart/spreadsheetanalytics/engine/DependencyExtractors.java#L62-L64
BioPAX/Paxtools
sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/VNode.java
VNode.setBounds
public void setBounds(float w, float h) { this.glyph.getBbox().setW(w); this.glyph.getBbox().setH(h); }
java
public void setBounds(float w, float h) { this.glyph.getBbox().setW(w); this.glyph.getBbox().setH(h); }
[ "public", "void", "setBounds", "(", "float", "w", ",", "float", "h", ")", "{", "this", ".", "glyph", ".", "getBbox", "(", ")", ".", "setW", "(", "w", ")", ";", "this", ".", "glyph", ".", "getBbox", "(", ")", ".", "setH", "(", "h", ")", ";", "}" ]
Sets the bound of this VNode by given width and height @param w new width @param h new height
[ "Sets", "the", "bound", "of", "this", "VNode", "by", "given", "width", "and", "height" ]
train
https://github.com/BioPAX/Paxtools/blob/2f93afa94426bf8b5afc2e0e61cd4b269a83288d/sbgn-converter/src/main/java/org/biopax/paxtools/io/sbgn/VNode.java#L142-L146
nohana/Amalgam
amalgam/src/main/java/com/amalgam/app/FragmentManagerUtils.java
FragmentManagerUtils.findFragmentById
@SuppressWarnings("unchecked") // we know that the returning fragment is child of fragment. @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static <F extends android.app.Fragment> F findFragmentById(android.app.FragmentManager manager, int id) { return (F) manager.findFragmentById(id); }
java
@SuppressWarnings("unchecked") // we know that the returning fragment is child of fragment. @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static <F extends android.app.Fragment> F findFragmentById(android.app.FragmentManager manager, int id) { return (F) manager.findFragmentById(id); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "// we know that the returning fragment is child of fragment.", "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "HONEYCOMB", ")", "public", "static", "<", "F", "extends", "android", ".", "app", ".", "Fragment", ">", "F", "findFragmentById", "(", "android", ".", "app", ".", "FragmentManager", "manager", ",", "int", "id", ")", "{", "return", "(", "F", ")", "manager", ".", "findFragmentById", "(", "id", ")", ";", "}" ]
Find a fragment that is under {@link android.app.FragmentManager}'s control by the id. @param manager the fragment manager. @param id the fragment id. @param <F> the concrete fragment class parameter. @return the fragment.
[ "Find", "a", "fragment", "that", "is", "under", "{" ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/app/FragmentManagerUtils.java#L23-L27
Azure/azure-sdk-for-java
datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java
ServicesInner.createOrUpdateAsync
public Observable<DataMigrationServiceInner> createOrUpdateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) { return createOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() { @Override public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) { return response.body(); } }); }
java
public Observable<DataMigrationServiceInner> createOrUpdateAsync(String groupName, String serviceName, DataMigrationServiceInner parameters) { return createOrUpdateWithServiceResponseAsync(groupName, serviceName, parameters).map(new Func1<ServiceResponse<DataMigrationServiceInner>, DataMigrationServiceInner>() { @Override public DataMigrationServiceInner call(ServiceResponse<DataMigrationServiceInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DataMigrationServiceInner", ">", "createOrUpdateAsync", "(", "String", "groupName", ",", "String", "serviceName", ",", "DataMigrationServiceInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "groupName", ",", "serviceName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "DataMigrationServiceInner", ">", ",", "DataMigrationServiceInner", ">", "(", ")", "{", "@", "Override", "public", "DataMigrationServiceInner", "call", "(", "ServiceResponse", "<", "DataMigrationServiceInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Create or update DMS Instance. The services resource is the top-level resource that represents the Data Migration Service. The PUT method creates a new service or updates an existing one. When a service is updated, existing child resources (i.e. tasks) are unaffected. Services currently support a single kind, "vm", which refers to a VM-based service, although other kinds may be added in the future. This method can change the kind, SKU, and network of the service, but if tasks are currently running (i.e. the service is busy), this will fail with 400 Bad Request ("ServiceIsBusy"). The provider will reply when successful with 200 OK or 201 Created. Long-running operations use the provisioningState property. @param groupName Name of the resource group @param serviceName Name of the service @param parameters Information about the service @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Create", "or", "update", "DMS", "Instance", ".", "The", "services", "resource", "is", "the", "top", "-", "level", "resource", "that", "represents", "the", "Data", "Migration", "Service", ".", "The", "PUT", "method", "creates", "a", "new", "service", "or", "updates", "an", "existing", "one", ".", "When", "a", "service", "is", "updated", "existing", "child", "resources", "(", "i", ".", "e", ".", "tasks", ")", "are", "unaffected", ".", "Services", "currently", "support", "a", "single", "kind", "vm", "which", "refers", "to", "a", "VM", "-", "based", "service", "although", "other", "kinds", "may", "be", "added", "in", "the", "future", ".", "This", "method", "can", "change", "the", "kind", "SKU", "and", "network", "of", "the", "service", "but", "if", "tasks", "are", "currently", "running", "(", "i", ".", "e", ".", "the", "service", "is", "busy", ")", "this", "will", "fail", "with", "400", "Bad", "Request", "(", "ServiceIsBusy", ")", ".", "The", "provider", "will", "reply", "when", "successful", "with", "200", "OK", "or", "201", "Created", ".", "Long", "-", "running", "operations", "use", "the", "provisioningState", "property", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ServicesInner.java#L193-L200
Hygieia/Hygieia
api/src/main/java/com/capitalone/dashboard/service/UserInfoServiceImpl.java
UserInfoServiceImpl.isUserValid
@Override public boolean isUserValid(String userId, AuthType authType) { if (userInfoRepository.findByUsernameAndAuthType(userId, authType) != null) { return true; } else { if (authType == AuthType.LDAP) { try { return searchLdapUser(userId); } catch (NamingException ne) { LOGGER.error("Failed to query ldap for " + userId, ne); return false; } } else { return false; } } }
java
@Override public boolean isUserValid(String userId, AuthType authType) { if (userInfoRepository.findByUsernameAndAuthType(userId, authType) != null) { return true; } else { if (authType == AuthType.LDAP) { try { return searchLdapUser(userId); } catch (NamingException ne) { LOGGER.error("Failed to query ldap for " + userId, ne); return false; } } else { return false; } } }
[ "@", "Override", "public", "boolean", "isUserValid", "(", "String", "userId", ",", "AuthType", "authType", ")", "{", "if", "(", "userInfoRepository", ".", "findByUsernameAndAuthType", "(", "userId", ",", "authType", ")", "!=", "null", ")", "{", "return", "true", ";", "}", "else", "{", "if", "(", "authType", "==", "AuthType", ".", "LDAP", ")", "{", "try", "{", "return", "searchLdapUser", "(", "userId", ")", ";", "}", "catch", "(", "NamingException", "ne", ")", "{", "LOGGER", ".", "error", "(", "\"Failed to query ldap for \"", "+", "userId", ",", "ne", ")", ";", "return", "false", ";", "}", "}", "else", "{", "return", "false", ";", "}", "}", "}" ]
Can be called to check validity of userId when creating a dashboard remotely via api @param userId @param authType @return
[ "Can", "be", "called", "to", "check", "validity", "of", "userId", "when", "creating", "a", "dashboard", "remotely", "via", "api" ]
train
https://github.com/Hygieia/Hygieia/blob/d8b67a590da2744acf59bcd99d9b34ef1bb84890/api/src/main/java/com/capitalone/dashboard/service/UserInfoServiceImpl.java#L134-L150
apache/flink
flink-core/src/main/java/org/apache/flink/api/java/typeutils/RowTypeInfo.java
RowTypeInfo.projectFields
public static RowTypeInfo projectFields(RowTypeInfo rowType, int[] fieldMapping) { TypeInformation[] fieldTypes = new TypeInformation[fieldMapping.length]; String[] fieldNames = new String[fieldMapping.length]; for (int i = 0; i < fieldMapping.length; i++) { fieldTypes[i] = rowType.getTypeAt(fieldMapping[i]); fieldNames[i] = rowType.getFieldNames()[fieldMapping[i]]; } return new RowTypeInfo(fieldTypes, fieldNames); }
java
public static RowTypeInfo projectFields(RowTypeInfo rowType, int[] fieldMapping) { TypeInformation[] fieldTypes = new TypeInformation[fieldMapping.length]; String[] fieldNames = new String[fieldMapping.length]; for (int i = 0; i < fieldMapping.length; i++) { fieldTypes[i] = rowType.getTypeAt(fieldMapping[i]); fieldNames[i] = rowType.getFieldNames()[fieldMapping[i]]; } return new RowTypeInfo(fieldTypes, fieldNames); }
[ "public", "static", "RowTypeInfo", "projectFields", "(", "RowTypeInfo", "rowType", ",", "int", "[", "]", "fieldMapping", ")", "{", "TypeInformation", "[", "]", "fieldTypes", "=", "new", "TypeInformation", "[", "fieldMapping", ".", "length", "]", ";", "String", "[", "]", "fieldNames", "=", "new", "String", "[", "fieldMapping", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "fieldMapping", ".", "length", ";", "i", "++", ")", "{", "fieldTypes", "[", "i", "]", "=", "rowType", ".", "getTypeAt", "(", "fieldMapping", "[", "i", "]", ")", ";", "fieldNames", "[", "i", "]", "=", "rowType", ".", "getFieldNames", "(", ")", "[", "fieldMapping", "[", "i", "]", "]", ";", "}", "return", "new", "RowTypeInfo", "(", "fieldTypes", ",", "fieldNames", ")", ";", "}" ]
Creates a {@link RowTypeInfo} with projected fields. @param rowType The original RowTypeInfo whose fields are projected @param fieldMapping The field mapping of the projection @return A RowTypeInfo with projected fields.
[ "Creates", "a", "{", "@link", "RowTypeInfo", "}", "with", "projected", "fields", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/api/java/typeutils/RowTypeInfo.java#L388-L396
Squarespace/cldr
compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java
CalendarCodeGenerator.addSkeletonClassifierMethod
private void addSkeletonClassifierMethod(TypeSpec.Builder type, List<DateTimeData> dataList) { Set<String> dates = new LinkedHashSet<>(); Set<String> times = new LinkedHashSet<>(); for (DateTimeData data : dataList) { for (Skeleton skeleton : data.dateTimeSkeletons) { if (isDateSkeleton(skeleton.skeleton)) { dates.add(skeleton.skeleton); } else { times.add(skeleton.skeleton); } } } MethodSpec.Builder method = buildSkeletonType(dates, times); type.addMethod(method.build()); }
java
private void addSkeletonClassifierMethod(TypeSpec.Builder type, List<DateTimeData> dataList) { Set<String> dates = new LinkedHashSet<>(); Set<String> times = new LinkedHashSet<>(); for (DateTimeData data : dataList) { for (Skeleton skeleton : data.dateTimeSkeletons) { if (isDateSkeleton(skeleton.skeleton)) { dates.add(skeleton.skeleton); } else { times.add(skeleton.skeleton); } } } MethodSpec.Builder method = buildSkeletonType(dates, times); type.addMethod(method.build()); }
[ "private", "void", "addSkeletonClassifierMethod", "(", "TypeSpec", ".", "Builder", "type", ",", "List", "<", "DateTimeData", ">", "dataList", ")", "{", "Set", "<", "String", ">", "dates", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "Set", "<", "String", ">", "times", "=", "new", "LinkedHashSet", "<>", "(", ")", ";", "for", "(", "DateTimeData", "data", ":", "dataList", ")", "{", "for", "(", "Skeleton", "skeleton", ":", "data", ".", "dateTimeSkeletons", ")", "{", "if", "(", "isDateSkeleton", "(", "skeleton", ".", "skeleton", ")", ")", "{", "dates", ".", "add", "(", "skeleton", ".", "skeleton", ")", ";", "}", "else", "{", "times", ".", "add", "(", "skeleton", ".", "skeleton", ")", ";", "}", "}", "}", "MethodSpec", ".", "Builder", "method", "=", "buildSkeletonType", "(", "dates", ",", "times", ")", ";", "type", ".", "addMethod", "(", "method", ".", "build", "(", ")", ")", ";", "}" ]
Create a helper class to classify skeletons as either DATE or TIME.
[ "Create", "a", "helper", "class", "to", "classify", "skeletons", "as", "either", "DATE", "or", "TIME", "." ]
train
https://github.com/Squarespace/cldr/blob/54b752d4ec2457df56e98461618f9c0eec41e1e1/compiler/src/main/java/com/squarespace/cldr/codegen/CalendarCodeGenerator.java#L113-L128
sarl/sarl
main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java
SARLJvmModelInferrer.appendCloneFunctionIfCloneable
protected void appendCloneFunctionIfCloneable(GenerationContext context, XtendTypeDeclaration source, JvmGenericType target) { if (!target.isInterface() && this.inheritanceHelper.isSubTypeOf(target, Cloneable.class, null)) { appendCloneFunction(context, source, target); } }
java
protected void appendCloneFunctionIfCloneable(GenerationContext context, XtendTypeDeclaration source, JvmGenericType target) { if (!target.isInterface() && this.inheritanceHelper.isSubTypeOf(target, Cloneable.class, null)) { appendCloneFunction(context, source, target); } }
[ "protected", "void", "appendCloneFunctionIfCloneable", "(", "GenerationContext", "context", ",", "XtendTypeDeclaration", "source", ",", "JvmGenericType", "target", ")", "{", "if", "(", "!", "target", ".", "isInterface", "(", ")", "&&", "this", ".", "inheritanceHelper", ".", "isSubTypeOf", "(", "target", ",", "Cloneable", ".", "class", ",", "null", ")", ")", "{", "appendCloneFunction", "(", "context", ",", "source", ",", "target", ")", ";", "}", "}" ]
Append the clone function only if the type is a subtype of {@link Cloneable}. <p>The clone function replies a value of the current type, not {@code Object}. @param context the current generation context. @param source the source object. @param target the inferred JVM object. @since 0.6 @see #appendCloneFunction(GenerationContext, XtendTypeDeclaration, JvmGenericType)
[ "Append", "the", "clone", "function", "only", "if", "the", "type", "is", "a", "subtype", "of", "{", "@link", "Cloneable", "}", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang/src/io/sarl/lang/jvmmodel/SARLJvmModelInferrer.java#L2877-L2881
jamesagnew/hapi-fhir
hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/RestfulClientFactory.java
RestfulClientFactory.newClient
@Override public synchronized <T extends IRestfulClient> T newClient(Class<T> theClientType, String theServerBase) { validateConfigured(); if (!theClientType.isInterface()) { throw new ConfigurationException(theClientType.getCanonicalName() + " is not an interface"); } ClientInvocationHandlerFactory invocationHandler = myInvocationHandlers.get(theClientType); if (invocationHandler == null) { IHttpClient httpClient = getHttpClient(theServerBase); invocationHandler = new ClientInvocationHandlerFactory(httpClient, myContext, theServerBase, theClientType); for (Method nextMethod : theClientType.getMethods()) { BaseMethodBinding<?> binding = BaseMethodBinding.bindMethod(nextMethod, myContext, null); invocationHandler.addBinding(nextMethod, binding); } myInvocationHandlers.put(theClientType, invocationHandler); } return instantiateProxy(theClientType, invocationHandler.newInvocationHandler(this)); }
java
@Override public synchronized <T extends IRestfulClient> T newClient(Class<T> theClientType, String theServerBase) { validateConfigured(); if (!theClientType.isInterface()) { throw new ConfigurationException(theClientType.getCanonicalName() + " is not an interface"); } ClientInvocationHandlerFactory invocationHandler = myInvocationHandlers.get(theClientType); if (invocationHandler == null) { IHttpClient httpClient = getHttpClient(theServerBase); invocationHandler = new ClientInvocationHandlerFactory(httpClient, myContext, theServerBase, theClientType); for (Method nextMethod : theClientType.getMethods()) { BaseMethodBinding<?> binding = BaseMethodBinding.bindMethod(nextMethod, myContext, null); invocationHandler.addBinding(nextMethod, binding); } myInvocationHandlers.put(theClientType, invocationHandler); } return instantiateProxy(theClientType, invocationHandler.newInvocationHandler(this)); }
[ "@", "Override", "public", "synchronized", "<", "T", "extends", "IRestfulClient", ">", "T", "newClient", "(", "Class", "<", "T", ">", "theClientType", ",", "String", "theServerBase", ")", "{", "validateConfigured", "(", ")", ";", "if", "(", "!", "theClientType", ".", "isInterface", "(", ")", ")", "{", "throw", "new", "ConfigurationException", "(", "theClientType", ".", "getCanonicalName", "(", ")", "+", "\" is not an interface\"", ")", ";", "}", "ClientInvocationHandlerFactory", "invocationHandler", "=", "myInvocationHandlers", ".", "get", "(", "theClientType", ")", ";", "if", "(", "invocationHandler", "==", "null", ")", "{", "IHttpClient", "httpClient", "=", "getHttpClient", "(", "theServerBase", ")", ";", "invocationHandler", "=", "new", "ClientInvocationHandlerFactory", "(", "httpClient", ",", "myContext", ",", "theServerBase", ",", "theClientType", ")", ";", "for", "(", "Method", "nextMethod", ":", "theClientType", ".", "getMethods", "(", ")", ")", "{", "BaseMethodBinding", "<", "?", ">", "binding", "=", "BaseMethodBinding", ".", "bindMethod", "(", "nextMethod", ",", "myContext", ",", "null", ")", ";", "invocationHandler", ".", "addBinding", "(", "nextMethod", ",", "binding", ")", ";", "}", "myInvocationHandlers", ".", "put", "(", "theClientType", ",", "invocationHandler", ")", ";", "}", "return", "instantiateProxy", "(", "theClientType", ",", "invocationHandler", ".", "newInvocationHandler", "(", "this", ")", ")", ";", "}" ]
Instantiates a new client instance @param theClientType The client type, which is an interface type to be instantiated @param theServerBase The URL of the base for the restful FHIR server to connect to @return A newly created client @throws ConfigurationException If the interface type is not an interface
[ "Instantiates", "a", "new", "client", "instance" ]
train
https://github.com/jamesagnew/hapi-fhir/blob/150a84d52fe691b7f48fcb28247c4bddb7aec352/hapi-fhir-client/src/main/java/ca/uhn/fhir/rest/client/impl/RestfulClientFactory.java#L139-L159
loldevs/riotapi
rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java
ThrottledApiHandler.getSummoners
public Future<Map<String, Summoner>> getSummoners(String... names) { return new ApiFuture<>(() -> handler.getSummoners(names)); }
java
public Future<Map<String, Summoner>> getSummoners(String... names) { return new ApiFuture<>(() -> handler.getSummoners(names)); }
[ "public", "Future", "<", "Map", "<", "String", ",", "Summoner", ">", ">", "getSummoners", "(", "String", "...", "names", ")", "{", "return", "new", "ApiFuture", "<>", "(", "(", ")", "->", "handler", ".", "getSummoners", "(", "names", ")", ")", ";", "}" ]
Get summoner information for the summoners with the specified names @param names The names of the players @return A map, mapping standardized player names to summoner information @see <a href=https://developer.riotgames.com/api/methods#!/620/1930>Official API documentation</a> @see net.boreeas.riotapi.Util#standardizeSummonerName(java.lang.String)
[ "Get", "summoner", "information", "for", "the", "summoners", "with", "the", "specified", "names" ]
train
https://github.com/loldevs/riotapi/blob/0b8aac407aa5289845f249024f9732332855544f/rest/src/main/java/net/boreeas/riotapi/rest/ThrottledApiHandler.java#L1091-L1093
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java
TitlePaneCloseButtonPainter.paintCloseEnabled
private void paintCloseEnabled(Graphics2D g, JComponent c, int width, int height) { paintClose(g, c, width, height, enabled); }
java
private void paintCloseEnabled(Graphics2D g, JComponent c, int width, int height) { paintClose(g, c, width, height, enabled); }
[ "private", "void", "paintCloseEnabled", "(", "Graphics2D", "g", ",", "JComponent", "c", ",", "int", "width", ",", "int", "height", ")", "{", "paintClose", "(", "g", ",", "c", ",", "width", ",", "height", ",", "enabled", ")", ";", "}" ]
Paint the background enabled state. @param g the Graphics2D context to paint with. @param c the component. @param width the width of the component. @param height the height of the component.
[ "Paint", "the", "background", "enabled", "state", "." ]
train
https://github.com/khuxtable/seaglass/blob/f25ecba622923d7b29b64cb7d6068dd8005989b3/src/main/java/com/seaglasslookandfeel/painter/TitlePaneCloseButtonPainter.java#L115-L117
future-architect/uroborosql
src/main/java/jp/co/future/uroborosql/connection/DataSourceConnectionSupplierImpl.java
DataSourceConnectionSupplierImpl.setTransactionIsolation
public void setTransactionIsolation(final String dataSourceName, final int transactionIsolation) { if (Connection.TRANSACTION_READ_UNCOMMITTED == transactionIsolation || Connection.TRANSACTION_READ_COMMITTED == transactionIsolation || Connection.TRANSACTION_REPEATABLE_READ == transactionIsolation || Connection.TRANSACTION_SERIALIZABLE == transactionIsolation) { Map<String, String> props = getConnPropsByDataSourceName(dataSourceName); props.put(PROPS_TRANSACTION_ISOLATION, String.valueOf(transactionIsolation)); } else { throw new IllegalArgumentException("Unsupported level [" + transactionIsolation + "]"); } }
java
public void setTransactionIsolation(final String dataSourceName, final int transactionIsolation) { if (Connection.TRANSACTION_READ_UNCOMMITTED == transactionIsolation || Connection.TRANSACTION_READ_COMMITTED == transactionIsolation || Connection.TRANSACTION_REPEATABLE_READ == transactionIsolation || Connection.TRANSACTION_SERIALIZABLE == transactionIsolation) { Map<String, String> props = getConnPropsByDataSourceName(dataSourceName); props.put(PROPS_TRANSACTION_ISOLATION, String.valueOf(transactionIsolation)); } else { throw new IllegalArgumentException("Unsupported level [" + transactionIsolation + "]"); } }
[ "public", "void", "setTransactionIsolation", "(", "final", "String", "dataSourceName", ",", "final", "int", "transactionIsolation", ")", "{", "if", "(", "Connection", ".", "TRANSACTION_READ_UNCOMMITTED", "==", "transactionIsolation", "||", "Connection", ".", "TRANSACTION_READ_COMMITTED", "==", "transactionIsolation", "||", "Connection", ".", "TRANSACTION_REPEATABLE_READ", "==", "transactionIsolation", "||", "Connection", ".", "TRANSACTION_SERIALIZABLE", "==", "transactionIsolation", ")", "{", "Map", "<", "String", ",", "String", ">", "props", "=", "getConnPropsByDataSourceName", "(", "dataSourceName", ")", ";", "props", ".", "put", "(", "PROPS_TRANSACTION_ISOLATION", ",", "String", ".", "valueOf", "(", "transactionIsolation", ")", ")", ";", "}", "else", "{", "throw", "new", "IllegalArgumentException", "(", "\"Unsupported level [\"", "+", "transactionIsolation", "+", "\"]\"", ")", ";", "}", "}" ]
{@link DataSourceConnectionSupplierImpl#setDefaultDataSourceName(String)} で指定したデータソースに対するtransactionIsolationオプションの指定 @see Connection#TRANSACTION_READ_UNCOMMITTED @see Connection#TRANSACTION_READ_COMMITTED @see Connection#TRANSACTION_REPEATABLE_READ @see Connection#TRANSACTION_SERIALIZABLE @param dataSourceName データソース名 @param transactionIsolation transactionIsolationオプション
[ "{", "@link", "DataSourceConnectionSupplierImpl#setDefaultDataSourceName", "(", "String", ")", "}", "で指定したデータソースに対するtransactionIsolationオプションの指定" ]
train
https://github.com/future-architect/uroborosql/blob/4c26db51defdac3c6ed16866e33ab45e190e2e0c/src/main/java/jp/co/future/uroborosql/connection/DataSourceConnectionSupplierImpl.java#L266-L276
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java
DateFormat.getInstanceForSkeleton
public final static DateFormat getInstanceForSkeleton(String skeleton) { return getPatternInstance(skeleton, ULocale.getDefault(Category.FORMAT)); }
java
public final static DateFormat getInstanceForSkeleton(String skeleton) { return getPatternInstance(skeleton, ULocale.getDefault(Category.FORMAT)); }
[ "public", "final", "static", "DateFormat", "getInstanceForSkeleton", "(", "String", "skeleton", ")", "{", "return", "getPatternInstance", "(", "skeleton", ",", "ULocale", ".", "getDefault", "(", "Category", ".", "FORMAT", ")", ")", ";", "}" ]
<strong>[icu]</strong> Returns a {@link DateFormat} object that can be used to format dates and times in the default locale. @param skeleton The skeleton that selects the fields to be formatted. (Uses the {@link DateTimePatternGenerator}.) This can be {@link DateFormat#ABBR_MONTH}, {@link DateFormat#MONTH_WEEKDAY_DAY}, etc.
[ "<strong", ">", "[", "icu", "]", "<", "/", "strong", ">", "Returns", "a", "{", "@link", "DateFormat", "}", "object", "that", "can", "be", "used", "to", "format", "dates", "and", "times", "in", "the", "default", "locale", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L1949-L1951
lucee/Lucee
core/src/main/java/lucee/runtime/config/PasswordImpl.java
PasswordImpl.readFromXML
public static Password readFromXML(Element el, String salt, boolean isDefault) { String prefix = isDefault ? "default-" : ""; // first we look for the hashed and salted password String pw = el.getAttribute(prefix + "hspw"); if (!StringUtil.isEmpty(pw, true)) { // password is only of use when there is a salt as well if (salt == null) return null; return new PasswordImpl(ORIGIN_HASHED_SALTED, pw, salt, HASHED_SALTED); } // fall back to password that is hashed but not salted pw = el.getAttribute(prefix + "pw"); if (!StringUtil.isEmpty(pw, true)) { return new PasswordImpl(ORIGIN_HASHED, pw, null, HASHED); } // fall back to encrypted password String pwEnc = el.getAttribute(prefix + "password"); if (!StringUtil.isEmpty(pwEnc, true)) { String rawPassword = new BlowfishEasy("tpwisgh").decryptString(pwEnc); return new PasswordImpl(ORIGIN_ENCRYPTED, rawPassword, salt); } return null; }
java
public static Password readFromXML(Element el, String salt, boolean isDefault) { String prefix = isDefault ? "default-" : ""; // first we look for the hashed and salted password String pw = el.getAttribute(prefix + "hspw"); if (!StringUtil.isEmpty(pw, true)) { // password is only of use when there is a salt as well if (salt == null) return null; return new PasswordImpl(ORIGIN_HASHED_SALTED, pw, salt, HASHED_SALTED); } // fall back to password that is hashed but not salted pw = el.getAttribute(prefix + "pw"); if (!StringUtil.isEmpty(pw, true)) { return new PasswordImpl(ORIGIN_HASHED, pw, null, HASHED); } // fall back to encrypted password String pwEnc = el.getAttribute(prefix + "password"); if (!StringUtil.isEmpty(pwEnc, true)) { String rawPassword = new BlowfishEasy("tpwisgh").decryptString(pwEnc); return new PasswordImpl(ORIGIN_ENCRYPTED, rawPassword, salt); } return null; }
[ "public", "static", "Password", "readFromXML", "(", "Element", "el", ",", "String", "salt", ",", "boolean", "isDefault", ")", "{", "String", "prefix", "=", "isDefault", "?", "\"default-\"", ":", "\"\"", ";", "// first we look for the hashed and salted password", "String", "pw", "=", "el", ".", "getAttribute", "(", "prefix", "+", "\"hspw\"", ")", ";", "if", "(", "!", "StringUtil", ".", "isEmpty", "(", "pw", ",", "true", ")", ")", "{", "// password is only of use when there is a salt as well", "if", "(", "salt", "==", "null", ")", "return", "null", ";", "return", "new", "PasswordImpl", "(", "ORIGIN_HASHED_SALTED", ",", "pw", ",", "salt", ",", "HASHED_SALTED", ")", ";", "}", "// fall back to password that is hashed but not salted", "pw", "=", "el", ".", "getAttribute", "(", "prefix", "+", "\"pw\"", ")", ";", "if", "(", "!", "StringUtil", ".", "isEmpty", "(", "pw", ",", "true", ")", ")", "{", "return", "new", "PasswordImpl", "(", "ORIGIN_HASHED", ",", "pw", ",", "null", ",", "HASHED", ")", ";", "}", "// fall back to encrypted password", "String", "pwEnc", "=", "el", ".", "getAttribute", "(", "prefix", "+", "\"password\"", ")", ";", "if", "(", "!", "StringUtil", ".", "isEmpty", "(", "pwEnc", ",", "true", ")", ")", "{", "String", "rawPassword", "=", "new", "BlowfishEasy", "(", "\"tpwisgh\"", ")", ".", "decryptString", "(", "pwEnc", ")", ";", "return", "new", "PasswordImpl", "(", "ORIGIN_ENCRYPTED", ",", "rawPassword", ",", "salt", ")", ";", "}", "return", "null", ";", "}" ]
reads the password defined in the Lucee configuration, this can also in older formats (only hashed or encrypted) @param el @param salt @param isDefault @return
[ "reads", "the", "password", "defined", "in", "the", "Lucee", "configuration", "this", "can", "also", "in", "older", "formats", "(", "only", "hashed", "or", "encrypted", ")" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/config/PasswordImpl.java#L135-L159
dlemmermann/CalendarFX
CalendarFXView/src/main/java/com/calendarfx/model/Interval.java
Interval.withDates
public Interval withDates(LocalDateTime startDateTime, LocalDateTime endDateTime) { requireNonNull(startDateTime); requireNonNull(endDateTime); return new Interval(startDateTime, endDateTime, this.zoneId); }
java
public Interval withDates(LocalDateTime startDateTime, LocalDateTime endDateTime) { requireNonNull(startDateTime); requireNonNull(endDateTime); return new Interval(startDateTime, endDateTime, this.zoneId); }
[ "public", "Interval", "withDates", "(", "LocalDateTime", "startDateTime", ",", "LocalDateTime", "endDateTime", ")", "{", "requireNonNull", "(", "startDateTime", ")", ";", "requireNonNull", "(", "endDateTime", ")", ";", "return", "new", "Interval", "(", "startDateTime", ",", "endDateTime", ",", "this", ".", "zoneId", ")", ";", "}" ]
Returns a new interval based on this interval but with a different start and end date. @param startDateTime the new start date @param endDateTime the new end date @return a new interval
[ "Returns", "a", "new", "interval", "based", "on", "this", "interval", "but", "with", "a", "different", "start", "and", "end", "date", "." ]
train
https://github.com/dlemmermann/CalendarFX/blob/f2b91c2622c3f29d004485b6426b23b86c331f96/CalendarFXView/src/main/java/com/calendarfx/model/Interval.java#L292-L296
dlew/joda-time-android
library/src/main/java/net/danlew/android/joda/DateUtils.java
DateUtils.getRelativeDateTimeString
public static CharSequence getRelativeDateTimeString(Context context, ReadableInstant time, ReadablePeriod transitionResolution, int flags) { Resources r = context.getResources(); // We set the millis to 0 so we aren't off by a fraction of a second when counting duration DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0); DateTime timeDt = new DateTime(time).withMillisOfSecond(0); boolean past = !now.isBefore(timeDt); Duration duration = past ? new Duration(timeDt, now) : new Duration(now, timeDt); // getRelativeTimeSpanString() doesn't correctly format relative dates // above a week or exact dates below a day, so clamp // transitionResolution as needed. Duration transitionDuration; Duration minDuration = Days.ONE.toPeriod().toDurationTo(timeDt); if (transitionResolution == null) { transitionDuration = minDuration; } else { transitionDuration = past ? transitionResolution.toPeriod().toDurationTo(now) : transitionResolution.toPeriod().toDurationFrom(now); Duration maxDuration = Weeks.ONE.toPeriod().toDurationTo(timeDt); if (transitionDuration.isLongerThan(maxDuration)) { transitionDuration = maxDuration; } else if (transitionDuration.isShorterThan(minDuration)) { transitionDuration = minDuration; } } CharSequence timeClause = formatDateRange(context, time, time, FORMAT_SHOW_TIME); String result; if (!duration.isLongerThan(transitionDuration)) { CharSequence relativeClause = getRelativeTimeSpanString(context, time, flags); result = r.getString(R.string.joda_time_android_relative_time, relativeClause, timeClause); } else { CharSequence dateClause = getRelativeTimeSpanString(context, time, false); result = r.getString(R.string.joda_time_android_date_time, dateClause, timeClause); } return result; }
java
public static CharSequence getRelativeDateTimeString(Context context, ReadableInstant time, ReadablePeriod transitionResolution, int flags) { Resources r = context.getResources(); // We set the millis to 0 so we aren't off by a fraction of a second when counting duration DateTime now = DateTime.now(time.getZone()).withMillisOfSecond(0); DateTime timeDt = new DateTime(time).withMillisOfSecond(0); boolean past = !now.isBefore(timeDt); Duration duration = past ? new Duration(timeDt, now) : new Duration(now, timeDt); // getRelativeTimeSpanString() doesn't correctly format relative dates // above a week or exact dates below a day, so clamp // transitionResolution as needed. Duration transitionDuration; Duration minDuration = Days.ONE.toPeriod().toDurationTo(timeDt); if (transitionResolution == null) { transitionDuration = minDuration; } else { transitionDuration = past ? transitionResolution.toPeriod().toDurationTo(now) : transitionResolution.toPeriod().toDurationFrom(now); Duration maxDuration = Weeks.ONE.toPeriod().toDurationTo(timeDt); if (transitionDuration.isLongerThan(maxDuration)) { transitionDuration = maxDuration; } else if (transitionDuration.isShorterThan(minDuration)) { transitionDuration = minDuration; } } CharSequence timeClause = formatDateRange(context, time, time, FORMAT_SHOW_TIME); String result; if (!duration.isLongerThan(transitionDuration)) { CharSequence relativeClause = getRelativeTimeSpanString(context, time, flags); result = r.getString(R.string.joda_time_android_relative_time, relativeClause, timeClause); } else { CharSequence dateClause = getRelativeTimeSpanString(context, time, false); result = r.getString(R.string.joda_time_android_date_time, dateClause, timeClause); } return result; }
[ "public", "static", "CharSequence", "getRelativeDateTimeString", "(", "Context", "context", ",", "ReadableInstant", "time", ",", "ReadablePeriod", "transitionResolution", ",", "int", "flags", ")", "{", "Resources", "r", "=", "context", ".", "getResources", "(", ")", ";", "// We set the millis to 0 so we aren't off by a fraction of a second when counting duration", "DateTime", "now", "=", "DateTime", ".", "now", "(", "time", ".", "getZone", "(", ")", ")", ".", "withMillisOfSecond", "(", "0", ")", ";", "DateTime", "timeDt", "=", "new", "DateTime", "(", "time", ")", ".", "withMillisOfSecond", "(", "0", ")", ";", "boolean", "past", "=", "!", "now", ".", "isBefore", "(", "timeDt", ")", ";", "Duration", "duration", "=", "past", "?", "new", "Duration", "(", "timeDt", ",", "now", ")", ":", "new", "Duration", "(", "now", ",", "timeDt", ")", ";", "// getRelativeTimeSpanString() doesn't correctly format relative dates", "// above a week or exact dates below a day, so clamp", "// transitionResolution as needed.", "Duration", "transitionDuration", ";", "Duration", "minDuration", "=", "Days", ".", "ONE", ".", "toPeriod", "(", ")", ".", "toDurationTo", "(", "timeDt", ")", ";", "if", "(", "transitionResolution", "==", "null", ")", "{", "transitionDuration", "=", "minDuration", ";", "}", "else", "{", "transitionDuration", "=", "past", "?", "transitionResolution", ".", "toPeriod", "(", ")", ".", "toDurationTo", "(", "now", ")", ":", "transitionResolution", ".", "toPeriod", "(", ")", ".", "toDurationFrom", "(", "now", ")", ";", "Duration", "maxDuration", "=", "Weeks", ".", "ONE", ".", "toPeriod", "(", ")", ".", "toDurationTo", "(", "timeDt", ")", ";", "if", "(", "transitionDuration", ".", "isLongerThan", "(", "maxDuration", ")", ")", "{", "transitionDuration", "=", "maxDuration", ";", "}", "else", "if", "(", "transitionDuration", ".", "isShorterThan", "(", "minDuration", ")", ")", "{", "transitionDuration", "=", "minDuration", ";", "}", "}", "CharSequence", "timeClause", "=", "formatDateRange", "(", "context", ",", "time", ",", "time", ",", "FORMAT_SHOW_TIME", ")", ";", "String", "result", ";", "if", "(", "!", "duration", ".", "isLongerThan", "(", "transitionDuration", ")", ")", "{", "CharSequence", "relativeClause", "=", "getRelativeTimeSpanString", "(", "context", ",", "time", ",", "flags", ")", ";", "result", "=", "r", ".", "getString", "(", "R", ".", "string", ".", "joda_time_android_relative_time", ",", "relativeClause", ",", "timeClause", ")", ";", "}", "else", "{", "CharSequence", "dateClause", "=", "getRelativeTimeSpanString", "(", "context", ",", "time", ",", "false", ")", ";", "result", "=", "r", ".", "getString", "(", "R", ".", "string", ".", "joda_time_android_date_time", ",", "dateClause", ",", "timeClause", ")", ";", "}", "return", "result", ";", "}" ]
Return string describing the time until/elapsed time since 'time' formatted like "[relative time/date], [time]". See {@link android.text.format.DateUtils#getRelativeDateTimeString} for full docs. @param context the context @param time some time @param transitionResolution the elapsed time (period) at which to stop reporting relative measurements. Periods greater than this resolution will default to normal date formatting. For example, will transition from "6 days ago" to "Dec 12" when using Weeks.ONE. If null, defaults to Days.ONE. Clamps to min value of Days.ONE, max of Weeks.ONE. @param flags flags for getRelativeTimeSpanString() (if duration is less than transitionResolution)
[ "Return", "string", "describing", "the", "time", "until", "/", "elapsed", "time", "since", "time", "formatted", "like", "[", "relative", "time", "/", "date", "]", "[", "time", "]", "." ]
train
https://github.com/dlew/joda-time-android/blob/5bf96f6ef4ea63ee91e73e1e528896fa00108dec/library/src/main/java/net/danlew/android/joda/DateUtils.java#L433-L476
Alluxio/alluxio
shell/src/main/java/alluxio/cli/fsadmin/report/CapacityCommand.java
CapacityCommand.getInfoFormat
private String getInfoFormat(List<WorkerInfo> workerInfoList, boolean isShort) { int maxWorkerNameLength = workerInfoList.stream().map(w -> w.getAddress().getHost().length()) .max(Comparator.comparing(Integer::intValue)).get(); int firstIndent = 16; if (firstIndent <= maxWorkerNameLength) { // extend first indent according to the longest worker name by default 5 firstIndent = maxWorkerNameLength + 5; } if (isShort) { return "%-" + firstIndent + "s %-16s %-13s %s"; } return "%-" + firstIndent + "s %-16s %-13s %-16s %s"; }
java
private String getInfoFormat(List<WorkerInfo> workerInfoList, boolean isShort) { int maxWorkerNameLength = workerInfoList.stream().map(w -> w.getAddress().getHost().length()) .max(Comparator.comparing(Integer::intValue)).get(); int firstIndent = 16; if (firstIndent <= maxWorkerNameLength) { // extend first indent according to the longest worker name by default 5 firstIndent = maxWorkerNameLength + 5; } if (isShort) { return "%-" + firstIndent + "s %-16s %-13s %s"; } return "%-" + firstIndent + "s %-16s %-13s %-16s %s"; }
[ "private", "String", "getInfoFormat", "(", "List", "<", "WorkerInfo", ">", "workerInfoList", ",", "boolean", "isShort", ")", "{", "int", "maxWorkerNameLength", "=", "workerInfoList", ".", "stream", "(", ")", ".", "map", "(", "w", "->", "w", ".", "getAddress", "(", ")", ".", "getHost", "(", ")", ".", "length", "(", ")", ")", ".", "max", "(", "Comparator", ".", "comparing", "(", "Integer", "::", "intValue", ")", ")", ".", "get", "(", ")", ";", "int", "firstIndent", "=", "16", ";", "if", "(", "firstIndent", "<=", "maxWorkerNameLength", ")", "{", "// extend first indent according to the longest worker name by default 5", "firstIndent", "=", "maxWorkerNameLength", "+", "5", ";", "}", "if", "(", "isShort", ")", "{", "return", "\"%-\"", "+", "firstIndent", "+", "\"s %-16s %-13s %s\"", ";", "}", "return", "\"%-\"", "+", "firstIndent", "+", "\"s %-16s %-13s %-16s %s\"", ";", "}" ]
Gets the info format according to the longest worker name. @param workerInfoList the worker info list to get info from @param isShort whether exists only one tier @return the info format for printing long/short worker info
[ "Gets", "the", "info", "format", "according", "to", "the", "longest", "worker", "name", "." ]
train
https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/shell/src/main/java/alluxio/cli/fsadmin/report/CapacityCommand.java#L255-L267
structurizr/java
structurizr-core/src/com/structurizr/view/ViewSet.java
ViewSet.createDynamicView
public DynamicView createDynamicView(String key, String description) { assertThatTheViewKeyIsSpecifiedAndUnique(key); DynamicView view = new DynamicView(model, key, description); view.setViewSet(this); dynamicViews.add(view); return view; }
java
public DynamicView createDynamicView(String key, String description) { assertThatTheViewKeyIsSpecifiedAndUnique(key); DynamicView view = new DynamicView(model, key, description); view.setViewSet(this); dynamicViews.add(view); return view; }
[ "public", "DynamicView", "createDynamicView", "(", "String", "key", ",", "String", "description", ")", "{", "assertThatTheViewKeyIsSpecifiedAndUnique", "(", "key", ")", ";", "DynamicView", "view", "=", "new", "DynamicView", "(", "model", ",", "key", ",", "description", ")", ";", "view", ".", "setViewSet", "(", "this", ")", ";", "dynamicViews", ".", "add", "(", "view", ")", ";", "return", "view", ";", "}" ]
Creates a dynamic view. @param key the key for the view (must be unique) @param description a description of the view @return a DynamicView object @throws IllegalArgumentException if the key is not unique
[ "Creates", "a", "dynamic", "view", "." ]
train
https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/view/ViewSet.java#L127-L134
facebookarchive/hadoop-20
src/mapred/org/apache/hadoop/mapred/MapTask.java
MapTask.updateJobWithSplit
private void updateJobWithSplit(final JobConf job, InputSplit inputSplit) { if (inputSplit instanceof FileSplit) { FileSplit fileSplit = (FileSplit) inputSplit; job.set("map.input.file", fileSplit.getPath().toString()); job.setLong("map.input.start", fileSplit.getStart()); job.setLong("map.input.length", fileSplit.getLength()); } LOG.info("split: " + inputSplit.toString()); }
java
private void updateJobWithSplit(final JobConf job, InputSplit inputSplit) { if (inputSplit instanceof FileSplit) { FileSplit fileSplit = (FileSplit) inputSplit; job.set("map.input.file", fileSplit.getPath().toString()); job.setLong("map.input.start", fileSplit.getStart()); job.setLong("map.input.length", fileSplit.getLength()); } LOG.info("split: " + inputSplit.toString()); }
[ "private", "void", "updateJobWithSplit", "(", "final", "JobConf", "job", ",", "InputSplit", "inputSplit", ")", "{", "if", "(", "inputSplit", "instanceof", "FileSplit", ")", "{", "FileSplit", "fileSplit", "=", "(", "FileSplit", ")", "inputSplit", ";", "job", ".", "set", "(", "\"map.input.file\"", ",", "fileSplit", ".", "getPath", "(", ")", ".", "toString", "(", ")", ")", ";", "job", ".", "setLong", "(", "\"map.input.start\"", ",", "fileSplit", ".", "getStart", "(", ")", ")", ";", "job", ".", "setLong", "(", "\"map.input.length\"", ",", "fileSplit", ".", "getLength", "(", ")", ")", ";", "}", "LOG", ".", "info", "(", "\"split: \"", "+", "inputSplit", ".", "toString", "(", ")", ")", ";", "}" ]
Update the job with details about the file split @param job the job configuration to update @param inputSplit the file split
[ "Update", "the", "job", "with", "details", "about", "the", "file", "split" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/mapred/org/apache/hadoop/mapred/MapTask.java#L383-L391
albfernandez/itext2
src/main/java/com/lowagie/text/rtf/parser/ctrlwords/RtfCtrlWordMgr.java
RtfCtrlWordMgr.dispatchKeyword
private int dispatchKeyword(RtfCtrlWordData ctrlWordData, int groupLevel) { int result = RtfParser.errOK; if(ctrlWordData != null) { RtfCtrlWordHandler ctrlWord = ctrlWordMap.getCtrlWordHandler(ctrlWordData.ctrlWord); if(ctrlWord != null) { ctrlWord.handleControlword(ctrlWordData); if(debug && debugFound) { System.out.println("Keyword found:" + " New:" + ctrlWordData.ctrlWord + " Param:" + ctrlWordData.param + " bParam=" + ctrlWordData.hasParam); } } else { result = RtfParser.errCtrlWordNotFound; //result = RtfParser2.errAssertion; if(debug && debugNotFound) { System.out.println("Keyword unknown:" + " New:" + ctrlWordData.ctrlWord + " Param:" + ctrlWordData.param + " bParam=" + ctrlWordData.hasParam); } } } return result; }
java
private int dispatchKeyword(RtfCtrlWordData ctrlWordData, int groupLevel) { int result = RtfParser.errOK; if(ctrlWordData != null) { RtfCtrlWordHandler ctrlWord = ctrlWordMap.getCtrlWordHandler(ctrlWordData.ctrlWord); if(ctrlWord != null) { ctrlWord.handleControlword(ctrlWordData); if(debug && debugFound) { System.out.println("Keyword found:" + " New:" + ctrlWordData.ctrlWord + " Param:" + ctrlWordData.param + " bParam=" + ctrlWordData.hasParam); } } else { result = RtfParser.errCtrlWordNotFound; //result = RtfParser2.errAssertion; if(debug && debugNotFound) { System.out.println("Keyword unknown:" + " New:" + ctrlWordData.ctrlWord + " Param:" + ctrlWordData.param + " bParam=" + ctrlWordData.hasParam); } } } return result; }
[ "private", "int", "dispatchKeyword", "(", "RtfCtrlWordData", "ctrlWordData", ",", "int", "groupLevel", ")", "{", "int", "result", "=", "RtfParser", ".", "errOK", ";", "if", "(", "ctrlWordData", "!=", "null", ")", "{", "RtfCtrlWordHandler", "ctrlWord", "=", "ctrlWordMap", ".", "getCtrlWordHandler", "(", "ctrlWordData", ".", "ctrlWord", ")", ";", "if", "(", "ctrlWord", "!=", "null", ")", "{", "ctrlWord", ".", "handleControlword", "(", "ctrlWordData", ")", ";", "if", "(", "debug", "&&", "debugFound", ")", "{", "System", ".", "out", ".", "println", "(", "\"Keyword found:\"", "+", "\" New:\"", "+", "ctrlWordData", ".", "ctrlWord", "+", "\" Param:\"", "+", "ctrlWordData", ".", "param", "+", "\" bParam=\"", "+", "ctrlWordData", ".", "hasParam", ")", ";", "}", "}", "else", "{", "result", "=", "RtfParser", ".", "errCtrlWordNotFound", ";", "//result = RtfParser2.errAssertion;", "if", "(", "debug", "&&", "debugNotFound", ")", "{", "System", ".", "out", ".", "println", "(", "\"Keyword unknown:\"", "+", "\" New:\"", "+", "ctrlWordData", ".", "ctrlWord", "+", "\" Param:\"", "+", "ctrlWordData", ".", "param", "+", "\" bParam=\"", "+", "ctrlWordData", ".", "hasParam", ")", ";", "}", "}", "}", "return", "result", ";", "}" ]
Dispatch the token to the correct control word handling object. @param ctrlWordData The <code>RtfCtrlWordData</code> object with control word and param @param groupLevel The current document group parsing level @return errOK if ok, otherwise an error code.
[ "Dispatch", "the", "token", "to", "the", "correct", "control", "word", "handling", "object", "." ]
train
https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/rtf/parser/ctrlwords/RtfCtrlWordMgr.java#L132-L156
virgo47/javasimon
core/src/main/java/org/javasimon/AbstractSimon.java
AbstractSimon.replaceChild
void replaceChild(Simon simon, AbstractSimon newSimon) { children.remove(simon); if (newSimon != null) { children.add(newSimon); newSimon.setParent(this); } }
java
void replaceChild(Simon simon, AbstractSimon newSimon) { children.remove(simon); if (newSimon != null) { children.add(newSimon); newSimon.setParent(this); } }
[ "void", "replaceChild", "(", "Simon", "simon", ",", "AbstractSimon", "newSimon", ")", "{", "children", ".", "remove", "(", "simon", ")", ";", "if", "(", "newSimon", "!=", "null", ")", "{", "children", ".", "add", "(", "newSimon", ")", ";", "newSimon", ".", "setParent", "(", "this", ")", ";", "}", "}" ]
Replaces one of the children for a new one (unknown to concrete). Used only internally. @param simon original Simon (unknown) @param newSimon new Simon
[ "Replaces", "one", "of", "the", "children", "for", "a", "new", "one", "(", "unknown", "to", "concrete", ")", ".", "Used", "only", "internally", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/AbstractSimon.java#L179-L185
Azure/azure-sdk-for-java
policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyAssignmentsInner.java
PolicyAssignmentsInner.createById
public PolicyAssignmentInner createById(String policyAssignmentId, PolicyAssignmentInner parameters) { return createByIdWithServiceResponseAsync(policyAssignmentId, parameters).toBlocking().single().body(); }
java
public PolicyAssignmentInner createById(String policyAssignmentId, PolicyAssignmentInner parameters) { return createByIdWithServiceResponseAsync(policyAssignmentId, parameters).toBlocking().single().body(); }
[ "public", "PolicyAssignmentInner", "createById", "(", "String", "policyAssignmentId", ",", "PolicyAssignmentInner", "parameters", ")", "{", "return", "createByIdWithServiceResponseAsync", "(", "policyAssignmentId", ",", "parameters", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Creates a policy assignment by ID. Policy assignments are inherited by child resources. For example, when you apply a policy to a resource group that policy is assigned to all resources in the group. When providing a scope for the assigment, use '/subscriptions/{subscription-id}/' for subscriptions, '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}' for resource groups, and '/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/{resource-provider-namespace}/{resource-type}/{resource-name}' for resources. @param policyAssignmentId The ID of the policy assignment to create. Use the format '/{scope}/providers/Microsoft.Authorization/policyAssignments/{policy-assignment-name}'. @param parameters Parameters for policy assignment. @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 PolicyAssignmentInner object if successful.
[ "Creates", "a", "policy", "assignment", "by", "ID", ".", "Policy", "assignments", "are", "inherited", "by", "child", "resources", ".", "For", "example", "when", "you", "apply", "a", "policy", "to", "a", "resource", "group", "that", "policy", "is", "assigned", "to", "all", "resources", "in", "the", "group", ".", "When", "providing", "a", "scope", "for", "the", "assigment", "use", "/", "subscriptions", "/", "{", "subscription", "-", "id", "}", "/", "for", "subscriptions", "/", "subscriptions", "/", "{", "subscription", "-", "id", "}", "/", "resourceGroups", "/", "{", "resource", "-", "group", "-", "name", "}", "for", "resource", "groups", "and", "/", "subscriptions", "/", "{", "subscription", "-", "id", "}", "/", "resourceGroups", "/", "{", "resource", "-", "group", "-", "name", "}", "/", "providers", "/", "{", "resource", "-", "provider", "-", "namespace", "}", "/", "{", "resource", "-", "type", "}", "/", "{", "resource", "-", "name", "}", "for", "resources", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/policy/resource-manager/v2016_12_01/src/main/java/com/microsoft/azure/management/policy/v2016_12_01/implementation/PolicyAssignmentsInner.java#L1204-L1206
mgm-tp/jfunk
jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java
ConstraintFactory.createModel
public Constraint createModel(final MathRandom random, final Element element) { if (element == null) { return null; } Class<? extends Constraint> classObject = null; Constraint object = null; try { classObject = getClassObject(element); Constructor<? extends Constraint> constructor = getConstructor(classObject); object = getObject(random, element, constructor); } catch (InvocationTargetException ex) { throw new JFunkException("Could not initialise object of class " + classObject, ex.getCause()); } catch (Exception ex) { throw new JFunkException("Could not initialise object of class " + classObject, ex); } putToCache(element, object); return object; }
java
public Constraint createModel(final MathRandom random, final Element element) { if (element == null) { return null; } Class<? extends Constraint> classObject = null; Constraint object = null; try { classObject = getClassObject(element); Constructor<? extends Constraint> constructor = getConstructor(classObject); object = getObject(random, element, constructor); } catch (InvocationTargetException ex) { throw new JFunkException("Could not initialise object of class " + classObject, ex.getCause()); } catch (Exception ex) { throw new JFunkException("Could not initialise object of class " + classObject, ex); } putToCache(element, object); return object; }
[ "public", "Constraint", "createModel", "(", "final", "MathRandom", "random", ",", "final", "Element", "element", ")", "{", "if", "(", "element", "==", "null", ")", "{", "return", "null", ";", "}", "Class", "<", "?", "extends", "Constraint", ">", "classObject", "=", "null", ";", "Constraint", "object", "=", "null", ";", "try", "{", "classObject", "=", "getClassObject", "(", "element", ")", ";", "Constructor", "<", "?", "extends", "Constraint", ">", "constructor", "=", "getConstructor", "(", "classObject", ")", ";", "object", "=", "getObject", "(", "random", ",", "element", ",", "constructor", ")", ";", "}", "catch", "(", "InvocationTargetException", "ex", ")", "{", "throw", "new", "JFunkException", "(", "\"Could not initialise object of class \"", "+", "classObject", ",", "ex", ".", "getCause", "(", ")", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "JFunkException", "(", "\"Could not initialise object of class \"", "+", "classObject", ",", "ex", ")", ";", "}", "putToCache", "(", "element", ",", "object", ")", ";", "return", "object", ";", "}" ]
Generates an instance based on the data in the given object. The object's class will be determined by the class attribute of the element. IF the element contains an id attribute the generated instance is stored in a map using this id as key.
[ "Generates", "an", "instance", "based", "on", "the", "data", "in", "the", "given", "object", ".", "The", "object", "s", "class", "will", "be", "determined", "by", "the", "class", "attribute", "of", "the", "element", ".", "IF", "the", "element", "contains", "an", "id", "attribute", "the", "generated", "instance", "is", "stored", "in", "a", "map", "using", "this", "id", "as", "key", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-data-generator/src/main/java/com/mgmtp/jfunk/data/generator/constraint/ConstraintFactory.java#L62-L79
apiman/apiman
manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java
EsMarshalling.unmarshallOrganizationSummary
public static OrganizationSummaryBean unmarshallOrganizationSummary(Map<String, Object> source) { if (source == null) { return null; } OrganizationSummaryBean bean = new OrganizationSummaryBean(); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); postMarshall(bean); return bean; }
java
public static OrganizationSummaryBean unmarshallOrganizationSummary(Map<String, Object> source) { if (source == null) { return null; } OrganizationSummaryBean bean = new OrganizationSummaryBean(); bean.setId(asString(source.get("id"))); bean.setName(asString(source.get("name"))); bean.setDescription(asString(source.get("description"))); postMarshall(bean); return bean; }
[ "public", "static", "OrganizationSummaryBean", "unmarshallOrganizationSummary", "(", "Map", "<", "String", ",", "Object", ">", "source", ")", "{", "if", "(", "source", "==", "null", ")", "{", "return", "null", ";", "}", "OrganizationSummaryBean", "bean", "=", "new", "OrganizationSummaryBean", "(", ")", ";", "bean", ".", "setId", "(", "asString", "(", "source", ".", "get", "(", "\"id\"", ")", ")", ")", ";", "bean", ".", "setName", "(", "asString", "(", "source", ".", "get", "(", "\"name\"", ")", ")", ")", ";", "bean", ".", "setDescription", "(", "asString", "(", "source", ".", "get", "(", "\"description\"", ")", ")", ")", ";", "postMarshall", "(", "bean", ")", ";", "return", "bean", ";", "}" ]
Unmarshals the given map source into a bean. @param source the source @return the organization summary
[ "Unmarshals", "the", "given", "map", "source", "into", "a", "bean", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/manager/api/es/src/main/java/io/apiman/manager/api/es/EsMarshalling.java#L1173-L1183
powermock/powermock
powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java
WhiteboxImpl.getMethod
public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { Class<?> thisType = type; if (parameterTypes == null) { parameterTypes = new Class<?>[0]; } while (thisType != null) { Method[] methodsToTraverse = null; if (thisType.isInterface()) { // Interfaces only contain public (and abstract) methods, no // need to traverse the hierarchy. methodsToTraverse = getAllPublicMethods(thisType); } else { methodsToTraverse = thisType.getDeclaredMethods(); } for (Method method : methodsToTraverse) { if (methodName.equals(method.getName()) && checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) { method.setAccessible(true); return method; } } thisType = thisType.getSuperclass(); } throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes}); return null; }
java
public static Method getMethod(Class<?> type, String methodName, Class<?>... parameterTypes) { Class<?> thisType = type; if (parameterTypes == null) { parameterTypes = new Class<?>[0]; } while (thisType != null) { Method[] methodsToTraverse = null; if (thisType.isInterface()) { // Interfaces only contain public (and abstract) methods, no // need to traverse the hierarchy. methodsToTraverse = getAllPublicMethods(thisType); } else { methodsToTraverse = thisType.getDeclaredMethods(); } for (Method method : methodsToTraverse) { if (methodName.equals(method.getName()) && checkIfParameterTypesAreSame(method.isVarArgs(), parameterTypes, method.getParameterTypes())) { method.setAccessible(true); return method; } } thisType = thisType.getSuperclass(); } throwExceptionIfMethodWasNotFound(type, methodName, null, new Object[]{parameterTypes}); return null; }
[ "public", "static", "Method", "getMethod", "(", "Class", "<", "?", ">", "type", ",", "String", "methodName", ",", "Class", "<", "?", ">", "...", "parameterTypes", ")", "{", "Class", "<", "?", ">", "thisType", "=", "type", ";", "if", "(", "parameterTypes", "==", "null", ")", "{", "parameterTypes", "=", "new", "Class", "<", "?", ">", "[", "0", "]", ";", "}", "while", "(", "thisType", "!=", "null", ")", "{", "Method", "[", "]", "methodsToTraverse", "=", "null", ";", "if", "(", "thisType", ".", "isInterface", "(", ")", ")", "{", "// Interfaces only contain public (and abstract) methods, no", "// need to traverse the hierarchy.", "methodsToTraverse", "=", "getAllPublicMethods", "(", "thisType", ")", ";", "}", "else", "{", "methodsToTraverse", "=", "thisType", ".", "getDeclaredMethods", "(", ")", ";", "}", "for", "(", "Method", "method", ":", "methodsToTraverse", ")", "{", "if", "(", "methodName", ".", "equals", "(", "method", ".", "getName", "(", ")", ")", "&&", "checkIfParameterTypesAreSame", "(", "method", ".", "isVarArgs", "(", ")", ",", "parameterTypes", ",", "method", ".", "getParameterTypes", "(", ")", ")", ")", "{", "method", ".", "setAccessible", "(", "true", ")", ";", "return", "method", ";", "}", "}", "thisType", "=", "thisType", ".", "getSuperclass", "(", ")", ";", "}", "throwExceptionIfMethodWasNotFound", "(", "type", ",", "methodName", ",", "null", ",", "new", "Object", "[", "]", "{", "parameterTypes", "}", ")", ";", "return", "null", ";", "}" ]
Convenience method to get a method from a class type without having to catch the checked exceptions otherwise required. These exceptions are wrapped as runtime exceptions. The method will first try to look for a declared method in the same class. If the method is not declared in this class it will look for the method in the super class. This will continue throughout the whole class hierarchy. If the method is not found an {@link IllegalArgumentException} is thrown. @param type The type of the class where the method is located. @param methodName The method names. @param parameterTypes All parameter types of the method (may be {@code null}). @return A .
[ "Convenience", "method", "to", "get", "a", "method", "from", "a", "class", "type", "without", "having", "to", "catch", "the", "checked", "exceptions", "otherwise", "required", ".", "These", "exceptions", "are", "wrapped", "as", "runtime", "exceptions", "." ]
train
https://github.com/powermock/powermock/blob/e8cd68026c284c6a7efe66959809eeebd8d1f9ad/powermock-reflect/src/main/java/org/powermock/reflect/internal/WhiteboxImpl.java#L158-L184
haifengl/smile
core/src/main/java/smile/association/FPGrowth.java
FPGrowth.buildTotalSupportTree
TotalSupportTree buildTotalSupportTree() { TotalSupportTree ttree = new TotalSupportTree(minSupport, T0.numFreqItems, T0.order); learn(null, null, ttree); return ttree; }
java
TotalSupportTree buildTotalSupportTree() { TotalSupportTree ttree = new TotalSupportTree(minSupport, T0.numFreqItems, T0.order); learn(null, null, ttree); return ttree; }
[ "TotalSupportTree", "buildTotalSupportTree", "(", ")", "{", "TotalSupportTree", "ttree", "=", "new", "TotalSupportTree", "(", "minSupport", ",", "T0", ".", "numFreqItems", ",", "T0", ".", "order", ")", ";", "learn", "(", "null", ",", "null", ",", "ttree", ")", ";", "return", "ttree", ";", "}" ]
Mines the frequent item sets. The discovered frequent item sets will be stored in a total support tree.
[ "Mines", "the", "frequent", "item", "sets", ".", "The", "discovered", "frequent", "item", "sets", "will", "be", "stored", "in", "a", "total", "support", "tree", "." ]
train
https://github.com/haifengl/smile/blob/e27e43e90fbaacce3f99d30120cf9dd6a764c33d/core/src/main/java/smile/association/FPGrowth.java#L164-L168
eobermuhlner/big-math
ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java
BigDecimalMath.log2
public static BigDecimal log2(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTwo(mc), mc); return round(result, mathContext); }
java
public static BigDecimal log2(BigDecimal x, MathContext mathContext) { checkMathContext(mathContext); MathContext mc = new MathContext(mathContext.getPrecision() + 4, mathContext.getRoundingMode()); BigDecimal result = log(x, mc).divide(logTwo(mc), mc); return round(result, mathContext); }
[ "public", "static", "BigDecimal", "log2", "(", "BigDecimal", "x", ",", "MathContext", "mathContext", ")", "{", "checkMathContext", "(", "mathContext", ")", ";", "MathContext", "mc", "=", "new", "MathContext", "(", "mathContext", ".", "getPrecision", "(", ")", "+", "4", ",", "mathContext", ".", "getRoundingMode", "(", ")", ")", ";", "BigDecimal", "result", "=", "log", "(", "x", ",", "mc", ")", ".", "divide", "(", "logTwo", "(", "mc", ")", ",", "mc", ")", ";", "return", "round", "(", "result", ",", "mathContext", ")", ";", "}" ]
Calculates the logarithm of {@link BigDecimal} x to the base 2. @param x the {@link BigDecimal} to calculate the logarithm base 2 for @param mathContext the {@link MathContext} used for the result @return the calculated natural logarithm {@link BigDecimal} to the base 2 with the precision specified in the <code>mathContext</code> @throws ArithmeticException if x &lt;= 0 @throws UnsupportedOperationException if the {@link MathContext} has unlimited precision
[ "Calculates", "the", "logarithm", "of", "{", "@link", "BigDecimal", "}", "x", "to", "the", "base", "2", "." ]
train
https://github.com/eobermuhlner/big-math/blob/52c4fc334d0d722b295de740c1018ee400e3e8f2/ch.obermuhlner.math.big/src/main/java/ch/obermuhlner/math/big/BigDecimalMath.java#L919-L925
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.findBeanForField
@SuppressWarnings("WeakerAccess") @Internal protected final Optional findBeanForField(BeanResolutionContext resolutionContext, BeanContext context, FieldInjectionPoint injectionPoint) { return resolveBeanWithGenericsForField(resolutionContext, injectionPoint, (beanType, qualifier) -> ((DefaultBeanContext) context).findBean(resolutionContext, beanType, qualifier) ); }
java
@SuppressWarnings("WeakerAccess") @Internal protected final Optional findBeanForField(BeanResolutionContext resolutionContext, BeanContext context, FieldInjectionPoint injectionPoint) { return resolveBeanWithGenericsForField(resolutionContext, injectionPoint, (beanType, qualifier) -> ((DefaultBeanContext) context).findBean(resolutionContext, beanType, qualifier) ); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "@", "Internal", "protected", "final", "Optional", "findBeanForField", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "FieldInjectionPoint", "injectionPoint", ")", "{", "return", "resolveBeanWithGenericsForField", "(", "resolutionContext", ",", "injectionPoint", ",", "(", "beanType", ",", "qualifier", ")", "->", "(", "(", "DefaultBeanContext", ")", "context", ")", ".", "findBean", "(", "resolutionContext", ",", "beanType", ",", "qualifier", ")", ")", ";", "}" ]
Obtains a an optional for the field at the given index and the argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param injectionPoint The field injection point @return The resolved bean
[ "Obtains", "a", "an", "optional", "for", "the", "field", "at", "the", "given", "index", "and", "the", "argument", "at", "the", "given", "index", "<p", ">", "Warning", ":", "this", "method", "is", "used", "by", "internal", "generated", "code", "and", "should", "not", "be", "called", "by", "user", "code", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L1387-L1393
ironjacamar/ironjacamar
rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java
Main.hasMcfTransactionSupport
private static void hasMcfTransactionSupport(PrintStream out, PrintStream error, String classname, URLClassLoader cl) { try { out.print(" TransactionSupport: "); Class<?> mcfClz = Class.forName(classname, true, cl); ManagedConnectionFactory mcf = (ManagedConnectionFactory)mcfClz.newInstance(); if (hasInterface(mcf.getClass(), "javax.resource.spi.TransactionSupport")) { out.println("Yes"); } else { out.println("No"); } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); out.println("Unknown"); } }
java
private static void hasMcfTransactionSupport(PrintStream out, PrintStream error, String classname, URLClassLoader cl) { try { out.print(" TransactionSupport: "); Class<?> mcfClz = Class.forName(classname, true, cl); ManagedConnectionFactory mcf = (ManagedConnectionFactory)mcfClz.newInstance(); if (hasInterface(mcf.getClass(), "javax.resource.spi.TransactionSupport")) { out.println("Yes"); } else { out.println("No"); } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); out.println("Unknown"); } }
[ "private", "static", "void", "hasMcfTransactionSupport", "(", "PrintStream", "out", ",", "PrintStream", "error", ",", "String", "classname", ",", "URLClassLoader", "cl", ")", "{", "try", "{", "out", ".", "print", "(", "\" TransactionSupport: \"", ")", ";", "Class", "<", "?", ">", "mcfClz", "=", "Class", ".", "forName", "(", "classname", ",", "true", ",", "cl", ")", ";", "ManagedConnectionFactory", "mcf", "=", "(", "ManagedConnectionFactory", ")", "mcfClz", ".", "newInstance", "(", ")", ";", "if", "(", "hasInterface", "(", "mcf", ".", "getClass", "(", ")", ",", "\"javax.resource.spi.TransactionSupport\"", ")", ")", "{", "out", ".", "println", "(", "\"Yes\"", ")", ";", "}", "else", "{", "out", ".", "println", "(", "\"No\"", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "// Nothing we can do", "t", ".", "printStackTrace", "(", "error", ")", ";", "out", ".", "println", "(", "\"Unknown\"", ")", ";", "}", "}" ]
hasMcfTransactionSupport @param out output stream @param error output stream @param classname classname @param cl classloader
[ "hasMcfTransactionSupport" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java#L949-L973
apache/groovy
src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java
InvokerHelper.setPropertySafe2
public static void setPropertySafe2(Object newValue, Object object, String property) { if (object != null) { setProperty2(newValue, object, property); } }
java
public static void setPropertySafe2(Object newValue, Object object, String property) { if (object != null) { setProperty2(newValue, object, property); } }
[ "public", "static", "void", "setPropertySafe2", "(", "Object", "newValue", ",", "Object", "object", ",", "String", "property", ")", "{", "if", "(", "object", "!=", "null", ")", "{", "setProperty2", "(", "newValue", ",", "object", ",", "property", ")", ";", "}", "}" ]
This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
[ "This", "is", "so", "we", "don", "t", "have", "to", "reorder", "the", "stack", "when", "we", "call", "this", "method", ".", "At", "some", "point", "a", "better", "name", "might", "be", "in", "order", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java#L249-L253
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Stream.java
Stream.takeWhileIndexed
@NotNull public Stream<T> takeWhileIndexed(@NotNull IndexedPredicate<? super T> predicate) { return takeWhileIndexed(0, 1, predicate); }
java
@NotNull public Stream<T> takeWhileIndexed(@NotNull IndexedPredicate<? super T> predicate) { return takeWhileIndexed(0, 1, predicate); }
[ "@", "NotNull", "public", "Stream", "<", "T", ">", "takeWhileIndexed", "(", "@", "NotNull", "IndexedPredicate", "<", "?", "super", "T", ">", "predicate", ")", "{", "return", "takeWhileIndexed", "(", "0", ",", "1", ",", "predicate", ")", ";", "}" ]
Takes elements while the {@code IndexedPredicate} returns {@code true}. <p>This is an intermediate operation. <p>Example: <pre> predicate: (index, value) -&gt; (index + value) &lt; 5 stream: [1, 2, 3, 4, -5, -6, -7] index: [0, 1, 2, 3, 4, 5, 6] sum: [1, 3, 5, 7, -1, -1, -1] result: [1, 2] </pre> @param predicate the {@code IndexedPredicate} used to take elements @return the new stream @since 1.1.6
[ "Takes", "elements", "while", "the", "{", "@code", "IndexedPredicate", "}", "returns", "{", "@code", "true", "}", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L1323-L1326
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/util/comparator/CompoundComparator.java
CompoundComparator.setComparator
public void setComparator(int index, Comparator<T> comparator, boolean ascending) { this.comparators.set(index, new InvertibleComparator<>(comparator, ascending)); }
java
public void setComparator(int index, Comparator<T> comparator, boolean ascending) { this.comparators.set(index, new InvertibleComparator<>(comparator, ascending)); }
[ "public", "void", "setComparator", "(", "int", "index", ",", "Comparator", "<", "T", ">", "comparator", ",", "boolean", "ascending", ")", "{", "this", ".", "comparators", ".", "set", "(", "index", ",", "new", "InvertibleComparator", "<>", "(", "comparator", ",", "ascending", ")", ")", ";", "}" ]
Replace the Comparator at the given index using the given sort order. @param index the index of the Comparator to replace @param comparator the Comparator to place at the given index @param ascending the sort order: ascending (true) or descending (false)
[ "Replace", "the", "Comparator", "at", "the", "given", "index", "using", "the", "given", "sort", "order", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/util/comparator/CompoundComparator.java#L112-L114
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/AnderbergHierarchicalClustering.java
AnderbergHierarchicalClustering.updateCache
private void updateCache(int size, double[] scratch, double[] bestd, int[] besti, int x, int y, int j, double d) { // New best if(d <= bestd[j]) { bestd[j] = d; besti[j] = y; return; } // Needs slow update. if(besti[j] == x || besti[j] == y) { findBest(size, scratch, bestd, besti, j); } }
java
private void updateCache(int size, double[] scratch, double[] bestd, int[] besti, int x, int y, int j, double d) { // New best if(d <= bestd[j]) { bestd[j] = d; besti[j] = y; return; } // Needs slow update. if(besti[j] == x || besti[j] == y) { findBest(size, scratch, bestd, besti, j); } }
[ "private", "void", "updateCache", "(", "int", "size", ",", "double", "[", "]", "scratch", ",", "double", "[", "]", "bestd", ",", "int", "[", "]", "besti", ",", "int", "x", ",", "int", "y", ",", "int", "j", ",", "double", "d", ")", "{", "// New best", "if", "(", "d", "<=", "bestd", "[", "j", "]", ")", "{", "bestd", "[", "j", "]", "=", "d", ";", "besti", "[", "j", "]", "=", "y", ";", "return", ";", "}", "// Needs slow update.", "if", "(", "besti", "[", "j", "]", "==", "x", "||", "besti", "[", "j", "]", "==", "y", ")", "{", "findBest", "(", "size", ",", "scratch", ",", "bestd", ",", "besti", ",", "j", ")", ";", "}", "}" ]
Update the cache. @param size Working set size @param scratch Scratch matrix @param bestd Best distance @param besti Best index @param x First cluster @param y Second cluster, {@code y < x} @param j Updated value d(y, j) @param d New distance
[ "Update", "the", "cache", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/AnderbergHierarchicalClustering.java#L312-L323
looly/hutool
hutool-core/src/main/java/cn/hutool/core/convert/Convert.java
Convert.hexStrToStr
@Deprecated public static String hexStrToStr(String hexStr, Charset charset) { return hexToStr(hexStr, charset); }
java
@Deprecated public static String hexStrToStr(String hexStr, Charset charset) { return hexToStr(hexStr, charset); }
[ "@", "Deprecated", "public", "static", "String", "hexStrToStr", "(", "String", "hexStr", ",", "Charset", "charset", ")", "{", "return", "hexToStr", "(", "hexStr", ",", "charset", ")", ";", "}" ]
十六进制转换字符串 @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B]) @param charset 编码 {@link Charset} @return 对应的字符串 @see HexUtil#decodeHexStr(String, Charset) @deprecated 请使用 {@link #hexToStr(String, Charset)}
[ "十六进制转换字符串" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L730-L733
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java
FileWriter.writeLines
public <T> File writeLines(Collection<T> list) throws IORuntimeException { return writeLines(list, false); }
java
public <T> File writeLines(Collection<T> list) throws IORuntimeException { return writeLines(list, false); }
[ "public", "<", "T", ">", "File", "writeLines", "(", "Collection", "<", "T", ">", "list", ")", "throws", "IORuntimeException", "{", "return", "writeLines", "(", "list", ",", "false", ")", ";", "}" ]
将列表写入文件,覆盖模式 @param <T> 集合元素类型 @param list 列表 @return 目标文件 @throws IORuntimeException IO异常
[ "将列表写入文件,覆盖模式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java#L157-L159
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java
PaxPropertySetter.setProperty
public void setProperty(String name, String value) { if (value == null) return; name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); //LogLog.debug("---------Key: "+name+", type="+prop.getPropertyType()); if (prop == null) { LogLog.warn("No such property [" + name + "] in "+ obj.getClass().getName()+"." ); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { LogLog.warn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex.rootCause); } } }
java
public void setProperty(String name, String value) { if (value == null) return; name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); //LogLog.debug("---------Key: "+name+", type="+prop.getPropertyType()); if (prop == null) { LogLog.warn("No such property [" + name + "] in "+ obj.getClass().getName()+"." ); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { LogLog.warn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex.rootCause); } } }
[ "public", "void", "setProperty", "(", "String", "name", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", ";", "name", "=", "Introspector", ".", "decapitalize", "(", "name", ")", ";", "PropertyDescriptor", "prop", "=", "getPropertyDescriptor", "(", "name", ")", ";", "//LogLog.debug(\"---------Key: \"+name+\", type=\"+prop.getPropertyType());", "if", "(", "prop", "==", "null", ")", "{", "LogLog", ".", "warn", "(", "\"No such property [\"", "+", "name", "+", "\"] in \"", "+", "obj", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", ")", ";", "}", "else", "{", "try", "{", "setProperty", "(", "prop", ",", "name", ",", "value", ")", ";", "}", "catch", "(", "PropertySetterException", "ex", ")", "{", "LogLog", ".", "warn", "(", "\"Failed to set property [\"", "+", "name", "+", "\"] to value \\\"\"", "+", "value", "+", "\"\\\". \"", ",", "ex", ".", "rootCause", ")", ";", "}", "}", "}" ]
Set a property on this PaxPropertySetter's Object. If successful, this method will invoke a setter method on the underlying Object. The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method. <p>If the setter expects a String no conversion is necessary. If it expects an int, then an attempt is made to convert 'value' to an int using new Integer(value). If the setter expects a boolean, the conversion is by new Boolean(value). @param name name of the property @param value String value of the property
[ "Set", "a", "property", "on", "this", "PaxPropertySetter", "s", "Object", ".", "If", "successful", "this", "method", "will", "invoke", "a", "setter", "method", "on", "the", "underlying", "Object", ".", "The", "setter", "is", "the", "one", "for", "the", "specified", "property", "name", "and", "the", "value", "is", "determined", "partly", "from", "the", "setter", "argument", "type", "and", "partly", "from", "the", "value", "specified", "in", "the", "call", "to", "this", "method", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java#L255-L275
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
FormLayout.computeGridOrigins
private static int[] computeGridOrigins(Container container, int totalSize, int offset, List formSpecs, List[] componentLists, int[][] groupIndices, Measure minMeasure, Measure prefMeasure) { /* For each spec compute the minimum and preferred size that is * the maximum of all component minimum and preferred sizes resp. */ int[] minSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, minMeasure); int[] prefSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, prefMeasure); int[] groupedMinSizes = groupedSizes(groupIndices, minSizes); int[] groupedPrefSizes = groupedSizes(groupIndices, prefSizes); int totalMinSize = sum(groupedMinSizes); int totalPrefSize = sum(groupedPrefSizes); int[] compressedSizes = compressedSizes(formSpecs, totalSize, totalMinSize, totalPrefSize, groupedMinSizes, prefSizes); int[] groupedSizes = groupedSizes(groupIndices, compressedSizes); int totalGroupedSize = sum(groupedSizes); int[] sizes = distributedSizes(formSpecs, totalSize, totalGroupedSize, groupedSizes); return computeOrigins(sizes, offset); }
java
private static int[] computeGridOrigins(Container container, int totalSize, int offset, List formSpecs, List[] componentLists, int[][] groupIndices, Measure minMeasure, Measure prefMeasure) { /* For each spec compute the minimum and preferred size that is * the maximum of all component minimum and preferred sizes resp. */ int[] minSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, minMeasure); int[] prefSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, prefMeasure); int[] groupedMinSizes = groupedSizes(groupIndices, minSizes); int[] groupedPrefSizes = groupedSizes(groupIndices, prefSizes); int totalMinSize = sum(groupedMinSizes); int totalPrefSize = sum(groupedPrefSizes); int[] compressedSizes = compressedSizes(formSpecs, totalSize, totalMinSize, totalPrefSize, groupedMinSizes, prefSizes); int[] groupedSizes = groupedSizes(groupIndices, compressedSizes); int totalGroupedSize = sum(groupedSizes); int[] sizes = distributedSizes(formSpecs, totalSize, totalGroupedSize, groupedSizes); return computeOrigins(sizes, offset); }
[ "private", "static", "int", "[", "]", "computeGridOrigins", "(", "Container", "container", ",", "int", "totalSize", ",", "int", "offset", ",", "List", "formSpecs", ",", "List", "[", "]", "componentLists", ",", "int", "[", "]", "[", "]", "groupIndices", ",", "Measure", "minMeasure", ",", "Measure", "prefMeasure", ")", "{", "/* For each spec compute the minimum and preferred size that is\n * the maximum of all component minimum and preferred sizes resp.\n */", "int", "[", "]", "minSizes", "=", "maximumSizes", "(", "container", ",", "formSpecs", ",", "componentLists", ",", "minMeasure", ",", "prefMeasure", ",", "minMeasure", ")", ";", "int", "[", "]", "prefSizes", "=", "maximumSizes", "(", "container", ",", "formSpecs", ",", "componentLists", ",", "minMeasure", ",", "prefMeasure", ",", "prefMeasure", ")", ";", "int", "[", "]", "groupedMinSizes", "=", "groupedSizes", "(", "groupIndices", ",", "minSizes", ")", ";", "int", "[", "]", "groupedPrefSizes", "=", "groupedSizes", "(", "groupIndices", ",", "prefSizes", ")", ";", "int", "totalMinSize", "=", "sum", "(", "groupedMinSizes", ")", ";", "int", "totalPrefSize", "=", "sum", "(", "groupedPrefSizes", ")", ";", "int", "[", "]", "compressedSizes", "=", "compressedSizes", "(", "formSpecs", ",", "totalSize", ",", "totalMinSize", ",", "totalPrefSize", ",", "groupedMinSizes", ",", "prefSizes", ")", ";", "int", "[", "]", "groupedSizes", "=", "groupedSizes", "(", "groupIndices", ",", "compressedSizes", ")", ";", "int", "totalGroupedSize", "=", "sum", "(", "groupedSizes", ")", ";", "int", "[", "]", "sizes", "=", "distributedSizes", "(", "formSpecs", ",", "totalSize", ",", "totalGroupedSize", ",", "groupedSizes", ")", ";", "return", "computeOrigins", "(", "sizes", ",", "offset", ")", ";", "}" ]
Computes and returns the grid's origins. @param container the layout container @param totalSize the total size to assign @param offset the offset from left or top margin @param formSpecs the column or row specs, resp. @param componentLists the components list for each col/row @param minMeasure the measure used to determine min sizes @param prefMeasure the measure used to determine pre sizes @param groupIndices the group specification @return an int array with the origins
[ "Computes", "and", "returns", "the", "grid", "s", "origins", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L1325-L1357
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java
WikibaseDataFetcher.getEntityDocumentByTitle
public EntityDocument getEntityDocumentByTitle(String siteKey, String title) throws MediaWikiApiErrorException, IOException { return getEntityDocumentsByTitle(siteKey, title).get(title); }
java
public EntityDocument getEntityDocumentByTitle(String siteKey, String title) throws MediaWikiApiErrorException, IOException { return getEntityDocumentsByTitle(siteKey, title).get(title); }
[ "public", "EntityDocument", "getEntityDocumentByTitle", "(", "String", "siteKey", ",", "String", "title", ")", "throws", "MediaWikiApiErrorException", ",", "IOException", "{", "return", "getEntityDocumentsByTitle", "(", "siteKey", ",", "title", ")", ".", "get", "(", "title", ")", ";", "}" ]
Fetches the document for the entity that has a page of the given title on the given site. Site keys should be some site identifier known to the Wikibase site that is queried, such as "enwiki" for Wikidata.org. <p> Note: This method will not work properly if a filter is set for sites that excludes the requested site. @param siteKey wiki site id, e.g., "enwiki" @param title string titles (e.g. "Douglas Adams") of requested entities @return document for the entity with this title, or null if no such document exists @throws MediaWikiApiErrorException @throws IOException
[ "Fetches", "the", "document", "for", "the", "entity", "that", "has", "a", "page", "of", "the", "given", "title", "on", "the", "given", "site", ".", "Site", "keys", "should", "be", "some", "site", "identifier", "known", "to", "the", "Wikibase", "site", "that", "is", "queried", "such", "as", "enwiki", "for", "Wikidata", ".", "org", ".", "<p", ">", "Note", ":", "This", "method", "will", "not", "work", "properly", "if", "a", "filter", "is", "set", "for", "sites", "that", "excludes", "the", "requested", "site", "." ]
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/WikibaseDataFetcher.java#L211-L214
aws/aws-sdk-java
aws-java-sdk-costexplorer/src/main/java/com/amazonaws/services/costexplorer/model/ReservationCoverageGroup.java
ReservationCoverageGroup.withAttributes
public ReservationCoverageGroup withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public ReservationCoverageGroup withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
[ "public", "ReservationCoverageGroup", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
<p> The attributes for this group of reservations. </p> @param attributes The attributes for this group of reservations. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "The", "attributes", "for", "this", "group", "of", "reservations", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-costexplorer/src/main/java/com/amazonaws/services/costexplorer/model/ReservationCoverageGroup.java#L79-L82
samskivert/pythagoras
src/main/java/pythagoras/i/MathUtil.java
MathUtil.floorDiv
public static int floorDiv (int dividend, int divisor) { boolean numpos = dividend >= 0, denpos = divisor >= 0; if (numpos == denpos) return dividend / divisor; return denpos ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor; }
java
public static int floorDiv (int dividend, int divisor) { boolean numpos = dividend >= 0, denpos = divisor >= 0; if (numpos == denpos) return dividend / divisor; return denpos ? (dividend - divisor + 1) / divisor : (dividend - divisor - 1) / divisor; }
[ "public", "static", "int", "floorDiv", "(", "int", "dividend", ",", "int", "divisor", ")", "{", "boolean", "numpos", "=", "dividend", ">=", "0", ",", "denpos", "=", "divisor", ">=", "0", ";", "if", "(", "numpos", "==", "denpos", ")", "return", "dividend", "/", "divisor", ";", "return", "denpos", "?", "(", "dividend", "-", "divisor", "+", "1", ")", "/", "divisor", ":", "(", "dividend", "-", "divisor", "-", "1", ")", "/", "divisor", ";", "}" ]
Computes the floored division {@code dividend/divisor} which is useful when dividing potentially negative numbers into bins. <p> For example, the following numbers {@code floorDiv} 10 are: <pre> -15 -10 -8 -2 0 2 8 10 15 -2 -1 -1 -1 0 0 0 1 1 </pre>
[ "Computes", "the", "floored", "division", "{", "@code", "dividend", "/", "divisor", "}", "which", "is", "useful", "when", "dividing", "potentially", "negative", "numbers", "into", "bins", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/i/MathUtil.java#L31-L35
Kurento/kurento-module-creator
src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java
ExpressionParser.parseVersionExpression
private Expression parseVersionExpression() { int major = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And(new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0))); } int minor = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); consumeNextToken(STAR); return new And(new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0))); }
java
private Expression parseVersionExpression() { int major = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); if (tokens.positiveLookahead(STAR)) { tokens.consume(); return new And(new GreaterOrEqual(versionOf(major, 0, 0)), new Less(versionOf(major + 1, 0, 0))); } int minor = intOf(consumeNextToken(NUMERIC).lexeme); consumeNextToken(DOT); consumeNextToken(STAR); return new And(new GreaterOrEqual(versionOf(major, minor, 0)), new Less(versionOf(major, minor + 1, 0))); }
[ "private", "Expression", "parseVersionExpression", "(", ")", "{", "int", "major", "=", "intOf", "(", "consumeNextToken", "(", "NUMERIC", ")", ".", "lexeme", ")", ";", "consumeNextToken", "(", "DOT", ")", ";", "if", "(", "tokens", ".", "positiveLookahead", "(", "STAR", ")", ")", "{", "tokens", ".", "consume", "(", ")", ";", "return", "new", "And", "(", "new", "GreaterOrEqual", "(", "versionOf", "(", "major", ",", "0", ",", "0", ")", ")", ",", "new", "Less", "(", "versionOf", "(", "major", "+", "1", ",", "0", ",", "0", ")", ")", ")", ";", "}", "int", "minor", "=", "intOf", "(", "consumeNextToken", "(", "NUMERIC", ")", ".", "lexeme", ")", ";", "consumeNextToken", "(", "DOT", ")", ";", "consumeNextToken", "(", "STAR", ")", ";", "return", "new", "And", "(", "new", "GreaterOrEqual", "(", "versionOf", "(", "major", ",", "minor", ",", "0", ")", ")", ",", "new", "Less", "(", "versionOf", "(", "major", ",", "minor", "+", "1", ",", "0", ")", ")", ")", ";", "}" ]
Parses the {@literal <version-expr>} non-terminal. <pre> {@literal <version-expr> ::= <major> "." "*" | <major> "." <minor> "." "*" } </pre> @return the expression AST
[ "Parses", "the", "{", "@literal", "<version", "-", "expr", ">", "}", "non", "-", "terminal", "." ]
train
https://github.com/Kurento/kurento-module-creator/blob/c371516c665b902b5476433496a5aefcbca86d64/src/main/java/com/github/zafarkhaja/semver/expr/ExpressionParser.java#L288-L301
ikew0ng/SwipeBackLayout
library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java
SwipeBackLayout.setShadow
public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); }
java
public void setShadow(Drawable shadow, int edgeFlag) { if ((edgeFlag & EDGE_LEFT) != 0) { mShadowLeft = shadow; } else if ((edgeFlag & EDGE_RIGHT) != 0) { mShadowRight = shadow; } else if ((edgeFlag & EDGE_BOTTOM) != 0) { mShadowBottom = shadow; } invalidate(); }
[ "public", "void", "setShadow", "(", "Drawable", "shadow", ",", "int", "edgeFlag", ")", "{", "if", "(", "(", "edgeFlag", "&", "EDGE_LEFT", ")", "!=", "0", ")", "{", "mShadowLeft", "=", "shadow", ";", "}", "else", "if", "(", "(", "edgeFlag", "&", "EDGE_RIGHT", ")", "!=", "0", ")", "{", "mShadowRight", "=", "shadow", ";", "}", "else", "if", "(", "(", "edgeFlag", "&", "EDGE_BOTTOM", ")", "!=", "0", ")", "{", "mShadowBottom", "=", "shadow", ";", "}", "invalidate", "(", ")", ";", "}" ]
Set a drawable used for edge shadow. @param shadow Drawable to use @param edgeFlags Combination of edge flags describing the edge to set @see #EDGE_LEFT @see #EDGE_RIGHT @see #EDGE_BOTTOM
[ "Set", "a", "drawable", "used", "for", "edge", "shadow", "." ]
train
https://github.com/ikew0ng/SwipeBackLayout/blob/7c6b0ac424813266cec57db86d65a7c9d9ff5fa6/library/src/main/java/me/imid/swipebacklayout/lib/SwipeBackLayout.java#L318-L327
timewalker74/ffmq
core/src/main/java/net/timewalker/ffmq4/local/session/LocalMessageProducer.java
LocalMessageProducer.sendToDestination
@Override protected final void sendToDestination(Destination destination, boolean destinationOverride, Message srcMessage, int deliveryMode, int priority, long timeToLive) throws JMSException { // Check that the destination was specified if (destination == null) throw new InvalidDestinationException("Destination not specified"); // [JMS SPEC] // Create an internal copy if necessary AbstractMessage message = MessageTools.makeInternalCopy(srcMessage); externalAccessLock.readLock().lock(); try { checkNotClosed(); // Dispatch to session ((LocalSession)session).dispatch(message); } finally { externalAccessLock.readLock().unlock(); } }
java
@Override protected final void sendToDestination(Destination destination, boolean destinationOverride, Message srcMessage, int deliveryMode, int priority, long timeToLive) throws JMSException { // Check that the destination was specified if (destination == null) throw new InvalidDestinationException("Destination not specified"); // [JMS SPEC] // Create an internal copy if necessary AbstractMessage message = MessageTools.makeInternalCopy(srcMessage); externalAccessLock.readLock().lock(); try { checkNotClosed(); // Dispatch to session ((LocalSession)session).dispatch(message); } finally { externalAccessLock.readLock().unlock(); } }
[ "@", "Override", "protected", "final", "void", "sendToDestination", "(", "Destination", "destination", ",", "boolean", "destinationOverride", ",", "Message", "srcMessage", ",", "int", "deliveryMode", ",", "int", "priority", ",", "long", "timeToLive", ")", "throws", "JMSException", "{", "// Check that the destination was specified", "if", "(", "destination", "==", "null", ")", "throw", "new", "InvalidDestinationException", "(", "\"Destination not specified\"", ")", ";", "// [JMS SPEC]", "// Create an internal copy if necessary", "AbstractMessage", "message", "=", "MessageTools", ".", "makeInternalCopy", "(", "srcMessage", ")", ";", "externalAccessLock", ".", "readLock", "(", ")", ".", "lock", "(", ")", ";", "try", "{", "checkNotClosed", "(", ")", ";", "// Dispatch to session", "(", "(", "LocalSession", ")", "session", ")", ".", "dispatch", "(", "message", ")", ";", "}", "finally", "{", "externalAccessLock", ".", "readLock", "(", ")", ".", "unlock", "(", ")", ";", "}", "}" ]
/* (non-Javadoc) @see net.timewalker.ffmq4.common.session.AbstractMessageProducer#sendToDestination(javax.jms.Destination, boolean, javax.jms.Message, int, int, long)
[ "/", "*", "(", "non", "-", "Javadoc", ")" ]
train
https://github.com/timewalker74/ffmq/blob/638773ee29a4a5f9c6119ed74ad14ac9c46382b3/core/src/main/java/net/timewalker/ffmq4/local/session/LocalMessageProducer.java#L90-L112
pryzach/midao
midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/MappingUtils.java
MappingUtils.invokeFunction
public static Object invokeFunction(Object object, String functionName, Class[] parameters, Object[] values) throws MjdbcException { Object result = null; try { Method method = object.getClass().getMethod(functionName, parameters); method.setAccessible(true); result = method.invoke(object, values); } catch (Exception ex) { throw new MjdbcException(ex); } return result; }
java
public static Object invokeFunction(Object object, String functionName, Class[] parameters, Object[] values) throws MjdbcException { Object result = null; try { Method method = object.getClass().getMethod(functionName, parameters); method.setAccessible(true); result = method.invoke(object, values); } catch (Exception ex) { throw new MjdbcException(ex); } return result; }
[ "public", "static", "Object", "invokeFunction", "(", "Object", "object", ",", "String", "functionName", ",", "Class", "[", "]", "parameters", ",", "Object", "[", "]", "values", ")", "throws", "MjdbcException", "{", "Object", "result", "=", "null", ";", "try", "{", "Method", "method", "=", "object", ".", "getClass", "(", ")", ".", "getMethod", "(", "functionName", ",", "parameters", ")", ";", "method", ".", "setAccessible", "(", "true", ")", ";", "result", "=", "method", ".", "invoke", "(", "object", ",", "values", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "throw", "new", "MjdbcException", "(", "ex", ")", ";", "}", "return", "result", ";", "}" ]
Invokes class function using Reflection @param object Instance which function would be invoked @param functionName function name @param parameters function parameters (array of Class) @param values function values (array of Object) @return function return @throws org.midao.jdbc.core.exception.MjdbcException in case function doesn't exists
[ "Invokes", "class", "function", "using", "Reflection" ]
train
https://github.com/pryzach/midao/blob/ed9048ed2c792a4794a2116a25779dfb84cd9447/midao-jdbc-core/src/main/java/org/midao/jdbc/core/handlers/utils/MappingUtils.java#L261-L273
hypfvieh/java-utils
src/main/java/com/github/hypfvieh/util/CompareUtil.java
CompareUtil.ifTrue
@SuppressWarnings("unchecked") public static <T> T ifTrue(boolean _b, T _t) { return _b ? _t : (_t instanceof CharSequence ? (T) "" : null); }
java
@SuppressWarnings("unchecked") public static <T> T ifTrue(boolean _b, T _t) { return _b ? _t : (_t instanceof CharSequence ? (T) "" : null); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "T", ">", "T", "ifTrue", "(", "boolean", "_b", ",", "T", "_t", ")", "{", "return", "_b", "?", "_t", ":", "(", "_t", "instanceof", "CharSequence", "?", "(", "T", ")", "\"\"", ":", "null", ")", ";", "}" ]
Returns the second parameter if the condition is true or null if the condition is false. Returns empty string instead of null for implementors of {@link CharSequence}. @param _b condition @param _t object @return object or null
[ "Returns", "the", "second", "parameter", "if", "the", "condition", "is", "true", "or", "null", "if", "the", "condition", "is", "false", ".", "Returns", "empty", "string", "instead", "of", "null", "for", "implementors", "of", "{" ]
train
https://github.com/hypfvieh/java-utils/blob/407c32d6b485596d4d2b644f5f7fc7a02d0169c6/src/main/java/com/github/hypfvieh/util/CompareUtil.java#L72-L75
ppiastucki/recast4j
detour-extras/src/main/java/org/recast4j/detour/extras/unity/astar/LinkBuilder.java
LinkBuilder.build
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) { for (int n = 0; n < connections.size(); n++) { int[] nodeConnections = connections.get(n); MeshData tile = graphData.getTile(n); Poly node = graphData.getNode(n); for (int connection : nodeConnections) { MeshData neighbourTile = graphData.getTile(connection - nodeOffset); if (neighbourTile != tile) { buildExternalLink(tile, node, neighbourTile); } else { Poly neighbour = graphData.getNode(connection - nodeOffset); buildInternalLink(tile, node, neighbourTile, neighbour); } } } }
java
void build(int nodeOffset, GraphMeshData graphData, List<int[]> connections) { for (int n = 0; n < connections.size(); n++) { int[] nodeConnections = connections.get(n); MeshData tile = graphData.getTile(n); Poly node = graphData.getNode(n); for (int connection : nodeConnections) { MeshData neighbourTile = graphData.getTile(connection - nodeOffset); if (neighbourTile != tile) { buildExternalLink(tile, node, neighbourTile); } else { Poly neighbour = graphData.getNode(connection - nodeOffset); buildInternalLink(tile, node, neighbourTile, neighbour); } } } }
[ "void", "build", "(", "int", "nodeOffset", ",", "GraphMeshData", "graphData", ",", "List", "<", "int", "[", "]", ">", "connections", ")", "{", "for", "(", "int", "n", "=", "0", ";", "n", "<", "connections", ".", "size", "(", ")", ";", "n", "++", ")", "{", "int", "[", "]", "nodeConnections", "=", "connections", ".", "get", "(", "n", ")", ";", "MeshData", "tile", "=", "graphData", ".", "getTile", "(", "n", ")", ";", "Poly", "node", "=", "graphData", ".", "getNode", "(", "n", ")", ";", "for", "(", "int", "connection", ":", "nodeConnections", ")", "{", "MeshData", "neighbourTile", "=", "graphData", ".", "getTile", "(", "connection", "-", "nodeOffset", ")", ";", "if", "(", "neighbourTile", "!=", "tile", ")", "{", "buildExternalLink", "(", "tile", ",", "node", ",", "neighbourTile", ")", ";", "}", "else", "{", "Poly", "neighbour", "=", "graphData", ".", "getNode", "(", "connection", "-", "nodeOffset", ")", ";", "buildInternalLink", "(", "tile", ",", "node", ",", "neighbourTile", ",", "neighbour", ")", ";", "}", "}", "}", "}" ]
Process connections and transform them into recast neighbour flags
[ "Process", "connections", "and", "transform", "them", "into", "recast", "neighbour", "flags" ]
train
https://github.com/ppiastucki/recast4j/blob/a414dc34f16b87c95fb4e0f46c28a7830d421788/detour-extras/src/main/java/org/recast4j/detour/extras/unity/astar/LinkBuilder.java#L13-L28
sarl/sarl
contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java
PyExpressionGenerator._generate
protected XExpression _generate(XBasicForLoopExpression forLoop, IAppendable it, IExtraLanguageGeneratorContext context) { for (final XExpression expr : forLoop.getInitExpressions()) { generate(expr, it, context); it.newLine(); } it.append("while "); //$NON-NLS-1$ generate(forLoop.getExpression(), it, context); it.append(":"); //$NON-NLS-1$ it.increaseIndentation().newLine(); final XExpression last = generate(forLoop.getEachExpression(), it, context); for (final XExpression expr : forLoop.getUpdateExpressions()) { it.newLine(); generate(expr, it, context); } it.decreaseIndentation(); return last; }
java
protected XExpression _generate(XBasicForLoopExpression forLoop, IAppendable it, IExtraLanguageGeneratorContext context) { for (final XExpression expr : forLoop.getInitExpressions()) { generate(expr, it, context); it.newLine(); } it.append("while "); //$NON-NLS-1$ generate(forLoop.getExpression(), it, context); it.append(":"); //$NON-NLS-1$ it.increaseIndentation().newLine(); final XExpression last = generate(forLoop.getEachExpression(), it, context); for (final XExpression expr : forLoop.getUpdateExpressions()) { it.newLine(); generate(expr, it, context); } it.decreaseIndentation(); return last; }
[ "protected", "XExpression", "_generate", "(", "XBasicForLoopExpression", "forLoop", ",", "IAppendable", "it", ",", "IExtraLanguageGeneratorContext", "context", ")", "{", "for", "(", "final", "XExpression", "expr", ":", "forLoop", ".", "getInitExpressions", "(", ")", ")", "{", "generate", "(", "expr", ",", "it", ",", "context", ")", ";", "it", ".", "newLine", "(", ")", ";", "}", "it", ".", "append", "(", "\"while \"", ")", ";", "//$NON-NLS-1$", "generate", "(", "forLoop", ".", "getExpression", "(", ")", ",", "it", ",", "context", ")", ";", "it", ".", "append", "(", "\":\"", ")", ";", "//$NON-NLS-1$", "it", ".", "increaseIndentation", "(", ")", ".", "newLine", "(", ")", ";", "final", "XExpression", "last", "=", "generate", "(", "forLoop", ".", "getEachExpression", "(", ")", ",", "it", ",", "context", ")", ";", "for", "(", "final", "XExpression", "expr", ":", "forLoop", ".", "getUpdateExpressions", "(", ")", ")", "{", "it", ".", "newLine", "(", ")", ";", "generate", "(", "expr", ",", "it", ",", "context", ")", ";", "}", "it", ".", "decreaseIndentation", "(", ")", ";", "return", "last", ";", "}" ]
Generate the given object. @param forLoop the for-loop. @param it the target for the generated content. @param context the context. @return the last statement in the loop or {@code null}.
[ "Generate", "the", "given", "object", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/contribs/io.sarl.pythongenerator/io.sarl.pythongenerator.generator/src/io/sarl/pythongenerator/generator/generator/PyExpressionGenerator.java#L649-L665