repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
188
func_name
stringlengths
7
127
whole_func_string
stringlengths
77
3.91k
language
stringclasses
1 value
func_code_string
stringlengths
77
3.91k
func_code_tokens
listlengths
20
745
func_documentation_string
stringlengths
61
1.98k
func_documentation_tokens
listlengths
1
477
split_name
stringclasses
1 value
func_code_url
stringlengths
111
288
apache/groovy
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
DefaultGroovyMethods.collectEntries
public static <K, V> Map<K, V> collectEntries(Iterator<?> self) { return collectEntries(self, Closure.IDENTITY); }
java
public static <K, V> Map<K, V> collectEntries(Iterator<?> self) { return collectEntries(self, Closure.IDENTITY); }
[ "public", "static", "<", "K", ",", "V", ">", "Map", "<", "K", ",", "V", ">", "collectEntries", "(", "Iterator", "<", "?", ">", "self", ")", "{", "return", "collectEntries", "(", "self", ",", "Closure", ".", "IDENTITY", ")", ";", "}" ]
A variant of collectEntries for Iterators using the identity closure as the transform. @param self an Iterator @return a Map of the transformed entries @see #collectEntries(Iterable) @since 1.8.7
[ "A", "variant", "of", "collectEntries", "for", "Iterators", "using", "the", "identity", "closure", "as", "the", "transform", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L4069-L4071
habernal/confusion-matrix
src/main/java/com/github/habernal/confusionmatrix/ConfusionMatrix.java
ConfusionMatrix.increaseValue
public void increaseValue(String goldValue, String observedValue, int times) { allGoldLabels.add(goldValue); allPredictedLabels.add(observedValue); for (int i = 0; i < times; i++) { labelSeries.add(observedValue); } if (!map.containsKey(goldValue)) { map.put(goldValue, new TreeMap<String, Integer>()); } if (!map.get(goldValue).containsKey(observedValue)) { map.get(goldValue).put(observedValue, 0); } int currentValue = this.map.get(goldValue).get(observedValue); this.map.get(goldValue).put(observedValue, currentValue + times); total += times; if (goldValue.equals(observedValue)) { correct += times; } }
java
public void increaseValue(String goldValue, String observedValue, int times) { allGoldLabels.add(goldValue); allPredictedLabels.add(observedValue); for (int i = 0; i < times; i++) { labelSeries.add(observedValue); } if (!map.containsKey(goldValue)) { map.put(goldValue, new TreeMap<String, Integer>()); } if (!map.get(goldValue).containsKey(observedValue)) { map.get(goldValue).put(observedValue, 0); } int currentValue = this.map.get(goldValue).get(observedValue); this.map.get(goldValue).put(observedValue, currentValue + times); total += times; if (goldValue.equals(observedValue)) { correct += times; } }
[ "public", "void", "increaseValue", "(", "String", "goldValue", ",", "String", "observedValue", ",", "int", "times", ")", "{", "allGoldLabels", ".", "add", "(", "goldValue", ")", ";", "allPredictedLabels", ".", "add", "(", "observedValue", ")", ";", "for", "(...
Increases value of goldValue x observedValue n times @param goldValue exp @param observedValue ac @param times n-times
[ "Increases", "value", "of", "goldValue", "x", "observedValue", "n", "times" ]
train
https://github.com/habernal/confusion-matrix/blob/d0310f0aeda0fa74a9d42bcb190db7250bf49ecc/src/main/java/com/github/habernal/confusionmatrix/ConfusionMatrix.java#L98-L123
jMotif/SAX
src/main/java/net/seninp/jmotif/sax/TSProcessor.java
TSProcessor.seriesToString
public String seriesToString(double[] series, NumberFormat df) { StringBuffer sb = new StringBuffer(); sb.append('['); for (double d : series) { sb.append(df.format(d)).append(','); } sb.delete(sb.length() - 2, sb.length() - 1).append("]"); return sb.toString(); }
java
public String seriesToString(double[] series, NumberFormat df) { StringBuffer sb = new StringBuffer(); sb.append('['); for (double d : series) { sb.append(df.format(d)).append(','); } sb.delete(sb.length() - 2, sb.length() - 1).append("]"); return sb.toString(); }
[ "public", "String", "seriesToString", "(", "double", "[", "]", "series", ",", "NumberFormat", "df", ")", "{", "StringBuffer", "sb", "=", "new", "StringBuffer", "(", ")", ";", "sb", ".", "append", "(", "'", "'", ")", ";", "for", "(", "double", "d", ":...
Prettyfies the timeseries for screen output. @param series the data. @param df the number format to use. @return The timeseries formatted for screen output.
[ "Prettyfies", "the", "timeseries", "for", "screen", "output", "." ]
train
https://github.com/jMotif/SAX/blob/39ee07a69facaa330def5130b8790aeda85f1061/src/main/java/net/seninp/jmotif/sax/TSProcessor.java#L461-L469
Azure/azure-sdk-for-java
mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java
LiveEventsInner.beginUpdateAsync
public Observable<LiveEventInner> beginUpdateAsync(String resourceGroupName, String accountName, String liveEventName, LiveEventInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, parameters).map(new Func1<ServiceResponse<LiveEventInner>, LiveEventInner>() { @Override public LiveEventInner call(ServiceResponse<LiveEventInner> response) { return response.body(); } }); }
java
public Observable<LiveEventInner> beginUpdateAsync(String resourceGroupName, String accountName, String liveEventName, LiveEventInner parameters) { return beginUpdateWithServiceResponseAsync(resourceGroupName, accountName, liveEventName, parameters).map(new Func1<ServiceResponse<LiveEventInner>, LiveEventInner>() { @Override public LiveEventInner call(ServiceResponse<LiveEventInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "LiveEventInner", ">", "beginUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "accountName", ",", "String", "liveEventName", ",", "LiveEventInner", "parameters", ")", "{", "return", "beginUpdateWithServiceResponseAsync", "(", ...
Updates a existing Live Event. @param resourceGroupName The name of the resource group within the Azure subscription. @param accountName The Media Services account name. @param liveEventName The name of the Live Event. @param parameters Live Event properties needed for creation. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the LiveEventInner object
[ "Updates", "a", "existing", "Live", "Event", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java#L869-L876
CloudSlang/cs-actions
cs-json/src/main/java/io/cloudslang/content/json/actions/MergeArrays.java
MergeArrays.execute
@Action(name = "Merge Arrays", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1, @Param(value = Constants.InputNames.ARRAY, required = true) String array2) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(array1)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, exceptionValue, new Exception(exceptionValue)); } if (StringUtilities.isBlank(array2)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, new Exception(exceptionValue)); } JsonNode jsonNode1; JsonNode jsonNode2; ObjectMapper mapper = new ObjectMapper(); try { jsonNode1 = mapper.readTree(array1); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1; return populateResult(returnResult, value, exception); } try { jsonNode2 = mapper.readTree(array2); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2; return populateResult(returnResult, value, exception); } final String result; if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) { final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1; final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2; final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory()); asJsonArrayResult.addAll(asJsonArray1); asJsonArrayResult.addAll(asJsonArray2); result = asJsonArrayResult.toString(); } else { result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2; return populateResult(returnResult, new Exception(result)); } return populateResult(returnResult, result, null); }
java
@Action(name = "Merge Arrays", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.ARRAY, required = true) String array1, @Param(value = Constants.InputNames.ARRAY, required = true) String array2) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(array1)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, exceptionValue, new Exception(exceptionValue)); } if (StringUtilities.isBlank(array2)) { final String exceptionValue = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY2_MESSAGE.replaceFirst("=", EMPTY_STRING); return populateResult(returnResult, new Exception(exceptionValue)); } JsonNode jsonNode1; JsonNode jsonNode2; ObjectMapper mapper = new ObjectMapper(); try { jsonNode1 = mapper.readTree(array1); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY1_MESSAGE + array1; return populateResult(returnResult, value, exception); } try { jsonNode2 = mapper.readTree(array2); } catch (IOException exception) { final String value = INVALID_JSON_OBJECT_PROVIDED_EXCEPTION_MESSAGE + ARRAY2_MESSAGE + array2; return populateResult(returnResult, value, exception); } final String result; if (jsonNode1 instanceof ArrayNode && jsonNode2 instanceof ArrayNode) { final ArrayNode asJsonArray1 = (ArrayNode) jsonNode1; final ArrayNode asJsonArray2 = (ArrayNode) jsonNode2; final ArrayNode asJsonArrayResult = new ArrayNode(mapper.getNodeFactory()); asJsonArrayResult.addAll(asJsonArray1); asJsonArrayResult.addAll(asJsonArray2); result = asJsonArrayResult.toString(); } else { result = NOT_A_VALID_JSON_ARRAY_MESSAGE + ARRAY1_MESSAGE + array1 + ARRAY2_MESSAGE + array2; return populateResult(returnResult, new Exception(result)); } return populateResult(returnResult, result, null); }
[ "@", "Action", "(", "name", "=", "\"Merge Arrays\"", ",", "outputs", "=", "{", "@", "Output", "(", "OutputNames", ".", "RETURN_RESULT", ")", ",", "@", "Output", "(", "OutputNames", ".", "RETURN_CODE", ")", ",", "@", "Output", "(", "OutputNames", ".", "EX...
This operation merge the contents of two JSON arrays. This operation does not modify either of the input arrays. The result is the contents or array1 and array2, merged into a single array. The merge operation add into the result the first array and then the second array. @param array1 The string representation of a JSON array object. Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] @param array2 The string representation of a JSON array object. Arrays in JSON are comma separated lists of objects, enclosed in square brackets [ ]. Examples: [1,2,3] or ["one","two","three"] or [{"one":1, "two":2}, 3, "four"] @return a map containing the output of the operation. Keys present in the map are: <p/> <br><br><b>returnResult</b> - This will contain the string representation of the new JSON array with the contents of array1 and array2. <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, this result contains the java stack trace of the runtime exception. <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
[ "This", "operation", "merge", "the", "contents", "of", "two", "JSON", "arrays", ".", "This", "operation", "does", "not", "modify", "either", "of", "the", "input", "arrays", ".", "The", "result", "is", "the", "contents", "or", "array1", "and", "array2", "me...
train
https://github.com/CloudSlang/cs-actions/blob/9a1be1e99ad88286a6c153d5f2275df6ae1a57a1/cs-json/src/main/java/io/cloudslang/content/json/actions/MergeArrays.java#L72-L126
samskivert/pythagoras
src/main/java/pythagoras/f/MathUtil.java
MathUtil.angularDistance
public static float angularDistance (float a1, float a2) { float ma1 = mirrorAngle(a1), ma2 = mirrorAngle(a2); return Math.min(Math.abs(a1 - a2), Math.abs(ma1 - ma2)); }
java
public static float angularDistance (float a1, float a2) { float ma1 = mirrorAngle(a1), ma2 = mirrorAngle(a2); return Math.min(Math.abs(a1 - a2), Math.abs(ma1 - ma2)); }
[ "public", "static", "float", "angularDistance", "(", "float", "a1", ",", "float", "a2", ")", "{", "float", "ma1", "=", "mirrorAngle", "(", "a1", ")", ",", "ma2", "=", "mirrorAngle", "(", "a2", ")", ";", "return", "Math", ".", "min", "(", "Math", ".",...
Returns the (shortest) distance between two angles, assuming that both angles are in [-pi, +pi].
[ "Returns", "the", "(", "shortest", ")", "distance", "between", "two", "angles", "assuming", "that", "both", "angles", "are", "in", "[", "-", "pi", "+", "pi", "]", "." ]
train
https://github.com/samskivert/pythagoras/blob/b8fea743ee8a7d742ad9c06ee4f11f50571fbd32/src/main/java/pythagoras/f/MathUtil.java#L127-L130
lessthanoptimal/BoofCV
integration/boofcv-android/examples/video/app/src/main/java/org/boofcv/video/GradientActivity.java
GradientActivity.renderBitmapImage
@Override protected void renderBitmapImage(BitmapMode mode, ImageBase image) { switch( mode ) { case UNSAFE: { // this application is configured to use double buffer and could ignore all other modes VisualizeImageData.colorizeGradient(derivX, derivY, -1, bitmap, bitmapTmp); } break; case DOUBLE_BUFFER: { VisualizeImageData.colorizeGradient(derivX, derivY, -1, bitmapWork, bitmapTmp); if( bitmapLock.tryLock() ) { try { Bitmap tmp = bitmapWork; bitmapWork = bitmap; bitmap = tmp; } finally { bitmapLock.unlock(); } } } break; } }
java
@Override protected void renderBitmapImage(BitmapMode mode, ImageBase image) { switch( mode ) { case UNSAFE: { // this application is configured to use double buffer and could ignore all other modes VisualizeImageData.colorizeGradient(derivX, derivY, -1, bitmap, bitmapTmp); } break; case DOUBLE_BUFFER: { VisualizeImageData.colorizeGradient(derivX, derivY, -1, bitmapWork, bitmapTmp); if( bitmapLock.tryLock() ) { try { Bitmap tmp = bitmapWork; bitmapWork = bitmap; bitmap = tmp; } finally { bitmapLock.unlock(); } } } break; } }
[ "@", "Override", "protected", "void", "renderBitmapImage", "(", "BitmapMode", "mode", ",", "ImageBase", "image", ")", "{", "switch", "(", "mode", ")", "{", "case", "UNSAFE", ":", "{", "// this application is configured to use double buffer and could ignore all other modes...
Override the default behavior and colorize gradient instead of converting input image.
[ "Override", "the", "default", "behavior", "and", "colorize", "gradient", "instead", "of", "converting", "input", "image", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/integration/boofcv-android/examples/video/app/src/main/java/org/boofcv/video/GradientActivity.java#L143-L164
groupon/odo
browsermob-proxy/src/main/java/com/groupon/odo/bmp/KeyStoreManager.java
KeyStoreManager.mapPublicKeys
public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute) { _mappedPublicKeys.put(original, substitute); if(persistImmediately) { persistPublicKeyMap(); } }
java
public synchronized void mapPublicKeys(final PublicKey original, final PublicKey substitute) { _mappedPublicKeys.put(original, substitute); if(persistImmediately) { persistPublicKeyMap(); } }
[ "public", "synchronized", "void", "mapPublicKeys", "(", "final", "PublicKey", "original", ",", "final", "PublicKey", "substitute", ")", "{", "_mappedPublicKeys", ".", "put", "(", "original", ",", "substitute", ")", ";", "if", "(", "persistImmediately", ")", "{",...
Stores a public key mapping. @param original @param substitute
[ "Stores", "a", "public", "key", "mapping", "." ]
train
https://github.com/groupon/odo/blob/3bae43d5eca8ace036775e5b2d3ed9af1a9ff9b1/browsermob-proxy/src/main/java/com/groupon/odo/bmp/KeyStoreManager.java#L935-L939
unbescape/unbescape
src/main/java/org/unbescape/uri/UriEscape.java
UriEscape.unescapeUriQueryParam
public static void unescapeUriQueryParam(final String text, final Writer writer) throws IOException { unescapeUriQueryParam(text, writer, DEFAULT_ENCODING); }
java
public static void unescapeUriQueryParam(final String text, final Writer writer) throws IOException { unescapeUriQueryParam(text, writer, DEFAULT_ENCODING); }
[ "public", "static", "void", "unescapeUriQueryParam", "(", "final", "String", "text", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "unescapeUriQueryParam", "(", "text", ",", "writer", ",", "DEFAULT_ENCODING", ")", ";", "}" ]
<p> Perform am URI query parameter (name or value) <strong>unescape</strong> operation on a <tt>String</tt> input using <tt>UTF-8</tt> as encoding, writing results to a <tt>Writer</tt>. </p> <p> This method will unescape every percent-encoded (<tt>%HH</tt>) sequences present in input, even for those characters that do not need to be percent-encoded in this context (unreserved characters can be percent-encoded even if/when this is not required, though it is not generally considered a good practice). </p> <p> This method will use <tt>UTF-8</tt> in order to determine the characters specified in the percent-encoded byte sequences. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>String</tt> to be unescaped. @param writer the <tt>java.io.Writer</tt> to which the unescaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "am", "URI", "query", "parameter", "(", "name", "or", "value", ")", "<strong", ">", "unescape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "String<", "/", "tt", ">", "input", "using", "<tt", ">", "UTF", "-", "8<", ...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/uri/UriEscape.java#L1954-L1957
UrielCh/ovh-java-sdk
ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java
ApiOvhOrder.email_exchange_organizationName_service_exchangeService_upgrade_GET
public OvhOrder email_exchange_organizationName_service_exchangeService_upgrade_GET(String organizationName, String exchangeService) throws IOException { String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/upgrade"; StringBuilder sb = path(qPath, organizationName, exchangeService); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
java
public OvhOrder email_exchange_organizationName_service_exchangeService_upgrade_GET(String organizationName, String exchangeService) throws IOException { String qPath = "/order/email/exchange/{organizationName}/service/{exchangeService}/upgrade"; StringBuilder sb = path(qPath, organizationName, exchangeService); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhOrder.class); }
[ "public", "OvhOrder", "email_exchange_organizationName_service_exchangeService_upgrade_GET", "(", "String", "organizationName", ",", "String", "exchangeService", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/order/email/exchange/{organizationName}/service/{exchangeSe...
Get prices and contracts information REST: GET /order/email/exchange/{organizationName}/service/{exchangeService}/upgrade @param organizationName [required] The internal name of your exchange organization @param exchangeService [required] The internal name of your exchange service
[ "Get", "prices", "and", "contracts", "information" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-order/src/main/java/net/minidev/ovh/api/ApiOvhOrder.java#L3773-L3778
jboss-integration/fuse-bxms-integ
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java
KnowledgeOperations.getInputList
public static List<Object> getInputList(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { return getInputList(message, operation.getInputExpressionMappings(), runtime); }
java
public static List<Object> getInputList(Message message, KnowledgeOperation operation, KnowledgeRuntimeEngine runtime) { return getInputList(message, operation.getInputExpressionMappings(), runtime); }
[ "public", "static", "List", "<", "Object", ">", "getInputList", "(", "Message", "message", ",", "KnowledgeOperation", "operation", ",", "KnowledgeRuntimeEngine", "runtime", ")", "{", "return", "getInputList", "(", "message", ",", "operation", ".", "getInputExpressio...
Gets an input (all) list. @param message the message @param operation the operation @param runtime the runtime engine @return the input (all) list
[ "Gets", "an", "input", "(", "all", ")", "list", "." ]
train
https://github.com/jboss-integration/fuse-bxms-integ/blob/ca5c012bf867ea15d1250f0991af3cd7e708aaaf/switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/operation/KnowledgeOperations.java#L190-L192
aws/aws-sdk-java
aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/GetQueueAttributesResult.java
GetQueueAttributesResult.withAttributes
public GetQueueAttributesResult withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
java
public GetQueueAttributesResult withAttributes(java.util.Map<String, String> attributes) { setAttributes(attributes); return this; }
[ "public", "GetQueueAttributesResult", "withAttributes", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "attributes", ")", "{", "setAttributes", "(", "attributes", ")", ";", "return", "this", ";", "}" ]
<p> A map of attributes to their respective values. </p> @param attributes A map of attributes to their respective values. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "map", "of", "attributes", "to", "their", "respective", "values", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-sqs/src/main/java/com/amazonaws/services/sqs/model/GetQueueAttributesResult.java#L74-L77
fcrepo4/fcrepo4
fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java
ContentExposingResource.createUpdateResponse
@SuppressWarnings("resource") protected Response createUpdateResponse(final FedoraResource resource, final boolean created) { addCacheControlHeaders(servletResponse, resource, session); addResourceLinkHeaders(resource, created); addExternalContentHeaders(resource); addAclHeader(resource); addMementoHeaders(resource); if (!created) { return noContent().build(); } final URI location = getUri(resource); final Response.ResponseBuilder builder = created(location); if (prefer == null || !prefer.hasReturn()) { final MediaType acceptablePlainText = acceptabePlainTextMediaType(); if (acceptablePlainText != null) { return builder.type(acceptablePlainText).entity(location.toString()).build(); } return notAcceptable(mediaTypes(TEXT_PLAIN_TYPE).build()).build(); } else if (prefer.getReturn().getValue().equals("minimal")) { return builder.build(); } else { if (prefer != null) { prefer.getReturn().addResponseHeaders(servletResponse); } final RdfNamespacedStream rdfStream = new RdfNamespacedStream( new DefaultRdfStream(asNode(resource), getResourceTriples(resource)), namespaceRegistry.getNamespaces()); return builder.entity(rdfStream).build(); } }
java
@SuppressWarnings("resource") protected Response createUpdateResponse(final FedoraResource resource, final boolean created) { addCacheControlHeaders(servletResponse, resource, session); addResourceLinkHeaders(resource, created); addExternalContentHeaders(resource); addAclHeader(resource); addMementoHeaders(resource); if (!created) { return noContent().build(); } final URI location = getUri(resource); final Response.ResponseBuilder builder = created(location); if (prefer == null || !prefer.hasReturn()) { final MediaType acceptablePlainText = acceptabePlainTextMediaType(); if (acceptablePlainText != null) { return builder.type(acceptablePlainText).entity(location.toString()).build(); } return notAcceptable(mediaTypes(TEXT_PLAIN_TYPE).build()).build(); } else if (prefer.getReturn().getValue().equals("minimal")) { return builder.build(); } else { if (prefer != null) { prefer.getReturn().addResponseHeaders(servletResponse); } final RdfNamespacedStream rdfStream = new RdfNamespacedStream( new DefaultRdfStream(asNode(resource), getResourceTriples(resource)), namespaceRegistry.getNamespaces()); return builder.entity(rdfStream).build(); } }
[ "@", "SuppressWarnings", "(", "\"resource\"", ")", "protected", "Response", "createUpdateResponse", "(", "final", "FedoraResource", "resource", ",", "final", "boolean", "created", ")", "{", "addCacheControlHeaders", "(", "servletResponse", ",", "resource", ",", "sessi...
Create the appropriate response after a create or update request is processed. When a resource is created, examine the Prefer and Accept headers to determine whether to include a representation. By default, the URI for the created resource is return as plain text. If a minimal response is requested, then no body is returned. If a non-minimal return is requested, return the RDF for the created resource in the appropriate RDF serialization. @param resource The created or updated Fedora resource. @param created True for a newly-created resource, false for an updated resource. @return 204 No Content (for updated resources), 201 Created (for created resources) including the resource URI or content depending on Prefer headers.
[ "Create", "the", "appropriate", "response", "after", "a", "create", "or", "update", "request", "is", "processed", ".", "When", "a", "resource", "is", "created", "examine", "the", "Prefer", "and", "Accept", "headers", "to", "determine", "whether", "to", "includ...
train
https://github.com/fcrepo4/fcrepo4/blob/7489ad5bc8fb44e2442c93eceb7d97ac54553ab6/fcrepo-http-api/src/main/java/org/fcrepo/http/api/ContentExposingResource.java#L882-L914
Stratio/bdt
src/main/java/com/stratio/qa/specs/CommandExecutionSpec.java
CommandExecutionSpec.executeLocalCommand
@Given("^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$") public void executeLocalCommand(String command, String foo, Integer exitStatus, String bar, String envVar) throws Exception { if (exitStatus == null) { exitStatus = 0; } commonspec.runLocalCommand(command); commonspec.runCommandLoggerAndEnvVar(exitStatus, envVar, Boolean.TRUE); Assertions.assertThat(commonspec.getCommandExitStatus()).isEqualTo(exitStatus); }
java
@Given("^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$") public void executeLocalCommand(String command, String foo, Integer exitStatus, String bar, String envVar) throws Exception { if (exitStatus == null) { exitStatus = 0; } commonspec.runLocalCommand(command); commonspec.runCommandLoggerAndEnvVar(exitStatus, envVar, Boolean.TRUE); Assertions.assertThat(commonspec.getCommandExitStatus()).isEqualTo(exitStatus); }
[ "@", "Given", "(", "\"^I run '(.+?)' locally( with exit status '(.+?)')?( and save the value in environment variable '(.+?)')?$\"", ")", "public", "void", "executeLocalCommand", "(", "String", "command", ",", "String", "foo", ",", "Integer", "exitStatus", ",", "String", "bar", ...
Executes the command specified in local system @param command command to be run locally @param foo regex needed to match method @param exitStatus command exit status @param bar regex needed to match method @param envVar environment variable name @throws Exception exception
[ "Executes", "the", "command", "specified", "in", "local", "system" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommandExecutionSpec.java#L107-L117
jglobus/JGlobus
ssl-proxies/src/main/java/org/globus/common/CoGProperties.java
CoGProperties.getTcpPortRange
public String getTcpPortRange() { String value = null; value = System.getProperty("GLOBUS_TCP_PORT_RANGE"); if (value != null) { return value; } value = System.getProperty("org.globus.tcp.port.range"); if (value != null) { return value; } return getProperty("tcp.port.range", null); }
java
public String getTcpPortRange() { String value = null; value = System.getProperty("GLOBUS_TCP_PORT_RANGE"); if (value != null) { return value; } value = System.getProperty("org.globus.tcp.port.range"); if (value != null) { return value; } return getProperty("tcp.port.range", null); }
[ "public", "String", "getTcpPortRange", "(", ")", "{", "String", "value", "=", "null", ";", "value", "=", "System", ".", "getProperty", "(", "\"GLOBUS_TCP_PORT_RANGE\"", ")", ";", "if", "(", "value", "!=", "null", ")", "{", "return", "value", ";", "}", "v...
Returns the tcp port range. It first checks the 'GLOBUS_TCP_PORT_RANGE' system property. If that system property is not set then 'org.globus.tcp.port.range' system property is checked. If that system property is not set then it returns the value specified in the configuration file. Returns null if the port range is not defined.<BR> The port range is in the following form: &lt;minport&gt;, &lt;maxport&gt; @return <code>String</code> the port range.
[ "Returns", "the", "tcp", "port", "range", ".", "It", "first", "checks", "the", "GLOBUS_TCP_PORT_RANGE", "system", "property", ".", "If", "that", "system", "property", "is", "not", "set", "then", "org", ".", "globus", ".", "tcp", ".", "port", ".", "range", ...
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/ssl-proxies/src/main/java/org/globus/common/CoGProperties.java#L408-L419
banq/jdonframework
src/main/java/com/jdon/util/UtilDateTime.java
UtilDateTime.toDate
public static java.util.Date toDate(int month, int day, int year, int hour, int minute, int second) { Calendar calendar = Calendar.getInstance(); try { calendar.set(year, month - 1, day, hour, minute, second); } catch (Exception e) { return null; } return new java.util.Date(calendar.getTime().getTime()); }
java
public static java.util.Date toDate(int month, int day, int year, int hour, int minute, int second) { Calendar calendar = Calendar.getInstance(); try { calendar.set(year, month - 1, day, hour, minute, second); } catch (Exception e) { return null; } return new java.util.Date(calendar.getTime().getTime()); }
[ "public", "static", "java", ".", "util", ".", "Date", "toDate", "(", "int", "month", ",", "int", "day", ",", "int", "year", ",", "int", "hour", ",", "int", "minute", ",", "int", "second", ")", "{", "Calendar", "calendar", "=", "Calendar", ".", "getIn...
Makes a Date from separate ints for month, day, year, hour, minute, and second. @param month The month int @param day The day int @param year The year int @param hour The hour int @param minute The minute int @param second The second int @return A Date made from separate ints for month, day, year, hour, minute, and second.
[ "Makes", "a", "Date", "from", "separate", "ints", "for", "month", "day", "year", "hour", "minute", "and", "second", "." ]
train
https://github.com/banq/jdonframework/blob/72b451caac04f775e57f52aaed3d8775044ead53/src/main/java/com/jdon/util/UtilDateTime.java#L410-L419
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/EnforceTrifocalGeometry.java
EnforceTrifocalGeometry.process
public void process( Point3D_F64 e2 , Point3D_F64 e3 , DMatrixRMaj A ) { // construct the linear system that the solution which solves the unknown square // matrices in the camera matrices constructE(e2, e3); // Computes U, which is used to map the 18 unknowns onto the 27 trifocal unknowns svdU.decompose(E); svdU.getU(U, false); // Copy the parts of U which correspond to the non singular parts if the SVD // since there are only really 18-nullity unknowns due to linear dependencies SingularOps_DDRM.descendingOrder(U,false,svdU.getSingularValues(),svdU.numberOfSingularValues(),null,false); int rank = SingularOps_DDRM.rank(svdU, 1e-13); Up.reshape(U.numRows,rank); CommonOps_DDRM.extract(U,0,U.numRows,0,Up.numCols,Up,0,0); // project the linear constraint matrix into this subspace AU.reshape(A.numRows,Up.numCols); CommonOps_DDRM.mult(A,Up,AU); // Extract the solution of ||A*U*x|| = 0 from the null space svdV.decompose(AU); xp.reshape(rank,1); SingularOps_DDRM.nullVector(svdV,true,xp); // Translate the solution from the subspace and into a valid trifocal tensor CommonOps_DDRM.mult(Up,xp,vectorT); // the sign of vectorT is arbitrary, but make it positive for consistency if( vectorT.data[0] > 0 ) CommonOps_DDRM.changeSign(vectorT); }
java
public void process( Point3D_F64 e2 , Point3D_F64 e3 , DMatrixRMaj A ) { // construct the linear system that the solution which solves the unknown square // matrices in the camera matrices constructE(e2, e3); // Computes U, which is used to map the 18 unknowns onto the 27 trifocal unknowns svdU.decompose(E); svdU.getU(U, false); // Copy the parts of U which correspond to the non singular parts if the SVD // since there are only really 18-nullity unknowns due to linear dependencies SingularOps_DDRM.descendingOrder(U,false,svdU.getSingularValues(),svdU.numberOfSingularValues(),null,false); int rank = SingularOps_DDRM.rank(svdU, 1e-13); Up.reshape(U.numRows,rank); CommonOps_DDRM.extract(U,0,U.numRows,0,Up.numCols,Up,0,0); // project the linear constraint matrix into this subspace AU.reshape(A.numRows,Up.numCols); CommonOps_DDRM.mult(A,Up,AU); // Extract the solution of ||A*U*x|| = 0 from the null space svdV.decompose(AU); xp.reshape(rank,1); SingularOps_DDRM.nullVector(svdV,true,xp); // Translate the solution from the subspace and into a valid trifocal tensor CommonOps_DDRM.mult(Up,xp,vectorT); // the sign of vectorT is arbitrary, but make it positive for consistency if( vectorT.data[0] > 0 ) CommonOps_DDRM.changeSign(vectorT); }
[ "public", "void", "process", "(", "Point3D_F64", "e2", ",", "Point3D_F64", "e3", ",", "DMatrixRMaj", "A", ")", "{", "// construct the linear system that the solution which solves the unknown square", "// matrices in the camera matrices", "constructE", "(", "e2", ",", "e3", ...
Computes a trifocal tensor which minimizes the algebraic error given the two epipoles and the linear constraint matrix. The epipoles are from a previously computed trifocal tensor. @param e2 Epipole of first image in the second image @param e3 Epipole of first image in the third image @param A Linear constraint matrix for trifocal tensor created from image observations.
[ "Computes", "a", "trifocal", "tensor", "which", "minimizes", "the", "algebraic", "error", "given", "the", "two", "epipoles", "and", "the", "linear", "constraint", "matrix", ".", "The", "epipoles", "are", "from", "a", "previously", "computed", "trifocal", "tensor...
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/trifocal/EnforceTrifocalGeometry.java#L85-L117
pizza/MaterialTabs
sample/src/io/karim/materialtabs/sample/TabsActivity.java
TabsActivity.getDrawable
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static Drawable getDrawable(Context context, @DrawableRes int drawableResId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return context.getDrawable(drawableResId); } else { return context.getResources().getDrawable(drawableResId); } }
java
@TargetApi(Build.VERSION_CODES.LOLLIPOP) private static Drawable getDrawable(Context context, @DrawableRes int drawableResId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return context.getDrawable(drawableResId); } else { return context.getResources().getDrawable(drawableResId); } }
[ "@", "TargetApi", "(", "Build", ".", "VERSION_CODES", ".", "LOLLIPOP", ")", "private", "static", "Drawable", "getDrawable", "(", "Context", "context", ",", "@", "DrawableRes", "int", "drawableResId", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_IN...
Convenience to use the new getDrawable(...) on Lollipop and the deprecated one on preLollipop.
[ "Convenience", "to", "use", "the", "new", "getDrawable", "(", "...", ")", "on", "Lollipop", "and", "the", "deprecated", "one", "on", "preLollipop", "." ]
train
https://github.com/pizza/MaterialTabs/blob/24c9bf922f29f0fbb201fb6b8f13d915fd87d322/sample/src/io/karim/materialtabs/sample/TabsActivity.java#L322-L329
unbescape/unbescape
src/main/java/org/unbescape/csv/CsvEscape.java
CsvEscape.escapeCsv
public static void escapeCsv(final char[] text, final int offset, final int len, final Writer writer) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } final int textLen = (text == null? 0 : text.length); if (offset < 0 || offset > textLen) { throw new IllegalArgumentException( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen); } if (len < 0 || (offset + len) > textLen) { throw new IllegalArgumentException( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen); } CsvEscapeUtil.escape(text, offset, len, writer); }
java
public static void escapeCsv(final char[] text, final int offset, final int len, final Writer writer) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } final int textLen = (text == null? 0 : text.length); if (offset < 0 || offset > textLen) { throw new IllegalArgumentException( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen); } if (len < 0 || (offset + len) > textLen) { throw new IllegalArgumentException( "Invalid (offset, len). offset=" + offset + ", len=" + len + ", text.length=" + textLen); } CsvEscapeUtil.escape(text, offset, len, writer); }
[ "public", "static", "void", "escapeCsv", "(", "final", "char", "[", "]", "text", ",", "final", "int", "offset", ",", "final", "int", "len", ",", "final", "Writer", "writer", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ")", "{"...
<p> Perform a CSV <strong>escape</strong> operation on a <tt>char[]</tt> input. </p> <p> This method is <strong>thread-safe</strong>. </p> @param text the <tt>char[]</tt> to be escaped. @param offset the position in <tt>text</tt> at which the escape operation should start. @param len the number of characters in <tt>text</tt> that should be escaped. @param writer the <tt>java.io.Writer</tt> to which the escaped result will be written. Nothing will be written at all to this writer if input is <tt>null</tt>. @throws IOException if an input/output exception occurs
[ "<p", ">", "Perform", "a", "CSV", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "char", "[]", "<", "/", "tt", ">", "input", ".", "<", "/", "p", ">", "<p", ">", "This", "method", "is", "<strong", ">", "thread",...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/csv/CsvEscape.java#L210-L231
pravega/pravega
client/src/main/java/io/pravega/client/stream/impl/ModelHelper.java
ModelHelper.decode
public static Controller.StreamCut decode(final String scope, final String stream, Map<Long, Long> streamCut) { return Controller.StreamCut.newBuilder().setStreamInfo(createStreamInfo(scope, stream)).putAllCut(streamCut).build(); }
java
public static Controller.StreamCut decode(final String scope, final String stream, Map<Long, Long> streamCut) { return Controller.StreamCut.newBuilder().setStreamInfo(createStreamInfo(scope, stream)).putAllCut(streamCut).build(); }
[ "public", "static", "Controller", ".", "StreamCut", "decode", "(", "final", "String", "scope", ",", "final", "String", "stream", ",", "Map", "<", "Long", ",", "Long", ">", "streamCut", ")", "{", "return", "Controller", ".", "StreamCut", ".", "newBuilder", ...
Creates a stream cut object. @param scope scope @param stream stream @param streamCut map of segment to position @return stream cut
[ "Creates", "a", "stream", "cut", "object", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/ModelHelper.java#L321-L323
rythmengine/rythmengine
src/main/java/org/rythmengine/exception/CompileException.java
CompileException.compilerException
public static CompilerException compilerException(String className, int line, String message) { CompilerException e = new CompilerException(); e.javaLineNumber = line; e.message = ExpressionParser.reversePositionPlaceHolder(message); e.className = className; return e; }
java
public static CompilerException compilerException(String className, int line, String message) { CompilerException e = new CompilerException(); e.javaLineNumber = line; e.message = ExpressionParser.reversePositionPlaceHolder(message); e.className = className; return e; }
[ "public", "static", "CompilerException", "compilerException", "(", "String", "className", ",", "int", "line", ",", "String", "message", ")", "{", "CompilerException", "e", "=", "new", "CompilerException", "(", ")", ";", "e", ".", "javaLineNumber", "=", "line", ...
create a compiler exception for the given className, line number and message @param className @param line @param message @return the CompilerException
[ "create", "a", "compiler", "exception", "for", "the", "given", "className", "line", "number", "and", "message" ]
train
https://github.com/rythmengine/rythmengine/blob/064b565f08d9da07378bf77a9dd856ea5831cc92/src/main/java/org/rythmengine/exception/CompileException.java#L43-L49
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RunnersApi.java
RunnersApi.enableRunner
public Runner enableRunner(Object projectIdOrPath, Integer runnerId) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm().withParam("runner_id", runnerId, true); Response response = post(Response.Status.CREATED, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "runners"); return (response.readEntity(Runner.class)); }
java
public Runner enableRunner(Object projectIdOrPath, Integer runnerId) throws GitLabApiException { GitLabApiForm formData = new GitLabApiForm().withParam("runner_id", runnerId, true); Response response = post(Response.Status.CREATED, formData.asMap(), "projects", getProjectIdOrPath(projectIdOrPath), "runners"); return (response.readEntity(Runner.class)); }
[ "public", "Runner", "enableRunner", "(", "Object", "projectIdOrPath", ",", "Integer", "runnerId", ")", "throws", "GitLabApiException", "{", "GitLabApiForm", "formData", "=", "new", "GitLabApiForm", "(", ")", ".", "withParam", "(", "\"runner_id\"", ",", "runnerId", ...
Enable an available specific runner in the project. <pre><code>GitLab Endpoint: POST /projects/:id/runners</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param runnerId The ID of a runner @return Runner instance of the Runner enabled @throws GitLabApiException if any exception occurs
[ "Enable", "an", "available", "specific", "runner", "in", "the", "project", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RunnersApi.java#L459-L464
GenesysPureEngage/provisioning-client-java
src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java
OperationsApi.getUsedSkillsAsyncWithHttpInfo
public ApiResponse<ApiAsyncSuccessResponse> getUsedSkillsAsyncWithHttpInfo(String aioId) throws ApiException { com.squareup.okhttp.Call call = getUsedSkillsAsyncValidateBeforeCall(aioId, null, null); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
java
public ApiResponse<ApiAsyncSuccessResponse> getUsedSkillsAsyncWithHttpInfo(String aioId) throws ApiException { com.squareup.okhttp.Call call = getUsedSkillsAsyncValidateBeforeCall(aioId, null, null); Type localVarReturnType = new TypeToken<ApiAsyncSuccessResponse>(){}.getType(); return apiClient.execute(call, localVarReturnType); }
[ "public", "ApiResponse", "<", "ApiAsyncSuccessResponse", ">", "getUsedSkillsAsyncWithHttpInfo", "(", "String", "aioId", ")", "throws", "ApiException", "{", "com", ".", "squareup", ".", "okhttp", ".", "Call", "call", "=", "getUsedSkillsAsyncValidateBeforeCall", "(", "a...
Get used skills. Get all [CfgSkill](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgSkill) that are linked to existing [CfgPerson](https://docs.genesys.com/Documentation/PSDK/latest/ConfigLayerRef/CfgPerson) objects. @param aioId A unique ID generated on the client (browser) when sending an API request that returns an asynchronous response. (required) @return ApiResponse&lt;ApiAsyncSuccessResponse&gt; @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
[ "Get", "used", "skills", ".", "Get", "all", "[", "CfgSkill", "]", "(", "https", ":", "//", "docs", ".", "genesys", ".", "com", "/", "Documentation", "/", "PSDK", "/", "latest", "/", "ConfigLayerRef", "/", "CfgSkill", ")", "that", "are", "linked", "to",...
train
https://github.com/GenesysPureEngage/provisioning-client-java/blob/1ad594c3767cec83052168e350994f922a26f75e/src/main/java/com/genesys/internal/provisioning/api/OperationsApi.java#L499-L503
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java
ResourceGroovyMethods.eachFileMatch
public static void eachFileMatch(final File self, final FileType fileType, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final File[] files = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (files == null) return; BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); for (final File currentFile : files) { if (fileType == FileType.ANY || (fileType != FileType.FILES && currentFile.isDirectory()) || (fileType != FileType.DIRECTORIES && currentFile.isFile())) { if (bmi.invoke(nameFilter, currentFile.getName())) closure.call(currentFile); } } }
java
public static void eachFileMatch(final File self, final FileType fileType, final Object nameFilter, @ClosureParams(value = SimpleType.class, options = "java.io.File") final Closure closure) throws FileNotFoundException, IllegalArgumentException { checkDir(self); final File[] files = self.listFiles(); // null check because of http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4803836 if (files == null) return; BooleanReturningMethodInvoker bmi = new BooleanReturningMethodInvoker("isCase"); for (final File currentFile : files) { if (fileType == FileType.ANY || (fileType != FileType.FILES && currentFile.isDirectory()) || (fileType != FileType.DIRECTORIES && currentFile.isFile())) { if (bmi.invoke(nameFilter, currentFile.getName())) closure.call(currentFile); } } }
[ "public", "static", "void", "eachFileMatch", "(", "final", "File", "self", ",", "final", "FileType", "fileType", ",", "final", "Object", "nameFilter", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.Fil...
Invokes the closure for each file whose name (file.name) matches the given nameFilter in the given directory - calling the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method to determine if a match occurs. This method can be used with different kinds of filters like regular expressions, classes, ranges etc. Both regular files and subdirectories may be candidates for matching depending on the value of fileType. <pre> // collect names of files in baseDir matching supplied regex pattern import static groovy.io.FileType.* def names = [] baseDir.eachFileMatch FILES, ~/foo\d\.txt/, { names {@code <<} it.name } assert names == ['foo1.txt', 'foo2.txt'] // remove all *.bak files in baseDir baseDir.eachFileMatch FILES, ~/.*\.bak/, { File bak {@code ->} bak.delete() } // print out files &gt; 4K in size from baseDir baseDir.eachFileMatch FILES, { new File(baseDir, it).size() {@code >} 4096 }, { println "$it.name ${it.size()}" } </pre> @param self a File (that happens to be a folder/directory) @param fileType whether normal files or directories or both should be processed @param nameFilter the filter to perform on the name of the file/directory (using the {@link DefaultGroovyMethods#isCase(java.lang.Object, java.lang.Object)} method) @param closure the closure to invoke @throws FileNotFoundException if the given directory does not exist @throws IllegalArgumentException if the provided File object does not represent a directory @since 1.7.1
[ "Invokes", "the", "closure", "for", "each", "file", "whose", "name", "(", "file", ".", "name", ")", "matches", "the", "given", "nameFilter", "in", "the", "given", "directory", "-", "calling", "the", "{", "@link", "DefaultGroovyMethods#isCase", "(", "java", "...
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L1532-L1547
linkedin/linkedin-zookeeper
org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/ZKClient.java
ZKClient.waitForState
public void waitForState(State state, Timespan timeout) throws TimeoutException, InterruptedException { long endTime = timeout == null ? 0 : timeout.futureTimeMillis(_clock); synchronized(_lock) { while(_state != state) { ConcurrentUtils.awaitUntil(_clock, _lock, endTime); } } }
java
public void waitForState(State state, Timespan timeout) throws TimeoutException, InterruptedException { long endTime = timeout == null ? 0 : timeout.futureTimeMillis(_clock); synchronized(_lock) { while(_state != state) { ConcurrentUtils.awaitUntil(_clock, _lock, endTime); } } }
[ "public", "void", "waitForState", "(", "State", "state", ",", "Timespan", "timeout", ")", "throws", "TimeoutException", ",", "InterruptedException", "{", "long", "endTime", "=", "timeout", "==", "null", "?", "0", ":", "timeout", ".", "futureTimeMillis", "(", "...
Wait (no longer than timeout if provided) for the client to be started
[ "Wait", "(", "no", "longer", "than", "timeout", "if", "provided", ")", "for", "the", "client", "to", "be", "started" ]
train
https://github.com/linkedin/linkedin-zookeeper/blob/600b1d01318594ed425ede566bbbdc94b026a53e/org.linkedin.zookeeper-impl/src/main/java/org/linkedin/zookeeper/client/ZKClient.java#L525-L537
khuxtable/seaglass
src/main/java/com/seaglasslookandfeel/painter/TitlePaneIconifyButtonPainter.java
TitlePaneIconifyButtonPainter.paintBackgroundEnabled
private void paintBackgroundEnabled(Graphics2D g, JComponent c, int width, int height) { paintBackground(g, c, width, height, enabled); }
java
private void paintBackgroundEnabled(Graphics2D g, JComponent c, int width, int height) { paintBackground(g, c, width, height, enabled); }
[ "private", "void", "paintBackgroundEnabled", "(", "Graphics2D", "g", ",", "JComponent", "c", ",", "int", "width", ",", "int", "height", ")", "{", "paintBackground", "(", "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/TitlePaneIconifyButtonPainter.java#L135-L137
yavijava/yavijava
src/main/java/com/vmware/vim25/mo/InventoryNavigator.java
InventoryNavigator.searchManagedEntities
public ManagedEntity[] searchManagedEntities(String type) throws InvalidProperty, RuntimeFault, RemoteException { String[][] typeinfo = new String[][]{new String[]{type, "name",},}; return searchManagedEntities(typeinfo, true); }
java
public ManagedEntity[] searchManagedEntities(String type) throws InvalidProperty, RuntimeFault, RemoteException { String[][] typeinfo = new String[][]{new String[]{type, "name",},}; return searchManagedEntities(typeinfo, true); }
[ "public", "ManagedEntity", "[", "]", "searchManagedEntities", "(", "String", "type", ")", "throws", "InvalidProperty", ",", "RuntimeFault", ",", "RemoteException", "{", "String", "[", "]", "[", "]", "typeinfo", "=", "new", "String", "[", "]", "[", "]", "{", ...
Get the first ManagedObjectReference from current node for the specified type
[ "Get", "the", "first", "ManagedObjectReference", "from", "current", "node", "for", "the", "specified", "type" ]
train
https://github.com/yavijava/yavijava/blob/27fd2c5826115782d5eeb934f86e3e39240179cd/src/main/java/com/vmware/vim25/mo/InventoryNavigator.java#L36-L39
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java
TransformerImpl.pushPairCurrentMatched
public void pushPairCurrentMatched(ElemTemplateElement template, int child) { m_currentMatchTemplates.push(template); m_currentMatchedNodes.push(child); }
java
public void pushPairCurrentMatched(ElemTemplateElement template, int child) { m_currentMatchTemplates.push(template); m_currentMatchedNodes.push(child); }
[ "public", "void", "pushPairCurrentMatched", "(", "ElemTemplateElement", "template", ",", "int", "child", ")", "{", "m_currentMatchTemplates", ".", "push", "(", "template", ")", ";", "m_currentMatchedNodes", ".", "push", "(", "child", ")", ";", "}" ]
Push both the current xsl:template or xsl:for-each onto the stack, along with the child node that was matched. (Note: should this only be used for xsl:templates?? -sb) @param template xsl:template or xsl:for-each. @param child The child that was matched.
[ "Push", "both", "the", "current", "xsl", ":", "template", "or", "xsl", ":", "for", "-", "each", "onto", "the", "stack", "along", "with", "the", "child", "node", "that", "was", "matched", ".", "(", "Note", ":", "should", "this", "only", "be", "used", ...
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/transformer/TransformerImpl.java#L2501-L2505
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/inject/writer/AbstractClassFileWriter.java
AbstractClassFileWriter.pushNewInstance
protected void pushNewInstance(GeneratorAdapter generatorAdapter, Type typeToInstantiate) { generatorAdapter.newInstance(typeToInstantiate); generatorAdapter.dup(); generatorAdapter.invokeConstructor(typeToInstantiate, METHOD_DEFAULT_CONSTRUCTOR); }
java
protected void pushNewInstance(GeneratorAdapter generatorAdapter, Type typeToInstantiate) { generatorAdapter.newInstance(typeToInstantiate); generatorAdapter.dup(); generatorAdapter.invokeConstructor(typeToInstantiate, METHOD_DEFAULT_CONSTRUCTOR); }
[ "protected", "void", "pushNewInstance", "(", "GeneratorAdapter", "generatorAdapter", ",", "Type", "typeToInstantiate", ")", "{", "generatorAdapter", ".", "newInstance", "(", "typeToInstantiate", ")", ";", "generatorAdapter", ".", "dup", "(", ")", ";", "generatorAdapte...
Push the instantiation of the given type. @param generatorAdapter The generator adaptor @param typeToInstantiate The type to instantiate.
[ "Push", "the", "instantiation", "of", "the", "given", "type", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/inject/writer/AbstractClassFileWriter.java#L1108-L1112
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.getMergeRequestByIid
public GitlabMergeRequest getMergeRequestByIid(Serializable projectId, Integer mergeRequestIid) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestIid; return retrieve().to(tailUrl, GitlabMergeRequest.class); }
java
public GitlabMergeRequest getMergeRequestByIid(Serializable projectId, Integer mergeRequestIid) throws IOException { String tailUrl = GitlabProject.URL + "/" + sanitizeProjectId(projectId) + GitlabMergeRequest.URL + "/" + mergeRequestIid; return retrieve().to(tailUrl, GitlabMergeRequest.class); }
[ "public", "GitlabMergeRequest", "getMergeRequestByIid", "(", "Serializable", "projectId", ",", "Integer", "mergeRequestIid", ")", "throws", "IOException", "{", "String", "tailUrl", "=", "GitlabProject", ".", "URL", "+", "\"/\"", "+", "sanitizeProjectId", "(", "project...
Return Merge Request. @param projectId The id of the project @param mergeRequestIid The internal id of the merge request @return the Gitlab Merge Request @throws IOException on gitlab api call error
[ "Return", "Merge", "Request", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L1557-L1560
google/j2objc
jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java
Locale.formatList
private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) { // If we have no list patterns, compose the list in a simple, // non-localized way. if (listPattern == null || listCompositionPattern == null) { StringBuffer result = new StringBuffer(); for (int i=0; i<stringList.length; ++i) { if (i>0) result.append(','); result.append(stringList[i]); } return result.toString(); } // Compose the list down to three elements if necessary if (stringList.length > 3) { MessageFormat format = new MessageFormat(listCompositionPattern); stringList = composeList(format, stringList); } // Rebuild the argument list with the list length as the first element Object[] args = new Object[stringList.length + 1]; System.arraycopy(stringList, 0, args, 1, stringList.length); args[0] = new Integer(stringList.length); // Format it using the pattern in the resource MessageFormat format = new MessageFormat(listPattern); return format.format(args); }
java
private static String formatList(String[] stringList, String listPattern, String listCompositionPattern) { // If we have no list patterns, compose the list in a simple, // non-localized way. if (listPattern == null || listCompositionPattern == null) { StringBuffer result = new StringBuffer(); for (int i=0; i<stringList.length; ++i) { if (i>0) result.append(','); result.append(stringList[i]); } return result.toString(); } // Compose the list down to three elements if necessary if (stringList.length > 3) { MessageFormat format = new MessageFormat(listCompositionPattern); stringList = composeList(format, stringList); } // Rebuild the argument list with the list length as the first element Object[] args = new Object[stringList.length + 1]; System.arraycopy(stringList, 0, args, 1, stringList.length); args[0] = new Integer(stringList.length); // Format it using the pattern in the resource MessageFormat format = new MessageFormat(listPattern); return format.format(args); }
[ "private", "static", "String", "formatList", "(", "String", "[", "]", "stringList", ",", "String", "listPattern", ",", "String", "listCompositionPattern", ")", "{", "// If we have no list patterns, compose the list in a simple,", "// non-localized way.", "if", "(", "listPat...
Format a list using given pattern strings. If either of the patterns is null, then a the list is formatted by concatenation with the delimiter ','. @param stringList the list of strings to be formatted. @param listPattern should create a MessageFormat taking 0-3 arguments and formatting them into a list. @param listCompositionPattern should take 2 arguments and is used by composeList. @return a string representing the list.
[ "Format", "a", "list", "using", "given", "pattern", "strings", ".", "If", "either", "of", "the", "patterns", "is", "null", "then", "a", "the", "list", "is", "formatted", "by", "concatenation", "with", "the", "delimiter", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/util/Locale.java#L2045-L2071
sagiegurari/fax4j
src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java
HylaFaxClientSpi.createFaxJobImpl
@Override protected FaxJob createFaxJobImpl() { //get client HylaFAXClient client=this.getHylaFAXClient(); FaxJob faxJob=null; try { //create job Job job=client.createJob(); faxJob=new HylaFaxJob(job); } catch(RuntimeException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } return faxJob; }
java
@Override protected FaxJob createFaxJobImpl() { //get client HylaFAXClient client=this.getHylaFAXClient(); FaxJob faxJob=null; try { //create job Job job=client.createJob(); faxJob=new HylaFaxJob(job); } catch(RuntimeException exception) { throw exception; } catch(Exception exception) { throw new FaxException("General error.",exception); } return faxJob; }
[ "@", "Override", "protected", "FaxJob", "createFaxJobImpl", "(", ")", "{", "//get client", "HylaFAXClient", "client", "=", "this", ".", "getHylaFAXClient", "(", ")", ";", "FaxJob", "faxJob", "=", "null", ";", "try", "{", "//create job", "Job", "job", "=", "c...
This function creates a new fax job instance to be used by the caller to submit a new fax job and so on. @return The fax job instance
[ "This", "function", "creates", "a", "new", "fax", "job", "instance", "to", "be", "used", "by", "the", "caller", "to", "submit", "a", "new", "fax", "job", "and", "so", "on", "." ]
train
https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/spi/hylafax/HylaFaxClientSpi.java#L272-L295
kirgor/enklib
sql/src/main/java/com/kirgor/enklib/sql/Session.java
Session.getSingleOrNull
public <T> T getSingleOrNull(String query, Class<T> entityClass, Object... params) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException { Cursor<T> cursor = getCursor(query, entityClass, params); return cursor.fetchSingleOrNull(); }
java
public <T> T getSingleOrNull(String query, Class<T> entityClass, Object... params) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException { Cursor<T> cursor = getCursor(query, entityClass, params); return cursor.fetchSingleOrNull(); }
[ "public", "<", "T", ">", "T", "getSingleOrNull", "(", "String", "query", ",", "Class", "<", "T", ">", "entityClass", ",", "Object", "...", "params", ")", "throws", "SQLException", ",", "NoSuchFieldException", ",", "InstantiationException", ",", "IllegalAccessExc...
Executes SQL query, which returns single entity or null if result is not there. @param <T> Entity type. @param query SQL query string. @param entityClass Entity class. @param params Parameters, which will be placed instead of '?' signs. @return Single result entity or null. @throws SQLException In general SQL error case. @throws NoSuchFieldException If result set has field which entity class doesn't. @throws InstantiationException If entity class hasn't default constructor. @throws IllegalAccessException If entity class is not accessible.
[ "Executes", "SQL", "query", "which", "returns", "single", "entity", "or", "null", "if", "result", "is", "not", "there", "." ]
train
https://github.com/kirgor/enklib/blob/8a24db296dc43db5d8fe509cf64ace0a0c7be8f2/sql/src/main/java/com/kirgor/enklib/sql/Session.java#L150-L154
cdk/cdk
base/core/src/main/java/org/openscience/cdk/graph/Cycles.java
Cycles.toRingSet
private static IRingSet toRingSet(IAtomContainer container, int[][] cycles, EdgeToBondMap bondMap) { // note currently no way to say the size of the RingSet // even through we know it IChemObjectBuilder builder = container.getBuilder(); IRingSet rings = builder.newInstance(IRingSet.class); for (int[] cycle : cycles) { rings.addAtomContainer(toRing(container, cycle, bondMap)); } return rings; }
java
private static IRingSet toRingSet(IAtomContainer container, int[][] cycles, EdgeToBondMap bondMap) { // note currently no way to say the size of the RingSet // even through we know it IChemObjectBuilder builder = container.getBuilder(); IRingSet rings = builder.newInstance(IRingSet.class); for (int[] cycle : cycles) { rings.addAtomContainer(toRing(container, cycle, bondMap)); } return rings; }
[ "private", "static", "IRingSet", "toRingSet", "(", "IAtomContainer", "container", ",", "int", "[", "]", "[", "]", "cycles", ",", "EdgeToBondMap", "bondMap", ")", "{", "// note currently no way to say the size of the RingSet", "// even through we know it", "IChemObjectBuilde...
Internal - convert a set of cycles to an ring set. @param container molecule @param cycles a cycle of the chemical graph @param bondMap mapping of the edges (int,int) to the bonds of the container @return the ring set
[ "Internal", "-", "convert", "a", "set", "of", "cycles", "to", "an", "ring", "set", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/base/core/src/main/java/org/openscience/cdk/graph/Cycles.java#L915-L927
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/apache/logging/log4j/CloseableThreadContext.java
CloseableThreadContext.put
public static CloseableThreadContext.Instance put(final String key, final String value) { return new CloseableThreadContext.Instance().put(key, value); }
java
public static CloseableThreadContext.Instance put(final String key, final String value) { return new CloseableThreadContext.Instance().put(key, value); }
[ "public", "static", "CloseableThreadContext", ".", "Instance", "put", "(", "final", "String", "key", ",", "final", "String", "value", ")", "{", "return", "new", "CloseableThreadContext", ".", "Instance", "(", ")", ".", "put", "(", "key", ",", "value", ")", ...
Populates the Thread Context Map with the supplied key/value pair. Any existing key in the {@link ThreadContext} will be replaced with the supplied value, and restored back to their original value when the instance is closed. @param key The key to be added @param value The value to be added @return a new instance that will back out the changes when closed.
[ "Populates", "the", "Thread", "Context", "Map", "with", "the", "supplied", "key", "/", "value", "pair", ".", "Any", "existing", "key", "in", "the", "{", "@link", "ThreadContext", "}", "will", "be", "replaced", "with", "the", "supplied", "value", "and", "re...
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/CloseableThreadContext.java#L74-L76
google/j2objc
jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java
MutableBigInteger.getLower
private BigInteger getLower(int n) { if (isZero()) { return BigInteger.ZERO; } else if (intLen < n) { return toBigInteger(1); } else { // strip zeros int len = n; while (len > 0 && value[offset+intLen-len] == 0) len--; int sign = len > 0 ? 1 : 0; return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign); } }
java
private BigInteger getLower(int n) { if (isZero()) { return BigInteger.ZERO; } else if (intLen < n) { return toBigInteger(1); } else { // strip zeros int len = n; while (len > 0 && value[offset+intLen-len] == 0) len--; int sign = len > 0 ? 1 : 0; return new BigInteger(Arrays.copyOfRange(value, offset+intLen-len, offset+intLen), sign); } }
[ "private", "BigInteger", "getLower", "(", "int", "n", ")", "{", "if", "(", "isZero", "(", ")", ")", "{", "return", "BigInteger", ".", "ZERO", ";", "}", "else", "if", "(", "intLen", "<", "n", ")", "{", "return", "toBigInteger", "(", "1", ")", ";", ...
Returns a {@code BigInteger} equal to the {@code n} low ints of this number.
[ "Returns", "a", "{" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/openjdk/src/share/classes/java/math/MutableBigInteger.java#L707-L720
JoanZapata/android-pdfview
android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java
DragPinchListener.isClick
private boolean isClick(MotionEvent upEvent, float xDown, float yDown, float xUp, float yUp) { if (upEvent == null) return false; long time = upEvent.getEventTime() - upEvent.getDownTime(); float distance = PointF.length( // xDown - xUp, // yDown - yUp); return time < MAX_CLICK_TIME && distance < MAX_CLICK_DISTANCE; }
java
private boolean isClick(MotionEvent upEvent, float xDown, float yDown, float xUp, float yUp) { if (upEvent == null) return false; long time = upEvent.getEventTime() - upEvent.getDownTime(); float distance = PointF.length( // xDown - xUp, // yDown - yUp); return time < MAX_CLICK_TIME && distance < MAX_CLICK_DISTANCE; }
[ "private", "boolean", "isClick", "(", "MotionEvent", "upEvent", ",", "float", "xDown", ",", "float", "yDown", ",", "float", "xUp", ",", "float", "yUp", ")", "{", "if", "(", "upEvent", "==", "null", ")", "return", "false", ";", "long", "time", "=", "upE...
Test if a MotionEvent with the given start and end offsets can be considered as a "click". @param upEvent The final finger-up event. @param xDown The x-offset of the down event. @param yDown The y-offset of the down event. @param xUp The x-offset of the up event. @param yUp The y-offset of the up event. @return true if it's a click, false otherwise
[ "Test", "if", "a", "MotionEvent", "with", "the", "given", "start", "and", "end", "offsets", "can", "be", "considered", "as", "a", "click", "." ]
train
https://github.com/JoanZapata/android-pdfview/blob/8f239bb91ab56ff3066739dc44bccf8b1753b0ba/android-pdfview/src/main/java/com/joanzapata/pdfview/util/DragPinchListener.java#L274-L281
Netflix/Hystrix
hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandExecutor.java
CommandExecutor.execute
public static Object execute(HystrixInvokable invokable, ExecutionType executionType, MetaHolder metaHolder) throws RuntimeException { Validate.notNull(invokable); Validate.notNull(metaHolder); switch (executionType) { case SYNCHRONOUS: { return castToExecutable(invokable, executionType).execute(); } case ASYNCHRONOUS: { HystrixExecutable executable = castToExecutable(invokable, executionType); if (metaHolder.hasFallbackMethodCommand() && ExecutionType.ASYNCHRONOUS == metaHolder.getFallbackExecutionType()) { return new FutureDecorator(executable.queue()); } return executable.queue(); } case OBSERVABLE: { HystrixObservable observable = castToObservable(invokable); return ObservableExecutionMode.EAGER == metaHolder.getObservableExecutionMode() ? observable.observe() : observable.toObservable(); } default: throw new RuntimeException("unsupported execution type: " + executionType); } }
java
public static Object execute(HystrixInvokable invokable, ExecutionType executionType, MetaHolder metaHolder) throws RuntimeException { Validate.notNull(invokable); Validate.notNull(metaHolder); switch (executionType) { case SYNCHRONOUS: { return castToExecutable(invokable, executionType).execute(); } case ASYNCHRONOUS: { HystrixExecutable executable = castToExecutable(invokable, executionType); if (metaHolder.hasFallbackMethodCommand() && ExecutionType.ASYNCHRONOUS == metaHolder.getFallbackExecutionType()) { return new FutureDecorator(executable.queue()); } return executable.queue(); } case OBSERVABLE: { HystrixObservable observable = castToObservable(invokable); return ObservableExecutionMode.EAGER == metaHolder.getObservableExecutionMode() ? observable.observe() : observable.toObservable(); } default: throw new RuntimeException("unsupported execution type: " + executionType); } }
[ "public", "static", "Object", "execute", "(", "HystrixInvokable", "invokable", ",", "ExecutionType", "executionType", ",", "MetaHolder", "metaHolder", ")", "throws", "RuntimeException", "{", "Validate", ".", "notNull", "(", "invokable", ")", ";", "Validate", ".", ...
Calls a method of {@link HystrixExecutable} in accordance with specified execution type. @param invokable {@link HystrixInvokable} @param metaHolder {@link MetaHolder} @return the result of invocation of specific method. @throws RuntimeException
[ "Calls", "a", "method", "of", "{", "@link", "HystrixExecutable", "}", "in", "accordance", "with", "specified", "execution", "type", "." ]
train
https://github.com/Netflix/Hystrix/blob/3cb21589895e9f8f87cfcdbc9d96d9f63d48b848/hystrix-contrib/hystrix-javanica/src/main/java/com/netflix/hystrix/contrib/javanica/command/CommandExecutor.java#L46-L69
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/jdbc/DataSourceService.java
DataSourceService.parseIsolationLevel
private static final void parseIsolationLevel(NavigableMap<String, Object> wProps, String vendorImplClassName) { // Convert isolationLevel constant name to integer Object isolationLevel = wProps.get(DataSourceDef.isolationLevel.name()); if (isolationLevel instanceof String) { isolationLevel = "TRANSACTION_READ_COMMITTED".equals(isolationLevel) ? Connection.TRANSACTION_READ_COMMITTED : "TRANSACTION_REPEATABLE_READ".equals(isolationLevel) ? Connection.TRANSACTION_REPEATABLE_READ : "TRANSACTION_SERIALIZABLE".equals(isolationLevel) ? Connection.TRANSACTION_SERIALIZABLE : "TRANSACTION_READ_UNCOMMITTED".equals(isolationLevel) ? Connection.TRANSACTION_READ_UNCOMMITTED : "TRANSACTION_NONE".equals(isolationLevel) ? Connection.TRANSACTION_NONE : "TRANSACTION_SNAPSHOT".equals(isolationLevel) ? (vendorImplClassName.startsWith("com.microsoft.") ? 4096 : 16) : isolationLevel; wProps.put(DataSourceDef.isolationLevel.name(), isolationLevel); } }
java
private static final void parseIsolationLevel(NavigableMap<String, Object> wProps, String vendorImplClassName) { // Convert isolationLevel constant name to integer Object isolationLevel = wProps.get(DataSourceDef.isolationLevel.name()); if (isolationLevel instanceof String) { isolationLevel = "TRANSACTION_READ_COMMITTED".equals(isolationLevel) ? Connection.TRANSACTION_READ_COMMITTED : "TRANSACTION_REPEATABLE_READ".equals(isolationLevel) ? Connection.TRANSACTION_REPEATABLE_READ : "TRANSACTION_SERIALIZABLE".equals(isolationLevel) ? Connection.TRANSACTION_SERIALIZABLE : "TRANSACTION_READ_UNCOMMITTED".equals(isolationLevel) ? Connection.TRANSACTION_READ_UNCOMMITTED : "TRANSACTION_NONE".equals(isolationLevel) ? Connection.TRANSACTION_NONE : "TRANSACTION_SNAPSHOT".equals(isolationLevel) ? (vendorImplClassName.startsWith("com.microsoft.") ? 4096 : 16) : isolationLevel; wProps.put(DataSourceDef.isolationLevel.name(), isolationLevel); } }
[ "private", "static", "final", "void", "parseIsolationLevel", "(", "NavigableMap", "<", "String", ",", "Object", ">", "wProps", ",", "String", "vendorImplClassName", ")", "{", "// Convert isolationLevel constant name to integer", "Object", "isolationLevel", "=", "wProps", ...
Utility method that converts transaction isolation level constant names to the corresponding int value. @param wProps WAS data source properties, including the configured isolationLevel property. @param vendorImplClassName name of the vendor data source or driver implementation class. @return Integer transaction isolation level constant value. If unknown, then the original String value.
[ "Utility", "method", "that", "converts", "transaction", "isolation", "level", "constant", "names", "to", "the", "corresponding", "int", "value", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/jdbc/DataSourceService.java#L871-L885
lucee/Lucee
core/src/main/java/lucee/runtime/reflection/Invoker.java
Invoker.setProperty
public static void setProperty(Object o, String prop, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException { getFieldIgnoreCase(o.getClass(), prop).set(o, value); }
java
public static void setProperty(Object o, String prop, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException { getFieldIgnoreCase(o.getClass(), prop).set(o, value); }
[ "public", "static", "void", "setProperty", "(", "Object", "o", ",", "String", "prop", ",", "Object", "value", ")", "throws", "IllegalArgumentException", ",", "IllegalAccessException", ",", "NoSuchFieldException", "{", "getFieldIgnoreCase", "(", "o", ".", "getClass",...
assign a value to a visible property of a object @param o Object to assign value to his property @param prop name of property @param value Value to assign @throws IllegalArgumentException @throws IllegalAccessException @throws NoSuchFieldException
[ "assign", "a", "value", "to", "a", "visible", "property", "of", "a", "object" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/reflection/Invoker.java#L376-L378
pgjdbc/pgjdbc
pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java
EscapedFunctions2.sqlyear
public static void sqlyear(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "extract(year from ", "year", parsedArgs); }
java
public static void sqlyear(StringBuilder buf, List<? extends CharSequence> parsedArgs) throws SQLException { singleArgumentFunctionCall(buf, "extract(year from ", "year", parsedArgs); }
[ "public", "static", "void", "sqlyear", "(", "StringBuilder", "buf", ",", "List", "<", "?", "extends", "CharSequence", ">", "parsedArgs", ")", "throws", "SQLException", "{", "singleArgumentFunctionCall", "(", "buf", ",", "\"extract(year from \"", ",", "\"year\"", "...
year translation @param buf The buffer to append into @param parsedArgs arguments @throws SQLException if something wrong happens
[ "year", "translation" ]
train
https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/EscapedFunctions2.java#L486-L488
alkacon/opencms-core
src/org/opencms/file/CmsObject.java
CmsObject.createResource
@Deprecated public CmsResource createResource(String resourcename, int type, byte[] content, List<CmsProperty> properties) throws CmsException, CmsIllegalArgumentException { return createResource(resourcename, getResourceType(type), content, properties); }
java
@Deprecated public CmsResource createResource(String resourcename, int type, byte[] content, List<CmsProperty> properties) throws CmsException, CmsIllegalArgumentException { return createResource(resourcename, getResourceType(type), content, properties); }
[ "@", "Deprecated", "public", "CmsResource", "createResource", "(", "String", "resourcename", ",", "int", "type", ",", "byte", "[", "]", "content", ",", "List", "<", "CmsProperty", ">", "properties", ")", "throws", "CmsException", ",", "CmsIllegalArgumentException"...
Creates a new resource of the given resource type with the provided content and properties.<p> @param resourcename the name of the resource to create (full current site relative path) @param type the type of the resource to create @param content the contents for the new resource @param properties the properties for the new resource @return the created resource @throws CmsException if something goes wrong @throws CmsIllegalArgumentException if the <code>resourcename</code> argument is null or of length 0 @deprecated Use {@link #createResource(String, I_CmsResourceType, byte[], List)} instead. Resource types should always be referenced either by its type class (preferred) or by type name. Use of int based resource type references will be discontinued in a future OpenCms release.
[ "Creates", "a", "new", "resource", "of", "the", "given", "resource", "type", "with", "the", "provided", "content", "and", "properties", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/file/CmsObject.java#L847-L852
Kickflip/kickflip-android-sdk
sdk/src/main/java/io/kickflip/sdk/av/EglCore.java
EglCore.getConfig
private EGLConfig getConfig(int flags, int version) { int renderableType = EGL14.EGL_OPENGL_ES2_BIT; if (version >= 3) { renderableType |= EGLExt.EGL_OPENGL_ES3_BIT_KHR; } // The actual surface is generally RGBA or RGBX, so situationally omitting alpha // doesn't really help. It can also lead to a huge performance hit on glReadPixels() // when reading into a GL_RGBA buffer. int[] attribList = { EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, //EGL14.EGL_DEPTH_SIZE, 16, //EGL14.EGL_STENCIL_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, renderableType, EGL14.EGL_NONE, 0, // placeholder for recordable [@-3] EGL14.EGL_NONE }; if ((flags & FLAG_RECORDABLE) != 0) { attribList[attribList.length - 3] = EGL_RECORDABLE_ANDROID; attribList[attribList.length - 2] = 1; } EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length, numConfigs, 0)) { Log.w(TAG, "unable to find RGB8888 / " + version + " EGLConfig"); return null; } return configs[0]; }
java
private EGLConfig getConfig(int flags, int version) { int renderableType = EGL14.EGL_OPENGL_ES2_BIT; if (version >= 3) { renderableType |= EGLExt.EGL_OPENGL_ES3_BIT_KHR; } // The actual surface is generally RGBA or RGBX, so situationally omitting alpha // doesn't really help. It can also lead to a huge performance hit on glReadPixels() // when reading into a GL_RGBA buffer. int[] attribList = { EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, EGL14.EGL_ALPHA_SIZE, 8, //EGL14.EGL_DEPTH_SIZE, 16, //EGL14.EGL_STENCIL_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, renderableType, EGL14.EGL_NONE, 0, // placeholder for recordable [@-3] EGL14.EGL_NONE }; if ((flags & FLAG_RECORDABLE) != 0) { attribList[attribList.length - 3] = EGL_RECORDABLE_ANDROID; attribList[attribList.length - 2] = 1; } EGLConfig[] configs = new EGLConfig[1]; int[] numConfigs = new int[1]; if (!EGL14.eglChooseConfig(mEGLDisplay, attribList, 0, configs, 0, configs.length, numConfigs, 0)) { Log.w(TAG, "unable to find RGB8888 / " + version + " EGLConfig"); return null; } return configs[0]; }
[ "private", "EGLConfig", "getConfig", "(", "int", "flags", ",", "int", "version", ")", "{", "int", "renderableType", "=", "EGL14", ".", "EGL_OPENGL_ES2_BIT", ";", "if", "(", "version", ">=", "3", ")", "{", "renderableType", "|=", "EGLExt", ".", "EGL_OPENGL_ES...
Finds a suitable EGLConfig. @param flags Bit flags from constructor. @param version Must be 2 or 3.
[ "Finds", "a", "suitable", "EGLConfig", "." ]
train
https://github.com/Kickflip/kickflip-android-sdk/blob/af3aae5f1128d7376e67aefe11a3a1a3844be734/sdk/src/main/java/io/kickflip/sdk/av/EglCore.java#L143-L175
astrapi69/jaulp-wicket
jaulp-wicket-dialogs/src/main/java/de/alpharogroup/wicket/dialogs/ajax/modal/BaseModalPanel.java
BaseModalPanel.newOkButton
protected AjaxButton newOkButton(final String id) { final AjaxButton ok = new AjaxButton(id) { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void onError(final AjaxRequestTarget target, final Form<?> form) { final T obj = BaseModalPanel.this.getModelObject(); onSelect(target, obj); } /** * {@inheritDoc} */ @Override protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) { final T obj = BaseModalPanel.this.getModelObject(); onSelect(target, obj); } }; return ok; }
java
protected AjaxButton newOkButton(final String id) { final AjaxButton ok = new AjaxButton(id) { /** * The serialVersionUID. */ private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override protected void onError(final AjaxRequestTarget target, final Form<?> form) { final T obj = BaseModalPanel.this.getModelObject(); onSelect(target, obj); } /** * {@inheritDoc} */ @Override protected void onSubmit(final AjaxRequestTarget target, final Form<?> form) { final T obj = BaseModalPanel.this.getModelObject(); onSelect(target, obj); } }; return ok; }
[ "protected", "AjaxButton", "newOkButton", "(", "final", "String", "id", ")", "{", "final", "AjaxButton", "ok", "=", "new", "AjaxButton", "(", "id", ")", "{", "/**\r\n\t\t\t * The serialVersionUID.\r\n\t\t\t */", "private", "static", "final", "long", "serialVersionUID"...
Factory method for creating the new ok {@link AjaxButton}. This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a new ok {@link AjaxButton}. @param id the id @return the new ok {@link AjaxButton}
[ "Factory", "method", "for", "creating", "the", "new", "ok", "{", "@link", "AjaxButton", "}", ".", "This", "method", "is", "invoked", "in", "the", "constructor", "from", "the", "derived", "classes", "and", "can", "be", "overridden", "so", "users", "can", "p...
train
https://github.com/astrapi69/jaulp-wicket/blob/85d74368d00abd9bb97659b5794e38c0f8a013d4/jaulp-wicket-dialogs/src/main/java/de/alpharogroup/wicket/dialogs/ajax/modal/BaseModalPanel.java#L141-L171
Bedework/bw-util
bw-util-xml/src/main/java/org/bedework/util/xml/XmlUtil.java
XmlUtil.getReqAttrVal
public static String getReqAttrVal(final Element el, final String name) throws SAXException { String str = getAttrVal(el, name); if ((str == null) || (str.length() == 0)) { throw new SAXException("Missing attribute value: " + name); } return str; }
java
public static String getReqAttrVal(final Element el, final String name) throws SAXException { String str = getAttrVal(el, name); if ((str == null) || (str.length() == 0)) { throw new SAXException("Missing attribute value: " + name); } return str; }
[ "public", "static", "String", "getReqAttrVal", "(", "final", "Element", "el", ",", "final", "String", "name", ")", "throws", "SAXException", "{", "String", "str", "=", "getAttrVal", "(", "el", ",", "name", ")", ";", "if", "(", "(", "str", "==", "null", ...
Return the required value of the named attribute of the given element. @param el Element @param name String name of desired attribute @return String attribute value @throws SAXException
[ "Return", "the", "required", "value", "of", "the", "named", "attribute", "of", "the", "given", "element", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-xml/src/main/java/org/bedework/util/xml/XmlUtil.java#L235-L244
landawn/AbacusUtil
src/com/landawn/abacus/util/HBaseColumn.java
HBaseColumn.asSortedMap
public static <T> SortedMap<Long, HBaseColumn<T>> asSortedMap(T value) { return asSortedMap(value, DESC_HBASE_VERSION_COMPARATOR); }
java
public static <T> SortedMap<Long, HBaseColumn<T>> asSortedMap(T value) { return asSortedMap(value, DESC_HBASE_VERSION_COMPARATOR); }
[ "public", "static", "<", "T", ">", "SortedMap", "<", "Long", ",", "HBaseColumn", "<", "T", ">", ">", "asSortedMap", "(", "T", "value", ")", "{", "return", "asSortedMap", "(", "value", ",", "DESC_HBASE_VERSION_COMPARATOR", ")", ";", "}" ]
Returns a sorted map descended by version @param value @return
[ "Returns", "a", "sorted", "map", "descended", "by", "version" ]
train
https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/HBaseColumn.java#L173-L175
apiman/apiman
common/net/src/main/java/io/apiman/common/net/hawkular/beans/MetricLongBean.java
MetricLongBean.addDataPoint
public DataPointLongBean addDataPoint(Date timestamp, long value) { DataPointLongBean point = new DataPointLongBean(timestamp, value); dataPoints.add(point); return point; }
java
public DataPointLongBean addDataPoint(Date timestamp, long value) { DataPointLongBean point = new DataPointLongBean(timestamp, value); dataPoints.add(point); return point; }
[ "public", "DataPointLongBean", "addDataPoint", "(", "Date", "timestamp", ",", "long", "value", ")", "{", "DataPointLongBean", "point", "=", "new", "DataPointLongBean", "(", "timestamp", ",", "value", ")", ";", "dataPoints", ".", "add", "(", "point", ")", ";", ...
Adds a single data point to the metric. @param timestamp @param value
[ "Adds", "a", "single", "data", "point", "to", "the", "metric", "." ]
train
https://github.com/apiman/apiman/blob/8c049c2a2f2e4a69bbb6125686a15edd26f29c21/common/net/src/main/java/io/apiman/common/net/hawkular/beans/MetricLongBean.java#L89-L93
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java
EmbeddedLeaderService.confirmLeader
private void confirmLeader(final EmbeddedLeaderElectionService service, final UUID leaderSessionId) { synchronized (lock) { // if the service was shut down in the meantime, ignore this confirmation if (!service.running || shutdown) { return; } try { // check if the confirmation is for the same grant, or whether it is a stale grant if (service == currentLeaderProposed && currentLeaderSessionId.equals(leaderSessionId)) { final String address = service.contender.getAddress(); LOG.info("Received confirmation of leadership for leader {} , session={}", address, leaderSessionId); // mark leadership currentLeaderConfirmed = service; currentLeaderAddress = address; currentLeaderProposed = null; // notify all listeners notifyAllListeners(address, leaderSessionId); } else { LOG.debug("Received confirmation of leadership for a stale leadership grant. Ignoring."); } } catch (Throwable t) { fatalError(t); } } }
java
private void confirmLeader(final EmbeddedLeaderElectionService service, final UUID leaderSessionId) { synchronized (lock) { // if the service was shut down in the meantime, ignore this confirmation if (!service.running || shutdown) { return; } try { // check if the confirmation is for the same grant, or whether it is a stale grant if (service == currentLeaderProposed && currentLeaderSessionId.equals(leaderSessionId)) { final String address = service.contender.getAddress(); LOG.info("Received confirmation of leadership for leader {} , session={}", address, leaderSessionId); // mark leadership currentLeaderConfirmed = service; currentLeaderAddress = address; currentLeaderProposed = null; // notify all listeners notifyAllListeners(address, leaderSessionId); } else { LOG.debug("Received confirmation of leadership for a stale leadership grant. Ignoring."); } } catch (Throwable t) { fatalError(t); } } }
[ "private", "void", "confirmLeader", "(", "final", "EmbeddedLeaderElectionService", "service", ",", "final", "UUID", "leaderSessionId", ")", "{", "synchronized", "(", "lock", ")", "{", "// if the service was shut down in the meantime, ignore this confirmation", "if", "(", "!...
Callback from leader contenders when they confirm a leader grant.
[ "Callback", "from", "leader", "contenders", "when", "they", "confirm", "a", "leader", "grant", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/highavailability/nonha/embedded/EmbeddedLeaderService.java#L239-L268
petergeneric/stdlib
stdlib/src/main/java/com/peterphi/std/net/IpHelper.java
IpHelper.getLocalIp
public static String getLocalIp() throws RuntimeException { try { InetAddress addr = getLocalIpAddress(); return addr.getHostAddress(); } catch (RuntimeException e) { throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to find the local machine", e); } }
java
public static String getLocalIp() throws RuntimeException { try { InetAddress addr = getLocalIpAddress(); return addr.getHostAddress(); } catch (RuntimeException e) { throw new RuntimeException("[FileHelper] {getLocalIp}: Unable to find the local machine", e); } }
[ "public", "static", "String", "getLocalIp", "(", ")", "throws", "RuntimeException", "{", "try", "{", "InetAddress", "addr", "=", "getLocalIpAddress", "(", ")", ";", "return", "addr", ".", "getHostAddress", "(", ")", ";", "}", "catch", "(", "RuntimeException", ...
Gets the local IP address @return String the local ip address's HostAddress @throws RuntimeException On error (eg. when the local host cannot be determined)
[ "Gets", "the", "local", "IP", "address" ]
train
https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/net/IpHelper.java#L89-L101
czyzby/gdx-lml
websocket/natives/gwt/src/main/java/com/github/czyzby/websocket/impl/GwtWebSocket.java
GwtWebSocket.onClose
protected void onClose(final int closeCode, final String reason) { postCloseEvent(WebSocketCloseCode.getByCodeOrElse(closeCode, WebSocketCloseCode.ABNORMAL), reason); }
java
protected void onClose(final int closeCode, final String reason) { postCloseEvent(WebSocketCloseCode.getByCodeOrElse(closeCode, WebSocketCloseCode.ABNORMAL), reason); }
[ "protected", "void", "onClose", "(", "final", "int", "closeCode", ",", "final", "String", "reason", ")", "{", "postCloseEvent", "(", "WebSocketCloseCode", ".", "getByCodeOrElse", "(", "closeCode", ",", "WebSocketCloseCode", ".", "ABNORMAL", ")", ",", "reason", "...
Invoked by native listener. @param closeCode see {@link WebSocketCloseCode}. @param reason optional closing reason.
[ "Invoked", "by", "native", "listener", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/websocket/natives/gwt/src/main/java/com/github/czyzby/websocket/impl/GwtWebSocket.java#L79-L81
chhh/MSFTBX
MSFileToolbox/src/main/java/umich/ms/datatypes/lcmsrun/LCMSRunInfo.java
LCMSRunInfo.addInstrument
public void addInstrument(Instrument instrument, String id) { if (instrument == null || id == null) { throw new IllegalArgumentException("Instruemnt and ID must be non-null values."); } if (instruments.size() == 0) { defaultInstrumentID = id; } else if (instruments.size() > 0 && !isDefaultExplicitlySet) { unsetDefaultInstrument(); } instruments.put(id, instrument); }
java
public void addInstrument(Instrument instrument, String id) { if (instrument == null || id == null) { throw new IllegalArgumentException("Instruemnt and ID must be non-null values."); } if (instruments.size() == 0) { defaultInstrumentID = id; } else if (instruments.size() > 0 && !isDefaultExplicitlySet) { unsetDefaultInstrument(); } instruments.put(id, instrument); }
[ "public", "void", "addInstrument", "(", "Instrument", "instrument", ",", "String", "id", ")", "{", "if", "(", "instrument", "==", "null", "||", "id", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Instruemnt and ID must be non-null val...
If only one instrument is added, it will be set as the default instrument, all the scans, that you add to the ScanCollection will implicitly refer to this one instrument. @param id some identifier for mapping instruments. Instrumnt list is normally stored at the beginning of the run file, so it's a mapping from this list, to instrument ID specified for each spectrumRef.
[ "If", "only", "one", "instrument", "is", "added", "it", "will", "be", "set", "as", "the", "default", "instrument", "all", "the", "scans", "that", "you", "add", "to", "the", "ScanCollection", "will", "implicitly", "refer", "to", "this", "one", "instrument", ...
train
https://github.com/chhh/MSFTBX/blob/e53ae6be982e2de3123292be7d5297715bec70bb/MSFileToolbox/src/main/java/umich/ms/datatypes/lcmsrun/LCMSRunInfo.java#L82-L93
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/json/JSONDeserializer.java
JSONDeserializer.fromString
public final IJSONSerializable<?> fromString(String string, final boolean validate) { if (null == (string = StringOps.toTrimOrNull(string))) { return null; } final JSONValue value = JSONParser.parseStrict(string); if (null == value) { return null; } final JSONObject json = value.isObject(); if (null == json) { return null; } try { final ValidationContext ctx = new ValidationContext(); ctx.setValidate(validate); ctx.setStopOnError(true); // bail if an error is encountered return fromJSON(json, ctx); } catch (final ValidationException e) { return null; } }
java
public final IJSONSerializable<?> fromString(String string, final boolean validate) { if (null == (string = StringOps.toTrimOrNull(string))) { return null; } final JSONValue value = JSONParser.parseStrict(string); if (null == value) { return null; } final JSONObject json = value.isObject(); if (null == json) { return null; } try { final ValidationContext ctx = new ValidationContext(); ctx.setValidate(validate); ctx.setStopOnError(true); // bail if an error is encountered return fromJSON(json, ctx); } catch (final ValidationException e) { return null; } }
[ "public", "final", "IJSONSerializable", "<", "?", ">", "fromString", "(", "String", "string", ",", "final", "boolean", "validate", ")", "{", "if", "(", "null", "==", "(", "string", "=", "StringOps", ".", "toTrimOrNull", "(", "string", ")", ")", ")", "{",...
Parses the JSON string and returns the IJSONSerializable. If validate is true, it will attempt to validate the attributes and types of child nodes etc. If validate is false, it assumes the JSON string is correct (this is a little faster.) @param string JSON string as produced by {@link IJSONSerializable#toJSONString()} @param validate Whether to validate the attributes and child node types @return IJSONSerializable
[ "Parses", "the", "JSON", "string", "and", "returns", "the", "IJSONSerializable", ".", "If", "validate", "is", "true", "it", "will", "attempt", "to", "validate", "the", "attributes", "and", "types", "of", "child", "nodes", "etc", ".", "If", "validate", "is", ...
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/json/JSONDeserializer.java#L98-L130
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/datetime/DateTimeFormatterCache.java
DateTimeFormatterCache.getDateTimeFormatterLenient
@Nonnull public static DateTimeFormatter getDateTimeFormatterLenient (@Nonnull @Nonempty final String sPattern) { return getDateTimeFormatter (sPattern, ResolverStyle.LENIENT); }
java
@Nonnull public static DateTimeFormatter getDateTimeFormatterLenient (@Nonnull @Nonempty final String sPattern) { return getDateTimeFormatter (sPattern, ResolverStyle.LENIENT); }
[ "@", "Nonnull", "public", "static", "DateTimeFormatter", "getDateTimeFormatterLenient", "(", "@", "Nonnull", "@", "Nonempty", "final", "String", "sPattern", ")", "{", "return", "getDateTimeFormatter", "(", "sPattern", ",", "ResolverStyle", ".", "LENIENT", ")", ";", ...
Get the cached DateTimeFormatter using LENIENT resolving. @param sPattern The pattern to retrieve. May neither be <code>null</code> nor empty. @return The compiled DateTimeFormatter and never <code>null</code> . @throws IllegalArgumentException If the pattern is invalid
[ "Get", "the", "cached", "DateTimeFormatter", "using", "LENIENT", "resolving", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/datetime/DateTimeFormatterCache.java#L106-L110
Javen205/IJPay
src/main/java/com/jpay/util/HttpKitExt.java
HttpKitExt.postSSL
protected static String postSSL(String url, String data, String certPath, String certPass) { HttpsURLConnection conn = null; OutputStream out = null; InputStream inputStream = null; BufferedReader reader = null; try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream(certPath), certPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, certPass.toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL _url = new URL(url); conn = (HttpsURLConnection) _url.openConnection(); conn.setConnectTimeout(25000); conn.setReadTimeout(25000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT); conn.connect(); out = conn.getOutputStream(); out.write(data.getBytes(Charsets.UTF_8)); out.flush(); inputStream = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); if (conn != null) { conn.disconnect(); } } }
java
protected static String postSSL(String url, String data, String certPath, String certPass) { HttpsURLConnection conn = null; OutputStream out = null; InputStream inputStream = null; BufferedReader reader = null; try { KeyStore clientStore = KeyStore.getInstance("PKCS12"); clientStore.load(new FileInputStream(certPath), certPass.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(clientStore, certPass.toCharArray()); KeyManager[] kms = kmf.getKeyManagers(); SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(kms, null, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); URL _url = new URL(url); conn = (HttpsURLConnection) _url.openConnection(); conn.setConnectTimeout(25000); conn.setReadTimeout(25000); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT); conn.connect(); out = conn.getOutputStream(); out.write(data.getBytes(Charsets.UTF_8)); out.flush(); inputStream = conn.getInputStream(); reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } return sb.toString(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeQuietly(out); IOUtils.closeQuietly(reader); IOUtils.closeQuietly(inputStream); if (conn != null) { conn.disconnect(); } } }
[ "protected", "static", "String", "postSSL", "(", "String", "url", ",", "String", "data", ",", "String", "certPath", ",", "String", "certPass", ")", "{", "HttpsURLConnection", "conn", "=", "null", ";", "OutputStream", "out", "=", "null", ";", "InputStream", "...
涉及资金回滚的接口会使用到商户证书,包括退款、撤销接口的请求 @param url 请求的地址 @param data xml数据 @param certPath 证书文件目录 @param certPass 证书密码 @return String 回调的xml信息
[ "涉及资金回滚的接口会使用到商户证书,包括退款、撤销接口的请求" ]
train
https://github.com/Javen205/IJPay/blob/78da6be4b70675abc6a41df74817532fa257ef29/src/main/java/com/jpay/util/HttpKitExt.java#L148-L198
facebookarchive/hadoop-20
src/core/org/apache/hadoop/jmx/JMXJsonServlet.java
JMXJsonServlet.renderMBean
private void renderMBean(JsonGenerator jg, ObjectName objectName) throws IOException { MBeanInfo beanInfo; String className; jg.writeObjectFieldStart(objectName.toString()); jg.writeStringField("beanName", objectName.toString()); try { beanInfo = mBeanServer.getMBeanInfo(objectName); className = beanInfo.getClassName(); // if we have the generic BaseModelMBean for className, attempt to get // more specific name if ("org.apache.commons.modeler.BaseModelMBean".equals(className)) { try { className = (String) mBeanServer.getAttribute(objectName, "modelerType"); } catch (Exception e) { // it's fine if no more-particular name can be found } } jg.writeStringField("className", className); for (MBeanAttributeInfo attr : beanInfo.getAttributes()) { writeAttribute(jg, objectName, attr); } } catch (OperationsException e) { // Some general MBean exception occurred. writeException(jg, e); } catch (ReflectionException e) { // This happens when the code inside the JMX bean threw an exception, so // log it and don't output the bean. writeException(jg, e); } jg.writeEndObject(); }
java
private void renderMBean(JsonGenerator jg, ObjectName objectName) throws IOException { MBeanInfo beanInfo; String className; jg.writeObjectFieldStart(objectName.toString()); jg.writeStringField("beanName", objectName.toString()); try { beanInfo = mBeanServer.getMBeanInfo(objectName); className = beanInfo.getClassName(); // if we have the generic BaseModelMBean for className, attempt to get // more specific name if ("org.apache.commons.modeler.BaseModelMBean".equals(className)) { try { className = (String) mBeanServer.getAttribute(objectName, "modelerType"); } catch (Exception e) { // it's fine if no more-particular name can be found } } jg.writeStringField("className", className); for (MBeanAttributeInfo attr : beanInfo.getAttributes()) { writeAttribute(jg, objectName, attr); } } catch (OperationsException e) { // Some general MBean exception occurred. writeException(jg, e); } catch (ReflectionException e) { // This happens when the code inside the JMX bean threw an exception, so // log it and don't output the bean. writeException(jg, e); } jg.writeEndObject(); }
[ "private", "void", "renderMBean", "(", "JsonGenerator", "jg", ",", "ObjectName", "objectName", ")", "throws", "IOException", "{", "MBeanInfo", "beanInfo", ";", "String", "className", ";", "jg", ".", "writeObjectFieldStart", "(", "objectName", ".", "toString", "(",...
Render a particular MBean's attributes to jg. @param jg JsonGenerator that will be written to @param objectName ObjectName for the mbean to render. @return void
[ "Render", "a", "particular", "MBean", "s", "attributes", "to", "jg", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/core/org/apache/hadoop/jmx/JMXJsonServlet.java#L237-L273
Azure/azure-sdk-for-java
network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/NetworkManagementClientImpl.java
NetworkManagementClientImpl.checkDnsNameAvailabilityAsync
public Observable<DnsNameAvailabilityResultInner> checkDnsNameAvailabilityAsync(String location, String domainNameLabel) { return checkDnsNameAvailabilityWithServiceResponseAsync(location, domainNameLabel).map(new Func1<ServiceResponse<DnsNameAvailabilityResultInner>, DnsNameAvailabilityResultInner>() { @Override public DnsNameAvailabilityResultInner call(ServiceResponse<DnsNameAvailabilityResultInner> response) { return response.body(); } }); }
java
public Observable<DnsNameAvailabilityResultInner> checkDnsNameAvailabilityAsync(String location, String domainNameLabel) { return checkDnsNameAvailabilityWithServiceResponseAsync(location, domainNameLabel).map(new Func1<ServiceResponse<DnsNameAvailabilityResultInner>, DnsNameAvailabilityResultInner>() { @Override public DnsNameAvailabilityResultInner call(ServiceResponse<DnsNameAvailabilityResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DnsNameAvailabilityResultInner", ">", "checkDnsNameAvailabilityAsync", "(", "String", "location", ",", "String", "domainNameLabel", ")", "{", "return", "checkDnsNameAvailabilityWithServiceResponseAsync", "(", "location", ",", "domainNameLabel", "...
Checks whether a domain name in the cloudapp.azure.com zone is available for use. @param location The location of the domain name. @param domainNameLabel The domain name to be verified. It must conform to the following regular expression: ^[a-z][a-z0-9-]{1,61}[a-z0-9]$. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DnsNameAvailabilityResultInner object
[ "Checks", "whether", "a", "domain", "name", "in", "the", "cloudapp", ".", "azure", ".", "com", "zone", "is", "available", "for", "use", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_08_01/src/main/java/com/microsoft/azure/management/network/v2018_08_01/implementation/NetworkManagementClientImpl.java#L1181-L1188
box/box-android-sdk
box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java
BoxApiMetadata.getUpdateFileMetadataRequest
public BoxRequestsMetadata.UpdateFileMetadata getUpdateFileMetadataRequest(String id, String scope, String template) { BoxRequestsMetadata.UpdateFileMetadata request = new BoxRequestsMetadata.UpdateFileMetadata(getFileMetadataUrl(id, scope, template), mSession); return request; }
java
public BoxRequestsMetadata.UpdateFileMetadata getUpdateFileMetadataRequest(String id, String scope, String template) { BoxRequestsMetadata.UpdateFileMetadata request = new BoxRequestsMetadata.UpdateFileMetadata(getFileMetadataUrl(id, scope, template), mSession); return request; }
[ "public", "BoxRequestsMetadata", ".", "UpdateFileMetadata", "getUpdateFileMetadataRequest", "(", "String", "id", ",", "String", "scope", ",", "String", "template", ")", "{", "BoxRequestsMetadata", ".", "UpdateFileMetadata", "request", "=", "new", "BoxRequestsMetadata", ...
Gets a request that updates the metadata for a specific template on a file @param id id of the file to retrieve metadata for @param scope currently only global and enterprise scopes are supported @param template metadata template to use @return request to update metadata on a file
[ "Gets", "a", "request", "that", "updates", "the", "metadata", "for", "a", "specific", "template", "on", "a", "file" ]
train
https://github.com/box/box-android-sdk/blob/a621ad5ddebf23067fec27529130d72718fc0e88/box-content-sdk/src/main/java/com/box/androidsdk/content/BoxApiMetadata.java#L228-L231
phax/ph-commons
ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java
KeyStoreHelper.loadPrivateKey
@Nonnull public static LoadedKey <KeyStore.PrivateKeyEntry> loadPrivateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.PrivateKeyEntry.class); }
java
@Nonnull public static LoadedKey <KeyStore.PrivateKeyEntry> loadPrivateKey (@Nonnull final KeyStore aKeyStore, @Nonnull final String sKeyStorePath, @Nullable final String sKeyStoreKeyAlias, @Nullable final char [] aKeyStoreKeyPassword) { return _loadKey (aKeyStore, sKeyStorePath, sKeyStoreKeyAlias, aKeyStoreKeyPassword, KeyStore.PrivateKeyEntry.class); }
[ "@", "Nonnull", "public", "static", "LoadedKey", "<", "KeyStore", ".", "PrivateKeyEntry", ">", "loadPrivateKey", "(", "@", "Nonnull", "final", "KeyStore", "aKeyStore", ",", "@", "Nonnull", "final", "String", "sKeyStorePath", ",", "@", "Nullable", "final", "Strin...
Load the specified private key entry from the provided key store. @param aKeyStore The key store to load the key from. May not be <code>null</code>. @param sKeyStorePath Key store path. For nice error messages only. May be <code>null</code>. @param sKeyStoreKeyAlias The alias to be resolved in the key store. Must be non- <code>null</code> to succeed. @param aKeyStoreKeyPassword The key password for the key store. Must be non-<code>null</code> to succeed. @return The key loading result. Never <code>null</code>.
[ "Load", "the", "specified", "private", "key", "entry", "from", "the", "provided", "key", "store", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-security/src/main/java/com/helger/security/keystore/KeyStoreHelper.java#L335-L342
kuali/ojb-1.0.4
src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java
OjbTagsHandler.forAllForeignkeyColumnPairs
public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException { for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++) { _curPairLeft = _curForeignkeyDef.getLocalColumn(idx); _curPairRight = _curForeignkeyDef.getRemoteColumn(idx); generate(template); } _curPairLeft = null; _curPairRight = null; }
java
public void forAllForeignkeyColumnPairs(String template, Properties attributes) throws XDocletException { for (int idx = 0; idx < _curForeignkeyDef.getNumColumnPairs(); idx++) { _curPairLeft = _curForeignkeyDef.getLocalColumn(idx); _curPairRight = _curForeignkeyDef.getRemoteColumn(idx); generate(template); } _curPairLeft = null; _curPairRight = null; }
[ "public", "void", "forAllForeignkeyColumnPairs", "(", "String", "template", ",", "Properties", "attributes", ")", "throws", "XDocletException", "{", "for", "(", "int", "idx", "=", "0", ";", "idx", "<", "_curForeignkeyDef", ".", "getNumColumnPairs", "(", ")", ";"...
Processes the template for all column pairs of the current foreignkey. @param template The template @param attributes The attributes of the tag @exception XDocletException if an error occurs @doc.tag type="block"
[ "Processes", "the", "template", "for", "all", "column", "pairs", "of", "the", "current", "foreignkey", "." ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/xdoclet/java/src/xdoclet/modules/ojb/OjbTagsHandler.java#L1380-L1390
beders/Resty
src/main/java/us/monoid/web/Resty.java
Resty.fillResourceFromURL
protected <T extends AbstractResource> T fillResourceFromURL(URLConnection con, T resource) throws IOException { resource.fill(con); resource.getAdditionalHeaders().putAll(getAdditionalHeaders()); // carry over additional headers TODO don't do it if there are no additional headers return resource; }
java
protected <T extends AbstractResource> T fillResourceFromURL(URLConnection con, T resource) throws IOException { resource.fill(con); resource.getAdditionalHeaders().putAll(getAdditionalHeaders()); // carry over additional headers TODO don't do it if there are no additional headers return resource; }
[ "protected", "<", "T", "extends", "AbstractResource", ">", "T", "fillResourceFromURL", "(", "URLConnection", "con", ",", "T", "resource", ")", "throws", "IOException", "{", "resource", ".", "fill", "(", "con", ")", ";", "resource", ".", "getAdditionalHeaders", ...
Get the content from the URLConnection, create a Resource representing the content and carry over some metadata like HTTP Result and location header. @param <T extends AbstractResource> the resource that will be created and filled @param con the URLConnection used to get the data @param resourceClass the resource class to instantiate @return the new resource @throws IOException
[ "Get", "the", "content", "from", "the", "URLConnection", "create", "a", "Resource", "representing", "the", "content", "and", "carry", "over", "some", "metadata", "like", "HTTP", "Result", "and", "location", "header", "." ]
train
https://github.com/beders/Resty/blob/4493603e9689c942cc3e53b9c5018010e414a364/src/main/java/us/monoid/web/Resty.java#L428-L432
lessthanoptimal/BoofCV
main/boofcv-recognition/src/main/java/boofcv/deepboof/ImageClassifierVggCifar10.java
ImageClassifierVggCifar10.loadModel
@Override public void loadModel(File directory) throws IOException { stats = DeepModelIO.load(new File(directory,"YuvStatistics.txt")); SequenceAndParameters<Tensor_F32, Function<Tensor_F32>> sequence = new ParseBinaryTorch7().parseIntoBoof(new File(directory,"model.net")); network = sequence.createForward(3,inputSize,inputSize); tensorOutput = new Tensor_F32(WI(1,network.getOutputShape())); BorderType type = BorderType.valueOf(stats.border); localNorm = new ImageLocalNormalization<>(GrayF32.class, type); kernel = DataManipulationOps.create1D_F32(stats.kernel); }
java
@Override public void loadModel(File directory) throws IOException { stats = DeepModelIO.load(new File(directory,"YuvStatistics.txt")); SequenceAndParameters<Tensor_F32, Function<Tensor_F32>> sequence = new ParseBinaryTorch7().parseIntoBoof(new File(directory,"model.net")); network = sequence.createForward(3,inputSize,inputSize); tensorOutput = new Tensor_F32(WI(1,network.getOutputShape())); BorderType type = BorderType.valueOf(stats.border); localNorm = new ImageLocalNormalization<>(GrayF32.class, type); kernel = DataManipulationOps.create1D_F32(stats.kernel); }
[ "@", "Override", "public", "void", "loadModel", "(", "File", "directory", ")", "throws", "IOException", "{", "stats", "=", "DeepModelIO", ".", "load", "(", "new", "File", "(", "directory", ",", "\"YuvStatistics.txt\"", ")", ")", ";", "SequenceAndParameters", "...
Expects there to be two files in the provided directory:<br> YuvStatistics.txt<br> model.net<br> @param directory Directory containing model files @throws IOException Throw if anything goes wrong while reading data
[ "Expects", "there", "to", "be", "two", "files", "in", "the", "provided", "directory", ":", "<br", ">", "YuvStatistics", ".", "txt<br", ">", "model", ".", "net<br", ">" ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-recognition/src/main/java/boofcv/deepboof/ImageClassifierVggCifar10.java#L72-L85
hankcs/HanLP
src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java
PerceptronClassifier.trainAveragedPerceptron
private static LinearModel trainAveragedPerceptron(Instance[] instanceList, FeatureMap featureMap, int maxIteration) { float[] parameter = new float[featureMap.size()]; double[] sum = new double[featureMap.size()]; int[] time = new int[featureMap.size()]; AveragedPerceptron model = new AveragedPerceptron(featureMap, parameter); int t = 0; for (int it = 0; it < maxIteration; ++it) { Utility.shuffleArray(instanceList); for (Instance instance : instanceList) { ++t; int y = model.decode(instance.x); if (y != instance.y) // 误差反馈 model.update(instance.x, instance.y, sum, time, t); } } model.average(sum, time, t); return model; }
java
private static LinearModel trainAveragedPerceptron(Instance[] instanceList, FeatureMap featureMap, int maxIteration) { float[] parameter = new float[featureMap.size()]; double[] sum = new double[featureMap.size()]; int[] time = new int[featureMap.size()]; AveragedPerceptron model = new AveragedPerceptron(featureMap, parameter); int t = 0; for (int it = 0; it < maxIteration; ++it) { Utility.shuffleArray(instanceList); for (Instance instance : instanceList) { ++t; int y = model.decode(instance.x); if (y != instance.y) // 误差反馈 model.update(instance.x, instance.y, sum, time, t); } } model.average(sum, time, t); return model; }
[ "private", "static", "LinearModel", "trainAveragedPerceptron", "(", "Instance", "[", "]", "instanceList", ",", "FeatureMap", "featureMap", ",", "int", "maxIteration", ")", "{", "float", "[", "]", "parameter", "=", "new", "float", "[", "featureMap", ".", "size", ...
平均感知机训练算法 @param instanceList 训练实例 @param featureMap 特征函数 @param maxIteration 训练迭代次数
[ "平均感知机训练算法" ]
train
https://github.com/hankcs/HanLP/blob/a538d0722ab2e4980a9dcd9ea40324fc3ddba7ce/src/main/java/com/hankcs/hanlp/model/perceptron/PerceptronClassifier.java#L79-L100
adamfisk/dnsjava-fork
src/org/xbill/DNS/utils/HMAC.java
HMAC.verify
public boolean verify(byte [] signature, boolean truncation_ok) { byte [] expected = sign(); if (truncation_ok && signature.length < expected.length) { byte [] truncated = new byte[signature.length]; System.arraycopy(expected, 0, truncated, 0, truncated.length); expected = truncated; } return Arrays.equals(signature, expected); }
java
public boolean verify(byte [] signature, boolean truncation_ok) { byte [] expected = sign(); if (truncation_ok && signature.length < expected.length) { byte [] truncated = new byte[signature.length]; System.arraycopy(expected, 0, truncated, 0, truncated.length); expected = truncated; } return Arrays.equals(signature, expected); }
[ "public", "boolean", "verify", "(", "byte", "[", "]", "signature", ",", "boolean", "truncation_ok", ")", "{", "byte", "[", "]", "expected", "=", "sign", "(", ")", ";", "if", "(", "truncation_ok", "&&", "signature", ".", "length", "<", "expected", ".", ...
Verifies the data (computes the secure hash and compares it to the input) @param signature The signature to compare against @param truncation_ok If true, the signature may be truncated; only the number of bytes in the provided signature are compared. @return true if the signature matches, false otherwise
[ "Verifies", "the", "data", "(", "computes", "the", "secure", "hash", "and", "compares", "it", "to", "the", "input", ")" ]
train
https://github.com/adamfisk/dnsjava-fork/blob/69510a1cad0518badb19a6615724313bebc61f90/src/org/xbill/DNS/utils/HMAC.java#L154-L163
onelogin/onelogin-java-sdk
src/main/java/com/onelogin/sdk/conn/Client.java
Client.getGroupsBatch
public OneLoginResponse<Group> getGroupsBatch(HashMap<String, String> queryParameters, int batchSize, String afterCursor) throws OAuthSystemException, OAuthProblemException, URISyntaxException { ExtractionContext context = extractResourceBatch(queryParameters, batchSize, afterCursor, Constants.GET_GROUPS_URL); List<Group> groups = new ArrayList<Group>(batchSize); afterCursor = getGroupsBatch(groups, context.url, context.bearerRequest, context.oAuthResponse); return new OneLoginResponse<Group>(groups, afterCursor); }
java
public OneLoginResponse<Group> getGroupsBatch(HashMap<String, String> queryParameters, int batchSize, String afterCursor) throws OAuthSystemException, OAuthProblemException, URISyntaxException { ExtractionContext context = extractResourceBatch(queryParameters, batchSize, afterCursor, Constants.GET_GROUPS_URL); List<Group> groups = new ArrayList<Group>(batchSize); afterCursor = getGroupsBatch(groups, context.url, context.bearerRequest, context.oAuthResponse); return new OneLoginResponse<Group>(groups, afterCursor); }
[ "public", "OneLoginResponse", "<", "Group", ">", "getGroupsBatch", "(", "HashMap", "<", "String", ",", "String", ">", "queryParameters", ",", "int", "batchSize", ",", "String", "afterCursor", ")", "throws", "OAuthSystemException", ",", "OAuthProblemException", ",", ...
Get a batch of Groups @param queryParameters Query parameters of the Resource @param batchSize Size of the Batch @param afterCursor Reference to continue collecting items of next page @return OneLoginResponse of Group @throws OAuthSystemException - if there is a IOException reading parameters of the httpURLConnection @throws OAuthProblemException - if there are errors validating the OneloginOAuthJSONResourceResponse and throwOAuthProblemException is enabled @throws URISyntaxException - if there is an error when generating the target URL at the URIBuilder constructor @see com.onelogin.sdk.model.Group @see <a target="_blank" href="https://developers.onelogin.com/api-docs/1/groups/get-groups">Get Groups documentation</a>
[ "Get", "a", "batch", "of", "Groups" ]
train
https://github.com/onelogin/onelogin-java-sdk/blob/1570b78033dcc1c7387099e77fe41b6b0638df8c/src/main/java/com/onelogin/sdk/conn/Client.java#L2293-L2299
zaproxy/zaproxy
src/org/zaproxy/zap/spider/URLCanonicalizer.java
URLCanonicalizer.createSortedParameters
private static SortedSet<QueryParameter> createSortedParameters(final String queryString) { if (queryString == null || queryString.isEmpty()) { return null; } final String[] pairs = queryString.split("&"); final SortedSet<QueryParameter> params = new TreeSet<>(); for (final String pair : pairs) { if (pair.length() == 0) { continue; } String[] tokens = pair.split("=", 2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.add(new QueryParameter("", tokens[0])); } else { params.add(new QueryParameter(tokens[0], "")); } break; case 2: params.add(new QueryParameter(tokens[0], tokens[1])); break; } } return params; }
java
private static SortedSet<QueryParameter> createSortedParameters(final String queryString) { if (queryString == null || queryString.isEmpty()) { return null; } final String[] pairs = queryString.split("&"); final SortedSet<QueryParameter> params = new TreeSet<>(); for (final String pair : pairs) { if (pair.length() == 0) { continue; } String[] tokens = pair.split("=", 2); switch (tokens.length) { case 1: if (pair.charAt(0) == '=') { params.add(new QueryParameter("", tokens[0])); } else { params.add(new QueryParameter(tokens[0], "")); } break; case 2: params.add(new QueryParameter(tokens[0], tokens[1])); break; } } return params; }
[ "private", "static", "SortedSet", "<", "QueryParameter", ">", "createSortedParameters", "(", "final", "String", "queryString", ")", "{", "if", "(", "queryString", "==", "null", "||", "queryString", ".", "isEmpty", "(", ")", ")", "{", "return", "null", ";", "...
Creates a sorted set with all the parameters from the given {@code query}, ordered lexicographically by name and value. @param queryString the query string @return a sorted set with all parameters, or {@code null} if the query string is {@code null} or empty.
[ "Creates", "a", "sorted", "set", "with", "all", "the", "parameters", "from", "the", "given", "{", "@code", "query", "}", "ordered", "lexicographically", "by", "name", "and", "value", "." ]
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/spider/URLCanonicalizer.java#L402-L430
wildfly-extras/wildfly-camel
common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java
IllegalStateAssertion.assertNotNull
public static <T> T assertNotNull(T value, String message) { if (value == null) throw new IllegalStateException(message); return value; }
java
public static <T> T assertNotNull(T value, String message) { if (value == null) throw new IllegalStateException(message); return value; }
[ "public", "static", "<", "T", ">", "T", "assertNotNull", "(", "T", "value", ",", "String", "message", ")", "{", "if", "(", "value", "==", "null", ")", "throw", "new", "IllegalStateException", "(", "message", ")", ";", "return", "value", ";", "}" ]
Throws an IllegalStateException when the given value is null. @return the value
[ "Throws", "an", "IllegalStateException", "when", "the", "given", "value", "is", "null", "." ]
train
https://github.com/wildfly-extras/wildfly-camel/blob/9ebd7e28574f277a6d5b583e8a4c357e1538c370/common/src/main/java/org/wildfly/camel/utils/IllegalStateAssertion.java#L48-L52
salesforce/Argus
ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java
Trigger.evaluateTrigger
public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } }
java
public static boolean evaluateTrigger(Trigger trigger, Double actualValue) { requireArgument(trigger != null, "Trigger cannot be null."); requireArgument(actualValue != null, "Trigger cannot be evaulated against null."); Double lowThreshold, highThreshold; switch (trigger.type) { case GREATER_THAN: return actualValue.compareTo(trigger.getThreshold()) > 0; case GREATER_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) >= 0; case LESS_THAN: return actualValue.compareTo(trigger.getThreshold()) < 0; case LESS_THAN_OR_EQ: return actualValue.compareTo(trigger.getThreshold()) <= 0; case EQUAL: return actualValue.compareTo(trigger.getThreshold()) == 0; case NOT_EQUAL: return actualValue.compareTo(trigger.getThreshold()) != 0; case BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) >= 0 && actualValue.compareTo(highThreshold) <= 0); case NOT_BETWEEN: lowThreshold = Math.min(trigger.getThreshold(), trigger.getSecondaryThreshold()); highThreshold = Math.max(trigger.getThreshold(), trigger.getSecondaryThreshold()); return (actualValue.compareTo(lowThreshold) < 0 || actualValue.compareTo(highThreshold) > 0); case NO_DATA: return actualValue == null; default: throw new SystemException("Unsupported trigger type " + trigger.type); } }
[ "public", "static", "boolean", "evaluateTrigger", "(", "Trigger", "trigger", ",", "Double", "actualValue", ")", "{", "requireArgument", "(", "trigger", "!=", "null", ",", "\"Trigger cannot be null.\"", ")", ";", "requireArgument", "(", "actualValue", "!=", "null", ...
Evaluates the trigger against actualValue (passed as parameter). @param trigger trigger to be evaluated. @param actualValue value against the trigger to be evaluated. @return true if the trigger should be fired so that notification will be sent otherwise false. @throws SystemException If an error in evaluation occurs.
[ "Evaluates", "the", "trigger", "against", "actualValue", "(", "passed", "as", "parameter", ")", "." ]
train
https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/Trigger.java#L230-L262
aws/aws-sdk-java
aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/iterable/S3Versions.java
S3Versions.forKey
public static S3Versions forKey(AmazonS3 s3, String bucketName, String key) { S3Versions versions = new S3Versions(s3, bucketName); versions.key = key; return versions; }
java
public static S3Versions forKey(AmazonS3 s3, String bucketName, String key) { S3Versions versions = new S3Versions(s3, bucketName); versions.key = key; return versions; }
[ "public", "static", "S3Versions", "forKey", "(", "AmazonS3", "s3", ",", "String", "bucketName", ",", "String", "key", ")", "{", "S3Versions", "versions", "=", "new", "S3Versions", "(", "s3", ",", "bucketName", ")", ";", "versions", ".", "key", "=", "key", ...
Constructs an iterable that covers the versions of a single Amazon S3 object. @param s3 The Amazon S3 client. @param bucketName The bucket name. @param key The key. @return An iterator for object version summaries.
[ "Constructs", "an", "iterable", "that", "covers", "the", "versions", "of", "a", "single", "Amazon", "S3", "object", "." ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/iterable/S3Versions.java#L96-L100
grails/grails-core
grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java
GrailsASTUtils.addDelegateStaticMethod
public static MethodNode addDelegateStaticMethod(Expression delegate, ClassNode classNode, MethodNode delegateMethod, AnnotationNode markerAnnotation, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) { Parameter[] parameterTypes = delegateMethod.getParameters(); String declaredMethodName = delegateMethod.getName(); if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) { declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME; } if (classNode.hasDeclaredMethod(declaredMethodName, copyParameters(parameterTypes, genericsPlaceholders))) { return null; } BlockStatement methodBody = new BlockStatement(); ArgumentListExpression arguments = createArgumentListFromParameters(parameterTypes, false, genericsPlaceholders); MethodCallExpression methodCallExpression = new MethodCallExpression( delegate, delegateMethod.getName(), arguments); methodCallExpression.setMethodTarget(delegateMethod); if(!noNullCheck && !(delegate instanceof ClassExpression)) { ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod); VariableExpression apiVar = addApiVariableDeclaration(delegate, delegateMethod, methodBody); IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar, missingMethodException); methodBody.addStatement(ifStatement); } else { methodBody.addStatement(new ExpressionStatement(methodCallExpression)); } ClassNode returnType = replaceGenericsPlaceholders(delegateMethod.getReturnType(), genericsPlaceholders); MethodNode methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType, copyParameters(parameterTypes, genericsPlaceholders), GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY, methodBody); copyAnnotations(delegateMethod, methodNode); if (shouldAddMarkerAnnotation(markerAnnotation, methodNode)) { methodNode.addAnnotation(markerAnnotation); } classNode.addMethod(methodNode); return methodNode; }
java
public static MethodNode addDelegateStaticMethod(Expression delegate, ClassNode classNode, MethodNode delegateMethod, AnnotationNode markerAnnotation, Map<String, ClassNode> genericsPlaceholders, boolean noNullCheck) { Parameter[] parameterTypes = delegateMethod.getParameters(); String declaredMethodName = delegateMethod.getName(); if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) { declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME; } if (classNode.hasDeclaredMethod(declaredMethodName, copyParameters(parameterTypes, genericsPlaceholders))) { return null; } BlockStatement methodBody = new BlockStatement(); ArgumentListExpression arguments = createArgumentListFromParameters(parameterTypes, false, genericsPlaceholders); MethodCallExpression methodCallExpression = new MethodCallExpression( delegate, delegateMethod.getName(), arguments); methodCallExpression.setMethodTarget(delegateMethod); if(!noNullCheck && !(delegate instanceof ClassExpression)) { ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod); VariableExpression apiVar = addApiVariableDeclaration(delegate, delegateMethod, methodBody); IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar, missingMethodException); methodBody.addStatement(ifStatement); } else { methodBody.addStatement(new ExpressionStatement(methodCallExpression)); } ClassNode returnType = replaceGenericsPlaceholders(delegateMethod.getReturnType(), genericsPlaceholders); MethodNode methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType, copyParameters(parameterTypes, genericsPlaceholders), GrailsArtefactClassInjector.EMPTY_CLASS_ARRAY, methodBody); copyAnnotations(delegateMethod, methodNode); if (shouldAddMarkerAnnotation(markerAnnotation, methodNode)) { methodNode.addAnnotation(markerAnnotation); } classNode.addMethod(methodNode); return methodNode; }
[ "public", "static", "MethodNode", "addDelegateStaticMethod", "(", "Expression", "delegate", ",", "ClassNode", "classNode", ",", "MethodNode", "delegateMethod", ",", "AnnotationNode", "markerAnnotation", ",", "Map", "<", "String", ",", "ClassNode", ">", "genericsPlacehol...
Adds a static method to the given class node that delegates to the given method and resolves the object to invoke the method on from the given expression. @param delegate The expression @param classNode The class node @param delegateMethod The delegate method @param markerAnnotation A marker annotation to be added to all methods @return The added method node or null if it couldn't be added
[ "Adds", "a", "static", "method", "to", "the", "given", "class", "node", "that", "delegates", "to", "the", "given", "method", "and", "resolves", "the", "object", "to", "invoke", "the", "method", "on", "from", "the", "given", "expression", "." ]
train
https://github.com/grails/grails-core/blob/c0b08aa995b0297143b75d05642abba8cb7b4122/grails-core/src/main/groovy/org/grails/compiler/injection/GrailsASTUtils.java#L396-L434
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/seo/CmsSeoOptionsDialog.java
CmsSeoOptionsDialog.saveAliases
public void saveAliases(final CmsUUID uuid, final List<CmsAliasBean> aliases) { final CmsRpcAction<Void> action = new CmsRpcAction<Void>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { start(200, true); CmsCoreProvider.getVfsService().saveAliases(uuid, aliases, this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override public void onResponse(Void result) { stop(false); } }; action.execute(); }
java
public void saveAliases(final CmsUUID uuid, final List<CmsAliasBean> aliases) { final CmsRpcAction<Void> action = new CmsRpcAction<Void>() { /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#execute() */ @Override public void execute() { start(200, true); CmsCoreProvider.getVfsService().saveAliases(uuid, aliases, this); } /** * @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object) */ @Override public void onResponse(Void result) { stop(false); } }; action.execute(); }
[ "public", "void", "saveAliases", "(", "final", "CmsUUID", "uuid", ",", "final", "List", "<", "CmsAliasBean", ">", "aliases", ")", "{", "final", "CmsRpcAction", "<", "Void", ">", "action", "=", "new", "CmsRpcAction", "<", "Void", ">", "(", ")", "{", "/**\...
Saves the aliases for a given page.<p> @param uuid the page structure id @param aliases the aliases to save
[ "Saves", "the", "aliases", "for", "a", "given", "page", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/seo/CmsSeoOptionsDialog.java#L237-L263
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/MapLabelSetterFactory.java
MapLabelSetterFactory.createField
private Optional<MapLabelSetter> createField(final Class<?> beanClass, final String fieldName) { final String labelFieldName = fieldName + "Label"; final Field labelField; try { labelField = beanClass.getDeclaredField(labelFieldName); labelField.setAccessible(true); } catch (NoSuchFieldException | SecurityException e) { return Optional.empty(); } if(!Map.class.isAssignableFrom(labelField.getType())) { return Optional.empty(); } final ParameterizedType type = (ParameterizedType) labelField.getGenericType(); final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0]; final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1]; if(keyType.equals(String.class) && valueType.equals(String.class)) { return Optional.of(new MapLabelSetter() { @SuppressWarnings("unchecked") @Override public void set(final Object beanObj, final String label, final String key) { ArgUtils.notNull(beanObj, "beanObj"); ArgUtils.notEmpty(label, "label"); try { Map<String, String> labelMapObj = (Map<String, String>) labelField.get(beanObj); if(labelMapObj == null) { labelMapObj = new LinkedHashMap<>(); labelField.set(beanObj, labelMapObj); } labelMapObj.put(key, label); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("fail access label field.", e); } } }); } return Optional.empty(); }
java
private Optional<MapLabelSetter> createField(final Class<?> beanClass, final String fieldName) { final String labelFieldName = fieldName + "Label"; final Field labelField; try { labelField = beanClass.getDeclaredField(labelFieldName); labelField.setAccessible(true); } catch (NoSuchFieldException | SecurityException e) { return Optional.empty(); } if(!Map.class.isAssignableFrom(labelField.getType())) { return Optional.empty(); } final ParameterizedType type = (ParameterizedType) labelField.getGenericType(); final Class<?> keyType = (Class<?>) type.getActualTypeArguments()[0]; final Class<?> valueType = (Class<?>) type.getActualTypeArguments()[1]; if(keyType.equals(String.class) && valueType.equals(String.class)) { return Optional.of(new MapLabelSetter() { @SuppressWarnings("unchecked") @Override public void set(final Object beanObj, final String label, final String key) { ArgUtils.notNull(beanObj, "beanObj"); ArgUtils.notEmpty(label, "label"); try { Map<String, String> labelMapObj = (Map<String, String>) labelField.get(beanObj); if(labelMapObj == null) { labelMapObj = new LinkedHashMap<>(); labelField.set(beanObj, labelMapObj); } labelMapObj.put(key, label); } catch (IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException("fail access label field.", e); } } }); } return Optional.empty(); }
[ "private", "Optional", "<", "MapLabelSetter", ">", "createField", "(", "final", "Class", "<", "?", ">", "beanClass", ",", "final", "String", "fieldName", ")", "{", "final", "String", "labelFieldName", "=", "fieldName", "+", "\"Label\"", ";", "final", "Field", ...
フィールドによるラベル情報を格納する場合。 <p>{@code <フィールド名> + Label}のメソッド名</p> @param beanClass フィールドが定義してあるクラスのインスタンス @param fieldName フィールド名 @return ラベル情報の設定用クラス
[ "フィールドによるラベル情報を格納する場合。", "<p", ">", "{", "@code", "<フィールド名", ">", "+", "Label", "}", "のメソッド名<", "/", "p", ">" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/fieldaccessor/MapLabelSetterFactory.java#L179-L229
aspectran/aspectran
core/src/main/java/com/aspectran/core/util/BeanDescriptor.java
BeanDescriptor.getSetterAnnotation
public <T extends Annotation> T getSetterAnnotation(String name, Class<T> annotationType) throws NoSuchMethodException { Method method = getSetter(name); return getSetterAnnotation(method, annotationType); }
java
public <T extends Annotation> T getSetterAnnotation(String name, Class<T> annotationType) throws NoSuchMethodException { Method method = getSetter(name); return getSetterAnnotation(method, annotationType); }
[ "public", "<", "T", "extends", "Annotation", ">", "T", "getSetterAnnotation", "(", "String", "name", ",", "Class", "<", "T", ">", "annotationType", ")", "throws", "NoSuchMethodException", "{", "Method", "method", "=", "getSetter", "(", "name", ")", ";", "ret...
Invokes the annotation of the given type. @param name the given setter name @param annotationType the annotation type to look for @param <T> the annotation type @return the annotation object, or null if not found @throws NoSuchMethodException when a setter method cannot be found
[ "Invokes", "the", "annotation", "of", "the", "given", "type", "." ]
train
https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/BeanDescriptor.java#L311-L315
tvesalainen/util
util/src/main/java/org/vesalainen/util/CmdArgs.java
CmdArgs.addOption
public final <T> void addOption(Class<T> cls, String name, String description, String exclusiveGroup, boolean mandatory) { if (names.contains(name)) { throw new IllegalArgumentException(name+" is already added as argument"); } Option opt = new Option(cls, name, description, exclusiveGroup, mandatory); Option old = map.put(name, opt); if (old != null) { throw new IllegalArgumentException(name+" was already added"); } if (exclusiveGroup != null) { groups.add(exclusiveGroup, opt); } }
java
public final <T> void addOption(Class<T> cls, String name, String description, String exclusiveGroup, boolean mandatory) { if (names.contains(name)) { throw new IllegalArgumentException(name+" is already added as argument"); } Option opt = new Option(cls, name, description, exclusiveGroup, mandatory); Option old = map.put(name, opt); if (old != null) { throw new IllegalArgumentException(name+" was already added"); } if (exclusiveGroup != null) { groups.add(exclusiveGroup, opt); } }
[ "public", "final", "<", "T", ">", "void", "addOption", "(", "Class", "<", "T", ">", "cls", ",", "String", "name", ",", "String", "description", ",", "String", "exclusiveGroup", ",", "boolean", "mandatory", ")", "{", "if", "(", "names", ".", "contains", ...
Add an option @param <T> Type of option @param cls Option type class @param name Option name Option name without @param description Option description @param exclusiveGroup A group of options. Only options of a single group are accepted. @param mandatory
[ "Add", "an", "option" ]
train
https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/util/CmdArgs.java#L358-L374
netscaler/nitro
src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslcrl_binding.java
sslcrl_binding.get
public static sslcrl_binding get(nitro_service service, String crlname) throws Exception{ sslcrl_binding obj = new sslcrl_binding(); obj.set_crlname(crlname); sslcrl_binding response = (sslcrl_binding) obj.get_resource(service); return response; }
java
public static sslcrl_binding get(nitro_service service, String crlname) throws Exception{ sslcrl_binding obj = new sslcrl_binding(); obj.set_crlname(crlname); sslcrl_binding response = (sslcrl_binding) obj.get_resource(service); return response; }
[ "public", "static", "sslcrl_binding", "get", "(", "nitro_service", "service", ",", "String", "crlname", ")", "throws", "Exception", "{", "sslcrl_binding", "obj", "=", "new", "sslcrl_binding", "(", ")", ";", "obj", ".", "set_crlname", "(", "crlname", ")", ";", ...
Use this API to fetch sslcrl_binding resource of given name .
[ "Use", "this", "API", "to", "fetch", "sslcrl_binding", "resource", "of", "given", "name", "." ]
train
https://github.com/netscaler/nitro/blob/2a98692dcf4e4ec430c7d7baab8382e4ba5a35e4/src/main/java/com/citrix/netscaler/nitro/resource/config/ssl/sslcrl_binding.java#L103-L108
OpenLiberty/open-liberty
dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java
TwitterEndpointServices.createAuthzHeaderForVerifyCredentialsEndpoint
public String createAuthzHeaderForVerifyCredentialsEndpoint(String endpointUrl, String token) { Map<String, String> parameters = populateVerifyCredentialsEndpointAuthzHeaderParams(token); return signAndCreateAuthzHeader(endpointUrl, parameters); }
java
public String createAuthzHeaderForVerifyCredentialsEndpoint(String endpointUrl, String token) { Map<String, String> parameters = populateVerifyCredentialsEndpointAuthzHeaderParams(token); return signAndCreateAuthzHeader(endpointUrl, parameters); }
[ "public", "String", "createAuthzHeaderForVerifyCredentialsEndpoint", "(", "String", "endpointUrl", ",", "String", "token", ")", "{", "Map", "<", "String", ",", "String", ">", "parameters", "=", "populateVerifyCredentialsEndpointAuthzHeaderParams", "(", "token", ")", ";"...
Generates the Authorization header value required for a {@value TwitterConstants#TWITTER_ENDPOINT_VERIFY_CREDENTIALS} endpoint request. See {@link https://dev.twitter.com/rest/reference/get/account/verify_credentials} for details. @param endpointUrl @param token @return
[ "Generates", "the", "Authorization", "header", "value", "required", "for", "a", "{", "@value", "TwitterConstants#TWITTER_ENDPOINT_VERIFY_CREDENTIALS", "}", "endpoint", "request", ".", "See", "{", "@link", "https", ":", "//", "dev", ".", "twitter", ".", "com", "/",...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/twitter/TwitterEndpointServices.java#L454-L457
motown-io/motown
ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/OcppJsonService.java
OcppJsonService.closeAndRemoveWebSocket
public void closeAndRemoveWebSocket(String chargingStationIdentifier, @Nullable WebSocket webSocket) { if (webSocket != null && webSocket.isOpen()) { // received a web socket, close it no matter what webSocket.close(); } WebSocketWrapper existingWrapper = sockets.get(chargingStationIdentifier); if (existingWrapper == null) { LOG.info("Could not find websocket to remove for {}.", chargingStationIdentifier); return; } if (webSocket == null || webSocket.equals(existingWrapper.getWebSocket())) { if (existingWrapper.isOpen()) { LOG.info("Websocket to remove was not closed for {}. Closing now and removing websocket...", chargingStationIdentifier); existingWrapper.close(); } WebSocketWrapper removedSocket = sockets.remove(chargingStationIdentifier); // if the caller passed a web socket then only remove the web socket if it equals the passed web socket if (webSocket != null && !webSocket.equals(removedSocket.getWebSocket())) { // some other thread beat us to it (other thread added a new web socket to the set while we were in this method) // we removed the new socket, we put it back and act like nothing happened... sockets.put(chargingStationIdentifier, removedSocket); } } }
java
public void closeAndRemoveWebSocket(String chargingStationIdentifier, @Nullable WebSocket webSocket) { if (webSocket != null && webSocket.isOpen()) { // received a web socket, close it no matter what webSocket.close(); } WebSocketWrapper existingWrapper = sockets.get(chargingStationIdentifier); if (existingWrapper == null) { LOG.info("Could not find websocket to remove for {}.", chargingStationIdentifier); return; } if (webSocket == null || webSocket.equals(existingWrapper.getWebSocket())) { if (existingWrapper.isOpen()) { LOG.info("Websocket to remove was not closed for {}. Closing now and removing websocket...", chargingStationIdentifier); existingWrapper.close(); } WebSocketWrapper removedSocket = sockets.remove(chargingStationIdentifier); // if the caller passed a web socket then only remove the web socket if it equals the passed web socket if (webSocket != null && !webSocket.equals(removedSocket.getWebSocket())) { // some other thread beat us to it (other thread added a new web socket to the set while we were in this method) // we removed the new socket, we put it back and act like nothing happened... sockets.put(chargingStationIdentifier, removedSocket); } } }
[ "public", "void", "closeAndRemoveWebSocket", "(", "String", "chargingStationIdentifier", ",", "@", "Nullable", "WebSocket", "webSocket", ")", "{", "if", "(", "webSocket", "!=", "null", "&&", "webSocket", ".", "isOpen", "(", ")", ")", "{", "// received a web socket...
Close and remove a web socket from the set of sockets. By passing a webSocket object the caller can force this method to check if it's removing the handle that contains this web socket. If the parameter is null this method will close whatever it has for the identifier. @param chargingStationIdentifier charging station identifier for the socket @param webSocket if not null this method checks if the socket in the set contains this socket
[ "Close", "and", "remove", "a", "web", "socket", "from", "the", "set", "of", "sockets", "." ]
train
https://github.com/motown-io/motown/blob/783ccda7c28b273a529ddd47defe8673b1ea365b/ocpp/websocket-json/src/main/java/io/motown/ocpp/websocketjson/OcppJsonService.java#L456-L484
jmxtrans/jmxtrans
jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java
GangliaWriter.getSpoofedHostName
public static String getSpoofedHostName(String host, String alias) { // Determine the host name to use as the spoofed host name, this should // be of the format IP:hostname String spoofed = host; if (StringUtils.isNotEmpty(alias)) { // If the alias was supplied in the appropriate format, use it // directly Matcher hostIpMatcher = PATTERN_HOST_IP.matcher(alias); if (hostIpMatcher.matches()) return alias; // Otherwise, use the alias as the host spoofed = alias; } // Attempt to find the IP of the given host (this may be an aliased // host) try { return InetAddress.getByName(spoofed).getHostAddress() + ":" + spoofed; } catch (UnknownHostException e) { log.debug("ignore failure to resolve spoofed host, continue host resolution", e); } // Attempt to return the local host IP with the spoofed host name try { return InetAddress.getLocalHost().getHostAddress() + ":" + spoofed; } catch (UnknownHostException e) { log.debug("ignore failure to resolve spoofed host, continue host resolution", e); } // We failed to resolve the spoofed host or our local host, return "x" // for the IP return "x:" + spoofed; }
java
public static String getSpoofedHostName(String host, String alias) { // Determine the host name to use as the spoofed host name, this should // be of the format IP:hostname String spoofed = host; if (StringUtils.isNotEmpty(alias)) { // If the alias was supplied in the appropriate format, use it // directly Matcher hostIpMatcher = PATTERN_HOST_IP.matcher(alias); if (hostIpMatcher.matches()) return alias; // Otherwise, use the alias as the host spoofed = alias; } // Attempt to find the IP of the given host (this may be an aliased // host) try { return InetAddress.getByName(spoofed).getHostAddress() + ":" + spoofed; } catch (UnknownHostException e) { log.debug("ignore failure to resolve spoofed host, continue host resolution", e); } // Attempt to return the local host IP with the spoofed host name try { return InetAddress.getLocalHost().getHostAddress() + ":" + spoofed; } catch (UnknownHostException e) { log.debug("ignore failure to resolve spoofed host, continue host resolution", e); } // We failed to resolve the spoofed host or our local host, return "x" // for the IP return "x:" + spoofed; }
[ "public", "static", "String", "getSpoofedHostName", "(", "String", "host", ",", "String", "alias", ")", "{", "// Determine the host name to use as the spoofed host name, this should", "// be of the format IP:hostname", "String", "spoofed", "=", "host", ";", "if", "(", "Stri...
Determines the spoofed host name to be used when emitting metrics to a gmond process. Spoofed host names are of the form IP:hostname. @param host the host of the gmond (ganglia monitor) to which we are connecting, not null @param alias the custom alias supplied, may be null @return the host name to use when emitting metrics, in the form of IP:hostname
[ "Determines", "the", "spoofed", "host", "name", "to", "be", "used", "when", "emitting", "metrics", "to", "a", "gmond", "process", ".", "Spoofed", "host", "names", "are", "of", "the", "form", "IP", ":", "hostname", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-output/jmxtrans-output-ganglia/src/main/java/com/googlecode/jmxtrans/model/output/GangliaWriter.java#L217-L246
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/rename/RenameFileExtensions.java
RenameFileExtensions.renameFile
public static boolean renameFile(final File fileToRename, final File newFileName) throws IOException, FileIsADirectoryException { return renameFile(fileToRename, newFileName, false); }
java
public static boolean renameFile(final File fileToRename, final File newFileName) throws IOException, FileIsADirectoryException { return renameFile(fileToRename, newFileName, false); }
[ "public", "static", "boolean", "renameFile", "(", "final", "File", "fileToRename", ",", "final", "File", "newFileName", ")", "throws", "IOException", ",", "FileIsADirectoryException", "{", "return", "renameFile", "(", "fileToRename", ",", "newFileName", ",", "false"...
This method renames a given file. For instance if we have a file which we want to rename with the path "/tmp/test.dat" to "/tmp/renamed.dat" then you call the method as follow: renameFile(new File("C://tmp//test.dat"), new File("C://tmp//renamed.dat")); @param fileToRename The file to rename. @param newFileName The new name from the file. @return 's true if the file was renamed otherwise false. @throws IOException Signals that an I/O exception has occurred. @throws FileIsADirectoryException the file is A directory exception
[ "This", "method", "renames", "a", "given", "file", ".", "For", "instance", "if", "we", "have", "a", "file", "which", "we", "want", "to", "rename", "with", "the", "path", "/", "tmp", "/", "test", ".", "dat", "to", "/", "tmp", "/", "renamed", ".", "d...
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/rename/RenameFileExtensions.java#L287-L291
samskivert/samskivert
src/main/java/com/samskivert/velocity/DispatcherServlet.java
DispatcherServlet.loadConfiguration
protected Properties loadConfiguration (ServletConfig config) throws IOException { Properties props = loadVelocityProps(config); // if we failed to create our application for whatever reason; bail if (_app == null) { return props; } // let the application set up velocity properties _app.configureVelocity(config, props); // if no file resource loader path has been set and a site-specific jar file path was // provided, wire up our site resource manager configureResourceManager(config, props); // wire up our #import directive props.setProperty("userdirective", ImportDirective.class.getName()); // configure the servlet context logger props.put(RuntimeSingleton.RUNTIME_LOG_LOGSYSTEM_CLASS, ServletContextLogger.class.getName()); // now return our augmented properties return props; }
java
protected Properties loadConfiguration (ServletConfig config) throws IOException { Properties props = loadVelocityProps(config); // if we failed to create our application for whatever reason; bail if (_app == null) { return props; } // let the application set up velocity properties _app.configureVelocity(config, props); // if no file resource loader path has been set and a site-specific jar file path was // provided, wire up our site resource manager configureResourceManager(config, props); // wire up our #import directive props.setProperty("userdirective", ImportDirective.class.getName()); // configure the servlet context logger props.put(RuntimeSingleton.RUNTIME_LOG_LOGSYSTEM_CLASS, ServletContextLogger.class.getName()); // now return our augmented properties return props; }
[ "protected", "Properties", "loadConfiguration", "(", "ServletConfig", "config", ")", "throws", "IOException", "{", "Properties", "props", "=", "loadVelocityProps", "(", "config", ")", ";", "// if we failed to create our application for whatever reason; bail", "if", "(", "_a...
We load our velocity properties from the classpath rather than from a file.
[ "We", "load", "our", "velocity", "properties", "from", "the", "classpath", "rather", "than", "from", "a", "file", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/velocity/DispatcherServlet.java#L216-L242
netty/netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseStatus.java
HttpResponseStatus.valueOf
public static HttpResponseStatus valueOf(int code, String reasonPhrase) { HttpResponseStatus responseStatus = valueOf0(code); return responseStatus != null && responseStatus.reasonPhrase().contentEquals(reasonPhrase) ? responseStatus : new HttpResponseStatus(code, reasonPhrase); }
java
public static HttpResponseStatus valueOf(int code, String reasonPhrase) { HttpResponseStatus responseStatus = valueOf0(code); return responseStatus != null && responseStatus.reasonPhrase().contentEquals(reasonPhrase) ? responseStatus : new HttpResponseStatus(code, reasonPhrase); }
[ "public", "static", "HttpResponseStatus", "valueOf", "(", "int", "code", ",", "String", "reasonPhrase", ")", "{", "HttpResponseStatus", "responseStatus", "=", "valueOf0", "(", "code", ")", ";", "return", "responseStatus", "!=", "null", "&&", "responseStatus", ".",...
Returns the {@link HttpResponseStatus} represented by the specified {@code code} and {@code reasonPhrase}. If the specified code is a standard HTTP status {@code code} and {@code reasonPhrase}, a cached instance will be returned. Otherwise, a new instance will be returned. @param code The response code value. @param reasonPhrase The response code reason phrase. @return the {@link HttpResponseStatus} represented by the specified {@code code} and {@code reasonPhrase}.
[ "Returns", "the", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/codec-http/src/main/java/io/netty/handler/codec/http/HttpResponseStatus.java#L464-L468
cdk/cdk
display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AtomSymbol.java
AtomSymbol.alignTo
AtomSymbol alignTo(SymbolAlignment alignment) { return new AtomSymbol(element, adjuncts, annotationAdjuncts, alignment, hull); }
java
AtomSymbol alignTo(SymbolAlignment alignment) { return new AtomSymbol(element, adjuncts, annotationAdjuncts, alignment, hull); }
[ "AtomSymbol", "alignTo", "(", "SymbolAlignment", "alignment", ")", "{", "return", "new", "AtomSymbol", "(", "element", ",", "adjuncts", ",", "annotationAdjuncts", ",", "alignment", ",", "hull", ")", ";", "}" ]
Create a new atom symbol (from this symbol) but with the specified alignment. @param alignment element alignment @return new atom symbol
[ "Create", "a", "new", "atom", "symbol", "(", "from", "this", "symbol", ")", "but", "with", "the", "specified", "alignment", "." ]
train
https://github.com/cdk/cdk/blob/c3d0f16502bf08df50365fee392e11d7c9856657/display/renderbasic/src/main/java/org/openscience/cdk/renderer/generators/standard/AtomSymbol.java#L117-L119
deeplearning4j/deeplearning4j
datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java
ArrowConverter.readFromFile
public static Pair<Schema,ArrowWritableRecordBatch> readFromFile(FileInputStream input) throws IOException { BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); Schema retSchema = null; ArrowWritableRecordBatch ret = null; SeekableReadChannel channel = new SeekableReadChannel(input.getChannel()); ArrowFileReader reader = new ArrowFileReader(channel, allocator); reader.loadNextBatch(); retSchema = toDatavecSchema(reader.getVectorSchemaRoot().getSchema()); //load the batch VectorUnloader unloader = new VectorUnloader(reader.getVectorSchemaRoot()); VectorLoader vectorLoader = new VectorLoader(reader.getVectorSchemaRoot()); ArrowRecordBatch recordBatch = unloader.getRecordBatch(); vectorLoader.load(recordBatch); ret = asDataVecBatch(recordBatch,retSchema,reader.getVectorSchemaRoot()); ret.setUnloader(unloader); return Pair.of(retSchema,ret); }
java
public static Pair<Schema,ArrowWritableRecordBatch> readFromFile(FileInputStream input) throws IOException { BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); Schema retSchema = null; ArrowWritableRecordBatch ret = null; SeekableReadChannel channel = new SeekableReadChannel(input.getChannel()); ArrowFileReader reader = new ArrowFileReader(channel, allocator); reader.loadNextBatch(); retSchema = toDatavecSchema(reader.getVectorSchemaRoot().getSchema()); //load the batch VectorUnloader unloader = new VectorUnloader(reader.getVectorSchemaRoot()); VectorLoader vectorLoader = new VectorLoader(reader.getVectorSchemaRoot()); ArrowRecordBatch recordBatch = unloader.getRecordBatch(); vectorLoader.load(recordBatch); ret = asDataVecBatch(recordBatch,retSchema,reader.getVectorSchemaRoot()); ret.setUnloader(unloader); return Pair.of(retSchema,ret); }
[ "public", "static", "Pair", "<", "Schema", ",", "ArrowWritableRecordBatch", ">", "readFromFile", "(", "FileInputStream", "input", ")", "throws", "IOException", "{", "BufferAllocator", "allocator", "=", "new", "RootAllocator", "(", "Long", ".", "MAX_VALUE", ")", ";...
Read a datavec schema and record set from the given arrow file. @param input the input to read @return the associated datavec schema and record
[ "Read", "a", "datavec", "schema", "and", "record", "set", "from", "the", "given", "arrow", "file", "." ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/datavec/datavec-arrow/src/main/java/org/datavec/arrow/ArrowConverter.java#L360-L379
SeaCloudsEU/SeaCloudsPlatform
sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/AgreementRest.java
AgreementRest.createAgreement
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createAgreement(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload){ logger.debug("StartOf createAgreement - Insert /agreements"); String location = null; try{ AgreementHelper agreementRestService = getAgreementHelper(); location = agreementRestService.createAgreement(hh,uriInfo.getAbsolutePath().toString(), payload); } catch (HelperException e) { logger.info("createAgreement exception", e); return buildResponse(e); } Response result = buildResponsePOST(HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The agreement has been stored successfully in the SLA Repository Database with location:"+location), location); logger.debug("EndOf createAgreement"); return result; }
java
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createAgreement(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload){ logger.debug("StartOf createAgreement - Insert /agreements"); String location = null; try{ AgreementHelper agreementRestService = getAgreementHelper(); location = agreementRestService.createAgreement(hh,uriInfo.getAbsolutePath().toString(), payload); } catch (HelperException e) { logger.info("createAgreement exception", e); return buildResponse(e); } Response result = buildResponsePOST(HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The agreement has been stored successfully in the SLA Repository Database with location:"+location), location); logger.debug("EndOf createAgreement"); return result; }
[ "@", "POST", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_XML", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_XML", ")", "public", "Response", "createAgreement", "(", "@", "Context", "HttpHeaders", "hh", ",", "@", "Context", "UriInfo", "uri...
Creates a new agreement <pre> POST /agreements Request: POST /agreements HTTP/1.1 Accept: application/xml Response: HTTP/1.1 201 Created Content-type: application/xml Location: http://.../agreements/$uuid {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="201" message= "The agreement has been stored successfully in the SLA Repository Database"/> } </pre> Example: <li>curl -H "Content-type: application/xml" -d@agreement02.xml localhost:8080/sla-service/agreements -X POST</li> @return XML information with the different details of the agreement
[ "Creates", "a", "new", "agreement" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/AgreementRest.java#L246-L266
lightblueseas/jcommons-lang
src/main/java/de/alpharogroup/lang/AnnotationExtensions.java
AnnotationExtensions.isAnnotationPresentInSuperClassesOrInterfaces
public static boolean isAnnotationPresentInSuperClassesOrInterfaces( final Class<?> componentClass, final Class<? extends Annotation> annotationClass) { return getAnnotation(componentClass, annotationClass) != null; }
java
public static boolean isAnnotationPresentInSuperClassesOrInterfaces( final Class<?> componentClass, final Class<? extends Annotation> annotationClass) { return getAnnotation(componentClass, annotationClass) != null; }
[ "public", "static", "boolean", "isAnnotationPresentInSuperClassesOrInterfaces", "(", "final", "Class", "<", "?", ">", "componentClass", ",", "final", "Class", "<", "?", "extends", "Annotation", ">", "annotationClass", ")", "{", "return", "getAnnotation", "(", "compo...
Checks if is annotation present through making a lookup if the given annotation class is present in the given class or in one of the super classes. @param componentClass the component class @param annotationClass the annotation class @return true, if is annotation present
[ "Checks", "if", "is", "annotation", "present", "through", "making", "a", "lookup", "if", "the", "given", "annotation", "class", "is", "present", "in", "the", "given", "class", "or", "in", "one", "of", "the", "super", "classes", "." ]
train
https://github.com/lightblueseas/jcommons-lang/blob/000e1f198e949ec3e721fd0fc3f5946e945232a3/src/main/java/de/alpharogroup/lang/AnnotationExtensions.java#L249-L253
Carbonado/Carbonado
src/main/java/com/amazon/carbonado/filter/Filter.java
Filter.andNotExists
public final Filter<S> andNotExists(String propertyName, Filter<?> subFilter) { ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty(); return and(ExistsFilter.build(prop, subFilter, true)); }
java
public final Filter<S> andNotExists(String propertyName, Filter<?> subFilter) { ChainedProperty<S> prop = new FilterParser<S>(mType, propertyName).parseChainedProperty(); return and(ExistsFilter.build(prop, subFilter, true)); }
[ "public", "final", "Filter", "<", "S", ">", "andNotExists", "(", "String", "propertyName", ",", "Filter", "<", "?", ">", "subFilter", ")", "{", "ChainedProperty", "<", "S", ">", "prop", "=", "new", "FilterParser", "<", "S", ">", "(", "mType", ",", "pro...
Returns a combined filter instance that accepts records which are only accepted by this filter and the "not exists" test applied to a join. @param propertyName join property name, which may be a chained property @param subFilter sub-filter to apply to join, which may be null to test for any not existing @return canonical Filter instance @throws IllegalArgumentException if property is not found @since 1.2
[ "Returns", "a", "combined", "filter", "instance", "that", "accepts", "records", "which", "are", "only", "accepted", "by", "this", "filter", "and", "the", "not", "exists", "test", "applied", "to", "a", "join", "." ]
train
https://github.com/Carbonado/Carbonado/blob/eee29b365a61c8f03e1a1dc6bed0692e6b04b1db/src/main/java/com/amazon/carbonado/filter/Filter.java#L320-L323
jpush/jmessage-api-java-client
src/main/java/cn/jmessage/api/crossapp/CrossAppClient.java
CrossAppClient.setCrossNoDisturb
public ResponseWrapper setCrossNoDisturb(String username, CrossNoDisturb[] array) throws APIConnectionException, APIRequestException { StringUtils.checkUsername(username); CrossNoDisturbPayload payload = new CrossNoDisturbPayload.Builder() .setCrossNoDistrub(array) .build(); return _httpClient.sendPost(_baseUrl + crossUserPath + "/" + username + "/nodisturb", payload.toString()); }
java
public ResponseWrapper setCrossNoDisturb(String username, CrossNoDisturb[] array) throws APIConnectionException, APIRequestException { StringUtils.checkUsername(username); CrossNoDisturbPayload payload = new CrossNoDisturbPayload.Builder() .setCrossNoDistrub(array) .build(); return _httpClient.sendPost(_baseUrl + crossUserPath + "/" + username + "/nodisturb", payload.toString()); }
[ "public", "ResponseWrapper", "setCrossNoDisturb", "(", "String", "username", ",", "CrossNoDisturb", "[", "]", "array", ")", "throws", "APIConnectionException", ",", "APIRequestException", "{", "StringUtils", ".", "checkUsername", "(", "username", ")", ";", "CrossNoDis...
Set cross app no disturb https://docs.jiguang.cn/jmessage/server/rest_api_im/#api_1 @param username Necessary @param array CrossNoDisturb array @return No content @throws APIConnectionException connect exception @throws APIRequestException request exception
[ "Set", "cross", "app", "no", "disturb", "https", ":", "//", "docs", ".", "jiguang", ".", "cn", "/", "jmessage", "/", "server", "/", "rest_api_im", "/", "#api_1" ]
train
https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/crossapp/CrossAppClient.java#L132-L139
Azure/azure-sdk-for-java
storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java
StorageAccountsInner.listKeys
public StorageAccountListKeysResultInner listKeys(String resourceGroupName, String accountName) { return listKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); }
java
public StorageAccountListKeysResultInner listKeys(String resourceGroupName, String accountName) { return listKeysWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); }
[ "public", "StorageAccountListKeysResultInner", "listKeys", "(", "String", "resourceGroupName", ",", "String", "accountName", ")", "{", "return", "listKeysWithServiceResponseAsync", "(", "resourceGroupName", ",", "accountName", ")", ".", "toBlocking", "(", ")", ".", "sin...
Lists the access keys for the specified storage account. @param resourceGroupName The name of the resource group within the user's subscription. The name is case insensitive. @param accountName The name of the storage account within the specified resource group. Storage account names must be between 3 and 24 characters in length and use numbers and lower-case letters only. @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 StorageAccountListKeysResultInner object if successful.
[ "Lists", "the", "access", "keys", "for", "the", "specified", "storage", "account", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/storage/resource-manager/v2018_03_01_preview/src/main/java/com/microsoft/azure/management/storage/v2018_03_01_preview/implementation/StorageAccountsInner.java#L833-L835
liferay/com-liferay-commerce
commerce-tax-api/src/main/java/com/liferay/commerce/tax/model/CommerceTaxMethodWrapper.java
CommerceTaxMethodWrapper.getName
@Override public String getName(String languageId, boolean useDefault) { return _commerceTaxMethod.getName(languageId, useDefault); }
java
@Override public String getName(String languageId, boolean useDefault) { return _commerceTaxMethod.getName(languageId, useDefault); }
[ "@", "Override", "public", "String", "getName", "(", "String", "languageId", ",", "boolean", "useDefault", ")", "{", "return", "_commerceTaxMethod", ".", "getName", "(", "languageId", ",", "useDefault", ")", ";", "}" ]
Returns the localized name of this commerce tax method in the language, optionally using the default language if no localization exists for the requested language. @param languageId the ID of the language @param useDefault whether to use the default language if no localization exists for the requested language @return the localized name of this commerce tax method
[ "Returns", "the", "localized", "name", "of", "this", "commerce", "tax", "method", "in", "the", "language", "optionally", "using", "the", "default", "language", "if", "no", "localization", "exists", "for", "the", "requested", "language", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-tax-api/src/main/java/com/liferay/commerce/tax/model/CommerceTaxMethodWrapper.java#L374-L377
shrinkwrap/descriptors
metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/PackageInfo.java
PackageInfo.copyPackageInfo
public static void copyPackageInfo(final MetadataParserPath path, final Metadata metadata, final boolean verbose) throws IOException { for (final MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { if (descriptor.getPathToPackageInfoApi() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoApi()); final String destDirectory = path.pathToApi + File.separatorChar + descriptor.getPackageApi().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } if (descriptor.getPathToPackageInfoImpl() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoImpl()); final String destDirectory = path.pathToImpl + File.separatorChar + descriptor.getPackageImpl().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } } }
java
public static void copyPackageInfo(final MetadataParserPath path, final Metadata metadata, final boolean verbose) throws IOException { for (final MetadataDescriptor descriptor : metadata.getMetadataDescriptorList()) { if (descriptor.getPathToPackageInfoApi() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoApi()); final String destDirectory = path.pathToApi + File.separatorChar + descriptor.getPackageApi().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } if (descriptor.getPathToPackageInfoImpl() != null) { final File sourceFile = new File(descriptor.getPathToPackageInfoImpl()); final String destDirectory = path.pathToImpl + File.separatorChar + descriptor.getPackageImpl().replace('.', '/'); deleteExistingPackageInfo(destDirectory, verbose); copy(sourceFile, destDirectory, verbose); } } }
[ "public", "static", "void", "copyPackageInfo", "(", "final", "MetadataParserPath", "path", ",", "final", "Metadata", "metadata", ",", "final", "boolean", "verbose", ")", "throws", "IOException", "{", "for", "(", "final", "MetadataDescriptor", "descriptor", ":", "m...
Copies the optional packageInfo files into the packages. @param path @param metadata @throws IOException
[ "Copies", "the", "optional", "packageInfo", "files", "into", "the", "packages", "." ]
train
https://github.com/shrinkwrap/descriptors/blob/023ba080e6396b9f4dd8275dc4e5c0ebb6b5e6ba/metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/PackageInfo.java#L42-L58
adorsys/hbci4java-adorsys
src/main/java/org/kapott/hbci/callback/AbstractHBCICallback.java
AbstractHBCICallback.createDefaultLogLine
protected String createDefaultLogLine(String msg, int level, Date date, StackTraceElement trace) { String[] levels = {"NON", "ERR", "WRN", "INF", "DBG", "DB2", "INT"}; StringBuffer ret = new StringBuffer(128); ret.append("<").append(levels[level]).append("> "); SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS"); ret.append("[").append(df.format(date)).append("] "); Thread thread = Thread.currentThread(); ret.append("[").append(thread.getThreadGroup().getName()); ret.append("/").append(thread.getName()).append("] "); String classname = trace.getClassName(); String hbciname = "org.kapott.hbci."; if (classname != null && classname.startsWith(hbciname)) ret.append(classname.substring((hbciname).length())).append(": "); if (msg == null) msg = ""; StringBuffer escapedString = new StringBuffer(); int len = msg.length(); for (int i = 0; i < len; i++) { char ch = msg.charAt(i); int x = ch; if ((x < 26 && x != 9 && x != 10 && x != 13) || ch == '\\') { String temp = Integer.toString(x, 16); if (temp.length() != 2) temp = "0" + temp; escapedString.append("\\").append(temp); } else escapedString.append(ch); } ret.append(escapedString); return ret.toString(); }
java
protected String createDefaultLogLine(String msg, int level, Date date, StackTraceElement trace) { String[] levels = {"NON", "ERR", "WRN", "INF", "DBG", "DB2", "INT"}; StringBuffer ret = new StringBuffer(128); ret.append("<").append(levels[level]).append("> "); SimpleDateFormat df = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS"); ret.append("[").append(df.format(date)).append("] "); Thread thread = Thread.currentThread(); ret.append("[").append(thread.getThreadGroup().getName()); ret.append("/").append(thread.getName()).append("] "); String classname = trace.getClassName(); String hbciname = "org.kapott.hbci."; if (classname != null && classname.startsWith(hbciname)) ret.append(classname.substring((hbciname).length())).append(": "); if (msg == null) msg = ""; StringBuffer escapedString = new StringBuffer(); int len = msg.length(); for (int i = 0; i < len; i++) { char ch = msg.charAt(i); int x = ch; if ((x < 26 && x != 9 && x != 10 && x != 13) || ch == '\\') { String temp = Integer.toString(x, 16); if (temp.length() != 2) temp = "0" + temp; escapedString.append("\\").append(temp); } else escapedString.append(ch); } ret.append(escapedString); return ret.toString(); }
[ "protected", "String", "createDefaultLogLine", "(", "String", "msg", ",", "int", "level", ",", "Date", "date", ",", "StackTraceElement", "trace", ")", "{", "String", "[", "]", "levels", "=", "{", "\"NON\"", ",", "\"ERR\"", ",", "\"WRN\"", ",", "\"INF\"", "...
Erzeugt einen Log-Eintrag. Diese Methode wird von den mitgelieferten Callback-Klassen für die Erzeugung von Log-Einträgen verwendet. Um ein eigenes Format für die Log-Eintrage zu definieren, kann diese Methode mit einer eigenen Implementierung überschrieben werden.<br/> Die Parameter entsprechen denen der {@link HBCICallback#log(String, int, Date, StackTraceElement) log}-Methode @return ein Log-Eintrag
[ "Erzeugt", "einen", "Log", "-", "Eintrag", ".", "Diese", "Methode", "wird", "von", "den", "mitgelieferten", "Callback", "-", "Klassen", "für", "die", "Erzeugung", "von", "Log", "-", "Einträgen", "verwendet", ".", "Um", "ein", "eigenes", "Format", "für", "die...
train
https://github.com/adorsys/hbci4java-adorsys/blob/5e24f7e429d6b555e1d993196b4cf1adda6433cf/src/main/java/org/kapott/hbci/callback/AbstractHBCICallback.java#L37-L72
jglobus/JGlobus
gram/src/main/java/org/globus/rsl/RslAttributes.java
RslAttributes.setMulti
public void setMulti(String attribute, String [] values) { NameOpValue nv = getRelation(attribute); nv.clear(); List list = new LinkedList(); for (int i=0;i<values.length;i++) { list.add(new Value(values[i])); } nv.add(list); }
java
public void setMulti(String attribute, String [] values) { NameOpValue nv = getRelation(attribute); nv.clear(); List list = new LinkedList(); for (int i=0;i<values.length;i++) { list.add(new Value(values[i])); } nv.add(list); }
[ "public", "void", "setMulti", "(", "String", "attribute", ",", "String", "[", "]", "values", ")", "{", "NameOpValue", "nv", "=", "getRelation", "(", "attribute", ")", ";", "nv", ".", "clear", "(", ")", ";", "List", "list", "=", "new", "LinkedList", "("...
Sets the attribute value to the given list of values. The list of values is added as a single value. @param attribute the attribute to set the value of. @param values the list of values to add.
[ "Sets", "the", "attribute", "value", "to", "the", "given", "list", "of", "values", ".", "The", "list", "of", "values", "is", "added", "as", "a", "single", "value", "." ]
train
https://github.com/jglobus/JGlobus/blob/e14f6f6636544fd84298f9cec749d626ea971930/gram/src/main/java/org/globus/rsl/RslAttributes.java#L318-L326
Wootric/WootricSDK-Android
androidsdk/src/main/java/com/wootric/androidsdk/Wootric.java
Wootric.init
@Deprecated public static Wootric init(FragmentActivity fragmentActivity, String clientId, String clientSecret, String accountToken) { Wootric local = singleton; if(local == null) { synchronized (Wootric.class) { local = singleton; if(local == null) { checkNotNull(fragmentActivity, "FragmentActivity"); checkNotNull(clientId, "Client Id"); checkNotNull(clientSecret, "Client Secret"); checkNotNull(accountToken, "Account Token"); singleton = local = new Wootric(fragmentActivity, clientId, clientSecret, accountToken); } } } return local; }
java
@Deprecated public static Wootric init(FragmentActivity fragmentActivity, String clientId, String clientSecret, String accountToken) { Wootric local = singleton; if(local == null) { synchronized (Wootric.class) { local = singleton; if(local == null) { checkNotNull(fragmentActivity, "FragmentActivity"); checkNotNull(clientId, "Client Id"); checkNotNull(clientSecret, "Client Secret"); checkNotNull(accountToken, "Account Token"); singleton = local = new Wootric(fragmentActivity, clientId, clientSecret, accountToken); } } } return local; }
[ "@", "Deprecated", "public", "static", "Wootric", "init", "(", "FragmentActivity", "fragmentActivity", ",", "String", "clientId", ",", "String", "clientSecret", ",", "String", "accountToken", ")", "{", "Wootric", "local", "=", "singleton", ";", "if", "(", "local...
It configures the SDK with required parameters. @param fragmentActivity FragmentActivity where the survey will be presented. @param clientId Found in API section of the Wootric's admin panel. @param clientSecret Found in API section of the Wootric's admin panel. @param accountToken Found in Install section of the Wootric's admin panel.
[ "It", "configures", "the", "SDK", "with", "required", "parameters", "." ]
train
https://github.com/Wootric/WootricSDK-Android/blob/ba584f2317ce99452424b9a78d024e361ad6fec4/androidsdk/src/main/java/com/wootric/androidsdk/Wootric.java#L71-L88
JodaOrg/joda-time
src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java
DateTimeFormatterBuilder.appendTimeZoneShortName
public DateTimeFormatterBuilder appendTimeZoneShortName(Map<String, DateTimeZone> parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.SHORT_NAME, parseLookup); return append0(pp, pp); }
java
public DateTimeFormatterBuilder appendTimeZoneShortName(Map<String, DateTimeZone> parseLookup) { TimeZoneName pp = new TimeZoneName(TimeZoneName.SHORT_NAME, parseLookup); return append0(pp, pp); }
[ "public", "DateTimeFormatterBuilder", "appendTimeZoneShortName", "(", "Map", "<", "String", ",", "DateTimeZone", ">", "parseLookup", ")", "{", "TimeZoneName", "pp", "=", "new", "TimeZoneName", "(", "TimeZoneName", ".", "SHORT_NAME", ",", "parseLookup", ")", ";", "...
Instructs the printer to emit a short locale-specific time zone name, providing a lookup for parsing. Time zone names are not unique, thus the API forces you to supply the lookup. The names are searched in the order of the map, thus it is strongly recommended to use a {@code LinkedHashMap} or similar. @param parseLookup the table of names, null to use the {@link DateTimeUtils#getDefaultTimeZoneNames() default names} @return this DateTimeFormatterBuilder, for chaining
[ "Instructs", "the", "printer", "to", "emit", "a", "short", "locale", "-", "specific", "time", "zone", "name", "providing", "a", "lookup", "for", "parsing", ".", "Time", "zone", "names", "are", "not", "unique", "thus", "the", "API", "forces", "you", "to", ...
train
https://github.com/JodaOrg/joda-time/blob/bd79f1c4245e79b3c2c56d7b04fde2a6e191fa42/src/main/java/org/joda/time/format/DateTimeFormatterBuilder.java#L1057-L1060
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java
Validator.validateNotNull
public void validateNotNull(Object object, String name, String message) { if (object == null) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.NOTNULL_KEY.name(), name))); } }
java
public void validateNotNull(Object object, String name, String message) { if (object == null) { addError(name, Optional.ofNullable(message).orElse(messages.get(Validation.NOTNULL_KEY.name(), name))); } }
[ "public", "void", "validateNotNull", "(", "Object", "object", ",", "String", "name", ",", "String", "message", ")", "{", "if", "(", "object", "==", "null", ")", "{", "addError", "(", "name", ",", "Optional", ".", "ofNullable", "(", "message", ")", ".", ...
Validates a given object to be not null @param object The object to check @param name The name of the field to display the error message @param message A custom error message instead of the default one
[ "Validates", "a", "given", "object", "to", "be", "not", "null" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/routing/bindings/Validator.java#L476-L480
liyiorg/weixin-popular
src/main/java/weixin/popular/api/PayMchAPI.java
PayMchAPI.secapiPayProfitsharing
public static SecapiPayProfitsharingResult secapiPayProfitsharing(SecapiPayProfitsharing secapiPayProfitsharing,String key){ Map<String,String> map = MapUtil.objectToMap(secapiPayProfitsharing, "receivers"); if(secapiPayProfitsharing.getReceivers() != null){ map.put("receivers", JsonUtil.toJSONString(secapiPayProfitsharing.getReceivers())); } String sign = SignatureUtil.generateSign(map,secapiPayProfitsharing.getSign_type() == null? "HMAC-SHA256": secapiPayProfitsharing.getSign_type(),key); secapiPayProfitsharing.setSign(sign); String xml = XMLConverUtil.convertToXML(secapiPayProfitsharing); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI() + "/secapi/pay/profitsharing") .setEntity(new StringEntity(xml,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(secapiPayProfitsharing.getMch_id(), httpUriRequest,SecapiPayProfitsharingResult.class, secapiPayProfitsharing.getSign_type() == null? "HMAC-SHA256": secapiPayProfitsharing.getSign_type(),key); }
java
public static SecapiPayProfitsharingResult secapiPayProfitsharing(SecapiPayProfitsharing secapiPayProfitsharing,String key){ Map<String,String> map = MapUtil.objectToMap(secapiPayProfitsharing, "receivers"); if(secapiPayProfitsharing.getReceivers() != null){ map.put("receivers", JsonUtil.toJSONString(secapiPayProfitsharing.getReceivers())); } String sign = SignatureUtil.generateSign(map,secapiPayProfitsharing.getSign_type() == null? "HMAC-SHA256": secapiPayProfitsharing.getSign_type(),key); secapiPayProfitsharing.setSign(sign); String xml = XMLConverUtil.convertToXML(secapiPayProfitsharing); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI() + "/secapi/pay/profitsharing") .setEntity(new StringEntity(xml,Charset.forName("utf-8"))) .build(); return LocalHttpClient.keyStoreExecuteXmlResult(secapiPayProfitsharing.getMch_id(), httpUriRequest,SecapiPayProfitsharingResult.class, secapiPayProfitsharing.getSign_type() == null? "HMAC-SHA256": secapiPayProfitsharing.getSign_type(),key); }
[ "public", "static", "SecapiPayProfitsharingResult", "secapiPayProfitsharing", "(", "SecapiPayProfitsharing", "secapiPayProfitsharing", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "MapUtil", ".", "objectToMap", "(", "secapiPayP...
分账-请求单次分账 @since 2.8.25 @param secapiPayProfitsharing secapiPayProfitsharing @param key key @return SecapiPayProfitsharingResult
[ "分账", "-", "请求单次分账" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L733-L747
liferay/com-liferay-commerce
commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java
CPDefinitionOptionRelPersistenceImpl.findByGroupId
@Override public List<CPDefinitionOptionRel> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
java
@Override public List<CPDefinitionOptionRel> findByGroupId(long groupId) { return findByGroupId(groupId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); }
[ "@", "Override", "public", "List", "<", "CPDefinitionOptionRel", ">", "findByGroupId", "(", "long", "groupId", ")", "{", "return", "findByGroupId", "(", "groupId", ",", "QueryUtil", ".", "ALL_POS", ",", "QueryUtil", ".", "ALL_POS", ",", "null", ")", ";", "}"...
Returns all the cp definition option rels where groupId = &#63;. @param groupId the group ID @return the matching cp definition option rels
[ "Returns", "all", "the", "cp", "definition", "option", "rels", "where", "groupId", "=", "&#63", ";", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-product-service/src/main/java/com/liferay/commerce/product/service/persistence/impl/CPDefinitionOptionRelPersistenceImpl.java#L1524-L1527
vkostyukov/la4j
src/main/java/org/la4j/Vectors.java
Vectors.asModFunction
public static VectorFunction asModFunction(final double arg) { return new VectorFunction() { @Override public double evaluate(int i, double value) { return value % arg; } }; }
java
public static VectorFunction asModFunction(final double arg) { return new VectorFunction() { @Override public double evaluate(int i, double value) { return value % arg; } }; }
[ "public", "static", "VectorFunction", "asModFunction", "(", "final", "double", "arg", ")", "{", "return", "new", "VectorFunction", "(", ")", "{", "@", "Override", "public", "double", "evaluate", "(", "int", "i", ",", "double", "value", ")", "{", "return", ...
Creates a mod function that calculates the modulus of it's argument and given {@code value}. @param arg a divisor value @return a closure that does {@code _ % _}
[ "Creates", "a", "mod", "function", "that", "calculates", "the", "modulus", "of", "it", "s", "argument", "and", "given", "{", "@code", "value", "}", "." ]
train
https://github.com/vkostyukov/la4j/blob/dd1b917caf9606399a49afa6b0d738934cd3a7b3/src/main/java/org/la4j/Vectors.java#L218-L225
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbookDraftsInner.java
RunbookDraftsInner.beginReplaceContent
public String beginReplaceContent(String resourceGroupName, String automationAccountName, String runbookName, String runbookContent) { return beginReplaceContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, runbookContent).toBlocking().single().body(); }
java
public String beginReplaceContent(String resourceGroupName, String automationAccountName, String runbookName, String runbookContent) { return beginReplaceContentWithServiceResponseAsync(resourceGroupName, automationAccountName, runbookName, runbookContent).toBlocking().single().body(); }
[ "public", "String", "beginReplaceContent", "(", "String", "resourceGroupName", ",", "String", "automationAccountName", ",", "String", "runbookName", ",", "String", "runbookContent", ")", "{", "return", "beginReplaceContentWithServiceResponseAsync", "(", "resourceGroupName", ...
Replaces the runbook draft content. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @param runbookName The runbook name. @param runbookContent The runbook draft content. @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the String object if successful.
[ "Replaces", "the", "runbook", "draft", "content", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/RunbookDraftsInner.java#L275-L277
RoaringBitmap/RoaringBitmap
roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java
RoaringArray.appendCopiesAfter
protected void appendCopiesAfter(RoaringArray sa, short beforeStart) { int startLocation = sa.getIndex(beforeStart); if (startLocation >= 0) { startLocation++; } else { startLocation = -startLocation - 1; } extendArray(sa.size - startLocation); for (int i = startLocation; i < sa.size; ++i) { this.keys[this.size] = sa.keys[i]; this.values[this.size] = sa.values[i].clone(); this.size++; } }
java
protected void appendCopiesAfter(RoaringArray sa, short beforeStart) { int startLocation = sa.getIndex(beforeStart); if (startLocation >= 0) { startLocation++; } else { startLocation = -startLocation - 1; } extendArray(sa.size - startLocation); for (int i = startLocation; i < sa.size; ++i) { this.keys[this.size] = sa.keys[i]; this.values[this.size] = sa.values[i].clone(); this.size++; } }
[ "protected", "void", "appendCopiesAfter", "(", "RoaringArray", "sa", ",", "short", "beforeStart", ")", "{", "int", "startLocation", "=", "sa", ".", "getIndex", "(", "beforeStart", ")", ";", "if", "(", "startLocation", ">=", "0", ")", "{", "startLocation", "+...
Append copies of the values AFTER a specified key (may or may not be present) to end. @param sa other array @param beforeStart given key is the largest key that we won't copy
[ "Append", "copies", "of", "the", "values", "AFTER", "a", "specified", "key", "(", "may", "or", "may", "not", "be", "present", ")", "to", "end", "." ]
train
https://github.com/RoaringBitmap/RoaringBitmap/blob/b26fd0a1330fd4d2877f4d74feb69ceb812e9efa/roaringbitmap/src/main/java/org/roaringbitmap/RoaringArray.java#L153-L167
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/transaction/ConnectionResource.java
ConnectionResource.freeResource
@Override protected void freeResource() throws EFapsException { try { if (!getConnection().isClosed()) { getConnection().close(); } } catch (final SQLException e) { throw new EFapsException("Could not close", e); } }
java
@Override protected void freeResource() throws EFapsException { try { if (!getConnection().isClosed()) { getConnection().close(); } } catch (final SQLException e) { throw new EFapsException("Could not close", e); } }
[ "@", "Override", "protected", "void", "freeResource", "(", ")", "throws", "EFapsException", "{", "try", "{", "if", "(", "!", "getConnection", "(", ")", ".", "isClosed", "(", ")", ")", "{", "getConnection", "(", ")", ".", "close", "(", ")", ";", "}", ...
Frees the resource and gives this connection resource back to the context object. @throws EFapsException on error
[ "Frees", "the", "resource", "and", "gives", "this", "connection", "resource", "back", "to", "the", "context", "object", "." ]
train
https://github.com/eFaps/eFaps-Kernel/blob/04b96548f518c2386a93f5ec2b9349f9b9063859/src/main/java/org/efaps/db/transaction/ConnectionResource.java#L83-L94