repository_name
stringlengths
7
54
func_path_in_repository
stringlengths
18
218
func_name
stringlengths
5
140
whole_func_string
stringlengths
79
3.99k
language
stringclasses
1 value
func_code_string
stringlengths
79
3.99k
func_code_tokens
listlengths
20
624
func_documentation_string
stringlengths
61
1.96k
func_documentation_tokens
listlengths
1
478
split_name
stringclasses
1 value
func_code_url
stringlengths
107
339
NordicSemiconductor/Android-DFU-Library
dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java
BaseCustomDfuImpl.writePacket
private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) { byte[] locBuffer = buffer; if (size <= 0) // This should never happen return; if (buffer.length != size) { locBuffer = new byte[size]; System.arraycopy(buffer, 0, locBuffer, 0, size); } characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); characteristic.setValue(locBuffer); gatt.writeCharacteristic(characteristic); }
java
private void writePacket(final BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic, final byte[] buffer, final int size) { byte[] locBuffer = buffer; if (size <= 0) // This should never happen return; if (buffer.length != size) { locBuffer = new byte[size]; System.arraycopy(buffer, 0, locBuffer, 0, size); } characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); characteristic.setValue(locBuffer); gatt.writeCharacteristic(characteristic); }
[ "private", "void", "writePacket", "(", "final", "BluetoothGatt", "gatt", ",", "final", "BluetoothGattCharacteristic", "characteristic", ",", "final", "byte", "[", "]", "buffer", ",", "final", "int", "size", ")", "{", "byte", "[", "]", "locBuffer", "=", "buffer...
Writes the buffer to the characteristic. The maximum size of the buffer is dependent on MTU. This method is ASYNCHRONOUS and returns immediately after adding the data to TX queue. @param characteristic the characteristic to write to. Should be the DFU PACKET. @param buffer the buffer with 1-20 bytes. @param size the number of bytes from the buffer to send.
[ "Writes", "the", "buffer", "to", "the", "characteristic", ".", "The", "maximum", "size", "of", "the", "buffer", "is", "dependent", "on", "MTU", ".", "This", "method", "is", "ASYNCHRONOUS", "and", "returns", "immediately", "after", "adding", "the", "data", "t...
train
https://github.com/NordicSemiconductor/Android-DFU-Library/blob/ec14c8c522bebe801a9a4c3dfbbeb1f53262c03f/dfu/src/main/java/no/nordicsemi/android/dfu/BaseCustomDfuImpl.java#L412-L423
JDBDT/jdbdt
src/main/java/org/jdbdt/JDBDT.java
JDBDT.assertUnchanged
public static void assertUnchanged(String message, DataSource dataSource) throws DBAssertionError { DataSet emptyDataSet = empty(dataSource); DBAssert.deltaAssertion(CallInfo.create(message), emptyDataSet, emptyDataSet); }
java
public static void assertUnchanged(String message, DataSource dataSource) throws DBAssertionError { DataSet emptyDataSet = empty(dataSource); DBAssert.deltaAssertion(CallInfo.create(message), emptyDataSet, emptyDataSet); }
[ "public", "static", "void", "assertUnchanged", "(", "String", "message", ",", "DataSource", "dataSource", ")", "throws", "DBAssertionError", "{", "DataSet", "emptyDataSet", "=", "empty", "(", "dataSource", ")", ";", "DBAssert", ".", "deltaAssertion", "(", "CallInf...
Assert that no changes occurred for the given data source (error message variant). @param message Assertion error message. @param dataSource Data source. @throws DBAssertionError if the assertion fails. @see #assertDelta(DataSet,DataSet) @see #assertDeleted(String, DataSet) @see #assertInserted(String, DataSet)
[ "Assert", "that", "no", "changes", "occurred", "for", "the", "given", "data", "source", "(", "error", "message", "variant", ")", "." ]
train
https://github.com/JDBDT/jdbdt/blob/7e32845ad41dfbc5d6fd0fd561e3613697186df4/src/main/java/org/jdbdt/JDBDT.java#L383-L386
raphw/byte-buddy
byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java
Dynamic.ofInvocation
public static Dynamic ofInvocation(Method method, Object... rawArgument) { return ofInvocation(method, Arrays.asList(rawArgument)); }
java
public static Dynamic ofInvocation(Method method, Object... rawArgument) { return ofInvocation(method, Arrays.asList(rawArgument)); }
[ "public", "static", "Dynamic", "ofInvocation", "(", "Method", "method", ",", "Object", "...", "rawArgument", ")", "{", "return", "ofInvocation", "(", "method", ",", "Arrays", ".", "asList", "(", "rawArgument", ")", ")", ";", "}" ]
Represents a constant that is resolved by invoking a {@code static} factory method. @param method The method to invoke to create the represented constant value. @param rawArgument The method's constant arguments. @return A dynamic constant that is resolved by the supplied factory method.
[ "Represents", "a", "constant", "that", "is", "resolved", "by", "invoking", "a", "{", "@code", "static", "}", "factory", "method", "." ]
train
https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-dep/src/main/java/net/bytebuddy/utility/JavaConstant.java#L1520-L1522
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/auth/KeycloakAuthenticationStrategy.java
KeycloakAuthenticationStrategy.refreshToken
public OAuthAccessToken refreshToken(RequestContext requestContext, OAuthAccessToken token) { OAuthAccessToken result = token; String[] scopes = token.getScopes(); String tokenUrl = String.format("%s/realms/%s/protocol/openid-connect/token", getServerUrl(), getRealm()); HttpPost httpPost = new HttpPost(tokenUrl); try (CloseableHttpClient httpclient = HttpClients.createDefault()) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("client_id", getApiKey())); params.add(new BasicNameValuePair("client_secret", getApiSecret())); params.add(new BasicNameValuePair("grant_type", "refresh_token")); params.add(new BasicNameValuePair("refresh_token", token.getRefreshToken())); httpPost.setEntity(new UrlEncodedFormEntity(params)); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); ObjectMapper objectMapper = new ObjectMapper(); try (InputStream stream = entity.getContent()) { RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(stream, RefreshTokenResponse.class); Date expiresAt = getExpiresAt(refreshTokenResponse.getExpiresIn()); result = new OAuthAccessToken(token.getExternalId(), refreshTokenResponse.getAccessToken(), refreshTokenResponse.getRefreshToken(), expiresAt, scopes); AuthUtils.purgeOAuthAccessTokens(requestContext, getName()); AuthUtils.storeOAuthAccessToken(requestContext, getName(), result); } EntityUtils.consume(entity); } else { logger.log(Level.WARNING, String.format("Failed to refresh access token with message [%d]: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } } } catch (IOException e) { logger.log(Level.WARNING, "Failed to refresh access token", e); } return result; }
java
public OAuthAccessToken refreshToken(RequestContext requestContext, OAuthAccessToken token) { OAuthAccessToken result = token; String[] scopes = token.getScopes(); String tokenUrl = String.format("%s/realms/%s/protocol/openid-connect/token", getServerUrl(), getRealm()); HttpPost httpPost = new HttpPost(tokenUrl); try (CloseableHttpClient httpclient = HttpClients.createDefault()) { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("client_id", getApiKey())); params.add(new BasicNameValuePair("client_secret", getApiSecret())); params.add(new BasicNameValuePair("grant_type", "refresh_token")); params.add(new BasicNameValuePair("refresh_token", token.getRefreshToken())); httpPost.setEntity(new UrlEncodedFormEntity(params)); try (CloseableHttpResponse response = httpclient.execute(httpPost)) { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() == 200) { HttpEntity entity = response.getEntity(); ObjectMapper objectMapper = new ObjectMapper(); try (InputStream stream = entity.getContent()) { RefreshTokenResponse refreshTokenResponse = objectMapper.readValue(stream, RefreshTokenResponse.class); Date expiresAt = getExpiresAt(refreshTokenResponse.getExpiresIn()); result = new OAuthAccessToken(token.getExternalId(), refreshTokenResponse.getAccessToken(), refreshTokenResponse.getRefreshToken(), expiresAt, scopes); AuthUtils.purgeOAuthAccessTokens(requestContext, getName()); AuthUtils.storeOAuthAccessToken(requestContext, getName(), result); } EntityUtils.consume(entity); } else { logger.log(Level.WARNING, String.format("Failed to refresh access token with message [%d]: %s", statusLine.getStatusCode(), statusLine.getReasonPhrase())); } } } catch (IOException e) { logger.log(Level.WARNING, "Failed to refresh access token", e); } return result; }
[ "public", "OAuthAccessToken", "refreshToken", "(", "RequestContext", "requestContext", ",", "OAuthAccessToken", "token", ")", "{", "OAuthAccessToken", "result", "=", "token", ";", "String", "[", "]", "scopes", "=", "token", ".", "getScopes", "(", ")", ";", "Stri...
Refreshes the access token @param requestContext request context @param token token @return refreshed token
[ "Refreshes", "the", "access", "token" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/auth/KeycloakAuthenticationStrategy.java#L148-L189
netty/netty
handler/src/main/java/io/netty/handler/ssl/SslHandler.java
SslHandler.allocateOutNetBuf
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) { return allocate(ctx, engineType.calculateWrapBufferCapacity(this, pendingBytes, numComponents)); }
java
private ByteBuf allocateOutNetBuf(ChannelHandlerContext ctx, int pendingBytes, int numComponents) { return allocate(ctx, engineType.calculateWrapBufferCapacity(this, pendingBytes, numComponents)); }
[ "private", "ByteBuf", "allocateOutNetBuf", "(", "ChannelHandlerContext", "ctx", ",", "int", "pendingBytes", ",", "int", "numComponents", ")", "{", "return", "allocate", "(", "ctx", ",", "engineType", ".", "calculateWrapBufferCapacity", "(", "this", ",", "pendingByte...
Allocates an outbound network buffer for {@link SSLEngine#wrap(ByteBuffer, ByteBuffer)} which can encrypt the specified amount of pending bytes.
[ "Allocates", "an", "outbound", "network", "buffer", "for", "{" ]
train
https://github.com/netty/netty/blob/ba06eafa1c1824bd154f1a380019e7ea2edf3c4c/handler/src/main/java/io/netty/handler/ssl/SslHandler.java#L2133-L2135
mgm-tp/jfunk
jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java
ResourceLoader.getInputStreamReader
public static InputStreamReader getInputStreamReader(final File resource, final String encoding) throws IOException { return new InputStreamReader(getInputStream(resource), encoding); }
java
public static InputStreamReader getInputStreamReader(final File resource, final String encoding) throws IOException { return new InputStreamReader(getInputStream(resource), encoding); }
[ "public", "static", "InputStreamReader", "getInputStreamReader", "(", "final", "File", "resource", ",", "final", "String", "encoding", ")", "throws", "IOException", "{", "return", "new", "InputStreamReader", "(", "getInputStream", "(", "resource", ")", ",", "encodin...
Loads a resource as {@link InputStreamReader}. @param resource The resource to be loaded. @param encoding The encoding to use @return The reader
[ "Loads", "a", "resource", "as", "{", "@link", "InputStreamReader", "}", "." ]
train
https://github.com/mgm-tp/jfunk/blob/5b9fecac5778b988bb458085ded39ea9a4c7c2ae/jfunk-common/src/main/java/com/mgmtp/jfunk/common/util/ResourceLoader.java#L283-L285
OpenTSDB/opentsdb
src/core/Tags.java
Tags.validateString
public static void validateString(final String what, final String s) { if (s == null) { throw new IllegalArgumentException("Invalid " + what + ": null"); } else if ("".equals(s)) { throw new IllegalArgumentException("Invalid " + what + ": empty string"); } final int n = s.length(); for (int i = 0; i < n; i++) { final char c = s.charAt(i); if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '-' || c == '_' || c == '.' || c == '/' || Character.isLetter(c) || isAllowSpecialChars(c))) { throw new IllegalArgumentException("Invalid " + what + " (\"" + s + "\"): illegal character: " + c); } } }
java
public static void validateString(final String what, final String s) { if (s == null) { throw new IllegalArgumentException("Invalid " + what + ": null"); } else if ("".equals(s)) { throw new IllegalArgumentException("Invalid " + what + ": empty string"); } final int n = s.length(); for (int i = 0; i < n; i++) { final char c = s.charAt(i); if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '-' || c == '_' || c == '.' || c == '/' || Character.isLetter(c) || isAllowSpecialChars(c))) { throw new IllegalArgumentException("Invalid " + what + " (\"" + s + "\"): illegal character: " + c); } } }
[ "public", "static", "void", "validateString", "(", "final", "String", "what", ",", "final", "String", "s", ")", "{", "if", "(", "s", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Invalid \"", "+", "what", "+", "\": null\"", ")...
Ensures that a given string is a valid metric name or tag name/value. @param what A human readable description of what's being validated. @param s The string to validate. @throws IllegalArgumentException if the string isn't valid.
[ "Ensures", "that", "a", "given", "string", "is", "a", "valid", "metric", "name", "or", "tag", "name", "/", "value", "." ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/core/Tags.java#L549-L565
legsem/legstar.avro
legstar.avro.cob2avro.hadoop/src/main/java/com/legstar/avro/cob2avro/hadoop/mapreduce/Cob2AvroJob.java
Cob2AvroJob.setInputRecordMatcher
public static void setInputRecordMatcher(Job job, Class<? extends CobolTypeFinder> matcherClass) { job.getConfiguration().setClass(CONF_INPUT_RECORD_MATCHER_CLASS, matcherClass, CobolTypeFinder.class); }
java
public static void setInputRecordMatcher(Job job, Class<? extends CobolTypeFinder> matcherClass) { job.getConfiguration().setClass(CONF_INPUT_RECORD_MATCHER_CLASS, matcherClass, CobolTypeFinder.class); }
[ "public", "static", "void", "setInputRecordMatcher", "(", "Job", "job", ",", "Class", "<", "?", "extends", "CobolTypeFinder", ">", "matcherClass", ")", "{", "job", ".", "getConfiguration", "(", ")", ".", "setClass", "(", "CONF_INPUT_RECORD_MATCHER_CLASS", ",", "...
Sets the job input record matcher class. @param job The job to configure. @param matcherClass The input record matcher class.
[ "Sets", "the", "job", "input", "record", "matcher", "class", "." ]
train
https://github.com/legsem/legstar.avro/blob/bad5e0bf41700951eee1ad6a5d6d0c47b3da8f0b/legstar.avro.cob2avro.hadoop/src/main/java/com/legstar/avro/cob2avro/hadoop/mapreduce/Cob2AvroJob.java#L80-L82
strator-dev/greenpepper
greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java
ConfluenceGreenPepper.saveImplementedVersion
public void saveImplementedVersion(Page page, Integer version) { Integer previousImplementedVersion = getImplementedVersion(page); if (previousImplementedVersion != null && version != null && previousImplementedVersion == version) return; if (previousImplementedVersion != null) savePreviousImplementedVersion(page, previousImplementedVersion); String value = version != null ? String.valueOf(version) : null; ContentEntityObject entityObject = getContentEntityManager().getById(page.getId()); getContentPropertyManager().setStringProperty(entityObject, IMPLEMENTED_VERSION, value); }
java
public void saveImplementedVersion(Page page, Integer version) { Integer previousImplementedVersion = getImplementedVersion(page); if (previousImplementedVersion != null && version != null && previousImplementedVersion == version) return; if (previousImplementedVersion != null) savePreviousImplementedVersion(page, previousImplementedVersion); String value = version != null ? String.valueOf(version) : null; ContentEntityObject entityObject = getContentEntityManager().getById(page.getId()); getContentPropertyManager().setStringProperty(entityObject, IMPLEMENTED_VERSION, value); }
[ "public", "void", "saveImplementedVersion", "(", "Page", "page", ",", "Integer", "version", ")", "{", "Integer", "previousImplementedVersion", "=", "getImplementedVersion", "(", "page", ")", ";", "if", "(", "previousImplementedVersion", "!=", "null", "&&", "version"...
Saves the sprecified version as the Iimplemented version @param page a {@link com.atlassian.confluence.pages.Page} object. @param version a {@link java.lang.Integer} object.
[ "Saves", "the", "sprecified", "version", "as", "the", "Iimplemented", "version" ]
train
https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L611-L622
jmapper-framework/jmapper-core
JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java
XML.deleteAttributes
public XML deleteAttributes(Class<?> aClass,String[] attributes){ checksAttributesExistence(aClass,attributes); if(isEmpty(findXmlClass(aClass).attributes) || findXmlClass(aClass).attributes.size()<=1) Error.xmlWrongMethod(aClass); for (String attributeName : attributes) { XmlAttribute attribute = null; for (XmlAttribute xmlAttribute : findXmlClass(aClass).attributes) if(xmlAttribute.name.equals(attributeName)) attribute = xmlAttribute; if(attribute == null) Error.xmlAttributeInexistent(this.xmlPath,attributeName,aClass); findXmlClass(aClass).attributes.remove(attribute); } return this; }
java
public XML deleteAttributes(Class<?> aClass,String[] attributes){ checksAttributesExistence(aClass,attributes); if(isEmpty(findXmlClass(aClass).attributes) || findXmlClass(aClass).attributes.size()<=1) Error.xmlWrongMethod(aClass); for (String attributeName : attributes) { XmlAttribute attribute = null; for (XmlAttribute xmlAttribute : findXmlClass(aClass).attributes) if(xmlAttribute.name.equals(attributeName)) attribute = xmlAttribute; if(attribute == null) Error.xmlAttributeInexistent(this.xmlPath,attributeName,aClass); findXmlClass(aClass).attributes.remove(attribute); } return this; }
[ "public", "XML", "deleteAttributes", "(", "Class", "<", "?", ">", "aClass", ",", "String", "[", "]", "attributes", ")", "{", "checksAttributesExistence", "(", "aClass", ",", "attributes", ")", ";", "if", "(", "isEmpty", "(", "findXmlClass", "(", "aClass", ...
This method deletes the attributes to an existing Class. @param aClass class to which delete the attributes @param attributes attributes to delete @return this instance of XML
[ "This", "method", "deletes", "the", "attributes", "to", "an", "existing", "Class", "." ]
train
https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/xml/XML.java#L349-L366
igniterealtime/Smack
smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java
PacketParserUtils.parseContent
public static CharSequence parseContent(XmlPullParser parser) throws XmlPullParserException, IOException { assert (parser.getEventType() == XmlPullParser.START_TAG); if (parser.isEmptyElementTag()) { return ""; } // Advance the parser, since we want to parse the content of the current element parser.next(); return parseContentDepth(parser, parser.getDepth(), false); }
java
public static CharSequence parseContent(XmlPullParser parser) throws XmlPullParserException, IOException { assert (parser.getEventType() == XmlPullParser.START_TAG); if (parser.isEmptyElementTag()) { return ""; } // Advance the parser, since we want to parse the content of the current element parser.next(); return parseContentDepth(parser, parser.getDepth(), false); }
[ "public", "static", "CharSequence", "parseContent", "(", "XmlPullParser", "parser", ")", "throws", "XmlPullParserException", ",", "IOException", "{", "assert", "(", "parser", ".", "getEventType", "(", ")", "==", "XmlPullParser", ".", "START_TAG", ")", ";", "if", ...
Returns the content of a element. <p> The parser must be positioned on the START_TAG of the element which content is going to get returned. If the current element is the empty element, then the empty string is returned. If it is a element which contains just text, then just the text is returned. If it contains nested elements (and text), then everything from the current opening tag to the corresponding closing tag of the same depth is returned as String. </p> Note that only the outermost namespace attributes ("xmlns") will be returned, not nested ones. @param parser the XML pull parser @return the content of a tag @throws XmlPullParserException if parser encounters invalid XML @throws IOException if an IO error occurs
[ "Returns", "the", "content", "of", "a", "element", ".", "<p", ">", "The", "parser", "must", "be", "positioned", "on", "the", "START_TAG", "of", "the", "element", "which", "content", "is", "going", "to", "get", "returned", ".", "If", "the", "current", "el...
train
https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-core/src/main/java/org/jivesoftware/smack/util/PacketParserUtils.java#L382-L391
paymill/paymill-java
src/main/java/com/paymill/services/PreauthorizationService.java
PreauthorizationService.createWithPayment
public Preauthorization createWithPayment( final Payment payment, final Integer amount, final String currency, final String description ) { ValidationUtils.validatesPayment( payment ); ValidationUtils.validatesAmount( amount ); ValidationUtils.validatesCurrency( currency ); ParameterMap<String, String> params = new ParameterMap<String, String>(); params.add( "payment", payment.getId() ); params.add( "amount", String.valueOf( amount ) ); params.add( "currency", currency ); params.add( "source", String.format( "%s-%s", PaymillContext.getProjectName(), PaymillContext.getProjectVersion() ) ); if( StringUtils.isNotBlank( description ) ) params.add( "description", description ); return RestfulUtils.create( PreauthorizationService.PATH, params, Preauthorization.class, super.httpClient ); }
java
public Preauthorization createWithPayment( final Payment payment, final Integer amount, final String currency, final String description ) { ValidationUtils.validatesPayment( payment ); ValidationUtils.validatesAmount( amount ); ValidationUtils.validatesCurrency( currency ); ParameterMap<String, String> params = new ParameterMap<String, String>(); params.add( "payment", payment.getId() ); params.add( "amount", String.valueOf( amount ) ); params.add( "currency", currency ); params.add( "source", String.format( "%s-%s", PaymillContext.getProjectName(), PaymillContext.getProjectVersion() ) ); if( StringUtils.isNotBlank( description ) ) params.add( "description", description ); return RestfulUtils.create( PreauthorizationService.PATH, params, Preauthorization.class, super.httpClient ); }
[ "public", "Preauthorization", "createWithPayment", "(", "final", "Payment", "payment", ",", "final", "Integer", "amount", ",", "final", "String", "currency", ",", "final", "String", "description", ")", "{", "ValidationUtils", ".", "validatesPayment", "(", "payment",...
Authorizes the given amount with the given {@link Payment}. <strong>Works only for credit cards. Direct debit not supported.</strong> @param payment The {@link Payment} itself (only creditcard-object) @param amount Amount (in cents) which will be charged. @param currency ISO 4217 formatted currency code. @param description A short description for the preauthorization. @return {@link Transaction} object with the {@link Preauthorization} as sub object.
[ "Authorizes", "the", "given", "amount", "with", "the", "given", "{", "@link", "Payment", "}", "." ]
train
https://github.com/paymill/paymill-java/blob/17281a0d4376c76f1711af9f09bfc138c90ba65a/src/main/java/com/paymill/services/PreauthorizationService.java#L173-L189
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java
ComputerVisionImpl.tagImageInStreamAsync
public Observable<TagResult> tagImageInStreamAsync(byte[] image, TagImageInStreamOptionalParameter tagImageInStreamOptionalParameter) { return tagImageInStreamWithServiceResponseAsync(image, tagImageInStreamOptionalParameter).map(new Func1<ServiceResponse<TagResult>, TagResult>() { @Override public TagResult call(ServiceResponse<TagResult> response) { return response.body(); } }); }
java
public Observable<TagResult> tagImageInStreamAsync(byte[] image, TagImageInStreamOptionalParameter tagImageInStreamOptionalParameter) { return tagImageInStreamWithServiceResponseAsync(image, tagImageInStreamOptionalParameter).map(new Func1<ServiceResponse<TagResult>, TagResult>() { @Override public TagResult call(ServiceResponse<TagResult> response) { return response.body(); } }); }
[ "public", "Observable", "<", "TagResult", ">", "tagImageInStreamAsync", "(", "byte", "[", "]", "image", ",", "TagImageInStreamOptionalParameter", "tagImageInStreamOptionalParameter", ")", "{", "return", "tagImageInStreamWithServiceResponseAsync", "(", "image", ",", "tagImag...
This operation generates a list of words, or tags, that are relevant to the content of the supplied image. The Computer Vision API can return tags based on objects, living beings, scenery or actions found in images. Unlike categories, tags are not organized according to a hierarchical classification system, but correspond to image content. Tags may contain hints to avoid ambiguity or provide context, for example the tag 'cello' may be accompanied by the hint 'musical instrument'. All tags are in English. @param image An image stream. @param tagImageInStreamOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the TagResult object
[ "This", "operation", "generates", "a", "list", "of", "words", "or", "tags", "that", "are", "relevant", "to", "the", "content", "of", "the", "supplied", "image", ".", "The", "Computer", "Vision", "API", "can", "return", "tags", "based", "on", "objects", "li...
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L451-L458
alkacon/opencms-core
src/org/opencms/workplace/CmsDialog.java
CmsDialog.includeErrorpage
public void includeErrorpage(CmsWorkplace wp, Throwable t) throws JspException { CmsLog.getLog(wp).error(Messages.get().getBundle().key(Messages.ERR_WORKPLACE_DIALOG_0), t); getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, wp); getJsp().getRequest().setAttribute(ATTRIBUTE_THROWABLE, t); getJsp().include(FILE_DIALOG_SCREEN_ERRORPAGE); }
java
public void includeErrorpage(CmsWorkplace wp, Throwable t) throws JspException { CmsLog.getLog(wp).error(Messages.get().getBundle().key(Messages.ERR_WORKPLACE_DIALOG_0), t); getJsp().getRequest().setAttribute(SESSION_WORKPLACE_CLASS, wp); getJsp().getRequest().setAttribute(ATTRIBUTE_THROWABLE, t); getJsp().include(FILE_DIALOG_SCREEN_ERRORPAGE); }
[ "public", "void", "includeErrorpage", "(", "CmsWorkplace", "wp", ",", "Throwable", "t", ")", "throws", "JspException", "{", "CmsLog", ".", "getLog", "(", "wp", ")", ".", "error", "(", "Messages", ".", "get", "(", ")", ".", "getBundle", "(", ")", ".", "...
Displays the throwable on the error page and logs the error.<p> @param wp the workplace class @param t the throwable to be displayed on the error page @throws JspException if the include of the error page jsp fails
[ "Displays", "the", "throwable", "on", "the", "error", "page", "and", "logs", "the", "error", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/workplace/CmsDialog.java#L1419-L1425
phax/ph-commons
ph-json/src/main/java/com/helger/json/serialize/JsonReader.java
JsonReader.readFromStream
@Nullable public static IJson readFromStream (@Nonnull final InputStream aIS, @Nonnull final Charset aFallbackCharset, @Nullable final IJsonParseExceptionCallback aCustomExceptionCallback) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aFallbackCharset, "FallbackCharset"); try { final Reader aReader = CharsetHelper.getReaderByBOM (aIS, aFallbackCharset); return readJson (aReader, (IJsonParserCustomizeCallback) null, aCustomExceptionCallback); } finally { StreamHelper.close (aIS); } }
java
@Nullable public static IJson readFromStream (@Nonnull final InputStream aIS, @Nonnull final Charset aFallbackCharset, @Nullable final IJsonParseExceptionCallback aCustomExceptionCallback) { ValueEnforcer.notNull (aIS, "InputStream"); ValueEnforcer.notNull (aFallbackCharset, "FallbackCharset"); try { final Reader aReader = CharsetHelper.getReaderByBOM (aIS, aFallbackCharset); return readJson (aReader, (IJsonParserCustomizeCallback) null, aCustomExceptionCallback); } finally { StreamHelper.close (aIS); } }
[ "@", "Nullable", "public", "static", "IJson", "readFromStream", "(", "@", "Nonnull", "final", "InputStream", "aIS", ",", "@", "Nonnull", "final", "Charset", "aFallbackCharset", ",", "@", "Nullable", "final", "IJsonParseExceptionCallback", "aCustomExceptionCallback", "...
Read the Json from the passed {@link InputStream}. @param aIS The input stream to use. May not be <code>null</code>. @param aFallbackCharset The charset to be used in case no BOM is present. May not be <code>null</code>. @param aCustomExceptionCallback An optional custom exception handler that can be used to collect the unrecoverable parsing errors. May be <code>null</code>. @return <code>null</code> if reading failed, the Json declarations otherwise.
[ "Read", "the", "Json", "from", "the", "passed", "{", "@link", "InputStream", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-json/src/main/java/com/helger/json/serialize/JsonReader.java#L676-L693
scala/scala
src/library/scala/runtime/BoxesRunTime.java
BoxesRunTime.equals2
public static boolean equals2(Object x, Object y) { if (x instanceof java.lang.Number) return equalsNumObject((java.lang.Number)x, y); if (x instanceof java.lang.Character) return equalsCharObject((java.lang.Character)x, y); if (x == null) return y == null; return x.equals(y); }
java
public static boolean equals2(Object x, Object y) { if (x instanceof java.lang.Number) return equalsNumObject((java.lang.Number)x, y); if (x instanceof java.lang.Character) return equalsCharObject((java.lang.Character)x, y); if (x == null) return y == null; return x.equals(y); }
[ "public", "static", "boolean", "equals2", "(", "Object", "x", ",", "Object", "y", ")", "{", "if", "(", "x", "instanceof", "java", ".", "lang", ".", "Number", ")", "return", "equalsNumObject", "(", "(", "java", ".", "lang", ".", "Number", ")", "x", ",...
Since all applicable logic has to be present in the equals method of a ScalaNumber in any case, we dispatch to it as soon as we spot one on either side.
[ "Since", "all", "applicable", "logic", "has", "to", "be", "present", "in", "the", "equals", "method", "of", "a", "ScalaNumber", "in", "any", "case", "we", "dispatch", "to", "it", "as", "soon", "as", "we", "spot", "one", "on", "either", "side", "." ]
train
https://github.com/scala/scala/blob/bec2441a24cbf3159a1118049b857a5ae7c452eb/src/library/scala/runtime/BoxesRunTime.java#L126-L135
jenkinsci/java-client-api
jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java
JenkinsServer.deleteJob
public JenkinsServer deleteJob(FolderJob folder, String jobName, boolean crumbFlag) throws IOException { client.post(UrlUtils.toJobBaseUrl(folder, jobName) + "/doDelete", crumbFlag); return this; }
java
public JenkinsServer deleteJob(FolderJob folder, String jobName, boolean crumbFlag) throws IOException { client.post(UrlUtils.toJobBaseUrl(folder, jobName) + "/doDelete", crumbFlag); return this; }
[ "public", "JenkinsServer", "deleteJob", "(", "FolderJob", "folder", ",", "String", "jobName", ",", "boolean", "crumbFlag", ")", "throws", "IOException", "{", "client", ".", "post", "(", "UrlUtils", ".", "toJobBaseUrl", "(", "folder", ",", "jobName", ")", "+", ...
Delete a job from Jenkins within a folder. @param folder The folder where the given job is located. @param jobName The job which should be deleted. @param crumbFlag The crumbFlag @throws IOException in case of problems.
[ "Delete", "a", "job", "from", "Jenkins", "within", "a", "folder", "." ]
train
https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L704-L707
groovy/groovy-core
src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java
StaticTypeCheckingSupport.buildParameter
private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) { if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) { return methodParameter; } if (paramType.isArray()) { ClassNode componentType = paramType.getComponentType(); Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName()); Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType); return new Parameter(component.getType().makeArray(), component.getName()); } ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType); return new Parameter(resolved, methodParameter.getName()); }
java
private static Parameter buildParameter(final Map<String, GenericsType> genericFromReceiver, final Map<String, GenericsType> placeholdersFromContext, final Parameter methodParameter, final ClassNode paramType) { if (genericFromReceiver.isEmpty() && (placeholdersFromContext==null||placeholdersFromContext.isEmpty())) { return methodParameter; } if (paramType.isArray()) { ClassNode componentType = paramType.getComponentType(); Parameter subMethodParameter = new Parameter(componentType, methodParameter.getName()); Parameter component = buildParameter(genericFromReceiver, placeholdersFromContext, subMethodParameter, componentType); return new Parameter(component.getType().makeArray(), component.getName()); } ClassNode resolved = resolveClassNodeGenerics(genericFromReceiver, placeholdersFromContext, paramType); return new Parameter(resolved, methodParameter.getName()); }
[ "private", "static", "Parameter", "buildParameter", "(", "final", "Map", "<", "String", ",", "GenericsType", ">", "genericFromReceiver", ",", "final", "Map", "<", "String", ",", "GenericsType", ">", "placeholdersFromContext", ",", "final", "Parameter", "methodParame...
Given a parameter, builds a new parameter for which the known generics placeholders are resolved. @param genericFromReceiver resolved generics from the receiver of the message @param placeholdersFromContext, resolved generics from the method context @param methodParameter the method parameter for which we want to resolve generic types @param paramType the (unresolved) type of the method parameter @return a new parameter with the same name and type as the original one, but with resolved generic types
[ "Given", "a", "parameter", "builds", "a", "new", "parameter", "for", "which", "the", "known", "generics", "placeholders", "are", "resolved", "." ]
train
https://github.com/groovy/groovy-core/blob/01309f9d4be34ddf93c4a9943b5a97843bff6181/src/main/org/codehaus/groovy/transform/stc/StaticTypeCheckingSupport.java#L1170-L1183
camunda/camunda-xml-model
src/main/java/org/camunda/bpm/model/xml/impl/parser/AbstractModelParser.java
AbstractModelParser.validateModel
public void validateModel(DomDocument document) { Schema schema = getSchema(document); if (schema == null) { return; } Validator validator = schema.newValidator(); try { synchronized(document) { validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (SAXException e) { throw new ModelValidationException("DOM document is not valid", e); } }
java
public void validateModel(DomDocument document) { Schema schema = getSchema(document); if (schema == null) { return; } Validator validator = schema.newValidator(); try { synchronized(document) { validator.validate(document.getDomSource()); } } catch (IOException e) { throw new ModelValidationException("Error during DOM document validation", e); } catch (SAXException e) { throw new ModelValidationException("DOM document is not valid", e); } }
[ "public", "void", "validateModel", "(", "DomDocument", "document", ")", "{", "Schema", "schema", "=", "getSchema", "(", "document", ")", ";", "if", "(", "schema", "==", "null", ")", "{", "return", ";", "}", "Validator", "validator", "=", "schema", ".", "...
Validate DOM document @param document the DOM document to validate
[ "Validate", "DOM", "document" ]
train
https://github.com/camunda/camunda-xml-model/blob/85b3f879e26d063f71c94cfd21ac17d9ff6baf4d/src/main/java/org/camunda/bpm/model/xml/impl/parser/AbstractModelParser.java#L121-L139
jeremylong/DependencyCheck
core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java
OpenSSLAnalyzer.analyzeDependency
@Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File file = dependency.getActualFile(); final String parentName = file.getParentFile().getName(); boolean found = false; final String contents = getFileContents(file); if (!contents.isEmpty()) { final Matcher matcher = VERSION_PATTERN.matcher(contents); if (matcher.find()) { found = true; final String version = getOpenSSLVersion(Long.parseLong(matcher.group(1), HEXADECIMAL)); dependency.addEvidence(EvidenceType.VERSION, OPENSSLV_H, "Version Constant", version, Confidence.HIGH); try { final PackageURL purl = PackageURLBuilder.aPackageURL().withType("generic") .withName("openssl").withVersion(version).build(); dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST)); } catch (MalformedPackageURLException ex) { LOGGER.debug("Unable to build package url for openssl", ex); final GenericIdentifier id = new GenericIdentifier("generic:openssl@" + version, Confidence.HIGHEST); dependency.addSoftwareIdentifier(id); } } } if (found) { dependency.setDisplayFileName(parentName + File.separatorChar + OPENSSLV_H); dependency.addEvidence(EvidenceType.VENDOR, OPENSSLV_H, "Vendor", "OpenSSL", Confidence.HIGHEST); dependency.addEvidence(EvidenceType.PRODUCT, OPENSSLV_H, "Product", "OpenSSL", Confidence.HIGHEST); } else { engine.removeDependency(dependency); } }
java
@Override protected void analyzeDependency(Dependency dependency, Engine engine) throws AnalysisException { final File file = dependency.getActualFile(); final String parentName = file.getParentFile().getName(); boolean found = false; final String contents = getFileContents(file); if (!contents.isEmpty()) { final Matcher matcher = VERSION_PATTERN.matcher(contents); if (matcher.find()) { found = true; final String version = getOpenSSLVersion(Long.parseLong(matcher.group(1), HEXADECIMAL)); dependency.addEvidence(EvidenceType.VERSION, OPENSSLV_H, "Version Constant", version, Confidence.HIGH); try { final PackageURL purl = PackageURLBuilder.aPackageURL().withType("generic") .withName("openssl").withVersion(version).build(); dependency.addSoftwareIdentifier(new PurlIdentifier(purl, Confidence.HIGHEST)); } catch (MalformedPackageURLException ex) { LOGGER.debug("Unable to build package url for openssl", ex); final GenericIdentifier id = new GenericIdentifier("generic:openssl@" + version, Confidence.HIGHEST); dependency.addSoftwareIdentifier(id); } } } if (found) { dependency.setDisplayFileName(parentName + File.separatorChar + OPENSSLV_H); dependency.addEvidence(EvidenceType.VENDOR, OPENSSLV_H, "Vendor", "OpenSSL", Confidence.HIGHEST); dependency.addEvidence(EvidenceType.PRODUCT, OPENSSLV_H, "Product", "OpenSSL", Confidence.HIGHEST); } else { engine.removeDependency(dependency); } }
[ "@", "Override", "protected", "void", "analyzeDependency", "(", "Dependency", "dependency", ",", "Engine", "engine", ")", "throws", "AnalysisException", "{", "final", "File", "file", "=", "dependency", ".", "getActualFile", "(", ")", ";", "final", "String", "par...
Analyzes python packages and adds evidence to the dependency. @param dependency the dependency being analyzed @param engine the engine being used to perform the scan @throws AnalysisException thrown if there is an unrecoverable error analyzing the dependency
[ "Analyzes", "python", "packages", "and", "adds", "evidence", "to", "the", "dependency", "." ]
train
https://github.com/jeremylong/DependencyCheck/blob/6cc7690ea12e4ca1454210ceaa2e9a5523f0926c/core/src/main/java/org/owasp/dependencycheck/analyzer/OpenSSLAnalyzer.java#L189-L222
lucee/Lucee
core/src/main/java/lucee/runtime/interpreter/VariableInterpreter.java
VariableInterpreter.removeVariable
public static Object removeVariable(PageContext pc, String var) throws PageException { // print.ln("var:"+var); StringList list = parse(pc, new ParserString(var), false); if (list == null) throw new InterpreterException("invalid variable declaration [" + var + "]"); if (list.size() == 1) { return pc.undefinedScope().remove(KeyImpl.init(list.next())); } int scope = scopeString2Int(pc.ignoreScopes(), list.next()); Object coll; if (scope == Scope.SCOPE_UNDEFINED) { coll = pc.undefinedScope().get(list.current()); } else { coll = VariableInterpreter.scope(pc, scope, true); // coll=pc.scope(scope); } while (list.hasNextNext()) { coll = pc.get(coll, list.next()); } return Caster.toCollection(coll).remove(KeyImpl.init(list.next())); }
java
public static Object removeVariable(PageContext pc, String var) throws PageException { // print.ln("var:"+var); StringList list = parse(pc, new ParserString(var), false); if (list == null) throw new InterpreterException("invalid variable declaration [" + var + "]"); if (list.size() == 1) { return pc.undefinedScope().remove(KeyImpl.init(list.next())); } int scope = scopeString2Int(pc.ignoreScopes(), list.next()); Object coll; if (scope == Scope.SCOPE_UNDEFINED) { coll = pc.undefinedScope().get(list.current()); } else { coll = VariableInterpreter.scope(pc, scope, true); // coll=pc.scope(scope); } while (list.hasNextNext()) { coll = pc.get(coll, list.next()); } return Caster.toCollection(coll).remove(KeyImpl.init(list.next())); }
[ "public", "static", "Object", "removeVariable", "(", "PageContext", "pc", ",", "String", "var", ")", "throws", "PageException", "{", "// print.ln(\"var:\"+var);", "StringList", "list", "=", "parse", "(", "pc", ",", "new", "ParserString", "(", "var", ")", ",", ...
removes a variable eith matching name from page context @param pc @param var @return has removed or not @throws PageException
[ "removes", "a", "variable", "eith", "matching", "name", "from", "page", "context" ]
train
https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/runtime/interpreter/VariableInterpreter.java#L394-L418
ModeShape/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java
AbstractJcrNode.nodeDefinitionId
NodeDefinitionId nodeDefinitionId() throws ItemNotFoundException, ConstraintViolationException, RepositoryException { CachedDefinition defn = cachedDefn; NodeTypes nodeTypes = session().nodeTypes(); if (defn == null || nodeTypes.getVersion() > defn.nodeTypesVersion) { assert !this.isRoot(); // Determine the node type based upon this node's type information ... CachedNode parent = getParent().node(); SessionCache cache = sessionCache(); Name nodeName = name(); Name primaryType = node().getPrimaryType(cache); Name parentPrimaryType = parent.getPrimaryType(cache); Set<Name> parentMixins = parent.getMixinTypes(cache); SiblingCounter siblingCounter = SiblingCounter.create(parent, cache); boolean skipProtected = true; NodeDefinitionSet childDefns = nodeTypes.findChildNodeDefinitions(parentPrimaryType, parentMixins); JcrNodeDefinition childDefn = childDefns.findBestDefinitionForChild(nodeName, primaryType, skipProtected, siblingCounter); if (childDefn == null) { throw new ConstraintViolationException(JcrI18n.noChildNodeDefinition.text(nodeName, getParent().location(), readable(parentPrimaryType), readable(parentMixins))); } NodeDefinitionId id = childDefn.getId(); setNodeDefinitionId(id, nodeTypes.getVersion()); return id; } return defn.nodeDefnId; }
java
NodeDefinitionId nodeDefinitionId() throws ItemNotFoundException, ConstraintViolationException, RepositoryException { CachedDefinition defn = cachedDefn; NodeTypes nodeTypes = session().nodeTypes(); if (defn == null || nodeTypes.getVersion() > defn.nodeTypesVersion) { assert !this.isRoot(); // Determine the node type based upon this node's type information ... CachedNode parent = getParent().node(); SessionCache cache = sessionCache(); Name nodeName = name(); Name primaryType = node().getPrimaryType(cache); Name parentPrimaryType = parent.getPrimaryType(cache); Set<Name> parentMixins = parent.getMixinTypes(cache); SiblingCounter siblingCounter = SiblingCounter.create(parent, cache); boolean skipProtected = true; NodeDefinitionSet childDefns = nodeTypes.findChildNodeDefinitions(parentPrimaryType, parentMixins); JcrNodeDefinition childDefn = childDefns.findBestDefinitionForChild(nodeName, primaryType, skipProtected, siblingCounter); if (childDefn == null) { throw new ConstraintViolationException(JcrI18n.noChildNodeDefinition.text(nodeName, getParent().location(), readable(parentPrimaryType), readable(parentMixins))); } NodeDefinitionId id = childDefn.getId(); setNodeDefinitionId(id, nodeTypes.getVersion()); return id; } return defn.nodeDefnId; }
[ "NodeDefinitionId", "nodeDefinitionId", "(", ")", "throws", "ItemNotFoundException", ",", "ConstraintViolationException", ",", "RepositoryException", "{", "CachedDefinition", "defn", "=", "cachedDefn", ";", "NodeTypes", "nodeTypes", "=", "session", "(", ")", ".", "nodeT...
Get the property definition ID. @return the cached property definition ID; never null @throws ItemNotFoundException if the node that contains this property doesn't exist anymore @throws ConstraintViolationException if no valid property definition could be found @throws RepositoryException if there is a problem with this repository
[ "Get", "the", "property", "definition", "ID", "." ]
train
https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-jcr/src/main/java/org/modeshape/jcr/AbstractJcrNode.java#L2857-L2884
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java
MemberSummaryBuilder.buildAnnotationTypeFieldsSummary
public void buildAnnotationTypeFieldsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.ANNOTATION_TYPE_FIELDS]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.ANNOTATION_TYPE_FIELDS]; addSummary(writer, visibleMemberMap, false, memberSummaryTree); }
java
public void buildAnnotationTypeFieldsSummary(XMLNode node, Content memberSummaryTree) { MemberSummaryWriter writer = memberSummaryWriters[VisibleMemberMap.ANNOTATION_TYPE_FIELDS]; VisibleMemberMap visibleMemberMap = visibleMemberMaps[VisibleMemberMap.ANNOTATION_TYPE_FIELDS]; addSummary(writer, visibleMemberMap, false, memberSummaryTree); }
[ "public", "void", "buildAnnotationTypeFieldsSummary", "(", "XMLNode", "node", ",", "Content", "memberSummaryTree", ")", "{", "MemberSummaryWriter", "writer", "=", "memberSummaryWriters", "[", "VisibleMemberMap", ".", "ANNOTATION_TYPE_FIELDS", "]", ";", "VisibleMemberMap", ...
Build the summary for fields. @param node the XML element that specifies which components to document @param memberSummaryTree the content tree to which the documentation will be added
[ "Build", "the", "summary", "for", "fields", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/builders/MemberSummaryBuilder.java#L222-L228
kite-sdk/kite
kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/base/Validator.java
Validator.validateRange
public void validateRange(Config config, T value, Comparable<T> min, Comparable<T> max) { boolean isValid = min.compareTo(value) <= 0 && 0 <= max.compareTo(value); if (!isValid) { throw new MorphlineCompilationException( String.format("Invalid choice: '%s' (choose from {%s..%s})", value, min, max), config); } }
java
public void validateRange(Config config, T value, Comparable<T> min, Comparable<T> max) { boolean isValid = min.compareTo(value) <= 0 && 0 <= max.compareTo(value); if (!isValid) { throw new MorphlineCompilationException( String.format("Invalid choice: '%s' (choose from {%s..%s})", value, min, max), config); } }
[ "public", "void", "validateRange", "(", "Config", "config", ",", "T", "value", ",", "Comparable", "<", "T", ">", "min", ",", "Comparable", "<", "T", ">", "max", ")", "{", "boolean", "isValid", "=", "min", ".", "compareTo", "(", "value", ")", "<=", "0...
Validates that the given value is contained in the range [min, max]
[ "Validates", "that", "the", "given", "value", "is", "contained", "in", "the", "range", "[", "min", "max", "]" ]
train
https://github.com/kite-sdk/kite/blob/72bfb4b1a881af85808cd7f14bc3e15160a1e811/kite-morphlines/kite-morphlines-core/src/main/java/org/kitesdk/morphline/base/Validator.java#L34-L44
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/StylesheetRoot.java
StylesheetRoot.initDefaultRule
private void initDefaultRule(ErrorListener errorListener) throws TransformerException { // Then manufacture a default m_defaultRule = new ElemTemplate(); m_defaultRule.setStylesheet(this); XPath defMatch = new XPath("*", this, this, XPath.MATCH, errorListener); m_defaultRule.setMatch(defMatch); ElemApplyTemplates childrenElement = new ElemApplyTemplates(); childrenElement.setIsDefaultTemplate(true); childrenElement.setSelect(m_selectDefault); m_defaultRule.appendChild(childrenElement); m_startRule = m_defaultRule; // ----------------------------- m_defaultTextRule = new ElemTemplate(); m_defaultTextRule.setStylesheet(this); defMatch = new XPath("text() | @*", this, this, XPath.MATCH, errorListener); m_defaultTextRule.setMatch(defMatch); ElemValueOf elemValueOf = new ElemValueOf(); m_defaultTextRule.appendChild(elemValueOf); XPath selectPattern = new XPath(".", this, this, XPath.SELECT, errorListener); elemValueOf.setSelect(selectPattern); //-------------------------------- m_defaultRootRule = new ElemTemplate(); m_defaultRootRule.setStylesheet(this); defMatch = new XPath("/", this, this, XPath.MATCH, errorListener); m_defaultRootRule.setMatch(defMatch); childrenElement = new ElemApplyTemplates(); childrenElement.setIsDefaultTemplate(true); m_defaultRootRule.appendChild(childrenElement); childrenElement.setSelect(m_selectDefault); }
java
private void initDefaultRule(ErrorListener errorListener) throws TransformerException { // Then manufacture a default m_defaultRule = new ElemTemplate(); m_defaultRule.setStylesheet(this); XPath defMatch = new XPath("*", this, this, XPath.MATCH, errorListener); m_defaultRule.setMatch(defMatch); ElemApplyTemplates childrenElement = new ElemApplyTemplates(); childrenElement.setIsDefaultTemplate(true); childrenElement.setSelect(m_selectDefault); m_defaultRule.appendChild(childrenElement); m_startRule = m_defaultRule; // ----------------------------- m_defaultTextRule = new ElemTemplate(); m_defaultTextRule.setStylesheet(this); defMatch = new XPath("text() | @*", this, this, XPath.MATCH, errorListener); m_defaultTextRule.setMatch(defMatch); ElemValueOf elemValueOf = new ElemValueOf(); m_defaultTextRule.appendChild(elemValueOf); XPath selectPattern = new XPath(".", this, this, XPath.SELECT, errorListener); elemValueOf.setSelect(selectPattern); //-------------------------------- m_defaultRootRule = new ElemTemplate(); m_defaultRootRule.setStylesheet(this); defMatch = new XPath("/", this, this, XPath.MATCH, errorListener); m_defaultRootRule.setMatch(defMatch); childrenElement = new ElemApplyTemplates(); childrenElement.setIsDefaultTemplate(true); m_defaultRootRule.appendChild(childrenElement); childrenElement.setSelect(m_selectDefault); }
[ "private", "void", "initDefaultRule", "(", "ErrorListener", "errorListener", ")", "throws", "TransformerException", "{", "// Then manufacture a default", "m_defaultRule", "=", "new", "ElemTemplate", "(", ")", ";", "m_defaultRule", ".", "setStylesheet", "(", "this", ")",...
Create the default rule if needed. @throws TransformerException
[ "Create", "the", "default", "rule", "if", "needed", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/templates/StylesheetRoot.java#L1067-L1118
amaembo/streamex
src/main/java/one/util/streamex/StreamEx.java
StreamEx.groupingTo
public <K, C extends Collection<T>> Map<K, C> groupingTo(Function<? super T, ? extends K> classifier, Supplier<C> collectionFactory) { return groupingBy(classifier, Collectors.toCollection(collectionFactory)); }
java
public <K, C extends Collection<T>> Map<K, C> groupingTo(Function<? super T, ? extends K> classifier, Supplier<C> collectionFactory) { return groupingBy(classifier, Collectors.toCollection(collectionFactory)); }
[ "public", "<", "K", ",", "C", "extends", "Collection", "<", "T", ">", ">", "Map", "<", "K", ",", "C", ">", "groupingTo", "(", "Function", "<", "?", "super", "T", ",", "?", "extends", "K", ">", "classifier", ",", "Supplier", "<", "C", ">", "collec...
Returns a {@code Map} whose keys are the values resulting from applying the classification function to the input elements, and whose corresponding values are the collections of the input elements which map to the associated key under the classification function. <p> There are no guarantees on the type, mutability or serializability of the {@code Map} objects returned. <p> This is a <a href="package-summary.html#StreamOps">terminal</a> operation. @param <K> the type of the keys @param <C> the type of the collection used in resulting {@code Map} values @param classifier the classifier function mapping input elements to keys @param collectionFactory a function which returns a new empty {@code Collection} which will be used to store the stream elements. @return a {@code Map} containing the results of the group-by operation @see #groupingBy(Function, Collector) @see Collectors#groupingBy(Function, Collector) @see Collectors#groupingByConcurrent(Function, Collector) @since 0.2.2
[ "Returns", "a", "{", "@code", "Map", "}", "whose", "keys", "are", "the", "values", "resulting", "from", "applying", "the", "classification", "function", "to", "the", "input", "elements", "and", "whose", "corresponding", "values", "are", "the", "collections", "...
train
https://github.com/amaembo/streamex/blob/936bbd1b7dfbcf64a3b990682bfc848213441d14/src/main/java/one/util/streamex/StreamEx.java#L604-L607
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java
EditManager.addEditDirective
static void addEditDirective(Element plfNode, String attributeName, IPerson person) throws PortalException { addDirective(plfNode, attributeName, Constants.ELM_EDIT, person); }
java
static void addEditDirective(Element plfNode, String attributeName, IPerson person) throws PortalException { addDirective(plfNode, attributeName, Constants.ELM_EDIT, person); }
[ "static", "void", "addEditDirective", "(", "Element", "plfNode", ",", "String", "attributeName", ",", "IPerson", "person", ")", "throws", "PortalException", "{", "addDirective", "(", "plfNode", ",", "attributeName", ",", "Constants", ".", "ELM_EDIT", ",", "person"...
Create and append an edit directive to the edit set if not there. This only records that the attribute was changed and the value in the plf copy node should be used, if allowed, during the merge at login time.
[ "Create", "and", "append", "an", "edit", "directive", "to", "the", "edit", "set", "if", "not", "there", ".", "This", "only", "records", "that", "the", "attribute", "was", "changed", "and", "the", "value", "in", "the", "plf", "copy", "node", "should", "be...
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/EditManager.java#L89-L92
OpenLiberty/open-liberty
dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/jdbc/WSJdbcDataSource.java
WSJdbcDataSource.invokeOperation
@Override Object invokeOperation(Object implObject, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, "invokeOperation: " + method.getName(), args); Object result; // Check for single parameter setter methods Class<?>[] types = method.getParameterTypes(); if (types != null && types.length == 1 && method.getName().startsWith("set") && void.class.equals(method.getReturnType())) { if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "invokeOperation: " + method.getName(), "not supported"); throw new SQLFeatureNotSupportedException(method.getName()); } else // Not modifying the configuration, use the instance for the current config ID. { implObject = mcf.getUnderlyingDataSource(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "invoke on " + AdapterUtil.toString(implObject)); result = method.invoke(implObject, args); } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "invokeOperation: " + method.getName(), result); return result; }
java
@Override Object invokeOperation(Object implObject, Method method, Object[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(this, tc, "invokeOperation: " + method.getName(), args); Object result; // Check for single parameter setter methods Class<?>[] types = method.getParameterTypes(); if (types != null && types.length == 1 && method.getName().startsWith("set") && void.class.equals(method.getReturnType())) { if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "invokeOperation: " + method.getName(), "not supported"); throw new SQLFeatureNotSupportedException(method.getName()); } else // Not modifying the configuration, use the instance for the current config ID. { implObject = mcf.getUnderlyingDataSource(); if (isTraceOn && tc.isDebugEnabled()) Tr.debug(this, tc, "invoke on " + AdapterUtil.toString(implObject)); result = method.invoke(implObject, args); } if (isTraceOn && tc.isEntryEnabled()) Tr.exit(this, tc, "invokeOperation: " + method.getName(), result); return result; }
[ "@", "Override", "Object", "invokeOperation", "(", "Object", "implObject", ",", "Method", "method", ",", "Object", "[", "]", "args", ")", "throws", "IllegalAccessException", ",", "IllegalArgumentException", ",", "InvocationTargetException", ",", "SQLException", "{", ...
Invokes a method. Data sources should use the dynamic configuration manager to select the correct configuration, or if the method is a single-parameter setter -- such as setExtProperties(map) -- then create a new configuration entry for it. @param implObject ignore this parameter; it does not apply to data sources. @param method the method being invoked. @param args the parameters to the method. @throws IllegalAccessException if the method is inaccessible. @throws IllegalArgumentException if the instance does not have the method or if the method arguments are not appropriate. @throws InvocationTargetException if the method raises a checked exception. @throws SQLException if unable to invoke the method for other reasons. @return the result of invoking the method.
[ "Invokes", "a", "method", ".", "Data", "sources", "should", "use", "the", "dynamic", "configuration", "manager", "to", "select", "the", "correct", "configuration", "or", "if", "the", "method", "is", "a", "single", "-", "parameter", "setter", "--", "such", "a...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jdbc/src/com/ibm/ws/rsadapter/jdbc/WSJdbcDataSource.java#L303-L333
amzn/ion-java
src/com/amazon/ion/util/IonStreamUtils.java
IonStreamUtils.writeBoolList
public static void writeBoolList(IonWriter writer, boolean[] values) throws IOException { if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeBoolList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeBool(values[ii]); } writer.stepOut(); }
java
public static void writeBoolList(IonWriter writer, boolean[] values) throws IOException { if (writer instanceof _Private_ListWriter) { ((_Private_ListWriter)writer).writeBoolList(values); return; } writer.stepIn(IonType.LIST); for (int ii=0; ii<values.length; ii++) { writer.writeBool(values[ii]); } writer.stepOut(); }
[ "public", "static", "void", "writeBoolList", "(", "IonWriter", "writer", ",", "boolean", "[", "]", "values", ")", "throws", "IOException", "{", "if", "(", "writer", "instanceof", "_Private_ListWriter", ")", "{", "(", "(", "_Private_ListWriter", ")", "writer", ...
writes an IonList with a series of IonBool values. This starts a List, writes the values (without any annoations) and closes the list. For text and tree writers this is just a convienience, but for the binary writer it can be optimized internally. @param values boolean values to populate the list with
[ "writes", "an", "IonList", "with", "a", "series", "of", "IonBool", "values", ".", "This", "starts", "a", "List", "writes", "the", "values", "(", "without", "any", "annoations", ")", "and", "closes", "the", "list", ".", "For", "text", "and", "tree", "writ...
train
https://github.com/amzn/ion-java/blob/4ce1f0f58c6a5a8e42d0425ccdb36e38be3e2270/src/com/amazon/ion/util/IonStreamUtils.java#L138-L151
mikepenz/FastAdapter
library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterUIUtils.java
FastAdapterUIUtils.getRippleDrawable
public static Drawable getRippleDrawable(@ColorInt int normalColor, @ColorInt int pressedColor, int radius) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return new RippleDrawable(ColorStateList.valueOf(pressedColor), new ColorDrawable(normalColor), getRippleMask(normalColor, radius)); } else { return getStateListDrawable(normalColor, pressedColor); } }
java
public static Drawable getRippleDrawable(@ColorInt int normalColor, @ColorInt int pressedColor, int radius) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return new RippleDrawable(ColorStateList.valueOf(pressedColor), new ColorDrawable(normalColor), getRippleMask(normalColor, radius)); } else { return getStateListDrawable(normalColor, pressedColor); } }
[ "public", "static", "Drawable", "getRippleDrawable", "(", "@", "ColorInt", "int", "normalColor", ",", "@", "ColorInt", "int", "pressedColor", ",", "int", "radius", ")", "{", "if", "(", "Build", ".", "VERSION", ".", "SDK_INT", ">=", "Build", ".", "VERSION_COD...
helper to create an ripple drawable with the given normal and pressed color @param normalColor the normal color @param pressedColor the pressed color @param radius the button radius @return the ripple drawable
[ "helper", "to", "create", "an", "ripple", "drawable", "with", "the", "given", "normal", "and", "pressed", "color" ]
train
https://github.com/mikepenz/FastAdapter/blob/3b2412abe001ba58422e0125846b704d4dba4ae9/library/src/main/java/com/mikepenz/fastadapter/commons/utils/FastAdapterUIUtils.java#L101-L108
alkacon/opencms-core
src/org/opencms/ui/apps/cacheadmin/CmsImageCacheTable.java
CmsImageCacheTable.showVariationsWindow
void showVariationsWindow(String resource) { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); CmsVariationsDialog variationsDialog = new CmsVariationsDialog(resource, new Runnable() { public void run() { window.close(); } }, Mode.ImageCache); try { CmsResource resourceObject = getRootCms().readResource(resource); variationsDialog.displayResourceInfo(Collections.singletonList(resourceObject)); } catch (CmsException e) { // } window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_CACHE_VIEW_FLEX_VARIATIONS_1, resource)); window.setContent(variationsDialog); A_CmsUI.get().addWindow(window); window.center(); }
java
void showVariationsWindow(String resource) { final Window window = CmsBasicDialog.prepareWindow(DialogWidth.max); CmsVariationsDialog variationsDialog = new CmsVariationsDialog(resource, new Runnable() { public void run() { window.close(); } }, Mode.ImageCache); try { CmsResource resourceObject = getRootCms().readResource(resource); variationsDialog.displayResourceInfo(Collections.singletonList(resourceObject)); } catch (CmsException e) { // } window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_CACHE_VIEW_FLEX_VARIATIONS_1, resource)); window.setContent(variationsDialog); A_CmsUI.get().addWindow(window); window.center(); }
[ "void", "showVariationsWindow", "(", "String", "resource", ")", "{", "final", "Window", "window", "=", "CmsBasicDialog", ".", "prepareWindow", "(", "DialogWidth", ".", "max", ")", ";", "CmsVariationsDialog", "variationsDialog", "=", "new", "CmsVariationsDialog", "("...
Shows dialog for variations of given resource.<p> @param resource to show variations for
[ "Shows", "dialog", "for", "variations", "of", "given", "resource", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ui/apps/cacheadmin/CmsImageCacheTable.java#L411-L433
ManfredTremmel/gwt-bean-validators
mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/EmailMustHaveSameDomainValidator.java
EmailMustHaveSameDomainValidator.isValid
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { if (pvalue == null) { return true; } try { final String field1Value = getDomainOf(BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, field1Name)); final String field2Value = getDomainOf(BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, field2Name)); if (!StringUtils.equals(field1Value, field2Value)) { switchContext(pcontext); return false; } return true; } catch (final Exception ignore) { switchContext(pcontext); return false; } }
java
@Override public final boolean isValid(final Object pvalue, final ConstraintValidatorContext pcontext) { if (pvalue == null) { return true; } try { final String field1Value = getDomainOf(BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, field1Name)); final String field2Value = getDomainOf(BeanPropertyReaderUtil.getNullSaveStringProperty(pvalue, field2Name)); if (!StringUtils.equals(field1Value, field2Value)) { switchContext(pcontext); return false; } return true; } catch (final Exception ignore) { switchContext(pcontext); return false; } }
[ "@", "Override", "public", "final", "boolean", "isValid", "(", "final", "Object", "pvalue", ",", "final", "ConstraintValidatorContext", "pcontext", ")", "{", "if", "(", "pvalue", "==", "null", ")", "{", "return", "true", ";", "}", "try", "{", "final", "Str...
{@inheritDoc} check if given object is valid. @see javax.validation.ConstraintValidator#isValid(Object, javax.validation.ConstraintValidatorContext)
[ "{", "@inheritDoc", "}", "check", "if", "given", "object", "is", "valid", "." ]
train
https://github.com/ManfredTremmel/gwt-bean-validators/blob/cff7a2c3d68c2d17bf9d3cc57c79cc16fa8b4d5c/mt-bean-validators/src/main/java/de/knightsoftnet/validators/shared/impl/EmailMustHaveSameDomainValidator.java#L80-L99
telly/groundy
library/src/main/java/com/telly/groundy/TaskResult.java
TaskResult.add
public TaskResult add(String key, CharSequence value) { mBundle.putCharSequence(key, value); return this; }
java
public TaskResult add(String key, CharSequence value) { mBundle.putCharSequence(key, value); return this; }
[ "public", "TaskResult", "add", "(", "String", "key", ",", "CharSequence", "value", ")", "{", "mBundle", ".", "putCharSequence", "(", "key", ",", "value", ")", ";", "return", "this", ";", "}" ]
Inserts a CharSequence value into the mapping of this Bundle, replacing any existing value for the given key. Either key or value may be null. @param key a String, or null @param value a CharSequence, or null
[ "Inserts", "a", "CharSequence", "value", "into", "the", "mapping", "of", "this", "Bundle", "replacing", "any", "existing", "value", "for", "the", "given", "key", ".", "Either", "key", "or", "value", "may", "be", "null", "." ]
train
https://github.com/telly/groundy/blob/e90baf9901a8be20b348bd1575d5ad782560cec8/library/src/main/java/com/telly/groundy/TaskResult.java#L167-L170
ops4j/org.ops4j.pax.exam2
containers/pax-exam-container-eclipse/src/main/java/org/ops4j/pax/exam/container/eclipse/impl/sources/directory/DirectoryResolver.java
DirectoryResolver.storeToFolder
public static void storeToFolder(File folder, Collection<? extends EclipseBundle> bundles, Collection<? extends EclipseFeature> features) throws IOException { File pluginsFolder = new File(folder, PLUGINS_FOLDER); File featuresFolder = new File(folder, FEATURES_FOLDER); FileUtils.forceMkdir(pluginsFolder); FileUtils.forceMkdir(featuresFolder); for (EclipseFeature feature : features) { if (feature instanceof StreamReference) { try (InputStream stream = ((StreamReference) feature).createStream()) { FileUtils.copyInputStreamToFile(stream, new File(featuresFolder, getFileName(feature))); } } else { throw new IllegalArgumentException("feature " + createWrongTypeMsg(feature)); } } for (EclipseBundle bundle : bundles) { if (bundle instanceof StreamReference) { try (InputStream stream = ((StreamReference) bundle).createStream()) { FileUtils.copyInputStreamToFile(stream, new File(pluginsFolder, getFileName(bundle))); } } else { throw new IllegalArgumentException("bundle " + createWrongTypeMsg(bundle)); } } }
java
public static void storeToFolder(File folder, Collection<? extends EclipseBundle> bundles, Collection<? extends EclipseFeature> features) throws IOException { File pluginsFolder = new File(folder, PLUGINS_FOLDER); File featuresFolder = new File(folder, FEATURES_FOLDER); FileUtils.forceMkdir(pluginsFolder); FileUtils.forceMkdir(featuresFolder); for (EclipseFeature feature : features) { if (feature instanceof StreamReference) { try (InputStream stream = ((StreamReference) feature).createStream()) { FileUtils.copyInputStreamToFile(stream, new File(featuresFolder, getFileName(feature))); } } else { throw new IllegalArgumentException("feature " + createWrongTypeMsg(feature)); } } for (EclipseBundle bundle : bundles) { if (bundle instanceof StreamReference) { try (InputStream stream = ((StreamReference) bundle).createStream()) { FileUtils.copyInputStreamToFile(stream, new File(pluginsFolder, getFileName(bundle))); } } else { throw new IllegalArgumentException("bundle " + createWrongTypeMsg(bundle)); } } }
[ "public", "static", "void", "storeToFolder", "(", "File", "folder", ",", "Collection", "<", "?", "extends", "EclipseBundle", ">", "bundles", ",", "Collection", "<", "?", "extends", "EclipseFeature", ">", "features", ")", "throws", "IOException", "{", "File", "...
Stores the given collection of bundles and features to the given folder in a way so it can be read back by the directory resolver. All bundles and features must be able to be transformed to an input stream via the {@link StreamReference} interface or an exception is raised! @param folder the folder to store the artifacts to @param bundles the bundles to store @param features the features to store @throws IOException if an I/O error occurs
[ "Stores", "the", "given", "collection", "of", "bundles", "and", "features", "to", "the", "given", "folder", "in", "a", "way", "so", "it", "can", "be", "read", "back", "by", "the", "directory", "resolver", ".", "All", "bundles", "and", "features", "must", ...
train
https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/containers/pax-exam-container-eclipse/src/main/java/org/ops4j/pax/exam/container/eclipse/impl/sources/directory/DirectoryResolver.java#L141-L170
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java
SDMath.iamax
public SDVariable iamax(SDVariable in, boolean keepDims, int... dimensions) { return iamax(null, in, keepDims, dimensions); }
java
public SDVariable iamax(SDVariable in, boolean keepDims, int... dimensions) { return iamax(null, in, keepDims, dimensions); }
[ "public", "SDVariable", "iamax", "(", "SDVariable", "in", ",", "boolean", "keepDims", ",", "int", "...", "dimensions", ")", "{", "return", "iamax", "(", "null", ",", "in", ",", "keepDims", ",", "dimensions", ")", ";", "}" ]
Index of the max absolute value: argmax(abs(in)) @see SameDiff#argmax(String, SDVariable, boolean, int...)
[ "Index", "of", "the", "max", "absolute", "value", ":", "argmax", "(", "abs", "(", "in", "))" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDMath.java#L1232-L1234
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/spi/impl/AbstractInvocationFuture.java
AbstractInvocationFuture.registerWaiter
private Object registerWaiter(Object waiter, Executor executor) { assert !(waiter instanceof UnblockableThread) : "Waiting for response on this thread is illegal"; WaitNode waitNode = null; for (; ; ) { final Object oldState = state; if (isDone(oldState)) { return oldState; } Object newState; if (oldState == VOID && (executor == null || executor == defaultExecutor)) { // nothing is syncing on this future, so instead of creating a WaitNode, we just try to cas the waiter newState = waiter; } else { // something already has been registered for syncing, so we need to create a WaitNode if (waitNode == null) { waitNode = new WaitNode(waiter, executor); } waitNode.next = oldState; newState = waitNode; } if (compareAndSetState(oldState, newState)) { // we have successfully registered return VOID; } } }
java
private Object registerWaiter(Object waiter, Executor executor) { assert !(waiter instanceof UnblockableThread) : "Waiting for response on this thread is illegal"; WaitNode waitNode = null; for (; ; ) { final Object oldState = state; if (isDone(oldState)) { return oldState; } Object newState; if (oldState == VOID && (executor == null || executor == defaultExecutor)) { // nothing is syncing on this future, so instead of creating a WaitNode, we just try to cas the waiter newState = waiter; } else { // something already has been registered for syncing, so we need to create a WaitNode if (waitNode == null) { waitNode = new WaitNode(waiter, executor); } waitNode.next = oldState; newState = waitNode; } if (compareAndSetState(oldState, newState)) { // we have successfully registered return VOID; } } }
[ "private", "Object", "registerWaiter", "(", "Object", "waiter", ",", "Executor", "executor", ")", "{", "assert", "!", "(", "waiter", "instanceof", "UnblockableThread", ")", ":", "\"Waiting for response on this thread is illegal\"", ";", "WaitNode", "waitNode", "=", "n...
Registers a waiter (thread/ExecutionCallback) that gets notified when the future completes. @param waiter the waiter @param executor the {@link Executor} to use in case of an {@link ExecutionCallback}. @return VOID if the registration was a success, anything else but void is the response.
[ "Registers", "a", "waiter", "(", "thread", "/", "ExecutionCallback", ")", "that", "gets", "notified", "when", "the", "future", "completes", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/spi/impl/AbstractInvocationFuture.java#L298-L325
JRebirth/JRebirth
org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/parameter/ObjectParameter.java
ObjectParameter.parseEnumParameter
@SuppressWarnings("unchecked") private Object parseEnumParameter(final Enum<?> e, final String serializedObject) { final Object res = Enum.valueOf(e.getClass(), serializedObject); return res; }
java
@SuppressWarnings("unchecked") private Object parseEnumParameter(final Enum<?> e, final String serializedObject) { final Object res = Enum.valueOf(e.getClass(), serializedObject); return res; }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "private", "Object", "parseEnumParameter", "(", "final", "Enum", "<", "?", ">", "e", ",", "final", "String", "serializedObject", ")", "{", "final", "Object", "res", "=", "Enum", ".", "valueOf", "(", "e", ...
Parse an Enum definition by calling Enum.valueOf. @param serializedObject the full enumerated value @return the class object
[ "Parse", "an", "Enum", "definition", "by", "calling", "Enum", ".", "valueOf", "." ]
train
https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/resource/parameter/ObjectParameter.java#L179-L183
buschmais/jqa-core-framework
rule/src/main/java/com/buschmais/jqassistant/core/rule/api/executor/RuleSetExecutor.java
RuleSetExecutor.applyConcept
private boolean applyConcept(RuleSet ruleSet, Concept concept, Severity severity) throws RuleException { Boolean result = executedConcepts.get(concept); if (result == null) { if (applyRequiredConcepts(ruleSet, concept)) { result = ruleVisitor.visitConcept(concept, severity); } else { ruleVisitor.skipConcept(concept, severity); result = false; } executedConcepts.put(concept, result); } return result; }
java
private boolean applyConcept(RuleSet ruleSet, Concept concept, Severity severity) throws RuleException { Boolean result = executedConcepts.get(concept); if (result == null) { if (applyRequiredConcepts(ruleSet, concept)) { result = ruleVisitor.visitConcept(concept, severity); } else { ruleVisitor.skipConcept(concept, severity); result = false; } executedConcepts.put(concept, result); } return result; }
[ "private", "boolean", "applyConcept", "(", "RuleSet", "ruleSet", ",", "Concept", "concept", ",", "Severity", "severity", ")", "throws", "RuleException", "{", "Boolean", "result", "=", "executedConcepts", ".", "get", "(", "concept", ")", ";", "if", "(", "result...
Applies the given concept. @param concept The concept. @throws RuleException If the concept cannot be applied.
[ "Applies", "the", "given", "concept", "." ]
train
https://github.com/buschmais/jqa-core-framework/blob/0e63ff509cfe52f9063539a23d5f9f183b2ea4a5/rule/src/main/java/com/buschmais/jqassistant/core/rule/api/executor/RuleSetExecutor.java#L180-L192
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java
HtmlDocletWriter.getTargetPackageLink
public Content getTargetPackageLink(PackageDoc pd, String target, Content label) { return getHyperLink(pathString(pd, DocPaths.PACKAGE_SUMMARY), label, "", target); }
java
public Content getTargetPackageLink(PackageDoc pd, String target, Content label) { return getHyperLink(pathString(pd, DocPaths.PACKAGE_SUMMARY), label, "", target); }
[ "public", "Content", "getTargetPackageLink", "(", "PackageDoc", "pd", ",", "String", "target", ",", "Content", "label", ")", "{", "return", "getHyperLink", "(", "pathString", "(", "pd", ",", "DocPaths", ".", "PACKAGE_SUMMARY", ")", ",", "label", ",", "\"\"", ...
Get Package link, with target frame. @param pd The link will be to the "package-summary.html" page for this package @param target name of the target frame @param label tag for the link @return a content for the target package link
[ "Get", "Package", "link", "with", "target", "frame", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java#L285-L288
OpenHFT/Chronicle-Map
src/main/java/net/openhft/chronicle/hash/replication/DefaultEventualConsistencyStrategy.java
DefaultEventualConsistencyStrategy.decideOnRemoteModification
public static AcceptanceDecision decideOnRemoteModification( ReplicableEntry entry, RemoteOperationContext<?> context) { long remoteTimestamp = context.remoteTimestamp(); long originTimestamp = entry.originTimestamp(); // Last write wins if (remoteTimestamp > originTimestamp) return ACCEPT; if (remoteTimestamp < originTimestamp) return DISCARD; // remoteTimestamp == originTimestamp below byte remoteIdentifier = context.remoteIdentifier(); byte originIdentifier = entry.originIdentifier(); // Lower identifier wins if (remoteIdentifier < originIdentifier) return ACCEPT; if (remoteIdentifier > originIdentifier) return DISCARD; // remoteTimestamp == originTimestamp && remoteIdentifier == originIdentifier below // This could be, only if a node with the origin identifier was lost, a new Chronicle Hash // instance was started up, but with system time which for some reason is very late, so // that it provides the same time, as the "old" node with this identifier, before it was // lost. (This is almost a theoretical situation.) In this case, give advantage to fresh // entry updates to the "new" node. Entries with the same id and timestamp, bootstrapped // "back" from other nodes in the system, are discarded on this new node (this is the // of the condition originIdentifier == currentNodeIdentifier). But those new updates // should win on other nodes. // // Another case, in which we could have remoteTimestamp == originTimestamp && // remoteIdentifier == originIdentifier, is replication of barely the same entry, if an // entry is bootstrapped "back" from remote node to it's origin node. In this case the // following condition also plays right (the update is discarded, due to it's redundancy). return originIdentifier == context.currentNodeIdentifier() ? DISCARD : ACCEPT; }
java
public static AcceptanceDecision decideOnRemoteModification( ReplicableEntry entry, RemoteOperationContext<?> context) { long remoteTimestamp = context.remoteTimestamp(); long originTimestamp = entry.originTimestamp(); // Last write wins if (remoteTimestamp > originTimestamp) return ACCEPT; if (remoteTimestamp < originTimestamp) return DISCARD; // remoteTimestamp == originTimestamp below byte remoteIdentifier = context.remoteIdentifier(); byte originIdentifier = entry.originIdentifier(); // Lower identifier wins if (remoteIdentifier < originIdentifier) return ACCEPT; if (remoteIdentifier > originIdentifier) return DISCARD; // remoteTimestamp == originTimestamp && remoteIdentifier == originIdentifier below // This could be, only if a node with the origin identifier was lost, a new Chronicle Hash // instance was started up, but with system time which for some reason is very late, so // that it provides the same time, as the "old" node with this identifier, before it was // lost. (This is almost a theoretical situation.) In this case, give advantage to fresh // entry updates to the "new" node. Entries with the same id and timestamp, bootstrapped // "back" from other nodes in the system, are discarded on this new node (this is the // of the condition originIdentifier == currentNodeIdentifier). But those new updates // should win on other nodes. // // Another case, in which we could have remoteTimestamp == originTimestamp && // remoteIdentifier == originIdentifier, is replication of barely the same entry, if an // entry is bootstrapped "back" from remote node to it's origin node. In this case the // following condition also plays right (the update is discarded, due to it's redundancy). return originIdentifier == context.currentNodeIdentifier() ? DISCARD : ACCEPT; }
[ "public", "static", "AcceptanceDecision", "decideOnRemoteModification", "(", "ReplicableEntry", "entry", ",", "RemoteOperationContext", "<", "?", ">", "context", ")", "{", "long", "remoteTimestamp", "=", "context", ".", "remoteTimestamp", "(", ")", ";", "long", "ori...
Returns the acceptance decision, should be made about the modification operation in the given {@code context}, aiming to modify the given {@code entry}. This method doesn't do any changes to {@code entry} nor {@code context} state. {@link MapRemoteOperations} and {@link SetRemoteOperations} method implementations should guide the result of calling this method to do something to <i>actually</i> apply the remote operation. @param entry the entry to be modified @param context the remote operation context @return if the remote operation should be accepted or discarded
[ "Returns", "the", "acceptance", "decision", "should", "be", "made", "about", "the", "modification", "operation", "in", "the", "given", "{", "@code", "context", "}", "aiming", "to", "modify", "the", "given", "{", "@code", "entry", "}", ".", "This", "method", ...
train
https://github.com/OpenHFT/Chronicle-Map/blob/0b09733cc96302f96be4394a261699eeb021fe37/src/main/java/net/openhft/chronicle/hash/replication/DefaultEventualConsistencyStrategy.java#L52-L84
lessthanoptimal/BoofCV
main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java
ConvertBufferedImage.convertFrom
public static GrayF32 convertFrom(BufferedImage src, GrayF32 dst) { if (dst != null) { dst.reshape(src.getWidth(), src.getHeight()); } else { dst = new GrayF32( src.getWidth(), src.getHeight()); } try { DataBuffer buff = src.getRaster().getDataBuffer(); if ( buff.getDataType() == DataBuffer.TYPE_BYTE ) { if( isKnownByteFormat(src) ) { ConvertRaster.bufferedToGray((DataBufferByte)buff,src.getRaster(),dst); } else { ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } } else if (buff.getDataType() == DataBuffer.TYPE_INT) { ConvertRaster.bufferedToGray((DataBufferInt)buff, src.getRaster(), dst); } else { ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } } catch( java.security.AccessControlException e) { // Applets don't allow access to the raster() ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } return dst; }
java
public static GrayF32 convertFrom(BufferedImage src, GrayF32 dst) { if (dst != null) { dst.reshape(src.getWidth(), src.getHeight()); } else { dst = new GrayF32( src.getWidth(), src.getHeight()); } try { DataBuffer buff = src.getRaster().getDataBuffer(); if ( buff.getDataType() == DataBuffer.TYPE_BYTE ) { if( isKnownByteFormat(src) ) { ConvertRaster.bufferedToGray((DataBufferByte)buff,src.getRaster(),dst); } else { ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } } else if (buff.getDataType() == DataBuffer.TYPE_INT) { ConvertRaster.bufferedToGray((DataBufferInt)buff, src.getRaster(), dst); } else { ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } } catch( java.security.AccessControlException e) { // Applets don't allow access to the raster() ConvertRaster.bufferedToGray(src, dst.data, dst.startIndex, dst.stride); } return dst; }
[ "public", "static", "GrayF32", "convertFrom", "(", "BufferedImage", "src", ",", "GrayF32", "dst", ")", "{", "if", "(", "dst", "!=", "null", ")", "{", "dst", ".", "reshape", "(", "src", ".", "getWidth", "(", ")", ",", "src", ".", "getHeight", "(", ")"...
Converts the buffered image into an {@link GrayF32}. If the buffered image has multiple channels the intensities of each channel are averaged together. @param src Input image. @param dst Where the converted image is written to. If null a new unsigned image is created. @return Converted image.
[ "Converts", "the", "buffered", "image", "into", "an", "{", "@link", "GrayF32", "}", ".", "If", "the", "buffered", "image", "has", "multiple", "channels", "the", "intensities", "of", "each", "channel", "are", "averaged", "together", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-io/src/main/java/boofcv/io/image/ConvertBufferedImage.java#L425-L452
hyperledger/fabric-sdk-java
src/main/java/org/hyperledger/fabric/sdk/Channel.java
Channel.setPeerOptions
PeerOptions setPeerOptions(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { if (initialized) { throw new InvalidArgumentException(format("Channel %s already initialized.", name)); } checkPeer(peer); PeerOptions ret = getPeersOptions(peer); removePeerInternal(peer); addPeer(peer, peerOptions); return ret; }
java
PeerOptions setPeerOptions(Peer peer, PeerOptions peerOptions) throws InvalidArgumentException { if (initialized) { throw new InvalidArgumentException(format("Channel %s already initialized.", name)); } checkPeer(peer); PeerOptions ret = getPeersOptions(peer); removePeerInternal(peer); addPeer(peer, peerOptions); return ret; }
[ "PeerOptions", "setPeerOptions", "(", "Peer", "peer", ",", "PeerOptions", "peerOptions", ")", "throws", "InvalidArgumentException", "{", "if", "(", "initialized", ")", "{", "throw", "new", "InvalidArgumentException", "(", "format", "(", "\"Channel %s already initialized...
Set peerOptions in the channel that has not be initialized yet. @param peer the peer to set options on. @param peerOptions see {@link PeerOptions} @return old options.
[ "Set", "peerOptions", "in", "the", "channel", "that", "has", "not", "be", "initialized", "yet", "." ]
train
https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L1001-L1013
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseConnectionPoliciesInner.java
DatabaseConnectionPoliciesInner.createOrUpdateAsync
public Observable<DatabaseConnectionPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, String databaseName, DatabaseConnectionPolicyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<DatabaseConnectionPolicyInner>, DatabaseConnectionPolicyInner>() { @Override public DatabaseConnectionPolicyInner call(ServiceResponse<DatabaseConnectionPolicyInner> response) { return response.body(); } }); }
java
public Observable<DatabaseConnectionPolicyInner> createOrUpdateAsync(String resourceGroupName, String serverName, String databaseName, DatabaseConnectionPolicyInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, databaseName, parameters).map(new Func1<ServiceResponse<DatabaseConnectionPolicyInner>, DatabaseConnectionPolicyInner>() { @Override public DatabaseConnectionPolicyInner call(ServiceResponse<DatabaseConnectionPolicyInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "DatabaseConnectionPolicyInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "String", "databaseName", ",", "DatabaseConnectionPolicyInner", "parameters", ")", "{", "return", "createOrUpdateW...
Creates or updates a database's connection policy, which is used with table auditing. Table auditing is deprecated, use blob auditing instead. @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. @param serverName The name of the server. @param databaseName The name of the database for which the connection policy will be defined. @param parameters The database connection policy. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the DatabaseConnectionPolicyInner object
[ "Creates", "or", "updates", "a", "database", "s", "connection", "policy", "which", "is", "used", "with", "table", "auditing", ".", "Table", "auditing", "is", "deprecated", "use", "blob", "auditing", "instead", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/DatabaseConnectionPoliciesInner.java#L202-L209
Netflix/dyno
dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/HostStatusTracker.java
HostStatusTracker.inactiveSetChanged
public boolean inactiveSetChanged(Collection<Host> hostsUp, Collection<Host> hostsDown) { boolean newInactiveHostsFound = false; // Check for condition 1. for (Host hostDown : hostsDown) { if (activeHosts.contains(hostDown)) { newInactiveHostsFound = true; break; } } // Check for condition 2. Set<Host> prevActiveHosts = new HashSet<Host>(activeHosts); prevActiveHosts.removeAll(hostsUp); newInactiveHostsFound = !prevActiveHosts.isEmpty(); return newInactiveHostsFound; }
java
public boolean inactiveSetChanged(Collection<Host> hostsUp, Collection<Host> hostsDown) { boolean newInactiveHostsFound = false; // Check for condition 1. for (Host hostDown : hostsDown) { if (activeHosts.contains(hostDown)) { newInactiveHostsFound = true; break; } } // Check for condition 2. Set<Host> prevActiveHosts = new HashSet<Host>(activeHosts); prevActiveHosts.removeAll(hostsUp); newInactiveHostsFound = !prevActiveHosts.isEmpty(); return newInactiveHostsFound; }
[ "public", "boolean", "inactiveSetChanged", "(", "Collection", "<", "Host", ">", "hostsUp", ",", "Collection", "<", "Host", ">", "hostsDown", ")", "{", "boolean", "newInactiveHostsFound", "=", "false", ";", "// Check for condition 1. ", "for", "(", "Host", "hostDow...
This check is more involved than the active set check. Here we 2 conditions to check for 1. We could have new hosts that were in the active set and have shown up in the inactive set. 2. We can also have the case where hosts from the active set have disappeared and also not in the provided inactive set. This is where we have simply forgotten about some active host and that it needs to be shutdown @param hostsUp @param hostsDown @return true/false indicating whether we have a host that has been shutdown
[ "This", "check", "is", "more", "involved", "than", "the", "active", "set", "check", ".", "Here", "we", "2", "conditions", "to", "check", "for" ]
train
https://github.com/Netflix/dyno/blob/158f807083ea8e9b09c8089cb07f98e954ad5b23/dyno-core/src/main/java/com/netflix/dyno/connectionpool/impl/HostStatusTracker.java#L103-L122
tzaeschke/zoodb
src/org/zoodb/internal/ZooClassDef.java
ZooClassDef.newVersion
private ZooClassDef newVersion(ClientSessionCache cache, ZooClassDef newSuper) { if (nextVersion != null) { throw new IllegalStateException(); } if (newSuper == null) { //no new version of super available newSuper = superDef; } long oid = jdoZooGetContext().getNode().getOidBuffer().allocateOid(); ZooClassDef newDef = new ZooClassDef(className, oid, newSuper.getOid(), schemaId, versionId + 1); //super-class newDef.associateSuperDef(newSuper); //caches cache.addSchema(newDef, false, jdoZooGetContext().getNode()); //versions newDef.prevVersionOid = jdoZooGetOid(); newDef.prevVersion = this; nextVersion = newDef; //API class newDef.versionProxy = versionProxy; versionProxy.newVersion(newDef); //context newDef.providedContext = new PCContext(newDef, providedContext.getSession(), providedContext.getNode()); //fields for (ZooFieldDef f: localFields) { ZooFieldDef fNew = new ZooFieldDef(f, newDef); newDef.localFields.add(fNew); if (fNew.getProxy() != null) { fNew.getProxy().updateVersion(fNew); } } newDef.associateFields(); return newDef; }
java
private ZooClassDef newVersion(ClientSessionCache cache, ZooClassDef newSuper) { if (nextVersion != null) { throw new IllegalStateException(); } if (newSuper == null) { //no new version of super available newSuper = superDef; } long oid = jdoZooGetContext().getNode().getOidBuffer().allocateOid(); ZooClassDef newDef = new ZooClassDef(className, oid, newSuper.getOid(), schemaId, versionId + 1); //super-class newDef.associateSuperDef(newSuper); //caches cache.addSchema(newDef, false, jdoZooGetContext().getNode()); //versions newDef.prevVersionOid = jdoZooGetOid(); newDef.prevVersion = this; nextVersion = newDef; //API class newDef.versionProxy = versionProxy; versionProxy.newVersion(newDef); //context newDef.providedContext = new PCContext(newDef, providedContext.getSession(), providedContext.getNode()); //fields for (ZooFieldDef f: localFields) { ZooFieldDef fNew = new ZooFieldDef(f, newDef); newDef.localFields.add(fNew); if (fNew.getProxy() != null) { fNew.getProxy().updateVersion(fNew); } } newDef.associateFields(); return newDef; }
[ "private", "ZooClassDef", "newVersion", "(", "ClientSessionCache", "cache", ",", "ZooClassDef", "newSuper", ")", "{", "if", "(", "nextVersion", "!=", "null", ")", "{", "throw", "new", "IllegalStateException", "(", ")", ";", "}", "if", "(", "newSuper", "==", ...
Schema versioning: We only create new schema instance when we add or remove fields. Renaming a field should not result in a new version! A new version is only required when the modified schema does not match the stored data. Such changes require also new versions of all sub-classes. WHY? If every class stored only their own fields would we still have a problem? Yes, because the new version of the referenced superclass has a different OID. @param cache @return New version.
[ "Schema", "versioning", ":", "We", "only", "create", "new", "schema", "instance", "when", "we", "add", "or", "remove", "fields", ".", "Renaming", "a", "field", "should", "not", "result", "in", "a", "new", "version!", "A", "new", "version", "is", "only", ...
train
https://github.com/tzaeschke/zoodb/blob/058d0ff161a8ee9d53244c433aca97ee9c654410/src/org/zoodb/internal/ZooClassDef.java#L182-L226
restfb/restfb
src/main/java/com/restfb/DefaultFacebookClient.java
DefaultFacebookClient.toParameterString
protected String toParameterString(boolean withJsonParameter, Parameter... parameters) { if (!isBlank(accessToken)) { parameters = parametersWithAdditionalParameter(Parameter.with(ACCESS_TOKEN_PARAM_NAME, accessToken), parameters); } if (!isBlank(accessToken) && !isBlank(appSecret)) { parameters = parametersWithAdditionalParameter( Parameter.with(APP_SECRET_PROOF_PARAM_NAME, obtainAppSecretProof(accessToken, appSecret)), parameters); } if (withJsonParameter) { parameters = parametersWithAdditionalParameter(Parameter.with(FORMAT_PARAM_NAME, "json"), parameters); } StringBuilder parameterStringBuilder = new StringBuilder(); boolean first = true; for (Parameter parameter : parameters) { if (first) { first = false; } else { parameterStringBuilder.append("&"); } parameterStringBuilder.append(urlEncode(parameter.name)); parameterStringBuilder.append("="); parameterStringBuilder.append(urlEncodedValueForParameterName(parameter.name, parameter.value)); } return parameterStringBuilder.toString(); }
java
protected String toParameterString(boolean withJsonParameter, Parameter... parameters) { if (!isBlank(accessToken)) { parameters = parametersWithAdditionalParameter(Parameter.with(ACCESS_TOKEN_PARAM_NAME, accessToken), parameters); } if (!isBlank(accessToken) && !isBlank(appSecret)) { parameters = parametersWithAdditionalParameter( Parameter.with(APP_SECRET_PROOF_PARAM_NAME, obtainAppSecretProof(accessToken, appSecret)), parameters); } if (withJsonParameter) { parameters = parametersWithAdditionalParameter(Parameter.with(FORMAT_PARAM_NAME, "json"), parameters); } StringBuilder parameterStringBuilder = new StringBuilder(); boolean first = true; for (Parameter parameter : parameters) { if (first) { first = false; } else { parameterStringBuilder.append("&"); } parameterStringBuilder.append(urlEncode(parameter.name)); parameterStringBuilder.append("="); parameterStringBuilder.append(urlEncodedValueForParameterName(parameter.name, parameter.value)); } return parameterStringBuilder.toString(); }
[ "protected", "String", "toParameterString", "(", "boolean", "withJsonParameter", ",", "Parameter", "...", "parameters", ")", "{", "if", "(", "!", "isBlank", "(", "accessToken", ")", ")", "{", "parameters", "=", "parametersWithAdditionalParameter", "(", "Parameter", ...
Generate the parameter string to be included in the Facebook API request. @param withJsonParameter add additional parameter format with type json @param parameters Arbitrary number of extra parameters to include in the request. @return The parameter string to include in the Facebook API request. @throws FacebookJsonMappingException If an error occurs when building the parameter string.
[ "Generate", "the", "parameter", "string", "to", "be", "included", "in", "the", "Facebook", "API", "request", "." ]
train
https://github.com/restfb/restfb/blob/fb77ba5486d1339e7deb81b9830670fa209b1047/src/main/java/com/restfb/DefaultFacebookClient.java#L875-L905
mediathekview/MLib
src/main/java/de/mediathekview/mlib/filmlisten/WriteFilmlistJson.java
WriteFilmlistJson.filmlisteSchreibenJsonCompressed
public void filmlisteSchreibenJsonCompressed(String datei, ListeFilme listeFilme) { final String tempFile = datei + "_temp"; filmlisteSchreibenJson(tempFile, listeFilme); try { Log.sysLog("Komprimiere Datei: " + datei); if (datei.endsWith(Const.FORMAT_XZ)) { final Path xz = testNativeXz(); if (xz != null) { Process p = new ProcessBuilder(xz.toString(), "-9", tempFile).start(); final int exitCode = p.waitFor(); if (exitCode == 0) { Files.move(Paths.get(tempFile + ".xz"), Paths.get(datei), StandardCopyOption.REPLACE_EXISTING); } } else compressFile(tempFile, datei); } Files.deleteIfExists(Paths.get(tempFile)); } catch (IOException | InterruptedException ex) { Log.sysLog("Komprimieren fehlgeschlagen"); } }
java
public void filmlisteSchreibenJsonCompressed(String datei, ListeFilme listeFilme) { final String tempFile = datei + "_temp"; filmlisteSchreibenJson(tempFile, listeFilme); try { Log.sysLog("Komprimiere Datei: " + datei); if (datei.endsWith(Const.FORMAT_XZ)) { final Path xz = testNativeXz(); if (xz != null) { Process p = new ProcessBuilder(xz.toString(), "-9", tempFile).start(); final int exitCode = p.waitFor(); if (exitCode == 0) { Files.move(Paths.get(tempFile + ".xz"), Paths.get(datei), StandardCopyOption.REPLACE_EXISTING); } } else compressFile(tempFile, datei); } Files.deleteIfExists(Paths.get(tempFile)); } catch (IOException | InterruptedException ex) { Log.sysLog("Komprimieren fehlgeschlagen"); } }
[ "public", "void", "filmlisteSchreibenJsonCompressed", "(", "String", "datei", ",", "ListeFilme", "listeFilme", ")", "{", "final", "String", "tempFile", "=", "datei", "+", "\"_temp\"", ";", "filmlisteSchreibenJson", "(", "tempFile", ",", "listeFilme", ")", ";", "tr...
Write film data and compress with LZMA2. @param datei file path @param listeFilme film data
[ "Write", "film", "data", "and", "compress", "with", "LZMA2", "." ]
train
https://github.com/mediathekview/MLib/blob/01fd5791d87390fea7536275b8a2d4407fc00908/src/main/java/de/mediathekview/mlib/filmlisten/WriteFilmlistJson.java#L74-L96
Azure/azure-sdk-for-java
automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ModulesInner.java
ModulesInner.listByAutomationAccountWithServiceResponseAsync
public Observable<ServiceResponse<Page<ModuleInner>>> listByAutomationAccountWithServiceResponseAsync(final String resourceGroupName, final String automationAccountName) { return listByAutomationAccountSinglePageAsync(resourceGroupName, automationAccountName) .concatMap(new Func1<ServiceResponse<Page<ModuleInner>>, Observable<ServiceResponse<Page<ModuleInner>>>>() { @Override public Observable<ServiceResponse<Page<ModuleInner>>> call(ServiceResponse<Page<ModuleInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAutomationAccountNextWithServiceResponseAsync(nextPageLink)); } }); }
java
public Observable<ServiceResponse<Page<ModuleInner>>> listByAutomationAccountWithServiceResponseAsync(final String resourceGroupName, final String automationAccountName) { return listByAutomationAccountSinglePageAsync(resourceGroupName, automationAccountName) .concatMap(new Func1<ServiceResponse<Page<ModuleInner>>, Observable<ServiceResponse<Page<ModuleInner>>>>() { @Override public Observable<ServiceResponse<Page<ModuleInner>>> call(ServiceResponse<Page<ModuleInner>> page) { String nextPageLink = page.body().nextPageLink(); if (nextPageLink == null) { return Observable.just(page); } return Observable.just(page).concatWith(listByAutomationAccountNextWithServiceResponseAsync(nextPageLink)); } }); }
[ "public", "Observable", "<", "ServiceResponse", "<", "Page", "<", "ModuleInner", ">", ">", ">", "listByAutomationAccountWithServiceResponseAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "automationAccountName", ")", "{", "return", "listByAu...
Retrieve a list of modules. @param resourceGroupName Name of an Azure Resource group. @param automationAccountName The name of the automation account. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ModuleInner&gt; object
[ "Retrieve", "a", "list", "of", "modules", "." ]
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/ModulesInner.java#L540-L552
threerings/playn
core/src/playn/core/AbstractPlatform.java
AbstractPlatform.notifySuccess
public <T> void notifySuccess(final Callback<T> callback, final T result) { invokeLater(new Runnable() { public void run() { callback.onSuccess(result); } }); }
java
public <T> void notifySuccess(final Callback<T> callback, final T result) { invokeLater(new Runnable() { public void run() { callback.onSuccess(result); } }); }
[ "public", "<", "T", ">", "void", "notifySuccess", "(", "final", "Callback", "<", "T", ">", "callback", ",", "final", "T", "result", ")", "{", "invokeLater", "(", "new", "Runnable", "(", ")", "{", "public", "void", "run", "(", ")", "{", "callback", "....
Delivers {@code result} to {@code callback} on the next game tick (on the PlayN thread).
[ "Delivers", "{" ]
train
https://github.com/threerings/playn/blob/c266eeb39188dcada4b00992a0d1199759e03d42/core/src/playn/core/AbstractPlatform.java#L66-L72
Ordinastie/MalisisCore
src/main/java/net/malisis/core/MalisisCore.java
MalisisCore.isClientClass
private boolean isClientClass(String className, Set<ASMData> clientClasses) { for (ASMData data : clientClasses) { if (data.getClassName().equals(className) && data.getObjectName().equals(data.getClassName()) && ((ModAnnotation.EnumHolder) data.getAnnotationInfo().get("value")).getValue().equals("CLIENT")) return true; } return false; }
java
private boolean isClientClass(String className, Set<ASMData> clientClasses) { for (ASMData data : clientClasses) { if (data.getClassName().equals(className) && data.getObjectName().equals(data.getClassName()) && ((ModAnnotation.EnumHolder) data.getAnnotationInfo().get("value")).getValue().equals("CLIENT")) return true; } return false; }
[ "private", "boolean", "isClientClass", "(", "String", "className", ",", "Set", "<", "ASMData", ">", "clientClasses", ")", "{", "for", "(", "ASMData", "data", ":", "clientClasses", ")", "{", "if", "(", "data", ".", "getClassName", "(", ")", ".", "equals", ...
Checks if is the specified class has a @SideOnly(Side.CLIENT) annotation. @param className the class name @param clientClasses the client classes @return true, if is client class
[ "Checks", "if", "is", "the", "specified", "class", "has", "a", "@SideOnly", "(", "Side", ".", "CLIENT", ")", "annotation", "." ]
train
https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/MalisisCore.java#L218-L227
agapsys/captcha-servlet
src/main/java/com/agapsys/captcha/CaptchaServlet.java
CaptchaServlet.isValid
public final boolean isValid(HttpServletRequest req, String token) { String storedToken = getStoredToken(req); if (storedToken == null) return false; return storedToken.equals(token); }
java
public final boolean isValid(HttpServletRequest req, String token) { String storedToken = getStoredToken(req); if (storedToken == null) return false; return storedToken.equals(token); }
[ "public", "final", "boolean", "isValid", "(", "HttpServletRequest", "req", ",", "String", "token", ")", "{", "String", "storedToken", "=", "getStoredToken", "(", "req", ")", ";", "if", "(", "storedToken", "==", "null", ")", "return", "false", ";", "return", ...
Tests given token against stored one. @param req request used to retrieve stored cookie @param token token to be tested @return a boolean indicating if given token is valid.
[ "Tests", "given", "token", "against", "stored", "one", "." ]
train
https://github.com/agapsys/captcha-servlet/blob/35ec59de53f115646f41bfe72dc5f30187204ee4/src/main/java/com/agapsys/captcha/CaptchaServlet.java#L53-L60
aws/aws-sdk-java
aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/UpdateIntegrationResponseResult.java
UpdateIntegrationResponseResult.withResponseParameters
public UpdateIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) { setResponseParameters(responseParameters); return this; }
java
public UpdateIntegrationResponseResult withResponseParameters(java.util.Map<String, String> responseParameters) { setResponseParameters(responseParameters); return this; }
[ "public", "UpdateIntegrationResponseResult", "withResponseParameters", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "responseParameters", ")", "{", "setResponseParameters", "(", "responseParameters", ")", ";", "return", "this", ";", "}" ]
<p> A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. </p> @param responseParameters A key-value map specifying response parameters that are passed to the method response from the back end. The key is a method response header parameter name and the mapped value is an integration response header value, a static value enclosed within a pair of single quotes, or a JSON expression from the integration response body. The mapping key must match the pattern of <code>method.response.header.{name}</code>, where <code>name</code> is a valid and unique header name. The mapped non-static value must match the pattern of <code>integration.response.header.{name}</code> or <code>integration.response.body.{JSON-expression}</code>, where <code>name</code> is a valid and unique response header name and <code>JSON-expression</code> is a valid JSON expression without the <code>$</code> prefix. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "A", "key", "-", "value", "map", "specifying", "response", "parameters", "that", "are", "passed", "to", "the", "method", "response", "from", "the", "back", "end", ".", "The", "key", "is", "a", "method", "response", "header", "parameter", "name",...
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-api-gateway/src/main/java/com/amazonaws/services/apigateway/model/UpdateIntegrationResponseResult.java#L284-L287
virgo47/javasimon
core/src/main/java/org/javasimon/callback/quantiles/QuantilesCallback.java
QuantilesCallback.createBuckets
protected final Buckets createBuckets(Stopwatch stopwatch, long min, long max, int bucketNb) { Buckets buckets = bucketsType.createBuckets(stopwatch, min, max, bucketNb); buckets.setLogTemplate(createLogTemplate(stopwatch)); return buckets; }
java
protected final Buckets createBuckets(Stopwatch stopwatch, long min, long max, int bucketNb) { Buckets buckets = bucketsType.createBuckets(stopwatch, min, max, bucketNb); buckets.setLogTemplate(createLogTemplate(stopwatch)); return buckets; }
[ "protected", "final", "Buckets", "createBuckets", "(", "Stopwatch", "stopwatch", ",", "long", "min", ",", "long", "max", ",", "int", "bucketNb", ")", "{", "Buckets", "buckets", "=", "bucketsType", ".", "createBuckets", "(", "stopwatch", ",", "min", ",", "max...
Factory method to create a Buckets object using given configuration. @param stopwatch Target Stopwatch @param min Min bound @param max Max bound @param bucketNb Number of buckets between min and max @return Buckets
[ "Factory", "method", "to", "create", "a", "Buckets", "object", "using", "given", "configuration", "." ]
train
https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/quantiles/QuantilesCallback.java#L106-L110
svenkubiak/mangooio
mangooio-core/src/main/java/io/mangoo/utils/MangooUtils.java
MangooUtils.readableFileSize
public static String readableFileSize(long size) { if (size <= 0) { return "0"; } int index = (int) (Math.log10(size) / Math.log10(CONVERTION)); return new DecimalFormat("#,##0.#").format(size / Math.pow(CONVERTION, index)) + " " + UNITS[index]; }
java
public static String readableFileSize(long size) { if (size <= 0) { return "0"; } int index = (int) (Math.log10(size) / Math.log10(CONVERTION)); return new DecimalFormat("#,##0.#").format(size / Math.pow(CONVERTION, index)) + " " + UNITS[index]; }
[ "public", "static", "String", "readableFileSize", "(", "long", "size", ")", "{", "if", "(", "size", "<=", "0", ")", "{", "return", "\"0\"", ";", "}", "int", "index", "=", "(", "int", ")", "(", "Math", ".", "log10", "(", "size", ")", "/", "Math", ...
Converts a given file size into a readable file size including unit @param size The size in bytes to convert @return Readable files size, e.g. 24 MB
[ "Converts", "a", "given", "file", "size", "into", "a", "readable", "file", "size", "including", "unit" ]
train
https://github.com/svenkubiak/mangooio/blob/b3beb6d09510dbbab0ed947d5069c463e1fda6e7/mangooio-core/src/main/java/io/mangoo/utils/MangooUtils.java#L103-L110
graknlabs/grakn
server/src/graql/reasoner/atom/Atom.java
Atom.semanticDifference
public SemanticDifference semanticDifference(Atom parentAtom, Unifier unifier) { Set<VariableDefinition> diff = new HashSet<>(); ImmutableMap<Variable, Type> childVarTypeMap = this.getParentQuery().getVarTypeMap(false); ImmutableMap<Variable, Type> parentVarTypeMap = parentAtom.getParentQuery().getVarTypeMap(false); Unifier unifierInverse = unifier.inverse(); unifier.mappings().forEach(m -> { Variable childVar = m.getKey(); Variable parentVar = m.getValue(); Type childType = childVarTypeMap.get(childVar); Type parentType = parentVarTypeMap.get(parentVar); Type type = childType != null ? parentType != null ? (!parentType.equals(childType) ? childType : null) : childType : null; Set<ValuePredicate> predicates = this.getPredicates(childVar, ValuePredicate.class).collect(toSet()); parentAtom.getPredicates(parentVar, ValuePredicate.class) .flatMap(vp -> vp.unify(unifierInverse).stream()) .forEach(predicates::remove); diff.add(new VariableDefinition(childVar, type, null, new HashSet<>(), predicates)); }); return new SemanticDifference(diff); }
java
public SemanticDifference semanticDifference(Atom parentAtom, Unifier unifier) { Set<VariableDefinition> diff = new HashSet<>(); ImmutableMap<Variable, Type> childVarTypeMap = this.getParentQuery().getVarTypeMap(false); ImmutableMap<Variable, Type> parentVarTypeMap = parentAtom.getParentQuery().getVarTypeMap(false); Unifier unifierInverse = unifier.inverse(); unifier.mappings().forEach(m -> { Variable childVar = m.getKey(); Variable parentVar = m.getValue(); Type childType = childVarTypeMap.get(childVar); Type parentType = parentVarTypeMap.get(parentVar); Type type = childType != null ? parentType != null ? (!parentType.equals(childType) ? childType : null) : childType : null; Set<ValuePredicate> predicates = this.getPredicates(childVar, ValuePredicate.class).collect(toSet()); parentAtom.getPredicates(parentVar, ValuePredicate.class) .flatMap(vp -> vp.unify(unifierInverse).stream()) .forEach(predicates::remove); diff.add(new VariableDefinition(childVar, type, null, new HashSet<>(), predicates)); }); return new SemanticDifference(diff); }
[ "public", "SemanticDifference", "semanticDifference", "(", "Atom", "parentAtom", ",", "Unifier", "unifier", ")", "{", "Set", "<", "VariableDefinition", ">", "diff", "=", "new", "HashSet", "<>", "(", ")", ";", "ImmutableMap", "<", "Variable", ",", "Type", ">", ...
Calculates the semantic difference between the parent and this (child) atom, that needs to be applied on A(P) to find the subset belonging to A(C). @param parentAtom parent atom @param unifier child->parent unifier @return semantic difference between child and parent
[ "Calculates", "the", "semantic", "difference", "between", "the", "parent", "and", "this", "(", "child", ")", "atom", "that", "needs", "to", "be", "applied", "on", "A", "(", "P", ")", "to", "find", "the", "subset", "belonging", "to", "A", "(", "C", ")",...
train
https://github.com/graknlabs/grakn/blob/6aaee75ea846202474d591f8809d62028262fac5/server/src/graql/reasoner/atom/Atom.java#L466-L491
skyscreamer/JSONassert
src/main/java/org/skyscreamer/jsonassert/JSONAssert.java
JSONAssert.assertNotEquals
public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode) throws JSONException { assertNotEquals("", expected, actual, compareMode); }
java
public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode) throws JSONException { assertNotEquals("", expected, actual, compareMode); }
[ "public", "static", "void", "assertNotEquals", "(", "JSONObject", "expected", ",", "JSONObject", "actual", ",", "JSONCompareMode", "compareMode", ")", "throws", "JSONException", "{", "assertNotEquals", "(", "\"\"", ",", "expected", ",", "actual", ",", "compareMode",...
Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an {@link AssertionError}. @param expected Expected JSONObject @param actual JSONObject to compare @param compareMode Specifies which comparison mode to use @throws JSONException JSON parsing error
[ "Asserts", "that", "the", "JSONObject", "provided", "does", "not", "match", "the", "expected", "JSONObject", ".", "If", "it", "is", "it", "throws", "an", "{", "@link", "AssertionError", "}", "." ]
train
https://github.com/skyscreamer/JSONassert/blob/830efcf546d07f955d8a213cc5c8a1db34d78f04/src/main/java/org/skyscreamer/jsonassert/JSONAssert.java#L617-L620
looly/hutool
hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java
DateUtil.isSameDay
public static boolean isSameDay(final Date date1, final Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } return isSameDay(calendar(date1), calendar(date2)); }
java
public static boolean isSameDay(final Date date1, final Date date2) { if (date1 == null || date2 == null) { throw new IllegalArgumentException("The date must not be null"); } return isSameDay(calendar(date1), calendar(date2)); }
[ "public", "static", "boolean", "isSameDay", "(", "final", "Date", "date1", ",", "final", "Date", "date2", ")", "{", "if", "(", "date1", "==", "null", "||", "date2", "==", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"The date must not...
比较两个日期是否为同一天 @param date1 日期1 @param date2 日期2 @return 是否为同一天 @since 4.1.13
[ "比较两个日期是否为同一天" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/date/DateUtil.java#L1394-L1399
kuali/ojb-1.0.4
src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java
QueryReferenceBroker.getFKQuery
private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds) { Query fkQuery; QueryByCriteria fkQueryCrit; if (cds.isMtoNRelation()) { fkQueryCrit = getFKQueryMtoN(obj, cld, cds); } else { fkQueryCrit = getFKQuery1toN(obj, cld, cds); } // check if collection must be ordered if (!cds.getOrderBy().isEmpty()) { Iterator iter = cds.getOrderBy().iterator(); while (iter.hasNext()) { fkQueryCrit.addOrderBy((FieldHelper)iter.next()); } } // BRJ: customize the query if (cds.getQueryCustomizer() != null) { fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit); } else { fkQuery = fkQueryCrit; } return fkQuery; }
java
private Query getFKQuery(Object obj, ClassDescriptor cld, CollectionDescriptor cds) { Query fkQuery; QueryByCriteria fkQueryCrit; if (cds.isMtoNRelation()) { fkQueryCrit = getFKQueryMtoN(obj, cld, cds); } else { fkQueryCrit = getFKQuery1toN(obj, cld, cds); } // check if collection must be ordered if (!cds.getOrderBy().isEmpty()) { Iterator iter = cds.getOrderBy().iterator(); while (iter.hasNext()) { fkQueryCrit.addOrderBy((FieldHelper)iter.next()); } } // BRJ: customize the query if (cds.getQueryCustomizer() != null) { fkQuery = cds.getQueryCustomizer().customizeQuery(obj, pb, cds, fkQueryCrit); } else { fkQuery = fkQueryCrit; } return fkQuery; }
[ "private", "Query", "getFKQuery", "(", "Object", "obj", ",", "ClassDescriptor", "cld", ",", "CollectionDescriptor", "cds", ")", "{", "Query", "fkQuery", ";", "QueryByCriteria", "fkQueryCrit", ";", "if", "(", "cds", ".", "isMtoNRelation", "(", ")", ")", "{", ...
Answer the foreign key query to retrieve the collection defined by CollectionDescriptor
[ "Answer", "the", "foreign", "key", "query", "to", "retrieve", "the", "collection", "defined", "by", "CollectionDescriptor" ]
train
https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/core/QueryReferenceBroker.java#L820-L855
apache/groovy
src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java
ResourceGroovyMethods.withReader
public static <T> T withReader(URL url, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException { return IOGroovyMethods.withReader(url.openConnection().getInputStream(), closure); }
java
public static <T> T withReader(URL url, @ClosureParams(value = SimpleType.class, options = "java.io.Reader") Closure<T> closure) throws IOException { return IOGroovyMethods.withReader(url.openConnection().getInputStream(), closure); }
[ "public", "static", "<", "T", ">", "T", "withReader", "(", "URL", "url", ",", "@", "ClosureParams", "(", "value", "=", "SimpleType", ".", "class", ",", "options", "=", "\"java.io.Reader\"", ")", "Closure", "<", "T", ">", "closure", ")", "throws", "IOExce...
Helper method to create a new BufferedReader for a URL and then passes it to the closure. The reader is closed after the closure returns. @param url a URL @param closure the closure to invoke with the reader @return the value returned by the closure @throws IOException if an IOException occurs. @since 1.5.2
[ "Helper", "method", "to", "create", "a", "new", "BufferedReader", "for", "a", "URL", "and", "then", "passes", "it", "to", "the", "closure", ".", "The", "reader", "is", "closed", "after", "the", "closure", "returns", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/ResourceGroovyMethods.java#L2111-L2113
Wikidata/Wikidata-Toolkit
wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/TermStatementUpdate.java
TermStatementUpdate.addAlias
protected void addAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang); NameWithUpdate currentLabel = newLabels.get(lang); // If there isn't any label for that language, put the alias there if (currentLabel == null) { newLabels.put(lang, new NameWithUpdate(alias, true)); // If the new alias is equal to the current label, skip it } else if (!currentLabel.value.equals(alias)) { if (currentAliasesUpdate == null) { currentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true); } List<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases; if(!currentAliases.contains(alias)) { currentAliases.add(alias); currentAliasesUpdate.added.add(alias); currentAliasesUpdate.write = true; } newAliases.put(lang, currentAliasesUpdate); } }
java
protected void addAlias(MonolingualTextValue alias) { String lang = alias.getLanguageCode(); AliasesWithUpdate currentAliasesUpdate = newAliases.get(lang); NameWithUpdate currentLabel = newLabels.get(lang); // If there isn't any label for that language, put the alias there if (currentLabel == null) { newLabels.put(lang, new NameWithUpdate(alias, true)); // If the new alias is equal to the current label, skip it } else if (!currentLabel.value.equals(alias)) { if (currentAliasesUpdate == null) { currentAliasesUpdate = new AliasesWithUpdate(new ArrayList<MonolingualTextValue>(), true); } List<MonolingualTextValue> currentAliases = currentAliasesUpdate.aliases; if(!currentAliases.contains(alias)) { currentAliases.add(alias); currentAliasesUpdate.added.add(alias); currentAliasesUpdate.write = true; } newAliases.put(lang, currentAliasesUpdate); } }
[ "protected", "void", "addAlias", "(", "MonolingualTextValue", "alias", ")", "{", "String", "lang", "=", "alias", ".", "getLanguageCode", "(", ")", ";", "AliasesWithUpdate", "currentAliasesUpdate", "=", "newAliases", ".", "get", "(", "lang", ")", ";", "NameWithUp...
Adds an individual alias. It will be merged with the current list of aliases, or added as a label if there is no label for this item in this language yet. @param alias the alias to add
[ "Adds", "an", "individual", "alias", ".", "It", "will", "be", "merged", "with", "the", "current", "list", "of", "aliases", "or", "added", "as", "a", "label", "if", "there", "is", "no", "label", "for", "this", "item", "in", "this", "language", "yet", "....
train
https://github.com/Wikidata/Wikidata-Toolkit/blob/7732851dda47e1febff406fba27bfec023f4786e/wdtk-wikibaseapi/src/main/java/org/wikidata/wdtk/wikibaseapi/TermStatementUpdate.java#L203-L224
roboconf/roboconf-platform
core/roboconf-dm/src/main/java/net/roboconf/dm/internal/utils/ConfigurationUtils.java
ConfigurationUtils.saveApplicationBindings
public static void saveApplicationBindings( Application app ) { File descDir = new File( app.getDirectory(), Constants.PROJECT_DIR_DESC ); File appBindingsFile = new File( descDir, APP_BINDINGS_FILE ); // Convert the bindings map Map<String,String> format = new HashMap<> (); for( Map.Entry<String,Set<String>> entry : app.getApplicationBindings().entrySet()) { String s = Utils.format( entry.getValue(), ", " ); format.put( entry.getKey(), s ); } // Save it Properties props = new Properties(); props.putAll( format ); try { Utils.createDirectory( descDir ); Utils.writePropertiesFile( props, appBindingsFile ); } catch( IOException e ) { Logger logger = Logger.getLogger( ConfigurationUtils.class.getName()); logger.severe( "Failed to save application bindings for " + app + ". " + e.getMessage()); Utils.logException( logger, e ); } }
java
public static void saveApplicationBindings( Application app ) { File descDir = new File( app.getDirectory(), Constants.PROJECT_DIR_DESC ); File appBindingsFile = new File( descDir, APP_BINDINGS_FILE ); // Convert the bindings map Map<String,String> format = new HashMap<> (); for( Map.Entry<String,Set<String>> entry : app.getApplicationBindings().entrySet()) { String s = Utils.format( entry.getValue(), ", " ); format.put( entry.getKey(), s ); } // Save it Properties props = new Properties(); props.putAll( format ); try { Utils.createDirectory( descDir ); Utils.writePropertiesFile( props, appBindingsFile ); } catch( IOException e ) { Logger logger = Logger.getLogger( ConfigurationUtils.class.getName()); logger.severe( "Failed to save application bindings for " + app + ". " + e.getMessage()); Utils.logException( logger, e ); } }
[ "public", "static", "void", "saveApplicationBindings", "(", "Application", "app", ")", "{", "File", "descDir", "=", "new", "File", "(", "app", ".", "getDirectory", "(", ")", ",", "Constants", ".", "PROJECT_DIR_DESC", ")", ";", "File", "appBindingsFile", "=", ...
Saves the application bindings into the DM's directory. @param app a non-null application @param configurationDirectory the DM's configuration directory
[ "Saves", "the", "application", "bindings", "into", "the", "DM", "s", "directory", "." ]
train
https://github.com/roboconf/roboconf-platform/blob/add54eead479effb138d0ff53a2d637902b82702/core/roboconf-dm/src/main/java/net/roboconf/dm/internal/utils/ConfigurationUtils.java#L202-L227
unbescape/unbescape
src/main/java/org/unbescape/java/JavaEscape.java
JavaEscape.escapeJava
public static void escapeJava(final Reader reader, final Writer writer, final JavaEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } JavaEscapeUtil.escape(reader, writer, level); }
java
public static void escapeJava(final Reader reader, final Writer writer, final JavaEscapeLevel level) throws IOException { if (writer == null) { throw new IllegalArgumentException("Argument 'writer' cannot be null"); } if (level == null) { throw new IllegalArgumentException("The 'level' argument cannot be null"); } JavaEscapeUtil.escape(reader, writer, level); }
[ "public", "static", "void", "escapeJava", "(", "final", "Reader", "reader", ",", "final", "Writer", "writer", ",", "final", "JavaEscapeLevel", "level", ")", "throws", "IOException", "{", "if", "(", "writer", "==", "null", ")", "{", "throw", "new", "IllegalAr...
<p> Perform a (configurable) Java <strong>escape</strong> operation on a <tt>Reader</tt> input, writing results to a <tt>Writer</tt>. </p> <p> This method will perform an escape operation according to the specified {@link org.unbescape.java.JavaEscapeLevel} argument value. </p> <p> All other <tt>String</tt>/<tt>Writer</tt>-based <tt>escapeJava*(...)</tt> methods call this one with preconfigured <tt>level</tt> values. </p> <p> This method is <strong>thread-safe</strong>. </p> @param reader the <tt>Reader</tt> reading the text to 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>. @param level the escape level to be applied, see {@link org.unbescape.java.JavaEscapeLevel}. @throws IOException if an input/output exception occurs @since 1.1.2
[ "<p", ">", "Perform", "a", "(", "configurable", ")", "Java", "<strong", ">", "escape<", "/", "strong", ">", "operation", "on", "a", "<tt", ">", "Reader<", "/", "tt", ">", "input", "writing", "results", "to", "a", "<tt", ">", "Writer<", "/", "tt", ">"...
train
https://github.com/unbescape/unbescape/blob/ec5435fb3508c2eed25d8165dc27ded2602cae13/src/main/java/org/unbescape/java/JavaEscape.java#L639-L652
Stratio/stratio-cassandra
src/java/org/apache/cassandra/scheduler/RoundRobinScheduler.java
RoundRobinScheduler.getWeightedQueue
private WeightedQueue getWeightedQueue(String id) { WeightedQueue weightedQueue = queues.get(id); if (weightedQueue != null) // queue existed return weightedQueue; WeightedQueue maybenew = new WeightedQueue(id, getWeight(id)); weightedQueue = queues.putIfAbsent(id, maybenew); if (weightedQueue == null) { // created new queue: register for monitoring maybenew.register(); return maybenew; } // another thread created the queue return weightedQueue; }
java
private WeightedQueue getWeightedQueue(String id) { WeightedQueue weightedQueue = queues.get(id); if (weightedQueue != null) // queue existed return weightedQueue; WeightedQueue maybenew = new WeightedQueue(id, getWeight(id)); weightedQueue = queues.putIfAbsent(id, maybenew); if (weightedQueue == null) { // created new queue: register for monitoring maybenew.register(); return maybenew; } // another thread created the queue return weightedQueue; }
[ "private", "WeightedQueue", "getWeightedQueue", "(", "String", "id", ")", "{", "WeightedQueue", "weightedQueue", "=", "queues", ".", "get", "(", "id", ")", ";", "if", "(", "weightedQueue", "!=", "null", ")", "// queue existed", "return", "weightedQueue", ";", ...
/* Get the Queue for the respective id, if one is not available create a new queue for that corresponding id and return it
[ "/", "*", "Get", "the", "Queue", "for", "the", "respective", "id", "if", "one", "is", "not", "available", "create", "a", "new", "queue", "for", "that", "corresponding", "id", "and", "return", "it" ]
train
https://github.com/Stratio/stratio-cassandra/blob/f6416b43ad5309083349ad56266450fa8c6a2106/src/java/org/apache/cassandra/scheduler/RoundRobinScheduler.java#L137-L155
joniles/mpxj
src/main/java/net/sf/mpxj/json/JsonWriter.java
JsonWriter.writeDoubleField
private void writeDoubleField(String fieldName, Object value) throws IOException { double val = ((Number) value).doubleValue(); if (val != 0) { m_writer.writeNameValuePair(fieldName, val); } }
java
private void writeDoubleField(String fieldName, Object value) throws IOException { double val = ((Number) value).doubleValue(); if (val != 0) { m_writer.writeNameValuePair(fieldName, val); } }
[ "private", "void", "writeDoubleField", "(", "String", "fieldName", ",", "Object", "value", ")", "throws", "IOException", "{", "double", "val", "=", "(", "(", "Number", ")", "value", ")", ".", "doubleValue", "(", ")", ";", "if", "(", "val", "!=", "0", "...
Write an double field to the JSON file. @param fieldName field name @param value field value
[ "Write", "an", "double", "field", "to", "the", "JSON", "file", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/json/JsonWriter.java#L385-L392
btrplace/scheduler
split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SubMapping.java
SubMapping.fillVMIndex
public void fillVMIndex(TIntIntHashMap index, int p) { for (Node n : scope) { for (VM v : parent.getRunningVMs(n)) { index.put(v.id(), p); } for (VM v : parent.getSleepingVMs(n)) { index.put(v.id(), p); } } for (VM v : ready) { index.put(v.id(), p); } }
java
public void fillVMIndex(TIntIntHashMap index, int p) { for (Node n : scope) { for (VM v : parent.getRunningVMs(n)) { index.put(v.id(), p); } for (VM v : parent.getSleepingVMs(n)) { index.put(v.id(), p); } } for (VM v : ready) { index.put(v.id(), p); } }
[ "public", "void", "fillVMIndex", "(", "TIntIntHashMap", "index", ",", "int", "p", ")", "{", "for", "(", "Node", "n", ":", "scope", ")", "{", "for", "(", "VM", "v", ":", "parent", ".", "getRunningVMs", "(", "n", ")", ")", "{", "index", ".", "put", ...
Fill an index with the VM presents in this mapping @param index the index to fill @param p the index value to use for each VM in the mapping
[ "Fill", "an", "index", "with", "the", "VM", "presents", "in", "this", "mapping" ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/split/src/main/java/org/btrplace/scheduler/runner/disjoint/model/SubMapping.java#L269-L281
hawkular/hawkular-apm
examples/polyglot-zipkin/java-dropwizard/src/main/java/org/hawkular/apm/example/dropwizard/util/DatabaseUtils.java
DatabaseUtils.readSqlStatements
private static String[] readSqlStatements(URL url) { try { char buffer[] = new char[256]; StringBuilder result = new StringBuilder(); InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); while (true) { int count = reader.read(buffer); if (count < 0) { break; } result.append(buffer, 0, count); } return result.toString().split(";"); } catch (IOException ex) { throw new RuntimeException("Cannot read " + url, ex); } }
java
private static String[] readSqlStatements(URL url) { try { char buffer[] = new char[256]; StringBuilder result = new StringBuilder(); InputStreamReader reader = new InputStreamReader(url.openStream(), "UTF-8"); while (true) { int count = reader.read(buffer); if (count < 0) { break; } result.append(buffer, 0, count); } return result.toString().split(";"); } catch (IOException ex) { throw new RuntimeException("Cannot read " + url, ex); } }
[ "private", "static", "String", "[", "]", "readSqlStatements", "(", "URL", "url", ")", "{", "try", "{", "char", "buffer", "[", "]", "=", "new", "char", "[", "256", "]", ";", "StringBuilder", "result", "=", "new", "StringBuilder", "(", ")", ";", "InputSt...
Reads SQL statements from file. SQL commands in file must be separated by a semicolon. @param url url of the file @return array of command strings
[ "Reads", "SQL", "statements", "from", "file", ".", "SQL", "commands", "in", "file", "must", "be", "separated", "by", "a", "semicolon", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/examples/polyglot-zipkin/java-dropwizard/src/main/java/org/hawkular/apm/example/dropwizard/util/DatabaseUtils.java#L74-L90
loicoudot/java4cpp-core
src/main/java/com/github/loicoudot/java4cpp/FileManager.java
FileManager.saveFile
private synchronized void saveFile(String fileContent, File fileName) { try { if (imports.getSymbols().contains(fileName.getName())) { logInfo(" imported " + fileName); ++imported; } else { export.getSymbols().add(fileName.getName()); MessageDigest algo = MessageDigest.getInstance("MD5"); algo.update(fileContent.getBytes()); String md5 = bytesToHexString(algo.digest()); newHashes.put(fileName.getName(), md5); if (!context.getSettings().isUseHash() || !oldFiles.contains(fileName) || !md5.equals(oldHashes.getProperty(fileName.getName()))) { fileName.setWritable(true); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(fileName)); writer.write(fileContent.getBytes()); fileName.setWritable(false); writer.close(); ++generated; logInfo(" generated " + fileName); } else { ++skipped; logInfo(" skipped " + fileName); } oldFiles.remove(fileName); } } catch (Exception e) { throw new RuntimeException("Failed to save file " + e.getMessage()); } }
java
private synchronized void saveFile(String fileContent, File fileName) { try { if (imports.getSymbols().contains(fileName.getName())) { logInfo(" imported " + fileName); ++imported; } else { export.getSymbols().add(fileName.getName()); MessageDigest algo = MessageDigest.getInstance("MD5"); algo.update(fileContent.getBytes()); String md5 = bytesToHexString(algo.digest()); newHashes.put(fileName.getName(), md5); if (!context.getSettings().isUseHash() || !oldFiles.contains(fileName) || !md5.equals(oldHashes.getProperty(fileName.getName()))) { fileName.setWritable(true); BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(fileName)); writer.write(fileContent.getBytes()); fileName.setWritable(false); writer.close(); ++generated; logInfo(" generated " + fileName); } else { ++skipped; logInfo(" skipped " + fileName); } oldFiles.remove(fileName); } } catch (Exception e) { throw new RuntimeException("Failed to save file " + e.getMessage()); } }
[ "private", "synchronized", "void", "saveFile", "(", "String", "fileContent", ",", "File", "fileName", ")", "{", "try", "{", "if", "(", "imports", ".", "getSymbols", "(", ")", ".", "contains", "(", "fileName", ".", "getName", "(", ")", ")", ")", "{", "l...
Write the file {@code fileName} in the target directory with {@code fileContent}. If {@code useHash} is true, then the file is save if it's doesn't exist or if the content has changed.
[ "Write", "the", "file", "{" ]
train
https://github.com/loicoudot/java4cpp-core/blob/7fe5a5dd5a29c3f95b62f46eaacbb8f8778b9493/src/main/java/com/github/loicoudot/java4cpp/FileManager.java#L230-L259
greatman/craftconomy3
src/main/java/com/greatmancode/craftconomy3/Common.java
Common.addMetricsGraph
public void addMetricsGraph(String title, String value) { if (metrics != null) { Metrics.Graph graph = metrics.createGraph(title); graph.addPlotter(new Metrics.Plotter(value) { @Override public int getValue() { return 1; } }); } }
java
public void addMetricsGraph(String title, String value) { if (metrics != null) { Metrics.Graph graph = metrics.createGraph(title); graph.addPlotter(new Metrics.Plotter(value) { @Override public int getValue() { return 1; } }); } }
[ "public", "void", "addMetricsGraph", "(", "String", "title", ",", "String", "value", ")", "{", "if", "(", "metrics", "!=", "null", ")", "{", "Metrics", ".", "Graph", "graph", "=", "metrics", ".", "createGraph", "(", "title", ")", ";", "graph", ".", "ad...
Add a graph to Metrics @param title The title of the Graph @param value The value of the entry
[ "Add", "a", "graph", "to", "Metrics" ]
train
https://github.com/greatman/craftconomy3/blob/51b1b3de7d039e20c7418d1e70b8c4b02b8cf840/src/main/java/com/greatmancode/craftconomy3/Common.java#L460-L470
OpenLiberty/open-liberty
dev/wlp-generateRepositoryContent/src/com/ibm/ws/wlp/repository/XmlGenerator.java
XmlGenerator.createSchema
private Schema createSchema(JAXBContext context) throws IOException, SAXException { // This is surprisingly faffy for something that has a generateSchema method! This will only produce // a Result object, of which a schema result is not possible but you can produce dom results that // can be converted into dom sources to be read by the schema factory. As you can define multiple // namespaces you need to have a list of these. final List<DOMResult> schemaDomResults = new ArrayList<DOMResult>(); // First use the context to create the schema dom objects context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { DOMResult domResult = new DOMResult(); domResult.setSystemId(suggestedFileName); schemaDomResults.add(domResult); return domResult; } }); // convert to a form that can be used by the schema factory DOMSource[] schemaDomSources = new DOMSource[schemaDomResults.size()]; for (int i = 0; i < schemaDomResults.size(); i++) { DOMSource domSource = new DOMSource(schemaDomResults.get(i).getNode()); schemaDomSources[i] = domSource; } // Finally create the schema Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaDomSources); return schema; }
java
private Schema createSchema(JAXBContext context) throws IOException, SAXException { // This is surprisingly faffy for something that has a generateSchema method! This will only produce // a Result object, of which a schema result is not possible but you can produce dom results that // can be converted into dom sources to be read by the schema factory. As you can define multiple // namespaces you need to have a list of these. final List<DOMResult> schemaDomResults = new ArrayList<DOMResult>(); // First use the context to create the schema dom objects context.generateSchema(new SchemaOutputResolver() { @Override public Result createOutput(String namespaceUri, String suggestedFileName) throws IOException { DOMResult domResult = new DOMResult(); domResult.setSystemId(suggestedFileName); schemaDomResults.add(domResult); return domResult; } }); // convert to a form that can be used by the schema factory DOMSource[] schemaDomSources = new DOMSource[schemaDomResults.size()]; for (int i = 0; i < schemaDomResults.size(); i++) { DOMSource domSource = new DOMSource(schemaDomResults.get(i).getNode()); schemaDomSources[i] = domSource; } // Finally create the schema Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(schemaDomSources); return schema; }
[ "private", "Schema", "createSchema", "(", "JAXBContext", "context", ")", "throws", "IOException", ",", "SAXException", "{", "// This is surprisingly faffy for something that has a generateSchema method! This will only produce", "// a Result object, of which a schema result is not possible ...
This method will create a {@link Schema} from a {@link JAXBContext}. @param context The context to create the schema for @return The {@link Schema} for this context @throws IOException @throws SAXException
[ "This", "method", "will", "create", "a", "{", "@link", "Schema", "}", "from", "a", "{", "@link", "JAXBContext", "}", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/wlp-generateRepositoryContent/src/com/ibm/ws/wlp/repository/XmlGenerator.java#L197-L227
jetty-project/jetty-npn
npn-boot/src/main/java/sun/security/ssl/ClientHandshaker.java
ClientHandshaker.getSubjectAltName
private static Object getSubjectAltName(X509Certificate cert, int type) { Collection<List<?>> subjectAltNames; try { subjectAltNames = cert.getSubjectAlternativeNames(); } catch (CertificateParsingException cpe) { if (debug != null && Debug.isOn("handshake")) { System.out.println( "Attempt to obtain subjectAltNames extension failed!"); } return null; } if (subjectAltNames != null) { for (List<?> subjectAltName : subjectAltNames) { int subjectAltNameType = (Integer)subjectAltName.get(0); if (subjectAltNameType == type) { return subjectAltName.get(1); } } } return null; }
java
private static Object getSubjectAltName(X509Certificate cert, int type) { Collection<List<?>> subjectAltNames; try { subjectAltNames = cert.getSubjectAlternativeNames(); } catch (CertificateParsingException cpe) { if (debug != null && Debug.isOn("handshake")) { System.out.println( "Attempt to obtain subjectAltNames extension failed!"); } return null; } if (subjectAltNames != null) { for (List<?> subjectAltName : subjectAltNames) { int subjectAltNameType = (Integer)subjectAltName.get(0); if (subjectAltNameType == type) { return subjectAltName.get(1); } } } return null; }
[ "private", "static", "Object", "getSubjectAltName", "(", "X509Certificate", "cert", ",", "int", "type", ")", "{", "Collection", "<", "List", "<", "?", ">", ">", "subjectAltNames", ";", "try", "{", "subjectAltNames", "=", "cert", ".", "getSubjectAlternativeNames"...
/* Returns the subject alternative name of the specified type in the subjectAltNames extension of a certificate.
[ "/", "*", "Returns", "the", "subject", "alternative", "name", "of", "the", "specified", "type", "in", "the", "subjectAltNames", "extension", "of", "a", "certificate", "." ]
train
https://github.com/jetty-project/jetty-npn/blob/a26a7a5eabeeb57a63c6ee08fcf9b8cec1fa6c0d/npn-boot/src/main/java/sun/security/ssl/ClientHandshaker.java#L1569-L1592
line/armeria
spring/boot-autoconfigure/src/main/java/com/linecorp/armeria/spring/AbstractServiceRegistrationBean.java
AbstractServiceRegistrationBean.setDecorators
@SafeVarargs public final U setDecorators( Function<Service<HttpRequest, HttpResponse>, ? extends Service<HttpRequest, HttpResponse>>... decorators) { return setDecorators(ImmutableList.copyOf(requireNonNull(decorators, "decorators"))); }
java
@SafeVarargs public final U setDecorators( Function<Service<HttpRequest, HttpResponse>, ? extends Service<HttpRequest, HttpResponse>>... decorators) { return setDecorators(ImmutableList.copyOf(requireNonNull(decorators, "decorators"))); }
[ "@", "SafeVarargs", "public", "final", "U", "setDecorators", "(", "Function", "<", "Service", "<", "HttpRequest", ",", "HttpResponse", ">", ",", "?", "extends", "Service", "<", "HttpRequest", ",", "HttpResponse", ">", ">", "...", "decorators", ")", "{", "ret...
Sets the decorator of the annotated service object. {@code decorators} are applied to {@code service} in order.
[ "Sets", "the", "decorator", "of", "the", "annotated", "service", "object", ".", "{" ]
train
https://github.com/line/armeria/blob/67d29e019fd35a35f89c45cc8f9119ff9b12b44d/spring/boot-autoconfigure/src/main/java/com/linecorp/armeria/spring/AbstractServiceRegistrationBean.java#L116-L121
arxanchain/java-common
src/main/java/com/arxanfintech/common/util/RLP.java
RLP.encodeLength
public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); return new byte[] { firstByte }; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if (length > 0xFF) binaryLength = intToBytesNoLeadZeroes(length); else binaryLength = new byte[] { (byte) length }; byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1); return concatenate(new byte[] { firstByte }, binaryLength); } else { throw new RuntimeException("Input too long"); } }
java
public static byte[] encodeLength(int length, int offset) { if (length < SIZE_THRESHOLD) { byte firstByte = (byte) (length + offset); return new byte[] { firstByte }; } else if (length < MAX_ITEM_LENGTH) { byte[] binaryLength; if (length > 0xFF) binaryLength = intToBytesNoLeadZeroes(length); else binaryLength = new byte[] { (byte) length }; byte firstByte = (byte) (binaryLength.length + offset + SIZE_THRESHOLD - 1); return concatenate(new byte[] { firstByte }, binaryLength); } else { throw new RuntimeException("Input too long"); } }
[ "public", "static", "byte", "[", "]", "encodeLength", "(", "int", "length", ",", "int", "offset", ")", "{", "if", "(", "length", "<", "SIZE_THRESHOLD", ")", "{", "byte", "firstByte", "=", "(", "byte", ")", "(", "length", "+", "offset", ")", ";", "ret...
Integer limitation goes up to 2^31-1 so length can never be bigger than MAX_ITEM_LENGTH @param length length @param offset offset @return byte[]
[ "Integer", "limitation", "goes", "up", "to", "2^31", "-", "1", "so", "length", "can", "never", "be", "bigger", "than", "MAX_ITEM_LENGTH" ]
train
https://github.com/arxanchain/java-common/blob/3ddfedfd948f5bab3fee0b74b85cdce4702ed84e/src/main/java/com/arxanfintech/common/util/RLP.java#L437-L452
OpenLiberty/open-liberty
dev/com.ibm.ws.session/src/com/ibm/ws/session/StoreCallback.java
StoreCallback.sessionAttributeAccessed
public void sessionAttributeAccessed(ISession session, Object name, Object value) { _sessionStateEventDispatcher.sessionAttributeAccessed(session, name, value); }
java
public void sessionAttributeAccessed(ISession session, Object name, Object value) { _sessionStateEventDispatcher.sessionAttributeAccessed(session, name, value); }
[ "public", "void", "sessionAttributeAccessed", "(", "ISession", "session", ",", "Object", "name", ",", "Object", "value", ")", "{", "_sessionStateEventDispatcher", ".", "sessionAttributeAccessed", "(", "session", ",", "name", ",", "value", ")", ";", "}" ]
Method sessionAttributeAccessed <p> @param session @param name @param value @see com.ibm.wsspi.session.IStoreCallback#sessionAttributeAccessed(com.ibm.wsspi.session.ISession, java.lang.Object, java.lang.Object)
[ "Method", "sessionAttributeAccessed", "<p", ">" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.session/src/com/ibm/ws/session/StoreCallback.java#L196-L199
httpcache4j/httpcache4j
httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Conditionals.java
Conditionals.toHeaders
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get())); } if (unModifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get())); } return headers; }
java
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_NONE_MATCH, buildTagHeaderValue(getNoneMatch()))); } if (modifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_MODIFIED_SINCE, modifiedSince.get())); } if (unModifiedSince.isPresent()) { headers = headers.set(HeaderUtils.toHttpDate(HeaderConstants.IF_UNMODIFIED_SINCE, unModifiedSince.get())); } return headers; }
[ "public", "Headers", "toHeaders", "(", ")", "{", "Headers", "headers", "=", "new", "Headers", "(", ")", ";", "if", "(", "!", "getMatch", "(", ")", ".", "isEmpty", "(", ")", ")", "{", "headers", "=", "headers", ".", "add", "(", "new", "Header", "(",...
Converts the Conditionals into real headers. @return real headers.
[ "Converts", "the", "Conditionals", "into", "real", "headers", "." ]
train
https://github.com/httpcache4j/httpcache4j/blob/9c07ebd63cd104a99eb9e771f760f14efa4fe0f6/httpcache4j-api/src/main/java/org/codehaus/httpcache4j/Conditionals.java#L216-L232
ujmp/universal-java-matrix-package
ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java
Ginv.swapCols
public static void swapCols(double[][] matrix, int col1, int col2) { double temp = 0; int rows = matrix.length; double[] r = null; for (int row = 0; row < rows; row++) { r = matrix[row]; temp = r[col1]; r[col1] = r[col2]; r[col2] = temp; } }
java
public static void swapCols(double[][] matrix, int col1, int col2) { double temp = 0; int rows = matrix.length; double[] r = null; for (int row = 0; row < rows; row++) { r = matrix[row]; temp = r[col1]; r[col1] = r[col2]; r[col2] = temp; } }
[ "public", "static", "void", "swapCols", "(", "double", "[", "]", "[", "]", "matrix", ",", "int", "col1", ",", "int", "col2", ")", "{", "double", "temp", "=", "0", ";", "int", "rows", "=", "matrix", ".", "length", ";", "double", "[", "]", "r", "="...
Swap components in the two columns. @param matrix the matrix to modify @param col1 the first row @param col2 the second row
[ "Swap", "components", "in", "the", "two", "columns", "." ]
train
https://github.com/ujmp/universal-java-matrix-package/blob/b7e1d293adeadaf35d208ffe8884028d6c06b63b/ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java#L184-L194
sarl/sarl
main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/properties/RuntimeEnvironmentPropertyPage.java
RuntimeEnvironmentPropertyPage.saveProjectSpecificOptions
@SuppressWarnings("static-method") protected boolean saveProjectSpecificOptions(IProject project, boolean useSpecificOptions) { if (project != null) { try { project.setPersistentProperty( qualify(PROPERTY_NAME_HAS_PROJECT_SPECIFIC), Boolean.toString(useSpecificOptions)); return true; } catch (CoreException e) { SARLEclipsePlugin.getDefault().log(e); } } return false; }
java
@SuppressWarnings("static-method") protected boolean saveProjectSpecificOptions(IProject project, boolean useSpecificOptions) { if (project != null) { try { project.setPersistentProperty( qualify(PROPERTY_NAME_HAS_PROJECT_SPECIFIC), Boolean.toString(useSpecificOptions)); return true; } catch (CoreException e) { SARLEclipsePlugin.getDefault().log(e); } } return false; }
[ "@", "SuppressWarnings", "(", "\"static-method\"", ")", "protected", "boolean", "saveProjectSpecificOptions", "(", "IProject", "project", ",", "boolean", "useSpecificOptions", ")", "{", "if", "(", "project", "!=", "null", ")", "{", "try", "{", "project", ".", "s...
Save the flag that indicates if the specific project options must be used. @param project the project. @param useSpecificOptions indicates if the specific options must be used. @return <code>true</code> if the property was saved successfully.
[ "Save", "the", "flag", "that", "indicates", "if", "the", "specific", "project", "options", "must", "be", "used", "." ]
train
https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.eclipse/src/io/sarl/eclipse/properties/RuntimeEnvironmentPropertyPage.java#L149-L162
vigna/Sux4J
src/it/unimi/dsi/sux4j/mph/HypergraphSorter.java
HypergraphSorter.bitVectorToEdge
public static void bitVectorToEdge(final BitVector bv, final long seed, final int numVertices, final int partSize, final int e[]) { if (numVertices == 0) { e[0] = e[1] = e[2] = -1; return; } final long[] hash = new long[3]; Hashes.spooky4(bv, seed, hash); e[0] = (int)((hash[0] & 0x7FFFFFFFFFFFFFFFL) % partSize); e[1] = (int)(partSize + (hash[1] & 0x7FFFFFFFFFFFFFFFL) % partSize); e[2] = (int)((partSize << 1) + (hash[2] & 0x7FFFFFFFFFFFFFFFL) % partSize); }
java
public static void bitVectorToEdge(final BitVector bv, final long seed, final int numVertices, final int partSize, final int e[]) { if (numVertices == 0) { e[0] = e[1] = e[2] = -1; return; } final long[] hash = new long[3]; Hashes.spooky4(bv, seed, hash); e[0] = (int)((hash[0] & 0x7FFFFFFFFFFFFFFFL) % partSize); e[1] = (int)(partSize + (hash[1] & 0x7FFFFFFFFFFFFFFFL) % partSize); e[2] = (int)((partSize << 1) + (hash[2] & 0x7FFFFFFFFFFFFFFFL) % partSize); }
[ "public", "static", "void", "bitVectorToEdge", "(", "final", "BitVector", "bv", ",", "final", "long", "seed", ",", "final", "int", "numVertices", ",", "final", "int", "partSize", ",", "final", "int", "e", "[", "]", ")", "{", "if", "(", "numVertices", "==...
Turns a bit vector into a 3-hyperedge. <p>The returned edge satisfies the property that the <var>i</var>-th vertex is in the interval [<var>i</var>&middot;{@link #partSize}..<var>i</var>+1&middot;{@link #partSize}). However, if there are no edges the vector <code>e</code> will be filled with -1. @param bv a bit vector. @param seed the seed for the hash function. @param numVertices the number of vertices in the underlying hypergraph. @param partSize <code>numVertices</code>/3 (to avoid a division). @param e an array to store the resulting edge.
[ "Turns", "a", "bit", "vector", "into", "a", "3", "-", "hyperedge", "." ]
train
https://github.com/vigna/Sux4J/blob/d57de8fa897c7d273e0e6dae7a3274174f175a5f/src/it/unimi/dsi/sux4j/mph/HypergraphSorter.java#L199-L209
moparisthebest/beehive
beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextServicesSupport.java
ControlBeanContextServicesSupport.revokeService
public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { // todo: for multithreaded usage this block needs to be synchronized if (!_serviceProviders.containsKey(serviceClass)) { return; } // propagate to any children implementing BeanContextServices Iterator i = iterator(); while (i.hasNext()) { Object o = i.next(); if (o instanceof BeanContextServices) { ((BeanContextServices) o).revokeService(serviceClass, serviceProvider, revokeCurrentServicesNow); } } BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent((BeanContextServices)getPeer(), serviceClass, revokeCurrentServicesNow); fireServiceRevokedEvent(bcsre); // fire revoked event to requestor listeners, if the service is delegated the owner of the // service should fire these events. ServiceProvider sp = _serviceProviders.get(serviceClass); if (!sp.isDelegated()) { sp.revoke(bcsre); } if (revokeCurrentServicesNow || !sp.hasRequestors()) { _serviceProviders.remove(serviceClass); } // end synchronized }
java
public void revokeService(Class serviceClass, BeanContextServiceProvider serviceProvider, boolean revokeCurrentServicesNow) { // todo: for multithreaded usage this block needs to be synchronized if (!_serviceProviders.containsKey(serviceClass)) { return; } // propagate to any children implementing BeanContextServices Iterator i = iterator(); while (i.hasNext()) { Object o = i.next(); if (o instanceof BeanContextServices) { ((BeanContextServices) o).revokeService(serviceClass, serviceProvider, revokeCurrentServicesNow); } } BeanContextServiceRevokedEvent bcsre = new BeanContextServiceRevokedEvent((BeanContextServices)getPeer(), serviceClass, revokeCurrentServicesNow); fireServiceRevokedEvent(bcsre); // fire revoked event to requestor listeners, if the service is delegated the owner of the // service should fire these events. ServiceProvider sp = _serviceProviders.get(serviceClass); if (!sp.isDelegated()) { sp.revoke(bcsre); } if (revokeCurrentServicesNow || !sp.hasRequestors()) { _serviceProviders.remove(serviceClass); } // end synchronized }
[ "public", "void", "revokeService", "(", "Class", "serviceClass", ",", "BeanContextServiceProvider", "serviceProvider", ",", "boolean", "revokeCurrentServicesNow", ")", "{", "// todo: for multithreaded usage this block needs to be synchronized", "if", "(", "!", "_serviceProviders"...
BeanContextServiceProviders wishing to remove a currently registered service from this context may do so via invocation of this method. Upon revocation of the service, the <code>BeanContextServices</code> fires a <code>BeanContextServiceRevokedEvent</code> to its list of currently registered <code>BeanContextServiceRevokedListeners</code> and <code>BeanContextServicesListeners</code>. @param serviceClass the service to revoke from this BeanContextServices @param serviceProvider the BeanContextServiceProvider associated with this particular service that is being revoked @param revokeCurrentServicesNow a value of <code>true</code> indicates an exceptional circumstance where the <code>BeanContextServiceProvider</code> or <code>BeanContextServices</code> wishes to immediately terminate service to all currently outstanding references to the specified service.
[ "BeanContextServiceProviders", "wishing", "to", "remove", "a", "currently", "registered", "service", "from", "this", "context", "may", "do", "so", "via", "invocation", "of", "this", "method", ".", "Upon", "revocation", "of", "the", "service", "the", "<code", ">"...
train
https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/webcontext/ControlBeanContextServicesSupport.java#L118-L148
lessthanoptimal/BoofCV
main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EssentialNister5.java
EssentialNister5.computeSpan
private void computeSpan( List<AssociatedPair> points ) { Q.reshape(points.size(), 9); int index = 0; for( int i = 0; i < points.size(); i++ ) { AssociatedPair p = points.get(i); Point2D_F64 a = p.p2; Point2D_F64 b = p.p1; // The points are assumed to be in homogeneous coordinates. This means z = 1 Q.data[index++] = a.x*b.x; Q.data[index++] = a.x*b.y; Q.data[index++] = a.x; Q.data[index++] = a.y*b.x; Q.data[index++] = a.y*b.y; Q.data[index++] = a.y; Q.data[index++] = b.x; Q.data[index++] = b.y; Q.data[index++] = 1; } if( !solverNull.process(Q,4,nullspace) ) throw new RuntimeException("Nullspace solver should never fail, probably bad input"); // extract the span of solutions for E from the null space for( int i = 0; i < 9; i++ ) { X[i] = nullspace.unsafe_get(i,0); Y[i] = nullspace.unsafe_get(i,1); Z[i] = nullspace.unsafe_get(i,2); W[i] = nullspace.unsafe_get(i,3); } }
java
private void computeSpan( List<AssociatedPair> points ) { Q.reshape(points.size(), 9); int index = 0; for( int i = 0; i < points.size(); i++ ) { AssociatedPair p = points.get(i); Point2D_F64 a = p.p2; Point2D_F64 b = p.p1; // The points are assumed to be in homogeneous coordinates. This means z = 1 Q.data[index++] = a.x*b.x; Q.data[index++] = a.x*b.y; Q.data[index++] = a.x; Q.data[index++] = a.y*b.x; Q.data[index++] = a.y*b.y; Q.data[index++] = a.y; Q.data[index++] = b.x; Q.data[index++] = b.y; Q.data[index++] = 1; } if( !solverNull.process(Q,4,nullspace) ) throw new RuntimeException("Nullspace solver should never fail, probably bad input"); // extract the span of solutions for E from the null space for( int i = 0; i < 9; i++ ) { X[i] = nullspace.unsafe_get(i,0); Y[i] = nullspace.unsafe_get(i,1); Z[i] = nullspace.unsafe_get(i,2); W[i] = nullspace.unsafe_get(i,3); } }
[ "private", "void", "computeSpan", "(", "List", "<", "AssociatedPair", ">", "points", ")", "{", "Q", ".", "reshape", "(", "points", ".", "size", "(", ")", ",", "9", ")", ";", "int", "index", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", ...
From the epipolar constraint p2^T*E*p1 = 0 construct a linear system and find its null space.
[ "From", "the", "epipolar", "constraint", "p2^T", "*", "E", "*", "p1", "=", "0", "construct", "a", "linear", "system", "and", "find", "its", "null", "space", "." ]
train
https://github.com/lessthanoptimal/BoofCV/blob/f01c0243da0ec086285ee722183804d5923bc3ac/main/boofcv-geo/src/main/java/boofcv/alg/geo/f/EssentialNister5.java#L148-L181
lightblueseas/file-worker
src/main/java/de/alpharogroup/file/checksum/ChecksumExtensions.java
ChecksumExtensions.getChecksum
public static long getChecksum(final File file, final boolean crc) throws FileNotFoundException, IOException { try (CheckedInputStream cis = crc ? new CheckedInputStream(new FileInputStream(file), new CRC32()) : new CheckedInputStream(new FileInputStream(file), new Adler32());) { final int length = (int)file.length(); final byte[] buffer = new byte[length]; long checksum = 0; while (cis.read(buffer) >= 0) { checksum = cis.getChecksum().getValue(); } checksum = cis.getChecksum().getValue(); return checksum; } }
java
public static long getChecksum(final File file, final boolean crc) throws FileNotFoundException, IOException { try (CheckedInputStream cis = crc ? new CheckedInputStream(new FileInputStream(file), new CRC32()) : new CheckedInputStream(new FileInputStream(file), new Adler32());) { final int length = (int)file.length(); final byte[] buffer = new byte[length]; long checksum = 0; while (cis.read(buffer) >= 0) { checksum = cis.getChecksum().getValue(); } checksum = cis.getChecksum().getValue(); return checksum; } }
[ "public", "static", "long", "getChecksum", "(", "final", "File", "file", ",", "final", "boolean", "crc", ")", "throws", "FileNotFoundException", ",", "IOException", "{", "try", "(", "CheckedInputStream", "cis", "=", "crc", "?", "new", "CheckedInputStream", "(", ...
Gets the checksum from the given file. If the flag crc is true than the CheckedInputStream is constructed with an instance of <code>java.util.zip.CRC32</code> otherwise with an instance of <code>java.util.zip.Adler32</code>. @param file The file The file from what to get the checksum. @param crc The crc If the flag crc is true than the CheckedInputStream is constructed with an instance of {@link java.util.zip.CRC32} object otherwise it is constructed with an instance of @return The checksum from the given file as long. @throws FileNotFoundException Is thrown if the file is not found. @throws IOException Signals that an I/O exception has occurred. {@link java.util.zip.CRC32} object otherwise it is constructed with an instance of {@link java.util.zip.Adler32} object. {@link java.util.zip.Adler32} object.
[ "Gets", "the", "checksum", "from", "the", "given", "file", ".", "If", "the", "flag", "crc", "is", "true", "than", "the", "CheckedInputStream", "is", "constructed", "with", "an", "instance", "of", "<code", ">", "java", ".", "util", ".", "zip", ".", "CRC32...
train
https://github.com/lightblueseas/file-worker/blob/2c81de10fb5d68de64c1abc3ed64ca681ce76da8/src/main/java/de/alpharogroup/file/checksum/ChecksumExtensions.java#L221-L238
hawkular/hawkular-apm
client/opentracing/src/main/java/org/hawkular/apm/client/opentracing/TagUtil.java
TagUtil.getUriPath
public static String getUriPath(Map<String, Object> tags) { for (Map.Entry<String,Object> entry : tags.entrySet()) { if (isUriKey(entry.getKey())) { return getUriPath(entry.getValue().toString()); } } return null; }
java
public static String getUriPath(Map<String, Object> tags) { for (Map.Entry<String,Object> entry : tags.entrySet()) { if (isUriKey(entry.getKey())) { return getUriPath(entry.getValue().toString()); } } return null; }
[ "public", "static", "String", "getUriPath", "(", "Map", "<", "String", ",", "Object", ">", "tags", ")", "{", "for", "(", "Map", ".", "Entry", "<", "String", ",", "Object", ">", "entry", ":", "tags", ".", "entrySet", "(", ")", ")", "{", "if", "(", ...
This method returns the URI value from a set of supplied tags, by first identifying which tag relates to a URI and then returning its path value. @param tags The tags @return The URI path, or null if not found
[ "This", "method", "returns", "the", "URI", "value", "from", "a", "set", "of", "supplied", "tags", "by", "first", "identifying", "which", "tag", "relates", "to", "a", "URI", "and", "then", "returning", "its", "path", "value", "." ]
train
https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/client/opentracing/src/main/java/org/hawkular/apm/client/opentracing/TagUtil.java#L81-L88
OpenLiberty/open-liberty
dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java
RecoveryDirectorImpl.addRecoveryRecord
private void addRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) { if (tc.isEntryEnabled()) Tr.entry(tc, "addRecoveryRecord", new Object[] { recoveryAgent, failureScope, this }); synchronized (_outstandingRecoveryRecords) { HashSet<RecoveryAgent> recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope); if (recoveryAgentSet == null) { recoveryAgentSet = new HashSet<RecoveryAgent>(); _outstandingRecoveryRecords.put(failureScope, recoveryAgentSet); } recoveryAgentSet.add(recoveryAgent); } if (tc.isEntryEnabled()) Tr.exit(tc, "addRecoveryRecord"); }
java
private void addRecoveryRecord(RecoveryAgent recoveryAgent, FailureScope failureScope) { if (tc.isEntryEnabled()) Tr.entry(tc, "addRecoveryRecord", new Object[] { recoveryAgent, failureScope, this }); synchronized (_outstandingRecoveryRecords) { HashSet<RecoveryAgent> recoveryAgentSet = _outstandingRecoveryRecords.get(failureScope); if (recoveryAgentSet == null) { recoveryAgentSet = new HashSet<RecoveryAgent>(); _outstandingRecoveryRecords.put(failureScope, recoveryAgentSet); } recoveryAgentSet.add(recoveryAgent); } if (tc.isEntryEnabled()) Tr.exit(tc, "addRecoveryRecord"); }
[ "private", "void", "addRecoveryRecord", "(", "RecoveryAgent", "recoveryAgent", ",", "FailureScope", "failureScope", ")", "{", "if", "(", "tc", ".", "isEntryEnabled", "(", ")", ")", "Tr", ".", "entry", "(", "tc", ",", "\"addRecoveryRecord\"", ",", "new", "Objec...
<p> Internal method to record an outstanding 'initialRecoveryComplete' call that must be issued by the client service represented by the supplied RecoveryAgent for the given failure scope. </p> <p> Just prior to requesting a RecoveryAgent to "initiateRecovery" of a FailureScope, this method is driven to record the request. When the client service completes the initial portion of the recovery process and invokes RecoveryDirector.initialRecoveryComplete, the removeRecoveryRecord method is called to remove this record. </p> <p> This allows the RLS to track the "initial" portion of an ongoing recovery process. </p> <p> [ SERIAL PHASE ] [ INITIAL PHASE ] [ RETRY PHASE ] </p> @param recoveryAgent The RecoveryAgent that is about to be directed to process recovery of a FailureScope. @param failureScope The FailureScope.
[ "<p", ">", "Internal", "method", "to", "record", "an", "outstanding", "initialRecoveryComplete", "call", "that", "must", "be", "issued", "by", "the", "client", "service", "represented", "by", "the", "supplied", "RecoveryAgent", "for", "the", "given", "failure", ...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.recoverylog/src/com/ibm/ws/recoverylog/spi/RecoveryDirectorImpl.java#L1172-L1189
realtime-framework/RealtimeStorage-Android
library/src/main/java/co/realtime/storage/TableRef.java
TableRef.notNull
public TableRef notNull(String attributeName){ filters.add(new Filter(StorageFilter.NOTNULL, attributeName, null, null)); return this; }
java
public TableRef notNull(String attributeName){ filters.add(new Filter(StorageFilter.NOTNULL, attributeName, null, null)); return this; }
[ "public", "TableRef", "notNull", "(", "String", "attributeName", ")", "{", "filters", ".", "add", "(", "new", "Filter", "(", "StorageFilter", ".", "NOTNULL", ",", "attributeName", ",", "null", ",", "null", ")", ")", ";", "return", "this", ";", "}" ]
Applies a filter to the table reference. When fetched, it will return the non null values. <pre> StorageRef storage = new StorageRef("your_app_key", "your_token"); TableRef tableRef = storage.table("your_table"); // Retrieve all items where their "itemProperty" value is not null tableRef.notNull("itemProperty").getItems(new OnItemSnapshot() { &#064;Override public void run(ItemSnapshot itemSnapshot) { if (itemSnapshot != null) { Log.d("TableRef", "Item retrieved: " + itemSnapshot.val()); } } }, new OnError() { &#064;Override public void run(Integer code, String errorMessage) { Log.e("TableRef", "Error retrieving items: " + errorMessage); } }); </pre> @param attributeName The name of the property to filter. @return Current table reference
[ "Applies", "a", "filter", "to", "the", "table", "reference", ".", "When", "fetched", "it", "will", "return", "the", "non", "null", "values", "." ]
train
https://github.com/realtime-framework/RealtimeStorage-Android/blob/05816a6b7a6dcc83f9e7400ac3048494dadca302/library/src/main/java/co/realtime/storage/TableRef.java#L796-L799
cqframework/clinical_quality_language
Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java
ElmBaseVisitor.visitFunctionRef
public T visitFunctionRef(FunctionRef elm, C context) { for (Expression element : elm.getOperand()) { visitElement(element, context); } return null; }
java
public T visitFunctionRef(FunctionRef elm, C context) { for (Expression element : elm.getOperand()) { visitElement(element, context); } return null; }
[ "public", "T", "visitFunctionRef", "(", "FunctionRef", "elm", ",", "C", "context", ")", "{", "for", "(", "Expression", "element", ":", "elm", ".", "getOperand", "(", ")", ")", "{", "visitElement", "(", "element", ",", "context", ")", ";", "}", "return", ...
Visit a FunctionRef. This method will be called for every node in the tree that is a FunctionRef. @param elm the ELM tree @param context the context passed to the visitor @return the visitor result
[ "Visit", "a", "FunctionRef", ".", "This", "method", "will", "be", "called", "for", "every", "node", "in", "the", "tree", "that", "is", "a", "FunctionRef", "." ]
train
https://github.com/cqframework/clinical_quality_language/blob/67459d1ef453e49db8d7c5c86e87278377ed0a0b/Src/java/elm/src/main/java/org/cqframework/cql/elm/visiting/ElmBaseVisitor.java#L357-L362
mlhartme/sushi
src/main/java/net/oneandone/sushi/fs/Node.java
Node.writeXml
public T writeXml(org.w3c.dom.Node node, boolean format) throws IOException { getWorld().getXml().getSerializer().serialize(node, this, format); return (T) this; }
java
public T writeXml(org.w3c.dom.Node node, boolean format) throws IOException { getWorld().getXml().getSerializer().serialize(node, this, format); return (T) this; }
[ "public", "T", "writeXml", "(", "org", ".", "w3c", ".", "dom", ".", "Node", "node", ",", "boolean", "format", ")", "throws", "IOException", "{", "getWorld", "(", ")", ".", "getXml", "(", ")", ".", "getSerializer", "(", ")", ".", "serialize", "(", "no...
Write the specified node into this file. Adds indentation/newlines when format is true. Otherwise, writes the document "as is" (but always prefixes the document with an xml declaration and encloses attributes in double quotes). @return this node
[ "Write", "the", "specified", "node", "into", "this", "file", ".", "Adds", "indentation", "/", "newlines", "when", "format", "is", "true", ".", "Otherwise", "writes", "the", "document", "as", "is", "(", "but", "always", "prefixes", "the", "document", "with", ...
train
https://github.com/mlhartme/sushi/blob/4af33414b04bd58584d4febe5cc63ef6c7346a75/src/main/java/net/oneandone/sushi/fs/Node.java#L717-L720
elastic/elasticsearch-hadoop
mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/UpdateBulkFactory.java
UpdateBulkFactory.writeLegacyFormatting
private void writeLegacyFormatting(List<Object> list, Object paramExtractor) { if (paramExtractor != null) { list.add("{\"params\":"); list.add(paramExtractor); list.add(","); } else { list.add("{"); } if (HAS_SCRIPT) { /* * { * "params": ..., * "lang": "...", * "script": "...", * "upsert": {...} * } */ if (HAS_LANG) { list.add(SCRIPT_LANG_1X); } list.add(SCRIPT_1X); if (UPSERT) { list.add(",\"upsert\":"); } } else { /* * { * "doc_as_upsert": true, * "doc": {...} * } */ if (UPSERT) { list.add("\"doc_as_upsert\":true,"); } list.add("\"doc\":"); } }
java
private void writeLegacyFormatting(List<Object> list, Object paramExtractor) { if (paramExtractor != null) { list.add("{\"params\":"); list.add(paramExtractor); list.add(","); } else { list.add("{"); } if (HAS_SCRIPT) { /* * { * "params": ..., * "lang": "...", * "script": "...", * "upsert": {...} * } */ if (HAS_LANG) { list.add(SCRIPT_LANG_1X); } list.add(SCRIPT_1X); if (UPSERT) { list.add(",\"upsert\":"); } } else { /* * { * "doc_as_upsert": true, * "doc": {...} * } */ if (UPSERT) { list.add("\"doc_as_upsert\":true,"); } list.add("\"doc\":"); } }
[ "private", "void", "writeLegacyFormatting", "(", "List", "<", "Object", ">", "list", ",", "Object", "paramExtractor", ")", "{", "if", "(", "paramExtractor", "!=", "null", ")", "{", "list", ".", "add", "(", "\"{\\\"params\\\":\"", ")", ";", "list", ".", "ad...
Script format meant for versions 1.x to 2.x. Required format for 1.x and below. @param list Consumer of snippets @param paramExtractor Extracts parameters from documents or constants
[ "Script", "format", "meant", "for", "versions", "1", ".", "x", "to", "2", ".", "x", ".", "Required", "format", "for", "1", ".", "x", "and", "below", "." ]
train
https://github.com/elastic/elasticsearch-hadoop/blob/f3acaba268ff96efae8eb946088c748c777c22cc/mr/src/main/java/org/elasticsearch/hadoop/serialization/bulk/UpdateBulkFactory.java#L129-L168
gfk-ba/senbot
SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/NavigationService.java
NavigationService.clickElementWithAttributeValue
public void clickElementWithAttributeValue(String attributeName, String attributeValue) { By xpath = By.xpath("//*[@" + attributeName + "='" + attributeValue + "']"); WebElement element = seleniumElementService.findExpectedElement(xpath); assertTrue("The element you are trying to click (" + xpath.toString() + ") is not displayed", element.isDisplayed()); element.click(); }
java
public void clickElementWithAttributeValue(String attributeName, String attributeValue) { By xpath = By.xpath("//*[@" + attributeName + "='" + attributeValue + "']"); WebElement element = seleniumElementService.findExpectedElement(xpath); assertTrue("The element you are trying to click (" + xpath.toString() + ") is not displayed", element.isDisplayed()); element.click(); }
[ "public", "void", "clickElementWithAttributeValue", "(", "String", "attributeName", ",", "String", "attributeValue", ")", "{", "By", "xpath", "=", "By", ".", "xpath", "(", "\"//*[@\"", "+", "attributeName", "+", "\"='\"", "+", "attributeValue", "+", "\"']\"", ")...
Find a Element that has a attribute with a certain value and click it @param attributeName @param attributeValue
[ "Find", "a", "Element", "that", "has", "a", "attribute", "with", "a", "certain", "value", "and", "click", "it" ]
train
https://github.com/gfk-ba/senbot/blob/e9a152aa67be48b1bb13a4691655caf6d873b553/SenBotRunner/src/main/java/com/gfk/senbot/framework/services/selenium/NavigationService.java#L90-L95
versionone/VersionOne.SDK.Java.ObjectModel
src/main/java/com/versionone/om/filters/EntityFilter.java
EntityFilter.buildFilter
public IFilterTerm buildFilter(IAssetType assetType, V1Instance instance) { FilterBuilder builder = new FilterBuilder(assetType, instance); internalModifyFilter(builder); internalModifyState(builder); return builder.root.hasTerm() ? builder.root : null; }
java
public IFilterTerm buildFilter(IAssetType assetType, V1Instance instance) { FilterBuilder builder = new FilterBuilder(assetType, instance); internalModifyFilter(builder); internalModifyState(builder); return builder.root.hasTerm() ? builder.root : null; }
[ "public", "IFilterTerm", "buildFilter", "(", "IAssetType", "assetType", ",", "V1Instance", "instance", ")", "{", "FilterBuilder", "builder", "=", "new", "FilterBuilder", "(", "assetType", ",", "instance", ")", ";", "internalModifyFilter", "(", "builder", ")", ";",...
Create representation one filter term on a query. @param assetType information about Asset type. @param instance The type this filter belongs to. @return created {@code IFilterTerm}.
[ "Create", "representation", "one", "filter", "term", "on", "a", "query", "." ]
train
https://github.com/versionone/VersionOne.SDK.Java.ObjectModel/blob/59d35b67c849299631bca45ee94143237eb2ae1a/src/main/java/com/versionone/om/filters/EntityFilter.java#L167-L173
googleapis/google-api-java-client
google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java
GoogleAccountCredential.usingOAuth2
public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); }
java
public static GoogleAccountCredential usingOAuth2(Context context, Collection<String> scopes) { Preconditions.checkArgument(scopes != null && scopes.iterator().hasNext()); String scopesStr = "oauth2: " + Joiner.on(' ').join(scopes); return new GoogleAccountCredential(context, scopesStr); }
[ "public", "static", "GoogleAccountCredential", "usingOAuth2", "(", "Context", "context", ",", "Collection", "<", "String", ">", "scopes", ")", "{", "Preconditions", ".", "checkArgument", "(", "scopes", "!=", "null", "&&", "scopes", ".", "iterator", "(", ")", "...
Constructs a new instance using OAuth 2.0 scopes. @param context context @param scopes non empty OAuth 2.0 scope list @return new instance @since 1.15
[ "Constructs", "a", "new", "instance", "using", "OAuth", "2", ".", "0", "scopes", "." ]
train
https://github.com/googleapis/google-api-java-client/blob/88decfd14fc40cae6eb6729a45c7d56a1132e450/google-api-client-android/src/main/java/com/google/api/client/googleapis/extensions/android/gms/auth/GoogleAccountCredential.java#L112-L116
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/extensions/ExtensionsTable.java
ExtensionsTable.elementAvailable
public boolean elementAvailable(String ns, String elemName) throws javax.xml.transform.TransformerException { boolean isAvailable = false; if (null != ns) { ExtensionHandler extNS = (ExtensionHandler) m_extensionFunctionNamespaces.get(ns); if (extNS != null) // defensive isAvailable = extNS.isElementAvailable(elemName); } return isAvailable; }
java
public boolean elementAvailable(String ns, String elemName) throws javax.xml.transform.TransformerException { boolean isAvailable = false; if (null != ns) { ExtensionHandler extNS = (ExtensionHandler) m_extensionFunctionNamespaces.get(ns); if (extNS != null) // defensive isAvailable = extNS.isElementAvailable(elemName); } return isAvailable; }
[ "public", "boolean", "elementAvailable", "(", "String", "ns", ",", "String", "elemName", ")", "throws", "javax", ".", "xml", ".", "transform", ".", "TransformerException", "{", "boolean", "isAvailable", "=", "false", ";", "if", "(", "null", "!=", "ns", ")", ...
Execute the element-available() function. @param ns the URI of namespace in which the function is needed @param elemName name of element being tested @return whether the given element is available or not. @throws javax.xml.transform.TransformerException
[ "Execute", "the", "element", "-", "available", "()", "function", ".", "@param", "ns", "the", "URI", "of", "namespace", "in", "which", "the", "function", "is", "needed", "@param", "elemName", "name", "of", "element", "being", "tested" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/extensions/ExtensionsTable.java#L132-L144
ngageoint/geopackage-core-java
src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java
TileBoundingBoxUtils.getBoundingBox
public static BoundingBox getBoundingBox(int x, int y, int zoom) { int tilesPerSide = tilesPerSide(zoom); double tileWidthDegrees = tileWidthDegrees(tilesPerSide); double tileHeightDegrees = tileHeightDegrees(tilesPerSide); double minLon = -180.0 + (x * tileWidthDegrees); double maxLon = minLon + tileWidthDegrees; double maxLat = 90.0 - (y * tileHeightDegrees); double minLat = maxLat - tileHeightDegrees; BoundingBox box = new BoundingBox(minLon, minLat, maxLon, maxLat); return box; }
java
public static BoundingBox getBoundingBox(int x, int y, int zoom) { int tilesPerSide = tilesPerSide(zoom); double tileWidthDegrees = tileWidthDegrees(tilesPerSide); double tileHeightDegrees = tileHeightDegrees(tilesPerSide); double minLon = -180.0 + (x * tileWidthDegrees); double maxLon = minLon + tileWidthDegrees; double maxLat = 90.0 - (y * tileHeightDegrees); double minLat = maxLat - tileHeightDegrees; BoundingBox box = new BoundingBox(minLon, minLat, maxLon, maxLat); return box; }
[ "public", "static", "BoundingBox", "getBoundingBox", "(", "int", "x", ",", "int", "y", ",", "int", "zoom", ")", "{", "int", "tilesPerSide", "=", "tilesPerSide", "(", "zoom", ")", ";", "double", "tileWidthDegrees", "=", "tileWidthDegrees", "(", "tilesPerSide", ...
Get the tile bounding box from the Google Maps API tile coordinates and zoom level @param x x coordinate @param y y coordinate @param zoom zoom level @return bounding box
[ "Get", "the", "tile", "bounding", "box", "from", "the", "Google", "Maps", "API", "tile", "coordinates", "and", "zoom", "level" ]
train
https://github.com/ngageoint/geopackage-core-java/blob/6431c3b041a45b7f3802904ea4156b4082a72daa/src/main/java/mil/nga/geopackage/tiles/TileBoundingBoxUtils.java#L318-L333
Bedework/bw-util
bw-util-directory/src/main/java/org/bedework/util/directory/ldap/LdapDirectory.java
LdapDirectory.checkProp
public String checkProp(final Properties pr, final String name, final String defaultVal) { String val = pr.getProperty(name); if (val == null) { pr.put(name, defaultVal); val = defaultVal; } return val; }
java
public String checkProp(final Properties pr, final String name, final String defaultVal) { String val = pr.getProperty(name); if (val == null) { pr.put(name, defaultVal); val = defaultVal; } return val; }
[ "public", "String", "checkProp", "(", "final", "Properties", "pr", ",", "final", "String", "name", ",", "final", "String", "defaultVal", ")", "{", "String", "val", "=", "pr", ".", "getProperty", "(", "name", ")", ";", "if", "(", "val", "==", "null", ")...
If the named property is present and has a value use that. Otherwise, set the value to the given default and use that. @param pr @param name @param defaultVal @return String
[ "If", "the", "named", "property", "is", "present", "and", "has", "a", "value", "use", "that", ".", "Otherwise", "set", "the", "value", "to", "the", "given", "default", "and", "use", "that", "." ]
train
https://github.com/Bedework/bw-util/blob/f51de4af3d7eb88fe63a0e22be8898a16c6cc3ad/bw-util-directory/src/main/java/org/bedework/util/directory/ldap/LdapDirectory.java#L305-L314
Javacord/Javacord
javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookUpdater.java
WebhookUpdater.setAvatar
public WebhookUpdater setAvatar(InputStream avatar, String fileType) { delegate.setAvatar(avatar, fileType); return this; }
java
public WebhookUpdater setAvatar(InputStream avatar, String fileType) { delegate.setAvatar(avatar, fileType); return this; }
[ "public", "WebhookUpdater", "setAvatar", "(", "InputStream", "avatar", ",", "String", "fileType", ")", "{", "delegate", ".", "setAvatar", "(", "avatar", ",", "fileType", ")", ";", "return", "this", ";", "}" ]
Queues the avatar to be updated. @param avatar The avatar to set. @param fileType The type of the avatar, e.g. "png" or "jpg". @return The current instance in order to chain call methods.
[ "Queues", "the", "avatar", "to", "be", "updated", "." ]
train
https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-api/src/main/java/org/javacord/api/entity/webhook/WebhookUpdater.java#L166-L169
jboss/jboss-jsf-api_spec
src/main/java/javax/faces/component/UIData.java
UIData.setValueExpression
public void setValueExpression(String name, ValueExpression binding) { if ("value".equals(name)) { this.model = null; } else if ("var".equals(name) || "rowIndex".equals(name)) { throw new IllegalArgumentException(); } super.setValueExpression(name, binding); }
java
public void setValueExpression(String name, ValueExpression binding) { if ("value".equals(name)) { this.model = null; } else if ("var".equals(name) || "rowIndex".equals(name)) { throw new IllegalArgumentException(); } super.setValueExpression(name, binding); }
[ "public", "void", "setValueExpression", "(", "String", "name", ",", "ValueExpression", "binding", ")", "{", "if", "(", "\"value\"", ".", "equals", "(", "name", ")", ")", "{", "this", ".", "model", "=", "null", ";", "}", "else", "if", "(", "\"var\"", "....
<p>Set the {@link ValueExpression} used to calculate the value for the specified attribute or property name, if any. In addition, if a {@link ValueExpression} is set for the <code>value</code> property, remove any synthesized {@link DataModel} for the data previously bound to this component.</p> @param name Name of the attribute or property for which to set a {@link ValueExpression} @param binding The {@link ValueExpression} to set, or <code>null</code> to remove any currently set {@link ValueExpression} @throws IllegalArgumentException if <code>name</code> is one of <code>id</code>, <code>parent</code>, <code>var</code>, or <code>rowIndex</code> @throws NullPointerException if <code>name</code> is <code>null</code> @since 1.2
[ "<p", ">", "Set", "the", "{", "@link", "ValueExpression", "}", "used", "to", "calculate", "the", "value", "for", "the", "specified", "attribute", "or", "property", "name", "if", "any", ".", "In", "addition", "if", "a", "{", "@link", "ValueExpression", "}",...
train
https://github.com/jboss/jboss-jsf-api_spec/blob/cb33d215acbab847f2db5cdf2c6fe4d99c0a01c3/src/main/java/javax/faces/component/UIData.java#L799-L808
shinesolutions/swagger-aem
java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java
SlingApi.postTreeActivationAsync
public com.squareup.okhttp.Call postTreeActivationAsync(Boolean ignoredeactivated, Boolean onlymodified, String path, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postTreeActivationValidateBeforeCall(ignoredeactivated, onlymodified, path, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
java
public com.squareup.okhttp.Call postTreeActivationAsync(Boolean ignoredeactivated, Boolean onlymodified, String path, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = postTreeActivationValidateBeforeCall(ignoredeactivated, onlymodified, path, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; }
[ "public", "com", ".", "squareup", ".", "okhttp", ".", "Call", "postTreeActivationAsync", "(", "Boolean", "ignoredeactivated", ",", "Boolean", "onlymodified", ",", "String", "path", ",", "final", "ApiCallback", "<", "Void", ">", "callback", ")", "throws", "ApiExc...
(asynchronously) @param ignoredeactivated (required) @param onlymodified (required) @param path (required) @param callback The callback to be executed when the API call finishes @return The request call @throws ApiException If fail to process the API call, e.g. serializing the request body object
[ "(", "asynchronously", ")" ]
train
https://github.com/shinesolutions/swagger-aem/blob/ae7da4df93e817dc2bad843779b2069d9c4e7c6b/java/generated/src/main/java/com/shinesolutions/swaggeraem4j/api/SlingApi.java#L4343-L4367
google/j2objc
translator/src/main/java/com/google/devtools/j2objc/util/PackageInfoLookup.java
PackageInfoLookup.hasAnnotation
private static boolean hasAnnotation(String pkgInfo, String annotation) { if (!annotation.contains(".")) { ErrorUtil.warning(annotation + " is not a fully qualified name"); } if (pkgInfo.contains("@" + annotation)) { return true; } int idx = annotation.lastIndexOf("."); String annotationPackageName = annotation.substring(0, idx); String annotationSimpleName = annotation.substring(idx + 1); if (pkgInfo.contains("@" + annotationSimpleName)) { String importRegex = "import\\s*" + annotationPackageName + "(\\.\\*|\\." + annotationSimpleName + ")"; Pattern p = Pattern.compile(importRegex); Matcher m = p.matcher(pkgInfo); if (m.find()) { return true; } } return false; }
java
private static boolean hasAnnotation(String pkgInfo, String annotation) { if (!annotation.contains(".")) { ErrorUtil.warning(annotation + " is not a fully qualified name"); } if (pkgInfo.contains("@" + annotation)) { return true; } int idx = annotation.lastIndexOf("."); String annotationPackageName = annotation.substring(0, idx); String annotationSimpleName = annotation.substring(idx + 1); if (pkgInfo.contains("@" + annotationSimpleName)) { String importRegex = "import\\s*" + annotationPackageName + "(\\.\\*|\\." + annotationSimpleName + ")"; Pattern p = Pattern.compile(importRegex); Matcher m = p.matcher(pkgInfo); if (m.find()) { return true; } } return false; }
[ "private", "static", "boolean", "hasAnnotation", "(", "String", "pkgInfo", ",", "String", "annotation", ")", "{", "if", "(", "!", "annotation", ".", "contains", "(", "\".\"", ")", ")", "{", "ErrorUtil", ".", "warning", "(", "annotation", "+", "\" is not a fu...
Return true if pkgInfo has the specified annotation. @param pkgInfo package-info source code @param annotation fully qualified name of the annotation
[ "Return", "true", "if", "pkgInfo", "has", "the", "specified", "annotation", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/translator/src/main/java/com/google/devtools/j2objc/util/PackageInfoLookup.java#L134-L154
KostyaSha/yet-another-docker-plugin
yet-another-docker-its/src/main/java/com/github/kostyasha/it/utils/TempFileHelper.java
TempFileHelper.createTempDirectory
public static File createTempDirectory(String prefix, Path dir) throws IOException { if (prefix == null) { prefix = ""; } final File file = generatePath(prefix, dir).toFile(); if (!file.mkdirs()) { throw new IOException("Can't create dir " + file.getAbsolutePath()); } return file; }
java
public static File createTempDirectory(String prefix, Path dir) throws IOException { if (prefix == null) { prefix = ""; } final File file = generatePath(prefix, dir).toFile(); if (!file.mkdirs()) { throw new IOException("Can't create dir " + file.getAbsolutePath()); } return file; }
[ "public", "static", "File", "createTempDirectory", "(", "String", "prefix", ",", "Path", "dir", ")", "throws", "IOException", "{", "if", "(", "prefix", "==", "null", ")", "{", "prefix", "=", "\"\"", ";", "}", "final", "File", "file", "=", "generatePath", ...
Creates a temporary directory in the given directory, or in in the temporary directory if dir is {@code null}.
[ "Creates", "a", "temporary", "directory", "in", "the", "given", "directory", "or", "in", "in", "the", "temporary", "directory", "if", "dir", "is", "{" ]
train
https://github.com/KostyaSha/yet-another-docker-plugin/blob/40b12e39ff94c3834cff7e028c3dd01c88e87d77/yet-another-docker-its/src/main/java/com/github/kostyasha/it/utils/TempFileHelper.java#L23-L32
jenkinsci/support-core-plugin
src/main/java/com/cloudbees/jenkins/support/SupportAction.java
SupportAction.doDownload
@RequirePOST public void doDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { doGenerateAllBundles(req, rsp); }
java
@RequirePOST public void doDownload(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException { doGenerateAllBundles(req, rsp); }
[ "@", "RequirePOST", "public", "void", "doDownload", "(", "StaplerRequest", "req", ",", "StaplerResponse", "rsp", ")", "throws", "ServletException", ",", "IOException", "{", "doGenerateAllBundles", "(", "req", ",", "rsp", ")", ";", "}" ]
Generates a support bundle. @param req The stapler request @param rsp The stapler response @throws ServletException @throws IOException
[ "Generates", "a", "support", "bundle", "." ]
train
https://github.com/jenkinsci/support-core-plugin/blob/bcbe1dfd5bf48ac89903645cd48ed897c1a04688/src/main/java/com/cloudbees/jenkins/support/SupportAction.java#L165-L168
mapsforge/mapsforge
mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java
AbstractPoiPersistenceManager.getSQLSelectString
protected static String getSQLSelectString(PoiCategoryFilter filter, int count, int version) { if (filter != null) { return PoiCategoryRangeQueryGenerator.getSQLSelectString(filter, count, version); } StringBuilder sb = new StringBuilder(); sb.append(DbConstants.FIND_IN_BOX_CLAUSE_SELECT); if (count > 0) { sb.append(DbConstants.JOIN_DATA_CLAUSE); } sb.append(DbConstants.FIND_IN_BOX_CLAUSE_WHERE); for (int i = 0; i < count; i++) { sb.append(DbConstants.FIND_BY_DATA_CLAUSE); } return sb.append(" LIMIT ?;").toString(); }
java
protected static String getSQLSelectString(PoiCategoryFilter filter, int count, int version) { if (filter != null) { return PoiCategoryRangeQueryGenerator.getSQLSelectString(filter, count, version); } StringBuilder sb = new StringBuilder(); sb.append(DbConstants.FIND_IN_BOX_CLAUSE_SELECT); if (count > 0) { sb.append(DbConstants.JOIN_DATA_CLAUSE); } sb.append(DbConstants.FIND_IN_BOX_CLAUSE_WHERE); for (int i = 0; i < count; i++) { sb.append(DbConstants.FIND_BY_DATA_CLAUSE); } return sb.append(" LIMIT ?;").toString(); }
[ "protected", "static", "String", "getSQLSelectString", "(", "PoiCategoryFilter", "filter", ",", "int", "count", ",", "int", "version", ")", "{", "if", "(", "filter", "!=", "null", ")", "{", "return", "PoiCategoryRangeQueryGenerator", ".", "getSQLSelectString", "("...
Gets the SQL query that looks up POI entries. @param filter The filter object for determining all wanted categories (may be null). @param count Count of patterns to search in points of interest data (may be 0). @param version POI specification version. @return The SQL query.
[ "Gets", "the", "SQL", "query", "that", "looks", "up", "POI", "entries", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-poi/src/main/java/org/mapsforge/poi/storage/AbstractPoiPersistenceManager.java#L97-L111
gallandarakhneorg/afc
advanced/gis/giscorefx/src/main/java/org/arakhne/afc/gis/ui/drawers/AbstractMapPointDrawer.java
AbstractMapPointDrawer.defineSmallRectangle
protected void defineSmallRectangle(ZoomableGraphicsContext gc, T element) { final double ptsSize = element.getPointSize() / 2.; final double x = element.getX() - ptsSize; final double y = element.getY() - ptsSize; final double mx = element.getX() + ptsSize; final double my = element.getY() + ptsSize; gc.moveTo(x, y); gc.lineTo(mx, y); gc.lineTo(mx, my); gc.lineTo(x, my); gc.closePath(); }
java
protected void defineSmallRectangle(ZoomableGraphicsContext gc, T element) { final double ptsSize = element.getPointSize() / 2.; final double x = element.getX() - ptsSize; final double y = element.getY() - ptsSize; final double mx = element.getX() + ptsSize; final double my = element.getY() + ptsSize; gc.moveTo(x, y); gc.lineTo(mx, y); gc.lineTo(mx, my); gc.lineTo(x, my); gc.closePath(); }
[ "protected", "void", "defineSmallRectangle", "(", "ZoomableGraphicsContext", "gc", ",", "T", "element", ")", "{", "final", "double", "ptsSize", "=", "element", ".", "getPointSize", "(", ")", "/", "2.", ";", "final", "double", "x", "=", "element", ".", "getX"...
Define a path that corresponds to the small rectangle around a point. @param gc the graphics context that must be used for drawing. @param element the map element.
[ "Define", "a", "path", "that", "corresponds", "to", "the", "small", "rectangle", "around", "a", "point", "." ]
train
https://github.com/gallandarakhneorg/afc/blob/0c7d2e1ddefd4167ef788416d970a6c1ef6f8bbb/advanced/gis/giscorefx/src/main/java/org/arakhne/afc/gis/ui/drawers/AbstractMapPointDrawer.java#L42-L53