repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
11
218
func_name
stringlengths
4
140
whole_func_string
stringlengths
153
5.32k
language
stringclasses
1 value
func_code_string
stringlengths
72
4k
func_code_tokens
sequencelengths
20
832
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
sequencelengths
1
647
split_name
stringclasses
1 value
func_code_url
stringlengths
102
339
TheHortonMachine/hortonmachine
gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java
CoverageUtilities.buildCoverage
public static GridCoverage2D buildCoverage( String name, double[][] dataMatrix, HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs, boolean matrixIsRowCol ) { """ Creates a {@link GridCoverage2D coverage} from a double[][] matrix and the necessary geographic Information. @param name the name of the coverage. @param dataMatrix the matrix containing the data. @param envelopeParams the map of boundary parameters. @param crs the {@link CoordinateReferenceSystem}. @param matrixIsRowCol a flag to tell if the matrix has rowCol or colRow order. @return the {@link GridCoverage2D coverage}. """ WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, matrixIsRowCol); return buildCoverage(name, writableRaster, envelopeParams, crs); }
java
public static GridCoverage2D buildCoverage( String name, double[][] dataMatrix, HashMap<String, Double> envelopeParams, CoordinateReferenceSystem crs, boolean matrixIsRowCol ) { WritableRaster writableRaster = createWritableRasterFromMatrix(dataMatrix, matrixIsRowCol); return buildCoverage(name, writableRaster, envelopeParams, crs); }
[ "public", "static", "GridCoverage2D", "buildCoverage", "(", "String", "name", ",", "double", "[", "]", "[", "]", "dataMatrix", ",", "HashMap", "<", "String", ",", "Double", ">", "envelopeParams", ",", "CoordinateReferenceSystem", "crs", ",", "boolean", "matrixIsRowCol", ")", "{", "WritableRaster", "writableRaster", "=", "createWritableRasterFromMatrix", "(", "dataMatrix", ",", "matrixIsRowCol", ")", ";", "return", "buildCoverage", "(", "name", ",", "writableRaster", ",", "envelopeParams", ",", "crs", ")", ";", "}" ]
Creates a {@link GridCoverage2D coverage} from a double[][] matrix and the necessary geographic Information. @param name the name of the coverage. @param dataMatrix the matrix containing the data. @param envelopeParams the map of boundary parameters. @param crs the {@link CoordinateReferenceSystem}. @param matrixIsRowCol a flag to tell if the matrix has rowCol or colRow order. @return the {@link GridCoverage2D coverage}.
[ "Creates", "a", "{", "@link", "GridCoverage2D", "coverage", "}", "from", "a", "double", "[]", "[]", "matrix", "and", "the", "necessary", "geographic", "Information", "." ]
train
https://github.com/TheHortonMachine/hortonmachine/blob/d2b436bbdf951dc1fda56096a42dbc0eae4d35a5/gears/src/main/java/org/hortonmachine/gears/utils/coverage/CoverageUtilities.java#L825-L829
cloudant/sync-android
cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/mazha/CouchURIHelper.java
CouchURIHelper.changesUri
public URI changesUri(Map<String, Object> query) { """ Returns URI for {@code _changes} endpoint using passed {@code query}. """ String base_uri = String.format( "%s/%s", this.rootUriString, "_changes" ); //lets find the since parameter if(query.containsKey("since")){ Object since = query.get("since"); if(!(since instanceof String)){ //json encode the seq number since it isn't a string query.put("since", JSONUtils.toJson(since)); } } String uri = appendQueryString(base_uri, query); return uriFor(uri); }
java
public URI changesUri(Map<String, Object> query) { String base_uri = String.format( "%s/%s", this.rootUriString, "_changes" ); //lets find the since parameter if(query.containsKey("since")){ Object since = query.get("since"); if(!(since instanceof String)){ //json encode the seq number since it isn't a string query.put("since", JSONUtils.toJson(since)); } } String uri = appendQueryString(base_uri, query); return uriFor(uri); }
[ "public", "URI", "changesUri", "(", "Map", "<", "String", ",", "Object", ">", "query", ")", "{", "String", "base_uri", "=", "String", ".", "format", "(", "\"%s/%s\"", ",", "this", ".", "rootUriString", ",", "\"_changes\"", ")", ";", "//lets find the since parameter", "if", "(", "query", ".", "containsKey", "(", "\"since\"", ")", ")", "{", "Object", "since", "=", "query", ".", "get", "(", "\"since\"", ")", ";", "if", "(", "!", "(", "since", "instanceof", "String", ")", ")", "{", "//json encode the seq number since it isn't a string", "query", ".", "put", "(", "\"since\"", ",", "JSONUtils", ".", "toJson", "(", "since", ")", ")", ";", "}", "}", "String", "uri", "=", "appendQueryString", "(", "base_uri", ",", "query", ")", ";", "return", "uriFor", "(", "uri", ")", ";", "}" ]
Returns URI for {@code _changes} endpoint using passed {@code query}.
[ "Returns", "URI", "for", "{" ]
train
https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/mazha/CouchURIHelper.java#L60-L78
micronaut-projects/micronaut-core
inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java
AbstractBeanDefinition.findBeanForField
@SuppressWarnings("WeakerAccess") @Internal protected final Optional findBeanForField(BeanResolutionContext resolutionContext, BeanContext context, FieldInjectionPoint injectionPoint) { """ Obtains a an optional for the field at the given index and the argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param injectionPoint The field injection point @return The resolved bean """ return resolveBeanWithGenericsForField(resolutionContext, injectionPoint, (beanType, qualifier) -> ((DefaultBeanContext) context).findBean(resolutionContext, beanType, qualifier) ); }
java
@SuppressWarnings("WeakerAccess") @Internal protected final Optional findBeanForField(BeanResolutionContext resolutionContext, BeanContext context, FieldInjectionPoint injectionPoint) { return resolveBeanWithGenericsForField(resolutionContext, injectionPoint, (beanType, qualifier) -> ((DefaultBeanContext) context).findBean(resolutionContext, beanType, qualifier) ); }
[ "@", "SuppressWarnings", "(", "\"WeakerAccess\"", ")", "@", "Internal", "protected", "final", "Optional", "findBeanForField", "(", "BeanResolutionContext", "resolutionContext", ",", "BeanContext", "context", ",", "FieldInjectionPoint", "injectionPoint", ")", "{", "return", "resolveBeanWithGenericsForField", "(", "resolutionContext", ",", "injectionPoint", ",", "(", "beanType", ",", "qualifier", ")", "->", "(", "(", "DefaultBeanContext", ")", "context", ")", ".", "findBean", "(", "resolutionContext", ",", "beanType", ",", "qualifier", ")", ")", ";", "}" ]
Obtains a an optional for the field at the given index and the argument at the given index <p> Warning: this method is used by internal generated code and should not be called by user code. @param resolutionContext The resolution context @param context The context @param injectionPoint The field injection point @return The resolved bean
[ "Obtains", "a", "an", "optional", "for", "the", "field", "at", "the", "given", "index", "and", "the", "argument", "at", "the", "given", "index", "<p", ">", "Warning", ":", "this", "method", "is", "used", "by", "internal", "generated", "code", "and", "should", "not", "be", "called", "by", "user", "code", "." ]
train
https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/context/AbstractBeanDefinition.java#L1387-L1393
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java
Configuration.checkOutputFileEncoding
private boolean checkOutputFileEncoding(String docencoding, DocErrorReporter reporter) { """ Check the validity of the given Source or Output File encoding on this platform. @param docencoding output file encoding. @param reporter used to report errors. """ OutputStream ost= new ByteArrayOutputStream(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter(ost, docencoding); } catch (UnsupportedEncodingException exc) { reporter.printError(getText("doclet.Encoding_not_supported", docencoding)); return false; } finally { try { if (osw != null) { osw.close(); } } catch (IOException exc) { } } return true; }
java
private boolean checkOutputFileEncoding(String docencoding, DocErrorReporter reporter) { OutputStream ost= new ByteArrayOutputStream(); OutputStreamWriter osw = null; try { osw = new OutputStreamWriter(ost, docencoding); } catch (UnsupportedEncodingException exc) { reporter.printError(getText("doclet.Encoding_not_supported", docencoding)); return false; } finally { try { if (osw != null) { osw.close(); } } catch (IOException exc) { } } return true; }
[ "private", "boolean", "checkOutputFileEncoding", "(", "String", "docencoding", ",", "DocErrorReporter", "reporter", ")", "{", "OutputStream", "ost", "=", "new", "ByteArrayOutputStream", "(", ")", ";", "OutputStreamWriter", "osw", "=", "null", ";", "try", "{", "osw", "=", "new", "OutputStreamWriter", "(", "ost", ",", "docencoding", ")", ";", "}", "catch", "(", "UnsupportedEncodingException", "exc", ")", "{", "reporter", ".", "printError", "(", "getText", "(", "\"doclet.Encoding_not_supported\"", ",", "docencoding", ")", ")", ";", "return", "false", ";", "}", "finally", "{", "try", "{", "if", "(", "osw", "!=", "null", ")", "{", "osw", ".", "close", "(", ")", ";", "}", "}", "catch", "(", "IOException", "exc", ")", "{", "}", "}", "return", "true", ";", "}" ]
Check the validity of the given Source or Output File encoding on this platform. @param docencoding output file encoding. @param reporter used to report errors.
[ "Check", "the", "validity", "of", "the", "given", "Source", "or", "Output", "File", "encoding", "on", "this", "platform", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/Configuration.java#L649-L668
Azure/azure-sdk-for-java
cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java
ReviewsImpl.addVideoTranscriptAsync
public Observable<Void> addVideoTranscriptAsync(String teamName, String reviewId, byte[] vTTfile) { """ This API adds a transcript file (text version of all the words spoken in a video) to a video review. The file should be a valid WebVTT format. @param teamName Your team name. @param reviewId Id of the review. @param vTTfile Transcript file of the video. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful. """ return addVideoTranscriptWithServiceResponseAsync(teamName, reviewId, vTTfile).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> addVideoTranscriptAsync(String teamName, String reviewId, byte[] vTTfile) { return addVideoTranscriptWithServiceResponseAsync(teamName, reviewId, vTTfile).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "addVideoTranscriptAsync", "(", "String", "teamName", ",", "String", "reviewId", ",", "byte", "[", "]", "vTTfile", ")", "{", "return", "addVideoTranscriptWithServiceResponseAsync", "(", "teamName", ",", "reviewId", ",", "vTTfile", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Void", ">", ",", "Void", ">", "(", ")", "{", "@", "Override", "public", "Void", "call", "(", "ServiceResponse", "<", "Void", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
This API adds a transcript file (text version of all the words spoken in a video) to a video review. The file should be a valid WebVTT format. @param teamName Your team name. @param reviewId Id of the review. @param vTTfile Transcript file of the video. @throws IllegalArgumentException thrown if parameters fail the validation @return the {@link ServiceResponse} object if successful.
[ "This", "API", "adds", "a", "transcript", "file", "(", "text", "version", "of", "all", "the", "words", "spoken", "in", "a", "video", ")", "to", "a", "video", "review", ".", "The", "file", "should", "be", "a", "valid", "WebVTT", "format", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/contentmoderator/src/main/java/com/microsoft/azure/cognitiveservices/vision/contentmoderator/implementation/ReviewsImpl.java#L1819-L1826
jmxtrans/jmxtrans
jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java
JmxTransformer.getProcessConfigFiles
@VisibleForTesting List<File> getProcessConfigFiles() { """ If getJsonFile() is a file, then that is all we load. Otherwise, look in the jsonDir for files. <p/> Files must end with .json as the suffix. """ // TODO : should use a FileVisitor (Once we update to Java 7) File[] files; File configurationDirOrFile = configuration.getProcessConfigDirOrFile(); if (configurationDirOrFile == null) { throw new IllegalStateException("Configuration should specify configuration directory or file, with -j of -f option"); } if (configurationDirOrFile.isFile()) { files = new File[1]; files[0] = configurationDirOrFile; } else { files = firstNonNull(configurationDirOrFile.listFiles(), new File[0]); } List<File> result = new ArrayList<>(); for (File file : files) { if (this.isProcessConfigFile(file)) { result.add(file); } } return result; }
java
@VisibleForTesting List<File> getProcessConfigFiles() { // TODO : should use a FileVisitor (Once we update to Java 7) File[] files; File configurationDirOrFile = configuration.getProcessConfigDirOrFile(); if (configurationDirOrFile == null) { throw new IllegalStateException("Configuration should specify configuration directory or file, with -j of -f option"); } if (configurationDirOrFile.isFile()) { files = new File[1]; files[0] = configurationDirOrFile; } else { files = firstNonNull(configurationDirOrFile.listFiles(), new File[0]); } List<File> result = new ArrayList<>(); for (File file : files) { if (this.isProcessConfigFile(file)) { result.add(file); } } return result; }
[ "@", "VisibleForTesting", "List", "<", "File", ">", "getProcessConfigFiles", "(", ")", "{", "// TODO : should use a FileVisitor (Once we update to Java 7)", "File", "[", "]", "files", ";", "File", "configurationDirOrFile", "=", "configuration", ".", "getProcessConfigDirOrFile", "(", ")", ";", "if", "(", "configurationDirOrFile", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Configuration should specify configuration directory or file, with -j of -f option\"", ")", ";", "}", "if", "(", "configurationDirOrFile", ".", "isFile", "(", ")", ")", "{", "files", "=", "new", "File", "[", "1", "]", ";", "files", "[", "0", "]", "=", "configurationDirOrFile", ";", "}", "else", "{", "files", "=", "firstNonNull", "(", "configurationDirOrFile", ".", "listFiles", "(", ")", ",", "new", "File", "[", "0", "]", ")", ";", "}", "List", "<", "File", ">", "result", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "File", "file", ":", "files", ")", "{", "if", "(", "this", ".", "isProcessConfigFile", "(", "file", ")", ")", "{", "result", ".", "add", "(", "file", ")", ";", "}", "}", "return", "result", ";", "}" ]
If getJsonFile() is a file, then that is all we load. Otherwise, look in the jsonDir for files. <p/> Files must end with .json as the suffix.
[ "If", "getJsonFile", "()", "is", "a", "file", "then", "that", "is", "all", "we", "load", ".", "Otherwise", "look", "in", "the", "jsonDir", "for", "files", ".", "<p", "/", ">", "Files", "must", "end", "with", ".", "json", "as", "the", "suffix", "." ]
train
https://github.com/jmxtrans/jmxtrans/blob/496f342de3bcf2c2226626374b7a16edf8f4ba2a/jmxtrans-core/src/main/java/com/googlecode/jmxtrans/JmxTransformer.java#L433-L455
fhoeben/hsac-fitnesse-fixtures
src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java
SoapCallMapColumnFixture.callServiceImpl
protected Response callServiceImpl(String urlSymbolKey, String soapAction) { """ Creates response, calls service using configured template and current row's values and calls SOAP service. @param urlSymbolKey key of symbol containing service's URL. @param soapAction SOAPAction header value (null if no header is required). @return filled response """ String url = getSymbol(urlSymbolKey).toString(); Response response = getEnvironment().createInstance(getResponseClass()); callSoapService(url, getTemplateName(), soapAction, response); return response; }
java
protected Response callServiceImpl(String urlSymbolKey, String soapAction) { String url = getSymbol(urlSymbolKey).toString(); Response response = getEnvironment().createInstance(getResponseClass()); callSoapService(url, getTemplateName(), soapAction, response); return response; }
[ "protected", "Response", "callServiceImpl", "(", "String", "urlSymbolKey", ",", "String", "soapAction", ")", "{", "String", "url", "=", "getSymbol", "(", "urlSymbolKey", ")", ".", "toString", "(", ")", ";", "Response", "response", "=", "getEnvironment", "(", ")", ".", "createInstance", "(", "getResponseClass", "(", ")", ")", ";", "callSoapService", "(", "url", ",", "getTemplateName", "(", ")", ",", "soapAction", ",", "response", ")", ";", "return", "response", ";", "}" ]
Creates response, calls service using configured template and current row's values and calls SOAP service. @param urlSymbolKey key of symbol containing service's URL. @param soapAction SOAPAction header value (null if no header is required). @return filled response
[ "Creates", "response", "calls", "service", "using", "configured", "template", "and", "current", "row", "s", "values", "and", "calls", "SOAP", "service", "." ]
train
https://github.com/fhoeben/hsac-fitnesse-fixtures/blob/4e9018d7386a9aa65bfcbf07eb28ae064edd1732/src/main/java/nl/hsac/fitnesse/fixture/fit/SoapCallMapColumnFixture.java#L56-L61
google/error-prone-javac
src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/taglets/ParamTaglet.java
ParamTaglet.getTagletOutput
public Content getTagletOutput(Doc holder, TagletWriter writer) { """ Given an array of <code>ParamTag</code>s,return its string representation. @param holder the member that holds the param tags. @param writer the TagletWriter that will write this tag. @return the TagletOutput representation of these <code>ParamTag</code>s. """ if (holder instanceof ExecutableMemberDoc) { ExecutableMemberDoc member = (ExecutableMemberDoc) holder; Content output = getTagletOutput(false, member, writer, member.typeParameters(), member.typeParamTags()); output.addContent(getTagletOutput(true, member, writer, member.parameters(), member.paramTags())); return output; } else { ClassDoc classDoc = (ClassDoc) holder; return getTagletOutput(false, classDoc, writer, classDoc.typeParameters(), classDoc.typeParamTags()); } }
java
public Content getTagletOutput(Doc holder, TagletWriter writer) { if (holder instanceof ExecutableMemberDoc) { ExecutableMemberDoc member = (ExecutableMemberDoc) holder; Content output = getTagletOutput(false, member, writer, member.typeParameters(), member.typeParamTags()); output.addContent(getTagletOutput(true, member, writer, member.parameters(), member.paramTags())); return output; } else { ClassDoc classDoc = (ClassDoc) holder; return getTagletOutput(false, classDoc, writer, classDoc.typeParameters(), classDoc.typeParamTags()); } }
[ "public", "Content", "getTagletOutput", "(", "Doc", "holder", ",", "TagletWriter", "writer", ")", "{", "if", "(", "holder", "instanceof", "ExecutableMemberDoc", ")", "{", "ExecutableMemberDoc", "member", "=", "(", "ExecutableMemberDoc", ")", "holder", ";", "Content", "output", "=", "getTagletOutput", "(", "false", ",", "member", ",", "writer", ",", "member", ".", "typeParameters", "(", ")", ",", "member", ".", "typeParamTags", "(", ")", ")", ";", "output", ".", "addContent", "(", "getTagletOutput", "(", "true", ",", "member", ",", "writer", ",", "member", ".", "parameters", "(", ")", ",", "member", ".", "paramTags", "(", ")", ")", ")", ";", "return", "output", ";", "}", "else", "{", "ClassDoc", "classDoc", "=", "(", "ClassDoc", ")", "holder", ";", "return", "getTagletOutput", "(", "false", ",", "classDoc", ",", "writer", ",", "classDoc", ".", "typeParameters", "(", ")", ",", "classDoc", ".", "typeParamTags", "(", ")", ")", ";", "}", "}" ]
Given an array of <code>ParamTag</code>s,return its string representation. @param holder the member that holds the param tags. @param writer the TagletWriter that will write this tag. @return the TagletOutput representation of these <code>ParamTag</code>s.
[ "Given", "an", "array", "of", "<code", ">", "ParamTag<", "/", "code", ">", "s", "return", "its", "string", "representation", "." ]
train
https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/taglets/ParamTaglet.java#L170-L183
Baidu-AIP/java-sdk
src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java
AipImageSearch.similarUpdateUrl
public JSONObject similarUpdateUrl(String url, HashMap<String, String> options) { """ 相似图检索—更新接口 **更新图库中图片的摘要和分类信息(具体变量为brief、tags)** @param url - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 @param options - 可选参数对象,key: value都为string类型 options - options列表: brief 更新的摘要信息,最长256B。样例:{"name":"周杰伦", "id":"666"} tags 1 - 65535范围内的整数,tag间以逗号分隔,最多2个tag。样例:"100,11" ;检索时可圈定分类维度进行检索 @return JSONObject """ AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.SIMILAR_UPDATE); postOperation(request); return requestServer(request); }
java
public JSONObject similarUpdateUrl(String url, HashMap<String, String> options) { AipRequest request = new AipRequest(); preOperation(request); request.addBody("url", url); if (options != null) { request.addBody(options); } request.setUri(ImageSearchConsts.SIMILAR_UPDATE); postOperation(request); return requestServer(request); }
[ "public", "JSONObject", "similarUpdateUrl", "(", "String", "url", ",", "HashMap", "<", "String", ",", "String", ">", "options", ")", "{", "AipRequest", "request", "=", "new", "AipRequest", "(", ")", ";", "preOperation", "(", "request", ")", ";", "request", ".", "addBody", "(", "\"url\"", ",", "url", ")", ";", "if", "(", "options", "!=", "null", ")", "{", "request", ".", "addBody", "(", "options", ")", ";", "}", "request", ".", "setUri", "(", "ImageSearchConsts", ".", "SIMILAR_UPDATE", ")", ";", "postOperation", "(", "request", ")", ";", "return", "requestServer", "(", "request", ")", ";", "}" ]
相似图检索—更新接口 **更新图库中图片的摘要和分类信息(具体变量为brief、tags)** @param url - 图片完整URL,URL长度不超过1024字节,URL对应的图片base64编码后大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式,当image字段存在时url字段失效 @param options - 可选参数对象,key: value都为string类型 options - options列表: brief 更新的摘要信息,最长256B。样例:{"name":"周杰伦", "id":"666"} tags 1 - 65535范围内的整数,tag间以逗号分隔,最多2个tag。样例:"100,11" ;检索时可圈定分类维度进行检索 @return JSONObject
[ "相似图检索—更新接口", "**", "更新图库中图片的摘要和分类信息(具体变量为brief、tags)", "**" ]
train
https://github.com/Baidu-AIP/java-sdk/blob/16bb8b7bb8f9bbcb7c8af62d0a67a1e79eecad90/src/main/java/com/baidu/aip/imagesearch/AipImageSearch.java#L561-L572
looly/hutool
hutool-core/src/main/java/cn/hutool/core/lang/Validator.java
Validator.validateMac
public static <T extends CharSequence> T validateMac(T value, String errorMsg) throws ValidateException { """ 验证是否为MAC地址 @param <T> 字符串类型 @param value 值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 @since 4.1.3 """ if (false == isMac(value)) { throw new ValidateException(errorMsg); } return value; }
java
public static <T extends CharSequence> T validateMac(T value, String errorMsg) throws ValidateException { if (false == isMac(value)) { throw new ValidateException(errorMsg); } return value; }
[ "public", "static", "<", "T", "extends", "CharSequence", ">", "T", "validateMac", "(", "T", "value", ",", "String", "errorMsg", ")", "throws", "ValidateException", "{", "if", "(", "false", "==", "isMac", "(", "value", ")", ")", "{", "throw", "new", "ValidateException", "(", "errorMsg", ")", ";", "}", "return", "value", ";", "}" ]
验证是否为MAC地址 @param <T> 字符串类型 @param value 值 @param errorMsg 验证错误的信息 @return 验证后的值 @throws ValidateException 验证异常 @since 4.1.3
[ "验证是否为MAC地址" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/lang/Validator.java#L863-L868
lightblueseas/net-extensions
src/main/java/de/alpharogroup/net/socket/SocketExtensions.java
SocketExtensions.readObject
public static Object readObject(final String serverName, final int port) throws IOException, ClassNotFoundException { """ Reads an object from the given socket InetAddress. @param serverName The Name from the address to read. @param port The port to read. @return the object @throws IOException Signals that an I/O exception has occurred. @throws ClassNotFoundException the class not found exception """ final InetAddress inetAddress = InetAddress.getByName(serverName); return readObject(new Socket(inetAddress, port)); }
java
public static Object readObject(final String serverName, final int port) throws IOException, ClassNotFoundException { final InetAddress inetAddress = InetAddress.getByName(serverName); return readObject(new Socket(inetAddress, port)); }
[ "public", "static", "Object", "readObject", "(", "final", "String", "serverName", ",", "final", "int", "port", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "final", "InetAddress", "inetAddress", "=", "InetAddress", ".", "getByName", "(", "serverName", ")", ";", "return", "readObject", "(", "new", "Socket", "(", "inetAddress", ",", "port", ")", ")", ";", "}" ]
Reads an object from the given socket InetAddress. @param serverName The Name from the address to read. @param port The port to read. @return the object @throws IOException Signals that an I/O exception has occurred. @throws ClassNotFoundException the class not found exception
[ "Reads", "an", "object", "from", "the", "given", "socket", "InetAddress", "." ]
train
https://github.com/lightblueseas/net-extensions/blob/771757a93fa9ad13ce0fe061c158e5cba43344cb/src/main/java/de/alpharogroup/net/socket/SocketExtensions.java#L332-L337
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java
DOMHelper.getParentOfNode
public static Node getParentOfNode(Node node) throws RuntimeException { """ Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs, parent for other nodes. <p> Background: The DOM believes that you must be your Parent's Child, and thus Attrs don't have parents. XPath said that Attrs do have their owning Element as their parent. This function bridges the difference, either by using the DOM Level 2 ownerElement function or by using a "silly and expensive function" in Level 1 DOMs. <p> (There's some discussion of future DOMs generalizing ownerElement into ownerNode and making it work on all types of nodes. This still wouldn't help the users of Level 1 or Level 2 DOMs) <p> @param node Node whose XPath parent we want to obtain @return the parent of the node, or the ownerElement if it's an Attr node, or null if the node is an orphan. @throws RuntimeException if the Document has no root element. This can't arise if the Document was created via the DOM Level 2 factory methods, but is possible if other mechanisms were used to obtain it """ Node parent; short nodeType = node.getNodeType(); if (Node.ATTRIBUTE_NODE == nodeType) { Document doc = node.getOwnerDocument(); /* TBD: if(null == doc) { throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!"); } */ // Given how expensive the tree walk may be, we should first ask // whether this DOM can answer the question for us. The additional // test does slow down Level 1 DOMs slightly. DOMHelper2, which // is currently specialized for Xerces, assumes it can use the // Level 2 solution. We might want to have an intermediate stage, // which would assume DOM Level 2 but not assume Xerces. // // (Shouldn't have to check whether impl is null in a compliant DOM, // but let's be paranoid for a moment...) DOMImplementation impl=doc.getImplementation(); if(impl!=null && impl.hasFeature("Core","2.0")) { parent=((Attr)node).getOwnerElement(); return parent; } // DOM Level 1 solution, as fallback. Hugely expensive. Element rootElem = doc.getDocumentElement(); if (null == rootElem) { throw new RuntimeException( XMLMessages.createXMLMessage( XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT, null)); //"Attribute child does not have an owner document element!"); } parent = locateAttrParent(rootElem, node); } else { parent = node.getParentNode(); // if((Node.DOCUMENT_NODE != nodeType) && (null == parent)) // { // throw new RuntimeException("Child does not have parent!"); // } } return parent; }
java
public static Node getParentOfNode(Node node) throws RuntimeException { Node parent; short nodeType = node.getNodeType(); if (Node.ATTRIBUTE_NODE == nodeType) { Document doc = node.getOwnerDocument(); /* TBD: if(null == doc) { throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!"); } */ // Given how expensive the tree walk may be, we should first ask // whether this DOM can answer the question for us. The additional // test does slow down Level 1 DOMs slightly. DOMHelper2, which // is currently specialized for Xerces, assumes it can use the // Level 2 solution. We might want to have an intermediate stage, // which would assume DOM Level 2 but not assume Xerces. // // (Shouldn't have to check whether impl is null in a compliant DOM, // but let's be paranoid for a moment...) DOMImplementation impl=doc.getImplementation(); if(impl!=null && impl.hasFeature("Core","2.0")) { parent=((Attr)node).getOwnerElement(); return parent; } // DOM Level 1 solution, as fallback. Hugely expensive. Element rootElem = doc.getDocumentElement(); if (null == rootElem) { throw new RuntimeException( XMLMessages.createXMLMessage( XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT, null)); //"Attribute child does not have an owner document element!"); } parent = locateAttrParent(rootElem, node); } else { parent = node.getParentNode(); // if((Node.DOCUMENT_NODE != nodeType) && (null == parent)) // { // throw new RuntimeException("Child does not have parent!"); // } } return parent; }
[ "public", "static", "Node", "getParentOfNode", "(", "Node", "node", ")", "throws", "RuntimeException", "{", "Node", "parent", ";", "short", "nodeType", "=", "node", ".", "getNodeType", "(", ")", ";", "if", "(", "Node", ".", "ATTRIBUTE_NODE", "==", "nodeType", ")", "{", "Document", "doc", "=", "node", ".", "getOwnerDocument", "(", ")", ";", "/*\n TBD:\n if(null == doc)\n {\n throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//\"Attribute child does not have an owner document!\");\n }\n */", "// Given how expensive the tree walk may be, we should first ask ", "// whether this DOM can answer the question for us. The additional", "// test does slow down Level 1 DOMs slightly. DOMHelper2, which", "// is currently specialized for Xerces, assumes it can use the", "// Level 2 solution. We might want to have an intermediate stage,", "// which would assume DOM Level 2 but not assume Xerces.", "//", "// (Shouldn't have to check whether impl is null in a compliant DOM,", "// but let's be paranoid for a moment...)", "DOMImplementation", "impl", "=", "doc", ".", "getImplementation", "(", ")", ";", "if", "(", "impl", "!=", "null", "&&", "impl", ".", "hasFeature", "(", "\"Core\"", ",", "\"2.0\"", ")", ")", "{", "parent", "=", "(", "(", "Attr", ")", "node", ")", ".", "getOwnerElement", "(", ")", ";", "return", "parent", ";", "}", "// DOM Level 1 solution, as fallback. Hugely expensive. ", "Element", "rootElem", "=", "doc", ".", "getDocumentElement", "(", ")", ";", "if", "(", "null", "==", "rootElem", ")", "{", "throw", "new", "RuntimeException", "(", "XMLMessages", ".", "createXMLMessage", "(", "XMLErrorResources", ".", "ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT", ",", "null", ")", ")", ";", "//\"Attribute child does not have an owner document element!\");", "}", "parent", "=", "locateAttrParent", "(", "rootElem", ",", "node", ")", ";", "}", "else", "{", "parent", "=", "node", ".", "getParentNode", "(", ")", ";", "// if((Node.DOCUMENT_NODE != nodeType) && (null == parent))", "// {", "// throw new RuntimeException(\"Child does not have parent!\");", "// }", "}", "return", "parent", ";", "}" ]
Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs, parent for other nodes. <p> Background: The DOM believes that you must be your Parent's Child, and thus Attrs don't have parents. XPath said that Attrs do have their owning Element as their parent. This function bridges the difference, either by using the DOM Level 2 ownerElement function or by using a "silly and expensive function" in Level 1 DOMs. <p> (There's some discussion of future DOMs generalizing ownerElement into ownerNode and making it work on all types of nodes. This still wouldn't help the users of Level 1 or Level 2 DOMs) <p> @param node Node whose XPath parent we want to obtain @return the parent of the node, or the ownerElement if it's an Attr node, or null if the node is an orphan. @throws RuntimeException if the Document has no root element. This can't arise if the Document was created via the DOM Level 2 factory methods, but is possible if other mechanisms were used to obtain it
[ "Obtain", "the", "XPath", "-", "model", "parent", "of", "a", "DOM", "node", "--", "ownerElement", "for", "Attrs", "parent", "for", "other", "nodes", ".", "<p", ">", "Background", ":", "The", "DOM", "believes", "that", "you", "must", "be", "your", "Parent", "s", "Child", "and", "thus", "Attrs", "don", "t", "have", "parents", ".", "XPath", "said", "that", "Attrs", "do", "have", "their", "owning", "Element", "as", "their", "parent", ".", "This", "function", "bridges", "the", "difference", "either", "by", "using", "the", "DOM", "Level", "2", "ownerElement", "function", "or", "by", "using", "a", "silly", "and", "expensive", "function", "in", "Level", "1", "DOMs", ".", "<p", ">", "(", "There", "s", "some", "discussion", "of", "future", "DOMs", "generalizing", "ownerElement", "into", "ownerNode", "and", "making", "it", "work", "on", "all", "types", "of", "nodes", ".", "This", "still", "wouldn", "t", "help", "the", "users", "of", "Level", "1", "or", "Level", "2", "DOMs", ")", "<p", ">" ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xml/utils/DOMHelper.java#L1010-L1068
ironjacamar/ironjacamar
rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java
Main.hasMcfTransactionSupport
private static void hasMcfTransactionSupport(PrintStream out, PrintStream error, String classname, URLClassLoader cl) { """ hasMcfTransactionSupport @param out output stream @param error output stream @param classname classname @param cl classloader """ try { out.print(" TransactionSupport: "); Class<?> mcfClz = Class.forName(classname, true, cl); ManagedConnectionFactory mcf = (ManagedConnectionFactory)mcfClz.newInstance(); if (hasInterface(mcf.getClass(), "javax.resource.spi.TransactionSupport")) { out.println("Yes"); } else { out.println("No"); } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); out.println("Unknown"); } }
java
private static void hasMcfTransactionSupport(PrintStream out, PrintStream error, String classname, URLClassLoader cl) { try { out.print(" TransactionSupport: "); Class<?> mcfClz = Class.forName(classname, true, cl); ManagedConnectionFactory mcf = (ManagedConnectionFactory)mcfClz.newInstance(); if (hasInterface(mcf.getClass(), "javax.resource.spi.TransactionSupport")) { out.println("Yes"); } else { out.println("No"); } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); out.println("Unknown"); } }
[ "private", "static", "void", "hasMcfTransactionSupport", "(", "PrintStream", "out", ",", "PrintStream", "error", ",", "String", "classname", ",", "URLClassLoader", "cl", ")", "{", "try", "{", "out", ".", "print", "(", "\" TransactionSupport: \"", ")", ";", "Class", "<", "?", ">", "mcfClz", "=", "Class", ".", "forName", "(", "classname", ",", "true", ",", "cl", ")", ";", "ManagedConnectionFactory", "mcf", "=", "(", "ManagedConnectionFactory", ")", "mcfClz", ".", "newInstance", "(", ")", ";", "if", "(", "hasInterface", "(", "mcf", ".", "getClass", "(", ")", ",", "\"javax.resource.spi.TransactionSupport\"", ")", ")", "{", "out", ".", "println", "(", "\"Yes\"", ")", ";", "}", "else", "{", "out", ".", "println", "(", "\"No\"", ")", ";", "}", "}", "catch", "(", "Throwable", "t", ")", "{", "// Nothing we can do", "t", ".", "printStackTrace", "(", "error", ")", ";", "out", ".", "println", "(", "\"Unknown\"", ")", ";", "}", "}" ]
hasMcfTransactionSupport @param out output stream @param error output stream @param classname classname @param cl classloader
[ "hasMcfTransactionSupport" ]
train
https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/rarinfo/src/main/java/org/ironjacamar/rarinfo/Main.java#L949-L973
SonarSource/sonarqube
server/sonar-process/src/main/java/org/sonar/process/logging/LogbackHelper.java
LogbackHelper.configureForSubprocessGobbler
public void configureForSubprocessGobbler(Props props, String logPattern) { """ Make the logback configuration for a sub process to correctly push all its logs to be read by a stream gobbler on the sub process's System.out. @see #buildLogPattern(RootLoggerConfig) """ if (isAllLogsToConsoleEnabled(props)) { LoggerContext ctx = getRootContext(); ctx.getLogger(ROOT_LOGGER_NAME).addAppender(newConsoleAppender(ctx, "root_console", logPattern)); } }
java
public void configureForSubprocessGobbler(Props props, String logPattern) { if (isAllLogsToConsoleEnabled(props)) { LoggerContext ctx = getRootContext(); ctx.getLogger(ROOT_LOGGER_NAME).addAppender(newConsoleAppender(ctx, "root_console", logPattern)); } }
[ "public", "void", "configureForSubprocessGobbler", "(", "Props", "props", ",", "String", "logPattern", ")", "{", "if", "(", "isAllLogsToConsoleEnabled", "(", "props", ")", ")", "{", "LoggerContext", "ctx", "=", "getRootContext", "(", ")", ";", "ctx", ".", "getLogger", "(", "ROOT_LOGGER_NAME", ")", ".", "addAppender", "(", "newConsoleAppender", "(", "ctx", ",", "\"root_console\"", ",", "logPattern", ")", ")", ";", "}", "}" ]
Make the logback configuration for a sub process to correctly push all its logs to be read by a stream gobbler on the sub process's System.out. @see #buildLogPattern(RootLoggerConfig)
[ "Make", "the", "logback", "configuration", "for", "a", "sub", "process", "to", "correctly", "push", "all", "its", "logs", "to", "be", "read", "by", "a", "stream", "gobbler", "on", "the", "sub", "process", "s", "System", ".", "out", "." ]
train
https://github.com/SonarSource/sonarqube/blob/2fffa4c2f79ae3714844d7742796e82822b6a98a/server/sonar-process/src/main/java/org/sonar/process/logging/LogbackHelper.java#L211-L216
aol/cyclops
cyclops/src/main/java/com/oath/cyclops/util/box/MutableByte.java
MutableByte.fromExternal
public static MutableByte fromExternal(final Supplier<Byte> s, final Consumer<Byte> c) { """ Construct a MutableByte that gets and sets an external value using the provided Supplier and Consumer e.g. <pre> {@code MutableByte mutable = MutableByte.fromExternal(()->!this.value,val->!this.value); } </pre> @param s Supplier of an external value @param c Consumer that sets an external value @return MutableByte that gets / sets an external (mutable) value """ return new MutableByte() { @Override public byte getAsByte() { return s.get(); } @Override public Byte get() { return getAsByte(); } @Override public MutableByte set(final byte value) { c.accept(value); return this; } }; }
java
public static MutableByte fromExternal(final Supplier<Byte> s, final Consumer<Byte> c) { return new MutableByte() { @Override public byte getAsByte() { return s.get(); } @Override public Byte get() { return getAsByte(); } @Override public MutableByte set(final byte value) { c.accept(value); return this; } }; }
[ "public", "static", "MutableByte", "fromExternal", "(", "final", "Supplier", "<", "Byte", ">", "s", ",", "final", "Consumer", "<", "Byte", ">", "c", ")", "{", "return", "new", "MutableByte", "(", ")", "{", "@", "Override", "public", "byte", "getAsByte", "(", ")", "{", "return", "s", ".", "get", "(", ")", ";", "}", "@", "Override", "public", "Byte", "get", "(", ")", "{", "return", "getAsByte", "(", ")", ";", "}", "@", "Override", "public", "MutableByte", "set", "(", "final", "byte", "value", ")", "{", "c", ".", "accept", "(", "value", ")", ";", "return", "this", ";", "}", "}", ";", "}" ]
Construct a MutableByte that gets and sets an external value using the provided Supplier and Consumer e.g. <pre> {@code MutableByte mutable = MutableByte.fromExternal(()->!this.value,val->!this.value); } </pre> @param s Supplier of an external value @param c Consumer that sets an external value @return MutableByte that gets / sets an external (mutable) value
[ "Construct", "a", "MutableByte", "that", "gets", "and", "sets", "an", "external", "value", "using", "the", "provided", "Supplier", "and", "Consumer" ]
train
https://github.com/aol/cyclops/blob/59a9fde30190a4d1faeb9f6d9851d209d82b81dd/cyclops/src/main/java/com/oath/cyclops/util/box/MutableByte.java#L81-L99
Wadpam/guja
guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java
GeneratedDUserDaoImpl.queryByDisplayName
public Iterable<DUser> queryByDisplayName(java.lang.String displayName) { """ query-by method for field displayName @param displayName the specified attribute @return an Iterable of DUsers for the specified displayName """ return queryByField(null, DUserMapper.Field.DISPLAYNAME.getFieldName(), displayName); }
java
public Iterable<DUser> queryByDisplayName(java.lang.String displayName) { return queryByField(null, DUserMapper.Field.DISPLAYNAME.getFieldName(), displayName); }
[ "public", "Iterable", "<", "DUser", ">", "queryByDisplayName", "(", "java", ".", "lang", ".", "String", "displayName", ")", "{", "return", "queryByField", "(", "null", ",", "DUserMapper", ".", "Field", ".", "DISPLAYNAME", ".", "getFieldName", "(", ")", ",", "displayName", ")", ";", "}" ]
query-by method for field displayName @param displayName the specified attribute @return an Iterable of DUsers for the specified displayName
[ "query", "-", "by", "method", "for", "field", "displayName" ]
train
https://github.com/Wadpam/guja/blob/eb8ba8e6794a96ea0dd9744cada4f9ad9618f114/guja-core/src/main/java/com/wadpam/guja/oauth2/dao/GeneratedDUserDaoImpl.java#L133-L135
pietermartin/sqlg
sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java
PostgresDialect.sqlTypeToPropertyType
@Override public PropertyType sqlTypeToPropertyType(SqlgGraph sqlgGraph, String schema, String table, String column, int sqlType, String typeName, ListIterator<Triple<String, Integer, String>> metaDataIter) { """ This is only used for upgrading from pre sqlg_schema sqlg to a sqlg_schema """ switch (sqlType) { case Types.BIT: return PropertyType.BOOLEAN; case Types.SMALLINT: return PropertyType.SHORT; case Types.INTEGER: return PropertyType.INTEGER; case Types.BIGINT: return PropertyType.LONG; case Types.REAL: return PropertyType.FLOAT; case Types.DOUBLE: return PropertyType.DOUBLE; case Types.VARCHAR: return PropertyType.STRING; case Types.TIMESTAMP: return PropertyType.LOCALDATETIME; case Types.DATE: return PropertyType.LOCALDATE; case Types.TIME: return PropertyType.LOCALTIME; case Types.OTHER: //this is a f up as only JSON can be used for other. //means all the gis data types which are also OTHER are not supported switch (typeName) { case "jsonb": return PropertyType.JSON; case "geometry": return getPostGisGeometryType(sqlgGraph, schema, table, column); case "geography": return getPostGisGeographyType(sqlgGraph, schema, table, column); default: throw new RuntimeException("Other type not supported " + typeName); } case Types.BINARY: return BYTE_ARRAY; case Types.ARRAY: return sqlArrayTypeNameToPropertyType(typeName, sqlgGraph, schema, table, column, metaDataIter); default: throw new IllegalStateException("Unknown sqlType " + sqlType); } }
java
@Override public PropertyType sqlTypeToPropertyType(SqlgGraph sqlgGraph, String schema, String table, String column, int sqlType, String typeName, ListIterator<Triple<String, Integer, String>> metaDataIter) { switch (sqlType) { case Types.BIT: return PropertyType.BOOLEAN; case Types.SMALLINT: return PropertyType.SHORT; case Types.INTEGER: return PropertyType.INTEGER; case Types.BIGINT: return PropertyType.LONG; case Types.REAL: return PropertyType.FLOAT; case Types.DOUBLE: return PropertyType.DOUBLE; case Types.VARCHAR: return PropertyType.STRING; case Types.TIMESTAMP: return PropertyType.LOCALDATETIME; case Types.DATE: return PropertyType.LOCALDATE; case Types.TIME: return PropertyType.LOCALTIME; case Types.OTHER: //this is a f up as only JSON can be used for other. //means all the gis data types which are also OTHER are not supported switch (typeName) { case "jsonb": return PropertyType.JSON; case "geometry": return getPostGisGeometryType(sqlgGraph, schema, table, column); case "geography": return getPostGisGeographyType(sqlgGraph, schema, table, column); default: throw new RuntimeException("Other type not supported " + typeName); } case Types.BINARY: return BYTE_ARRAY; case Types.ARRAY: return sqlArrayTypeNameToPropertyType(typeName, sqlgGraph, schema, table, column, metaDataIter); default: throw new IllegalStateException("Unknown sqlType " + sqlType); } }
[ "@", "Override", "public", "PropertyType", "sqlTypeToPropertyType", "(", "SqlgGraph", "sqlgGraph", ",", "String", "schema", ",", "String", "table", ",", "String", "column", ",", "int", "sqlType", ",", "String", "typeName", ",", "ListIterator", "<", "Triple", "<", "String", ",", "Integer", ",", "String", ">", ">", "metaDataIter", ")", "{", "switch", "(", "sqlType", ")", "{", "case", "Types", ".", "BIT", ":", "return", "PropertyType", ".", "BOOLEAN", ";", "case", "Types", ".", "SMALLINT", ":", "return", "PropertyType", ".", "SHORT", ";", "case", "Types", ".", "INTEGER", ":", "return", "PropertyType", ".", "INTEGER", ";", "case", "Types", ".", "BIGINT", ":", "return", "PropertyType", ".", "LONG", ";", "case", "Types", ".", "REAL", ":", "return", "PropertyType", ".", "FLOAT", ";", "case", "Types", ".", "DOUBLE", ":", "return", "PropertyType", ".", "DOUBLE", ";", "case", "Types", ".", "VARCHAR", ":", "return", "PropertyType", ".", "STRING", ";", "case", "Types", ".", "TIMESTAMP", ":", "return", "PropertyType", ".", "LOCALDATETIME", ";", "case", "Types", ".", "DATE", ":", "return", "PropertyType", ".", "LOCALDATE", ";", "case", "Types", ".", "TIME", ":", "return", "PropertyType", ".", "LOCALTIME", ";", "case", "Types", ".", "OTHER", ":", "//this is a f up as only JSON can be used for other.", "//means all the gis data types which are also OTHER are not supported", "switch", "(", "typeName", ")", "{", "case", "\"jsonb\"", ":", "return", "PropertyType", ".", "JSON", ";", "case", "\"geometry\"", ":", "return", "getPostGisGeometryType", "(", "sqlgGraph", ",", "schema", ",", "table", ",", "column", ")", ";", "case", "\"geography\"", ":", "return", "getPostGisGeographyType", "(", "sqlgGraph", ",", "schema", ",", "table", ",", "column", ")", ";", "default", ":", "throw", "new", "RuntimeException", "(", "\"Other type not supported \"", "+", "typeName", ")", ";", "}", "case", "Types", ".", "BINARY", ":", "return", "BYTE_ARRAY", ";", "case", "Types", ".", "ARRAY", ":", "return", "sqlArrayTypeNameToPropertyType", "(", "typeName", ",", "sqlgGraph", ",", "schema", ",", "table", ",", "column", ",", "metaDataIter", ")", ";", "default", ":", "throw", "new", "IllegalStateException", "(", "\"Unknown sqlType \"", "+", "sqlType", ")", ";", "}", "}" ]
This is only used for upgrading from pre sqlg_schema sqlg to a sqlg_schema
[ "This", "is", "only", "used", "for", "upgrading", "from", "pre", "sqlg_schema", "sqlg", "to", "a", "sqlg_schema" ]
train
https://github.com/pietermartin/sqlg/blob/c1845a1b31328a5ffda646873b0369ee72af56a7/sqlg-postgres-parent/sqlg-postgres-dialect/src/main/java/org/umlg/sqlg/sql/dialect/PostgresDialect.java#L2108-L2152
apereo/cas
support/cas-server-support-couchdb-core/src/main/java/org/apereo/cas/couchdb/core/ProfileCouchDbRepository.java
ProfileCouchDbRepository.findByLinkedid
@View(name = "by_linkedid", map = "function(doc) { """ Find profile by linkedid. @param linkedid to be searched for @return profile found """ if(doc.linkedid){ emit(doc.linkedid, doc) } }") public CouchDbProfileDocument findByLinkedid(final String linkedid) { return queryView("by_linkedid", linkedid).stream().findFirst().orElse(null); }
java
@View(name = "by_linkedid", map = "function(doc) { if(doc.linkedid){ emit(doc.linkedid, doc) } }") public CouchDbProfileDocument findByLinkedid(final String linkedid) { return queryView("by_linkedid", linkedid).stream().findFirst().orElse(null); }
[ "@", "View", "(", "name", "=", "\"by_linkedid\"", ",", "map", "=", "\"function(doc) { if(doc.linkedid){ emit(doc.linkedid, doc) } }\"", ")", "public", "CouchDbProfileDocument", "findByLinkedid", "(", "final", "String", "linkedid", ")", "{", "return", "queryView", "(", "\"by_linkedid\"", ",", "linkedid", ")", ".", "stream", "(", ")", ".", "findFirst", "(", ")", ".", "orElse", "(", "null", ")", ";", "}" ]
Find profile by linkedid. @param linkedid to be searched for @return profile found
[ "Find", "profile", "by", "linkedid", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-couchdb-core/src/main/java/org/apereo/cas/couchdb/core/ProfileCouchDbRepository.java#L33-L36
mapsforge/mapsforge
mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java
BoundingBox.getPositionRelativeToTile
public Rectangle getPositionRelativeToTile(Tile tile) { """ Computes the coordinates of this bounding box relative to a tile. @param tile the tile to compute the relative position for. @return rectangle giving the relative position. """ Point upperLeft = MercatorProjection.getPixelRelativeToTile(new LatLong(this.maxLatitude, minLongitude), tile); Point lowerRight = MercatorProjection.getPixelRelativeToTile(new LatLong(this.minLatitude, maxLongitude), tile); return new Rectangle(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); }
java
public Rectangle getPositionRelativeToTile(Tile tile) { Point upperLeft = MercatorProjection.getPixelRelativeToTile(new LatLong(this.maxLatitude, minLongitude), tile); Point lowerRight = MercatorProjection.getPixelRelativeToTile(new LatLong(this.minLatitude, maxLongitude), tile); return new Rectangle(upperLeft.x, upperLeft.y, lowerRight.x, lowerRight.y); }
[ "public", "Rectangle", "getPositionRelativeToTile", "(", "Tile", "tile", ")", "{", "Point", "upperLeft", "=", "MercatorProjection", ".", "getPixelRelativeToTile", "(", "new", "LatLong", "(", "this", ".", "maxLatitude", ",", "minLongitude", ")", ",", "tile", ")", ";", "Point", "lowerRight", "=", "MercatorProjection", ".", "getPixelRelativeToTile", "(", "new", "LatLong", "(", "this", ".", "minLatitude", ",", "maxLongitude", ")", ",", "tile", ")", ";", "return", "new", "Rectangle", "(", "upperLeft", ".", "x", ",", "upperLeft", ".", "y", ",", "lowerRight", ".", "x", ",", "lowerRight", ".", "y", ")", ";", "}" ]
Computes the coordinates of this bounding box relative to a tile. @param tile the tile to compute the relative position for. @return rectangle giving the relative position.
[ "Computes", "the", "coordinates", "of", "this", "bounding", "box", "relative", "to", "a", "tile", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/mapsforge-core/src/main/java/org/mapsforge/core/model/BoundingBox.java#L291-L295
Stratio/bdt
src/main/java/com/stratio/qa/specs/CommonG.java
CommonG.generateRequest
@Deprecated public Future<Response> generateRequest(String requestType, boolean secure, String user, String password, String endPoint, String data, String type, String codeBase64) throws Exception { """ Generates the request based on the type of request, the end point, the data and type passed @param requestType type of request to be sent @param secure type of protocol @param user user to be used in request @param password password to be used in request @param endPoint end point to sent the request to @param data to be sent for PUT/POST requests @param type type of data to be sent (json|string) @param codeBase64 XXX @throws Exception exception """ return generateRequest(requestType, secure, user, password, endPoint, data, type); }
java
@Deprecated public Future<Response> generateRequest(String requestType, boolean secure, String user, String password, String endPoint, String data, String type, String codeBase64) throws Exception { return generateRequest(requestType, secure, user, password, endPoint, data, type); }
[ "@", "Deprecated", "public", "Future", "<", "Response", ">", "generateRequest", "(", "String", "requestType", ",", "boolean", "secure", ",", "String", "user", ",", "String", "password", ",", "String", "endPoint", ",", "String", "data", ",", "String", "type", ",", "String", "codeBase64", ")", "throws", "Exception", "{", "return", "generateRequest", "(", "requestType", ",", "secure", ",", "user", ",", "password", ",", "endPoint", ",", "data", ",", "type", ")", ";", "}" ]
Generates the request based on the type of request, the end point, the data and type passed @param requestType type of request to be sent @param secure type of protocol @param user user to be used in request @param password password to be used in request @param endPoint end point to sent the request to @param data to be sent for PUT/POST requests @param type type of data to be sent (json|string) @param codeBase64 XXX @throws Exception exception
[ "Generates", "the", "request", "based", "on", "the", "type", "of", "request", "the", "end", "point", "the", "data", "and", "type", "passed" ]
train
https://github.com/Stratio/bdt/blob/55324d19e7497764ad3dd7139923e13eb9841d75/src/main/java/com/stratio/qa/specs/CommonG.java#L1086-L1089
ologolo/streamline-engine
src/org/daisy/streamline/engine/TaskRunner.java
TaskRunner.runTasks
public RunnerResults runTasks(FileSet input, BaseFolder output, String manifestFileName, List<InternalTask> tasks) throws IOException, TaskSystemException { """ Runs a list of tasks starting from the input file as input to the first task, the following tasks use the preceding result as input. The final result is written to the output. @param input the input file @param output the output file @param manifestFileName the file name of the manifest file @param tasks the list of tasks @return returns a list of runner results @throws IOException if there is an I/O error @throws TaskSystemException if there is a problem with the task system """ Progress progress = new Progress(); logger.info(name + " started on " + progress.getStart()); int i = 0; NumberFormat nf = NumberFormat.getPercentInstance(); TempFileWriter tempWriter =writeTempFiles ? Optional.ofNullable(tempFileWriter).orElseGet(()->new DefaultTempFileWriter.Builder().build()) : null; RunnerResults.Builder builder = new RunnerResults.Builder(); // I use this to pass the exception out of the lambda Variable<IOException> ex = new Variable<>(); Consumer<FileSet> outputConsumer = current->{ try { builder.fileSet(DefaultFileSet.copy(current, output, manifestFileName)); } catch (IOException e) { ex.setValue(e); } }; try (TaskRunnerCore2 itr = new TaskRunnerCore2(input, outputConsumer, tempWriter)) { for (InternalTask task : tasks) { builder.addResults(itr.runTask(task)); i++; ProgressEvent event = progress.updateProgress(i/(double)tasks.size()); logger.info(nf.format(event.getProgress()) + " done. ETC " + event.getETC()); progressListeners.forEach(v->v.accept(event)); } } catch (IOException | TaskSystemException | RuntimeException e) { //This is called after the resource (fj) is closed. //Since the temp file handler is closed the current state will be written to output. However, we do not want it. PathTools.deleteRecursive(output.getPath()); throw e; } if (ex.getValue()!=null) { throw ex.getValue(); } if (!keepTempFilesOnSuccess && tempWriter!=null) { // Process were successful, delete temp files tempWriter.deleteTempFiles(); } logger.info(name + " finished in " + Math.round(progress.timeSinceStart()/100d)/10d + " s"); return builder.build(); }
java
public RunnerResults runTasks(FileSet input, BaseFolder output, String manifestFileName, List<InternalTask> tasks) throws IOException, TaskSystemException { Progress progress = new Progress(); logger.info(name + " started on " + progress.getStart()); int i = 0; NumberFormat nf = NumberFormat.getPercentInstance(); TempFileWriter tempWriter =writeTempFiles ? Optional.ofNullable(tempFileWriter).orElseGet(()->new DefaultTempFileWriter.Builder().build()) : null; RunnerResults.Builder builder = new RunnerResults.Builder(); // I use this to pass the exception out of the lambda Variable<IOException> ex = new Variable<>(); Consumer<FileSet> outputConsumer = current->{ try { builder.fileSet(DefaultFileSet.copy(current, output, manifestFileName)); } catch (IOException e) { ex.setValue(e); } }; try (TaskRunnerCore2 itr = new TaskRunnerCore2(input, outputConsumer, tempWriter)) { for (InternalTask task : tasks) { builder.addResults(itr.runTask(task)); i++; ProgressEvent event = progress.updateProgress(i/(double)tasks.size()); logger.info(nf.format(event.getProgress()) + " done. ETC " + event.getETC()); progressListeners.forEach(v->v.accept(event)); } } catch (IOException | TaskSystemException | RuntimeException e) { //This is called after the resource (fj) is closed. //Since the temp file handler is closed the current state will be written to output. However, we do not want it. PathTools.deleteRecursive(output.getPath()); throw e; } if (ex.getValue()!=null) { throw ex.getValue(); } if (!keepTempFilesOnSuccess && tempWriter!=null) { // Process were successful, delete temp files tempWriter.deleteTempFiles(); } logger.info(name + " finished in " + Math.round(progress.timeSinceStart()/100d)/10d + " s"); return builder.build(); }
[ "public", "RunnerResults", "runTasks", "(", "FileSet", "input", ",", "BaseFolder", "output", ",", "String", "manifestFileName", ",", "List", "<", "InternalTask", ">", "tasks", ")", "throws", "IOException", ",", "TaskSystemException", "{", "Progress", "progress", "=", "new", "Progress", "(", ")", ";", "logger", ".", "info", "(", "name", "+", "\" started on \"", "+", "progress", ".", "getStart", "(", ")", ")", ";", "int", "i", "=", "0", ";", "NumberFormat", "nf", "=", "NumberFormat", ".", "getPercentInstance", "(", ")", ";", "TempFileWriter", "tempWriter", "=", "writeTempFiles", "?", "Optional", ".", "ofNullable", "(", "tempFileWriter", ")", ".", "orElseGet", "(", "(", ")", "->", "new", "DefaultTempFileWriter", ".", "Builder", "(", ")", ".", "build", "(", ")", ")", ":", "null", ";", "RunnerResults", ".", "Builder", "builder", "=", "new", "RunnerResults", ".", "Builder", "(", ")", ";", "// I use this to pass the exception out of the lambda", "Variable", "<", "IOException", ">", "ex", "=", "new", "Variable", "<>", "(", ")", ";", "Consumer", "<", "FileSet", ">", "outputConsumer", "=", "current", "->", "{", "try", "{", "builder", ".", "fileSet", "(", "DefaultFileSet", ".", "copy", "(", "current", ",", "output", ",", "manifestFileName", ")", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "ex", ".", "setValue", "(", "e", ")", ";", "}", "}", ";", "try", "(", "TaskRunnerCore2", "itr", "=", "new", "TaskRunnerCore2", "(", "input", ",", "outputConsumer", ",", "tempWriter", ")", ")", "{", "for", "(", "InternalTask", "task", ":", "tasks", ")", "{", "builder", ".", "addResults", "(", "itr", ".", "runTask", "(", "task", ")", ")", ";", "i", "++", ";", "ProgressEvent", "event", "=", "progress", ".", "updateProgress", "(", "i", "/", "(", "double", ")", "tasks", ".", "size", "(", ")", ")", ";", "logger", ".", "info", "(", "nf", ".", "format", "(", "event", ".", "getProgress", "(", ")", ")", "+", "\" done. ETC \"", "+", "event", ".", "getETC", "(", ")", ")", ";", "progressListeners", ".", "forEach", "(", "v", "->", "v", ".", "accept", "(", "event", ")", ")", ";", "}", "}", "catch", "(", "IOException", "|", "TaskSystemException", "|", "RuntimeException", "e", ")", "{", "//This is called after the resource (fj) is closed.", "//Since the temp file handler is closed the current state will be written to output. However, we do not want it.", "PathTools", ".", "deleteRecursive", "(", "output", ".", "getPath", "(", ")", ")", ";", "throw", "e", ";", "}", "if", "(", "ex", ".", "getValue", "(", ")", "!=", "null", ")", "{", "throw", "ex", ".", "getValue", "(", ")", ";", "}", "if", "(", "!", "keepTempFilesOnSuccess", "&&", "tempWriter", "!=", "null", ")", "{", "// Process were successful, delete temp files", "tempWriter", ".", "deleteTempFiles", "(", ")", ";", "}", "logger", ".", "info", "(", "name", "+", "\" finished in \"", "+", "Math", ".", "round", "(", "progress", ".", "timeSinceStart", "(", ")", "/", "100d", ")", "/", "10d", "+", "\" s\"", ")", ";", "return", "builder", ".", "build", "(", ")", ";", "}" ]
Runs a list of tasks starting from the input file as input to the first task, the following tasks use the preceding result as input. The final result is written to the output. @param input the input file @param output the output file @param manifestFileName the file name of the manifest file @param tasks the list of tasks @return returns a list of runner results @throws IOException if there is an I/O error @throws TaskSystemException if there is a problem with the task system
[ "Runs", "a", "list", "of", "tasks", "starting", "from", "the", "input", "file", "as", "input", "to", "the", "first", "task", "the", "following", "tasks", "use", "the", "preceding", "result", "as", "input", ".", "The", "final", "result", "is", "written", "to", "the", "output", "." ]
train
https://github.com/ologolo/streamline-engine/blob/04b7adc85d84d91dc5f0eaaa401d2738f9401b17/src/org/daisy/streamline/engine/TaskRunner.java#L204-L243
verhas/License3j
src/main/java/javax0/license3j/RevocableLicense.java
RevocableLicense.getRevocationURL
public URL getRevocationURL() throws MalformedURLException { """ Get the revocation URL of the license. This feature is stored in the license under the name {@code revocationUrl}. This URL may contain the string <code>${licenseId}</code> which is replaced by the actual license ID. Thus there is no need to wire into the revocation URL the license ID. <p> If there is no license id defined in the license then the place holder will be replaced using the fingerprint of the license. @return the revocation URL with the license id place holder filled in, or {@code null} if there is no revocation URL template defined in the license. @throws MalformedURLException when the revocation url is not well formatted """ final var revocationURLTemplate = license.get(REVOCATION_URL) == null ? null : license.get(REVOCATION_URL).getString(); final String revocationURL; if (revocationURLTemplate != null) { final var id = Optional.ofNullable(license.getLicenseId()).orElse(license.fingerprint()); if (id != null) { return new URL(revocationURLTemplate.replaceAll("\\$\\{licenseId}", id.toString())); } else { return new URL(revocationURLTemplate); } } else { return null; } }
java
public URL getRevocationURL() throws MalformedURLException { final var revocationURLTemplate = license.get(REVOCATION_URL) == null ? null : license.get(REVOCATION_URL).getString(); final String revocationURL; if (revocationURLTemplate != null) { final var id = Optional.ofNullable(license.getLicenseId()).orElse(license.fingerprint()); if (id != null) { return new URL(revocationURLTemplate.replaceAll("\\$\\{licenseId}", id.toString())); } else { return new URL(revocationURLTemplate); } } else { return null; } }
[ "public", "URL", "getRevocationURL", "(", ")", "throws", "MalformedURLException", "{", "final", "var", "revocationURLTemplate", "=", "license", ".", "get", "(", "REVOCATION_URL", ")", "==", "null", "?", "null", ":", "license", ".", "get", "(", "REVOCATION_URL", ")", ".", "getString", "(", ")", ";", "final", "String", "revocationURL", ";", "if", "(", "revocationURLTemplate", "!=", "null", ")", "{", "final", "var", "id", "=", "Optional", ".", "ofNullable", "(", "license", ".", "getLicenseId", "(", ")", ")", ".", "orElse", "(", "license", ".", "fingerprint", "(", ")", ")", ";", "if", "(", "id", "!=", "null", ")", "{", "return", "new", "URL", "(", "revocationURLTemplate", ".", "replaceAll", "(", "\"\\\\$\\\\{licenseId}\"", ",", "id", ".", "toString", "(", ")", ")", ")", ";", "}", "else", "{", "return", "new", "URL", "(", "revocationURLTemplate", ")", ";", "}", "}", "else", "{", "return", "null", ";", "}", "}" ]
Get the revocation URL of the license. This feature is stored in the license under the name {@code revocationUrl}. This URL may contain the string <code>${licenseId}</code> which is replaced by the actual license ID. Thus there is no need to wire into the revocation URL the license ID. <p> If there is no license id defined in the license then the place holder will be replaced using the fingerprint of the license. @return the revocation URL with the license id place holder filled in, or {@code null} if there is no revocation URL template defined in the license. @throws MalformedURLException when the revocation url is not well formatted
[ "Get", "the", "revocation", "URL", "of", "the", "license", ".", "This", "feature", "is", "stored", "in", "the", "license", "under", "the", "name", "{", "@code", "revocationUrl", "}", ".", "This", "URL", "may", "contain", "the", "string", "<code", ">", "$", "{", "licenseId", "}", "<", "/", "code", ">", "which", "is", "replaced", "by", "the", "actual", "license", "ID", ".", "Thus", "there", "is", "no", "need", "to", "wire", "into", "the", "revocation", "URL", "the", "license", "ID", ".", "<p", ">", "If", "there", "is", "no", "license", "id", "defined", "in", "the", "license", "then", "the", "place", "holder", "will", "be", "replaced", "using", "the", "fingerprint", "of", "the", "license", "." ]
train
https://github.com/verhas/License3j/blob/f44c6e81b3eb59ab591cc757792749d3556b4afb/src/main/java/javax0/license3j/RevocableLicense.java#L38-L51
apache/groovy
src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java
InvokerHelper.setPropertySafe2
public static void setPropertySafe2(Object newValue, Object object, String property) { """ This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order. """ if (object != null) { setProperty2(newValue, object, property); } }
java
public static void setPropertySafe2(Object newValue, Object object, String property) { if (object != null) { setProperty2(newValue, object, property); } }
[ "public", "static", "void", "setPropertySafe2", "(", "Object", "newValue", ",", "Object", "object", ",", "String", "property", ")", "{", "if", "(", "object", "!=", "null", ")", "{", "setProperty2", "(", "newValue", ",", "object", ",", "property", ")", ";", "}", "}" ]
This is so we don't have to reorder the stack when we call this method. At some point a better name might be in order.
[ "This", "is", "so", "we", "don", "t", "have", "to", "reorder", "the", "stack", "when", "we", "call", "this", "method", ".", "At", "some", "point", "a", "better", "name", "might", "be", "in", "order", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/InvokerHelper.java#L249-L253
apache/incubator-gobblin
gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java
Partitioner.getHighWatermark
@VisibleForTesting protected long getHighWatermark(ExtractType extractType, WatermarkType watermarkType) { """ Get high water mark @param extractType Extract type @param watermarkType Watermark type @return high water mark in {@link Partitioner#WATERMARKTIMEFORMAT} """ LOG.debug("Getting high watermark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; if (this.isWatermarkOverride()) { highWatermark = this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0); if (highWatermark == 0) { highWatermark = Long.parseLong(Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone)); } else { // User specifies SOURCE_QUERYBASED_END_VALUE hasUserSpecifiedHighWatermark = true; } LOG.info("Overriding high water mark with the given end value:" + highWatermark); } else { if (isSnapshot(extractType)) { highWatermark = this.getSnapshotHighWatermark(watermarkType); } else { highWatermark = this.getAppendHighWatermark(extractType); } } return (highWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : highWatermark); }
java
@VisibleForTesting protected long getHighWatermark(ExtractType extractType, WatermarkType watermarkType) { LOG.debug("Getting high watermark"); String timeZone = this.state.getProp(ConfigurationKeys.SOURCE_TIMEZONE); long highWatermark = ConfigurationKeys.DEFAULT_WATERMARK_VALUE; if (this.isWatermarkOverride()) { highWatermark = this.state.getPropAsLong(ConfigurationKeys.SOURCE_QUERYBASED_END_VALUE, 0); if (highWatermark == 0) { highWatermark = Long.parseLong(Utils.dateTimeToString(getCurrentTime(timeZone), WATERMARKTIMEFORMAT, timeZone)); } else { // User specifies SOURCE_QUERYBASED_END_VALUE hasUserSpecifiedHighWatermark = true; } LOG.info("Overriding high water mark with the given end value:" + highWatermark); } else { if (isSnapshot(extractType)) { highWatermark = this.getSnapshotHighWatermark(watermarkType); } else { highWatermark = this.getAppendHighWatermark(extractType); } } return (highWatermark == 0 ? ConfigurationKeys.DEFAULT_WATERMARK_VALUE : highWatermark); }
[ "@", "VisibleForTesting", "protected", "long", "getHighWatermark", "(", "ExtractType", "extractType", ",", "WatermarkType", "watermarkType", ")", "{", "LOG", ".", "debug", "(", "\"Getting high watermark\"", ")", ";", "String", "timeZone", "=", "this", ".", "state", ".", "getProp", "(", "ConfigurationKeys", ".", "SOURCE_TIMEZONE", ")", ";", "long", "highWatermark", "=", "ConfigurationKeys", ".", "DEFAULT_WATERMARK_VALUE", ";", "if", "(", "this", ".", "isWatermarkOverride", "(", ")", ")", "{", "highWatermark", "=", "this", ".", "state", ".", "getPropAsLong", "(", "ConfigurationKeys", ".", "SOURCE_QUERYBASED_END_VALUE", ",", "0", ")", ";", "if", "(", "highWatermark", "==", "0", ")", "{", "highWatermark", "=", "Long", ".", "parseLong", "(", "Utils", ".", "dateTimeToString", "(", "getCurrentTime", "(", "timeZone", ")", ",", "WATERMARKTIMEFORMAT", ",", "timeZone", ")", ")", ";", "}", "else", "{", "// User specifies SOURCE_QUERYBASED_END_VALUE", "hasUserSpecifiedHighWatermark", "=", "true", ";", "}", "LOG", ".", "info", "(", "\"Overriding high water mark with the given end value:\"", "+", "highWatermark", ")", ";", "}", "else", "{", "if", "(", "isSnapshot", "(", "extractType", ")", ")", "{", "highWatermark", "=", "this", ".", "getSnapshotHighWatermark", "(", "watermarkType", ")", ";", "}", "else", "{", "highWatermark", "=", "this", ".", "getAppendHighWatermark", "(", "extractType", ")", ";", "}", "}", "return", "(", "highWatermark", "==", "0", "?", "ConfigurationKeys", ".", "DEFAULT_WATERMARK_VALUE", ":", "highWatermark", ")", ";", "}" ]
Get high water mark @param extractType Extract type @param watermarkType Watermark type @return high water mark in {@link Partitioner#WATERMARKTIMEFORMAT}
[ "Get", "high", "water", "mark" ]
train
https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-core/src/main/java/org/apache/gobblin/source/extractor/partition/Partitioner.java#L422-L444
RestComm/sip-servlets
sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionKey.java
SipSessionKey.setToTag
public void setToTag(String toTag, boolean recomputeSessionId) { """ Sets the to tag on the key when we receive a response. We recompute the session id only for derived session otherwise the id will change when the a request is received or sent and the response is sent back or received which should not happen See TCK test SipSessionListenerTest.testSessionDestroyed001 @param toTag the toTag to set @param recomputeSessionId check if the sessionid need to be recomputed """ this.toTag = toTag; if(toTag != null && recomputeSessionId) { // Issue 2365 : to tag needed for getApplicationSession().getSipSession(<sessionId>) to return forked session and not the parent one computeToString(); } }
java
public void setToTag(String toTag, boolean recomputeSessionId) { this.toTag = toTag; if(toTag != null && recomputeSessionId) { // Issue 2365 : to tag needed for getApplicationSession().getSipSession(<sessionId>) to return forked session and not the parent one computeToString(); } }
[ "public", "void", "setToTag", "(", "String", "toTag", ",", "boolean", "recomputeSessionId", ")", "{", "this", ".", "toTag", "=", "toTag", ";", "if", "(", "toTag", "!=", "null", "&&", "recomputeSessionId", ")", "{", "// Issue 2365 : to tag needed for getApplicationSession().getSipSession(<sessionId>) to return forked session and not the parent one\r", "computeToString", "(", ")", ";", "}", "}" ]
Sets the to tag on the key when we receive a response. We recompute the session id only for derived session otherwise the id will change when the a request is received or sent and the response is sent back or received which should not happen See TCK test SipSessionListenerTest.testSessionDestroyed001 @param toTag the toTag to set @param recomputeSessionId check if the sessionid need to be recomputed
[ "Sets", "the", "to", "tag", "on", "the", "key", "when", "we", "receive", "a", "response", ".", "We", "recompute", "the", "session", "id", "only", "for", "derived", "session", "otherwise", "the", "id", "will", "change", "when", "the", "a", "request", "is", "received", "or", "sent", "and", "the", "response", "is", "sent", "back", "or", "received", "which", "should", "not", "happen", "See", "TCK", "test", "SipSessionListenerTest", ".", "testSessionDestroyed001" ]
train
https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SipSessionKey.java#L163-L169
groupby/api-java
src/main/java/com/groupbyinc/api/Query.java
Query.addValueRefinement
public Query addValueRefinement(String navigationName, String value, boolean exclude) { """ <code> Add a value refinement. Takes a refinement name, a value, and whether or not to exclude this refinement. </code> @param navigationName The name of the navigation @param value The refinement value @param exclude True if the results should exclude this value refinement, false otherwise """ return addRefinement(navigationName, new RefinementValue().setValue(value).setExclude(exclude)); }
java
public Query addValueRefinement(String navigationName, String value, boolean exclude) { return addRefinement(navigationName, new RefinementValue().setValue(value).setExclude(exclude)); }
[ "public", "Query", "addValueRefinement", "(", "String", "navigationName", ",", "String", "value", ",", "boolean", "exclude", ")", "{", "return", "addRefinement", "(", "navigationName", ",", "new", "RefinementValue", "(", ")", ".", "setValue", "(", "value", ")", ".", "setExclude", "(", "exclude", ")", ")", ";", "}" ]
<code> Add a value refinement. Takes a refinement name, a value, and whether or not to exclude this refinement. </code> @param navigationName The name of the navigation @param value The refinement value @param exclude True if the results should exclude this value refinement, false otherwise
[ "<code", ">", "Add", "a", "value", "refinement", ".", "Takes", "a", "refinement", "name", "a", "value", "and", "whether", "or", "not", "to", "exclude", "this", "refinement", ".", "<", "/", "code", ">" ]
train
https://github.com/groupby/api-java/blob/257c4ed0777221e5e4ade3b29b9921300fac4e2e/src/main/java/com/groupbyinc/api/Query.java#L787-L789
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/util/InvocationUtil.java
InvocationUtil.executeLocallyWithRetry
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) { """ Constructs a local execution with retry logic. The operation must not have an {@link OperationResponseHandler}, it must return a response and it must not validate the target. @return the local execution @throws IllegalArgumentException if the operation has a response handler set, if it does not return a response or if it validates the operation target @see Operation#returnsResponse() @see Operation#getOperationResponseHandler() @see Operation#validatesTarget() """ if (operation.getOperationResponseHandler() != null) { throw new IllegalArgumentException("Operation must not have a response handler set"); } if (!operation.returnsResponse()) { throw new IllegalArgumentException("Operation must return a response"); } if (operation.validatesTarget()) { throw new IllegalArgumentException("Operation must not validate the target"); } final LocalRetryableExecution execution = new LocalRetryableExecution(nodeEngine, operation); execution.run(); return execution; }
java
public static LocalRetryableExecution executeLocallyWithRetry(NodeEngine nodeEngine, Operation operation) { if (operation.getOperationResponseHandler() != null) { throw new IllegalArgumentException("Operation must not have a response handler set"); } if (!operation.returnsResponse()) { throw new IllegalArgumentException("Operation must return a response"); } if (operation.validatesTarget()) { throw new IllegalArgumentException("Operation must not validate the target"); } final LocalRetryableExecution execution = new LocalRetryableExecution(nodeEngine, operation); execution.run(); return execution; }
[ "public", "static", "LocalRetryableExecution", "executeLocallyWithRetry", "(", "NodeEngine", "nodeEngine", ",", "Operation", "operation", ")", "{", "if", "(", "operation", ".", "getOperationResponseHandler", "(", ")", "!=", "null", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Operation must not have a response handler set\"", ")", ";", "}", "if", "(", "!", "operation", ".", "returnsResponse", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Operation must return a response\"", ")", ";", "}", "if", "(", "operation", ".", "validatesTarget", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Operation must not validate the target\"", ")", ";", "}", "final", "LocalRetryableExecution", "execution", "=", "new", "LocalRetryableExecution", "(", "nodeEngine", ",", "operation", ")", ";", "execution", ".", "run", "(", ")", ";", "return", "execution", ";", "}" ]
Constructs a local execution with retry logic. The operation must not have an {@link OperationResponseHandler}, it must return a response and it must not validate the target. @return the local execution @throws IllegalArgumentException if the operation has a response handler set, if it does not return a response or if it validates the operation target @see Operation#returnsResponse() @see Operation#getOperationResponseHandler() @see Operation#validatesTarget()
[ "Constructs", "a", "local", "execution", "with", "retry", "logic", ".", "The", "operation", "must", "not", "have", "an", "{", "@link", "OperationResponseHandler", "}", "it", "must", "return", "a", "response", "and", "it", "must", "not", "validate", "the", "target", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/util/InvocationUtil.java#L102-L115
b3log/latke
latke-core/src/main/java/org/json/JSONObject.java
JSONObject.optInt
public int optInt(String key, int defaultValue) { """ Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value. """ final Number val = this.optNumber(key, null); if (val == null) { return defaultValue; } return val.intValue(); }
java
public int optInt(String key, int defaultValue) { final Number val = this.optNumber(key, null); if (val == null) { return defaultValue; } return val.intValue(); }
[ "public", "int", "optInt", "(", "String", "key", ",", "int", "defaultValue", ")", "{", "final", "Number", "val", "=", "this", ".", "optNumber", "(", "key", ",", "null", ")", ";", "if", "(", "val", "==", "null", ")", "{", "return", "defaultValue", ";", "}", "return", "val", ".", "intValue", "(", ")", ";", "}" ]
Get an optional int value associated with a key, or the default if there is no such key or if the value is not a number. If the value is a string, an attempt will be made to evaluate it as a number. @param key A key string. @param defaultValue The default. @return An object which is the value.
[ "Get", "an", "optional", "int", "value", "associated", "with", "a", "key", "or", "the", "default", "if", "there", "is", "no", "such", "key", "or", "if", "the", "value", "is", "not", "a", "number", ".", "If", "the", "value", "is", "a", "string", "an", "attempt", "will", "be", "made", "to", "evaluate", "it", "as", "a", "number", "." ]
train
https://github.com/b3log/latke/blob/f7e08a47eeecea5f7c94006382c24f353585de33/latke-core/src/main/java/org/json/JSONObject.java#L1305-L1311
Azure/azure-sdk-for-java
network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java
VirtualNetworkGatewaysInner.getBgpPeerStatusAsync
public Observable<BgpPeerStatusListResultInner> getBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) { """ The GetBgpPeerStatus operation retrieves the status of all BGP peers. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param peer The IP address of the peer to retrieve the status of. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request """ return getBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() { @Override public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) { return response.body(); } }); }
java
public Observable<BgpPeerStatusListResultInner> getBgpPeerStatusAsync(String resourceGroupName, String virtualNetworkGatewayName, String peer) { return getBgpPeerStatusWithServiceResponseAsync(resourceGroupName, virtualNetworkGatewayName, peer).map(new Func1<ServiceResponse<BgpPeerStatusListResultInner>, BgpPeerStatusListResultInner>() { @Override public BgpPeerStatusListResultInner call(ServiceResponse<BgpPeerStatusListResultInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "BgpPeerStatusListResultInner", ">", "getBgpPeerStatusAsync", "(", "String", "resourceGroupName", ",", "String", "virtualNetworkGatewayName", ",", "String", "peer", ")", "{", "return", "getBgpPeerStatusWithServiceResponseAsync", "(", "resourceGroupName", ",", "virtualNetworkGatewayName", ",", "peer", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "BgpPeerStatusListResultInner", ">", ",", "BgpPeerStatusListResultInner", ">", "(", ")", "{", "@", "Override", "public", "BgpPeerStatusListResultInner", "call", "(", "ServiceResponse", "<", "BgpPeerStatusListResultInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
The GetBgpPeerStatus operation retrieves the status of all BGP peers. @param resourceGroupName The name of the resource group. @param virtualNetworkGatewayName The name of the virtual network gateway. @param peer The IP address of the peer to retrieve the status of. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "The", "GetBgpPeerStatus", "operation", "retrieves", "the", "status", "of", "all", "BGP", "peers", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/VirtualNetworkGatewaysInner.java#L2046-L2053
deeplearning4j/deeplearning4j
deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java
WordVectorSerializer.fromPair
public static Word2Vec fromPair(Pair<InMemoryLookupTable, VocabCache> pair) { """ Load word vectors from the given pair @param pair the given pair @return a read only word vectors impl based on the given lookup table and vocab """ Word2Vec vectors = new Word2Vec(); vectors.setLookupTable(pair.getFirst()); vectors.setVocab(pair.getSecond()); vectors.setModelUtils(new BasicModelUtils()); return vectors; }
java
public static Word2Vec fromPair(Pair<InMemoryLookupTable, VocabCache> pair) { Word2Vec vectors = new Word2Vec(); vectors.setLookupTable(pair.getFirst()); vectors.setVocab(pair.getSecond()); vectors.setModelUtils(new BasicModelUtils()); return vectors; }
[ "public", "static", "Word2Vec", "fromPair", "(", "Pair", "<", "InMemoryLookupTable", ",", "VocabCache", ">", "pair", ")", "{", "Word2Vec", "vectors", "=", "new", "Word2Vec", "(", ")", ";", "vectors", ".", "setLookupTable", "(", "pair", ".", "getFirst", "(", ")", ")", ";", "vectors", ".", "setVocab", "(", "pair", ".", "getSecond", "(", ")", ")", ";", "vectors", ".", "setModelUtils", "(", "new", "BasicModelUtils", "(", ")", ")", ";", "return", "vectors", ";", "}" ]
Load word vectors from the given pair @param pair the given pair @return a read only word vectors impl based on the given lookup table and vocab
[ "Load", "word", "vectors", "from", "the", "given", "pair" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp/src/main/java/org/deeplearning4j/models/embeddings/loader/WordVectorSerializer.java#L1582-L1588
craterdog/java-security-framework
java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java
CertificateManager.saveKeyStore
public final void saveKeyStore(OutputStream output, KeyStore keyStore, char[] password) throws IOException { """ This method saves a PKCS12 format key store out to an output stream. @param output The output stream to be written to. @param keyStore The PKCS12 format key store. @param password The password that should be used to encrypt the file. @throws java.io.IOException Unable to save the key store to the specified output stream. """ logger.entry(); try { keyStore.store(output, password); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to save a keystore.", e); logger.error(exception.toString()); throw exception; } logger.exit(); }
java
public final void saveKeyStore(OutputStream output, KeyStore keyStore, char[] password) throws IOException { logger.entry(); try { keyStore.store(output, password); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException e) { RuntimeException exception = new RuntimeException("An unexpected exception occurred while attempting to save a keystore.", e); logger.error(exception.toString()); throw exception; } logger.exit(); }
[ "public", "final", "void", "saveKeyStore", "(", "OutputStream", "output", ",", "KeyStore", "keyStore", ",", "char", "[", "]", "password", ")", "throws", "IOException", "{", "logger", ".", "entry", "(", ")", ";", "try", "{", "keyStore", ".", "store", "(", "output", ",", "password", ")", ";", "}", "catch", "(", "KeyStoreException", "|", "NoSuchAlgorithmException", "|", "CertificateException", "e", ")", "{", "RuntimeException", "exception", "=", "new", "RuntimeException", "(", "\"An unexpected exception occurred while attempting to save a keystore.\"", ",", "e", ")", ";", "logger", ".", "error", "(", "exception", ".", "toString", "(", ")", ")", ";", "throw", "exception", ";", "}", "logger", ".", "exit", "(", ")", ";", "}" ]
This method saves a PKCS12 format key store out to an output stream. @param output The output stream to be written to. @param keyStore The PKCS12 format key store. @param password The password that should be used to encrypt the file. @throws java.io.IOException Unable to save the key store to the specified output stream.
[ "This", "method", "saves", "a", "PKCS12", "format", "key", "store", "out", "to", "an", "output", "stream", "." ]
train
https://github.com/craterdog/java-security-framework/blob/a5634c19812d473b608bc11060f5cbb4b4b0b5da/java-certificate-management-api/src/main/java/craterdog/security/CertificateManager.java#L44-L54
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/TypePoolGroupNameMap.java
TypePoolGroupNameMap.containsKey
public boolean containsKey(ResourceType type, String poolGroupName) { """ Is the value set with the appropriate keys? @param type Resource type @param poolGroup Name of pool group @return True if this map contains a mapping for the specified key, false otherwise """ Map<String, V> poolGroupNameMap = typePoolGroupNameMap.get(type); if (poolGroupNameMap == null) { return false; } return poolGroupNameMap.containsKey(poolGroupName); }
java
public boolean containsKey(ResourceType type, String poolGroupName) { Map<String, V> poolGroupNameMap = typePoolGroupNameMap.get(type); if (poolGroupNameMap == null) { return false; } return poolGroupNameMap.containsKey(poolGroupName); }
[ "public", "boolean", "containsKey", "(", "ResourceType", "type", ",", "String", "poolGroupName", ")", "{", "Map", "<", "String", ",", "V", ">", "poolGroupNameMap", "=", "typePoolGroupNameMap", ".", "get", "(", "type", ")", ";", "if", "(", "poolGroupNameMap", "==", "null", ")", "{", "return", "false", ";", "}", "return", "poolGroupNameMap", ".", "containsKey", "(", "poolGroupName", ")", ";", "}" ]
Is the value set with the appropriate keys? @param type Resource type @param poolGroup Name of pool group @return True if this map contains a mapping for the specified key, false otherwise
[ "Is", "the", "value", "set", "with", "the", "appropriate", "keys?" ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/TypePoolGroupNameMap.java#L77-L83
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Stream.java
Stream.takeWhileIndexed
@NotNull public Stream<T> takeWhileIndexed(@NotNull IndexedPredicate<? super T> predicate) { """ Takes elements while the {@code IndexedPredicate} returns {@code true}. <p>This is an intermediate operation. <p>Example: <pre> predicate: (index, value) -&gt; (index + value) &lt; 5 stream: [1, 2, 3, 4, -5, -6, -7] index: [0, 1, 2, 3, 4, 5, 6] sum: [1, 3, 5, 7, -1, -1, -1] result: [1, 2] </pre> @param predicate the {@code IndexedPredicate} used to take elements @return the new stream @since 1.1.6 """ return takeWhileIndexed(0, 1, predicate); }
java
@NotNull public Stream<T> takeWhileIndexed(@NotNull IndexedPredicate<? super T> predicate) { return takeWhileIndexed(0, 1, predicate); }
[ "@", "NotNull", "public", "Stream", "<", "T", ">", "takeWhileIndexed", "(", "@", "NotNull", "IndexedPredicate", "<", "?", "super", "T", ">", "predicate", ")", "{", "return", "takeWhileIndexed", "(", "0", ",", "1", ",", "predicate", ")", ";", "}" ]
Takes elements while the {@code IndexedPredicate} returns {@code true}. <p>This is an intermediate operation. <p>Example: <pre> predicate: (index, value) -&gt; (index + value) &lt; 5 stream: [1, 2, 3, 4, -5, -6, -7] index: [0, 1, 2, 3, 4, 5, 6] sum: [1, 3, 5, 7, -1, -1, -1] result: [1, 2] </pre> @param predicate the {@code IndexedPredicate} used to take elements @return the new stream @since 1.1.6
[ "Takes", "elements", "while", "the", "{", "@code", "IndexedPredicate", "}", "returns", "{", "@code", "true", "}", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Stream.java#L1323-L1326
transloadit/java-sdk
src/main/java/com/transloadit/sdk/Assembly.java
Assembly.addFile
public void addFile(InputStream inputStream, String name) { """ Adds a file to your assembly. If the field name specified already exists, it will override the content of the existing name. @param inputStream {@link InputStream} the file to be uploaded. @param name {@link String} the field name of the file when submitted Transloadit. """ fileStreams.put(name, inputStream); // remove duplicate key if (files.containsKey(name)) { files.remove(name); } }
java
public void addFile(InputStream inputStream, String name) { fileStreams.put(name, inputStream); // remove duplicate key if (files.containsKey(name)) { files.remove(name); } }
[ "public", "void", "addFile", "(", "InputStream", "inputStream", ",", "String", "name", ")", "{", "fileStreams", ".", "put", "(", "name", ",", "inputStream", ")", ";", "// remove duplicate key", "if", "(", "files", ".", "containsKey", "(", "name", ")", ")", "{", "files", ".", "remove", "(", "name", ")", ";", "}", "}" ]
Adds a file to your assembly. If the field name specified already exists, it will override the content of the existing name. @param inputStream {@link InputStream} the file to be uploaded. @param name {@link String} the field name of the file when submitted Transloadit.
[ "Adds", "a", "file", "to", "your", "assembly", ".", "If", "the", "field", "name", "specified", "already", "exists", "it", "will", "override", "the", "content", "of", "the", "existing", "name", "." ]
train
https://github.com/transloadit/java-sdk/blob/9326c540a66f77b3d907d0b2c05bff1145ca14f7/src/main/java/com/transloadit/sdk/Assembly.java#L83-L90
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java
DownloadChemCompProvider.writeID
private void writeID(String contents, String currentID) throws IOException { """ Output chemical contents to a file @param contents File contents @param currentID Chemical ID, used to determine the filename @throws IOException """ String localName = getLocalFileName(currentID); try ( PrintWriter pw = new PrintWriter(new GZIPOutputStream(new FileOutputStream(localName))) ) { pw.print(contents); pw.flush(); } }
java
private void writeID(String contents, String currentID) throws IOException{ String localName = getLocalFileName(currentID); try ( PrintWriter pw = new PrintWriter(new GZIPOutputStream(new FileOutputStream(localName))) ) { pw.print(contents); pw.flush(); } }
[ "private", "void", "writeID", "(", "String", "contents", ",", "String", "currentID", ")", "throws", "IOException", "{", "String", "localName", "=", "getLocalFileName", "(", "currentID", ")", ";", "try", "(", "PrintWriter", "pw", "=", "new", "PrintWriter", "(", "new", "GZIPOutputStream", "(", "new", "FileOutputStream", "(", "localName", ")", ")", ")", ")", "{", "pw", ".", "print", "(", "contents", ")", ";", "pw", ".", "flush", "(", ")", ";", "}", "}" ]
Output chemical contents to a file @param contents File contents @param currentID Chemical ID, used to determine the filename @throws IOException
[ "Output", "chemical", "contents", "to", "a", "file" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/io/mmcif/DownloadChemCompProvider.java#L227-L236
liyiorg/weixin-popular
src/main/java/weixin/popular/api/PayMchAPI.java
PayMchAPI.payitilReport
public static MchBaseResult payitilReport(Report report,String key) { """ 交易保障 <br> 测速上报 @param report report @param key key @return MchBaseResult """ Map<String,String> map = MapUtil.objectToMap(report); String sign = SignatureUtil.generateSign(map,report.getSign_type(),key); report.setSign(sign); String shorturlXML = XMLConverUtil.convertToXML(report); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/payitil/report") .setEntity(new StringEntity(shorturlXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeXmlResult(httpUriRequest,MchBaseResult.class); }
java
public static MchBaseResult payitilReport(Report report,String key){ Map<String,String> map = MapUtil.objectToMap(report); String sign = SignatureUtil.generateSign(map,report.getSign_type(),key); report.setSign(sign); String shorturlXML = XMLConverUtil.convertToXML(report); HttpUriRequest httpUriRequest = RequestBuilder.post() .setHeader(xmlHeader) .setUri(baseURI()+ "/payitil/report") .setEntity(new StringEntity(shorturlXML,Charset.forName("utf-8"))) .build(); return LocalHttpClient.executeXmlResult(httpUriRequest,MchBaseResult.class); }
[ "public", "static", "MchBaseResult", "payitilReport", "(", "Report", "report", ",", "String", "key", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "MapUtil", ".", "objectToMap", "(", "report", ")", ";", "String", "sign", "=", "SignatureUtil", ".", "generateSign", "(", "map", ",", "report", ".", "getSign_type", "(", ")", ",", "key", ")", ";", "report", ".", "setSign", "(", "sign", ")", ";", "String", "shorturlXML", "=", "XMLConverUtil", ".", "convertToXML", "(", "report", ")", ";", "HttpUriRequest", "httpUriRequest", "=", "RequestBuilder", ".", "post", "(", ")", ".", "setHeader", "(", "xmlHeader", ")", ".", "setUri", "(", "baseURI", "(", ")", "+", "\"/payitil/report\"", ")", ".", "setEntity", "(", "new", "StringEntity", "(", "shorturlXML", ",", "Charset", ".", "forName", "(", "\"utf-8\"", ")", ")", ")", ".", "build", "(", ")", ";", "return", "LocalHttpClient", ".", "executeXmlResult", "(", "httpUriRequest", ",", "MchBaseResult", ".", "class", ")", ";", "}" ]
交易保障 <br> 测速上报 @param report report @param key key @return MchBaseResult
[ "交易保障", "<br", ">", "测速上报" ]
train
https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/PayMchAPI.java#L413-L424
facebookarchive/hadoop-20
src/contrib/corona/src/java/org/apache/hadoop/corona/Scheduler.java
Scheduler.addSession
public void addSession(String id, Session session) { """ Add a session for scheduling. @param id Identifies the session @param session Actual session to be scheduled """ for (SchedulerForType scheduleThread : schedulersForTypes.values()) { scheduleThread.addSession(id, session); } }
java
public void addSession(String id, Session session) { for (SchedulerForType scheduleThread : schedulersForTypes.values()) { scheduleThread.addSession(id, session); } }
[ "public", "void", "addSession", "(", "String", "id", ",", "Session", "session", ")", "{", "for", "(", "SchedulerForType", "scheduleThread", ":", "schedulersForTypes", ".", "values", "(", ")", ")", "{", "scheduleThread", ".", "addSession", "(", "id", ",", "session", ")", ";", "}", "}" ]
Add a session for scheduling. @param id Identifies the session @param session Actual session to be scheduled
[ "Add", "a", "session", "for", "scheduling", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/contrib/corona/src/java/org/apache/hadoop/corona/Scheduler.java#L124-L128
looly/hutool
hutool-http/src/main/java/cn/hutool/http/webservice/SoapClient.java
SoapClient.setParam
public SoapClient setParam(String name, Object value, boolean useMethodPrefix) { """ 设置方法参数 @param name 参数名 @param value 参数值,可以是字符串或Map或{@link SOAPElement} @param useMethodPrefix 是否使用方法的命名空间前缀 @return this """ setParam(this.methodEle, name, value, useMethodPrefix ? this.methodEle.getPrefix() : null); return this; }
java
public SoapClient setParam(String name, Object value, boolean useMethodPrefix) { setParam(this.methodEle, name, value, useMethodPrefix ? this.methodEle.getPrefix() : null); return this; }
[ "public", "SoapClient", "setParam", "(", "String", "name", ",", "Object", "value", ",", "boolean", "useMethodPrefix", ")", "{", "setParam", "(", "this", ".", "methodEle", ",", "name", ",", "value", ",", "useMethodPrefix", "?", "this", ".", "methodEle", ".", "getPrefix", "(", ")", ":", "null", ")", ";", "return", "this", ";", "}" ]
设置方法参数 @param name 参数名 @param value 参数值,可以是字符串或Map或{@link SOAPElement} @param useMethodPrefix 是否使用方法的命名空间前缀 @return this
[ "设置方法参数" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-http/src/main/java/cn/hutool/http/webservice/SoapClient.java#L314-L317
biojava/biojava
biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java
Equals.classEqual
public static boolean classEqual(Object one, Object two) { """ This method should be called before beginning any equals methods. In order to return true the method: <ol> <li>The two given objects are the same instance using ==. This also means if both Objects are null then this method will return true (well technically they are equal)</li> <li>Tests that neither object is null</li> <li>The the two classes from the objects are equal using ==</li> </ol> The boilerplate using this method then becomes: <pre> boolean equals = false; if (EqualsHelper.classEqual(this, obj)) { TargetClass casted = (TargetClass) obj; equals = (EqualsHelper.equal(this.getId(), casted.getId()) &amp;&amp; EqualsHelper .equal(this.getName(), casted.getName())); } return equals; </pre> @param one The first object to test @param two The second object to test @return A boolean indicating if the logic agrees that these two objects are equal at the class level """ return one == two || !(one == null || two == null) && one.getClass() == two.getClass(); }
java
public static boolean classEqual(Object one, Object two) { return one == two || !(one == null || two == null) && one.getClass() == two.getClass(); }
[ "public", "static", "boolean", "classEqual", "(", "Object", "one", ",", "Object", "two", ")", "{", "return", "one", "==", "two", "||", "!", "(", "one", "==", "null", "||", "two", "==", "null", ")", "&&", "one", ".", "getClass", "(", ")", "==", "two", ".", "getClass", "(", ")", ";", "}" ]
This method should be called before beginning any equals methods. In order to return true the method: <ol> <li>The two given objects are the same instance using ==. This also means if both Objects are null then this method will return true (well technically they are equal)</li> <li>Tests that neither object is null</li> <li>The the two classes from the objects are equal using ==</li> </ol> The boilerplate using this method then becomes: <pre> boolean equals = false; if (EqualsHelper.classEqual(this, obj)) { TargetClass casted = (TargetClass) obj; equals = (EqualsHelper.equal(this.getId(), casted.getId()) &amp;&amp; EqualsHelper .equal(this.getName(), casted.getName())); } return equals; </pre> @param one The first object to test @param two The second object to test @return A boolean indicating if the logic agrees that these two objects are equal at the class level
[ "This", "method", "should", "be", "called", "before", "beginning", "any", "equals", "methods", ".", "In", "order", "to", "return", "true", "the", "method", ":" ]
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-core/src/main/java/org/biojava/nbio/core/util/Equals.java#L84-L86
Azure/azure-sdk-for-java
batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/ClustersInner.java
ClustersInner.listByWorkspaceAsync
public Observable<Page<ClusterInner>> listByWorkspaceAsync(final String resourceGroupName, final String workspaceName, final ClustersListByWorkspaceOptions clustersListByWorkspaceOptions) { """ Gets information about Clusters associated with the given Workspace. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param clustersListByWorkspaceOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ClusterInner&gt; object """ return listByWorkspaceWithServiceResponseAsync(resourceGroupName, workspaceName, clustersListByWorkspaceOptions) .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); }
java
public Observable<Page<ClusterInner>> listByWorkspaceAsync(final String resourceGroupName, final String workspaceName, final ClustersListByWorkspaceOptions clustersListByWorkspaceOptions) { return listByWorkspaceWithServiceResponseAsync(resourceGroupName, workspaceName, clustersListByWorkspaceOptions) .map(new Func1<ServiceResponse<Page<ClusterInner>>, Page<ClusterInner>>() { @Override public Page<ClusterInner> call(ServiceResponse<Page<ClusterInner>> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Page", "<", "ClusterInner", ">", ">", "listByWorkspaceAsync", "(", "final", "String", "resourceGroupName", ",", "final", "String", "workspaceName", ",", "final", "ClustersListByWorkspaceOptions", "clustersListByWorkspaceOptions", ")", "{", "return", "listByWorkspaceWithServiceResponseAsync", "(", "resourceGroupName", ",", "workspaceName", ",", "clustersListByWorkspaceOptions", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "Page", "<", "ClusterInner", ">", ">", ",", "Page", "<", "ClusterInner", ">", ">", "(", ")", "{", "@", "Override", "public", "Page", "<", "ClusterInner", ">", "call", "(", "ServiceResponse", "<", "Page", "<", "ClusterInner", ">", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Gets information about Clusters associated with the given Workspace. @param resourceGroupName Name of the resource group to which the resource belongs. @param workspaceName The name of the workspace. Workspace names can only contain a combination of alphanumeric characters along with dash (-) and underscore (_). The name must be from 1 through 64 characters long. @param clustersListByWorkspaceOptions Additional parameters for the operation @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ClusterInner&gt; object
[ "Gets", "information", "about", "Clusters", "associated", "with", "the", "given", "Workspace", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batchai/resource-manager/v2018_05_01/src/main/java/com/microsoft/azure/management/batchai/v2018_05_01/implementation/ClustersInner.java#L1434-L1442
exoplatform/jcr
exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java
PropPatchCommand.propPatch
public Response propPatch(Session session, String path, HierarchicalProperty body, List<String> tokens, String baseURI) { """ Webdav Proppatch method method implementation. @param session current session @param path resource path @param body request body @param tokens tokens @param baseURI base uri @return the instance of javax.ws.rs.core.Response """ try { lockHolder.checkLock(session, path, tokens); Node node = (Node)session.getItem(path); WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session); URI uri = new URI(TextUtil.escape(baseURI + node.getPath(), '%', true)); List<HierarchicalProperty> setList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "set")) != null) { setList = setList(body); } List<HierarchicalProperty> removeList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "remove")) != null) { removeList = removeList(body); } PropPatchResponseEntity entity = new PropPatchResponseEntity(nsContext, node, uri, setList, removeList); return Response.status(HTTPStatus.MULTISTATUS).entity(entity).type(MediaType.TEXT_XML).build(); } catch (PathNotFoundException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (LockException exc) { return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build(); } catch (Exception exc) { log.error(exc.getMessage(), exc); return Response.serverError().entity(exc.getMessage()).build(); } }
java
public Response propPatch(Session session, String path, HierarchicalProperty body, List<String> tokens, String baseURI) { try { lockHolder.checkLock(session, path, tokens); Node node = (Node)session.getItem(path); WebDavNamespaceContext nsContext = new WebDavNamespaceContext(session); URI uri = new URI(TextUtil.escape(baseURI + node.getPath(), '%', true)); List<HierarchicalProperty> setList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "set")) != null) { setList = setList(body); } List<HierarchicalProperty> removeList = Collections.emptyList(); if (body.getChild(new QName("DAV:", "remove")) != null) { removeList = removeList(body); } PropPatchResponseEntity entity = new PropPatchResponseEntity(nsContext, node, uri, setList, removeList); return Response.status(HTTPStatus.MULTISTATUS).entity(entity).type(MediaType.TEXT_XML).build(); } catch (PathNotFoundException exc) { return Response.status(HTTPStatus.NOT_FOUND).entity(exc.getMessage()).build(); } catch (LockException exc) { return Response.status(HTTPStatus.LOCKED).entity(exc.getMessage()).build(); } catch (Exception exc) { log.error(exc.getMessage(), exc); return Response.serverError().entity(exc.getMessage()).build(); } }
[ "public", "Response", "propPatch", "(", "Session", "session", ",", "String", "path", ",", "HierarchicalProperty", "body", ",", "List", "<", "String", ">", "tokens", ",", "String", "baseURI", ")", "{", "try", "{", "lockHolder", ".", "checkLock", "(", "session", ",", "path", ",", "tokens", ")", ";", "Node", "node", "=", "(", "Node", ")", "session", ".", "getItem", "(", "path", ")", ";", "WebDavNamespaceContext", "nsContext", "=", "new", "WebDavNamespaceContext", "(", "session", ")", ";", "URI", "uri", "=", "new", "URI", "(", "TextUtil", ".", "escape", "(", "baseURI", "+", "node", ".", "getPath", "(", ")", ",", "'", "'", ",", "true", ")", ")", ";", "List", "<", "HierarchicalProperty", ">", "setList", "=", "Collections", ".", "emptyList", "(", ")", ";", "if", "(", "body", ".", "getChild", "(", "new", "QName", "(", "\"DAV:\"", ",", "\"set\"", ")", ")", "!=", "null", ")", "{", "setList", "=", "setList", "(", "body", ")", ";", "}", "List", "<", "HierarchicalProperty", ">", "removeList", "=", "Collections", ".", "emptyList", "(", ")", ";", "if", "(", "body", ".", "getChild", "(", "new", "QName", "(", "\"DAV:\"", ",", "\"remove\"", ")", ")", "!=", "null", ")", "{", "removeList", "=", "removeList", "(", "body", ")", ";", "}", "PropPatchResponseEntity", "entity", "=", "new", "PropPatchResponseEntity", "(", "nsContext", ",", "node", ",", "uri", ",", "setList", ",", "removeList", ")", ";", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "MULTISTATUS", ")", ".", "entity", "(", "entity", ")", ".", "type", "(", "MediaType", ".", "TEXT_XML", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "PathNotFoundException", "exc", ")", "{", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "NOT_FOUND", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "LockException", "exc", ")", "{", "return", "Response", ".", "status", "(", "HTTPStatus", ".", "LOCKED", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "catch", "(", "Exception", "exc", ")", "{", "log", ".", "error", "(", "exc", ".", "getMessage", "(", ")", ",", "exc", ")", ";", "return", "Response", ".", "serverError", "(", ")", ".", "entity", "(", "exc", ".", "getMessage", "(", ")", ")", ".", "build", "(", ")", ";", "}", "}" ]
Webdav Proppatch method method implementation. @param session current session @param path resource path @param body request body @param tokens tokens @param baseURI base uri @return the instance of javax.ws.rs.core.Response
[ "Webdav", "Proppatch", "method", "method", "implementation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.webdav/src/main/java/org/exoplatform/services/jcr/webdav/command/PropPatchCommand.java#L82-L126
rosette-api/java
api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java
HttpRosetteAPI.sendGetRequest
private <T extends Response> T sendGetRequest(String urlStr, Class<T> clazz) throws HttpRosetteAPIException { """ Sends a GET request to Rosette API. <p> Returns a Response. @param urlStr Rosette API end point. @param clazz Response class @return Response @throws HttpRosetteAPIException """ HttpGet get = new HttpGet(urlStr); for (Header header : additionalHeaders) { get.addHeader(header); } try (CloseableHttpResponse httpResponse = httpClient.execute(get)) { T resp = getResponse(httpResponse, clazz); responseHeadersToExtendedInformation(resp, httpResponse); return resp; } catch (IOException e) { throw new RosetteRuntimeException("IO Exception communicating with the Rosette API", e); } }
java
private <T extends Response> T sendGetRequest(String urlStr, Class<T> clazz) throws HttpRosetteAPIException { HttpGet get = new HttpGet(urlStr); for (Header header : additionalHeaders) { get.addHeader(header); } try (CloseableHttpResponse httpResponse = httpClient.execute(get)) { T resp = getResponse(httpResponse, clazz); responseHeadersToExtendedInformation(resp, httpResponse); return resp; } catch (IOException e) { throw new RosetteRuntimeException("IO Exception communicating with the Rosette API", e); } }
[ "private", "<", "T", "extends", "Response", ">", "T", "sendGetRequest", "(", "String", "urlStr", ",", "Class", "<", "T", ">", "clazz", ")", "throws", "HttpRosetteAPIException", "{", "HttpGet", "get", "=", "new", "HttpGet", "(", "urlStr", ")", ";", "for", "(", "Header", "header", ":", "additionalHeaders", ")", "{", "get", ".", "addHeader", "(", "header", ")", ";", "}", "try", "(", "CloseableHttpResponse", "httpResponse", "=", "httpClient", ".", "execute", "(", "get", ")", ")", "{", "T", "resp", "=", "getResponse", "(", "httpResponse", ",", "clazz", ")", ";", "responseHeadersToExtendedInformation", "(", "resp", ",", "httpResponse", ")", ";", "return", "resp", ";", "}", "catch", "(", "IOException", "e", ")", "{", "throw", "new", "RosetteRuntimeException", "(", "\"IO Exception communicating with the Rosette API\"", ",", "e", ")", ";", "}", "}" ]
Sends a GET request to Rosette API. <p> Returns a Response. @param urlStr Rosette API end point. @param clazz Response class @return Response @throws HttpRosetteAPIException
[ "Sends", "a", "GET", "request", "to", "Rosette", "API", ".", "<p", ">", "Returns", "a", "Response", "." ]
train
https://github.com/rosette-api/java/blob/35faf9fbb9c940eae47df004da7639a3b177b80b/api/src/main/java/com/basistech/rosette/api/HttpRosetteAPI.java#L326-L339
yanzhenjie/AndServer
api/src/main/java/com/yanzhenjie/andserver/util/comparator/CompoundComparator.java
CompoundComparator.setComparator
public void setComparator(int index, Comparator<T> comparator, boolean ascending) { """ Replace the Comparator at the given index using the given sort order. @param index the index of the Comparator to replace @param comparator the Comparator to place at the given index @param ascending the sort order: ascending (true) or descending (false) """ this.comparators.set(index, new InvertibleComparator<>(comparator, ascending)); }
java
public void setComparator(int index, Comparator<T> comparator, boolean ascending) { this.comparators.set(index, new InvertibleComparator<>(comparator, ascending)); }
[ "public", "void", "setComparator", "(", "int", "index", ",", "Comparator", "<", "T", ">", "comparator", ",", "boolean", "ascending", ")", "{", "this", ".", "comparators", ".", "set", "(", "index", ",", "new", "InvertibleComparator", "<>", "(", "comparator", ",", "ascending", ")", ")", ";", "}" ]
Replace the Comparator at the given index using the given sort order. @param index the index of the Comparator to replace @param comparator the Comparator to place at the given index @param ascending the sort order: ascending (true) or descending (false)
[ "Replace", "the", "Comparator", "at", "the", "given", "index", "using", "the", "given", "sort", "order", "." ]
train
https://github.com/yanzhenjie/AndServer/blob/f95f316cdfa5755d6a3fec3c6a1b5df783b81517/api/src/main/java/com/yanzhenjie/andserver/util/comparator/CompoundComparator.java#L112-L114
OpenLiberty/open-liberty
dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelPlainFormatter.java
HpelPlainFormatter.createEventTimeStamp
protected void createEventTimeStamp(RepositoryLogRecord record, StringBuilder buffer) { """ Generates the time stamp for the RepositoryLogRecord event. The resulting time stamp is formatted based on the formatter's locale and time zone. @param record of the event. @param buffer output buffer where converted timestamp is appended to. """ if (null == record) { throw new IllegalArgumentException("Record cannot be null"); } if (null == buffer) { throw new IllegalArgumentException("Buffer cannot be null"); } // Create the time stamp buffer.append('['); Date eventDate = new Date(record.getMillis()); // set the dateFormat object to the desired timeZone. Allows log output // to be presented in different time zones. dateFormat.setTimeZone(timeZone); // set the format to // the desired // time zone. buffer.append(dateFormat.format(eventDate)); buffer.append("] "); }
java
protected void createEventTimeStamp(RepositoryLogRecord record, StringBuilder buffer) { if (null == record) { throw new IllegalArgumentException("Record cannot be null"); } if (null == buffer) { throw new IllegalArgumentException("Buffer cannot be null"); } // Create the time stamp buffer.append('['); Date eventDate = new Date(record.getMillis()); // set the dateFormat object to the desired timeZone. Allows log output // to be presented in different time zones. dateFormat.setTimeZone(timeZone); // set the format to // the desired // time zone. buffer.append(dateFormat.format(eventDate)); buffer.append("] "); }
[ "protected", "void", "createEventTimeStamp", "(", "RepositoryLogRecord", "record", ",", "StringBuilder", "buffer", ")", "{", "if", "(", "null", "==", "record", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Record cannot be null\"", ")", ";", "}", "if", "(", "null", "==", "buffer", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Buffer cannot be null\"", ")", ";", "}", "// Create the time stamp", "buffer", ".", "append", "(", "'", "'", ")", ";", "Date", "eventDate", "=", "new", "Date", "(", "record", ".", "getMillis", "(", ")", ")", ";", "// set the dateFormat object to the desired timeZone. Allows log output", "// to be presented in different time zones.", "dateFormat", ".", "setTimeZone", "(", "timeZone", ")", ";", "// set the format to", "// the desired", "// time zone.", "buffer", ".", "append", "(", "dateFormat", ".", "format", "(", "eventDate", ")", ")", ";", "buffer", ".", "append", "(", "\"] \"", ")", ";", "}" ]
Generates the time stamp for the RepositoryLogRecord event. The resulting time stamp is formatted based on the formatter's locale and time zone. @param record of the event. @param buffer output buffer where converted timestamp is appended to.
[ "Generates", "the", "time", "stamp", "for", "the", "RepositoryLogRecord", "event", ".", "The", "resulting", "time", "stamp", "is", "formatted", "based", "on", "the", "formatter", "s", "locale", "and", "time", "zone", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.logging.hpel/src/com/ibm/websphere/logging/hpel/reader/HpelPlainFormatter.java#L56-L73
mabe02/lanterna
src/main/java/com/googlecode/lanterna/input/EscapeSequenceCharacterPattern.java
EscapeSequenceCharacterPattern.getKeyStroke
protected KeyStroke getKeyStroke(KeyType key, int mods) { """ combines a KeyType and modifiers into a KeyStroke. Subclasses can override this for customization purposes. @param key the KeyType as determined by parsing the sequence. It will be null, if the pattern looked like a key sequence but wasn't identified. @param mods the bitmask of the modifer keys pressed along with the key. @return either null (to report mis-match), or a valid KeyStroke. """ boolean bShift = false, bCtrl = false, bAlt = false; if (key == null) { return null; } // alternative: key = KeyType.Unknown; if (mods >= 0) { // only use when non-negative! bShift = (mods & SHIFT) != 0; bAlt = (mods & ALT) != 0; bCtrl = (mods & CTRL) != 0; } return new KeyStroke( key , bCtrl, bAlt, bShift); }
java
protected KeyStroke getKeyStroke(KeyType key, int mods) { boolean bShift = false, bCtrl = false, bAlt = false; if (key == null) { return null; } // alternative: key = KeyType.Unknown; if (mods >= 0) { // only use when non-negative! bShift = (mods & SHIFT) != 0; bAlt = (mods & ALT) != 0; bCtrl = (mods & CTRL) != 0; } return new KeyStroke( key , bCtrl, bAlt, bShift); }
[ "protected", "KeyStroke", "getKeyStroke", "(", "KeyType", "key", ",", "int", "mods", ")", "{", "boolean", "bShift", "=", "false", ",", "bCtrl", "=", "false", ",", "bAlt", "=", "false", ";", "if", "(", "key", "==", "null", ")", "{", "return", "null", ";", "}", "// alternative: key = KeyType.Unknown;", "if", "(", "mods", ">=", "0", ")", "{", "// only use when non-negative!", "bShift", "=", "(", "mods", "&", "SHIFT", ")", "!=", "0", ";", "bAlt", "=", "(", "mods", "&", "ALT", ")", "!=", "0", ";", "bCtrl", "=", "(", "mods", "&", "CTRL", ")", "!=", "0", ";", "}", "return", "new", "KeyStroke", "(", "key", ",", "bCtrl", ",", "bAlt", ",", "bShift", ")", ";", "}" ]
combines a KeyType and modifiers into a KeyStroke. Subclasses can override this for customization purposes. @param key the KeyType as determined by parsing the sequence. It will be null, if the pattern looked like a key sequence but wasn't identified. @param mods the bitmask of the modifer keys pressed along with the key. @return either null (to report mis-match), or a valid KeyStroke.
[ "combines", "a", "KeyType", "and", "modifiers", "into", "a", "KeyStroke", ".", "Subclasses", "can", "override", "this", "for", "customization", "purposes", "." ]
train
https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/input/EscapeSequenceCharacterPattern.java#L140-L149
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java
DecimalFormat.skipPatternWhiteSpace
private static int skipPatternWhiteSpace(String text, int pos) { """ Skips over a run of zero or more Pattern_White_Space characters at pos in text. """ while (pos < text.length()) { int c = UTF16.charAt(text, pos); if (!PatternProps.isWhiteSpace(c)) { break; } pos += UTF16.getCharCount(c); } return pos; }
java
private static int skipPatternWhiteSpace(String text, int pos) { while (pos < text.length()) { int c = UTF16.charAt(text, pos); if (!PatternProps.isWhiteSpace(c)) { break; } pos += UTF16.getCharCount(c); } return pos; }
[ "private", "static", "int", "skipPatternWhiteSpace", "(", "String", "text", ",", "int", "pos", ")", "{", "while", "(", "pos", "<", "text", ".", "length", "(", ")", ")", "{", "int", "c", "=", "UTF16", ".", "charAt", "(", "text", ",", "pos", ")", ";", "if", "(", "!", "PatternProps", ".", "isWhiteSpace", "(", "c", ")", ")", "{", "break", ";", "}", "pos", "+=", "UTF16", ".", "getCharCount", "(", "c", ")", ";", "}", "return", "pos", ";", "}" ]
Skips over a run of zero or more Pattern_White_Space characters at pos in text.
[ "Skips", "over", "a", "run", "of", "zero", "or", "more", "Pattern_White_Space", "characters", "at", "pos", "in", "text", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DecimalFormat.java#L3011-L3020
killbilling/recurly-java-library
src/main/java/com/ning/billing/recurly/RecurlyClient.java
RecurlyClient.createPlanAddOn
public AddOn createPlanAddOn(final String planCode, final AddOn addOn) { """ Create an AddOn to a Plan <p> @param planCode The planCode of the {@link Plan } to create within recurly @param addOn The {@link AddOn} to create within recurly @return the {@link AddOn} object as identified by the passed in object """ return doPOST(Plan.PLANS_RESOURCE + "/" + planCode + AddOn.ADDONS_RESOURCE, addOn, AddOn.class); }
java
public AddOn createPlanAddOn(final String planCode, final AddOn addOn) { return doPOST(Plan.PLANS_RESOURCE + "/" + planCode + AddOn.ADDONS_RESOURCE, addOn, AddOn.class); }
[ "public", "AddOn", "createPlanAddOn", "(", "final", "String", "planCode", ",", "final", "AddOn", "addOn", ")", "{", "return", "doPOST", "(", "Plan", ".", "PLANS_RESOURCE", "+", "\"/\"", "+", "planCode", "+", "AddOn", ".", "ADDONS_RESOURCE", ",", "addOn", ",", "AddOn", ".", "class", ")", ";", "}" ]
Create an AddOn to a Plan <p> @param planCode The planCode of the {@link Plan } to create within recurly @param addOn The {@link AddOn} to create within recurly @return the {@link AddOn} object as identified by the passed in object
[ "Create", "an", "AddOn", "to", "a", "Plan", "<p", ">" ]
train
https://github.com/killbilling/recurly-java-library/blob/5e05eedd91885a51e1aa8293bd41139d082cf7f4/src/main/java/com/ning/billing/recurly/RecurlyClient.java#L1438-L1444
kuujo/vertigo
core/src/main/java/net/kuujo/vertigo/Vertigo.java
Vertigo.deployCluster
public Vertigo deployCluster(String cluster, int nodes) { """ Deploys multiple nodes within a cluster at the given address. @param cluster The cluster event bus address. @param nodes The number of nodes to deploy. @return The Vertigo instance. """ return deployCluster(cluster, null, nodes, null); }
java
public Vertigo deployCluster(String cluster, int nodes) { return deployCluster(cluster, null, nodes, null); }
[ "public", "Vertigo", "deployCluster", "(", "String", "cluster", ",", "int", "nodes", ")", "{", "return", "deployCluster", "(", "cluster", ",", "null", ",", "nodes", ",", "null", ")", ";", "}" ]
Deploys multiple nodes within a cluster at the given address. @param cluster The cluster event bus address. @param nodes The number of nodes to deploy. @return The Vertigo instance.
[ "Deploys", "multiple", "nodes", "within", "a", "cluster", "at", "the", "given", "address", "." ]
train
https://github.com/kuujo/vertigo/blob/c5869dbc5fff89eb5262e83f7a81719b01a5ba6f/core/src/main/java/net/kuujo/vertigo/Vertigo.java#L234-L236
alipay/sofa-rpc
extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java
SofaConfigs.getIntegerValue
public static int getIntegerValue(String appName, String key, int defaultValue) { """ 解析数字型配置 @param appName 应用名 @param key 配置项 @param defaultValue 默认值 @return 配置 """ String ret = getStringValue0(appName, key); return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseInt(ret, defaultValue); }
java
public static int getIntegerValue(String appName, String key, int defaultValue) { String ret = getStringValue0(appName, key); return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseInt(ret, defaultValue); }
[ "public", "static", "int", "getIntegerValue", "(", "String", "appName", ",", "String", "key", ",", "int", "defaultValue", ")", "{", "String", "ret", "=", "getStringValue0", "(", "appName", ",", "key", ")", ";", "return", "StringUtils", ".", "isEmpty", "(", "ret", ")", "?", "defaultValue", ":", "CommonUtils", ".", "parseInt", "(", "ret", ",", "defaultValue", ")", ";", "}" ]
解析数字型配置 @param appName 应用名 @param key 配置项 @param defaultValue 默认值 @return 配置
[ "解析数字型配置" ]
train
https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java#L120-L123
joinfaces/joinfaces
joinfaces-autoconfigure/src/main/java/org/joinfaces/autoconfigure/adminfaces/AdminfacesAutoConfiguration.java
AdminfacesAutoConfiguration.adminfacesWebServerFactoryCustomizer
@Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> adminfacesWebServerFactoryCustomizer() { """ This {@link WebServerFactoryCustomizer} adds a {@link ServletContextInitializer} to the embedded servlet-container which is equivalent to adminfaces's own {@code META-INF/web-fragment.xml}. @return adminfaces web server factory customizer """ return factory -> { factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403.jsf"), new ErrorPage(AccessDeniedException.class, "/403.jsf"), new ErrorPage(AccessLocalException.class, "/403.jsf"), new ErrorPage(HttpStatus.NOT_FOUND, "/404.jsf"), new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.jsf"), new ErrorPage(Throwable.class, "/500.jsf"), new ErrorPage(ViewExpiredException.class, "/expired.jsf"), new ErrorPage(OptimisticLockException.class, "/optimistic.jsf") ); factory.addInitializers(servletContext -> { servletContext.addListener(new AdminServletContextListener()); }); }; }
java
@Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> adminfacesWebServerFactoryCustomizer() { return factory -> { factory.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403.jsf"), new ErrorPage(AccessDeniedException.class, "/403.jsf"), new ErrorPage(AccessLocalException.class, "/403.jsf"), new ErrorPage(HttpStatus.NOT_FOUND, "/404.jsf"), new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.jsf"), new ErrorPage(Throwable.class, "/500.jsf"), new ErrorPage(ViewExpiredException.class, "/expired.jsf"), new ErrorPage(OptimisticLockException.class, "/optimistic.jsf") ); factory.addInitializers(servletContext -> { servletContext.addListener(new AdminServletContextListener()); }); }; }
[ "@", "Bean", "public", "WebServerFactoryCustomizer", "<", "ConfigurableServletWebServerFactory", ">", "adminfacesWebServerFactoryCustomizer", "(", ")", "{", "return", "factory", "->", "{", "factory", ".", "addErrorPages", "(", "new", "ErrorPage", "(", "HttpStatus", ".", "FORBIDDEN", ",", "\"/403.jsf\"", ")", ",", "new", "ErrorPage", "(", "AccessDeniedException", ".", "class", ",", "\"/403.jsf\"", ")", ",", "new", "ErrorPage", "(", "AccessLocalException", ".", "class", ",", "\"/403.jsf\"", ")", ",", "new", "ErrorPage", "(", "HttpStatus", ".", "NOT_FOUND", ",", "\"/404.jsf\"", ")", ",", "new", "ErrorPage", "(", "HttpStatus", ".", "INTERNAL_SERVER_ERROR", ",", "\"/500.jsf\"", ")", ",", "new", "ErrorPage", "(", "Throwable", ".", "class", ",", "\"/500.jsf\"", ")", ",", "new", "ErrorPage", "(", "ViewExpiredException", ".", "class", ",", "\"/expired.jsf\"", ")", ",", "new", "ErrorPage", "(", "OptimisticLockException", ".", "class", ",", "\"/optimistic.jsf\"", ")", ")", ";", "factory", ".", "addInitializers", "(", "servletContext", "->", "{", "servletContext", ".", "addListener", "(", "new", "AdminServletContextListener", "(", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
This {@link WebServerFactoryCustomizer} adds a {@link ServletContextInitializer} to the embedded servlet-container which is equivalent to adminfaces's own {@code META-INF/web-fragment.xml}. @return adminfaces web server factory customizer
[ "This", "{" ]
train
https://github.com/joinfaces/joinfaces/blob/c9fc811a9eaf695820951f2c04715297dd1e6d66/joinfaces-autoconfigure/src/main/java/org/joinfaces/autoconfigure/adminfaces/AdminfacesAutoConfiguration.java#L93-L109
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WButtonExample.java
WButtonExample.addDefaultSubmitButtonExample
private void addDefaultSubmitButtonExample() { """ Examples showing how to set a WButton as the default submit button for an input control. """ add(new WHeading(HeadingLevel.H3, "Default submit button")); add(new ExplanatoryText( "This example shows how to use an image as the only content of a WButton. " + "In addition this text field submits the entire screen using the image button to the right of the field.")); // We use WFieldLayout to lay out a label:input pair. In this case the input is a //compound control of a WTextField and a WButton. WFieldLayout imageButtonFieldLayout = new WFieldLayout(); imageButtonFieldLayout.setLabelWidth(25); add(imageButtonFieldLayout); // the text field and the button both need to be defined explicitly to be able to add them into a wrapper WTextField textFld = new WTextField(); //and finally we get to the actual button WButton button = new WButton("Flag this record for follow-up"); button.setImage("/image/flag.png"); button.getImageHolder().setCacheKey("eg-button-flag"); button.setActionObject(button); button.setAction(new ExampleButtonAction()); //we can set the image button to be the default submit button for the text field. textFld.setDefaultSubmitButton(button); //There are many way of putting multiple controls in to a WField's input. //We are using a WContainer is the one which is lowest impact in the UI. WContainer imageButtonFieldContainer = new WContainer(); imageButtonFieldContainer.add(textFld); //Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount. imageButtonFieldContainer.add(new WText("\u2002")); //an en space is half an em. a none-breaking space \u00a0 could also be used but will have no effect on inter-node wrapping imageButtonFieldContainer.add(button); //Finally add the input wrapper to the WFieldLayout imageButtonFieldLayout.addField("Enter record ID", imageButtonFieldContainer); }
java
private void addDefaultSubmitButtonExample() { add(new WHeading(HeadingLevel.H3, "Default submit button")); add(new ExplanatoryText( "This example shows how to use an image as the only content of a WButton. " + "In addition this text field submits the entire screen using the image button to the right of the field.")); // We use WFieldLayout to lay out a label:input pair. In this case the input is a //compound control of a WTextField and a WButton. WFieldLayout imageButtonFieldLayout = new WFieldLayout(); imageButtonFieldLayout.setLabelWidth(25); add(imageButtonFieldLayout); // the text field and the button both need to be defined explicitly to be able to add them into a wrapper WTextField textFld = new WTextField(); //and finally we get to the actual button WButton button = new WButton("Flag this record for follow-up"); button.setImage("/image/flag.png"); button.getImageHolder().setCacheKey("eg-button-flag"); button.setActionObject(button); button.setAction(new ExampleButtonAction()); //we can set the image button to be the default submit button for the text field. textFld.setDefaultSubmitButton(button); //There are many way of putting multiple controls in to a WField's input. //We are using a WContainer is the one which is lowest impact in the UI. WContainer imageButtonFieldContainer = new WContainer(); imageButtonFieldContainer.add(textFld); //Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount. imageButtonFieldContainer.add(new WText("\u2002")); //an en space is half an em. a none-breaking space \u00a0 could also be used but will have no effect on inter-node wrapping imageButtonFieldContainer.add(button); //Finally add the input wrapper to the WFieldLayout imageButtonFieldLayout.addField("Enter record ID", imageButtonFieldContainer); }
[ "private", "void", "addDefaultSubmitButtonExample", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"Default submit button\"", ")", ")", ";", "add", "(", "new", "ExplanatoryText", "(", "\"This example shows how to use an image as the only content of a WButton. \"", "+", "\"In addition this text field submits the entire screen using the image button to the right of the field.\"", ")", ")", ";", "// We use WFieldLayout to lay out a label:input pair. In this case the input is a", "//compound control of a WTextField and a WButton.", "WFieldLayout", "imageButtonFieldLayout", "=", "new", "WFieldLayout", "(", ")", ";", "imageButtonFieldLayout", ".", "setLabelWidth", "(", "25", ")", ";", "add", "(", "imageButtonFieldLayout", ")", ";", "// the text field and the button both need to be defined explicitly to be able to add them into a wrapper", "WTextField", "textFld", "=", "new", "WTextField", "(", ")", ";", "//and finally we get to the actual button", "WButton", "button", "=", "new", "WButton", "(", "\"Flag this record for follow-up\"", ")", ";", "button", ".", "setImage", "(", "\"/image/flag.png\"", ")", ";", "button", ".", "getImageHolder", "(", ")", ".", "setCacheKey", "(", "\"eg-button-flag\"", ")", ";", "button", ".", "setActionObject", "(", "button", ")", ";", "button", ".", "setAction", "(", "new", "ExampleButtonAction", "(", ")", ")", ";", "//we can set the image button to be the default submit button for the text field.", "textFld", ".", "setDefaultSubmitButton", "(", "button", ")", ";", "//There are many way of putting multiple controls in to a WField's input.", "//We are using a WContainer is the one which is lowest impact in the UI.", "WContainer", "imageButtonFieldContainer", "=", "new", "WContainer", "(", ")", ";", "imageButtonFieldContainer", ".", "add", "(", "textFld", ")", ";", "//Use a WText to push the button off of the text field by an appropriate (user-agent determined) amount.", "imageButtonFieldContainer", ".", "add", "(", "new", "WText", "(", "\"\\u2002\"", ")", ")", ";", "//an en space is half an em. a none-breaking space \\u00a0 could also be used but will have no effect on inter-node wrapping", "imageButtonFieldContainer", ".", "add", "(", "button", ")", ";", "//Finally add the input wrapper to the WFieldLayout", "imageButtonFieldLayout", ".", "addField", "(", "\"Enter record ID\"", ",", "imageButtonFieldContainer", ")", ";", "}" ]
Examples showing how to set a WButton as the default submit button for an input control.
[ "Examples", "showing", "how", "to", "set", "a", "WButton", "as", "the", "default", "submit", "button", "for", "an", "input", "control", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/WButtonExample.java#L280-L311
OpenTSDB/opentsdb
src/tools/ConfigArgP.java
ConfigArgP.loadConfig
protected static Properties loadConfig(URL url) { """ Loads properties from the passed URL @param url The url to load from @return the loaded properties """ InputStream is = null; try { URLConnection connection = url.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection)connection; conn.setConnectTimeout(5000); conn.setReadTimeout(5000); } is = connection.getInputStream(); return loadConfig(url.toString(), is); } catch (Exception ex) { ex.printStackTrace(System.err); throw new IllegalArgumentException("Failed to load configuration from [" + url + "]", ex); }finally { if(is!=null) try { is.close(); } catch (Exception ex) { /* No Op */ } } }
java
protected static Properties loadConfig(URL url) { InputStream is = null; try { URLConnection connection = url.openConnection(); if(connection instanceof HttpURLConnection) { HttpURLConnection conn = (HttpURLConnection)connection; conn.setConnectTimeout(5000); conn.setReadTimeout(5000); } is = connection.getInputStream(); return loadConfig(url.toString(), is); } catch (Exception ex) { ex.printStackTrace(System.err); throw new IllegalArgumentException("Failed to load configuration from [" + url + "]", ex); }finally { if(is!=null) try { is.close(); } catch (Exception ex) { /* No Op */ } } }
[ "protected", "static", "Properties", "loadConfig", "(", "URL", "url", ")", "{", "InputStream", "is", "=", "null", ";", "try", "{", "URLConnection", "connection", "=", "url", ".", "openConnection", "(", ")", ";", "if", "(", "connection", "instanceof", "HttpURLConnection", ")", "{", "HttpURLConnection", "conn", "=", "(", "HttpURLConnection", ")", "connection", ";", "conn", ".", "setConnectTimeout", "(", "5000", ")", ";", "conn", ".", "setReadTimeout", "(", "5000", ")", ";", "}", "is", "=", "connection", ".", "getInputStream", "(", ")", ";", "return", "loadConfig", "(", "url", ".", "toString", "(", ")", ",", "is", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "ex", ".", "printStackTrace", "(", "System", ".", "err", ")", ";", "throw", "new", "IllegalArgumentException", "(", "\"Failed to load configuration from [\"", "+", "url", "+", "\"]\"", ",", "ex", ")", ";", "}", "finally", "{", "if", "(", "is", "!=", "null", ")", "try", "{", "is", ".", "close", "(", ")", ";", "}", "catch", "(", "Exception", "ex", ")", "{", "/* No Op */", "}", "}", "}" ]
Loads properties from the passed URL @param url The url to load from @return the loaded properties
[ "Loads", "properties", "from", "the", "passed", "URL" ]
train
https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/ConfigArgP.java#L279-L296
elki-project/elki
elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/AnderbergHierarchicalClustering.java
AnderbergHierarchicalClustering.updateCache
private void updateCache(int size, double[] scratch, double[] bestd, int[] besti, int x, int y, int j, double d) { """ Update the cache. @param size Working set size @param scratch Scratch matrix @param bestd Best distance @param besti Best index @param x First cluster @param y Second cluster, {@code y < x} @param j Updated value d(y, j) @param d New distance """ // New best if(d <= bestd[j]) { bestd[j] = d; besti[j] = y; return; } // Needs slow update. if(besti[j] == x || besti[j] == y) { findBest(size, scratch, bestd, besti, j); } }
java
private void updateCache(int size, double[] scratch, double[] bestd, int[] besti, int x, int y, int j, double d) { // New best if(d <= bestd[j]) { bestd[j] = d; besti[j] = y; return; } // Needs slow update. if(besti[j] == x || besti[j] == y) { findBest(size, scratch, bestd, besti, j); } }
[ "private", "void", "updateCache", "(", "int", "size", ",", "double", "[", "]", "scratch", ",", "double", "[", "]", "bestd", ",", "int", "[", "]", "besti", ",", "int", "x", ",", "int", "y", ",", "int", "j", ",", "double", "d", ")", "{", "// New best", "if", "(", "d", "<=", "bestd", "[", "j", "]", ")", "{", "bestd", "[", "j", "]", "=", "d", ";", "besti", "[", "j", "]", "=", "y", ";", "return", ";", "}", "// Needs slow update.", "if", "(", "besti", "[", "j", "]", "==", "x", "||", "besti", "[", "j", "]", "==", "y", ")", "{", "findBest", "(", "size", ",", "scratch", ",", "bestd", ",", "besti", ",", "j", ")", ";", "}", "}" ]
Update the cache. @param size Working set size @param scratch Scratch matrix @param bestd Best distance @param besti Best index @param x First cluster @param y Second cluster, {@code y < x} @param j Updated value d(y, j) @param d New distance
[ "Update", "the", "cache", "." ]
train
https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-clustering/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/hierarchical/AnderbergHierarchicalClustering.java#L312-L323
exoplatform/jcr
exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/GroupHandlerImpl.java
GroupHandlerImpl.postSave
private void postSave(Group group, boolean isNew) throws Exception { """ Notifying listeners after group creation. @param group the group which is used in create operation @param isNew true, if we have a deal with new group, otherwise it is false which mean update operation is in progress @throws Exception if any listener failed to handle the event """ for (GroupEventListener listener : listeners) { listener.postSave(group, isNew); } }
java
private void postSave(Group group, boolean isNew) throws Exception { for (GroupEventListener listener : listeners) { listener.postSave(group, isNew); } }
[ "private", "void", "postSave", "(", "Group", "group", ",", "boolean", "isNew", ")", "throws", "Exception", "{", "for", "(", "GroupEventListener", "listener", ":", "listeners", ")", "{", "listener", ".", "postSave", "(", "group", ",", "isNew", ")", ";", "}", "}" ]
Notifying listeners after group creation. @param group the group which is used in create operation @param isNew true, if we have a deal with new group, otherwise it is false which mean update operation is in progress @throws Exception if any listener failed to handle the event
[ "Notifying", "listeners", "after", "group", "creation", "." ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.ext.services/src/main/java/org/exoplatform/services/jcr/ext/organization/GroupHandlerImpl.java#L572-L578
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPInputHandler.java
PtoPInputHandler.checkTargetAbleToAcceptOrExceptionMessage
private int checkTargetAbleToAcceptOrExceptionMessage(JsDestinationAddress targetDestinationAddr) throws SITemporaryDestinationNotFoundException, SIResourceException, SINotPossibleInCurrentConfigurationException { """ See if a target destination or, if necessary, its exception destination, can handle any more messages. @return reason code signifying whether the destination can accept messages or the reason for not being able to do so. @throws SINotPossibleInCurrentConfigurationException @throws SIResourceException @throws SITemporaryDestinationNotFoundException """ if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "checkTargetAbleToAcceptOrExceptionMessage", targetDestinationAddr); int blockingReason = DestinationHandler.OUTPUT_HANDLER_NOT_FOUND; // If the original routingDestination address in the message was blank we simply return // 'not found'. if (targetDestinationAddr != null) { // Lookup the routing (target) destination. This may throw a SIMPNotPossibleInCurrentConfigurationException. DestinationHandler targetDestination = _messageProcessor.getDestinationManager().getDestination(targetDestinationAddr, false); SIBUuid8 targetDestinationMEUuid = targetDestinationAddr.getME(); // Can the routing destination accept a message blockingReason = targetDestination.checkCanAcceptMessage(targetDestinationMEUuid, null); // If the target is full (or put-disabled, etc) then we want to go on & see if we can // put to the exception destination of the target destination if (blockingReason != DestinationHandler.OUTPUT_HANDLER_FOUND) { int linkBlockingReason = checkCanExceptionMessage(targetDestination); // If we can exception the message then reset the blockingReason return code if (linkBlockingReason == DestinationHandler.OUTPUT_HANDLER_FOUND) blockingReason = DestinationHandler.OUTPUT_HANDLER_FOUND; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkTargetAbleToAcceptOrExceptionMessage", Integer.valueOf(blockingReason)); return blockingReason; }
java
private int checkTargetAbleToAcceptOrExceptionMessage(JsDestinationAddress targetDestinationAddr) throws SITemporaryDestinationNotFoundException, SIResourceException, SINotPossibleInCurrentConfigurationException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "checkTargetAbleToAcceptOrExceptionMessage", targetDestinationAddr); int blockingReason = DestinationHandler.OUTPUT_HANDLER_NOT_FOUND; // If the original routingDestination address in the message was blank we simply return // 'not found'. if (targetDestinationAddr != null) { // Lookup the routing (target) destination. This may throw a SIMPNotPossibleInCurrentConfigurationException. DestinationHandler targetDestination = _messageProcessor.getDestinationManager().getDestination(targetDestinationAddr, false); SIBUuid8 targetDestinationMEUuid = targetDestinationAddr.getME(); // Can the routing destination accept a message blockingReason = targetDestination.checkCanAcceptMessage(targetDestinationMEUuid, null); // If the target is full (or put-disabled, etc) then we want to go on & see if we can // put to the exception destination of the target destination if (blockingReason != DestinationHandler.OUTPUT_HANDLER_FOUND) { int linkBlockingReason = checkCanExceptionMessage(targetDestination); // If we can exception the message then reset the blockingReason return code if (linkBlockingReason == DestinationHandler.OUTPUT_HANDLER_FOUND) blockingReason = DestinationHandler.OUTPUT_HANDLER_FOUND; } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "checkTargetAbleToAcceptOrExceptionMessage", Integer.valueOf(blockingReason)); return blockingReason; }
[ "private", "int", "checkTargetAbleToAcceptOrExceptionMessage", "(", "JsDestinationAddress", "targetDestinationAddr", ")", "throws", "SITemporaryDestinationNotFoundException", ",", "SIResourceException", ",", "SINotPossibleInCurrentConfigurationException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "entry", "(", "tc", ",", "\"checkTargetAbleToAcceptOrExceptionMessage\"", ",", "targetDestinationAddr", ")", ";", "int", "blockingReason", "=", "DestinationHandler", ".", "OUTPUT_HANDLER_NOT_FOUND", ";", "// If the original routingDestination address in the message was blank we simply return", "// 'not found'.", "if", "(", "targetDestinationAddr", "!=", "null", ")", "{", "// Lookup the routing (target) destination. This may throw a SIMPNotPossibleInCurrentConfigurationException.", "DestinationHandler", "targetDestination", "=", "_messageProcessor", ".", "getDestinationManager", "(", ")", ".", "getDestination", "(", "targetDestinationAddr", ",", "false", ")", ";", "SIBUuid8", "targetDestinationMEUuid", "=", "targetDestinationAddr", ".", "getME", "(", ")", ";", "// Can the routing destination accept a message", "blockingReason", "=", "targetDestination", ".", "checkCanAcceptMessage", "(", "targetDestinationMEUuid", ",", "null", ")", ";", "// If the target is full (or put-disabled, etc) then we want to go on & see if we can", "// put to the exception destination of the target destination", "if", "(", "blockingReason", "!=", "DestinationHandler", ".", "OUTPUT_HANDLER_FOUND", ")", "{", "int", "linkBlockingReason", "=", "checkCanExceptionMessage", "(", "targetDestination", ")", ";", "// If we can exception the message then reset the blockingReason return code", "if", "(", "linkBlockingReason", "==", "DestinationHandler", ".", "OUTPUT_HANDLER_FOUND", ")", "blockingReason", "=", "DestinationHandler", ".", "OUTPUT_HANDLER_FOUND", ";", "}", "}", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "exit", "(", "tc", ",", "\"checkTargetAbleToAcceptOrExceptionMessage\"", ",", "Integer", ".", "valueOf", "(", "blockingReason", ")", ")", ";", "return", "blockingReason", ";", "}" ]
See if a target destination or, if necessary, its exception destination, can handle any more messages. @return reason code signifying whether the destination can accept messages or the reason for not being able to do so. @throws SINotPossibleInCurrentConfigurationException @throws SIResourceException @throws SITemporaryDestinationNotFoundException
[ "See", "if", "a", "target", "destination", "or", "if", "necessary", "its", "exception", "destination", "can", "handle", "any", "more", "messages", "." ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/PtoPInputHandler.java#L3324-L3360
BorderTech/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java
WCheckBoxSelectExample.addExampleUsingArrayList
private void addExampleUsingArrayList() { """ This example creates the WCheckBoxSelect from a List of CarOptions. """ add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect created using an array list of options")); List<CarOption> options = new ArrayList<>(); options.add(new CarOption("1", "Ferrari", "F-360")); options.add(new CarOption("2", "Mercedez Benz", "amg")); options.add(new CarOption("3", "Nissan", "Skyline")); options.add(new CarOption("5", "Toyota", "Prius")); final WCheckBoxSelect select = new WCheckBoxSelect(options); select.setToolTip("Cars"); final WTextField text = new WTextField(); text.setReadOnly(true); text.setText(NO_SELECTION); WButton update = new WButton("Select Cars"); update.setAction(new Action() { @Override public void execute(final ActionEvent event) { String output = select.getSelected().isEmpty() ? NO_SELECTION : "The selected cars are: " + select.getSelected(); text.setText(output); } }); select.setDefaultSubmitButton(update); add(select); add(update); add(text); add(new WAjaxControl(update, text)); }
java
private void addExampleUsingArrayList() { add(new WHeading(HeadingLevel.H3, "WCheckBoxSelect created using an array list of options")); List<CarOption> options = new ArrayList<>(); options.add(new CarOption("1", "Ferrari", "F-360")); options.add(new CarOption("2", "Mercedez Benz", "amg")); options.add(new CarOption("3", "Nissan", "Skyline")); options.add(new CarOption("5", "Toyota", "Prius")); final WCheckBoxSelect select = new WCheckBoxSelect(options); select.setToolTip("Cars"); final WTextField text = new WTextField(); text.setReadOnly(true); text.setText(NO_SELECTION); WButton update = new WButton("Select Cars"); update.setAction(new Action() { @Override public void execute(final ActionEvent event) { String output = select.getSelected().isEmpty() ? NO_SELECTION : "The selected cars are: " + select.getSelected(); text.setText(output); } }); select.setDefaultSubmitButton(update); add(select); add(update); add(text); add(new WAjaxControl(update, text)); }
[ "private", "void", "addExampleUsingArrayList", "(", ")", "{", "add", "(", "new", "WHeading", "(", "HeadingLevel", ".", "H3", ",", "\"WCheckBoxSelect created using an array list of options\"", ")", ")", ";", "List", "<", "CarOption", ">", "options", "=", "new", "ArrayList", "<>", "(", ")", ";", "options", ".", "add", "(", "new", "CarOption", "(", "\"1\"", ",", "\"Ferrari\"", ",", "\"F-360\"", ")", ")", ";", "options", ".", "add", "(", "new", "CarOption", "(", "\"2\"", ",", "\"Mercedez Benz\"", ",", "\"amg\"", ")", ")", ";", "options", ".", "add", "(", "new", "CarOption", "(", "\"3\"", ",", "\"Nissan\"", ",", "\"Skyline\"", ")", ")", ";", "options", ".", "add", "(", "new", "CarOption", "(", "\"5\"", ",", "\"Toyota\"", ",", "\"Prius\"", ")", ")", ";", "final", "WCheckBoxSelect", "select", "=", "new", "WCheckBoxSelect", "(", "options", ")", ";", "select", ".", "setToolTip", "(", "\"Cars\"", ")", ";", "final", "WTextField", "text", "=", "new", "WTextField", "(", ")", ";", "text", ".", "setReadOnly", "(", "true", ")", ";", "text", ".", "setText", "(", "NO_SELECTION", ")", ";", "WButton", "update", "=", "new", "WButton", "(", "\"Select Cars\"", ")", ";", "update", ".", "setAction", "(", "new", "Action", "(", ")", "{", "@", "Override", "public", "void", "execute", "(", "final", "ActionEvent", "event", ")", "{", "String", "output", "=", "select", ".", "getSelected", "(", ")", ".", "isEmpty", "(", ")", "?", "NO_SELECTION", ":", "\"The selected cars are: \"", "+", "select", ".", "getSelected", "(", ")", ";", "text", ".", "setText", "(", "output", ")", ";", "}", "}", ")", ";", "select", ".", "setDefaultSubmitButton", "(", "update", ")", ";", "add", "(", "select", ")", ";", "add", "(", "update", ")", ";", "add", "(", "text", ")", ";", "add", "(", "new", "WAjaxControl", "(", "update", ",", "text", ")", ")", ";", "}" ]
This example creates the WCheckBoxSelect from a List of CarOptions.
[ "This", "example", "creates", "the", "WCheckBoxSelect", "from", "a", "List", "of", "CarOptions", "." ]
train
https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/theme/WCheckBoxSelectExample.java#L142-L171
lionsoul2014/jcseg
jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java
StringUtil.isDigit
public static boolean isDigit(String str, int beginIndex, int endIndex) { """ check the specified char is a digit or not true will return if it is or return false this method can recognize full-with char @param str @param beginIndex @param endIndex @return boolean """ char c; for ( int j = beginIndex; j < endIndex; j++ ) { c = str.charAt(j); //make full-width char half-width if ( c > 65280 ) c -= 65248; if ( c < 48 || c > 57 ) { return false; } } return true; }
java
public static boolean isDigit(String str, int beginIndex, int endIndex) { char c; for ( int j = beginIndex; j < endIndex; j++ ) { c = str.charAt(j); //make full-width char half-width if ( c > 65280 ) c -= 65248; if ( c < 48 || c > 57 ) { return false; } } return true; }
[ "public", "static", "boolean", "isDigit", "(", "String", "str", ",", "int", "beginIndex", ",", "int", "endIndex", ")", "{", "char", "c", ";", "for", "(", "int", "j", "=", "beginIndex", ";", "j", "<", "endIndex", ";", "j", "++", ")", "{", "c", "=", "str", ".", "charAt", "(", "j", ")", ";", "//make full-width char half-width", "if", "(", "c", ">", "65280", ")", "c", "-=", "65248", ";", "if", "(", "c", "<", "48", "||", "c", ">", "57", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
check the specified char is a digit or not true will return if it is or return false this method can recognize full-with char @param str @param beginIndex @param endIndex @return boolean
[ "check", "the", "specified", "char", "is", "a", "digit", "or", "not", "true", "will", "return", "if", "it", "is", "or", "return", "false", "this", "method", "can", "recognize", "full", "-", "with", "char" ]
train
https://github.com/lionsoul2014/jcseg/blob/7c8a912e3bbcaf4f8de701180b9c24e2e444a94b/jcseg-core/src/main/java/org/lionsoul/jcseg/util/StringUtil.java#L272-L285
mmazi/rescu
src/main/java/si/mazi/rescu/HttpTemplate.java
HttpTemplate.readInputStreamAsEncodedString
String readInputStreamAsEncodedString(InputStream inputStream, HttpURLConnection connection) throws IOException { """ <p> Reads an InputStream as a String allowing for different encoding types. This closes the stream at the end. </p> @param inputStream The input stream @param connection The HTTP connection object @return A String representation of the input stream @throws IOException If something goes wrong """ if (inputStream == null) { return null; } BufferedReader reader = null; try { String responseEncoding = getResponseEncoding(connection); if (izGzipped(connection)) { inputStream = new GZIPInputStream(inputStream); } final InputStreamReader in = responseEncoding != null ? new InputStreamReader(inputStream, responseEncoding) : new InputStreamReader(inputStream, CHARSET_UTF_8); reader = new BufferedReader(in); StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } return sb.toString(); } finally { inputStream.close(); if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } }
java
String readInputStreamAsEncodedString(InputStream inputStream, HttpURLConnection connection) throws IOException { if (inputStream == null) { return null; } BufferedReader reader = null; try { String responseEncoding = getResponseEncoding(connection); if (izGzipped(connection)) { inputStream = new GZIPInputStream(inputStream); } final InputStreamReader in = responseEncoding != null ? new InputStreamReader(inputStream, responseEncoding) : new InputStreamReader(inputStream, CHARSET_UTF_8); reader = new BufferedReader(in); StringBuilder sb = new StringBuilder(); for (String line; (line = reader.readLine()) != null; ) { sb.append(line); } return sb.toString(); } finally { inputStream.close(); if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } }
[ "String", "readInputStreamAsEncodedString", "(", "InputStream", "inputStream", ",", "HttpURLConnection", "connection", ")", "throws", "IOException", "{", "if", "(", "inputStream", "==", "null", ")", "{", "return", "null", ";", "}", "BufferedReader", "reader", "=", "null", ";", "try", "{", "String", "responseEncoding", "=", "getResponseEncoding", "(", "connection", ")", ";", "if", "(", "izGzipped", "(", "connection", ")", ")", "{", "inputStream", "=", "new", "GZIPInputStream", "(", "inputStream", ")", ";", "}", "final", "InputStreamReader", "in", "=", "responseEncoding", "!=", "null", "?", "new", "InputStreamReader", "(", "inputStream", ",", "responseEncoding", ")", ":", "new", "InputStreamReader", "(", "inputStream", ",", "CHARSET_UTF_8", ")", ";", "reader", "=", "new", "BufferedReader", "(", "in", ")", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "for", "(", "String", "line", ";", "(", "line", "=", "reader", ".", "readLine", "(", ")", ")", "!=", "null", ";", ")", "{", "sb", ".", "append", "(", "line", ")", ";", "}", "return", "sb", ".", "toString", "(", ")", ";", "}", "finally", "{", "inputStream", ".", "close", "(", ")", ";", "if", "(", "reader", "!=", "null", ")", "{", "try", "{", "reader", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "ignore", ")", "{", "}", "}", "}", "}" ]
<p> Reads an InputStream as a String allowing for different encoding types. This closes the stream at the end. </p> @param inputStream The input stream @param connection The HTTP connection object @return A String representation of the input stream @throws IOException If something goes wrong
[ "<p", ">", "Reads", "an", "InputStream", "as", "a", "String", "allowing", "for", "different", "encoding", "types", ".", "This", "closes", "the", "stream", "at", "the", "end", ".", "<", "/", "p", ">" ]
train
https://github.com/mmazi/rescu/blob/8a4f9367994da0a2617bd37acf0320c942e62de3/src/main/java/si/mazi/rescu/HttpTemplate.java#L216-L241
aNNiMON/Lightweight-Stream-API
stream/src/main/java/com/annimon/stream/Collectors.java
Collectors.summingInt
@NotNull public static <T> Collector<T, ?, Integer> summingInt(@NotNull final ToIntFunction<? super T> mapper) { """ Returns a {@code Collector} that summing integer-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3 """ return new CollectorsImpl<T, int[], Integer>( new Supplier<int[]>() { @NotNull @Override public int[] get() { return new int[] { 0 }; } }, new BiConsumer<int[], T>() { @Override public void accept(int[] t, T u) { t[0] += mapper.applyAsInt(u); } }, new Function<int[], Integer>() { @Override public Integer apply(int[] value) { return value[0]; } } ); }
java
@NotNull public static <T> Collector<T, ?, Integer> summingInt(@NotNull final ToIntFunction<? super T> mapper) { return new CollectorsImpl<T, int[], Integer>( new Supplier<int[]>() { @NotNull @Override public int[] get() { return new int[] { 0 }; } }, new BiConsumer<int[], T>() { @Override public void accept(int[] t, T u) { t[0] += mapper.applyAsInt(u); } }, new Function<int[], Integer>() { @Override public Integer apply(int[] value) { return value[0]; } } ); }
[ "@", "NotNull", "public", "static", "<", "T", ">", "Collector", "<", "T", ",", "?", ",", "Integer", ">", "summingInt", "(", "@", "NotNull", "final", "ToIntFunction", "<", "?", "super", "T", ">", "mapper", ")", "{", "return", "new", "CollectorsImpl", "<", "T", ",", "int", "[", "]", ",", "Integer", ">", "(", "new", "Supplier", "<", "int", "[", "]", ">", "(", ")", "{", "@", "NotNull", "@", "Override", "public", "int", "[", "]", "get", "(", ")", "{", "return", "new", "int", "[", "]", "{", "0", "}", ";", "}", "}", ",", "new", "BiConsumer", "<", "int", "[", "]", ",", "T", ">", "(", ")", "{", "@", "Override", "public", "void", "accept", "(", "int", "[", "]", "t", ",", "T", "u", ")", "{", "t", "[", "0", "]", "+=", "mapper", ".", "applyAsInt", "(", "u", ")", ";", "}", "}", ",", "new", "Function", "<", "int", "[", "]", ",", "Integer", ">", "(", ")", "{", "@", "Override", "public", "Integer", "apply", "(", "int", "[", "]", "value", ")", "{", "return", "value", "[", "0", "]", ";", "}", "}", ")", ";", "}" ]
Returns a {@code Collector} that summing integer-valued input elements. @param <T> the type of the input elements @param mapper the mapping function which extracts value from element to calculate result @return a {@code Collector} @since 1.1.3
[ "Returns", "a", "{", "@code", "Collector", "}", "that", "summing", "integer", "-", "valued", "input", "elements", "." ]
train
https://github.com/aNNiMON/Lightweight-Stream-API/blob/f29fd57208c20252a4549b084d55ed082c3e58f0/stream/src/main/java/com/annimon/stream/Collectors.java#L577-L603
Whiley/WhileyCompiler
src/main/java/wyil/transform/VerificationConditionGenerator.java
VerificationConditionGenerator.translateSingleAssignment
private Context translateSingleAssignment(WyilFile.LVal lval, Expr rval, Context context) { """ Translate an individual assignment from one rval to exactly one lval. @param lval A single location representing the left-hand side @param rval A single expression representing the right-hand side @param context @return """ // FIXME: this method is a bit of a kludge. It would be nicer, // eventually, to have all right-hand side expression represented in // WyTP directly. This could potentially be done by including an update // operation in WyTP ... ? switch (lval.getOpcode()) { case WyilFile.EXPR_arrayaccess: case WyilFile.EXPR_arrayborrow: return translateArrayAssign((WyilFile.Expr.ArrayAccess) lval, rval, context); case WyilFile.EXPR_dereference: return translateDereference((WyilFile.Expr.Dereference) lval, rval, context); case WyilFile.EXPR_recordaccess: case WyilFile.EXPR_recordborrow: return translateRecordAssign((WyilFile.Expr.RecordAccess) lval, rval, context); case WyilFile.EXPR_variablemove: case WyilFile.EXPR_variablecopy: return translateVariableAssign((WyilFile.Expr.VariableAccess) lval, rval, context); default: throw new SyntacticException("unknown lval encountered (" + lval + ")", context.getEnclosingFile().getEntry(), lval); } }
java
private Context translateSingleAssignment(WyilFile.LVal lval, Expr rval, Context context) { // FIXME: this method is a bit of a kludge. It would be nicer, // eventually, to have all right-hand side expression represented in // WyTP directly. This could potentially be done by including an update // operation in WyTP ... ? switch (lval.getOpcode()) { case WyilFile.EXPR_arrayaccess: case WyilFile.EXPR_arrayborrow: return translateArrayAssign((WyilFile.Expr.ArrayAccess) lval, rval, context); case WyilFile.EXPR_dereference: return translateDereference((WyilFile.Expr.Dereference) lval, rval, context); case WyilFile.EXPR_recordaccess: case WyilFile.EXPR_recordborrow: return translateRecordAssign((WyilFile.Expr.RecordAccess) lval, rval, context); case WyilFile.EXPR_variablemove: case WyilFile.EXPR_variablecopy: return translateVariableAssign((WyilFile.Expr.VariableAccess) lval, rval, context); default: throw new SyntacticException("unknown lval encountered (" + lval + ")", context.getEnclosingFile().getEntry(), lval); } }
[ "private", "Context", "translateSingleAssignment", "(", "WyilFile", ".", "LVal", "lval", ",", "Expr", "rval", ",", "Context", "context", ")", "{", "// FIXME: this method is a bit of a kludge. It would be nicer,", "// eventually, to have all right-hand side expression represented in", "// WyTP directly. This could potentially be done by including an update", "// operation in WyTP ... ?", "switch", "(", "lval", ".", "getOpcode", "(", ")", ")", "{", "case", "WyilFile", ".", "EXPR_arrayaccess", ":", "case", "WyilFile", ".", "EXPR_arrayborrow", ":", "return", "translateArrayAssign", "(", "(", "WyilFile", ".", "Expr", ".", "ArrayAccess", ")", "lval", ",", "rval", ",", "context", ")", ";", "case", "WyilFile", ".", "EXPR_dereference", ":", "return", "translateDereference", "(", "(", "WyilFile", ".", "Expr", ".", "Dereference", ")", "lval", ",", "rval", ",", "context", ")", ";", "case", "WyilFile", ".", "EXPR_recordaccess", ":", "case", "WyilFile", ".", "EXPR_recordborrow", ":", "return", "translateRecordAssign", "(", "(", "WyilFile", ".", "Expr", ".", "RecordAccess", ")", "lval", ",", "rval", ",", "context", ")", ";", "case", "WyilFile", ".", "EXPR_variablemove", ":", "case", "WyilFile", ".", "EXPR_variablecopy", ":", "return", "translateVariableAssign", "(", "(", "WyilFile", ".", "Expr", ".", "VariableAccess", ")", "lval", ",", "rval", ",", "context", ")", ";", "default", ":", "throw", "new", "SyntacticException", "(", "\"unknown lval encountered (\"", "+", "lval", "+", "\")\"", ",", "context", ".", "getEnclosingFile", "(", ")", ".", "getEntry", "(", ")", ",", "lval", ")", ";", "}", "}" ]
Translate an individual assignment from one rval to exactly one lval. @param lval A single location representing the left-hand side @param rval A single expression representing the right-hand side @param context @return
[ "Translate", "an", "individual", "assignment", "from", "one", "rval", "to", "exactly", "one", "lval", "." ]
train
https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L585-L608
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/FormattedWriter.java
FormattedWriter.taggedValue
public final void taggedValue(String tag, long value) throws IOException { """ Write out a one-line XML tag with a long datatype, for instance &lttag&gt123456&lt/tag&gt @param tag The name of the tag to be written @param value The data value to be written @throws IOException If an I/O error occurs while attempting to write the characters """ startTag(tag); write(Long.toString(value)); endTag(tag); }
java
public final void taggedValue(String tag, long value) throws IOException { startTag(tag); write(Long.toString(value)); endTag(tag); }
[ "public", "final", "void", "taggedValue", "(", "String", "tag", ",", "long", "value", ")", "throws", "IOException", "{", "startTag", "(", "tag", ")", ";", "write", "(", "Long", ".", "toString", "(", "value", ")", ")", ";", "endTag", "(", "tag", ")", ";", "}" ]
Write out a one-line XML tag with a long datatype, for instance &lttag&gt123456&lt/tag&gt @param tag The name of the tag to be written @param value The data value to be written @throws IOException If an I/O error occurs while attempting to write the characters
[ "Write", "out", "a", "one", "-", "line", "XML", "tag", "with", "a", "long", "datatype", "for", "instance", "&lttag&gt123456&lt", "/", "tag&gt" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.utils/src/com/ibm/ws/sib/utils/ras/FormattedWriter.java#L212-L216
hal/core
gui/src/main/java/org/jboss/as/console/server/proxy/HttpClient.java
HttpClient.doPost
public InputStream doPost(byte[] postData, String contentType) { """ posts data to the inputstream and returns the InputStream. @param postData data to be posted. must be url-encoded already. @param contentType allows you to set the contentType of the request. @return InputStream input stream from URLConnection """ this.urlConnection.setDoOutput(true); if (contentType != null) this.urlConnection.setRequestProperty( "Content-type", contentType ); OutputStream out = null; try { out = this.getOutputStream(); if(out!=null) { out.write(postData); out.flush(); } } catch (IOException e) { e.printStackTrace(); }finally { if(out!=null) try { out.close(); } catch (IOException e) { // } } return (this.getInputStream()); }
java
public InputStream doPost(byte[] postData, String contentType) { this.urlConnection.setDoOutput(true); if (contentType != null) this.urlConnection.setRequestProperty( "Content-type", contentType ); OutputStream out = null; try { out = this.getOutputStream(); if(out!=null) { out.write(postData); out.flush(); } } catch (IOException e) { e.printStackTrace(); }finally { if(out!=null) try { out.close(); } catch (IOException e) { // } } return (this.getInputStream()); }
[ "public", "InputStream", "doPost", "(", "byte", "[", "]", "postData", ",", "String", "contentType", ")", "{", "this", ".", "urlConnection", ".", "setDoOutput", "(", "true", ")", ";", "if", "(", "contentType", "!=", "null", ")", "this", ".", "urlConnection", ".", "setRequestProperty", "(", "\"Content-type\"", ",", "contentType", ")", ";", "OutputStream", "out", "=", "null", ";", "try", "{", "out", "=", "this", ".", "getOutputStream", "(", ")", ";", "if", "(", "out", "!=", "null", ")", "{", "out", ".", "write", "(", "postData", ")", ";", "out", ".", "flush", "(", ")", ";", "}", "}", "catch", "(", "IOException", "e", ")", "{", "e", ".", "printStackTrace", "(", ")", ";", "}", "finally", "{", "if", "(", "out", "!=", "null", ")", "try", "{", "out", ".", "close", "(", ")", ";", "}", "catch", "(", "IOException", "e", ")", "{", "//", "}", "}", "return", "(", "this", ".", "getInputStream", "(", ")", ")", ";", "}" ]
posts data to the inputstream and returns the InputStream. @param postData data to be posted. must be url-encoded already. @param contentType allows you to set the contentType of the request. @return InputStream input stream from URLConnection
[ "posts", "data", "to", "the", "inputstream", "and", "returns", "the", "InputStream", "." ]
train
https://github.com/hal/core/blob/d6d03f0bb128dc0470f5dc75fdb1ea1014400602/gui/src/main/java/org/jboss/as/console/server/proxy/HttpClient.java#L315-L340
looly/hutool
hutool-core/src/main/java/cn/hutool/core/convert/Convert.java
Convert.hexStrToStr
@Deprecated public static String hexStrToStr(String hexStr, Charset charset) { """ 十六进制转换字符串 @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B]) @param charset 编码 {@link Charset} @return 对应的字符串 @see HexUtil#decodeHexStr(String, Charset) @deprecated 请使用 {@link #hexToStr(String, Charset)} """ return hexToStr(hexStr, charset); }
java
@Deprecated public static String hexStrToStr(String hexStr, Charset charset) { return hexToStr(hexStr, charset); }
[ "@", "Deprecated", "public", "static", "String", "hexStrToStr", "(", "String", "hexStr", ",", "Charset", "charset", ")", "{", "return", "hexToStr", "(", "hexStr", ",", "charset", ")", ";", "}" ]
十六进制转换字符串 @param hexStr Byte字符串(Byte之间无分隔符 如:[616C6B]) @param charset 编码 {@link Charset} @return 对应的字符串 @see HexUtil#decodeHexStr(String, Charset) @deprecated 请使用 {@link #hexToStr(String, Charset)}
[ "十六进制转换字符串" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/convert/Convert.java#L730-L733
square/burst
burst/src/main/java/com/squareup/burst/BurstableConstructor.java
BurstableConstructor.findAll
private static TestConstructor[] findAll(Class<?> cls) { """ Finds all constructors of {@code cls} that are burstable. A burstable constructor is public, and may or may not be the default constructor. @throws IllegalStateException if cls has public fields and a non-default constructor """ final Constructor<?>[] constructors = cls.getConstructors(); final Field[] fields = getBurstableFields(cls); final List<TestConstructor> filteredConstructors = new ArrayList<>(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0 && fields.length > 0) { throw new IllegalStateException( "Class " + cls.getName() + " has a parameterized constructor, so cannot also be parameterized on fields"); } filteredConstructors.add(new TestConstructor(constructor, fields)); } return filteredConstructors.toArray(new TestConstructor[filteredConstructors.size()]); }
java
private static TestConstructor[] findAll(Class<?> cls) { final Constructor<?>[] constructors = cls.getConstructors(); final Field[] fields = getBurstableFields(cls); final List<TestConstructor> filteredConstructors = new ArrayList<>(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length > 0 && fields.length > 0) { throw new IllegalStateException( "Class " + cls.getName() + " has a parameterized constructor, so cannot also be parameterized on fields"); } filteredConstructors.add(new TestConstructor(constructor, fields)); } return filteredConstructors.toArray(new TestConstructor[filteredConstructors.size()]); }
[ "private", "static", "TestConstructor", "[", "]", "findAll", "(", "Class", "<", "?", ">", "cls", ")", "{", "final", "Constructor", "<", "?", ">", "[", "]", "constructors", "=", "cls", ".", "getConstructors", "(", ")", ";", "final", "Field", "[", "]", "fields", "=", "getBurstableFields", "(", "cls", ")", ";", "final", "List", "<", "TestConstructor", ">", "filteredConstructors", "=", "new", "ArrayList", "<>", "(", ")", ";", "for", "(", "Constructor", "<", "?", ">", "constructor", ":", "constructors", ")", "{", "if", "(", "constructor", ".", "getParameterTypes", "(", ")", ".", "length", ">", "0", "&&", "fields", ".", "length", ">", "0", ")", "{", "throw", "new", "IllegalStateException", "(", "\"Class \"", "+", "cls", ".", "getName", "(", ")", "+", "\" has a parameterized constructor, so cannot also be parameterized on fields\"", ")", ";", "}", "filteredConstructors", ".", "add", "(", "new", "TestConstructor", "(", "constructor", ",", "fields", ")", ")", ";", "}", "return", "filteredConstructors", ".", "toArray", "(", "new", "TestConstructor", "[", "filteredConstructors", ".", "size", "(", ")", "]", ")", ";", "}" ]
Finds all constructors of {@code cls} that are burstable. A burstable constructor is public, and may or may not be the default constructor. @throws IllegalStateException if cls has public fields and a non-default constructor
[ "Finds", "all", "constructors", "of", "{", "@code", "cls", "}", "that", "are", "burstable", ".", "A", "burstable", "constructor", "is", "public", "and", "may", "or", "may", "not", "be", "the", "default", "constructor", "." ]
train
https://github.com/square/burst/blob/20cdb4473896143402f92e11cf03d236fcbe3f12/burst/src/main/java/com/squareup/burst/BurstableConstructor.java#L41-L58
Azure/azure-sdk-for-java
cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java
ModelsImpl.updatePatternAnyEntityRole
public OperationStatus updatePatternAnyEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId, UpdatePatternAnyEntityRoleOptionalParameter updatePatternAnyEntityRoleOptionalParameter) { """ Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updatePatternAnyEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful. """ return updatePatternAnyEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updatePatternAnyEntityRoleOptionalParameter).toBlocking().single().body(); }
java
public OperationStatus updatePatternAnyEntityRole(UUID appId, String versionId, UUID entityId, UUID roleId, UpdatePatternAnyEntityRoleOptionalParameter updatePatternAnyEntityRoleOptionalParameter) { return updatePatternAnyEntityRoleWithServiceResponseAsync(appId, versionId, entityId, roleId, updatePatternAnyEntityRoleOptionalParameter).toBlocking().single().body(); }
[ "public", "OperationStatus", "updatePatternAnyEntityRole", "(", "UUID", "appId", ",", "String", "versionId", ",", "UUID", "entityId", ",", "UUID", "roleId", ",", "UpdatePatternAnyEntityRoleOptionalParameter", "updatePatternAnyEntityRoleOptionalParameter", ")", "{", "return", "updatePatternAnyEntityRoleWithServiceResponseAsync", "(", "appId", ",", "versionId", ",", "entityId", ",", "roleId", ",", "updatePatternAnyEntityRoleOptionalParameter", ")", ".", "toBlocking", "(", ")", ".", "single", "(", ")", ".", "body", "(", ")", ";", "}" ]
Update an entity role for a given entity. @param appId The application ID. @param versionId The version ID. @param entityId The entity ID. @param roleId The entity role ID. @param updatePatternAnyEntityRoleOptionalParameter the object representing the optional parameters to be set before calling this API @throws IllegalArgumentException thrown if parameters fail the validation @throws ErrorResponseException thrown if the request is rejected by server @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent @return the OperationStatus object if successful.
[ "Update", "an", "entity", "role", "for", "a", "given", "entity", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L12857-L12859
cdapio/netty-http
src/main/java/io/cdap/http/internal/HttpResourceHandler.java
HttpResourceHandler.getWeightedMatchScore
private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) { """ Generate a weighted score based on position for matches of URI parts. The matches are weighted in descending order from left to right. Exact match is weighted higher than group match, and group match is weighted higher than wildcard match. @param requestUriParts the parts of request URI @param destUriParts the parts of destination URI @return weighted score """ // The score calculated below is a base 5 number // The score will have one digit for one part of the URI // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13 // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during // score calculation long score = 0; for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator(); rit.hasNext() && dit.hasNext(); ) { String requestPart = rit.next(); String destPart = dit.next(); if (requestPart.equals(destPart)) { score = (score * 5) + 4; } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) { score = (score * 5) + 3; } else { score = (score * 5) + 2; } } return score; }
java
private long getWeightedMatchScore(Iterable<String> requestUriParts, Iterable<String> destUriParts) { // The score calculated below is a base 5 number // The score will have one digit for one part of the URI // This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13 // We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during // score calculation long score = 0; for (Iterator<String> rit = requestUriParts.iterator(), dit = destUriParts.iterator(); rit.hasNext() && dit.hasNext(); ) { String requestPart = rit.next(); String destPart = dit.next(); if (requestPart.equals(destPart)) { score = (score * 5) + 4; } else if (PatternPathRouterWithGroups.GROUP_PATTERN.matcher(destPart).matches()) { score = (score * 5) + 3; } else { score = (score * 5) + 2; } } return score; }
[ "private", "long", "getWeightedMatchScore", "(", "Iterable", "<", "String", ">", "requestUriParts", ",", "Iterable", "<", "String", ">", "destUriParts", ")", "{", "// The score calculated below is a base 5 number", "// The score will have one digit for one part of the URI", "// This will allow for 27 parts in the path since log (Long.MAX_VALUE) to base 5 = 27.13", "// We limit the number of parts in the path to 25 using MAX_PATH_PARTS constant above to avoid overflow during", "// score calculation", "long", "score", "=", "0", ";", "for", "(", "Iterator", "<", "String", ">", "rit", "=", "requestUriParts", ".", "iterator", "(", ")", ",", "dit", "=", "destUriParts", ".", "iterator", "(", ")", ";", "rit", ".", "hasNext", "(", ")", "&&", "dit", ".", "hasNext", "(", ")", ";", ")", "{", "String", "requestPart", "=", "rit", ".", "next", "(", ")", ";", "String", "destPart", "=", "dit", ".", "next", "(", ")", ";", "if", "(", "requestPart", ".", "equals", "(", "destPart", ")", ")", "{", "score", "=", "(", "score", "*", "5", ")", "+", "4", ";", "}", "else", "if", "(", "PatternPathRouterWithGroups", ".", "GROUP_PATTERN", ".", "matcher", "(", "destPart", ")", ".", "matches", "(", ")", ")", "{", "score", "=", "(", "score", "*", "5", ")", "+", "3", ";", "}", "else", "{", "score", "=", "(", "score", "*", "5", ")", "+", "2", ";", "}", "}", "return", "score", ";", "}" ]
Generate a weighted score based on position for matches of URI parts. The matches are weighted in descending order from left to right. Exact match is weighted higher than group match, and group match is weighted higher than wildcard match. @param requestUriParts the parts of request URI @param destUriParts the parts of destination URI @return weighted score
[ "Generate", "a", "weighted", "score", "based", "on", "position", "for", "matches", "of", "URI", "parts", ".", "The", "matches", "are", "weighted", "in", "descending", "order", "from", "left", "to", "right", ".", "Exact", "match", "is", "weighted", "higher", "than", "group", "match", "and", "group", "match", "is", "weighted", "higher", "than", "wildcard", "match", "." ]
train
https://github.com/cdapio/netty-http/blob/02fdbb45bdd51d3dd58c0efbb2f27195d265cd0f/src/main/java/io/cdap/http/internal/HttpResourceHandler.java#L352-L372
xerial/snappy-java
src/main/java/org/xerial/snappy/Snappy.java
Snappy.rawUncompress
public static long rawUncompress(long inputAddr, long inputSize, long destAddr) throws IOException { """ Zero-copy decompress using memory addresses. @param inputAddr input memory address @param inputSize input byte size @param destAddr destination address of the uncompressed data @return the uncompressed data size @throws IOException """ return impl.rawUncompress(inputAddr, inputSize, destAddr); }
java
public static long rawUncompress(long inputAddr, long inputSize, long destAddr) throws IOException { return impl.rawUncompress(inputAddr, inputSize, destAddr); }
[ "public", "static", "long", "rawUncompress", "(", "long", "inputAddr", ",", "long", "inputSize", ",", "long", "destAddr", ")", "throws", "IOException", "{", "return", "impl", ".", "rawUncompress", "(", "inputAddr", ",", "inputSize", ",", "destAddr", ")", ";", "}" ]
Zero-copy decompress using memory addresses. @param inputAddr input memory address @param inputSize input byte size @param destAddr destination address of the uncompressed data @return the uncompressed data size @throws IOException
[ "Zero", "-", "copy", "decompress", "using", "memory", "addresses", "." ]
train
https://github.com/xerial/snappy-java/blob/9df6ed7bbce88186c82f2e7cdcb7b974421b3340/src/main/java/org/xerial/snappy/Snappy.java#L403-L407
apache/groovy
subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java
DateTimeExtensions.leftShift
public static OffsetDateTime leftShift(final OffsetTime self, LocalDate date) { """ Returns an {@link java.time.OffsetDateTime} of this time and the provided {@link java.time.LocalDate}. @param self an OffsetTime @param date a LocalDate @return an OffsetDateTime @since 2.5.0 """ return OffsetDateTime.of(date, self.toLocalTime(), self.getOffset()); }
java
public static OffsetDateTime leftShift(final OffsetTime self, LocalDate date) { return OffsetDateTime.of(date, self.toLocalTime(), self.getOffset()); }
[ "public", "static", "OffsetDateTime", "leftShift", "(", "final", "OffsetTime", "self", ",", "LocalDate", "date", ")", "{", "return", "OffsetDateTime", ".", "of", "(", "date", ",", "self", ".", "toLocalTime", "(", ")", ",", "self", ".", "getOffset", "(", ")", ")", ";", "}" ]
Returns an {@link java.time.OffsetDateTime} of this time and the provided {@link java.time.LocalDate}. @param self an OffsetTime @param date a LocalDate @return an OffsetDateTime @since 2.5.0
[ "Returns", "an", "{", "@link", "java", ".", "time", ".", "OffsetDateTime", "}", "of", "this", "time", "and", "the", "provided", "{", "@link", "java", ".", "time", ".", "LocalDate", "}", "." ]
train
https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/subprojects/groovy-datetime/src/main/java/org/apache/groovy/datetime/extensions/DateTimeExtensions.java#L1262-L1264
atomix/atomix
protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java
RaftServiceContext.keepAliveSessions
public void keepAliveSessions(long index, long timestamp) { """ Keeps all sessions alive using the given timestamp. @param index the index of the timestamp @param timestamp the timestamp with which to reset session timeouts """ log.debug("Resetting session timeouts"); this.currentIndex = index; this.currentTimestamp = Math.max(currentTimestamp, timestamp); for (RaftSession session : sessions.getSessions(primitiveId)) { session.setLastUpdated(timestamp); } }
java
public void keepAliveSessions(long index, long timestamp) { log.debug("Resetting session timeouts"); this.currentIndex = index; this.currentTimestamp = Math.max(currentTimestamp, timestamp); for (RaftSession session : sessions.getSessions(primitiveId)) { session.setLastUpdated(timestamp); } }
[ "public", "void", "keepAliveSessions", "(", "long", "index", ",", "long", "timestamp", ")", "{", "log", ".", "debug", "(", "\"Resetting session timeouts\"", ")", ";", "this", ".", "currentIndex", "=", "index", ";", "this", ".", "currentTimestamp", "=", "Math", ".", "max", "(", "currentTimestamp", ",", "timestamp", ")", ";", "for", "(", "RaftSession", "session", ":", "sessions", ".", "getSessions", "(", "primitiveId", ")", ")", "{", "session", ".", "setLastUpdated", "(", "timestamp", ")", ";", "}", "}" ]
Keeps all sessions alive using the given timestamp. @param index the index of the timestamp @param timestamp the timestamp with which to reset session timeouts
[ "Keeps", "all", "sessions", "alive", "using", "the", "given", "timestamp", "." ]
train
https://github.com/atomix/atomix/blob/3a94b7c80576d762dd0d396d4645df07a0b37c31/protocols/raft/src/main/java/io/atomix/protocols/raft/service/RaftServiceContext.java#L423-L432
eldur/jwbf
src/main/java/net/sourceforge/jwbf/mediawiki/actions/queries/OldreviewedPagesTitles.java
OldreviewedPagesTitles.generateRequest
private HttpAction generateRequest(int[] namespace, String orstart, String orend) { """ generates the next MediaWiki-request (GetMethod) and adds it to msgs. @param namespace the namespace(s) that will be searched for links, as a string of numbers separated by '|'; if null, this parameter is omitted @param orstart Start listing at this timestamp @param orend Stop listing at this timestamp """ RequestBuilder requestBuilder = new ApiRequestBuilder() // .action("query") // .formatXml() // .param("list", "oldreviewedpages") // .param("orlimit", LIMIT) // ; if (namespace != null) { String ornamespace = MediaWiki.urlEncode(MWAction.createNsString(namespace)); requestBuilder.param("ornamespace", ornamespace); } if (orstart.length() > 0) { requestBuilder.param("orstart", orstart); } if (orend.length() > 0) { requestBuilder.param("orend", orend); } return requestBuilder.buildGet(); }
java
private HttpAction generateRequest(int[] namespace, String orstart, String orend) { RequestBuilder requestBuilder = new ApiRequestBuilder() // .action("query") // .formatXml() // .param("list", "oldreviewedpages") // .param("orlimit", LIMIT) // ; if (namespace != null) { String ornamespace = MediaWiki.urlEncode(MWAction.createNsString(namespace)); requestBuilder.param("ornamespace", ornamespace); } if (orstart.length() > 0) { requestBuilder.param("orstart", orstart); } if (orend.length() > 0) { requestBuilder.param("orend", orend); } return requestBuilder.buildGet(); }
[ "private", "HttpAction", "generateRequest", "(", "int", "[", "]", "namespace", ",", "String", "orstart", ",", "String", "orend", ")", "{", "RequestBuilder", "requestBuilder", "=", "new", "ApiRequestBuilder", "(", ")", "//", ".", "action", "(", "\"query\"", ")", "//", ".", "formatXml", "(", ")", "//", ".", "param", "(", "\"list\"", ",", "\"oldreviewedpages\"", ")", "//", ".", "param", "(", "\"orlimit\"", ",", "LIMIT", ")", "//", ";", "if", "(", "namespace", "!=", "null", ")", "{", "String", "ornamespace", "=", "MediaWiki", ".", "urlEncode", "(", "MWAction", ".", "createNsString", "(", "namespace", ")", ")", ";", "requestBuilder", ".", "param", "(", "\"ornamespace\"", ",", "ornamespace", ")", ";", "}", "if", "(", "orstart", ".", "length", "(", ")", ">", "0", ")", "{", "requestBuilder", ".", "param", "(", "\"orstart\"", ",", "orstart", ")", ";", "}", "if", "(", "orend", ".", "length", "(", ")", ">", "0", ")", "{", "requestBuilder", ".", "param", "(", "\"orend\"", ",", "orend", ")", ";", "}", "return", "requestBuilder", ".", "buildGet", "(", ")", ";", "}" ]
generates the next MediaWiki-request (GetMethod) and adds it to msgs. @param namespace the namespace(s) that will be searched for links, as a string of numbers separated by '|'; if null, this parameter is omitted @param orstart Start listing at this timestamp @param orend Stop listing at this timestamp
[ "generates", "the", "next", "MediaWiki", "-", "request", "(", "GetMethod", ")", "and", "adds", "it", "to", "msgs", "." ]
train
https://github.com/eldur/jwbf/blob/ee17ea2fa5a26f17c8332a094b2db86dd596d1ff/src/main/java/net/sourceforge/jwbf/mediawiki/actions/queries/OldreviewedPagesTitles.java#L59-L80
matthewhorridge/owlapi-gwt
owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataExactCardinalityImpl_CustomFieldSerializer.java
OWLDataExactCardinalityImpl_CustomFieldSerializer.serializeInstance
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataExactCardinalityImpl instance) throws SerializationException { """ Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful """ serialize(streamWriter, instance); }
java
@Override public void serializeInstance(SerializationStreamWriter streamWriter, OWLDataExactCardinalityImpl instance) throws SerializationException { serialize(streamWriter, instance); }
[ "@", "Override", "public", "void", "serializeInstance", "(", "SerializationStreamWriter", "streamWriter", ",", "OWLDataExactCardinalityImpl", "instance", ")", "throws", "SerializationException", "{", "serialize", "(", "streamWriter", ",", "instance", ")", ";", "}" ]
Serializes the content of the object into the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter}. @param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the object's content to @param instance the object instance to serialize @throws com.google.gwt.user.client.rpc.SerializationException if the serialization operation is not successful
[ "Serializes", "the", "content", "of", "the", "object", "into", "the", "{", "@link", "com", ".", "google", ".", "gwt", ".", "user", ".", "client", ".", "rpc", ".", "SerializationStreamWriter", "}", "." ]
train
https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/uk/ac/manchester/cs/owl/owlapi/OWLDataExactCardinalityImpl_CustomFieldSerializer.java#L73-L76
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/io/stream/StreamHelper.java
StreamHelper.writeStream
@Nonnull public static ESuccess writeStream (@WillClose @Nonnull final OutputStream aOS, @Nonnull final String sContent, @Nonnull final Charset aCharset) { """ Write bytes to an {@link OutputStream}. @param aOS The output stream to write to. May not be <code>null</code>. Is closed independent of error or success. @param sContent The string to be written. May not be <code>null</code>. @param aCharset The charset to be used, to convert the String to a byte array. @return {@link ESuccess} """ ValueEnforcer.notNull (sContent, "Content"); ValueEnforcer.notNull (aCharset, "Charset"); return writeStream (aOS, sContent.getBytes (aCharset)); }
java
@Nonnull public static ESuccess writeStream (@WillClose @Nonnull final OutputStream aOS, @Nonnull final String sContent, @Nonnull final Charset aCharset) { ValueEnforcer.notNull (sContent, "Content"); ValueEnforcer.notNull (aCharset, "Charset"); return writeStream (aOS, sContent.getBytes (aCharset)); }
[ "@", "Nonnull", "public", "static", "ESuccess", "writeStream", "(", "@", "WillClose", "@", "Nonnull", "final", "OutputStream", "aOS", ",", "@", "Nonnull", "final", "String", "sContent", ",", "@", "Nonnull", "final", "Charset", "aCharset", ")", "{", "ValueEnforcer", ".", "notNull", "(", "sContent", ",", "\"Content\"", ")", ";", "ValueEnforcer", ".", "notNull", "(", "aCharset", ",", "\"Charset\"", ")", ";", "return", "writeStream", "(", "aOS", ",", "sContent", ".", "getBytes", "(", "aCharset", ")", ")", ";", "}" ]
Write bytes to an {@link OutputStream}. @param aOS The output stream to write to. May not be <code>null</code>. Is closed independent of error or success. @param sContent The string to be written. May not be <code>null</code>. @param aCharset The charset to be used, to convert the String to a byte array. @return {@link ESuccess}
[ "Write", "bytes", "to", "an", "{", "@link", "OutputStream", "}", "." ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/io/stream/StreamHelper.java#L1321-L1330
looly/hutool
hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java
FileWriter.writeLines
public <T> File writeLines(Collection<T> list) throws IORuntimeException { """ 将列表写入文件,覆盖模式 @param <T> 集合元素类型 @param list 列表 @return 目标文件 @throws IORuntimeException IO异常 """ return writeLines(list, false); }
java
public <T> File writeLines(Collection<T> list) throws IORuntimeException { return writeLines(list, false); }
[ "public", "<", "T", ">", "File", "writeLines", "(", "Collection", "<", "T", ">", "list", ")", "throws", "IORuntimeException", "{", "return", "writeLines", "(", "list", ",", "false", ")", ";", "}" ]
将列表写入文件,覆盖模式 @param <T> 集合元素类型 @param list 列表 @return 目标文件 @throws IORuntimeException IO异常
[ "将列表写入文件,覆盖模式" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/file/FileWriter.java#L157-L159
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/operators/windowing/KeyMap.java
KeyMap.putOrAggregate
public final V putOrAggregate(K key, V value, ReduceFunction<V> aggregator) throws Exception { """ Inserts or aggregates a value into the hash map. If the hash map does not yet contain the key, this method inserts the value. If the table already contains the key (and a value) this method will use the given ReduceFunction function to combine the existing value and the given value to a new value, and store that value for the key. @param key The key to map the value. @param value The new value to insert, or aggregate with the existing value. @param aggregator The aggregator to use if a value is already contained. @return The value in the map after this operation: Either the given value, or the aggregated value. @throws java.lang.NullPointerException Thrown, if the key is null. @throws Exception The method forwards exceptions from the aggregation function. """ final int hash = hash(key); final int slot = indexOf(hash); // search the chain from the slot for (Entry<K, V> entry = table[slot]; entry != null; entry = entry.next) { if (entry.hashCode == hash && entry.key.equals(key)) { // found match entry.value = aggregator.reduce(entry.value, value); return entry.value; } } // no match, insert a new value insertNewEntry(hash, key, value, slot); // return the original value return value; }
java
public final V putOrAggregate(K key, V value, ReduceFunction<V> aggregator) throws Exception { final int hash = hash(key); final int slot = indexOf(hash); // search the chain from the slot for (Entry<K, V> entry = table[slot]; entry != null; entry = entry.next) { if (entry.hashCode == hash && entry.key.equals(key)) { // found match entry.value = aggregator.reduce(entry.value, value); return entry.value; } } // no match, insert a new value insertNewEntry(hash, key, value, slot); // return the original value return value; }
[ "public", "final", "V", "putOrAggregate", "(", "K", "key", ",", "V", "value", ",", "ReduceFunction", "<", "V", ">", "aggregator", ")", "throws", "Exception", "{", "final", "int", "hash", "=", "hash", "(", "key", ")", ";", "final", "int", "slot", "=", "indexOf", "(", "hash", ")", ";", "// search the chain from the slot", "for", "(", "Entry", "<", "K", ",", "V", ">", "entry", "=", "table", "[", "slot", "]", ";", "entry", "!=", "null", ";", "entry", "=", "entry", ".", "next", ")", "{", "if", "(", "entry", ".", "hashCode", "==", "hash", "&&", "entry", ".", "key", ".", "equals", "(", "key", ")", ")", "{", "// found match", "entry", ".", "value", "=", "aggregator", ".", "reduce", "(", "entry", ".", "value", ",", "value", ")", ";", "return", "entry", ".", "value", ";", "}", "}", "// no match, insert a new value", "insertNewEntry", "(", "hash", ",", "key", ",", "value", ",", "slot", ")", ";", "// return the original value", "return", "value", ";", "}" ]
Inserts or aggregates a value into the hash map. If the hash map does not yet contain the key, this method inserts the value. If the table already contains the key (and a value) this method will use the given ReduceFunction function to combine the existing value and the given value to a new value, and store that value for the key. @param key The key to map the value. @param value The new value to insert, or aggregate with the existing value. @param aggregator The aggregator to use if a value is already contained. @return The value in the map after this operation: Either the given value, or the aggregated value. @throws java.lang.NullPointerException Thrown, if the key is null. @throws Exception The method forwards exceptions from the aggregation function.
[ "Inserts", "or", "aggregates", "a", "value", "into", "the", "hash", "map", ".", "If", "the", "hash", "map", "does", "not", "yet", "contain", "the", "key", "this", "method", "inserts", "the", "value", ".", "If", "the", "table", "already", "contains", "the", "key", "(", "and", "a", "value", ")", "this", "method", "will", "use", "the", "given", "ReduceFunction", "function", "to", "combine", "the", "existing", "value", "and", "the", "given", "value", "to", "a", "new", "value", "and", "store", "that", "value", "for", "the", "key", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/runtime/operators/windowing/KeyMap.java#L192-L209
BranchMetrics/android-branch-deep-linking
Branch-SDK/src/io/branch/referral/network/BranchRemoteInterface.java
BranchRemoteInterface.make_restful_post
public final ServerResponse make_restful_post(JSONObject body, String url, String tag, String branchKey) { """ Method for handling the RESTful POST operations to Branch Servers. Internally calls abstract method {@link #doRestfulPost(String, JSONObject)} @param url The url end point @param body {@link JSONObject with parameters to the POST call} @param tag {@link String} Tag for identifying the request for analytical or debugging purpose @param branchKey {@link String} Branch key @return {@link ServerResponse} object representing the result of RESTful POST to Branch Server """ long reqStartTime = System.currentTimeMillis(); body = body != null ? body : new JSONObject(); if (!addCommonParams(body, branchKey)) { return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID); } PrefHelper.Debug("posting to " + url); PrefHelper.Debug("Post value = " + body.toString()); try { BranchResponse response = doRestfulPost(url, body); return processEntityForJSON(response.responseData, response.responseCode, tag); } catch (BranchRemoteException branchError) { if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) { return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT); } else { // All other errors are considered as connectivity error return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY); } } finally { if (Branch.getInstance() != null) { int brttVal = (int) (System.currentTimeMillis() - reqStartTime); Branch.getInstance().addExtraInstrumentationData(tag + "-" + Defines.Jsonkey.Branch_Round_Trip_Time.getKey(), String.valueOf(brttVal)); } } }
java
public final ServerResponse make_restful_post(JSONObject body, String url, String tag, String branchKey) { long reqStartTime = System.currentTimeMillis(); body = body != null ? body : new JSONObject(); if (!addCommonParams(body, branchKey)) { return new ServerResponse(tag, BranchError.ERR_BRANCH_KEY_INVALID); } PrefHelper.Debug("posting to " + url); PrefHelper.Debug("Post value = " + body.toString()); try { BranchResponse response = doRestfulPost(url, body); return processEntityForJSON(response.responseData, response.responseCode, tag); } catch (BranchRemoteException branchError) { if (branchError.branchErrorCode == BranchError.ERR_BRANCH_REQ_TIMED_OUT) { return new ServerResponse(tag, BranchError.ERR_BRANCH_REQ_TIMED_OUT); } else { // All other errors are considered as connectivity error return new ServerResponse(tag, BranchError.ERR_BRANCH_NO_CONNECTIVITY); } } finally { if (Branch.getInstance() != null) { int brttVal = (int) (System.currentTimeMillis() - reqStartTime); Branch.getInstance().addExtraInstrumentationData(tag + "-" + Defines.Jsonkey.Branch_Round_Trip_Time.getKey(), String.valueOf(brttVal)); } } }
[ "public", "final", "ServerResponse", "make_restful_post", "(", "JSONObject", "body", ",", "String", "url", ",", "String", "tag", ",", "String", "branchKey", ")", "{", "long", "reqStartTime", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "body", "=", "body", "!=", "null", "?", "body", ":", "new", "JSONObject", "(", ")", ";", "if", "(", "!", "addCommonParams", "(", "body", ",", "branchKey", ")", ")", "{", "return", "new", "ServerResponse", "(", "tag", ",", "BranchError", ".", "ERR_BRANCH_KEY_INVALID", ")", ";", "}", "PrefHelper", ".", "Debug", "(", "\"posting to \"", "+", "url", ")", ";", "PrefHelper", ".", "Debug", "(", "\"Post value = \"", "+", "body", ".", "toString", "(", ")", ")", ";", "try", "{", "BranchResponse", "response", "=", "doRestfulPost", "(", "url", ",", "body", ")", ";", "return", "processEntityForJSON", "(", "response", ".", "responseData", ",", "response", ".", "responseCode", ",", "tag", ")", ";", "}", "catch", "(", "BranchRemoteException", "branchError", ")", "{", "if", "(", "branchError", ".", "branchErrorCode", "==", "BranchError", ".", "ERR_BRANCH_REQ_TIMED_OUT", ")", "{", "return", "new", "ServerResponse", "(", "tag", ",", "BranchError", ".", "ERR_BRANCH_REQ_TIMED_OUT", ")", ";", "}", "else", "{", "// All other errors are considered as connectivity error", "return", "new", "ServerResponse", "(", "tag", ",", "BranchError", ".", "ERR_BRANCH_NO_CONNECTIVITY", ")", ";", "}", "}", "finally", "{", "if", "(", "Branch", ".", "getInstance", "(", ")", "!=", "null", ")", "{", "int", "brttVal", "=", "(", "int", ")", "(", "System", ".", "currentTimeMillis", "(", ")", "-", "reqStartTime", ")", ";", "Branch", ".", "getInstance", "(", ")", ".", "addExtraInstrumentationData", "(", "tag", "+", "\"-\"", "+", "Defines", ".", "Jsonkey", ".", "Branch_Round_Trip_Time", ".", "getKey", "(", ")", ",", "String", ".", "valueOf", "(", "brttVal", ")", ")", ";", "}", "}", "}" ]
Method for handling the RESTful POST operations to Branch Servers. Internally calls abstract method {@link #doRestfulPost(String, JSONObject)} @param url The url end point @param body {@link JSONObject with parameters to the POST call} @param tag {@link String} Tag for identifying the request for analytical or debugging purpose @param branchKey {@link String} Branch key @return {@link ServerResponse} object representing the result of RESTful POST to Branch Server
[ "Method", "for", "handling", "the", "RESTful", "POST", "operations", "to", "Branch", "Servers", ".", "Internally", "calls", "abstract", "method", "{", "@link", "#doRestfulPost", "(", "String", "JSONObject", ")", "}" ]
train
https://github.com/BranchMetrics/android-branch-deep-linking/blob/e3bee2ccfcbf6d4bf1a5815b5b86666e4ff8f848/Branch-SDK/src/io/branch/referral/network/BranchRemoteInterface.java#L125-L150
blinkfox/zealot
src/main/java/com/blinkfox/zealot/core/ZealotKhala.java
ZealotKhala.orLikePattern
public ZealotKhala orLikePattern(String field, String pattern) { """ 根据指定的模式字符串生成带" OR "前缀的like模糊查询的SQL片段. <p>示例:传入 {"b.title", "Java%"} 两个参数,生成的SQL片段为:" OR b.title LIKE 'Java%' "</p> @param field 数据库字段 @param pattern 模式字符串 @return ZealotKhala实例 """ return this.doLikePattern(ZealotConst.OR_PREFIX, field, pattern, true, true); }
java
public ZealotKhala orLikePattern(String field, String pattern) { return this.doLikePattern(ZealotConst.OR_PREFIX, field, pattern, true, true); }
[ "public", "ZealotKhala", "orLikePattern", "(", "String", "field", ",", "String", "pattern", ")", "{", "return", "this", ".", "doLikePattern", "(", "ZealotConst", ".", "OR_PREFIX", ",", "field", ",", "pattern", ",", "true", ",", "true", ")", ";", "}" ]
根据指定的模式字符串生成带" OR "前缀的like模糊查询的SQL片段. <p>示例:传入 {"b.title", "Java%"} 两个参数,生成的SQL片段为:" OR b.title LIKE 'Java%' "</p> @param field 数据库字段 @param pattern 模式字符串 @return ZealotKhala实例
[ "根据指定的模式字符串生成带", "OR", "前缀的like模糊查询的SQL片段", ".", "<p", ">", "示例:传入", "{", "b", ".", "title", "Java%", "}", "两个参数,生成的SQL片段为:", "OR", "b", ".", "title", "LIKE", "Java%", "<", "/", "p", ">" ]
train
https://github.com/blinkfox/zealot/blob/21b00fa3e4ed42188eef3116d494e112e7a4194c/src/main/java/com/blinkfox/zealot/core/ZealotKhala.java#L1092-L1094
UrielCh/ovh-java-sdk
ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java
ApiOvhMe.xdsl_setting_GET
public OvhSetting xdsl_setting_GET() throws IOException { """ Get xdsl settings linked to the nichandle REST: GET /me/xdsl/setting """ String qPath = "/me/xdsl/setting"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSetting.class); }
java
public OvhSetting xdsl_setting_GET() throws IOException { String qPath = "/me/xdsl/setting"; StringBuilder sb = path(qPath); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo(resp, OvhSetting.class); }
[ "public", "OvhSetting", "xdsl_setting_GET", "(", ")", "throws", "IOException", "{", "String", "qPath", "=", "\"/me/xdsl/setting\"", ";", "StringBuilder", "sb", "=", "path", "(", "qPath", ")", ";", "String", "resp", "=", "exec", "(", "qPath", ",", "\"GET\"", ",", "sb", ".", "toString", "(", ")", ",", "null", ")", ";", "return", "convertTo", "(", "resp", ",", "OvhSetting", ".", "class", ")", ";", "}" ]
Get xdsl settings linked to the nichandle REST: GET /me/xdsl/setting
[ "Get", "xdsl", "settings", "linked", "to", "the", "nichandle" ]
train
https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L2167-L2172
google/j2objc
xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/Function2Args.java
Function2Args.fixupVariables
public void fixupVariables(java.util.Vector vars, int globalsSize) { """ This function is used to fixup variables from QNames to stack frame indexes at stylesheet build time. @param vars List of QNames that correspond to variables. This list should be searched backwards for the first qualified name that corresponds to the variable reference qname. The position of the QName in the vector from the start of the vector will be its position in the stack frame (but variables above the globalsTop value will need to be offset to the current stack frame). """ super.fixupVariables(vars, globalsSize); if(null != m_arg1) m_arg1.fixupVariables(vars, globalsSize); }
java
public void fixupVariables(java.util.Vector vars, int globalsSize) { super.fixupVariables(vars, globalsSize); if(null != m_arg1) m_arg1.fixupVariables(vars, globalsSize); }
[ "public", "void", "fixupVariables", "(", "java", ".", "util", ".", "Vector", "vars", ",", "int", "globalsSize", ")", "{", "super", ".", "fixupVariables", "(", "vars", ",", "globalsSize", ")", ";", "if", "(", "null", "!=", "m_arg1", ")", "m_arg1", ".", "fixupVariables", "(", "vars", ",", "globalsSize", ")", ";", "}" ]
This function is used to fixup variables from QNames to stack frame indexes at stylesheet build time. @param vars List of QNames that correspond to variables. This list should be searched backwards for the first qualified name that corresponds to the variable reference qname. The position of the QName in the vector from the start of the vector will be its position in the stack frame (but variables above the globalsTop value will need to be offset to the current stack frame).
[ "This", "function", "is", "used", "to", "fixup", "variables", "from", "QNames", "to", "stack", "frame", "indexes", "at", "stylesheet", "build", "time", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/functions/Function2Args.java#L61-L66
exoplatform/jcr
exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/registry/RegistryService.java
RegistryService.checkGroup
private void checkGroup(final SessionProvider sessionProvider, final String groupPath) throws RepositoryException { """ check if group exists and creates one if necessary @param sessionProvider @param groupPath @throws RepositoryException """ String[] groupNames = groupPath.split("/"); String prefix = "/" + EXO_REGISTRY; Session session = session(sessionProvider, repositoryService.getCurrentRepository()); for (String name : groupNames) { String path = prefix + "/" + name; try { Node group = (Node)session.getItem(path); if (!group.isNodeType(EXO_REGISTRYGROUP_NT)) throw new RepositoryException("Node at " + path + " should be " + EXO_REGISTRYGROUP_NT + " type"); } catch (PathNotFoundException e) { Node parent = (Node)session.getItem(prefix); parent.addNode(name, EXO_REGISTRYGROUP_NT); parent.save(); } prefix = path; } }
java
private void checkGroup(final SessionProvider sessionProvider, final String groupPath) throws RepositoryException { String[] groupNames = groupPath.split("/"); String prefix = "/" + EXO_REGISTRY; Session session = session(sessionProvider, repositoryService.getCurrentRepository()); for (String name : groupNames) { String path = prefix + "/" + name; try { Node group = (Node)session.getItem(path); if (!group.isNodeType(EXO_REGISTRYGROUP_NT)) throw new RepositoryException("Node at " + path + " should be " + EXO_REGISTRYGROUP_NT + " type"); } catch (PathNotFoundException e) { Node parent = (Node)session.getItem(prefix); parent.addNode(name, EXO_REGISTRYGROUP_NT); parent.save(); } prefix = path; } }
[ "private", "void", "checkGroup", "(", "final", "SessionProvider", "sessionProvider", ",", "final", "String", "groupPath", ")", "throws", "RepositoryException", "{", "String", "[", "]", "groupNames", "=", "groupPath", ".", "split", "(", "\"/\"", ")", ";", "String", "prefix", "=", "\"/\"", "+", "EXO_REGISTRY", ";", "Session", "session", "=", "session", "(", "sessionProvider", ",", "repositoryService", ".", "getCurrentRepository", "(", ")", ")", ";", "for", "(", "String", "name", ":", "groupNames", ")", "{", "String", "path", "=", "prefix", "+", "\"/\"", "+", "name", ";", "try", "{", "Node", "group", "=", "(", "Node", ")", "session", ".", "getItem", "(", "path", ")", ";", "if", "(", "!", "group", ".", "isNodeType", "(", "EXO_REGISTRYGROUP_NT", ")", ")", "throw", "new", "RepositoryException", "(", "\"Node at \"", "+", "path", "+", "\" should be \"", "+", "EXO_REGISTRYGROUP_NT", "+", "\" type\"", ")", ";", "}", "catch", "(", "PathNotFoundException", "e", ")", "{", "Node", "parent", "=", "(", "Node", ")", "session", ".", "getItem", "(", "prefix", ")", ";", "parent", ".", "addNode", "(", "name", ",", "EXO_REGISTRYGROUP_NT", ")", ";", "parent", ".", "save", "(", ")", ";", "}", "prefix", "=", "path", ";", "}", "}" ]
check if group exists and creates one if necessary @param sessionProvider @param groupPath @throws RepositoryException
[ "check", "if", "group", "exists", "and", "creates", "one", "if", "necessary" ]
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/registry/RegistryService.java#L647-L669
Azure/azure-sdk-for-java
sql/resource-manager/v2014_04_01/src/main/java/com/microsoft/azure/management/sql/v2014_04_01/implementation/ServersInner.java
ServersInner.createOrUpdateAsync
public Observable<ServerInner> createOrUpdateAsync(String resourceGroupName, String serverName, ServerInner parameters) { """ Creates or updates a new server. @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 parameters The required parameters for creating or updating a server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerInner object """ return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() { @Override public ServerInner call(ServiceResponse<ServerInner> response) { return response.body(); } }); }
java
public Observable<ServerInner> createOrUpdateAsync(String resourceGroupName, String serverName, ServerInner parameters) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, parameters).map(new Func1<ServiceResponse<ServerInner>, ServerInner>() { @Override public ServerInner call(ServiceResponse<ServerInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "ServerInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "serverName", ",", "ServerInner", "parameters", ")", "{", "return", "createOrUpdateWithServiceResponseAsync", "(", "resourceGroupName", ",", "serverName", ",", "parameters", ")", ".", "map", "(", "new", "Func1", "<", "ServiceResponse", "<", "ServerInner", ">", ",", "ServerInner", ">", "(", ")", "{", "@", "Override", "public", "ServerInner", "call", "(", "ServiceResponse", "<", "ServerInner", ">", "response", ")", "{", "return", "response", ".", "body", "(", ")", ";", "}", "}", ")", ";", "}" ]
Creates or updates a new server. @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 parameters The required parameters for creating or updating a server. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the ServerInner object
[ "Creates", "or", "updates", "a", "new", "server", "." ]
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/ServersInner.java#L298-L305
calrissian/mango
mango-core/src/main/java/org/calrissian/mango/io/Serializables.java
Serializables.deserialize
public static <T extends Serializable> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { """ Utility for returning a Serializable object from a byte array. """ return deserialize(bytes, false); }
java
public static <T extends Serializable> T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { return deserialize(bytes, false); }
[ "public", "static", "<", "T", "extends", "Serializable", ">", "T", "deserialize", "(", "byte", "[", "]", "bytes", ")", "throws", "IOException", ",", "ClassNotFoundException", "{", "return", "deserialize", "(", "bytes", ",", "false", ")", ";", "}" ]
Utility for returning a Serializable object from a byte array.
[ "Utility", "for", "returning", "a", "Serializable", "object", "from", "a", "byte", "array", "." ]
train
https://github.com/calrissian/mango/blob/a95aa5e77af9aa0e629787228d80806560023452/mango-core/src/main/java/org/calrissian/mango/io/Serializables.java#L58-L60
leancloud/java-sdk-all
realtime/src/main/java/cn/leancloud/im/v2/AVIMConversation.java
AVIMConversation.queryMessagesByType
public void queryMessagesByType(int msgType, final String msgId, final long timestamp, final int limit, final AVIMMessagesQueryCallback callback) { """ 获取特定类型的历史消息。 注意:这个操作总是会从云端获取记录。 另,如果不指定 msgId 和 timestamp,则该函数效果等同于 queryMessageByType(type, limit, callback) @param msgType 消息类型,可以参看 `AVIMMessageType` 里的定义。 @param msgId 消息id,从特定消息 id 开始向前查询(结果不会包含该记录) @param timestamp 查询起始的时间戳,返回小于这个时间的记录,必须配合 msgId 一起使用。 要从最新消息开始获取时,请用 0 代替客户端的本地当前时间(System.currentTimeMillis()) @param limit 返回条数限制 @param callback 结果回调函数 """ if (null == callback) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.PARAM_MESSAGE_QUERY_MSGID, msgId); params.put(Conversation.PARAM_MESSAGE_QUERY_TIMESTAMP, timestamp); params.put(Conversation.PARAM_MESSAGE_QUERY_STARTCLOSED, false); params.put(Conversation.PARAM_MESSAGE_QUERY_TO_MSGID, ""); params.put(Conversation.PARAM_MESSAGE_QUERY_TO_TIMESTAMP, 0); params.put(Conversation.PARAM_MESSAGE_QUERY_TOCLOSED, false); params.put(Conversation.PARAM_MESSAGE_QUERY_DIRECT, AVIMMessageQueryDirection.AVIMMessageQueryDirectionFromNewToOld.getCode()); params.put(Conversation.PARAM_MESSAGE_QUERY_LIMIT, limit); params.put(Conversation.PARAM_MESSAGE_QUERY_TYPE, msgType); boolean ret = InternalConfiguration.getOperationTube().queryMessages(this.client.getClientId(), getConversationId(), getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_MESSAGE_QUERY, callback); if (!ret) { callback.internalDone(new AVException(AVException.OPERATION_FORBIDDEN, "couldn't send request in background.")); } }
java
public void queryMessagesByType(int msgType, final String msgId, final long timestamp, final int limit, final AVIMMessagesQueryCallback callback) { if (null == callback) { return; } Map<String, Object> params = new HashMap<String, Object>(); params.put(Conversation.PARAM_MESSAGE_QUERY_MSGID, msgId); params.put(Conversation.PARAM_MESSAGE_QUERY_TIMESTAMP, timestamp); params.put(Conversation.PARAM_MESSAGE_QUERY_STARTCLOSED, false); params.put(Conversation.PARAM_MESSAGE_QUERY_TO_MSGID, ""); params.put(Conversation.PARAM_MESSAGE_QUERY_TO_TIMESTAMP, 0); params.put(Conversation.PARAM_MESSAGE_QUERY_TOCLOSED, false); params.put(Conversation.PARAM_MESSAGE_QUERY_DIRECT, AVIMMessageQueryDirection.AVIMMessageQueryDirectionFromNewToOld.getCode()); params.put(Conversation.PARAM_MESSAGE_QUERY_LIMIT, limit); params.put(Conversation.PARAM_MESSAGE_QUERY_TYPE, msgType); boolean ret = InternalConfiguration.getOperationTube().queryMessages(this.client.getClientId(), getConversationId(), getType(), JSON.toJSONString(params), Conversation.AVIMOperation.CONVERSATION_MESSAGE_QUERY, callback); if (!ret) { callback.internalDone(new AVException(AVException.OPERATION_FORBIDDEN, "couldn't send request in background.")); } }
[ "public", "void", "queryMessagesByType", "(", "int", "msgType", ",", "final", "String", "msgId", ",", "final", "long", "timestamp", ",", "final", "int", "limit", ",", "final", "AVIMMessagesQueryCallback", "callback", ")", "{", "if", "(", "null", "==", "callback", ")", "{", "return", ";", "}", "Map", "<", "String", ",", "Object", ">", "params", "=", "new", "HashMap", "<", "String", ",", "Object", ">", "(", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_MSGID", ",", "msgId", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_TIMESTAMP", ",", "timestamp", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_STARTCLOSED", ",", "false", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_TO_MSGID", ",", "\"\"", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_TO_TIMESTAMP", ",", "0", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_TOCLOSED", ",", "false", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_DIRECT", ",", "AVIMMessageQueryDirection", ".", "AVIMMessageQueryDirectionFromNewToOld", ".", "getCode", "(", ")", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_LIMIT", ",", "limit", ")", ";", "params", ".", "put", "(", "Conversation", ".", "PARAM_MESSAGE_QUERY_TYPE", ",", "msgType", ")", ";", "boolean", "ret", "=", "InternalConfiguration", ".", "getOperationTube", "(", ")", ".", "queryMessages", "(", "this", ".", "client", ".", "getClientId", "(", ")", ",", "getConversationId", "(", ")", ",", "getType", "(", ")", ",", "JSON", ".", "toJSONString", "(", "params", ")", ",", "Conversation", ".", "AVIMOperation", ".", "CONVERSATION_MESSAGE_QUERY", ",", "callback", ")", ";", "if", "(", "!", "ret", ")", "{", "callback", ".", "internalDone", "(", "new", "AVException", "(", "AVException", ".", "OPERATION_FORBIDDEN", ",", "\"couldn't send request in background.\"", ")", ")", ";", "}", "}" ]
获取特定类型的历史消息。 注意:这个操作总是会从云端获取记录。 另,如果不指定 msgId 和 timestamp,则该函数效果等同于 queryMessageByType(type, limit, callback) @param msgType 消息类型,可以参看 `AVIMMessageType` 里的定义。 @param msgId 消息id,从特定消息 id 开始向前查询(结果不会包含该记录) @param timestamp 查询起始的时间戳,返回小于这个时间的记录,必须配合 msgId 一起使用。 要从最新消息开始获取时,请用 0 代替客户端的本地当前时间(System.currentTimeMillis()) @param limit 返回条数限制 @param callback 结果回调函数
[ "获取特定类型的历史消息。", "注意:这个操作总是会从云端获取记录。", "另,如果不指定", "msgId", "和", "timestamp,则该函数效果等同于", "queryMessageByType", "(", "type", "limit", "callback", ")" ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/realtime/src/main/java/cn/leancloud/im/v2/AVIMConversation.java#L803-L824
ops4j/org.ops4j.pax.logging
pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java
PaxPropertySetter.setProperty
public void setProperty(String name, String value) { """ Set a property on this PaxPropertySetter's Object. If successful, this method will invoke a setter method on the underlying Object. The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method. <p>If the setter expects a String no conversion is necessary. If it expects an int, then an attempt is made to convert 'value' to an int using new Integer(value). If the setter expects a boolean, the conversion is by new Boolean(value). @param name name of the property @param value String value of the property """ if (value == null) return; name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); //LogLog.debug("---------Key: "+name+", type="+prop.getPropertyType()); if (prop == null) { LogLog.warn("No such property [" + name + "] in "+ obj.getClass().getName()+"." ); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { LogLog.warn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex.rootCause); } } }
java
public void setProperty(String name, String value) { if (value == null) return; name = Introspector.decapitalize(name); PropertyDescriptor prop = getPropertyDescriptor(name); //LogLog.debug("---------Key: "+name+", type="+prop.getPropertyType()); if (prop == null) { LogLog.warn("No such property [" + name + "] in "+ obj.getClass().getName()+"." ); } else { try { setProperty(prop, name, value); } catch (PropertySetterException ex) { LogLog.warn("Failed to set property [" + name + "] to value \"" + value + "\". ", ex.rootCause); } } }
[ "public", "void", "setProperty", "(", "String", "name", ",", "String", "value", ")", "{", "if", "(", "value", "==", "null", ")", "return", ";", "name", "=", "Introspector", ".", "decapitalize", "(", "name", ")", ";", "PropertyDescriptor", "prop", "=", "getPropertyDescriptor", "(", "name", ")", ";", "//LogLog.debug(\"---------Key: \"+name+\", type=\"+prop.getPropertyType());", "if", "(", "prop", "==", "null", ")", "{", "LogLog", ".", "warn", "(", "\"No such property [\"", "+", "name", "+", "\"] in \"", "+", "obj", ".", "getClass", "(", ")", ".", "getName", "(", ")", "+", "\".\"", ")", ";", "}", "else", "{", "try", "{", "setProperty", "(", "prop", ",", "name", ",", "value", ")", ";", "}", "catch", "(", "PropertySetterException", "ex", ")", "{", "LogLog", ".", "warn", "(", "\"Failed to set property [\"", "+", "name", "+", "\"] to value \\\"\"", "+", "value", "+", "\"\\\". \"", ",", "ex", ".", "rootCause", ")", ";", "}", "}", "}" ]
Set a property on this PaxPropertySetter's Object. If successful, this method will invoke a setter method on the underlying Object. The setter is the one for the specified property name and the value is determined partly from the setter argument type and partly from the value specified in the call to this method. <p>If the setter expects a String no conversion is necessary. If it expects an int, then an attempt is made to convert 'value' to an int using new Integer(value). If the setter expects a boolean, the conversion is by new Boolean(value). @param name name of the property @param value String value of the property
[ "Set", "a", "property", "on", "this", "PaxPropertySetter", "s", "Object", ".", "If", "successful", "this", "method", "will", "invoke", "a", "setter", "method", "on", "the", "underlying", "Object", ".", "The", "setter", "is", "the", "one", "for", "the", "specified", "property", "name", "and", "the", "value", "is", "determined", "partly", "from", "the", "setter", "argument", "type", "and", "partly", "from", "the", "value", "specified", "in", "the", "call", "to", "this", "method", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/config/PaxPropertySetter.java#L255-L275
evernote/evernote-sdk-android
library/src/main/java/com/evernote/client/android/EvernoteUtil.java
EvernoteUtil.hash
public static byte[] hash(InputStream in) throws IOException { """ Returns an MD5 checksum of the contents of the provided InputStream. """ if (HASH_DIGEST == null) { throw new EvernoteUtilException(EDAM_HASH_ALGORITHM + " not supported", new NoSuchAlgorithmException(EDAM_HASH_ALGORITHM)); } byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) != -1) { HASH_DIGEST.update(buf, 0, n); } return HASH_DIGEST.digest(); }
java
public static byte[] hash(InputStream in) throws IOException { if (HASH_DIGEST == null) { throw new EvernoteUtilException(EDAM_HASH_ALGORITHM + " not supported", new NoSuchAlgorithmException(EDAM_HASH_ALGORITHM)); } byte[] buf = new byte[1024]; int n; while ((n = in.read(buf)) != -1) { HASH_DIGEST.update(buf, 0, n); } return HASH_DIGEST.digest(); }
[ "public", "static", "byte", "[", "]", "hash", "(", "InputStream", "in", ")", "throws", "IOException", "{", "if", "(", "HASH_DIGEST", "==", "null", ")", "{", "throw", "new", "EvernoteUtilException", "(", "EDAM_HASH_ALGORITHM", "+", "\" not supported\"", ",", "new", "NoSuchAlgorithmException", "(", "EDAM_HASH_ALGORITHM", ")", ")", ";", "}", "byte", "[", "]", "buf", "=", "new", "byte", "[", "1024", "]", ";", "int", "n", ";", "while", "(", "(", "n", "=", "in", ".", "read", "(", "buf", ")", ")", "!=", "-", "1", ")", "{", "HASH_DIGEST", ".", "update", "(", "buf", ",", "0", ",", "n", ")", ";", "}", "return", "HASH_DIGEST", ".", "digest", "(", ")", ";", "}" ]
Returns an MD5 checksum of the contents of the provided InputStream.
[ "Returns", "an", "MD5", "checksum", "of", "the", "contents", "of", "the", "provided", "InputStream", "." ]
train
https://github.com/evernote/evernote-sdk-android/blob/fc59be643e85c4f59d562d1bfe76563997aa73cf/library/src/main/java/com/evernote/client/android/EvernoteUtil.java#L142-L153
prometheus/jmx_exporter
jmx_prometheus_javaagent/src/main/java/io/prometheus/jmx/JavaAgent.java
JavaAgent.parseConfig
public static Config parseConfig(String args, String ifc) { """ Parse the Java Agent configuration. The arguments are typically specified to the JVM as a javaagent as {@code -javaagent:/path/to/agent.jar=<CONFIG>}. This method parses the {@code <CONFIG>} portion. @param args provided agent args @param ifc default bind interface @return configuration to use for our application """ Pattern pattern = Pattern.compile( "^(?:((?:[\\w.]+)|(?:\\[.+])):)?" + // host name, or ipv4, or ipv6 address in brackets "(\\d{1,5}):" + // port "(.+)"); // config file Matcher matcher = pattern.matcher(args); if (!matcher.matches()) { throw new IllegalArgumentException("Malformed arguments - " + args); } String givenHost = matcher.group(1); String givenPort = matcher.group(2); String givenConfigFile = matcher.group(3); int port = Integer.parseInt(givenPort); InetSocketAddress socket; if (givenHost != null && !givenHost.isEmpty()) { socket = new InetSocketAddress(givenHost, port); } else { socket = new InetSocketAddress(ifc, port); givenHost = ifc; } return new Config(givenHost, port, givenConfigFile, socket); }
java
public static Config parseConfig(String args, String ifc) { Pattern pattern = Pattern.compile( "^(?:((?:[\\w.]+)|(?:\\[.+])):)?" + // host name, or ipv4, or ipv6 address in brackets "(\\d{1,5}):" + // port "(.+)"); // config file Matcher matcher = pattern.matcher(args); if (!matcher.matches()) { throw new IllegalArgumentException("Malformed arguments - " + args); } String givenHost = matcher.group(1); String givenPort = matcher.group(2); String givenConfigFile = matcher.group(3); int port = Integer.parseInt(givenPort); InetSocketAddress socket; if (givenHost != null && !givenHost.isEmpty()) { socket = new InetSocketAddress(givenHost, port); } else { socket = new InetSocketAddress(ifc, port); givenHost = ifc; } return new Config(givenHost, port, givenConfigFile, socket); }
[ "public", "static", "Config", "parseConfig", "(", "String", "args", ",", "String", "ifc", ")", "{", "Pattern", "pattern", "=", "Pattern", ".", "compile", "(", "\"^(?:((?:[\\\\w.]+)|(?:\\\\[.+])):)?\"", "+", "// host name, or ipv4, or ipv6 address in brackets", "\"(\\\\d{1,5}):\"", "+", "// port", "\"(.+)\"", ")", ";", "// config file", "Matcher", "matcher", "=", "pattern", ".", "matcher", "(", "args", ")", ";", "if", "(", "!", "matcher", ".", "matches", "(", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"Malformed arguments - \"", "+", "args", ")", ";", "}", "String", "givenHost", "=", "matcher", ".", "group", "(", "1", ")", ";", "String", "givenPort", "=", "matcher", ".", "group", "(", "2", ")", ";", "String", "givenConfigFile", "=", "matcher", ".", "group", "(", "3", ")", ";", "int", "port", "=", "Integer", ".", "parseInt", "(", "givenPort", ")", ";", "InetSocketAddress", "socket", ";", "if", "(", "givenHost", "!=", "null", "&&", "!", "givenHost", ".", "isEmpty", "(", ")", ")", "{", "socket", "=", "new", "InetSocketAddress", "(", "givenHost", ",", "port", ")", ";", "}", "else", "{", "socket", "=", "new", "InetSocketAddress", "(", "ifc", ",", "port", ")", ";", "givenHost", "=", "ifc", ";", "}", "return", "new", "Config", "(", "givenHost", ",", "port", ",", "givenConfigFile", ",", "socket", ")", ";", "}" ]
Parse the Java Agent configuration. The arguments are typically specified to the JVM as a javaagent as {@code -javaagent:/path/to/agent.jar=<CONFIG>}. This method parses the {@code <CONFIG>} portion. @param args provided agent args @param ifc default bind interface @return configuration to use for our application
[ "Parse", "the", "Java", "Agent", "configuration", ".", "The", "arguments", "are", "typically", "specified", "to", "the", "JVM", "as", "a", "javaagent", "as", "{" ]
train
https://github.com/prometheus/jmx_exporter/blob/6a8d92c580b93d62a1a9183cbb7cb1a3b19a8473/jmx_prometheus_javaagent/src/main/java/io/prometheus/jmx/JavaAgent.java#L46-L73
eurekaclinical/protempa
protempa-framework/src/main/java/org/protempa/PropositionCopier.java
PropositionCopier.visit
@Override public void visit(AbstractParameter abstractParameter) { """ Creates a derived abstract parameter with the id specified in the constructor and the same characteristics (e.g., data source type, interval, value, etc.). @param abstractParameter an {@link AbstractParameter}. Cannot be <code>null</code>. """ assert this.kh != null : "kh wasn't set"; AbstractParameter param = new AbstractParameter(propId, this.uniqueIdProvider.getInstance()); param.setSourceSystem(SourceSystem.DERIVED); param.setInterval(abstractParameter.getInterval()); param.setValue(abstractParameter.getValue()); param.setCreateDate(new Date()); this.kh.insertLogical(param); this.derivationsBuilder.propositionAsserted(abstractParameter, param); LOGGER.log(Level.FINER, "Asserted derived proposition {0}", param); }
java
@Override public void visit(AbstractParameter abstractParameter) { assert this.kh != null : "kh wasn't set"; AbstractParameter param = new AbstractParameter(propId, this.uniqueIdProvider.getInstance()); param.setSourceSystem(SourceSystem.DERIVED); param.setInterval(abstractParameter.getInterval()); param.setValue(abstractParameter.getValue()); param.setCreateDate(new Date()); this.kh.insertLogical(param); this.derivationsBuilder.propositionAsserted(abstractParameter, param); LOGGER.log(Level.FINER, "Asserted derived proposition {0}", param); }
[ "@", "Override", "public", "void", "visit", "(", "AbstractParameter", "abstractParameter", ")", "{", "assert", "this", ".", "kh", "!=", "null", ":", "\"kh wasn't set\"", ";", "AbstractParameter", "param", "=", "new", "AbstractParameter", "(", "propId", ",", "this", ".", "uniqueIdProvider", ".", "getInstance", "(", ")", ")", ";", "param", ".", "setSourceSystem", "(", "SourceSystem", ".", "DERIVED", ")", ";", "param", ".", "setInterval", "(", "abstractParameter", ".", "getInterval", "(", ")", ")", ";", "param", ".", "setValue", "(", "abstractParameter", ".", "getValue", "(", ")", ")", ";", "param", ".", "setCreateDate", "(", "new", "Date", "(", ")", ")", ";", "this", ".", "kh", ".", "insertLogical", "(", "param", ")", ";", "this", ".", "derivationsBuilder", ".", "propositionAsserted", "(", "abstractParameter", ",", "param", ")", ";", "LOGGER", ".", "log", "(", "Level", ".", "FINER", ",", "\"Asserted derived proposition {0}\"", ",", "param", ")", ";", "}" ]
Creates a derived abstract parameter with the id specified in the constructor and the same characteristics (e.g., data source type, interval, value, etc.). @param abstractParameter an {@link AbstractParameter}. Cannot be <code>null</code>.
[ "Creates", "a", "derived", "abstract", "parameter", "with", "the", "id", "specified", "in", "the", "constructor", "and", "the", "same", "characteristics", "(", "e", ".", "g", ".", "data", "source", "type", "interval", "value", "etc", ".", ")", "." ]
train
https://github.com/eurekaclinical/protempa/blob/5a620d1a407c7a5426d1cf17d47b97717cf71634/protempa-framework/src/main/java/org/protempa/PropositionCopier.java#L116-L127
VoltDB/voltdb
src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/pool/WrapperInvocationHandler.java
WrapperInvocationHandler.getDatabaseMetaDataSurrogate
protected Object getDatabaseMetaDataSurrogate(final Method method, final Object[] args) throws Throwable { """ Surrogate for any method of the delegate that returns an instance of <tt>DatabaseMetaData</tt> object. <p> @param method returning <tt>DatabaseMetaData</tt> @param args to the method @throws java.lang.Throwable the exception, if any, thrown by invoking the given method with the given arguments upon the delegate @return surrogate for the underlying DatabaseMetaData object """ if (this.dbmdHandler == null) { Object dbmd = method.invoke(this.delegate, args); this.dbmdHandler = new WrapperInvocationHandler(dbmd, this); } return this.dbmdHandler.surrogate; }
java
protected Object getDatabaseMetaDataSurrogate(final Method method, final Object[] args) throws Throwable { if (this.dbmdHandler == null) { Object dbmd = method.invoke(this.delegate, args); this.dbmdHandler = new WrapperInvocationHandler(dbmd, this); } return this.dbmdHandler.surrogate; }
[ "protected", "Object", "getDatabaseMetaDataSurrogate", "(", "final", "Method", "method", ",", "final", "Object", "[", "]", "args", ")", "throws", "Throwable", "{", "if", "(", "this", ".", "dbmdHandler", "==", "null", ")", "{", "Object", "dbmd", "=", "method", ".", "invoke", "(", "this", ".", "delegate", ",", "args", ")", ";", "this", ".", "dbmdHandler", "=", "new", "WrapperInvocationHandler", "(", "dbmd", ",", "this", ")", ";", "}", "return", "this", ".", "dbmdHandler", ".", "surrogate", ";", "}" ]
Surrogate for any method of the delegate that returns an instance of <tt>DatabaseMetaData</tt> object. <p> @param method returning <tt>DatabaseMetaData</tt> @param args to the method @throws java.lang.Throwable the exception, if any, thrown by invoking the given method with the given arguments upon the delegate @return surrogate for the underlying DatabaseMetaData object
[ "Surrogate", "for", "any", "method", "of", "the", "delegate", "that", "returns", "an", "instance", "of", "<tt", ">", "DatabaseMetaData<", "/", "tt", ">", "object", ".", "<p", ">" ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/hsqldb19b3/org/hsqldb_voltpatches/jdbc/pool/WrapperInvocationHandler.java#L874-L884
indeedeng/util
util-core/src/main/java/com/indeed/util/core/NetUtils.java
NetUtils.determineHostName
@Nonnull public static String determineHostName() throws UnknownHostException { """ Determine the hostname of the machine that we are on. Do not allow, blank or 0.0.0.0 as valid hostnames. The host name will be save into the OPT_HOSTNAME static variable. We should not have to worry about threading, because the worst that should happen is multiple threads lookup the hostname at the same time, and its pointer is changed multiple times. The optional is immutable. @return hostname @throws java.net.UnknownHostException unable to lookup a host name correctly """ if (!OPT_HOSTNAME.isPresent()) { final String hostName = InetAddress.getLocalHost().getHostName(); if (Strings.isNullOrEmpty(hostName)) { throw new UnknownHostException("Unable to lookup localhost, got back empty hostname"); } if (Strings.nullToEmpty(hostName).equals("0.0.0.0")) { throw new UnknownHostException("Unable to resolve correct hostname saw bad host"); } OPT_HOSTNAME = Optional.of(hostName); return OPT_HOSTNAME.get(); } else { return OPT_HOSTNAME.get(); } }
java
@Nonnull public static String determineHostName() throws UnknownHostException { if (!OPT_HOSTNAME.isPresent()) { final String hostName = InetAddress.getLocalHost().getHostName(); if (Strings.isNullOrEmpty(hostName)) { throw new UnknownHostException("Unable to lookup localhost, got back empty hostname"); } if (Strings.nullToEmpty(hostName).equals("0.0.0.0")) { throw new UnknownHostException("Unable to resolve correct hostname saw bad host"); } OPT_HOSTNAME = Optional.of(hostName); return OPT_HOSTNAME.get(); } else { return OPT_HOSTNAME.get(); } }
[ "@", "Nonnull", "public", "static", "String", "determineHostName", "(", ")", "throws", "UnknownHostException", "{", "if", "(", "!", "OPT_HOSTNAME", ".", "isPresent", "(", ")", ")", "{", "final", "String", "hostName", "=", "InetAddress", ".", "getLocalHost", "(", ")", ".", "getHostName", "(", ")", ";", "if", "(", "Strings", ".", "isNullOrEmpty", "(", "hostName", ")", ")", "{", "throw", "new", "UnknownHostException", "(", "\"Unable to lookup localhost, got back empty hostname\"", ")", ";", "}", "if", "(", "Strings", ".", "nullToEmpty", "(", "hostName", ")", ".", "equals", "(", "\"0.0.0.0\"", ")", ")", "{", "throw", "new", "UnknownHostException", "(", "\"Unable to resolve correct hostname saw bad host\"", ")", ";", "}", "OPT_HOSTNAME", "=", "Optional", ".", "of", "(", "hostName", ")", ";", "return", "OPT_HOSTNAME", ".", "get", "(", ")", ";", "}", "else", "{", "return", "OPT_HOSTNAME", ".", "get", "(", ")", ";", "}", "}" ]
Determine the hostname of the machine that we are on. Do not allow, blank or 0.0.0.0 as valid hostnames. The host name will be save into the OPT_HOSTNAME static variable. We should not have to worry about threading, because the worst that should happen is multiple threads lookup the hostname at the same time, and its pointer is changed multiple times. The optional is immutable. @return hostname @throws java.net.UnknownHostException unable to lookup a host name correctly
[ "Determine", "the", "hostname", "of", "the", "machine", "that", "we", "are", "on", ".", "Do", "not", "allow", "blank", "or", "0", ".", "0", ".", "0", ".", "0", "as", "valid", "hostnames", ".", "The", "host", "name", "will", "be", "save", "into", "the", "OPT_HOSTNAME", "static", "variable", "." ]
train
https://github.com/indeedeng/util/blob/332008426cf14b57e7fc3e817d9423e3f84fb922/util-core/src/main/java/com/indeed/util/core/NetUtils.java#L37-L52
Harium/keel
src/main/java/com/harium/keel/catalano/math/distance/Distance.java
Distance.JaccardDistance
public static double JaccardDistance(double[] p, double[] q) { """ Gets the Jaccard distance between two points. @param p A point in space. @param q A point in space. @return The Jaccard distance between x and y. """ double distance = 0; int intersection = 0, union = 0; for (int x = 0; x < p.length; x++) { if ((p[x] != 0) || (q[x] != 0)) { if (p[x] == q[x]) { intersection++; } union++; } } if (union != 0) distance = 1.0 - ((double) intersection / (double) union); else distance = 0; return distance; }
java
public static double JaccardDistance(double[] p, double[] q) { double distance = 0; int intersection = 0, union = 0; for (int x = 0; x < p.length; x++) { if ((p[x] != 0) || (q[x] != 0)) { if (p[x] == q[x]) { intersection++; } union++; } } if (union != 0) distance = 1.0 - ((double) intersection / (double) union); else distance = 0; return distance; }
[ "public", "static", "double", "JaccardDistance", "(", "double", "[", "]", "p", ",", "double", "[", "]", "q", ")", "{", "double", "distance", "=", "0", ";", "int", "intersection", "=", "0", ",", "union", "=", "0", ";", "for", "(", "int", "x", "=", "0", ";", "x", "<", "p", ".", "length", ";", "x", "++", ")", "{", "if", "(", "(", "p", "[", "x", "]", "!=", "0", ")", "||", "(", "q", "[", "x", "]", "!=", "0", ")", ")", "{", "if", "(", "p", "[", "x", "]", "==", "q", "[", "x", "]", ")", "{", "intersection", "++", ";", "}", "union", "++", ";", "}", "}", "if", "(", "union", "!=", "0", ")", "distance", "=", "1.0", "-", "(", "(", "double", ")", "intersection", "/", "(", "double", ")", "union", ")", ";", "else", "distance", "=", "0", ";", "return", "distance", ";", "}" ]
Gets the Jaccard distance between two points. @param p A point in space. @param q A point in space. @return The Jaccard distance between x and y.
[ "Gets", "the", "Jaccard", "distance", "between", "two", "points", "." ]
train
https://github.com/Harium/keel/blob/0369ae674f9e664bccc5f9e161ae7e7a3b949a1e/src/main/java/com/harium/keel/catalano/math/distance/Distance.java#L431-L451
Netflix/servo
servo-core/src/main/java/com/netflix/servo/tag/BasicTagList.java
BasicTagList.concat
public static BasicTagList concat(TagList t1, TagList t2) { """ Returns a tag list containing the union of {@code t1} and {@code t2}. If there is a conflict with tag keys, the tag from {@code t2} will be used. """ return new BasicTagList(Iterables.concat(t1, t2)); }
java
public static BasicTagList concat(TagList t1, TagList t2) { return new BasicTagList(Iterables.concat(t1, t2)); }
[ "public", "static", "BasicTagList", "concat", "(", "TagList", "t1", ",", "TagList", "t2", ")", "{", "return", "new", "BasicTagList", "(", "Iterables", ".", "concat", "(", "t1", ",", "t2", ")", ")", ";", "}" ]
Returns a tag list containing the union of {@code t1} and {@code t2}. If there is a conflict with tag keys, the tag from {@code t2} will be used.
[ "Returns", "a", "tag", "list", "containing", "the", "union", "of", "{" ]
train
https://github.com/Netflix/servo/blob/d67b5afce8c50bd9e9e31c288dbf4b78fb2ac815/servo-core/src/main/java/com/netflix/servo/tag/BasicTagList.java#L166-L168
google/closure-compiler
src/com/google/javascript/jscomp/MustBeReachingVariableDef.java
MustBeReachingVariableDef.getDef
Definition getDef(String name, Node useNode) { """ Gets the must reaching definition of a given node. @param name name of the variable. It can only be names of local variable that are not function parameters, escaped variables or variables declared in catch. @param useNode the location of the use where the definition reaches. """ checkArgument(getCfg().hasNode(useNode)); GraphNode<Node, Branch> n = getCfg().getNode(useNode); FlowState<MustDef> state = n.getAnnotation(); return state.getIn().reachingDef.get(allVarsInFn.get(name)); }
java
Definition getDef(String name, Node useNode) { checkArgument(getCfg().hasNode(useNode)); GraphNode<Node, Branch> n = getCfg().getNode(useNode); FlowState<MustDef> state = n.getAnnotation(); return state.getIn().reachingDef.get(allVarsInFn.get(name)); }
[ "Definition", "getDef", "(", "String", "name", ",", "Node", "useNode", ")", "{", "checkArgument", "(", "getCfg", "(", ")", ".", "hasNode", "(", "useNode", ")", ")", ";", "GraphNode", "<", "Node", ",", "Branch", ">", "n", "=", "getCfg", "(", ")", ".", "getNode", "(", "useNode", ")", ";", "FlowState", "<", "MustDef", ">", "state", "=", "n", ".", "getAnnotation", "(", ")", ";", "return", "state", ".", "getIn", "(", ")", ".", "reachingDef", ".", "get", "(", "allVarsInFn", ".", "get", "(", "name", ")", ")", ";", "}" ]
Gets the must reaching definition of a given node. @param name name of the variable. It can only be names of local variable that are not function parameters, escaped variables or variables declared in catch. @param useNode the location of the use where the definition reaches.
[ "Gets", "the", "must", "reaching", "definition", "of", "a", "given", "node", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/MustBeReachingVariableDef.java#L469-L474
threerings/nenya
core/src/main/java/com/threerings/media/image/ImageManager.java
ImageManager.getPreparedImage
public BufferedImage getPreparedImage (String rset, String path, Colorization[] zations) { """ Loads (and caches) the specified image from the resource manager, obtaining the image from the supplied resource set and applying the using the supplied path to identify the image. <p> Additionally the image is optimized for display in the current graphics configuration. Consider using {@link #getMirage(ImageKey,Colorization[])} instead of prepared images as they (some day) will automatically use volatile images to increase performance. """ BufferedImage image = getImage(rset, path, zations); BufferedImage prepped = null; if (image != null) { prepped = createImage(image.getWidth(), image.getHeight(), image.getColorModel().getTransparency()); Graphics2D pg = prepped.createGraphics(); pg.drawImage(image, 0, 0, null); pg.dispose(); } return prepped; }
java
public BufferedImage getPreparedImage (String rset, String path, Colorization[] zations) { BufferedImage image = getImage(rset, path, zations); BufferedImage prepped = null; if (image != null) { prepped = createImage(image.getWidth(), image.getHeight(), image.getColorModel().getTransparency()); Graphics2D pg = prepped.createGraphics(); pg.drawImage(image, 0, 0, null); pg.dispose(); } return prepped; }
[ "public", "BufferedImage", "getPreparedImage", "(", "String", "rset", ",", "String", "path", ",", "Colorization", "[", "]", "zations", ")", "{", "BufferedImage", "image", "=", "getImage", "(", "rset", ",", "path", ",", "zations", ")", ";", "BufferedImage", "prepped", "=", "null", ";", "if", "(", "image", "!=", "null", ")", "{", "prepped", "=", "createImage", "(", "image", ".", "getWidth", "(", ")", ",", "image", ".", "getHeight", "(", ")", ",", "image", ".", "getColorModel", "(", ")", ".", "getTransparency", "(", ")", ")", ";", "Graphics2D", "pg", "=", "prepped", ".", "createGraphics", "(", ")", ";", "pg", ".", "drawImage", "(", "image", ",", "0", ",", "0", ",", "null", ")", ";", "pg", ".", "dispose", "(", ")", ";", "}", "return", "prepped", ";", "}" ]
Loads (and caches) the specified image from the resource manager, obtaining the image from the supplied resource set and applying the using the supplied path to identify the image. <p> Additionally the image is optimized for display in the current graphics configuration. Consider using {@link #getMirage(ImageKey,Colorization[])} instead of prepared images as they (some day) will automatically use volatile images to increase performance.
[ "Loads", "(", "and", "caches", ")", "the", "specified", "image", "from", "the", "resource", "manager", "obtaining", "the", "image", "from", "the", "supplied", "resource", "set", "and", "applying", "the", "using", "the", "supplied", "path", "to", "identify", "the", "image", "." ]
train
https://github.com/threerings/nenya/blob/3165a012fd859009db3367f87bd2a5b820cc760a/core/src/main/java/com/threerings/media/image/ImageManager.java#L244-L256
LGoodDatePicker/LGoodDatePicker
Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java
FormLayout.computeGridOrigins
private static int[] computeGridOrigins(Container container, int totalSize, int offset, List formSpecs, List[] componentLists, int[][] groupIndices, Measure minMeasure, Measure prefMeasure) { """ Computes and returns the grid's origins. @param container the layout container @param totalSize the total size to assign @param offset the offset from left or top margin @param formSpecs the column or row specs, resp. @param componentLists the components list for each col/row @param minMeasure the measure used to determine min sizes @param prefMeasure the measure used to determine pre sizes @param groupIndices the group specification @return an int array with the origins """ /* For each spec compute the minimum and preferred size that is * the maximum of all component minimum and preferred sizes resp. */ int[] minSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, minMeasure); int[] prefSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, prefMeasure); int[] groupedMinSizes = groupedSizes(groupIndices, minSizes); int[] groupedPrefSizes = groupedSizes(groupIndices, prefSizes); int totalMinSize = sum(groupedMinSizes); int totalPrefSize = sum(groupedPrefSizes); int[] compressedSizes = compressedSizes(formSpecs, totalSize, totalMinSize, totalPrefSize, groupedMinSizes, prefSizes); int[] groupedSizes = groupedSizes(groupIndices, compressedSizes); int totalGroupedSize = sum(groupedSizes); int[] sizes = distributedSizes(formSpecs, totalSize, totalGroupedSize, groupedSizes); return computeOrigins(sizes, offset); }
java
private static int[] computeGridOrigins(Container container, int totalSize, int offset, List formSpecs, List[] componentLists, int[][] groupIndices, Measure minMeasure, Measure prefMeasure) { /* For each spec compute the minimum and preferred size that is * the maximum of all component minimum and preferred sizes resp. */ int[] minSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, minMeasure); int[] prefSizes = maximumSizes(container, formSpecs, componentLists, minMeasure, prefMeasure, prefMeasure); int[] groupedMinSizes = groupedSizes(groupIndices, minSizes); int[] groupedPrefSizes = groupedSizes(groupIndices, prefSizes); int totalMinSize = sum(groupedMinSizes); int totalPrefSize = sum(groupedPrefSizes); int[] compressedSizes = compressedSizes(formSpecs, totalSize, totalMinSize, totalPrefSize, groupedMinSizes, prefSizes); int[] groupedSizes = groupedSizes(groupIndices, compressedSizes); int totalGroupedSize = sum(groupedSizes); int[] sizes = distributedSizes(formSpecs, totalSize, totalGroupedSize, groupedSizes); return computeOrigins(sizes, offset); }
[ "private", "static", "int", "[", "]", "computeGridOrigins", "(", "Container", "container", ",", "int", "totalSize", ",", "int", "offset", ",", "List", "formSpecs", ",", "List", "[", "]", "componentLists", ",", "int", "[", "]", "[", "]", "groupIndices", ",", "Measure", "minMeasure", ",", "Measure", "prefMeasure", ")", "{", "/* For each spec compute the minimum and preferred size that is\n * the maximum of all component minimum and preferred sizes resp.\n */", "int", "[", "]", "minSizes", "=", "maximumSizes", "(", "container", ",", "formSpecs", ",", "componentLists", ",", "minMeasure", ",", "prefMeasure", ",", "minMeasure", ")", ";", "int", "[", "]", "prefSizes", "=", "maximumSizes", "(", "container", ",", "formSpecs", ",", "componentLists", ",", "minMeasure", ",", "prefMeasure", ",", "prefMeasure", ")", ";", "int", "[", "]", "groupedMinSizes", "=", "groupedSizes", "(", "groupIndices", ",", "minSizes", ")", ";", "int", "[", "]", "groupedPrefSizes", "=", "groupedSizes", "(", "groupIndices", ",", "prefSizes", ")", ";", "int", "totalMinSize", "=", "sum", "(", "groupedMinSizes", ")", ";", "int", "totalPrefSize", "=", "sum", "(", "groupedPrefSizes", ")", ";", "int", "[", "]", "compressedSizes", "=", "compressedSizes", "(", "formSpecs", ",", "totalSize", ",", "totalMinSize", ",", "totalPrefSize", ",", "groupedMinSizes", ",", "prefSizes", ")", ";", "int", "[", "]", "groupedSizes", "=", "groupedSizes", "(", "groupIndices", ",", "compressedSizes", ")", ";", "int", "totalGroupedSize", "=", "sum", "(", "groupedSizes", ")", ";", "int", "[", "]", "sizes", "=", "distributedSizes", "(", "formSpecs", ",", "totalSize", ",", "totalGroupedSize", ",", "groupedSizes", ")", ";", "return", "computeOrigins", "(", "sizes", ",", "offset", ")", ";", "}" ]
Computes and returns the grid's origins. @param container the layout container @param totalSize the total size to assign @param offset the offset from left or top margin @param formSpecs the column or row specs, resp. @param componentLists the components list for each col/row @param minMeasure the measure used to determine min sizes @param prefMeasure the measure used to determine pre sizes @param groupIndices the group specification @return an int array with the origins
[ "Computes", "and", "returns", "the", "grid", "s", "origins", "." ]
train
https://github.com/LGoodDatePicker/LGoodDatePicker/blob/c7df05a5fe382e1e08a6237e9391d8dc5fd48692/Project/src/main/java/com/privatejgoodies/forms/layout/FormLayout.java#L1325-L1357
iron-io/iron_mq_java
src/main/java/io/iron/ironmq/Queue.java
Queue.pushMessages
public Ids pushMessages(String[] msg, long delay) throws IOException { """ Pushes a messages onto the queue. @param msg The array of the messages to push. @param delay The message's delay in seconds. @return The IDs of new messages @throws io.iron.ironmq.HTTPException If the IronMQ service returns a status other than 200 OK. @throws java.io.IOException If there is an error accessing the IronMQ server. """ ArrayList<Message> messages = new ArrayList<Message>(); for (String messageName: msg){ Message message = new Message(); message.setBody(messageName); message.setDelay(delay); messages.add(message); } MessagesArrayList msgs = new MessagesArrayList(messages); IronReader reader = client.post("queues/" + name + "/messages", msgs); Ids ids = gson.fromJson(reader.reader, Ids.class); reader.close(); return ids; }
java
public Ids pushMessages(String[] msg, long delay) throws IOException { ArrayList<Message> messages = new ArrayList<Message>(); for (String messageName: msg){ Message message = new Message(); message.setBody(messageName); message.setDelay(delay); messages.add(message); } MessagesArrayList msgs = new MessagesArrayList(messages); IronReader reader = client.post("queues/" + name + "/messages", msgs); Ids ids = gson.fromJson(reader.reader, Ids.class); reader.close(); return ids; }
[ "public", "Ids", "pushMessages", "(", "String", "[", "]", "msg", ",", "long", "delay", ")", "throws", "IOException", "{", "ArrayList", "<", "Message", ">", "messages", "=", "new", "ArrayList", "<", "Message", ">", "(", ")", ";", "for", "(", "String", "messageName", ":", "msg", ")", "{", "Message", "message", "=", "new", "Message", "(", ")", ";", "message", ".", "setBody", "(", "messageName", ")", ";", "message", ".", "setDelay", "(", "delay", ")", ";", "messages", ".", "add", "(", "message", ")", ";", "}", "MessagesArrayList", "msgs", "=", "new", "MessagesArrayList", "(", "messages", ")", ";", "IronReader", "reader", "=", "client", ".", "post", "(", "\"queues/\"", "+", "name", "+", "\"/messages\"", ",", "msgs", ")", ";", "Ids", "ids", "=", "gson", ".", "fromJson", "(", "reader", ".", "reader", ",", "Ids", ".", "class", ")", ";", "reader", ".", "close", "(", ")", ";", "return", "ids", ";", "}" ]
Pushes a messages onto the queue. @param msg The array of the messages to push. @param delay The message's delay in seconds. @return The IDs of new messages @throws io.iron.ironmq.HTTPException If the IronMQ service returns a status other than 200 OK. @throws java.io.IOException If there is an error accessing the IronMQ server.
[ "Pushes", "a", "messages", "onto", "the", "queue", "." ]
train
https://github.com/iron-io/iron_mq_java/blob/62d6a86545ca7ef31b7b4797aae0c5b31394a507/src/main/java/io/iron/ironmq/Queue.java#L412-L427
google/closure-compiler
src/com/google/javascript/jscomp/ReplaceMessages.java
ReplaceMessages.getNewValueNode
private Node getNewValueNode(JsMessage message, Node origValueNode) throws MalformedException { """ Constructs a node representing a message's value, or, if possible, just modifies {@code origValueNode} so that it accurately represents the message's value. @param message a message @param origValueNode the message's original value node @return a Node that can replace {@code origValueNode} @throws MalformedException if the passed node's subtree structure is not as expected """ switch (origValueNode.getToken()) { case FUNCTION: // The message is a function. Modify the function node. updateFunctionNode(message, origValueNode); return origValueNode; case STRING: // The message is a simple string. Modify the string node. String newString = message.toString(); if (!origValueNode.getString().equals(newString)) { origValueNode.setString(newString); compiler.reportChangeToEnclosingScope(origValueNode); } return origValueNode; case ADD: // The message is a simple string. Create a string node. return IR.string(message.toString()); case CALL: // The message is a function call. Replace it with a string expression. return replaceCallNode(message, origValueNode); default: throw new MalformedException( "Expected FUNCTION, STRING, or ADD node; found: " + origValueNode.getToken(), origValueNode); } }
java
private Node getNewValueNode(JsMessage message, Node origValueNode) throws MalformedException { switch (origValueNode.getToken()) { case FUNCTION: // The message is a function. Modify the function node. updateFunctionNode(message, origValueNode); return origValueNode; case STRING: // The message is a simple string. Modify the string node. String newString = message.toString(); if (!origValueNode.getString().equals(newString)) { origValueNode.setString(newString); compiler.reportChangeToEnclosingScope(origValueNode); } return origValueNode; case ADD: // The message is a simple string. Create a string node. return IR.string(message.toString()); case CALL: // The message is a function call. Replace it with a string expression. return replaceCallNode(message, origValueNode); default: throw new MalformedException( "Expected FUNCTION, STRING, or ADD node; found: " + origValueNode.getToken(), origValueNode); } }
[ "private", "Node", "getNewValueNode", "(", "JsMessage", "message", ",", "Node", "origValueNode", ")", "throws", "MalformedException", "{", "switch", "(", "origValueNode", ".", "getToken", "(", ")", ")", "{", "case", "FUNCTION", ":", "// The message is a function. Modify the function node.", "updateFunctionNode", "(", "message", ",", "origValueNode", ")", ";", "return", "origValueNode", ";", "case", "STRING", ":", "// The message is a simple string. Modify the string node.", "String", "newString", "=", "message", ".", "toString", "(", ")", ";", "if", "(", "!", "origValueNode", ".", "getString", "(", ")", ".", "equals", "(", "newString", ")", ")", "{", "origValueNode", ".", "setString", "(", "newString", ")", ";", "compiler", ".", "reportChangeToEnclosingScope", "(", "origValueNode", ")", ";", "}", "return", "origValueNode", ";", "case", "ADD", ":", "// The message is a simple string. Create a string node.", "return", "IR", ".", "string", "(", "message", ".", "toString", "(", ")", ")", ";", "case", "CALL", ":", "// The message is a function call. Replace it with a string expression.", "return", "replaceCallNode", "(", "message", ",", "origValueNode", ")", ";", "default", ":", "throw", "new", "MalformedException", "(", "\"Expected FUNCTION, STRING, or ADD node; found: \"", "+", "origValueNode", ".", "getToken", "(", ")", ",", "origValueNode", ")", ";", "}", "}" ]
Constructs a node representing a message's value, or, if possible, just modifies {@code origValueNode} so that it accurately represents the message's value. @param message a message @param origValueNode the message's original value node @return a Node that can replace {@code origValueNode} @throws MalformedException if the passed node's subtree structure is not as expected
[ "Constructs", "a", "node", "representing", "a", "message", "s", "value", "or", "if", "possible", "just", "modifies", "{", "@code", "origValueNode", "}", "so", "that", "it", "accurately", "represents", "the", "message", "s", "value", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/ReplaceMessages.java#L119-L145
Impetus/Kundera
src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java
OracleNoSQLClient.readEmbeddable
private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata, MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute) { """ Read embeddable. @param key the key @param columnsToSelect the columns to select @param entityMetadata the entity metadata @param metamodel the metamodel @param schemaTable the schema table @param value the value @param attribute the attribute """ EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Set<Attribute> embeddedAttributes = embeddableId.getAttributes(); for (Attribute embeddedAttrib : embeddedAttributes) { String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName(); Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember()); // either null or empty or contains that column if (eligibleToFetch(columnsToSelect, columnName)) { NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName); } } }
java
private void readEmbeddable(Object key, List<String> columnsToSelect, EntityMetadata entityMetadata, MetamodelImpl metamodel, Table schemaTable, RecordValue value, Attribute attribute) { EmbeddableType embeddableId = metamodel.embeddable(((AbstractAttribute) attribute).getBindableJavaType()); Set<Attribute> embeddedAttributes = embeddableId.getAttributes(); for (Attribute embeddedAttrib : embeddedAttributes) { String columnName = ((AbstractAttribute) embeddedAttrib).getJPAColumnName(); Object embeddedColumn = PropertyAccessorHelper.getObject(key, (Field) embeddedAttrib.getJavaMember()); // either null or empty or contains that column if (eligibleToFetch(columnsToSelect, columnName)) { NoSqlDBUtils.add(schemaTable.getField(columnName), value, embeddedColumn, columnName); } } }
[ "private", "void", "readEmbeddable", "(", "Object", "key", ",", "List", "<", "String", ">", "columnsToSelect", ",", "EntityMetadata", "entityMetadata", ",", "MetamodelImpl", "metamodel", ",", "Table", "schemaTable", ",", "RecordValue", "value", ",", "Attribute", "attribute", ")", "{", "EmbeddableType", "embeddableId", "=", "metamodel", ".", "embeddable", "(", "(", "(", "AbstractAttribute", ")", "attribute", ")", ".", "getBindableJavaType", "(", ")", ")", ";", "Set", "<", "Attribute", ">", "embeddedAttributes", "=", "embeddableId", ".", "getAttributes", "(", ")", ";", "for", "(", "Attribute", "embeddedAttrib", ":", "embeddedAttributes", ")", "{", "String", "columnName", "=", "(", "(", "AbstractAttribute", ")", "embeddedAttrib", ")", ".", "getJPAColumnName", "(", ")", ";", "Object", "embeddedColumn", "=", "PropertyAccessorHelper", ".", "getObject", "(", "key", ",", "(", "Field", ")", "embeddedAttrib", ".", "getJavaMember", "(", ")", ")", ";", "// either null or empty or contains that column", "if", "(", "eligibleToFetch", "(", "columnsToSelect", ",", "columnName", ")", ")", "{", "NoSqlDBUtils", ".", "add", "(", "schemaTable", ".", "getField", "(", "columnName", ")", ",", "value", ",", "embeddedColumn", ",", "columnName", ")", ";", "}", "}", "}" ]
Read embeddable. @param key the key @param columnsToSelect the columns to select @param entityMetadata the entity metadata @param metamodel the metamodel @param schemaTable the schema table @param value the value @param attribute the attribute
[ "Read", "embeddable", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/kundera-oracle-nosql/src/main/java/com/impetus/client/oraclenosql/OracleNoSQLClient.java#L264-L281
gmessner/gitlab4j-api
src/main/java/org/gitlab4j/api/RepositoryApi.java
RepositoryApi.deleteBranch
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException { """ Delete a single project repository branch. <pre><code>GitLab Endpoint: DELETE /projects/:id/repository/branches/:branch</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param branchName the name of the branch to delete @throws GitLabApiException if any exception occurs """ Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName)); }
java
public void deleteBranch(Object projectIdOrPath, String branchName) throws GitLabApiException { Response.Status expectedStatus = (isApiVersion(ApiVersion.V3) ? Response.Status.OK : Response.Status.NO_CONTENT); delete(expectedStatus, null, "projects", getProjectIdOrPath(projectIdOrPath), "repository", "branches", urlEncode(branchName)); }
[ "public", "void", "deleteBranch", "(", "Object", "projectIdOrPath", ",", "String", "branchName", ")", "throws", "GitLabApiException", "{", "Response", ".", "Status", "expectedStatus", "=", "(", "isApiVersion", "(", "ApiVersion", ".", "V3", ")", "?", "Response", ".", "Status", ".", "OK", ":", "Response", ".", "Status", ".", "NO_CONTENT", ")", ";", "delete", "(", "expectedStatus", ",", "null", ",", "\"projects\"", ",", "getProjectIdOrPath", "(", "projectIdOrPath", ")", ",", "\"repository\"", ",", "\"branches\"", ",", "urlEncode", "(", "branchName", ")", ")", ";", "}" ]
Delete a single project repository branch. <pre><code>GitLab Endpoint: DELETE /projects/:id/repository/branches/:branch</code></pre> @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance @param branchName the name of the branch to delete @throws GitLabApiException if any exception occurs
[ "Delete", "a", "single", "project", "repository", "branch", "." ]
train
https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/RepositoryApi.java#L158-L162
google/j2objc
jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java
RelativeDateTimeFormatter.getInstance
public static RelativeDateTimeFormatter getInstance(ULocale locale, NumberFormat nf) { """ Returns a RelativeDateTimeFormatter for a particular locale that uses a particular NumberFormat object. @param locale the locale @param nf the number format object. It is defensively copied to ensure thread-safety and immutability of this class. @return An instance of RelativeDateTimeFormatter. """ return getInstance(locale, nf, Style.LONG, DisplayContext.CAPITALIZATION_NONE); }
java
public static RelativeDateTimeFormatter getInstance(ULocale locale, NumberFormat nf) { return getInstance(locale, nf, Style.LONG, DisplayContext.CAPITALIZATION_NONE); }
[ "public", "static", "RelativeDateTimeFormatter", "getInstance", "(", "ULocale", "locale", ",", "NumberFormat", "nf", ")", "{", "return", "getInstance", "(", "locale", ",", "nf", ",", "Style", ".", "LONG", ",", "DisplayContext", ".", "CAPITALIZATION_NONE", ")", ";", "}" ]
Returns a RelativeDateTimeFormatter for a particular locale that uses a particular NumberFormat object. @param locale the locale @param nf the number format object. It is defensively copied to ensure thread-safety and immutability of this class. @return An instance of RelativeDateTimeFormatter.
[ "Returns", "a", "RelativeDateTimeFormatter", "for", "a", "particular", "locale", "that", "uses", "a", "particular", "NumberFormat", "object", "." ]
train
https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/RelativeDateTimeFormatter.java#L393-L395
samskivert/samskivert
src/main/java/com/samskivert/util/ClassUtil.java
ClassUtil.primitiveIsAssignableFrom
public static boolean primitiveIsAssignableFrom (Class<?> lhs, Class<?> rhs) { """ Tells whether an instance of the primitive class represented by 'rhs' can be assigned to an instance of the primitive class represented by 'lhs'. @param lhs assignee class. @param rhs assigned class. @return true if compatible, false otherwise. If either argument is <code>null</code>, or one of the parameters does not represent a primitive (e.g. Byte.TYPE), returns false. """ if (lhs == null || rhs == null) { return false; } if (!(lhs.isPrimitive() && rhs.isPrimitive())) { return false; } if (lhs.equals(rhs)) { return true; } Set<Class<?>> wideningSet = _primitiveWideningsMap.get(rhs); if (wideningSet == null) { return false; } return wideningSet.contains(lhs); }
java
public static boolean primitiveIsAssignableFrom (Class<?> lhs, Class<?> rhs) { if (lhs == null || rhs == null) { return false; } if (!(lhs.isPrimitive() && rhs.isPrimitive())) { return false; } if (lhs.equals(rhs)) { return true; } Set<Class<?>> wideningSet = _primitiveWideningsMap.get(rhs); if (wideningSet == null) { return false; } return wideningSet.contains(lhs); }
[ "public", "static", "boolean", "primitiveIsAssignableFrom", "(", "Class", "<", "?", ">", "lhs", ",", "Class", "<", "?", ">", "rhs", ")", "{", "if", "(", "lhs", "==", "null", "||", "rhs", "==", "null", ")", "{", "return", "false", ";", "}", "if", "(", "!", "(", "lhs", ".", "isPrimitive", "(", ")", "&&", "rhs", ".", "isPrimitive", "(", ")", ")", ")", "{", "return", "false", ";", "}", "if", "(", "lhs", ".", "equals", "(", "rhs", ")", ")", "{", "return", "true", ";", "}", "Set", "<", "Class", "<", "?", ">", ">", "wideningSet", "=", "_primitiveWideningsMap", ".", "get", "(", "rhs", ")", ";", "if", "(", "wideningSet", "==", "null", ")", "{", "return", "false", ";", "}", "return", "wideningSet", ".", "contains", "(", "lhs", ")", ";", "}" ]
Tells whether an instance of the primitive class represented by 'rhs' can be assigned to an instance of the primitive class represented by 'lhs'. @param lhs assignee class. @param rhs assigned class. @return true if compatible, false otherwise. If either argument is <code>null</code>, or one of the parameters does not represent a primitive (e.g. Byte.TYPE), returns false.
[ "Tells", "whether", "an", "instance", "of", "the", "primitive", "class", "represented", "by", "rhs", "can", "be", "assigned", "to", "an", "instance", "of", "the", "primitive", "class", "represented", "by", "lhs", "." ]
train
https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ClassUtil.java#L236-L252
alkacon/opencms-core
src/org/opencms/db/generic/CmsSubscriptionDriver.java
CmsSubscriptionDriver.internalReadVisitEntry
protected CmsVisitEntry internalReadVisitEntry(ResultSet res) throws SQLException { """ Creates a new {@link CmsVisitEntry} object from the given result set entry.<p> @param res the result set @return the new {@link CmsVisitEntry} object @throws SQLException if something goes wrong """ CmsUUID userId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_VISIT_USER_ID"))); long date = res.getLong(m_sqlManager.readQuery("C_VISIT_DATE")); CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_VISIT_STRUCTURE_ID"))); return new CmsVisitEntry(userId, date, structureId); }
java
protected CmsVisitEntry internalReadVisitEntry(ResultSet res) throws SQLException { CmsUUID userId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_VISIT_USER_ID"))); long date = res.getLong(m_sqlManager.readQuery("C_VISIT_DATE")); CmsUUID structureId = new CmsUUID(res.getString(m_sqlManager.readQuery("C_VISIT_STRUCTURE_ID"))); return new CmsVisitEntry(userId, date, structureId); }
[ "protected", "CmsVisitEntry", "internalReadVisitEntry", "(", "ResultSet", "res", ")", "throws", "SQLException", "{", "CmsUUID", "userId", "=", "new", "CmsUUID", "(", "res", ".", "getString", "(", "m_sqlManager", ".", "readQuery", "(", "\"C_VISIT_USER_ID\"", ")", ")", ")", ";", "long", "date", "=", "res", ".", "getLong", "(", "m_sqlManager", ".", "readQuery", "(", "\"C_VISIT_DATE\"", ")", ")", ";", "CmsUUID", "structureId", "=", "new", "CmsUUID", "(", "res", ".", "getString", "(", "m_sqlManager", ".", "readQuery", "(", "\"C_VISIT_STRUCTURE_ID\"", ")", ")", ")", ";", "return", "new", "CmsVisitEntry", "(", "userId", ",", "date", ",", "structureId", ")", ";", "}" ]
Creates a new {@link CmsVisitEntry} object from the given result set entry.<p> @param res the result set @return the new {@link CmsVisitEntry} object @throws SQLException if something goes wrong
[ "Creates", "a", "new", "{", "@link", "CmsVisitEntry", "}", "object", "from", "the", "given", "result", "set", "entry", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/generic/CmsSubscriptionDriver.java#L941-L947