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 listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jcuda/jcusparse | JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java | JCusparse.cusparseScsric0 | public static int cusparseScsric0(
cusparseHandle handle,
int trans,
int m,
cusparseMatDescr descrA,
Pointer csrSortedValA_ValM,
/** matrix A values are updated inplace
to be the preconditioner M values */
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
cusparseSolveAnalysisInfo info) {
"""
<pre>
Description: Compute the incomplete-Cholesky factorization with 0 fill-in (IC0)
of the matrix A stored in CSR format based on the information in the opaque
structure info that was obtained from the analysis phase (csrsv_analysis).
This routine implements algorithm 1 for this problem.
</pre>
"""
return checkResult(cusparseScsric0Native(handle, trans, m, descrA, csrSortedValA_ValM, csrSortedRowPtrA, csrSortedColIndA, info));
} | java | public static int cusparseScsric0(
cusparseHandle handle,
int trans,
int m,
cusparseMatDescr descrA,
Pointer csrSortedValA_ValM,
/** matrix A values are updated inplace
to be the preconditioner M values */
Pointer csrSortedRowPtrA,
Pointer csrSortedColIndA,
cusparseSolveAnalysisInfo info)
{
return checkResult(cusparseScsric0Native(handle, trans, m, descrA, csrSortedValA_ValM, csrSortedRowPtrA, csrSortedColIndA, info));
} | [
"public",
"static",
"int",
"cusparseScsric0",
"(",
"cusparseHandle",
"handle",
",",
"int",
"trans",
",",
"int",
"m",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"csrSortedValA_ValM",
",",
"/** matrix A values are updated inplace \r\n ... | <pre>
Description: Compute the incomplete-Cholesky factorization with 0 fill-in (IC0)
of the matrix A stored in CSR format based on the information in the opaque
structure info that was obtained from the analysis phase (csrsv_analysis).
This routine implements algorithm 1 for this problem.
</pre> | [
"<pre",
">",
"Description",
":",
"Compute",
"the",
"incomplete",
"-",
"Cholesky",
"factorization",
"with",
"0",
"fill",
"-",
"in",
"(",
"IC0",
")",
"of",
"the",
"matrix",
"A",
"stored",
"in",
"CSR",
"format",
"based",
"on",
"the",
"information",
"in",
"t... | train | https://github.com/jcuda/jcusparse/blob/7687a62a4ef6b76cb91cf7da93d4cf5ade96a791/JCusparseJava/src/main/java/jcuda/jcusparse/JCusparse.java#L6946-L6959 |
aoindustries/aocode-public | src/main/java/com/aoindustries/servlet/http/LastModifiedServlet.java | LastModifiedServlet.getLastModified | public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) {
"""
Automatically determines extension from path.
@see #getLastModified(javax.servlet.ServletContext, java.lang.String, java.lang.String)
"""
return getLastModified(
servletContext,
request,
path,
FileUtils.getExtension(path)
);
} | java | public static long getLastModified(ServletContext servletContext, HttpServletRequest request, String path) {
return getLastModified(
servletContext,
request,
path,
FileUtils.getExtension(path)
);
} | [
"public",
"static",
"long",
"getLastModified",
"(",
"ServletContext",
"servletContext",
",",
"HttpServletRequest",
"request",
",",
"String",
"path",
")",
"{",
"return",
"getLastModified",
"(",
"servletContext",
",",
"request",
",",
"path",
",",
"FileUtils",
".",
"... | Automatically determines extension from path.
@see #getLastModified(javax.servlet.ServletContext, java.lang.String, java.lang.String) | [
"Automatically",
"determines",
"extension",
"from",
"path",
"."
] | train | https://github.com/aoindustries/aocode-public/blob/c7bc1d08aee1d02dfaeeb1421fad21aca1aad4c3/src/main/java/com/aoindustries/servlet/http/LastModifiedServlet.java#L421-L428 |
alkacon/opencms-core | src/org/opencms/db/CmsSubscriptionManager.java | CmsSubscriptionManager.markResourceAsVisitedBy | public void markResourceAsVisitedBy(CmsObject cms, CmsResource resource, CmsUser user) throws CmsException {
"""
Mark the given resource as visited by the user.<p>
@param cms the current users context
@param resource the resource to mark as visited
@param user the user that visited the resource
@throws CmsException if something goes wrong
"""
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.markResourceAsVisitedBy(cms.getRequestContext(), getPoolName(), resource, user);
} | java | public void markResourceAsVisitedBy(CmsObject cms, CmsResource resource, CmsUser user) throws CmsException {
if (!isEnabled()) {
throw new CmsRuntimeException(Messages.get().container(Messages.ERR_SUBSCRIPTION_MANAGER_DISABLED_0));
}
m_securityManager.markResourceAsVisitedBy(cms.getRequestContext(), getPoolName(), resource, user);
} | [
"public",
"void",
"markResourceAsVisitedBy",
"(",
"CmsObject",
"cms",
",",
"CmsResource",
"resource",
",",
"CmsUser",
"user",
")",
"throws",
"CmsException",
"{",
"if",
"(",
"!",
"isEnabled",
"(",
")",
")",
"{",
"throw",
"new",
"CmsRuntimeException",
"(",
"Mess... | Mark the given resource as visited by the user.<p>
@param cms the current users context
@param resource the resource to mark as visited
@param user the user that visited the resource
@throws CmsException if something goes wrong | [
"Mark",
"the",
"given",
"resource",
"as",
"visited",
"by",
"the",
"user",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/db/CmsSubscriptionManager.java#L171-L177 |
apache/incubator-gobblin | gobblin-runtime/src/main/java/org/apache/gobblin/runtime/mapreduce/MRJobLauncher.java | MRJobLauncher.addHDFSFiles | @SuppressWarnings("deprecation")
private void addHDFSFiles(String jobFileList, Configuration conf) {
"""
Add non-jar files already on HDFS that the job depends on to DistributedCache.
"""
DistributedCache.createSymlink(conf);
jobFileList = PasswordManager.getInstance(this.jobProps).readPassword(jobFileList);
for (String jobFile : SPLITTER.split(jobFileList)) {
Path srcJobFile = new Path(jobFile);
// Create a URI that is in the form path#symlink
URI srcFileUri = URI.create(srcJobFile.toUri().getPath() + "#" + srcJobFile.getName());
LOG.info(String.format("Adding %s to DistributedCache", srcFileUri));
// Finally add the file to DistributedCache with a symlink named after the file name
DistributedCache.addCacheFile(srcFileUri, conf);
}
} | java | @SuppressWarnings("deprecation")
private void addHDFSFiles(String jobFileList, Configuration conf) {
DistributedCache.createSymlink(conf);
jobFileList = PasswordManager.getInstance(this.jobProps).readPassword(jobFileList);
for (String jobFile : SPLITTER.split(jobFileList)) {
Path srcJobFile = new Path(jobFile);
// Create a URI that is in the form path#symlink
URI srcFileUri = URI.create(srcJobFile.toUri().getPath() + "#" + srcJobFile.getName());
LOG.info(String.format("Adding %s to DistributedCache", srcFileUri));
// Finally add the file to DistributedCache with a symlink named after the file name
DistributedCache.addCacheFile(srcFileUri, conf);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"deprecation\"",
")",
"private",
"void",
"addHDFSFiles",
"(",
"String",
"jobFileList",
",",
"Configuration",
"conf",
")",
"{",
"DistributedCache",
".",
"createSymlink",
"(",
"conf",
")",
";",
"jobFileList",
"=",
"PasswordManager",
"... | Add non-jar files already on HDFS that the job depends on to DistributedCache. | [
"Add",
"non",
"-",
"jar",
"files",
"already",
"on",
"HDFS",
"that",
"the",
"job",
"depends",
"on",
"to",
"DistributedCache",
"."
] | train | https://github.com/apache/incubator-gobblin/blob/f029b4c0fea0fe4aa62f36dda2512344ff708bae/gobblin-runtime/src/main/java/org/apache/gobblin/runtime/mapreduce/MRJobLauncher.java#L550-L562 |
Cornutum/tcases | tcases-io/src/main/java/org/cornutum/tcases/TcasesJson.java | TcasesJson.writeInputModel | public static void writeInputModel( SystemInputDef inputDef, OutputStream outputStream) {
"""
Writes a {@link SystemInputJsonWriter JSON document} describing the given system input definition to the given output stream.
"""
try( SystemInputJsonWriter writer = new SystemInputJsonWriter( outputStream))
{
writer.write( inputDef);
}
catch( Exception e)
{
throw new RuntimeException( "Can't write input definition", e);
}
} | java | public static void writeInputModel( SystemInputDef inputDef, OutputStream outputStream)
{
try( SystemInputJsonWriter writer = new SystemInputJsonWriter( outputStream))
{
writer.write( inputDef);
}
catch( Exception e)
{
throw new RuntimeException( "Can't write input definition", e);
}
} | [
"public",
"static",
"void",
"writeInputModel",
"(",
"SystemInputDef",
"inputDef",
",",
"OutputStream",
"outputStream",
")",
"{",
"try",
"(",
"SystemInputJsonWriter",
"writer",
"=",
"new",
"SystemInputJsonWriter",
"(",
"outputStream",
")",
")",
"{",
"writer",
".",
... | Writes a {@link SystemInputJsonWriter JSON document} describing the given system input definition to the given output stream. | [
"Writes",
"a",
"{"
] | train | https://github.com/Cornutum/tcases/blob/21e15cf107fa149620c40f4bda1829c1224fcfb1/tcases-io/src/main/java/org/cornutum/tcases/TcasesJson.java#L48-L58 |
intel/jndn-utils | src/main/java/com/intel/jndn/utils/client/impl/DefaultSegmentedClient.java | DefaultSegmentedClient.replaceFinalComponent | protected Interest replaceFinalComponent(Interest interest, long segmentNumber, byte marker) {
"""
Replace the final component of an interest name with a segmented component;
if the interest name does not have a segmented component, this will add
one.
@param interest the request
@param segmentNumber a segment number
@param marker a marker to use for segmenting the packet
@return a segmented interest (a copy of the passed interest)
"""
Interest copied = new Interest(interest);
Component lastComponent = Component.fromNumberWithMarker(segmentNumber, marker);
Name newName = (SegmentationHelper.isSegmented(copied.getName(), marker))
? copied.getName().getPrefix(-1)
: new Name(copied.getName());
copied.setName(newName.append(lastComponent));
return copied;
} | java | protected Interest replaceFinalComponent(Interest interest, long segmentNumber, byte marker) {
Interest copied = new Interest(interest);
Component lastComponent = Component.fromNumberWithMarker(segmentNumber, marker);
Name newName = (SegmentationHelper.isSegmented(copied.getName(), marker))
? copied.getName().getPrefix(-1)
: new Name(copied.getName());
copied.setName(newName.append(lastComponent));
return copied;
} | [
"protected",
"Interest",
"replaceFinalComponent",
"(",
"Interest",
"interest",
",",
"long",
"segmentNumber",
",",
"byte",
"marker",
")",
"{",
"Interest",
"copied",
"=",
"new",
"Interest",
"(",
"interest",
")",
";",
"Component",
"lastComponent",
"=",
"Component",
... | Replace the final component of an interest name with a segmented component;
if the interest name does not have a segmented component, this will add
one.
@param interest the request
@param segmentNumber a segment number
@param marker a marker to use for segmenting the packet
@return a segmented interest (a copy of the passed interest) | [
"Replace",
"the",
"final",
"component",
"of",
"an",
"interest",
"name",
"with",
"a",
"segmented",
"component",
";",
"if",
"the",
"interest",
"name",
"does",
"not",
"have",
"a",
"segmented",
"component",
"this",
"will",
"add",
"one",
"."
] | train | https://github.com/intel/jndn-utils/blob/7f670b259484c35d51a6c5acce5715b0573faedd/src/main/java/com/intel/jndn/utils/client/impl/DefaultSegmentedClient.java#L81-L89 |
HeidelTime/heideltime | src/jflexcrf/Feature.java | Feature.eFeature1Init | public void eFeature1Init(int y, int yp, Map fmap) {
"""
E feature1 init.
@param y the y
@param yp the yp
@param fmap the fmap
"""
eFeature1Init(y, yp);
strId2IdxAdd(fmap);
} | java | public void eFeature1Init(int y, int yp, Map fmap) {
eFeature1Init(y, yp);
strId2IdxAdd(fmap);
} | [
"public",
"void",
"eFeature1Init",
"(",
"int",
"y",
",",
"int",
"yp",
",",
"Map",
"fmap",
")",
"{",
"eFeature1Init",
"(",
"y",
",",
"yp",
")",
";",
"strId2IdxAdd",
"(",
"fmap",
")",
";",
"}"
] | E feature1 init.
@param y the y
@param yp the yp
@param fmap the fmap | [
"E",
"feature1",
"init",
"."
] | train | https://github.com/HeidelTime/heideltime/blob/4ef5002eb5ecfeb818086ff7e394e792ee360335/src/jflexcrf/Feature.java#L96-L99 |
looly/hutool | hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java | FileUtil.copy | public static File copy(File src, File dest, boolean isOverride) throws IORuntimeException {
"""
复制文件或目录<br>
情况如下:
<pre>
1、src和dest都为目录,则将src目录及其目录下所有文件目录拷贝到dest下
2、src和dest都为文件,直接复制,名字为dest
3、src为文件,dest为目录,将src拷贝到dest目录下
</pre>
@param src 源文件
@param dest 目标文件或目录,目标不存在会自动创建(目录、文件都创建)
@param isOverride 是否覆盖目标文件
@return 目标目录或文件
@throws IORuntimeException IO异常
"""
return FileCopier.create(src, dest).setOverride(isOverride).copy();
} | java | public static File copy(File src, File dest, boolean isOverride) throws IORuntimeException {
return FileCopier.create(src, dest).setOverride(isOverride).copy();
} | [
"public",
"static",
"File",
"copy",
"(",
"File",
"src",
",",
"File",
"dest",
",",
"boolean",
"isOverride",
")",
"throws",
"IORuntimeException",
"{",
"return",
"FileCopier",
".",
"create",
"(",
"src",
",",
"dest",
")",
".",
"setOverride",
"(",
"isOverride",
... | 复制文件或目录<br>
情况如下:
<pre>
1、src和dest都为目录,则将src目录及其目录下所有文件目录拷贝到dest下
2、src和dest都为文件,直接复制,名字为dest
3、src为文件,dest为目录,将src拷贝到dest目录下
</pre>
@param src 源文件
@param dest 目标文件或目录,目标不存在会自动创建(目录、文件都创建)
@param isOverride 是否覆盖目标文件
@return 目标目录或文件
@throws IORuntimeException IO异常 | [
"复制文件或目录<br",
">",
"情况如下:"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/io/FileUtil.java#L1003-L1005 |
jpush/jmessage-api-java-client | src/main/java/cn/jmessage/api/message/MessageClient.java | MessageClient.getUserMessagesByCursor | @Deprecated
public MessageListResult getUserMessagesByCursor(String username, String cursor)
throws APIConnectionException, APIRequestException {
"""
Please use {@link cn.jmessage.api.reportv2.ReportClient#v2GetUserMessagesByCursor}
Get user's message list with cursor, the cursor will effective in 120 seconds.
And will return same count of messages as first request.
@param username Necessary parameter.
@param cursor First request will return cursor
@return MessageListResult
@throws APIConnectionException connect exception
@throws APIRequestException request exception
"""
StringUtils.checkUsername(username);
if (null != cursor) {
String requestUrl = reportBaseUrl + v2_userPath + "/" + username + "/messages?cursor=" + cursor;
ResponseWrapper response = _httpClient.sendGet(requestUrl);
return MessageListResult.fromResponse(response, MessageListResult.class);
} else {
throw new IllegalArgumentException("the cursor parameter should not be null");
}
} | java | @Deprecated
public MessageListResult getUserMessagesByCursor(String username, String cursor)
throws APIConnectionException, APIRequestException {
StringUtils.checkUsername(username);
if (null != cursor) {
String requestUrl = reportBaseUrl + v2_userPath + "/" + username + "/messages?cursor=" + cursor;
ResponseWrapper response = _httpClient.sendGet(requestUrl);
return MessageListResult.fromResponse(response, MessageListResult.class);
} else {
throw new IllegalArgumentException("the cursor parameter should not be null");
}
} | [
"@",
"Deprecated",
"public",
"MessageListResult",
"getUserMessagesByCursor",
"(",
"String",
"username",
",",
"String",
"cursor",
")",
"throws",
"APIConnectionException",
",",
"APIRequestException",
"{",
"StringUtils",
".",
"checkUsername",
"(",
"username",
")",
";",
"... | Please use {@link cn.jmessage.api.reportv2.ReportClient#v2GetUserMessagesByCursor}
Get user's message list with cursor, the cursor will effective in 120 seconds.
And will return same count of messages as first request.
@param username Necessary parameter.
@param cursor First request will return cursor
@return MessageListResult
@throws APIConnectionException connect exception
@throws APIRequestException request exception | [
"Please",
"use",
"{"
] | train | https://github.com/jpush/jmessage-api-java-client/blob/767f5fb15e9fe5a546c00f6e68b64f6dd53c617c/src/main/java/cn/jmessage/api/message/MessageClient.java#L184-L195 |
OpenLiberty/open-liberty | dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java | InjectionUtils.getAsynchronizedGenericType | private static Type getAsynchronizedGenericType(Object targetObject) {
"""
Hack to generate a type class for collection object.
@param targetObject
@return
"""
if (targetObject instanceof java.util.Collection) {
Class<? extends java.util.Collection> rawType = (Class<? extends Collection>) targetObject.getClass();
Class<?> actualType = Object.class;
if (((java.util.Collection<?>) targetObject).size() > 0) {
Object element = ((java.util.Collection<?>) targetObject).iterator().next();
actualType = element.getClass();
}
return new ParameterizedType() {
private Type actualType, rawType;
public ParameterizedType setTypes(Type actualType, Type rawType) {
this.actualType = actualType;
this.rawType = rawType;
return this;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[] { actualType };
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return null;
}
}.setTypes(actualType, rawType);
} else
return targetObject.getClass();
} | java | private static Type getAsynchronizedGenericType(Object targetObject) {
if (targetObject instanceof java.util.Collection) {
Class<? extends java.util.Collection> rawType = (Class<? extends Collection>) targetObject.getClass();
Class<?> actualType = Object.class;
if (((java.util.Collection<?>) targetObject).size() > 0) {
Object element = ((java.util.Collection<?>) targetObject).iterator().next();
actualType = element.getClass();
}
return new ParameterizedType() {
private Type actualType, rawType;
public ParameterizedType setTypes(Type actualType, Type rawType) {
this.actualType = actualType;
this.rawType = rawType;
return this;
}
@Override
public Type[] getActualTypeArguments() {
return new Type[] { actualType };
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return null;
}
}.setTypes(actualType, rawType);
} else
return targetObject.getClass();
} | [
"private",
"static",
"Type",
"getAsynchronizedGenericType",
"(",
"Object",
"targetObject",
")",
"{",
"if",
"(",
"targetObject",
"instanceof",
"java",
".",
"util",
".",
"Collection",
")",
"{",
"Class",
"<",
"?",
"extends",
"java",
".",
"util",
".",
"Collection"... | Hack to generate a type class for collection object.
@param targetObject
@return | [
"Hack",
"to",
"generate",
"a",
"type",
"class",
"for",
"collection",
"object",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.org.apache.cxf.cxf.rt.frontend.jaxrs.3.2/src/org/apache/cxf/jaxrs/utils/InjectionUtils.java#L1780-L1815 |
beangle/beangle3 | struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java | Component.findValue | protected Object findValue(String expr, Class<?> toType) {
"""
Evaluates the OGNL stack to find an Object of the given type. Will
evaluate <code>expr</code> the portion wrapped with altSyntax (%{...})
against stack when altSyntax is on, else the whole <code>expr</code> is
evaluated against the stack.
<p/>
This method only supports the altSyntax. So this should be set to true.
@param expr
OGNL expression.
@param toType
the type expected to find.
@return the Object found, or <tt>null</tt> if not found.
"""
if (altSyntax() && toType == String.class) {
return TextParseUtil.translateVariables('%', expr, stack);
} else {
expr = stripExpressionIfAltSyntax(expr);
return stack.findValue(expr, toType, false);
}
} | java | protected Object findValue(String expr, Class<?> toType) {
if (altSyntax() && toType == String.class) {
return TextParseUtil.translateVariables('%', expr, stack);
} else {
expr = stripExpressionIfAltSyntax(expr);
return stack.findValue(expr, toType, false);
}
} | [
"protected",
"Object",
"findValue",
"(",
"String",
"expr",
",",
"Class",
"<",
"?",
">",
"toType",
")",
"{",
"if",
"(",
"altSyntax",
"(",
")",
"&&",
"toType",
"==",
"String",
".",
"class",
")",
"{",
"return",
"TextParseUtil",
".",
"translateVariables",
"(... | Evaluates the OGNL stack to find an Object of the given type. Will
evaluate <code>expr</code> the portion wrapped with altSyntax (%{...})
against stack when altSyntax is on, else the whole <code>expr</code> is
evaluated against the stack.
<p/>
This method only supports the altSyntax. So this should be set to true.
@param expr
OGNL expression.
@param toType
the type expected to find.
@return the Object found, or <tt>null</tt> if not found. | [
"Evaluates",
"the",
"OGNL",
"stack",
"to",
"find",
"an",
"Object",
"of",
"the",
"given",
"type",
".",
"Will",
"evaluate",
"<code",
">",
"expr<",
"/",
"code",
">",
"the",
"portion",
"wrapped",
"with",
"altSyntax",
"(",
"%",
"{",
"...",
"}",
")",
"agains... | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/struts/s2/src/main/java/org/beangle/struts2/view/component/Component.java#L360-L367 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/util/search/support/BinarySearch.java | BinarySearch.doSearch | protected <E> E doSearch(final List<E> list) {
"""
Performs the actual (binary) search of an ordered collection (List) of elements in search of a single element
matching the criteria defined by the Matcher.
@param <E> the Class type of the elements in the List.
@param list the List of elements to search.
@return a single element of the List matching the criteria defined by the Matcher or null if no element in the List
matches the criteria defined by the Matcher.
@see #getMatcher()
@see #search(java.util.Collection)
@see java.util.List
"""
if (!list.isEmpty()) {
int matchIndex = (list.size() / 2);
E element = list.get(matchIndex);
int matchResult = getMatcher().match(element);
if (matchResult == 0) {
return element;
}
else if (matchResult < 0) {
return doSearch(list.subList(0, matchIndex));
}
else {
return doSearch(list.subList(matchIndex + 1, list.size()));
}
}
return null;
} | java | protected <E> E doSearch(final List<E> list) {
if (!list.isEmpty()) {
int matchIndex = (list.size() / 2);
E element = list.get(matchIndex);
int matchResult = getMatcher().match(element);
if (matchResult == 0) {
return element;
}
else if (matchResult < 0) {
return doSearch(list.subList(0, matchIndex));
}
else {
return doSearch(list.subList(matchIndex + 1, list.size()));
}
}
return null;
} | [
"protected",
"<",
"E",
">",
"E",
"doSearch",
"(",
"final",
"List",
"<",
"E",
">",
"list",
")",
"{",
"if",
"(",
"!",
"list",
".",
"isEmpty",
"(",
")",
")",
"{",
"int",
"matchIndex",
"=",
"(",
"list",
".",
"size",
"(",
")",
"/",
"2",
")",
";",
... | Performs the actual (binary) search of an ordered collection (List) of elements in search of a single element
matching the criteria defined by the Matcher.
@param <E> the Class type of the elements in the List.
@param list the List of elements to search.
@return a single element of the List matching the criteria defined by the Matcher or null if no element in the List
matches the criteria defined by the Matcher.
@see #getMatcher()
@see #search(java.util.Collection)
@see java.util.List | [
"Performs",
"the",
"actual",
"(",
"binary",
")",
"search",
"of",
"an",
"ordered",
"collection",
"(",
"List",
")",
"of",
"elements",
"in",
"search",
"of",
"a",
"single",
"element",
"matching",
"the",
"criteria",
"defined",
"by",
"the",
"Matcher",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/util/search/support/BinarySearch.java#L73-L91 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PathNormalizer.java | PathNormalizer.normalizePath | public static final String normalizePath(String path) {
"""
Removes leading and trailing separators from a path, and removes double
separators (// is replaced by /).
@param path
the path to normalize
@return the normalized path
"""
String normalizedPath = path.replaceAll("//", JawrConstant.URL_SEPARATOR);
StringTokenizer tk = new StringTokenizer(normalizedPath, JawrConstant.URL_SEPARATOR);
StringBuilder sb = new StringBuilder();
while (tk.hasMoreTokens()) {
sb.append(tk.nextToken());
if (tk.hasMoreTokens())
sb.append(JawrConstant.URL_SEPARATOR);
}
return sb.toString();
} | java | public static final String normalizePath(String path) {
String normalizedPath = path.replaceAll("//", JawrConstant.URL_SEPARATOR);
StringTokenizer tk = new StringTokenizer(normalizedPath, JawrConstant.URL_SEPARATOR);
StringBuilder sb = new StringBuilder();
while (tk.hasMoreTokens()) {
sb.append(tk.nextToken());
if (tk.hasMoreTokens())
sb.append(JawrConstant.URL_SEPARATOR);
}
return sb.toString();
} | [
"public",
"static",
"final",
"String",
"normalizePath",
"(",
"String",
"path",
")",
"{",
"String",
"normalizedPath",
"=",
"path",
".",
"replaceAll",
"(",
"\"//\"",
",",
"JawrConstant",
".",
"URL_SEPARATOR",
")",
";",
"StringTokenizer",
"tk",
"=",
"new",
"Strin... | Removes leading and trailing separators from a path, and removes double
separators (// is replaced by /).
@param path
the path to normalize
@return the normalized path | [
"Removes",
"leading",
"and",
"trailing",
"separators",
"from",
"a",
"path",
"and",
"removes",
"double",
"separators",
"(",
"//",
"is",
"replaced",
"by",
"/",
")",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/factory/util/PathNormalizer.java#L363-L374 |
apache/incubator-zipkin | zipkin-storage/cassandra-v1/src/main/java/zipkin2/storage/cassandra/v1/TimestampCodec.java | TimestampCodec.deserialize | public long deserialize(Row row, String name) {
"""
Reads timestamp binary value directly (getBytesUnsafe) to avoid allocating java.util.Date, and
converts to microseconds.
"""
return 1000L * TypeCodec.bigint().deserialize(row.getBytesUnsafe(name), protocolVersion);
} | java | public long deserialize(Row row, String name) {
return 1000L * TypeCodec.bigint().deserialize(row.getBytesUnsafe(name), protocolVersion);
} | [
"public",
"long",
"deserialize",
"(",
"Row",
"row",
",",
"String",
"name",
")",
"{",
"return",
"1000L",
"*",
"TypeCodec",
".",
"bigint",
"(",
")",
".",
"deserialize",
"(",
"row",
".",
"getBytesUnsafe",
"(",
"name",
")",
",",
"protocolVersion",
")",
";",
... | Reads timestamp binary value directly (getBytesUnsafe) to avoid allocating java.util.Date, and
converts to microseconds. | [
"Reads",
"timestamp",
"binary",
"value",
"directly",
"(",
"getBytesUnsafe",
")",
"to",
"avoid",
"allocating",
"java",
".",
"util",
".",
"Date",
"and",
"converts",
"to",
"microseconds",
"."
] | train | https://github.com/apache/incubator-zipkin/blob/89b2fab983fc626b3be32ce9d7cf64b3f01f1a87/zipkin-storage/cassandra-v1/src/main/java/zipkin2/storage/cassandra/v1/TimestampCodec.java#L48-L50 |
restfb/restfb | src/main/java/com/restfb/util/ReflectionUtils.java | ReflectionUtils.findFieldsWithAnnotation | public static <T extends Annotation> List<FieldWithAnnotation<T>> findFieldsWithAnnotation(Class<?> type,
Class<T> annotationType) {
"""
Finds fields on the given {@code type} and all of its superclasses annotated with annotations of type
{@code annotationType}.
@param <T>
The annotation type.
@param type
The target type token.
@param annotationType
The annotation type token.
@return A list of field/annotation pairs.
"""
ClassAnnotationCacheKey cacheKey = new ClassAnnotationCacheKey(type, annotationType);
@SuppressWarnings("unchecked")
List<FieldWithAnnotation<T>> cachedResults =
(List<FieldWithAnnotation<T>>) FIELDS_WITH_ANNOTATION_CACHE.get(cacheKey);
if (cachedResults != null) {
return cachedResults;
}
List<FieldWithAnnotation<T>> fieldsWithAnnotation = new ArrayList<>();
// Walk all superclasses looking for annotated fields until we hit Object
while (!Object.class.equals(type) && type != null) {
for (Field field : type.getDeclaredFields()) {
T annotation = field.getAnnotation(annotationType);
if (annotation != null) {
fieldsWithAnnotation.add(new FieldWithAnnotation<>(field, annotation));
}
}
type = type.getSuperclass();
}
fieldsWithAnnotation = unmodifiableList(fieldsWithAnnotation);
FIELDS_WITH_ANNOTATION_CACHE.put(cacheKey, fieldsWithAnnotation);
return fieldsWithAnnotation;
} | java | public static <T extends Annotation> List<FieldWithAnnotation<T>> findFieldsWithAnnotation(Class<?> type,
Class<T> annotationType) {
ClassAnnotationCacheKey cacheKey = new ClassAnnotationCacheKey(type, annotationType);
@SuppressWarnings("unchecked")
List<FieldWithAnnotation<T>> cachedResults =
(List<FieldWithAnnotation<T>>) FIELDS_WITH_ANNOTATION_CACHE.get(cacheKey);
if (cachedResults != null) {
return cachedResults;
}
List<FieldWithAnnotation<T>> fieldsWithAnnotation = new ArrayList<>();
// Walk all superclasses looking for annotated fields until we hit Object
while (!Object.class.equals(type) && type != null) {
for (Field field : type.getDeclaredFields()) {
T annotation = field.getAnnotation(annotationType);
if (annotation != null) {
fieldsWithAnnotation.add(new FieldWithAnnotation<>(field, annotation));
}
}
type = type.getSuperclass();
}
fieldsWithAnnotation = unmodifiableList(fieldsWithAnnotation);
FIELDS_WITH_ANNOTATION_CACHE.put(cacheKey, fieldsWithAnnotation);
return fieldsWithAnnotation;
} | [
"public",
"static",
"<",
"T",
"extends",
"Annotation",
">",
"List",
"<",
"FieldWithAnnotation",
"<",
"T",
">",
">",
"findFieldsWithAnnotation",
"(",
"Class",
"<",
"?",
">",
"type",
",",
"Class",
"<",
"T",
">",
"annotationType",
")",
"{",
"ClassAnnotationCach... | Finds fields on the given {@code type} and all of its superclasses annotated with annotations of type
{@code annotationType}.
@param <T>
The annotation type.
@param type
The target type token.
@param annotationType
The annotation type token.
@return A list of field/annotation pairs. | [
"Finds",
"fields",
"on",
"the",
"given",
"{",
"@code",
"type",
"}",
"and",
"all",
"of",
"its",
"superclasses",
"annotated",
"with",
"annotations",
"of",
"type",
"{",
"@code",
"annotationType",
"}",
"."
] | train | https://github.com/restfb/restfb/blob/fb77ba5486d1339e7deb81b9830670fa209b1047/src/main/java/com/restfb/util/ReflectionUtils.java#L96-L126 |
threerings/gwt-utils | src/main/java/com/threerings/gwt/ui/PagedTable.java | PagedTable.addRow | protected static boolean addRow (SmartTable table, List<Widget> widgets) {
"""
Convenience function to append a list of widgets to a table as a new row.
"""
if (widgets == null) {
return false;
}
int row = table.getRowCount();
for (int col=0; col<widgets.size(); ++col) {
table.setWidget(row, col, widgets.get(col));
table.getFlexCellFormatter().setStyleName(row, col, "col"+col);
}
return true;
} | java | protected static boolean addRow (SmartTable table, List<Widget> widgets)
{
if (widgets == null) {
return false;
}
int row = table.getRowCount();
for (int col=0; col<widgets.size(); ++col) {
table.setWidget(row, col, widgets.get(col));
table.getFlexCellFormatter().setStyleName(row, col, "col"+col);
}
return true;
} | [
"protected",
"static",
"boolean",
"addRow",
"(",
"SmartTable",
"table",
",",
"List",
"<",
"Widget",
">",
"widgets",
")",
"{",
"if",
"(",
"widgets",
"==",
"null",
")",
"{",
"return",
"false",
";",
"}",
"int",
"row",
"=",
"table",
".",
"getRowCount",
"("... | Convenience function to append a list of widgets to a table as a new row. | [
"Convenience",
"function",
"to",
"append",
"a",
"list",
"of",
"widgets",
"to",
"a",
"table",
"as",
"a",
"new",
"row",
"."
] | train | https://github.com/threerings/gwt-utils/blob/31b31a23b667f2a9c683160d77646db259f2aae5/src/main/java/com/threerings/gwt/ui/PagedTable.java#L68-L79 |
alkacon/opencms-core | src/org/opencms/ade/publish/CmsDirectPublishProject.java | CmsDirectPublishProject.shouldIncludeContents | protected boolean shouldIncludeContents(Map<String, String> params) {
"""
Returns true if the folder contents should be included.<p>
@param params the publish parameters
@return true if the folder contents should be included
"""
String includeContentsStr = params.get(CmsPublishOptions.PARAM_INCLUDE_CONTENTS);
boolean includeContents = false;
try {
includeContents = Boolean.parseBoolean(includeContentsStr);
} catch (Exception e) {
// ignore; includeContents remains the default value
}
return includeContents;
} | java | protected boolean shouldIncludeContents(Map<String, String> params) {
String includeContentsStr = params.get(CmsPublishOptions.PARAM_INCLUDE_CONTENTS);
boolean includeContents = false;
try {
includeContents = Boolean.parseBoolean(includeContentsStr);
} catch (Exception e) {
// ignore; includeContents remains the default value
}
return includeContents;
} | [
"protected",
"boolean",
"shouldIncludeContents",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"params",
")",
"{",
"String",
"includeContentsStr",
"=",
"params",
".",
"get",
"(",
"CmsPublishOptions",
".",
"PARAM_INCLUDE_CONTENTS",
")",
";",
"boolean",
"includeCon... | Returns true if the folder contents should be included.<p>
@param params the publish parameters
@return true if the folder contents should be included | [
"Returns",
"true",
"if",
"the",
"folder",
"contents",
"should",
"be",
"included",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/publish/CmsDirectPublishProject.java#L173-L183 |
alipay/sofa-rpc | extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java | SofaConfigs.getStringValue0 | private static String getStringValue0(String appName, String key) {
"""
System.getProperty() > 外部配置 > rpc-config.properties
@param appName 应用名
@param key 配置项
@return 配置
"""
String ret = System.getProperty(key);
if (StringUtils.isNotEmpty(ret)) {
return ret;
}
rLock.lock();
try {
for (ExternalConfigLoader configLoader : CONFIG_LOADERS) {
ret = appName == null ? configLoader.getValue(key)
: configLoader.getValue(appName, key);
if (StringUtils.isNotEmpty(ret)) {
return ret;
}
}
} finally {
rLock.unlock();
}
return getConfig().getProperty(key);
} | java | private static String getStringValue0(String appName, String key) {
String ret = System.getProperty(key);
if (StringUtils.isNotEmpty(ret)) {
return ret;
}
rLock.lock();
try {
for (ExternalConfigLoader configLoader : CONFIG_LOADERS) {
ret = appName == null ? configLoader.getValue(key)
: configLoader.getValue(appName, key);
if (StringUtils.isNotEmpty(ret)) {
return ret;
}
}
} finally {
rLock.unlock();
}
return getConfig().getProperty(key);
} | [
"private",
"static",
"String",
"getStringValue0",
"(",
"String",
"appName",
",",
"String",
"key",
")",
"{",
"String",
"ret",
"=",
"System",
".",
"getProperty",
"(",
"key",
")",
";",
"if",
"(",
"StringUtils",
".",
"isNotEmpty",
"(",
"ret",
")",
")",
"{",
... | System.getProperty() > 外部配置 > rpc-config.properties
@param appName 应用名
@param key 配置项
@return 配置 | [
"System",
".",
"getProperty",
"()",
">",
"外部配置",
">",
"rpc",
"-",
"config",
".",
"properties"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/extension-impl/extension-common/src/main/java/com/alipay/sofa/rpc/common/SofaConfigs.java#L183-L201 |
Azure/azure-sdk-for-java | kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java | ClustersInner.listSkusByResourceAsync | public Observable<List<AzureResourceSkuInner>> listSkusByResourceAsync(String resourceGroupName, String clusterName) {
"""
Returns the SKUs available for the provided resource.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<AzureResourceSkuInner> object
"""
return listSkusByResourceWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<List<AzureResourceSkuInner>>, List<AzureResourceSkuInner>>() {
@Override
public List<AzureResourceSkuInner> call(ServiceResponse<List<AzureResourceSkuInner>> response) {
return response.body();
}
});
} | java | public Observable<List<AzureResourceSkuInner>> listSkusByResourceAsync(String resourceGroupName, String clusterName) {
return listSkusByResourceWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<List<AzureResourceSkuInner>>, List<AzureResourceSkuInner>>() {
@Override
public List<AzureResourceSkuInner> call(ServiceResponse<List<AzureResourceSkuInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"List",
"<",
"AzureResourceSkuInner",
">",
">",
"listSkusByResourceAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"return",
"listSkusByResourceWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clus... | Returns the SKUs available for the provided resource.
@param resourceGroupName The name of the resource group containing the Kusto cluster.
@param clusterName The name of the Kusto cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the List<AzureResourceSkuInner> object | [
"Returns",
"the",
"SKUs",
"available",
"for",
"the",
"provided",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/kusto/resource-manager/v2018_09_07_preview/src/main/java/com/microsoft/azure/management/kusto/v2018_09_07_preview/implementation/ClustersInner.java#L1402-L1409 |
aws/aws-sdk-java | aws-java-sdk-lex/src/main/java/com/amazonaws/services/lexruntime/model/PostTextRequest.java | PostTextRequest.withRequestAttributes | public PostTextRequest withRequestAttributes(java.util.Map<String, String> requestAttributes) {
"""
<p>
Request-specific information passed between Amazon Lex and a client application.
</p>
<p>
The namespace <code>x-amz-lex:</code> is reserved for special attributes. Don't create any request attributes
with the prefix <code>x-amz-lex:</code>.
</p>
<p>
For more information, see <a
href="http://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html#context-mgmt-request-attribs">Setting Request
Attributes</a>.
</p>
@param requestAttributes
Request-specific information passed between Amazon Lex and a client application.</p>
<p>
The namespace <code>x-amz-lex:</code> is reserved for special attributes. Don't create any request
attributes with the prefix <code>x-amz-lex:</code>.
</p>
<p>
For more information, see <a
href="http://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html#context-mgmt-request-attribs">Setting
Request Attributes</a>.
@return Returns a reference to this object so that method calls can be chained together.
"""
setRequestAttributes(requestAttributes);
return this;
} | java | public PostTextRequest withRequestAttributes(java.util.Map<String, String> requestAttributes) {
setRequestAttributes(requestAttributes);
return this;
} | [
"public",
"PostTextRequest",
"withRequestAttributes",
"(",
"java",
".",
"util",
".",
"Map",
"<",
"String",
",",
"String",
">",
"requestAttributes",
")",
"{",
"setRequestAttributes",
"(",
"requestAttributes",
")",
";",
"return",
"this",
";",
"}"
] | <p>
Request-specific information passed between Amazon Lex and a client application.
</p>
<p>
The namespace <code>x-amz-lex:</code> is reserved for special attributes. Don't create any request attributes
with the prefix <code>x-amz-lex:</code>.
</p>
<p>
For more information, see <a
href="http://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html#context-mgmt-request-attribs">Setting Request
Attributes</a>.
</p>
@param requestAttributes
Request-specific information passed between Amazon Lex and a client application.</p>
<p>
The namespace <code>x-amz-lex:</code> is reserved for special attributes. Don't create any request
attributes with the prefix <code>x-amz-lex:</code>.
</p>
<p>
For more information, see <a
href="http://docs.aws.amazon.com/lex/latest/dg/context-mgmt.html#context-mgmt-request-attribs">Setting
Request Attributes</a>.
@return Returns a reference to this object so that method calls can be chained together. | [
"<p",
">",
"Request",
"-",
"specific",
"information",
"passed",
"between",
"Amazon",
"Lex",
"and",
"a",
"client",
"application",
".",
"<",
"/",
"p",
">",
"<p",
">",
"The",
"namespace",
"<code",
">",
"x",
"-",
"amz",
"-",
"lex",
":",
"<",
"/",
"code",... | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-lex/src/main/java/com/amazonaws/services/lexruntime/model/PostTextRequest.java#L594-L597 |
JM-Lab/utils-java9 | src/main/java/kr/jm/utils/HttpGetRequester.java | HttpGetRequester.getResponseAsString | public static String getResponseAsString(String uri, String charsetName) {
"""
Gets response as string.
@param uri the uri
@param charsetName the charset name
@return the response as string
"""
return HttpRequester.getResponseAsString(uri, charsetName);
} | java | public static String getResponseAsString(String uri, String charsetName) {
return HttpRequester.getResponseAsString(uri, charsetName);
} | [
"public",
"static",
"String",
"getResponseAsString",
"(",
"String",
"uri",
",",
"String",
"charsetName",
")",
"{",
"return",
"HttpRequester",
".",
"getResponseAsString",
"(",
"uri",
",",
"charsetName",
")",
";",
"}"
] | Gets response as string.
@param uri the uri
@param charsetName the charset name
@return the response as string | [
"Gets",
"response",
"as",
"string",
"."
] | train | https://github.com/JM-Lab/utils-java9/blob/ee80235b2760396a616cf7563cbdc98d4affe8e1/src/main/java/kr/jm/utils/HttpGetRequester.java#L41-L43 |
jpkrohling/secret-store | common/src/main/java/org/keycloak/secretstore/common/AuthServerRequestExecutor.java | AuthServerRequestExecutor.execute | public String execute(String url, String urlParameters, String clientId, String secret, String method) throws
Exception {
"""
Performs an HTTP call to the Keycloak server, returning the server's response as String.
@param url the full URL to call, including protocol, host, port and path.
@param urlParameters the HTTP Query Parameters properly encoded and without the leading "?".
@param clientId the OAuth client ID.
@param secret the OAuth client secret.
@param method the HTTP method to use (GET or POST). If anything other than POST is sent, GET is used.
@return a String with the response from the Keycloak server, in both success and error scenarios
@throws Exception if communication problems with the Keycloak server occurs.
"""
HttpURLConnection connection;
String credentials = clientId + ":" + secret;
String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
if ("POST".equalsIgnoreCase(method)) {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoInput(true);
connection.setDoOutput(true);
if (null != urlParameters) {
try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
out.print(urlParameters);
}
}
} else {
connection = (HttpURLConnection) new URL(url + "?" + urlParameters).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", authorizationHeader);
}
int timeout = Integer.parseInt(System.getProperty("org.hawkular.accounts.http.timeout", "5000"));
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
StringBuilder response = new StringBuilder();
int statusCode;
try {
statusCode = connection.getResponseCode();
} catch (SocketTimeoutException timeoutException) {
throw new UsernamePasswordConversionException("Timed out when trying to contact the Keycloak server.");
}
InputStream inputStream;
if (statusCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
for (String line; (line = reader.readLine()) != null; ) {
response.append(line);
}
}
return response.toString();
} | java | public String execute(String url, String urlParameters, String clientId, String secret, String method) throws
Exception {
HttpURLConnection connection;
String credentials = clientId + ":" + secret;
String authorizationHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
if ("POST".equalsIgnoreCase(method)) {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Authorization", authorizationHeader);
connection.setDoInput(true);
connection.setDoOutput(true);
if (null != urlParameters) {
try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
out.print(urlParameters);
}
}
} else {
connection = (HttpURLConnection) new URL(url + "?" + urlParameters).openConnection();
connection.setRequestMethod(method);
connection.setRequestProperty("Authorization", authorizationHeader);
}
int timeout = Integer.parseInt(System.getProperty("org.hawkular.accounts.http.timeout", "5000"));
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
StringBuilder response = new StringBuilder();
int statusCode;
try {
statusCode = connection.getResponseCode();
} catch (SocketTimeoutException timeoutException) {
throw new UsernamePasswordConversionException("Timed out when trying to contact the Keycloak server.");
}
InputStream inputStream;
if (statusCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
for (String line; (line = reader.readLine()) != null; ) {
response.append(line);
}
}
return response.toString();
} | [
"public",
"String",
"execute",
"(",
"String",
"url",
",",
"String",
"urlParameters",
",",
"String",
"clientId",
",",
"String",
"secret",
",",
"String",
"method",
")",
"throws",
"Exception",
"{",
"HttpURLConnection",
"connection",
";",
"String",
"credentials",
"=... | Performs an HTTP call to the Keycloak server, returning the server's response as String.
@param url the full URL to call, including protocol, host, port and path.
@param urlParameters the HTTP Query Parameters properly encoded and without the leading "?".
@param clientId the OAuth client ID.
@param secret the OAuth client secret.
@param method the HTTP method to use (GET or POST). If anything other than POST is sent, GET is used.
@return a String with the response from the Keycloak server, in both success and error scenarios
@throws Exception if communication problems with the Keycloak server occurs. | [
"Performs",
"an",
"HTTP",
"call",
"to",
"the",
"Keycloak",
"server",
"returning",
"the",
"server",
"s",
"response",
"as",
"String",
"."
] | train | https://github.com/jpkrohling/secret-store/blob/f136ea6286a6919cc767d0b4a5e84f333c33f483/common/src/main/java/org/keycloak/secretstore/common/AuthServerRequestExecutor.java#L66-L120 |
RestComm/sip-servlets | sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SessionManagerUtil.java | SessionManagerUtil.getSipApplicationSessionKey | public static SipApplicationSessionKey getSipApplicationSessionKey(final String applicationName, final String id, final String appGeneratedKey) {
"""
Computes the sip application session key from the input parameters.
The sip application session key will be of the form (UUID,APPNAME)
@param applicationName the name of the application that will be the second component of the key
@param id the Id composing the first component of the key
@return the computed key
@throws NullPointerException if one of the two parameters is null
"""
if (logger.isDebugEnabled()){
logger.debug("getSipApplicationSessionKey - applicationName=" + applicationName + ", id=" + id + ", appGeneratedKey=" + appGeneratedKey);
}
if(applicationName == null) {
throw new NullPointerException("the application name cannot be null for sip application session key creation");
}
return new SipApplicationSessionKey(
id,
applicationName,
appGeneratedKey);
} | java | public static SipApplicationSessionKey getSipApplicationSessionKey(final String applicationName, final String id, final String appGeneratedKey) {
if (logger.isDebugEnabled()){
logger.debug("getSipApplicationSessionKey - applicationName=" + applicationName + ", id=" + id + ", appGeneratedKey=" + appGeneratedKey);
}
if(applicationName == null) {
throw new NullPointerException("the application name cannot be null for sip application session key creation");
}
return new SipApplicationSessionKey(
id,
applicationName,
appGeneratedKey);
} | [
"public",
"static",
"SipApplicationSessionKey",
"getSipApplicationSessionKey",
"(",
"final",
"String",
"applicationName",
",",
"final",
"String",
"id",
",",
"final",
"String",
"appGeneratedKey",
")",
"{",
"if",
"(",
"logger",
".",
"isDebugEnabled",
"(",
")",
")",
... | Computes the sip application session key from the input parameters.
The sip application session key will be of the form (UUID,APPNAME)
@param applicationName the name of the application that will be the second component of the key
@param id the Id composing the first component of the key
@return the computed key
@throws NullPointerException if one of the two parameters is null | [
"Computes",
"the",
"sip",
"application",
"session",
"key",
"from",
"the",
"input",
"parameters",
".",
"The",
"sip",
"application",
"session",
"key",
"will",
"be",
"of",
"the",
"form",
"(",
"UUID",
"APPNAME",
")"
] | train | https://github.com/RestComm/sip-servlets/blob/fd7011d2803ab1d205b140768a760c8c69e0c997/sip-servlets-impl/src/main/java/org/mobicents/servlet/sip/core/session/SessionManagerUtil.java#L114-L125 |
Azure/azure-sdk-for-java | sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java | SyncGroupsInner.refreshHubSchemaAsync | public Observable<Void> refreshHubSchemaAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName) {
"""
Refreshes a hub database schema.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database on which the sync group is hosted.
@param syncGroupName The name of the sync group.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request
"""
return refreshHubSchemaWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> refreshHubSchemaAsync(String resourceGroupName, String serverName, String databaseName, String syncGroupName) {
return refreshHubSchemaWithServiceResponseAsync(resourceGroupName, serverName, databaseName, syncGroupName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"refreshHubSchemaAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"serverName",
",",
"String",
"databaseName",
",",
"String",
"syncGroupName",
")",
"{",
"return",
"refreshHubSchemaWithServiceResponseAsync",
"(",
"resou... | Refreshes a hub database schema.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param serverName The name of the server.
@param databaseName The name of the database on which the sync group is hosted.
@param syncGroupName The name of the sync group.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable for the request | [
"Refreshes",
"a",
"hub",
"database",
"schema",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SyncGroupsInner.java#L299-L306 |
aws/aws-sdk-java | aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/util/SignerUtils.java | SignerUtils.makeBytesUrlSafe | public static String makeBytesUrlSafe(byte[] bytes) {
"""
Converts the given data to be safe for use in signed URLs for a private
distribution by using specialized Base64 encoding.
"""
byte[] encoded = Base64.encode(bytes);
for (int i=0; i < encoded.length; i++) {
switch(encoded[i]) {
case '+':
encoded[i] = '-'; continue;
case '=':
encoded[i] = '_'; continue;
case '/':
encoded[i] = '~'; continue;
default:
continue;
}
}
return new String(encoded, UTF8);
} | java | public static String makeBytesUrlSafe(byte[] bytes) {
byte[] encoded = Base64.encode(bytes);
for (int i=0; i < encoded.length; i++) {
switch(encoded[i]) {
case '+':
encoded[i] = '-'; continue;
case '=':
encoded[i] = '_'; continue;
case '/':
encoded[i] = '~'; continue;
default:
continue;
}
}
return new String(encoded, UTF8);
} | [
"public",
"static",
"String",
"makeBytesUrlSafe",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"byte",
"[",
"]",
"encoded",
"=",
"Base64",
".",
"encode",
"(",
"bytes",
")",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"encoded",
".",
"length"... | Converts the given data to be safe for use in signed URLs for a private
distribution by using specialized Base64 encoding. | [
"Converts",
"the",
"given",
"data",
"to",
"be",
"safe",
"for",
"use",
"in",
"signed",
"URLs",
"for",
"a",
"private",
"distribution",
"by",
"using",
"specialized",
"Base64",
"encoding",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cloudfront/src/main/java/com/amazonaws/services/cloudfront/util/SignerUtils.java#L97-L113 |
gliga/ekstazi | org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java | AbstractMojoInterceptor.throwMojoExecutionException | protected static void throwMojoExecutionException(Object mojo, String message, Exception cause) throws Exception {
"""
Throws MojoExecutionException.
@param mojo
Surefire plugin
@param message
Message for the exception
@param cause
The actual exception
@throws Exception
MojoExecutionException
"""
Class<?> clz = mojo.getClass().getClassLoader().loadClass(MavenNames.MOJO_EXECUTION_EXCEPTION_BIN);
Constructor<?> con = clz.getConstructor(String.class, Exception.class);
Exception ex = (Exception) con.newInstance(message, cause);
throw ex;
} | java | protected static void throwMojoExecutionException(Object mojo, String message, Exception cause) throws Exception {
Class<?> clz = mojo.getClass().getClassLoader().loadClass(MavenNames.MOJO_EXECUTION_EXCEPTION_BIN);
Constructor<?> con = clz.getConstructor(String.class, Exception.class);
Exception ex = (Exception) con.newInstance(message, cause);
throw ex;
} | [
"protected",
"static",
"void",
"throwMojoExecutionException",
"(",
"Object",
"mojo",
",",
"String",
"message",
",",
"Exception",
"cause",
")",
"throws",
"Exception",
"{",
"Class",
"<",
"?",
">",
"clz",
"=",
"mojo",
".",
"getClass",
"(",
")",
".",
"getClassLo... | Throws MojoExecutionException.
@param mojo
Surefire plugin
@param message
Message for the exception
@param cause
The actual exception
@throws Exception
MojoExecutionException | [
"Throws",
"MojoExecutionException",
"."
] | train | https://github.com/gliga/ekstazi/blob/5bf4d39a13305afe62f8b8d2d7b4c573d37d42a1/org.ekstazi.core/src/main/java/org/ekstazi/maven/AbstractMojoInterceptor.java#L80-L85 |
synchronoss/cpo-api | cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java | CassandraCpoAdapter.getWriteSession | protected Session getWriteSession() throws CpoException {
"""
getWriteSession returns the write session for Cassandra
@return A Session object for writing
@throws CpoException
"""
Session session;
try {
session = getWriteDataSource().getSession();
} catch (Throwable t) {
String msg = "getWriteConnection(): failed";
logger.error(msg, t);
throw new CpoException(msg, t);
}
return session;
} | java | protected Session getWriteSession() throws CpoException {
Session session;
try {
session = getWriteDataSource().getSession();
} catch (Throwable t) {
String msg = "getWriteConnection(): failed";
logger.error(msg, t);
throw new CpoException(msg, t);
}
return session;
} | [
"protected",
"Session",
"getWriteSession",
"(",
")",
"throws",
"CpoException",
"{",
"Session",
"session",
";",
"try",
"{",
"session",
"=",
"getWriteDataSource",
"(",
")",
".",
"getSession",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"t",
")",
"{",
"Str... | getWriteSession returns the write session for Cassandra
@return A Session object for writing
@throws CpoException | [
"getWriteSession",
"returns",
"the",
"write",
"session",
"for",
"Cassandra"
] | train | https://github.com/synchronoss/cpo-api/blob/dc745aca3b3206abf80b85d9689b0132f5baa694/cpo-cassandra/src/main/java/org/synchronoss/cpo/cassandra/CassandraCpoAdapter.java#L1954-L1966 |
sarl/sarl | main/coreplugins/io.sarl.lang.core/src/io/sarl/lang/scoping/extensions/numbers/arithmetic/FloatArithmeticExtensions.java | FloatArithmeticExtensions.operator_power | @Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, long right) {
"""
The binary {@code power} operator. This is the equivalent to
the Java's {@code Math.pow()} function. This function is not null-safe.
@param left a number.
@param right a number.
@return {@code Math::pow(left, right)}
"""
return Math.pow(left.floatValue(), right);
} | java | @Pure
@Inline(value = "$3.pow($1.floatValue(), $2)", imported = Math.class)
public static double operator_power(Float left, long right) {
return Math.pow(left.floatValue(), right);
} | [
"@",
"Pure",
"@",
"Inline",
"(",
"value",
"=",
"\"$3.pow($1.floatValue(), $2)\"",
",",
"imported",
"=",
"Math",
".",
"class",
")",
"public",
"static",
"double",
"operator_power",
"(",
"Float",
"left",
",",
"long",
"right",
")",
"{",
"return",
"Math",
".",
... | The binary {@code power} operator. This is the equivalent to
the Java's {@code Math.pow()} function. This function is not null-safe.
@param left a number.
@param right a number.
@return {@code Math::pow(left, right)} | [
"The",
"binary",
"{",
"@code",
"power",
"}",
"operator",
".",
"This",
"is",
"the",
"equivalent",
"to",
"the",
"Java",
"s",
"{",
"@code",
"Math",
".",
"pow",
"()",
"}",
"function",
".",
"This",
"function",
"is",
"not",
"null",
"-",
"safe",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.core/src/io/sarl/lang/scoping/extensions/numbers/arithmetic/FloatArithmeticExtensions.java#L429-L433 |
apache/flink | flink-core/src/main/java/org/apache/flink/util/Preconditions.java | Preconditions.checkElementIndex | public static void checkElementIndex(int index, int size) {
"""
Ensures that the given index is valid for an array, list or string of the given size.
@param index index to check
@param size size of the array, list or string
@throws IllegalArgumentException Thrown, if size is negative.
@throws IndexOutOfBoundsException Thrown, if the index negative or greater than or equal to size
"""
checkArgument(size >= 0, "Size was negative.");
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
} | java | public static void checkElementIndex(int index, int size) {
checkArgument(size >= 0, "Size was negative.");
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
}
} | [
"public",
"static",
"void",
"checkElementIndex",
"(",
"int",
"index",
",",
"int",
"size",
")",
"{",
"checkArgument",
"(",
"size",
">=",
"0",
",",
"\"Size was negative.\"",
")",
";",
"if",
"(",
"index",
"<",
"0",
"||",
"index",
">=",
"size",
")",
"{",
"... | Ensures that the given index is valid for an array, list or string of the given size.
@param index index to check
@param size size of the array, list or string
@throws IllegalArgumentException Thrown, if size is negative.
@throws IndexOutOfBoundsException Thrown, if the index negative or greater than or equal to size | [
"Ensures",
"that",
"the",
"given",
"index",
"is",
"valid",
"for",
"an",
"array",
"list",
"or",
"string",
"of",
"the",
"given",
"size",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-core/src/main/java/org/apache/flink/util/Preconditions.java#L230-L235 |
mikepenz/Android-Iconics | library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java | IconicsDrawable.sizeDpX | @NonNull
public IconicsDrawable sizeDpX(@Dimension(unit = DP) int sizeDp) {
"""
Set the size of the drawable.
@param sizeDp The size in density-independent pixels (dp).
@return The current IconicsDrawable for chaining.
"""
return sizePxX(Utils.convertDpToPx(mContext, sizeDp));
} | java | @NonNull
public IconicsDrawable sizeDpX(@Dimension(unit = DP) int sizeDp) {
return sizePxX(Utils.convertDpToPx(mContext, sizeDp));
} | [
"@",
"NonNull",
"public",
"IconicsDrawable",
"sizeDpX",
"(",
"@",
"Dimension",
"(",
"unit",
"=",
"DP",
")",
"int",
"sizeDp",
")",
"{",
"return",
"sizePxX",
"(",
"Utils",
".",
"convertDpToPx",
"(",
"mContext",
",",
"sizeDp",
")",
")",
";",
"}"
] | Set the size of the drawable.
@param sizeDp The size in density-independent pixels (dp).
@return The current IconicsDrawable for chaining. | [
"Set",
"the",
"size",
"of",
"the",
"drawable",
"."
] | train | https://github.com/mikepenz/Android-Iconics/blob/0b2c8f7d07b6d2715a417563c66311e7e1fcc7d8/library-core/src/main/java/com/mikepenz/iconics/IconicsDrawable.java#L681-L684 |
zaproxy/zaproxy | src/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java | ApiResponseConversionUtils.httpMessageToSet | public static ApiResponseSet<String> httpMessageToSet(int historyId, int historyType, HttpMessage msg) {
"""
Converts the given HTTP message into an {@code ApiResponseSet}.
@param historyId the ID of the message
@param historyType the type of the message
@param msg the HTTP message to be converted
@return the {@code ApiResponseSet} with the ID, type and the HTTP message
@since 2.6.0
"""
Map<String, String> map = new HashMap<>();
map.put("id", String.valueOf(historyId));
map.put("type", String.valueOf(historyType));
map.put("timestamp", String.valueOf(msg.getTimeSentMillis()));
map.put("rtt", String.valueOf(msg.getTimeElapsedMillis()));
map.put("cookieParams", msg.getCookieParamsAsString());
map.put("note", msg.getNote());
map.put("requestHeader", msg.getRequestHeader().toString());
map.put("requestBody", msg.getRequestBody().toString());
map.put("responseHeader", msg.getResponseHeader().toString());
if (HttpHeader.GZIP.equals(msg.getResponseHeader().getHeader(HttpHeader.CONTENT_ENCODING))) {
// Uncompress gziped content
try (ByteArrayInputStream bais = new ByteArrayInputStream(msg.getResponseBody().getBytes());
GZIPInputStream gis = new GZIPInputStream(bais);
InputStreamReader isr = new InputStreamReader(gis);
BufferedReader br = new BufferedReader(isr);) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
map.put("responseBody", sb.toString());
} catch (IOException e) {
LOGGER.error("Unable to uncompress gzip content: " + e.getMessage(), e);
map.put("responseBody", msg.getResponseBody().toString());
}
} else {
map.put("responseBody", msg.getResponseBody().toString());
}
List<String> tags = Collections.emptyList();
try {
tags = HistoryReference.getTags(historyId);
} catch (DatabaseException e) {
LOGGER.warn("Failed to obtain the tags for message with ID " + historyId, e);
}
return new HttpMessageResponseSet(map, tags);
} | java | public static ApiResponseSet<String> httpMessageToSet(int historyId, int historyType, HttpMessage msg) {
Map<String, String> map = new HashMap<>();
map.put("id", String.valueOf(historyId));
map.put("type", String.valueOf(historyType));
map.put("timestamp", String.valueOf(msg.getTimeSentMillis()));
map.put("rtt", String.valueOf(msg.getTimeElapsedMillis()));
map.put("cookieParams", msg.getCookieParamsAsString());
map.put("note", msg.getNote());
map.put("requestHeader", msg.getRequestHeader().toString());
map.put("requestBody", msg.getRequestBody().toString());
map.put("responseHeader", msg.getResponseHeader().toString());
if (HttpHeader.GZIP.equals(msg.getResponseHeader().getHeader(HttpHeader.CONTENT_ENCODING))) {
// Uncompress gziped content
try (ByteArrayInputStream bais = new ByteArrayInputStream(msg.getResponseBody().getBytes());
GZIPInputStream gis = new GZIPInputStream(bais);
InputStreamReader isr = new InputStreamReader(gis);
BufferedReader br = new BufferedReader(isr);) {
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
}
map.put("responseBody", sb.toString());
} catch (IOException e) {
LOGGER.error("Unable to uncompress gzip content: " + e.getMessage(), e);
map.put("responseBody", msg.getResponseBody().toString());
}
} else {
map.put("responseBody", msg.getResponseBody().toString());
}
List<String> tags = Collections.emptyList();
try {
tags = HistoryReference.getTags(historyId);
} catch (DatabaseException e) {
LOGGER.warn("Failed to obtain the tags for message with ID " + historyId, e);
}
return new HttpMessageResponseSet(map, tags);
} | [
"public",
"static",
"ApiResponseSet",
"<",
"String",
">",
"httpMessageToSet",
"(",
"int",
"historyId",
",",
"int",
"historyType",
",",
"HttpMessage",
"msg",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"HashMap",
"<>",
"(",
")",
... | Converts the given HTTP message into an {@code ApiResponseSet}.
@param historyId the ID of the message
@param historyType the type of the message
@param msg the HTTP message to be converted
@return the {@code ApiResponseSet} with the ID, type and the HTTP message
@since 2.6.0 | [
"Converts",
"the",
"given",
"HTTP",
"message",
"into",
"an",
"{",
"@code",
"ApiResponseSet",
"}",
"."
] | train | https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/extension/api/ApiResponseConversionUtils.java#L81-L120 |
looly/hutool | hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java | SqlExecutor.executeBatch | public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
"""
批量执行非查询语句<br>
语句包括 插入、更新、删除<br>
此方法不会关闭Connection
@param conn 数据库连接对象
@param sql SQL
@param paramsBatch 批量的参数
@return 每个SQL执行影响的行数
@throws SQLException SQL执行异常
"""
return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
} | java | public static int[] executeBatch(Connection conn, String sql, Object[]... paramsBatch) throws SQLException {
return executeBatch(conn, sql, new ArrayIter<Object[]>(paramsBatch));
} | [
"public",
"static",
"int",
"[",
"]",
"executeBatch",
"(",
"Connection",
"conn",
",",
"String",
"sql",
",",
"Object",
"[",
"]",
"...",
"paramsBatch",
")",
"throws",
"SQLException",
"{",
"return",
"executeBatch",
"(",
"conn",
",",
"sql",
",",
"new",
"ArrayIt... | 批量执行非查询语句<br>
语句包括 插入、更新、删除<br>
此方法不会关闭Connection
@param conn 数据库连接对象
@param sql SQL
@param paramsBatch 批量的参数
@return 每个SQL执行影响的行数
@throws SQLException SQL执行异常 | [
"批量执行非查询语句<br",
">",
"语句包括",
"插入、更新、删除<br",
">",
"此方法不会关闭Connection"
] | train | https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-db/src/main/java/cn/hutool/db/sql/SqlExecutor.java#L164-L166 |
dkpro/dkpro-jwpl | de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/consumer/article/reader/WikipediaXMLReader.java | WikipediaXMLReader.readContributor | protected void readContributor(Revision rev, String str) throws IOException, ArticleReaderException {
"""
Parses the content within the contributor tags and adds the
parsed info to the provided revision object.
@param rev the revision object to store the parsed info in
@param str the contributor data to be parsed
@throws IOException
@throws ArticleReaderException
"""
char[] contrChars = str.toCharArray();
int size;
StringBuilder buffer = null;
this.keywords.reset();
for(char curChar:contrChars){
if (buffer != null) {
buffer.append(curChar);
}
if (this.keywords.check(curChar)) {
switch (this.keywords.getValue()) {
case KEY_START_ID:
case KEY_START_IP:
case KEY_START_USERNAME:
buffer = new StringBuilder();
break;
case KEY_END_IP:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_IP.getKeyword()
.length(), size);
// escape id string
rev.setContributorName(SQLEscape.escape(buffer.toString()));
rev.setContributorIsRegistered(false);
buffer = null;
break;
case KEY_END_USERNAME:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_USERNAME.getKeyword()
.length(), size);
// escape id string
rev.setContributorName(SQLEscape.escape(buffer.toString()));
rev.setContributorIsRegistered(true);
buffer = null;
break;
case KEY_END_ID:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_ID.getKeyword()
.length(), size);
String id = buffer.toString();
if(!id.isEmpty()){
rev.setContributorId(Integer.parseInt(buffer.toString()));
}
buffer = null;
break;
}
}
}
} | java | protected void readContributor(Revision rev, String str) throws IOException, ArticleReaderException
{
char[] contrChars = str.toCharArray();
int size;
StringBuilder buffer = null;
this.keywords.reset();
for(char curChar:contrChars){
if (buffer != null) {
buffer.append(curChar);
}
if (this.keywords.check(curChar)) {
switch (this.keywords.getValue()) {
case KEY_START_ID:
case KEY_START_IP:
case KEY_START_USERNAME:
buffer = new StringBuilder();
break;
case KEY_END_IP:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_IP.getKeyword()
.length(), size);
// escape id string
rev.setContributorName(SQLEscape.escape(buffer.toString()));
rev.setContributorIsRegistered(false);
buffer = null;
break;
case KEY_END_USERNAME:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_USERNAME.getKeyword()
.length(), size);
// escape id string
rev.setContributorName(SQLEscape.escape(buffer.toString()));
rev.setContributorIsRegistered(true);
buffer = null;
break;
case KEY_END_ID:
size = buffer.length();
buffer.delete(size
- WikipediaXMLKeys.KEY_END_ID.getKeyword()
.length(), size);
String id = buffer.toString();
if(!id.isEmpty()){
rev.setContributorId(Integer.parseInt(buffer.toString()));
}
buffer = null;
break;
}
}
}
} | [
"protected",
"void",
"readContributor",
"(",
"Revision",
"rev",
",",
"String",
"str",
")",
"throws",
"IOException",
",",
"ArticleReaderException",
"{",
"char",
"[",
"]",
"contrChars",
"=",
"str",
".",
"toCharArray",
"(",
")",
";",
"int",
"size",
";",
"String... | Parses the content within the contributor tags and adds the
parsed info to the provided revision object.
@param rev the revision object to store the parsed info in
@param str the contributor data to be parsed
@throws IOException
@throws ArticleReaderException | [
"Parses",
"the",
"content",
"within",
"the",
"contributor",
"tags",
"and",
"adds",
"the",
"parsed",
"info",
"to",
"the",
"provided",
"revision",
"object",
"."
] | train | https://github.com/dkpro/dkpro-jwpl/blob/0a0304b6a0aa13acc18838957994e06dd4613a58/de.tudarmstadt.ukp.wikipedia.revisionmachine/src/main/java/de/tudarmstadt/ukp/wikipedia/revisionmachine/difftool/consumer/article/reader/WikipediaXMLReader.java#L571-L631 |
Swagger2Markup/swagger2markup | src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java | PathOperationComponent.buildOperationTitle | private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
"""
Adds the operation title to the document. If the operation has a summary, the title is the summary.
Otherwise the title is the method of the operation and the URL of the operation.
@param operation the Swagger Operation
"""
buildOperationTitle(markupDocBuilder, operation.getTitle(), operation.getId());
if (operation.getTitle().equals(operation.getOperation().getSummary())) {
markupDocBuilder.block(operation.getMethod() + " " + operation.getPath(), MarkupBlockStyle.LITERAL);
}
} | java | private void buildOperationTitle(MarkupDocBuilder markupDocBuilder, PathOperation operation) {
buildOperationTitle(markupDocBuilder, operation.getTitle(), operation.getId());
if (operation.getTitle().equals(operation.getOperation().getSummary())) {
markupDocBuilder.block(operation.getMethod() + " " + operation.getPath(), MarkupBlockStyle.LITERAL);
}
} | [
"private",
"void",
"buildOperationTitle",
"(",
"MarkupDocBuilder",
"markupDocBuilder",
",",
"PathOperation",
"operation",
")",
"{",
"buildOperationTitle",
"(",
"markupDocBuilder",
",",
"operation",
".",
"getTitle",
"(",
")",
",",
"operation",
".",
"getId",
"(",
")",... | Adds the operation title to the document. If the operation has a summary, the title is the summary.
Otherwise the title is the method of the operation and the URL of the operation.
@param operation the Swagger Operation | [
"Adds",
"the",
"operation",
"title",
"to",
"the",
"document",
".",
"If",
"the",
"operation",
"has",
"a",
"summary",
"the",
"title",
"is",
"the",
"summary",
".",
"Otherwise",
"the",
"title",
"is",
"the",
"method",
"of",
"the",
"operation",
"and",
"the",
"... | train | https://github.com/Swagger2Markup/swagger2markup/blob/da83465f19a2f8a0f1fba873b5762bca8587896b/src/main/java/io/github/swagger2markup/internal/component/PathOperationComponent.java#L135-L140 |
hawkular/hawkular-apm | api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java | AbstractAnalyticsService.createRegex | protected static String createRegex(String endpoint, boolean meta) {
"""
This method derives the regular expression from the supplied
URI.
@param endpoint The endpoint
@param meta Whether this is a meta endpoint
@return The regular expression
"""
StringBuilder regex = new StringBuilder();
regex.append('^');
for (int i=0; i < endpoint.length(); i++) {
char ch=endpoint.charAt(i);
if ("*".indexOf(ch) != -1) {
regex.append('.');
} else if ("\\.^$|?+[]{}()".indexOf(ch) != -1) {
regex.append('\\');
}
regex.append(ch);
}
regex.append('$');
return regex.toString();
} | java | protected static String createRegex(String endpoint, boolean meta) {
StringBuilder regex = new StringBuilder();
regex.append('^');
for (int i=0; i < endpoint.length(); i++) {
char ch=endpoint.charAt(i);
if ("*".indexOf(ch) != -1) {
regex.append('.');
} else if ("\\.^$|?+[]{}()".indexOf(ch) != -1) {
regex.append('\\');
}
regex.append(ch);
}
regex.append('$');
return regex.toString();
} | [
"protected",
"static",
"String",
"createRegex",
"(",
"String",
"endpoint",
",",
"boolean",
"meta",
")",
"{",
"StringBuilder",
"regex",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"regex",
".",
"append",
"(",
"'",
"'",
")",
";",
"for",
"(",
"int",
"i",
... | This method derives the regular expression from the supplied
URI.
@param endpoint The endpoint
@param meta Whether this is a meta endpoint
@return The regular expression | [
"This",
"method",
"derives",
"the",
"regular",
"expression",
"from",
"the",
"supplied",
"URI",
"."
] | train | https://github.com/hawkular/hawkular-apm/blob/57a4df0611b359597626563ea5f9ac64d4bb2533/api/src/main/java/org/hawkular/apm/api/services/AbstractAnalyticsService.java#L506-L524 |
Whiley/WhileyCompiler | src/main/java/wyil/transform/VerificationConditionGenerator.java | VerificationConditionGenerator.translateContinue | private Context translateContinue(WyilFile.Stmt.Continue stmt, Context context) {
"""
Translate a continue statement. This takes the current context and pushes it
into the enclosing loop scope. It will then be extracted later and used.
@param stmt
@param wyalFile
"""
LoopScope enclosingLoop = context.getEnclosingLoopScope();
enclosingLoop.addContinueContext(context);
return null;
} | java | private Context translateContinue(WyilFile.Stmt.Continue stmt, Context context) {
LoopScope enclosingLoop = context.getEnclosingLoopScope();
enclosingLoop.addContinueContext(context);
return null;
} | [
"private",
"Context",
"translateContinue",
"(",
"WyilFile",
".",
"Stmt",
".",
"Continue",
"stmt",
",",
"Context",
"context",
")",
"{",
"LoopScope",
"enclosingLoop",
"=",
"context",
".",
"getEnclosingLoopScope",
"(",
")",
";",
"enclosingLoop",
".",
"addContinueCont... | Translate a continue statement. This takes the current context and pushes it
into the enclosing loop scope. It will then be extracted later and used.
@param stmt
@param wyalFile | [
"Translate",
"a",
"continue",
"statement",
".",
"This",
"takes",
"the",
"current",
"context",
"and",
"pushes",
"it",
"into",
"the",
"enclosing",
"loop",
"scope",
".",
"It",
"will",
"then",
"be",
"extracted",
"later",
"and",
"used",
"."
] | train | https://github.com/Whiley/WhileyCompiler/blob/680f8a657d3fc286f8cc422755988b6d74ab3f4c/src/main/java/wyil/transform/VerificationConditionGenerator.java#L757-L761 |
BorderTech/wcomponents | wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java | AbstractWComponent.switchFlag | private static int switchFlag(final int flags, final int mask, final boolean value) {
"""
A utility method to set or clear one or more bits in the given set of flags.
@param flags the current set of flags.
@param mask the bit mask for the flags to set/clear.
@param value true to set the flag(s), false to clear.
@return the new set of flags.
"""
int newFlags = value ? flags | mask : flags & ~mask;
return newFlags;
} | java | private static int switchFlag(final int flags, final int mask, final boolean value) {
int newFlags = value ? flags | mask : flags & ~mask;
return newFlags;
} | [
"private",
"static",
"int",
"switchFlag",
"(",
"final",
"int",
"flags",
",",
"final",
"int",
"mask",
",",
"final",
"boolean",
"value",
")",
"{",
"int",
"newFlags",
"=",
"value",
"?",
"flags",
"|",
"mask",
":",
"flags",
"&",
"~",
"mask",
";",
"return",
... | A utility method to set or clear one or more bits in the given set of flags.
@param flags the current set of flags.
@param mask the bit mask for the flags to set/clear.
@param value true to set the flag(s), false to clear.
@return the new set of flags. | [
"A",
"utility",
"method",
"to",
"set",
"or",
"clear",
"one",
"or",
"more",
"bits",
"in",
"the",
"given",
"set",
"of",
"flags",
"."
] | train | https://github.com/BorderTech/wcomponents/blob/d1a2b2243270067db030feb36ca74255aaa94436/wcomponents-core/src/main/java/com/github/bordertech/wcomponents/AbstractWComponent.java#L993-L996 |
jenkinsci/jenkins | core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java | AuthenticationProcessingFilter2.onUnsuccessfulAuthentication | @Override
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
"""
Leave the information about login failure.
<p>
Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere.
"""
super.onUnsuccessfulAuthentication(request, response, failed);
LOGGER.log(Level.FINE, "Login attempt failed", failed);
Authentication auth = failed.getAuthentication();
if (auth != null) {
SecurityListener.fireFailedToLogIn(auth.getName());
}
} | java | @Override
protected void onUnsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
super.onUnsuccessfulAuthentication(request, response, failed);
LOGGER.log(Level.FINE, "Login attempt failed", failed);
Authentication auth = failed.getAuthentication();
if (auth != null) {
SecurityListener.fireFailedToLogIn(auth.getName());
}
} | [
"@",
"Override",
"protected",
"void",
"onUnsuccessfulAuthentication",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
",",
"AuthenticationException",
"failed",
")",
"throws",
"IOException",
"{",
"super",
".",
"onUnsuccessfulAuthentication",
"("... | Leave the information about login failure.
<p>
Otherwise it seems like Acegi doesn't really leave the detail of the failure anywhere. | [
"Leave",
"the",
"information",
"about",
"login",
"failure",
"."
] | train | https://github.com/jenkinsci/jenkins/blob/44c4d3989232082c254d27ae360aa810669f44b7/core/src/main/java/hudson/security/AuthenticationProcessingFilter2.java#L115-L123 |
fullcontact/hadoop-sstable | sstable-core/src/main/java/com/fullcontact/cassandra/io/compress/CompressionMetadata.java | CompressionMetadata.readChunkOffsets | private Memory readChunkOffsets(DataInput input) {
"""
Read offsets of the individual chunks from the given input.
@param input Source of the data.
@return collection of the chunk offsets.
"""
try {
int chunkCount = input.readInt();
Memory offsets = Memory.allocate(chunkCount * 8);
for (int i = 0; i < chunkCount; i++) {
try {
offsets.setLong(i * 8, input.readLong());
} catch (EOFException e) {
String msg = String.format("Corrupted Index File %s: read %d but expected %d chunks.",
indexFilePath, i, chunkCount);
throw new CorruptSSTableException(new IOException(msg, e), indexFilePath);
}
}
return offsets;
} catch (IOException e) {
throw new FSReadError(e, indexFilePath);
}
} | java | private Memory readChunkOffsets(DataInput input) {
try {
int chunkCount = input.readInt();
Memory offsets = Memory.allocate(chunkCount * 8);
for (int i = 0; i < chunkCount; i++) {
try {
offsets.setLong(i * 8, input.readLong());
} catch (EOFException e) {
String msg = String.format("Corrupted Index File %s: read %d but expected %d chunks.",
indexFilePath, i, chunkCount);
throw new CorruptSSTableException(new IOException(msg, e), indexFilePath);
}
}
return offsets;
} catch (IOException e) {
throw new FSReadError(e, indexFilePath);
}
} | [
"private",
"Memory",
"readChunkOffsets",
"(",
"DataInput",
"input",
")",
"{",
"try",
"{",
"int",
"chunkCount",
"=",
"input",
".",
"readInt",
"(",
")",
";",
"Memory",
"offsets",
"=",
"Memory",
".",
"allocate",
"(",
"chunkCount",
"*",
"8",
")",
";",
"for",... | Read offsets of the individual chunks from the given input.
@param input Source of the data.
@return collection of the chunk offsets. | [
"Read",
"offsets",
"of",
"the",
"individual",
"chunks",
"from",
"the",
"given",
"input",
"."
] | train | https://github.com/fullcontact/hadoop-sstable/blob/1189c2cb3a2cbbe03b75fda1cf02698e6283dfb2/sstable-core/src/main/java/com/fullcontact/cassandra/io/compress/CompressionMetadata.java#L136-L155 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-chinese/src/main/java/org/ansj/library/DicLibrary.java | DicLibrary.insert | public static void insert(String key, String keyword, String nature, int freq) {
"""
关键词增加
@param keyword 所要增加的关键词
@param nature 关键词的词性
@param freq 关键词的词频
"""
Forest dic = get(key);
String[] paramers = new String[2];
paramers[0] = nature;
paramers[1] = String.valueOf(freq);
Value value = new Value(keyword, paramers);
Library.insertWord(dic, value);
} | java | public static void insert(String key, String keyword, String nature, int freq) {
Forest dic = get(key);
String[] paramers = new String[2];
paramers[0] = nature;
paramers[1] = String.valueOf(freq);
Value value = new Value(keyword, paramers);
Library.insertWord(dic, value);
} | [
"public",
"static",
"void",
"insert",
"(",
"String",
"key",
",",
"String",
"keyword",
",",
"String",
"nature",
",",
"int",
"freq",
")",
"{",
"Forest",
"dic",
"=",
"get",
"(",
"key",
")",
";",
"String",
"[",
"]",
"paramers",
"=",
"new",
"String",
"[",... | 关键词增加
@param keyword 所要增加的关键词
@param nature 关键词的词性
@param freq 关键词的词频 | [
"关键词增加"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nlp-parent/deeplearning4j-nlp-chinese/src/main/java/org/ansj/library/DicLibrary.java#L58-L65 |
RestComm/Restcomm-Connect | restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/filters/FileCacheServlet.java | FileCacheServlet.doHead | protected void doHead(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
"""
Process HEAD request. This returns the same headers as GET request, but
without content.
@see HttpServlet#doHead(HttpServletRequest, HttpServletResponse).
"""
// Process request without content.
processRequest(request, response, false);
} | java | protected void doHead(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Process request without content.
processRequest(request, response, false);
} | [
"protected",
"void",
"doHead",
"(",
"HttpServletRequest",
"request",
",",
"HttpServletResponse",
"response",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"// Process request without content.",
"processRequest",
"(",
"request",
",",
"response",
",",
"false",... | Process HEAD request. This returns the same headers as GET request, but
without content.
@see HttpServlet#doHead(HttpServletRequest, HttpServletResponse). | [
"Process",
"HEAD",
"request",
".",
"This",
"returns",
"the",
"same",
"headers",
"as",
"GET",
"request",
"but",
"without",
"content",
"."
] | train | https://github.com/RestComm/Restcomm-Connect/blob/2194dee4fc524cdfd0af77a218ba5f212f97f7c5/restcomm/restcomm.http/src/main/java/org/restcomm/connect/http/filters/FileCacheServlet.java#L62-L66 |
Azure/autorest-clientruntime-for-java | azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java | AzureAsyncOperation.fromResponse | static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {
"""
Creates AzureAsyncOperation from the given HTTP response.
@param serializerAdapter the adapter to use for deserialization
@param response the response
@return the async operation object
@throws CloudException if the deserialization fails or response contains invalid body
"""
AzureAsyncOperation asyncOperation = null;
String rawString = null;
if (response.body() != null) {
try {
rawString = response.body().string();
asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);
} catch (IOException exception) {
// Exception will be handled below
} finally {
response.body().close();
}
}
if (asyncOperation == null || asyncOperation.status() == null) {
throw new CloudException("polling response does not contain a valid body: " + rawString, response);
}
else {
asyncOperation.rawString = rawString;
}
return asyncOperation;
} | java | static AzureAsyncOperation fromResponse(SerializerAdapter<?> serializerAdapter, Response<ResponseBody> response) throws CloudException {
AzureAsyncOperation asyncOperation = null;
String rawString = null;
if (response.body() != null) {
try {
rawString = response.body().string();
asyncOperation = serializerAdapter.deserialize(rawString, AzureAsyncOperation.class);
} catch (IOException exception) {
// Exception will be handled below
} finally {
response.body().close();
}
}
if (asyncOperation == null || asyncOperation.status() == null) {
throw new CloudException("polling response does not contain a valid body: " + rawString, response);
}
else {
asyncOperation.rawString = rawString;
}
return asyncOperation;
} | [
"static",
"AzureAsyncOperation",
"fromResponse",
"(",
"SerializerAdapter",
"<",
"?",
">",
"serializerAdapter",
",",
"Response",
"<",
"ResponseBody",
">",
"response",
")",
"throws",
"CloudException",
"{",
"AzureAsyncOperation",
"asyncOperation",
"=",
"null",
";",
"Stri... | Creates AzureAsyncOperation from the given HTTP response.
@param serializerAdapter the adapter to use for deserialization
@param response the response
@return the async operation object
@throws CloudException if the deserialization fails or response contains invalid body | [
"Creates",
"AzureAsyncOperation",
"from",
"the",
"given",
"HTTP",
"response",
"."
] | train | https://github.com/Azure/autorest-clientruntime-for-java/blob/04621e07dbb0456dd5459dd641f06a9fd4f3abad/azure-client-runtime/src/main/java/com/microsoft/azure/AzureAsyncOperation.java#L134-L154 |
kuali/ojb-1.0.4 | src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java | SqlQueryStatement.appendColName | protected boolean appendColName(String attr, boolean useOuterJoins, UserAlias aUserAlias, StringBuffer buf) {
"""
Append the appropriate ColumnName to the buffer<br>
if a FIELDDESCRIPTOR is found for the Criteria the colName is taken from
there otherwise its taken from Criteria. <br>
field names in functions (ie: sum(name) ) are tried to resolve
ie: name from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br>
also resolve pathExpression adress.city or owner.konti.saldo
"""
AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses());
TableAlias tableAlias = attrInfo.tableAlias;
return appendColName(tableAlias, attrInfo.pathInfo, (tableAlias != null), buf);
} | java | protected boolean appendColName(String attr, boolean useOuterJoins, UserAlias aUserAlias, StringBuffer buf)
{
AttributeInfo attrInfo = getAttributeInfo(attr, useOuterJoins, aUserAlias, getQuery().getPathClasses());
TableAlias tableAlias = attrInfo.tableAlias;
return appendColName(tableAlias, attrInfo.pathInfo, (tableAlias != null), buf);
} | [
"protected",
"boolean",
"appendColName",
"(",
"String",
"attr",
",",
"boolean",
"useOuterJoins",
",",
"UserAlias",
"aUserAlias",
",",
"StringBuffer",
"buf",
")",
"{",
"AttributeInfo",
"attrInfo",
"=",
"getAttributeInfo",
"(",
"attr",
",",
"useOuterJoins",
",",
"aU... | Append the appropriate ColumnName to the buffer<br>
if a FIELDDESCRIPTOR is found for the Criteria the colName is taken from
there otherwise its taken from Criteria. <br>
field names in functions (ie: sum(name) ) are tried to resolve
ie: name from FIELDDESCRIPTOR , UPPER(name_test) from Criteria<br>
also resolve pathExpression adress.city or owner.konti.saldo | [
"Append",
"the",
"appropriate",
"ColumnName",
"to",
"the",
"buffer<br",
">",
"if",
"a",
"FIELDDESCRIPTOR",
"is",
"found",
"for",
"the",
"Criteria",
"the",
"colName",
"is",
"taken",
"from",
"there",
"otherwise",
"its",
"taken",
"from",
"Criteria",
".",
"<br",
... | train | https://github.com/kuali/ojb-1.0.4/blob/9a544372f67ce965f662cdc71609dd03683c8f04/src/java/org/apache/ojb/broker/accesslayer/sql/SqlQueryStatement.java#L440-L446 |
awslabs/jsii | packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java | JsiiEngine.registerObject | public void registerObject(final JsiiObjectRef objRef, final Object obj) {
"""
Registers an object into the object cache.
@param objRef The object reference.
@param obj The object to register.
"""
if (obj instanceof JsiiObject) {
((JsiiObject) obj).setObjRef(objRef);
}
this.objects.put(objRef.getObjId(), obj);
} | java | public void registerObject(final JsiiObjectRef objRef, final Object obj) {
if (obj instanceof JsiiObject) {
((JsiiObject) obj).setObjRef(objRef);
}
this.objects.put(objRef.getObjId(), obj);
} | [
"public",
"void",
"registerObject",
"(",
"final",
"JsiiObjectRef",
"objRef",
",",
"final",
"Object",
"obj",
")",
"{",
"if",
"(",
"obj",
"instanceof",
"JsiiObject",
")",
"{",
"(",
"(",
"JsiiObject",
")",
"obj",
")",
".",
"setObjRef",
"(",
"objRef",
")",
"... | Registers an object into the object cache.
@param objRef The object reference.
@param obj The object to register. | [
"Registers",
"an",
"object",
"into",
"the",
"object",
"cache",
"."
] | train | https://github.com/awslabs/jsii/blob/6bbf743f5f65e98e5199ad31c93961533ffc40e5/packages/jsii-java-runtime/project/src/main/java/software/amazon/jsii/JsiiEngine.java#L116-L121 |
gmessner/gitlab4j-api | src/main/java/org/gitlab4j/api/ProjectApi.java | ProjectApi.getRawSnippetContent | public String getRawSnippetContent(Object projectIdOrPath, Integer snippetId) throws GitLabApiException {
"""
Get the raw project snippet as plain text.
<pre><code>GET /projects/:id/snippets/:snippet_id/raw</code></pre>
@param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
@param snippetId the ID of the project's snippet
@return the raw project snippet plain text as an Optional instance
@throws GitLabApiException if any exception occurs
"""
Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "raw");
return (response.readEntity(String.class));
} | java | public String getRawSnippetContent(Object projectIdOrPath, Integer snippetId) throws GitLabApiException {
Response response = get(Response.Status.OK, null, "projects", getProjectIdOrPath(projectIdOrPath), "snippets", snippetId, "raw");
return (response.readEntity(String.class));
} | [
"public",
"String",
"getRawSnippetContent",
"(",
"Object",
"projectIdOrPath",
",",
"Integer",
"snippetId",
")",
"throws",
"GitLabApiException",
"{",
"Response",
"response",
"=",
"get",
"(",
"Response",
".",
"Status",
".",
"OK",
",",
"null",
",",
"\"projects\"",
... | Get the raw project snippet as plain text.
<pre><code>GET /projects/:id/snippets/:snippet_id/raw</code></pre>
@param projectIdOrPath projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance, required
@param snippetId the ID of the project's snippet
@return the raw project snippet plain text as an Optional instance
@throws GitLabApiException if any exception occurs | [
"Get",
"the",
"raw",
"project",
"snippet",
"as",
"plain",
"text",
"."
] | train | https://github.com/gmessner/gitlab4j-api/blob/ab045070abac0a8f4ccbf17b5ed9bfdef5723eed/src/main/java/org/gitlab4j/api/ProjectApi.java#L2049-L2052 |
op4j/op4j | src/main/java/org/op4j/Op.java | Op.onArrayFor | public static <T> Level0ArrayOperator<Double[],Double> onArrayFor(final Double... elements) {
"""
<p>
Creates an array with the specified elements and an <i>operation expression</i> on it.
</p>
@param elements the elements of the array being created
@return an operator, ready for chaining
"""
return onArrayOf(Types.DOUBLE, VarArgsUtil.asRequiredObjectArray(elements));
} | java | public static <T> Level0ArrayOperator<Double[],Double> onArrayFor(final Double... elements) {
return onArrayOf(Types.DOUBLE, VarArgsUtil.asRequiredObjectArray(elements));
} | [
"public",
"static",
"<",
"T",
">",
"Level0ArrayOperator",
"<",
"Double",
"[",
"]",
",",
"Double",
">",
"onArrayFor",
"(",
"final",
"Double",
"...",
"elements",
")",
"{",
"return",
"onArrayOf",
"(",
"Types",
".",
"DOUBLE",
",",
"VarArgsUtil",
".",
"asRequir... | <p>
Creates an array with the specified elements and an <i>operation expression</i> on it.
</p>
@param elements the elements of the array being created
@return an operator, ready for chaining | [
"<p",
">",
"Creates",
"an",
"array",
"with",
"the",
"specified",
"elements",
"and",
"an",
"<i",
">",
"operation",
"expression<",
"/",
"i",
">",
"on",
"it",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/op4j/op4j/blob/b577596dfe462089d3dd169666defc6de7ad289a/src/main/java/org/op4j/Op.java#L945-L947 |
alkacon/opencms-core | src/org/opencms/ade/configuration/CmsConfigurationReader.java | CmsConfigurationReader.parseProperty | public static CmsPropertyConfig parseProperty(CmsObject cms, I_CmsXmlContentLocation field) {
"""
Helper method to parse a property.<p>
@param cms the CMS context to use
@param field the location of the parent value
@return the parsed property configuration
"""
String name = getString(cms, field.getSubValue(N_PROPERTY_NAME));
String includeName = getString(cms, field.getSubValue(N_INCLUDE_NAME));
String widget = getString(cms, field.getSubValue(N_WIDGET));
String widgetConfig = getString(cms, field.getSubValue(N_WIDGET_CONFIG));
String ruleRegex = getString(cms, field.getSubValue(N_RULE_REGEX));
String ruleType = getString(cms, field.getSubValue(N_RULE_TYPE));
String default1 = getString(cms, field.getSubValue(N_DEFAULT));
String error = getString(cms, field.getSubValue(N_ERROR));
String niceName = getString(cms, field.getSubValue(N_DISPLAY_NAME));
String description = getString(cms, field.getSubValue(N_DESCRIPTION));
String preferFolder = getString(cms, field.getSubValue(N_PREFER_FOLDER));
String disabledStr = getString(cms, field.getSubValue(N_DISABLED));
boolean disabled = ((disabledStr != null) && Boolean.parseBoolean(disabledStr));
String orderStr = getString(cms, field.getSubValue(N_ORDER));
int order = I_CmsConfigurationObject.DEFAULT_ORDER;
try {
order = Integer.parseInt(orderStr);
} catch (NumberFormatException e) {
// noop
}
Visibility visibility;
String visibilityStr = getString(cms, field.getSubValue(N_VISIBILITY));
try {
// to stay compatible with former visibility option values
if ("both".equals(visibilityStr)) {
visibilityStr = Visibility.elementAndParentIndividual.name();
} else if ("parent".equals(visibilityStr)) {
visibilityStr = Visibility.parentShared.name();
}
visibility = Visibility.valueOf(visibilityStr);
} catch (Exception e) {
visibility = null;
}
CmsXmlContentProperty prop = new CmsXmlContentProperty(
name,
"string",
visibility,
widget,
widgetConfig,
ruleRegex,
ruleType,
default1,
niceName,
description,
error,
preferFolder).withIncludeName(includeName);
// since these are real properties, using type vfslist makes no sense, so we always use the "string" type
CmsPropertyConfig propConfig = new CmsPropertyConfig(prop, disabled, order);
return propConfig;
} | java | public static CmsPropertyConfig parseProperty(CmsObject cms, I_CmsXmlContentLocation field) {
String name = getString(cms, field.getSubValue(N_PROPERTY_NAME));
String includeName = getString(cms, field.getSubValue(N_INCLUDE_NAME));
String widget = getString(cms, field.getSubValue(N_WIDGET));
String widgetConfig = getString(cms, field.getSubValue(N_WIDGET_CONFIG));
String ruleRegex = getString(cms, field.getSubValue(N_RULE_REGEX));
String ruleType = getString(cms, field.getSubValue(N_RULE_TYPE));
String default1 = getString(cms, field.getSubValue(N_DEFAULT));
String error = getString(cms, field.getSubValue(N_ERROR));
String niceName = getString(cms, field.getSubValue(N_DISPLAY_NAME));
String description = getString(cms, field.getSubValue(N_DESCRIPTION));
String preferFolder = getString(cms, field.getSubValue(N_PREFER_FOLDER));
String disabledStr = getString(cms, field.getSubValue(N_DISABLED));
boolean disabled = ((disabledStr != null) && Boolean.parseBoolean(disabledStr));
String orderStr = getString(cms, field.getSubValue(N_ORDER));
int order = I_CmsConfigurationObject.DEFAULT_ORDER;
try {
order = Integer.parseInt(orderStr);
} catch (NumberFormatException e) {
// noop
}
Visibility visibility;
String visibilityStr = getString(cms, field.getSubValue(N_VISIBILITY));
try {
// to stay compatible with former visibility option values
if ("both".equals(visibilityStr)) {
visibilityStr = Visibility.elementAndParentIndividual.name();
} else if ("parent".equals(visibilityStr)) {
visibilityStr = Visibility.parentShared.name();
}
visibility = Visibility.valueOf(visibilityStr);
} catch (Exception e) {
visibility = null;
}
CmsXmlContentProperty prop = new CmsXmlContentProperty(
name,
"string",
visibility,
widget,
widgetConfig,
ruleRegex,
ruleType,
default1,
niceName,
description,
error,
preferFolder).withIncludeName(includeName);
// since these are real properties, using type vfslist makes no sense, so we always use the "string" type
CmsPropertyConfig propConfig = new CmsPropertyConfig(prop, disabled, order);
return propConfig;
} | [
"public",
"static",
"CmsPropertyConfig",
"parseProperty",
"(",
"CmsObject",
"cms",
",",
"I_CmsXmlContentLocation",
"field",
")",
"{",
"String",
"name",
"=",
"getString",
"(",
"cms",
",",
"field",
".",
"getSubValue",
"(",
"N_PROPERTY_NAME",
")",
")",
";",
"String... | Helper method to parse a property.<p>
@param cms the CMS context to use
@param field the location of the parent value
@return the parsed property configuration | [
"Helper",
"method",
"to",
"parse",
"a",
"property",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/ade/configuration/CmsConfigurationReader.java#L297-L353 |
paoding-code/paoding-rose | paoding-rose-jade/src/main/java/net/paoding/rose/jade/statement/cached/CachedStatement.java | CachedStatement.buildKey | private static String buildKey(String key, Map<String, Object> parameters) {
"""
查找模板 KEY 中所有的 :name, :name.property 参数替换成实际值。
@param key - 作为模板的 KEY
@param parameters - 传入的参数
@return 最终的缓存 KEY
@author 廖涵 in355hz@gmail.com
"""
// 匹配符合 :name 格式的参数
Matcher matcher = PATTERN.matcher(key);
if (matcher.find()) {
StringBuilder builder = new StringBuilder();
int index = 0;
do {
// 提取参数名称
final String name = matcher.group(1).trim();
Object value = null;
// 解析 a.b.c 类型的名称
int find = name.indexOf('.');
if (find >= 0) {
// 用 BeanWrapper 获取属性值
Object bean = parameters.get(name.substring(0, find));
if (bean != null) {
value = new BeanWrapperImpl(bean)
.getPropertyValue(name.substring(find + 1));
}
} else {
// 获取参数值
value = parameters.get(name);
}
// 拼装参数值
builder.append(key.substring(index, matcher.start()));
builder.append(value);
index = matcher.end();
} while (matcher.find());
// 拼装最后一段
builder.append(key.substring(index));
return builder.toString();
}
return key;
} | java | private static String buildKey(String key, Map<String, Object> parameters) {
// 匹配符合 :name 格式的参数
Matcher matcher = PATTERN.matcher(key);
if (matcher.find()) {
StringBuilder builder = new StringBuilder();
int index = 0;
do {
// 提取参数名称
final String name = matcher.group(1).trim();
Object value = null;
// 解析 a.b.c 类型的名称
int find = name.indexOf('.');
if (find >= 0) {
// 用 BeanWrapper 获取属性值
Object bean = parameters.get(name.substring(0, find));
if (bean != null) {
value = new BeanWrapperImpl(bean)
.getPropertyValue(name.substring(find + 1));
}
} else {
// 获取参数值
value = parameters.get(name);
}
// 拼装参数值
builder.append(key.substring(index, matcher.start()));
builder.append(value);
index = matcher.end();
} while (matcher.find());
// 拼装最后一段
builder.append(key.substring(index));
return builder.toString();
}
return key;
} | [
"private",
"static",
"String",
"buildKey",
"(",
"String",
"key",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
")",
"{",
"// 匹配符合 :name 格式的参数",
"Matcher",
"matcher",
"=",
"PATTERN",
".",
"matcher",
"(",
"key",
")",
";",
"if",
"(",
"matcher"... | 查找模板 KEY 中所有的 :name, :name.property 参数替换成实际值。
@param key - 作为模板的 KEY
@param parameters - 传入的参数
@return 最终的缓存 KEY
@author 廖涵 in355hz@gmail.com | [
"查找模板",
"KEY",
"中所有的",
":",
"name",
":",
"name",
".",
"property",
"参数替换成实际值。"
] | train | https://github.com/paoding-code/paoding-rose/blob/8b512704174dd6cba95e544c7d6ab66105cb8ec4/paoding-rose-jade/src/main/java/net/paoding/rose/jade/statement/cached/CachedStatement.java#L132-L179 |
f2prateek/ln | ln/src/main/java/com/f2prateek/ln/DebugLn.java | DebugLn.println | protected void println(int priority, String msg) {
"""
Print the message.
This method simply prints to {@link android.util.Log}. Override this to use the log level
feature and post to your endpoint.
@param priority The message priority to print.
@param msg The message to print.
"""
Log.println(priority, processTag(packageName), processMessage(msg));
} | java | protected void println(int priority, String msg) {
Log.println(priority, processTag(packageName), processMessage(msg));
} | [
"protected",
"void",
"println",
"(",
"int",
"priority",
",",
"String",
"msg",
")",
"{",
"Log",
".",
"println",
"(",
"priority",
",",
"processTag",
"(",
"packageName",
")",
",",
"processMessage",
"(",
"msg",
")",
")",
";",
"}"
] | Print the message.
This method simply prints to {@link android.util.Log}. Override this to use the log level
feature and post to your endpoint.
@param priority The message priority to print.
@param msg The message to print. | [
"Print",
"the",
"message",
"."
] | train | https://github.com/f2prateek/ln/blob/a84d1a7a4d8fc3c46f6917b0e19862282b878378/ln/src/main/java/com/f2prateek/ln/DebugLn.java#L220-L222 |
moparisthebest/beehive | beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ClientInitializer.java | ClientInitializer.enforceVersionRequired | protected static void enforceVersionRequired( ControlBean control, VersionRequired versionRequired ) {
"""
Enforces the VersionRequired annotation at runtime (called when an instance of a control is annotated
with VersionRequired). Throws a ControlException if enforcement fails.
@param versionRequired the value of the VersionRequired annotation on a control field
"""
Class controlIntf = ControlUtils.getMostDerivedInterface( control.getControlInterface() );
Version versionPresent = (Version) controlIntf.getAnnotation( Version.class );
if ( versionPresent != null )
{
ControlBean.enforceVersionRequired( controlIntf.getCanonicalName(), versionPresent, versionRequired );
}
} | java | protected static void enforceVersionRequired( ControlBean control, VersionRequired versionRequired )
{
Class controlIntf = ControlUtils.getMostDerivedInterface( control.getControlInterface() );
Version versionPresent = (Version) controlIntf.getAnnotation( Version.class );
if ( versionPresent != null )
{
ControlBean.enforceVersionRequired( controlIntf.getCanonicalName(), versionPresent, versionRequired );
}
} | [
"protected",
"static",
"void",
"enforceVersionRequired",
"(",
"ControlBean",
"control",
",",
"VersionRequired",
"versionRequired",
")",
"{",
"Class",
"controlIntf",
"=",
"ControlUtils",
".",
"getMostDerivedInterface",
"(",
"control",
".",
"getControlInterface",
"(",
")"... | Enforces the VersionRequired annotation at runtime (called when an instance of a control is annotated
with VersionRequired). Throws a ControlException if enforcement fails.
@param versionRequired the value of the VersionRequired annotation on a control field | [
"Enforces",
"the",
"VersionRequired",
"annotation",
"at",
"runtime",
"(",
"called",
"when",
"an",
"instance",
"of",
"a",
"control",
"is",
"annotated",
"with",
"VersionRequired",
")",
".",
"Throws",
"a",
"ControlException",
"if",
"enforcement",
"fails",
"."
] | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-controls/src/main/java/org/apache/beehive/controls/runtime/bean/ClientInitializer.java#L42-L51 |
apache/flink | flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/table/descriptors/Kafka.java | Kafka.startFromSpecificOffsets | public Kafka startFromSpecificOffsets(Map<Integer, Long> specificOffsets) {
"""
Configures to start reading partitions from specific offsets, set independently for each partition.
Resets previously set offsets.
@param specificOffsets the specified offsets for partitions
@see FlinkKafkaConsumerBase#setStartFromSpecificOffsets(Map)
"""
this.startupMode = StartupMode.SPECIFIC_OFFSETS;
this.specificOffsets = Preconditions.checkNotNull(specificOffsets);
return this;
} | java | public Kafka startFromSpecificOffsets(Map<Integer, Long> specificOffsets) {
this.startupMode = StartupMode.SPECIFIC_OFFSETS;
this.specificOffsets = Preconditions.checkNotNull(specificOffsets);
return this;
} | [
"public",
"Kafka",
"startFromSpecificOffsets",
"(",
"Map",
"<",
"Integer",
",",
"Long",
">",
"specificOffsets",
")",
"{",
"this",
".",
"startupMode",
"=",
"StartupMode",
".",
"SPECIFIC_OFFSETS",
";",
"this",
".",
"specificOffsets",
"=",
"Preconditions",
".",
"ch... | Configures to start reading partitions from specific offsets, set independently for each partition.
Resets previously set offsets.
@param specificOffsets the specified offsets for partitions
@see FlinkKafkaConsumerBase#setStartFromSpecificOffsets(Map) | [
"Configures",
"to",
"start",
"reading",
"partitions",
"from",
"specific",
"offsets",
"set",
"independently",
"for",
"each",
"partition",
".",
"Resets",
"previously",
"set",
"offsets",
"."
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-connectors/flink-connector-kafka-base/src/main/java/org/apache/flink/table/descriptors/Kafka.java#L163-L167 |
strator-dev/greenpepper | greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java | ConfluenceGreenPepper.saveExecutionResult | public void saveExecutionResult(Page page, String sut, XmlReport xmlReport) throws GreenPepperServerException {
"""
<p>saveExecutionResult.</p>
@param page a {@link com.atlassian.confluence.pages.Page} object.
@param sut a {@link java.lang.String} object.
@param xmlReport a {@link com.greenpepper.report.XmlReport} object.
@throws com.greenpepper.server.GreenPepperServerException if any.
"""
Specification specification = getSpecification(page);
List<SystemUnderTest> systemUnderTests = getSystemsUnderTests(page.getSpaceKey());
SystemUnderTest systemUnderTest = null;
for (SystemUnderTest s : systemUnderTests) {
if (s.getName().equals(sut)) {
systemUnderTest = s;
break;
}
}
if (systemUnderTest == null) {
throw new GreenPepperServerException(GreenPepperServerErrorKey.SUT_NOT_FOUND, sut);
}
getGPServerService().createExecution(systemUnderTest, specification, xmlReport);
} | java | public void saveExecutionResult(Page page, String sut, XmlReport xmlReport) throws GreenPepperServerException {
Specification specification = getSpecification(page);
List<SystemUnderTest> systemUnderTests = getSystemsUnderTests(page.getSpaceKey());
SystemUnderTest systemUnderTest = null;
for (SystemUnderTest s : systemUnderTests) {
if (s.getName().equals(sut)) {
systemUnderTest = s;
break;
}
}
if (systemUnderTest == null) {
throw new GreenPepperServerException(GreenPepperServerErrorKey.SUT_NOT_FOUND, sut);
}
getGPServerService().createExecution(systemUnderTest, specification, xmlReport);
} | [
"public",
"void",
"saveExecutionResult",
"(",
"Page",
"page",
",",
"String",
"sut",
",",
"XmlReport",
"xmlReport",
")",
"throws",
"GreenPepperServerException",
"{",
"Specification",
"specification",
"=",
"getSpecification",
"(",
"page",
")",
";",
"List",
"<",
"Sys... | <p>saveExecutionResult.</p>
@param page a {@link com.atlassian.confluence.pages.Page} object.
@param sut a {@link java.lang.String} object.
@param xmlReport a {@link com.greenpepper.report.XmlReport} object.
@throws com.greenpepper.server.GreenPepperServerException if any. | [
"<p",
">",
"saveExecutionResult",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/greenpepper-open/confluence/greenpepper-confluence-code/src/main/java/com/greenpepper/confluence/velocity/ConfluenceGreenPepper.java#L1231-L1250 |
alkacon/opencms-core | src/org/opencms/staticexport/CmsStaticExportManager.java | CmsStaticExportManager.addExportRule | public void addExportRule(String name, String description) {
"""
Adds a new export rule to the configuration.<p>
@param name the name of the rule
@param description the description for the rule
"""
m_exportRules.add(
new CmsStaticExportExportRule(
name,
description,
m_exportTmpRule.getModifiedResources(),
m_exportTmpRule.getExportResourcePatterns()));
m_exportTmpRule = new CmsStaticExportExportRule("", "");
} | java | public void addExportRule(String name, String description) {
m_exportRules.add(
new CmsStaticExportExportRule(
name,
description,
m_exportTmpRule.getModifiedResources(),
m_exportTmpRule.getExportResourcePatterns()));
m_exportTmpRule = new CmsStaticExportExportRule("", "");
} | [
"public",
"void",
"addExportRule",
"(",
"String",
"name",
",",
"String",
"description",
")",
"{",
"m_exportRules",
".",
"add",
"(",
"new",
"CmsStaticExportExportRule",
"(",
"name",
",",
"description",
",",
"m_exportTmpRule",
".",
"getModifiedResources",
"(",
")",
... | Adds a new export rule to the configuration.<p>
@param name the name of the rule
@param description the description for the rule | [
"Adds",
"a",
"new",
"export",
"rule",
"to",
"the",
"configuration",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/staticexport/CmsStaticExportManager.java#L362-L371 |
http-builder-ng/http-builder-ng | http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java | HttpBuilder.putAsync | public <T> CompletableFuture<T> putAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
"""
Executes an asynchronous PUT request on the configured URI (asynchronous alias to `put(Class,Consumer)`), with additional configuration provided
by the configuration function. The result will be cast to the specified `type`.
This method is generally used for Java-specific configuration.
[source,groovy]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
CompletableFuture<String> future = http.putAsync(String.class, config -> {
config.getRequest().getUri().setPath("/foo");
});
String result = future.get();
----
The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface.
@param type the type of the response content
@param configuration the additional configuration function (delegated to {@link HttpConfig})
@return the resulting content cast to the specified type, wrapped in a {@link CompletableFuture}
"""
return CompletableFuture.supplyAsync(() -> put(type, configuration), getExecutor());
} | java | public <T> CompletableFuture<T> putAsync(final Class<T> type, final Consumer<HttpConfig> configuration) {
return CompletableFuture.supplyAsync(() -> put(type, configuration), getExecutor());
} | [
"public",
"<",
"T",
">",
"CompletableFuture",
"<",
"T",
">",
"putAsync",
"(",
"final",
"Class",
"<",
"T",
">",
"type",
",",
"final",
"Consumer",
"<",
"HttpConfig",
">",
"configuration",
")",
"{",
"return",
"CompletableFuture",
".",
"supplyAsync",
"(",
"(",... | Executes an asynchronous PUT request on the configured URI (asynchronous alias to `put(Class,Consumer)`), with additional configuration provided
by the configuration function. The result will be cast to the specified `type`.
This method is generally used for Java-specific configuration.
[source,groovy]
----
HttpBuilder http = HttpBuilder.configure(config -> {
config.getRequest().setUri("http://localhost:10101");
});
CompletableFuture<String> future = http.putAsync(String.class, config -> {
config.getRequest().getUri().setPath("/foo");
});
String result = future.get();
----
The `configuration` {@link Consumer} allows additional configuration for this request based on the {@link HttpConfig} interface.
@param type the type of the response content
@param configuration the additional configuration function (delegated to {@link HttpConfig})
@return the resulting content cast to the specified type, wrapped in a {@link CompletableFuture} | [
"Executes",
"an",
"asynchronous",
"PUT",
"request",
"on",
"the",
"configured",
"URI",
"(",
"asynchronous",
"alias",
"to",
"put",
"(",
"Class",
"Consumer",
")",
")",
"with",
"additional",
"configuration",
"provided",
"by",
"the",
"configuration",
"function",
".",... | train | https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L1081-L1083 |
cloudant/sync-android | cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/query/callables/CreateIndexCallable.java | CreateIndexCallable.createVirtualTableStatementForIndex | private String createVirtualTableStatementForIndex(String indexName,
List<String> columns,
List<String> indexSettings) {
"""
This method generates the virtual table create SQL for the specified index.
Note: Any column that contains an '=' will cause the statement to fail
because it triggers SQLite to expect that a parameter/value is being passed in.
@param indexName the index name to be used when creating the SQLite virtual table
@param columns the columns in the table
@param indexSettings the special settings to apply to the virtual table -
(only 'tokenize' is current supported)
@return the SQL to create the SQLite virtual table
"""
String tableName = String.format(Locale.ENGLISH, "\"%s\"", QueryImpl
.tableNameForIndex(indexName));
String cols = Misc.join(",", columns);
String settings = Misc.join(",", indexSettings);
return String.format("CREATE VIRTUAL TABLE %s USING FTS4 ( %s, %s )", tableName,
cols,
settings);
} | java | private String createVirtualTableStatementForIndex(String indexName,
List<String> columns,
List<String> indexSettings) {
String tableName = String.format(Locale.ENGLISH, "\"%s\"", QueryImpl
.tableNameForIndex(indexName));
String cols = Misc.join(",", columns);
String settings = Misc.join(",", indexSettings);
return String.format("CREATE VIRTUAL TABLE %s USING FTS4 ( %s, %s )", tableName,
cols,
settings);
} | [
"private",
"String",
"createVirtualTableStatementForIndex",
"(",
"String",
"indexName",
",",
"List",
"<",
"String",
">",
"columns",
",",
"List",
"<",
"String",
">",
"indexSettings",
")",
"{",
"String",
"tableName",
"=",
"String",
".",
"format",
"(",
"Locale",
... | This method generates the virtual table create SQL for the specified index.
Note: Any column that contains an '=' will cause the statement to fail
because it triggers SQLite to expect that a parameter/value is being passed in.
@param indexName the index name to be used when creating the SQLite virtual table
@param columns the columns in the table
@param indexSettings the special settings to apply to the virtual table -
(only 'tokenize' is current supported)
@return the SQL to create the SQLite virtual table | [
"This",
"method",
"generates",
"the",
"virtual",
"table",
"create",
"SQL",
"for",
"the",
"specified",
"index",
".",
"Note",
":",
"Any",
"column",
"that",
"contains",
"an",
"=",
"will",
"cause",
"the",
"statement",
"to",
"fail",
"because",
"it",
"triggers",
... | train | https://github.com/cloudant/sync-android/blob/5f1416ed1bd9ab05d7a4b8736480c8ae68bd7383/cloudant-sync-datastore-core/src/main/java/com/cloudant/sync/internal/query/callables/CreateIndexCallable.java#L113-L124 |
ontop/ontop | client/protege/src/main/java/it/unibz/inf/ontop/protege/gui/treemodels/ResultSetTableModel.java | ResultSetTableModel.getValueAt | @Override
public Object getValueAt(int row, int column) {
"""
This is the key method of TableModel: it returns the value at each cell
of the table. We use strings in this case. If anything goes wrong, we
return the exception as a string, so it will be displayed in the table.
Note that SQL row and column numbers start at 1, but TableModel column
numbers start at 0.
"""
Vector<String> aux = results.get(row);
return aux.get(column);
} | java | @Override
public Object getValueAt(int row, int column) {
Vector<String> aux = results.get(row);
return aux.get(column);
} | [
"@",
"Override",
"public",
"Object",
"getValueAt",
"(",
"int",
"row",
",",
"int",
"column",
")",
"{",
"Vector",
"<",
"String",
">",
"aux",
"=",
"results",
".",
"get",
"(",
"row",
")",
";",
"return",
"aux",
".",
"get",
"(",
"column",
")",
";",
"}"
] | This is the key method of TableModel: it returns the value at each cell
of the table. We use strings in this case. If anything goes wrong, we
return the exception as a string, so it will be displayed in the table.
Note that SQL row and column numbers start at 1, but TableModel column
numbers start at 0. | [
"This",
"is",
"the",
"key",
"method",
"of",
"TableModel",
":",
"it",
"returns",
"the",
"value",
"at",
"each",
"cell",
"of",
"the",
"table",
".",
"We",
"use",
"strings",
"in",
"this",
"case",
".",
"If",
"anything",
"goes",
"wrong",
"we",
"return",
"the"... | train | https://github.com/ontop/ontop/blob/ddf78b26981b6129ee9a1a59310016830f5352e4/client/protege/src/main/java/it/unibz/inf/ontop/protege/gui/treemodels/ResultSetTableModel.java#L138-L142 |
truward/metrics4j | metrics4j-json-log/src/main/java/com/truward/metrics/json/internal/appender/RollingJacksonMapAppender.java | RollingJacksonMapAppender.rollLog | private void rollLog() {
"""
Writes older log into the file and updates current output stream
"""
final File file = currentFile;
if (file == null) {
throw new IllegalStateException("currentFile is null"); // shouldn't happen
}
final OutputStream stream = currentStream;
if (stream == null) {
throw new IllegalStateException("currentStream is null"); // shouldn't happen
}
// reset class members
this.currentFile = null;
this.currentStream = null;
// compress file, if needed
if (compressor == null) {
return; // compression is not needed
}
// start new compression thread
final Thread compressingThread = new Thread(new Runnable() {
@Override
public void run() {
log.trace("Closing output stream of target file={}", file);
// close old stream
try {
stream.close();
} catch (IOException e) {
log.error("Unable to properly close output stream", e);
}
// compress file contents
compressFileContents(compressor, file);
// mark current thread as null
currentCompressingThread = null;
}
});
compressingThread.run();
currentCompressingThread = compressingThread;
} | java | private void rollLog() {
final File file = currentFile;
if (file == null) {
throw new IllegalStateException("currentFile is null"); // shouldn't happen
}
final OutputStream stream = currentStream;
if (stream == null) {
throw new IllegalStateException("currentStream is null"); // shouldn't happen
}
// reset class members
this.currentFile = null;
this.currentStream = null;
// compress file, if needed
if (compressor == null) {
return; // compression is not needed
}
// start new compression thread
final Thread compressingThread = new Thread(new Runnable() {
@Override
public void run() {
log.trace("Closing output stream of target file={}", file);
// close old stream
try {
stream.close();
} catch (IOException e) {
log.error("Unable to properly close output stream", e);
}
// compress file contents
compressFileContents(compressor, file);
// mark current thread as null
currentCompressingThread = null;
}
});
compressingThread.run();
currentCompressingThread = compressingThread;
} | [
"private",
"void",
"rollLog",
"(",
")",
"{",
"final",
"File",
"file",
"=",
"currentFile",
";",
"if",
"(",
"file",
"==",
"null",
")",
"{",
"throw",
"new",
"IllegalStateException",
"(",
"\"currentFile is null\"",
")",
";",
"// shouldn't happen",
"}",
"final",
... | Writes older log into the file and updates current output stream | [
"Writes",
"older",
"log",
"into",
"the",
"file",
"and",
"updates",
"current",
"output",
"stream"
] | train | https://github.com/truward/metrics4j/blob/6e81c00ce24e008c029cce875d44f667e2bc978c/metrics4j-json-log/src/main/java/com/truward/metrics/json/internal/appender/RollingJacksonMapAppender.java#L142-L184 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/FrameOutputWriter.java | FrameOutputWriter.generateFrameFile | protected void generateFrameFile() throws DocFileIOException {
"""
Generate the constants in the "index.html" file. Print the frame details
as well as warning if browser is not supporting the Html frames.
@throws DocFileIOException if there is a problem generating the frame file
"""
Content frame = getFrameDetails();
HtmlTree body = new HtmlTree(HtmlTag.BODY);
body.addAttr(HtmlAttr.ONLOAD, "loadFrames()");
String topFilePath = configuration.topFile.getPath();
String javaScriptRefresh = "\nif (targetPage == \"\" || targetPage == \"undefined\")\n" +
" window.location.replace('" + topFilePath + "');\n";
RawHtml scriptContent = new RawHtml(javaScriptRefresh.replace("\n", DocletConstants.NL));
HtmlTree scriptTree = HtmlTree.SCRIPT();
scriptTree.addContent(scriptContent);
body.addContent(scriptTree);
Content noScript = HtmlTree.NOSCRIPT(contents.noScriptMessage);
body.addContent(noScript);
if (configuration.allowTag(HtmlTag.MAIN)) {
HtmlTree main = HtmlTree.MAIN(frame);
body.addContent(main);
} else {
body.addContent(frame);
}
if (configuration.windowtitle.length() > 0) {
printFramesDocument(configuration.windowtitle, configuration,
body);
} else {
printFramesDocument(configuration.getText("doclet.Generated_Docs_Untitled"),
configuration, body);
}
} | java | protected void generateFrameFile() throws DocFileIOException {
Content frame = getFrameDetails();
HtmlTree body = new HtmlTree(HtmlTag.BODY);
body.addAttr(HtmlAttr.ONLOAD, "loadFrames()");
String topFilePath = configuration.topFile.getPath();
String javaScriptRefresh = "\nif (targetPage == \"\" || targetPage == \"undefined\")\n" +
" window.location.replace('" + topFilePath + "');\n";
RawHtml scriptContent = new RawHtml(javaScriptRefresh.replace("\n", DocletConstants.NL));
HtmlTree scriptTree = HtmlTree.SCRIPT();
scriptTree.addContent(scriptContent);
body.addContent(scriptTree);
Content noScript = HtmlTree.NOSCRIPT(contents.noScriptMessage);
body.addContent(noScript);
if (configuration.allowTag(HtmlTag.MAIN)) {
HtmlTree main = HtmlTree.MAIN(frame);
body.addContent(main);
} else {
body.addContent(frame);
}
if (configuration.windowtitle.length() > 0) {
printFramesDocument(configuration.windowtitle, configuration,
body);
} else {
printFramesDocument(configuration.getText("doclet.Generated_Docs_Untitled"),
configuration, body);
}
} | [
"protected",
"void",
"generateFrameFile",
"(",
")",
"throws",
"DocFileIOException",
"{",
"Content",
"frame",
"=",
"getFrameDetails",
"(",
")",
";",
"HtmlTree",
"body",
"=",
"new",
"HtmlTree",
"(",
"HtmlTag",
".",
"BODY",
")",
";",
"body",
".",
"addAttr",
"("... | Generate the constants in the "index.html" file. Print the frame details
as well as warning if browser is not supporting the Html frames.
@throws DocFileIOException if there is a problem generating the frame file | [
"Generate",
"the",
"constants",
"in",
"the",
"index",
".",
"html",
"file",
".",
"Print",
"the",
"frame",
"details",
"as",
"well",
"as",
"warning",
"if",
"browser",
"is",
"not",
"supporting",
"the",
"Html",
"frames",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/FrameOutputWriter.java#L93-L119 |
NoraUi/NoraUi | src/main/java/com/github/noraui/application/steps/FileSteps.java | FileSteps.waitDownloadFile | @Conditioned
@Lorsque("Je patiente que le fichier nommé '(.*)' soit téléchargé avec un timeout de '(.*)' secondes[\\.|\\?]")
@Then("I wait file named '(.*)' to be downloaded with timeout of '(.*)' seconds[\\.|\\?]")
public void waitDownloadFile(String file, int timeout, List<GherkinStepCondition> conditions) throws InterruptedException, FailureException, TechnicalException {
"""
Waits the full download of a file with a maximum timeout in seconds.
@param file
The name of the file to download
@param timeout
The maximum timeout
@param conditions
List of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws InterruptedException
Exception for the sleep
@throws TechnicalException
@throws FailureException
"""
File f;
int nbTry = 0;
do {
if (nbTry >= timeout) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_DOWNLOADED_FILE_NOT_FOUND), file), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
Thread.sleep(1000);
f = new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + file);
nbTry++;
} while (!(f.exists() && !f.isDirectory()));
logger.debug("File downloaded in {} seconds.", nbTry);
} | java | @Conditioned
@Lorsque("Je patiente que le fichier nommé '(.*)' soit téléchargé avec un timeout de '(.*)' secondes[\\.|\\?]")
@Then("I wait file named '(.*)' to be downloaded with timeout of '(.*)' seconds[\\.|\\?]")
public void waitDownloadFile(String file, int timeout, List<GherkinStepCondition> conditions) throws InterruptedException, FailureException, TechnicalException {
File f;
int nbTry = 0;
do {
if (nbTry >= timeout) {
new Result.Failure<>(file, Messages.format(Messages.getMessage(Messages.FAIL_MESSAGE_DOWNLOADED_FILE_NOT_FOUND), file), false, Context.getCallBack(Callbacks.RESTART_WEB_DRIVER));
}
Thread.sleep(1000);
f = new File(System.getProperty(USER_DIR) + File.separator + DOWNLOADED_FILES_FOLDER + File.separator + file);
nbTry++;
} while (!(f.exists() && !f.isDirectory()));
logger.debug("File downloaded in {} seconds.", nbTry);
} | [
"@",
"Conditioned",
"@",
"Lorsque",
"(",
"\"Je patiente que le fichier nommé '(.*)' soit téléchargé avec un timeout de '(.*)' secondes[\\\\.|\\\\?]\")",
"",
"@",
"Then",
"(",
"\"I wait file named '(.*)' to be downloaded with timeout of '(.*)' seconds[\\\\.|\\\\?]\"",
")",
"public",
"void",... | Waits the full download of a file with a maximum timeout in seconds.
@param file
The name of the file to download
@param timeout
The maximum timeout
@param conditions
List of 'expected' values condition and 'actual' values ({@link com.github.noraui.gherkin.GherkinStepCondition}).
@throws InterruptedException
Exception for the sleep
@throws TechnicalException
@throws FailureException | [
"Waits",
"the",
"full",
"download",
"of",
"a",
"file",
"with",
"a",
"maximum",
"timeout",
"in",
"seconds",
"."
] | train | https://github.com/NoraUi/NoraUi/blob/5f491a3339c7d3c20d7207760bdaf2acdb8f260c/src/main/java/com/github/noraui/application/steps/FileSteps.java#L124-L139 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/transform/TransformersLogger.java | TransformersLogger.logAttributeWarning | public void logAttributeWarning(PathAddress address, String attribute) {
"""
Log a warning for the resource at the provided address and a single attribute. The detail message is a default
'Attributes are not understood in the target model version and this resource will need to be ignored on the target host.'
@param address where warning occurred
@param attribute attribute we are warning about
"""
logAttributeWarning(address, null, null, attribute);
} | java | public void logAttributeWarning(PathAddress address, String attribute) {
logAttributeWarning(address, null, null, attribute);
} | [
"public",
"void",
"logAttributeWarning",
"(",
"PathAddress",
"address",
",",
"String",
"attribute",
")",
"{",
"logAttributeWarning",
"(",
"address",
",",
"null",
",",
"null",
",",
"attribute",
")",
";",
"}"
] | Log a warning for the resource at the provided address and a single attribute. The detail message is a default
'Attributes are not understood in the target model version and this resource will need to be ignored on the target host.'
@param address where warning occurred
@param attribute attribute we are warning about | [
"Log",
"a",
"warning",
"for",
"the",
"resource",
"at",
"the",
"provided",
"address",
"and",
"a",
"single",
"attribute",
".",
"The",
"detail",
"message",
"is",
"a",
"default",
"Attributes",
"are",
"not",
"understood",
"in",
"the",
"target",
"model",
"version"... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/transform/TransformersLogger.java#L98-L100 |
ops4j/org.ops4j.pax.exam2 | core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/PaxExamRuntime.java | PaxExamRuntime.waitForStop | private static void waitForStop(TestContainer testContainer, int localPort) {
"""
Opens a server socket listening for text commands on the given port.
Each command is terminated by a newline. The server expects a "stop" command
followed by a "quit" command.
@param testContainer
@param localPort
"""
try {
ServerSocket serverSocket = new ServerSocket(localPort);
Socket socket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(writer, true);
boolean running = true;
while (running) {
String command = reader.readLine();
LOG.debug("command = {}", command);
if (command.equals("stop")) {
testContainer.stop();
pw.println("stopped");
writer.flush();
LOG.info("test container stopped");
}
else if (command.equals("quit")) {
LOG.debug("quitting PaxExamRuntime");
pw.close();
socket.close();
serverSocket.close();
running = false;
}
}
}
catch (IOException exc) {
LOG.debug("socket error", exc);
}
} | java | private static void waitForStop(TestContainer testContainer, int localPort) {
try {
ServerSocket serverSocket = new ServerSocket(localPort);
Socket socket = serverSocket.accept();
InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(isr);
OutputStream os = socket.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(writer, true);
boolean running = true;
while (running) {
String command = reader.readLine();
LOG.debug("command = {}", command);
if (command.equals("stop")) {
testContainer.stop();
pw.println("stopped");
writer.flush();
LOG.info("test container stopped");
}
else if (command.equals("quit")) {
LOG.debug("quitting PaxExamRuntime");
pw.close();
socket.close();
serverSocket.close();
running = false;
}
}
}
catch (IOException exc) {
LOG.debug("socket error", exc);
}
} | [
"private",
"static",
"void",
"waitForStop",
"(",
"TestContainer",
"testContainer",
",",
"int",
"localPort",
")",
"{",
"try",
"{",
"ServerSocket",
"serverSocket",
"=",
"new",
"ServerSocket",
"(",
"localPort",
")",
";",
"Socket",
"socket",
"=",
"serverSocket",
"."... | Opens a server socket listening for text commands on the given port.
Each command is terminated by a newline. The server expects a "stop" command
followed by a "quit" command.
@param testContainer
@param localPort | [
"Opens",
"a",
"server",
"socket",
"listening",
"for",
"text",
"commands",
"on",
"the",
"given",
"port",
".",
"Each",
"command",
"is",
"terminated",
"by",
"a",
"newline",
".",
"The",
"server",
"expects",
"a",
"stop",
"command",
"followed",
"by",
"a",
"quit"... | train | https://github.com/ops4j/org.ops4j.pax.exam2/blob/7f83796cbbb857123d8fc7fe817a7637218d5d77/core/pax-exam-spi/src/main/java/org/ops4j/pax/exam/spi/PaxExamRuntime.java#L124-L156 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/DbEntityManager.java | DbEntityManager.isOptimisticLockingException | private boolean isOptimisticLockingException(DbOperation failedOperation, Throwable cause) {
"""
Checks if the reason for a persistence exception was the foreign-key referencing of a (currently)
non-existing entity. This might happen with concurrent transactions, leading to an
OptimisticLockingException.
@param failedOperation
@return
"""
boolean isConstraintViolation = ExceptionUtil.checkForeignKeyConstraintViolation(cause);
boolean isVariableIntegrityViolation = ExceptionUtil.checkVariableIntegrityViolation(cause);
if (isVariableIntegrityViolation) {
return true;
} else if (
isConstraintViolation
&& failedOperation instanceof DbEntityOperation
&& ((DbEntityOperation) failedOperation).getEntity() instanceof HasDbReferences
&& (failedOperation.getOperationType().equals(DbOperationType.INSERT)
|| failedOperation.getOperationType().equals(DbOperationType.UPDATE))
) {
DbEntity entity = ((DbEntityOperation) failedOperation).getEntity();
for (Map.Entry<String, Class> reference : ((HasDbReferences)entity).getReferencedEntitiesIdAndClass().entrySet()) {
DbEntity referencedEntity = this.persistenceSession.selectById(reference.getValue(), reference.getKey());
if (referencedEntity == null) {
return true;
}
}
}
return false;
} | java | private boolean isOptimisticLockingException(DbOperation failedOperation, Throwable cause) {
boolean isConstraintViolation = ExceptionUtil.checkForeignKeyConstraintViolation(cause);
boolean isVariableIntegrityViolation = ExceptionUtil.checkVariableIntegrityViolation(cause);
if (isVariableIntegrityViolation) {
return true;
} else if (
isConstraintViolation
&& failedOperation instanceof DbEntityOperation
&& ((DbEntityOperation) failedOperation).getEntity() instanceof HasDbReferences
&& (failedOperation.getOperationType().equals(DbOperationType.INSERT)
|| failedOperation.getOperationType().equals(DbOperationType.UPDATE))
) {
DbEntity entity = ((DbEntityOperation) failedOperation).getEntity();
for (Map.Entry<String, Class> reference : ((HasDbReferences)entity).getReferencedEntitiesIdAndClass().entrySet()) {
DbEntity referencedEntity = this.persistenceSession.selectById(reference.getValue(), reference.getKey());
if (referencedEntity == null) {
return true;
}
}
}
return false;
} | [
"private",
"boolean",
"isOptimisticLockingException",
"(",
"DbOperation",
"failedOperation",
",",
"Throwable",
"cause",
")",
"{",
"boolean",
"isConstraintViolation",
"=",
"ExceptionUtil",
".",
"checkForeignKeyConstraintViolation",
"(",
"cause",
")",
";",
"boolean",
"isVar... | Checks if the reason for a persistence exception was the foreign-key referencing of a (currently)
non-existing entity. This might happen with concurrent transactions, leading to an
OptimisticLockingException.
@param failedOperation
@return | [
"Checks",
"if",
"the",
"reason",
"for",
"a",
"persistence",
"exception",
"was",
"the",
"foreign",
"-",
"key",
"referencing",
"of",
"a",
"(",
"currently",
")",
"non",
"-",
"existing",
"entity",
".",
"This",
"might",
"happen",
"with",
"concurrent",
"transactio... | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/db/entitymanager/DbEntityManager.java#L405-L432 |
js-lib-com/commons | src/main/java/js/converter/ConverterRegistry.java | ConverterRegistry.registerConverterInstance | private void registerConverterInstance(Class<?> valueType, Converter converter) {
"""
Utility method to bind converter instance to concrete value type.
@param valueType concrete value type,
@param converter converter instance able to handle value type.
"""
if(converters.put(valueType, converter) == null) {
log.debug("Register converter |%s| for value type |%s|.", converter.getClass(), valueType);
}
else {
log.warn("Override converter |%s| for value type |%s|.", converter.getClass(), valueType);
}
} | java | private void registerConverterInstance(Class<?> valueType, Converter converter)
{
if(converters.put(valueType, converter) == null) {
log.debug("Register converter |%s| for value type |%s|.", converter.getClass(), valueType);
}
else {
log.warn("Override converter |%s| for value type |%s|.", converter.getClass(), valueType);
}
} | [
"private",
"void",
"registerConverterInstance",
"(",
"Class",
"<",
"?",
">",
"valueType",
",",
"Converter",
"converter",
")",
"{",
"if",
"(",
"converters",
".",
"put",
"(",
"valueType",
",",
"converter",
")",
"==",
"null",
")",
"{",
"log",
".",
"debug",
... | Utility method to bind converter instance to concrete value type.
@param valueType concrete value type,
@param converter converter instance able to handle value type. | [
"Utility",
"method",
"to",
"bind",
"converter",
"instance",
"to",
"concrete",
"value",
"type",
"."
] | train | https://github.com/js-lib-com/commons/blob/f8c64482142b163487745da74feb106f0765c16b/src/main/java/js/converter/ConverterRegistry.java#L382-L390 |
alipay/sofa-rpc | core/api/src/main/java/com/alipay/sofa/rpc/filter/FilterInvoker.java | FilterInvoker.getStringMethodParam | protected String getStringMethodParam(String methodName, String paramKey, String defaultValue) {
"""
取得方法的特殊参数配置
@param methodName 方法名
@param paramKey 参数关键字
@param defaultValue 默认值
@return 都找不到为null string method param
"""
if (CommonUtils.isEmpty(configContext)) {
return defaultValue;
}
String o = (String) configContext.get(buildMethodKey(methodName, paramKey));
if (o == null) {
o = (String) configContext.get(paramKey);
return o == null ? defaultValue : o;
} else {
return o;
}
} | java | protected String getStringMethodParam(String methodName, String paramKey, String defaultValue) {
if (CommonUtils.isEmpty(configContext)) {
return defaultValue;
}
String o = (String) configContext.get(buildMethodKey(methodName, paramKey));
if (o == null) {
o = (String) configContext.get(paramKey);
return o == null ? defaultValue : o;
} else {
return o;
}
} | [
"protected",
"String",
"getStringMethodParam",
"(",
"String",
"methodName",
",",
"String",
"paramKey",
",",
"String",
"defaultValue",
")",
"{",
"if",
"(",
"CommonUtils",
".",
"isEmpty",
"(",
"configContext",
")",
")",
"{",
"return",
"defaultValue",
";",
"}",
"... | 取得方法的特殊参数配置
@param methodName 方法名
@param paramKey 参数关键字
@param defaultValue 默认值
@return 都找不到为null string method param | [
"取得方法的特殊参数配置"
] | train | https://github.com/alipay/sofa-rpc/blob/a31406410291e56696185a29c3ba4bd1f54488fd/core/api/src/main/java/com/alipay/sofa/rpc/filter/FilterInvoker.java#L161-L172 |
jcuda/jcusolver | JCusolverJava/src/main/java/jcuda/jcusolver/JCusolverSp.java | JCusolverSp.cusolverSpXcsrsymrcmHost | public static int cusolverSpXcsrsymrcmHost(
cusolverSpHandle handle,
int n,
int nnzA,
cusparseMatDescr descrA,
Pointer csrRowPtrA,
Pointer csrColIndA,
Pointer p) {
"""
<pre>
--------- CPU symrcm
Symmetric reverse Cuthill McKee permutation
</pre>
"""
return checkResult(cusolverSpXcsrsymrcmHostNative(handle, n, nnzA, descrA, csrRowPtrA, csrColIndA, p));
} | java | public static int cusolverSpXcsrsymrcmHost(
cusolverSpHandle handle,
int n,
int nnzA,
cusparseMatDescr descrA,
Pointer csrRowPtrA,
Pointer csrColIndA,
Pointer p)
{
return checkResult(cusolverSpXcsrsymrcmHostNative(handle, n, nnzA, descrA, csrRowPtrA, csrColIndA, p));
} | [
"public",
"static",
"int",
"cusolverSpXcsrsymrcmHost",
"(",
"cusolverSpHandle",
"handle",
",",
"int",
"n",
",",
"int",
"nnzA",
",",
"cusparseMatDescr",
"descrA",
",",
"Pointer",
"csrRowPtrA",
",",
"Pointer",
"csrColIndA",
",",
"Pointer",
"p",
")",
"{",
"return",... | <pre>
--------- CPU symrcm
Symmetric reverse Cuthill McKee permutation
</pre> | [
"<pre",
">",
"---------",
"CPU",
"symrcm",
"Symmetric",
"reverse",
"Cuthill",
"McKee",
"permutation"
] | train | https://github.com/jcuda/jcusolver/blob/2600c7eca36a92a60ebcc78cae6e028e0c1d00b9/JCusolverJava/src/main/java/jcuda/jcusolver/JCusolverSp.java#L1354-L1364 |
korpling/ANNIS | annis-service/src/main/java/annis/security/ANNISUserConfigurationManager.java | ANNISUserConfigurationManager.deleteUser | public boolean deleteUser(String userName) {
"""
Deletes the user from the disk
@param userName
@return True if successful.
"""
// load user info from file
if (resourcePath != null) {
lock.writeLock().lock();
try {
File userDir = new File(resourcePath, "users");
if (userDir.isDirectory()) {
// get the file which corresponds to the user
File userFile = new File(userDir.getAbsolutePath(), userName);
return userFile.delete();
}
} finally {
lock.writeLock().unlock();
}
} // end if resourcePath not null
return false;
} | java | public boolean deleteUser(String userName) {
// load user info from file
if (resourcePath != null) {
lock.writeLock().lock();
try {
File userDir = new File(resourcePath, "users");
if (userDir.isDirectory()) {
// get the file which corresponds to the user
File userFile = new File(userDir.getAbsolutePath(), userName);
return userFile.delete();
}
} finally {
lock.writeLock().unlock();
}
} // end if resourcePath not null
return false;
} | [
"public",
"boolean",
"deleteUser",
"(",
"String",
"userName",
")",
"{",
"// load user info from file",
"if",
"(",
"resourcePath",
"!=",
"null",
")",
"{",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"try",
"{",
"File",
"userDir",
"=",
... | Deletes the user from the disk
@param userName
@return True if successful. | [
"Deletes",
"the",
"user",
"from",
"the",
"disk"
] | train | https://github.com/korpling/ANNIS/blob/152a2e34832e015f73ac8ce8a7d4c32641641324/annis-service/src/main/java/annis/security/ANNISUserConfigurationManager.java#L204-L221 |
jbossws/jbossws-common | src/main/java/org/jboss/ws/common/configuration/ConfigHelper.java | ConfigHelper.setupConfigHandlers | @SuppressWarnings("rawtypes")
public void setupConfigHandlers(Binding binding, CommonConfig config) {
"""
Setups a given Binding instance using a specified CommonConfig
@param binding the Binding instance to setup
@param config the CommonConfig with the input configuration
"""
if (config != null) {
//start with the use handlers only to remove the previously set configuration
List<Handler> userHandlers = getNonConfigHandlers(binding.getHandlerChain());
List<Handler> handlers = convertToHandlers(config.getPreHandlerChains(), binding.getBindingID(), true); //PRE
handlers.addAll(userHandlers); //ENDPOINT
handlers.addAll(convertToHandlers(config.getPostHandlerChains(), binding.getBindingID(), false)); //POST
binding.setHandlerChain(handlers);
}
} | java | @SuppressWarnings("rawtypes")
public void setupConfigHandlers(Binding binding, CommonConfig config)
{
if (config != null) {
//start with the use handlers only to remove the previously set configuration
List<Handler> userHandlers = getNonConfigHandlers(binding.getHandlerChain());
List<Handler> handlers = convertToHandlers(config.getPreHandlerChains(), binding.getBindingID(), true); //PRE
handlers.addAll(userHandlers); //ENDPOINT
handlers.addAll(convertToHandlers(config.getPostHandlerChains(), binding.getBindingID(), false)); //POST
binding.setHandlerChain(handlers);
}
} | [
"@",
"SuppressWarnings",
"(",
"\"rawtypes\"",
")",
"public",
"void",
"setupConfigHandlers",
"(",
"Binding",
"binding",
",",
"CommonConfig",
"config",
")",
"{",
"if",
"(",
"config",
"!=",
"null",
")",
"{",
"//start with the use handlers only to remove the previously set ... | Setups a given Binding instance using a specified CommonConfig
@param binding the Binding instance to setup
@param config the CommonConfig with the input configuration | [
"Setups",
"a",
"given",
"Binding",
"instance",
"using",
"a",
"specified",
"CommonConfig"
] | train | https://github.com/jbossws/jbossws-common/blob/fcff8a3ef9bfe046d6fa8c855a3fe4f62841add7/src/main/java/org/jboss/ws/common/configuration/ConfigHelper.java#L176-L187 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java | DateFunctions.dateTruncStr | public static Expression dateTruncStr(String expression, DatePart part) {
"""
Returned expression results in ISO 8601 timestamp that has been truncated
so that the given date part is the least significant.
"""
return dateTruncStr(x(expression), part);
} | java | public static Expression dateTruncStr(String expression, DatePart part) {
return dateTruncStr(x(expression), part);
} | [
"public",
"static",
"Expression",
"dateTruncStr",
"(",
"String",
"expression",
",",
"DatePart",
"part",
")",
"{",
"return",
"dateTruncStr",
"(",
"x",
"(",
"expression",
")",
",",
"part",
")",
";",
"}"
] | Returned expression results in ISO 8601 timestamp that has been truncated
so that the given date part is the least significant. | [
"Returned",
"expression",
"results",
"in",
"ISO",
"8601",
"timestamp",
"that",
"has",
"been",
"truncated",
"so",
"that",
"the",
"given",
"date",
"part",
"is",
"the",
"least",
"significant",
"."
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/query/dsl/functions/DateFunctions.java#L196-L198 |
pravega/pravega | controller/src/main/java/io/pravega/controller/store/stream/PravegaTablesStoreHelper.java | PravegaTablesStoreHelper.addNewEntryIfAbsent | public CompletableFuture<Version> addNewEntryIfAbsent(String tableName, String key, @NonNull byte[] value) {
"""
Method to add new entry to table if it does not exist.
@param tableName tableName
@param key Key to add
@param value value to add
@return CompletableFuture which when completed will have added entry to the table if it did not exist.
"""
// if entry exists, we will get write conflict in attempting to create it again.
return expectingDataExists(addNewEntry(tableName, key, value), null);
} | java | public CompletableFuture<Version> addNewEntryIfAbsent(String tableName, String key, @NonNull byte[] value) {
// if entry exists, we will get write conflict in attempting to create it again.
return expectingDataExists(addNewEntry(tableName, key, value), null);
} | [
"public",
"CompletableFuture",
"<",
"Version",
">",
"addNewEntryIfAbsent",
"(",
"String",
"tableName",
",",
"String",
"key",
",",
"@",
"NonNull",
"byte",
"[",
"]",
"value",
")",
"{",
"// if entry exists, we will get write conflict in attempting to create it again. ",
"ret... | Method to add new entry to table if it does not exist.
@param tableName tableName
@param key Key to add
@param value value to add
@return CompletableFuture which when completed will have added entry to the table if it did not exist. | [
"Method",
"to",
"add",
"new",
"entry",
"to",
"table",
"if",
"it",
"does",
"not",
"exist",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/controller/src/main/java/io/pravega/controller/store/stream/PravegaTablesStoreHelper.java#L194-L197 |
molgenis/molgenis | molgenis-ontology/src/main/java/org/molgenis/ontology/sorta/service/impl/SortaServiceImpl.java | SortaServiceImpl.calculateNGromOTAnnotations | private Entity calculateNGromOTAnnotations(Entity inputEntity, Entity ontologyTermEntity) {
"""
A helper function to check if the ontology term (OT) contains the ontology annotations provided
in input. If the OT has the same annotation, the OT will be considered as a good match and the
similarity scores 100 are allocated to the OT
"""
OntologyTermHitEntity mapEntity =
new OntologyTermHitEntity(ontologyTermEntity, ontologyTermHitMetaData);
for (Entity annotationEntity :
ontologyTermEntity.getEntities(OntologyTermMetadata.ONTOLOGY_TERM_DYNAMIC_ANNOTATION)) {
String annotationName =
annotationEntity.getString(OntologyTermDynamicAnnotationMetadata.NAME);
String annotationValue =
annotationEntity.getString(OntologyTermDynamicAnnotationMetadata.VALUE);
for (String attributeName : inputEntity.getAttributeNames()) {
if (StringUtils.isNotEmpty(inputEntity.getString(attributeName))
&& StringUtils.equalsIgnoreCase(attributeName, annotationName)
&& StringUtils.equalsIgnoreCase(
inputEntity.getString(attributeName), annotationValue)) {
mapEntity.set(SCORE, 100d);
mapEntity.set(COMBINED_SCORE, 100d);
return mapEntity;
}
}
}
return mapEntity;
} | java | private Entity calculateNGromOTAnnotations(Entity inputEntity, Entity ontologyTermEntity) {
OntologyTermHitEntity mapEntity =
new OntologyTermHitEntity(ontologyTermEntity, ontologyTermHitMetaData);
for (Entity annotationEntity :
ontologyTermEntity.getEntities(OntologyTermMetadata.ONTOLOGY_TERM_DYNAMIC_ANNOTATION)) {
String annotationName =
annotationEntity.getString(OntologyTermDynamicAnnotationMetadata.NAME);
String annotationValue =
annotationEntity.getString(OntologyTermDynamicAnnotationMetadata.VALUE);
for (String attributeName : inputEntity.getAttributeNames()) {
if (StringUtils.isNotEmpty(inputEntity.getString(attributeName))
&& StringUtils.equalsIgnoreCase(attributeName, annotationName)
&& StringUtils.equalsIgnoreCase(
inputEntity.getString(attributeName), annotationValue)) {
mapEntity.set(SCORE, 100d);
mapEntity.set(COMBINED_SCORE, 100d);
return mapEntity;
}
}
}
return mapEntity;
} | [
"private",
"Entity",
"calculateNGromOTAnnotations",
"(",
"Entity",
"inputEntity",
",",
"Entity",
"ontologyTermEntity",
")",
"{",
"OntologyTermHitEntity",
"mapEntity",
"=",
"new",
"OntologyTermHitEntity",
"(",
"ontologyTermEntity",
",",
"ontologyTermHitMetaData",
")",
";",
... | A helper function to check if the ontology term (OT) contains the ontology annotations provided
in input. If the OT has the same annotation, the OT will be considered as a good match and the
similarity scores 100 are allocated to the OT | [
"A",
"helper",
"function",
"to",
"check",
"if",
"the",
"ontology",
"term",
"(",
"OT",
")",
"contains",
"the",
"ontology",
"annotations",
"provided",
"in",
"input",
".",
"If",
"the",
"OT",
"has",
"the",
"same",
"annotation",
"the",
"OT",
"will",
"be",
"co... | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-ontology/src/main/java/org/molgenis/ontology/sorta/service/impl/SortaServiceImpl.java#L296-L317 |
molgenis/molgenis | molgenis-i18n/src/main/java/org/molgenis/i18n/LocalizationMessageSource.java | LocalizationMessageSource.resolveCodeWithoutArguments | @Override
protected String resolveCodeWithoutArguments(String code, @Nullable @CheckForNull Locale locale) {
"""
Looks up a code in the {@link MessageResolution}.
<p>First tries the given locale if it is nonnull, then the fallbackLocale and finally the
default locale.
@param code the messageID to look up.
@param locale the Locale whose language code should be tried first, may be null
@return The message, or null if none found.
"""
Stream<Locale> candidates = Stream.of(locale, tryGetFallbackLocale(), DEFAULT_LOCALE);
return candidates
.filter(Objects::nonNull)
.map(candidate -> messageRepository.resolveCodeWithoutArguments(code, candidate))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} | java | @Override
protected String resolveCodeWithoutArguments(String code, @Nullable @CheckForNull Locale locale) {
Stream<Locale> candidates = Stream.of(locale, tryGetFallbackLocale(), DEFAULT_LOCALE);
return candidates
.filter(Objects::nonNull)
.map(candidate -> messageRepository.resolveCodeWithoutArguments(code, candidate))
.filter(Objects::nonNull)
.findFirst()
.orElse(null);
} | [
"@",
"Override",
"protected",
"String",
"resolveCodeWithoutArguments",
"(",
"String",
"code",
",",
"@",
"Nullable",
"@",
"CheckForNull",
"Locale",
"locale",
")",
"{",
"Stream",
"<",
"Locale",
">",
"candidates",
"=",
"Stream",
".",
"of",
"(",
"locale",
",",
"... | Looks up a code in the {@link MessageResolution}.
<p>First tries the given locale if it is nonnull, then the fallbackLocale and finally the
default locale.
@param code the messageID to look up.
@param locale the Locale whose language code should be tried first, may be null
@return The message, or null if none found. | [
"Looks",
"up",
"a",
"code",
"in",
"the",
"{",
"@link",
"MessageResolution",
"}",
"."
] | train | https://github.com/molgenis/molgenis/blob/b4d0d6b27e6f6c8d7505a3863dc03b589601f987/molgenis-i18n/src/main/java/org/molgenis/i18n/LocalizationMessageSource.java#L85-L94 |
samskivert/samskivert | src/main/java/com/samskivert/util/ProcessLogger.java | ProcessLogger.copyMergedOutput | public static void copyMergedOutput (Logger target, String name, Process process) {
"""
Starts a thread to copy the output of the supplied process's stdout stream to the supplied
target logger (it assumes the process was created with a ProcessBuilder and the stdout and
stderr streams have been merged).
@see #copyOutput
"""
new StreamReader(target, name + " output", process.getInputStream()).start();
} | java | public static void copyMergedOutput (Logger target, String name, Process process)
{
new StreamReader(target, name + " output", process.getInputStream()).start();
} | [
"public",
"static",
"void",
"copyMergedOutput",
"(",
"Logger",
"target",
",",
"String",
"name",
",",
"Process",
"process",
")",
"{",
"new",
"StreamReader",
"(",
"target",
",",
"name",
"+",
"\" output\"",
",",
"process",
".",
"getInputStream",
"(",
")",
")",
... | Starts a thread to copy the output of the supplied process's stdout stream to the supplied
target logger (it assumes the process was created with a ProcessBuilder and the stdout and
stderr streams have been merged).
@see #copyOutput | [
"Starts",
"a",
"thread",
"to",
"copy",
"the",
"output",
"of",
"the",
"supplied",
"process",
"s",
"stdout",
"stream",
"to",
"the",
"supplied",
"target",
"logger",
"(",
"it",
"assumes",
"the",
"process",
"was",
"created",
"with",
"a",
"ProcessBuilder",
"and",
... | train | https://github.com/samskivert/samskivert/blob/a64d9ef42b69819bdb2c66bddac6a64caef928b6/src/main/java/com/samskivert/util/ProcessLogger.java#L42-L45 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeDirectory.java | INodeDirectory.addChild | <T extends INode> T addChild(final T node, boolean inheritPermission) {
"""
Add a child inode to the directory.
@param node INode to insert
@param inheritPermission inherit permission from parent?
@return null if the child with this name already exists;
node, otherwise
"""
return addChild(node, inheritPermission, true, UNKNOWN_INDEX);
} | java | <T extends INode> T addChild(final T node, boolean inheritPermission) {
return addChild(node, inheritPermission, true, UNKNOWN_INDEX);
} | [
"<",
"T",
"extends",
"INode",
">",
"T",
"addChild",
"(",
"final",
"T",
"node",
",",
"boolean",
"inheritPermission",
")",
"{",
"return",
"addChild",
"(",
"node",
",",
"inheritPermission",
",",
"true",
",",
"UNKNOWN_INDEX",
")",
";",
"}"
] | Add a child inode to the directory.
@param node INode to insert
@param inheritPermission inherit permission from parent?
@return null if the child with this name already exists;
node, otherwise | [
"Add",
"a",
"child",
"inode",
"to",
"the",
"directory",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/namenode/INodeDirectory.java#L247-L249 |
jimmoores/quandl4j | core/src/main/java/com/jimmoores/quandl/SearchResult.java | SearchResult.getMetaDataResultList | public List<MetaDataResult> getMetaDataResultList() {
"""
Extract a list of MetaDataResult objects, each one representing a match. Throws a QuandlRuntimeException if it cannot construct a valid
HeaderDefinition
@return the header definition, not null
"""
JSONArray jsonArray = null;
try {
jsonArray = _jsonObject.getJSONArray(DATASETS_ARRAY_FIELD);
List<MetaDataResult> metaDataResults = new ArrayList<MetaDataResult>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
metaDataResults.add(MetaDataResult.of(jsonArray.getJSONObject(i)));
}
return metaDataResults;
} catch (JSONException ex) {
s_logger.error("Metadata had unexpected structure - could not extract datasets field, was:\n{}", _jsonObject.toString());
throw new QuandlRuntimeException("Metadata had unexpected structure", ex);
}
} | java | public List<MetaDataResult> getMetaDataResultList() {
JSONArray jsonArray = null;
try {
jsonArray = _jsonObject.getJSONArray(DATASETS_ARRAY_FIELD);
List<MetaDataResult> metaDataResults = new ArrayList<MetaDataResult>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
metaDataResults.add(MetaDataResult.of(jsonArray.getJSONObject(i)));
}
return metaDataResults;
} catch (JSONException ex) {
s_logger.error("Metadata had unexpected structure - could not extract datasets field, was:\n{}", _jsonObject.toString());
throw new QuandlRuntimeException("Metadata had unexpected structure", ex);
}
} | [
"public",
"List",
"<",
"MetaDataResult",
">",
"getMetaDataResultList",
"(",
")",
"{",
"JSONArray",
"jsonArray",
"=",
"null",
";",
"try",
"{",
"jsonArray",
"=",
"_jsonObject",
".",
"getJSONArray",
"(",
"DATASETS_ARRAY_FIELD",
")",
";",
"List",
"<",
"MetaDataResul... | Extract a list of MetaDataResult objects, each one representing a match. Throws a QuandlRuntimeException if it cannot construct a valid
HeaderDefinition
@return the header definition, not null | [
"Extract",
"a",
"list",
"of",
"MetaDataResult",
"objects",
"each",
"one",
"representing",
"a",
"match",
".",
"Throws",
"a",
"QuandlRuntimeException",
"if",
"it",
"cannot",
"construct",
"a",
"valid",
"HeaderDefinition"
] | train | https://github.com/jimmoores/quandl4j/blob/5d67ae60279d889da93ae7aa3bf6b7d536f88822/core/src/main/java/com/jimmoores/quandl/SearchResult.java#L92-L105 |
diffplug/JMatIO | src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java | MatFileReader.zeroEndByteArrayToString | private String zeroEndByteArrayToString(byte[] bytes) throws IOException {
"""
Converts byte array to <code>String</code>.
It assumes that String ends with \0 value.
@param bytes byte array containing the string.
@return String retrieved from byte array.
@throws IOException if reading error occurred.
"""
int i = 0;
for ( i = 0; i < bytes.length && bytes[i] != 0; i++ );
return new String( bytes, 0, i );
} | java | private String zeroEndByteArrayToString(byte[] bytes) throws IOException
{
int i = 0;
for ( i = 0; i < bytes.length && bytes[i] != 0; i++ );
return new String( bytes, 0, i );
} | [
"private",
"String",
"zeroEndByteArrayToString",
"(",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"IOException",
"{",
"int",
"i",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"0",
";",
"i",
"<",
"bytes",
".",
"length",
"&&",
"bytes",
"[",
"i",
"]",
"!=",
"0"... | Converts byte array to <code>String</code>.
It assumes that String ends with \0 value.
@param bytes byte array containing the string.
@return String retrieved from byte array.
@throws IOException if reading error occurred. | [
"Converts",
"byte",
"array",
"to",
"<code",
">",
"String<",
"/",
"code",
">",
"."
] | train | https://github.com/diffplug/JMatIO/blob/dab8a54fa21a8faeaa81537cdc45323c5c4e6ca6/src/main/java/ca/mjdsystems/jmatio/io/MatFileReader.java#L1301-L1309 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java | PublicIPPrefixesInner.updateTags | public PublicIPPrefixInner updateTags(String resourceGroupName, String publicIpPrefixName) {
"""
Updates public IP prefix tags.
@param resourceGroupName The name of the resource group.
@param publicIpPrefixName The name of the public IP prefix.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PublicIPPrefixInner object if successful.
"""
return updateTagsWithServiceResponseAsync(resourceGroupName, publicIpPrefixName).toBlocking().last().body();
} | java | public PublicIPPrefixInner updateTags(String resourceGroupName, String publicIpPrefixName) {
return updateTagsWithServiceResponseAsync(resourceGroupName, publicIpPrefixName).toBlocking().last().body();
} | [
"public",
"PublicIPPrefixInner",
"updateTags",
"(",
"String",
"resourceGroupName",
",",
"String",
"publicIpPrefixName",
")",
"{",
"return",
"updateTagsWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"publicIpPrefixName",
")",
".",
"toBlocking",
"(",
")",
".",
... | Updates public IP prefix tags.
@param resourceGroupName The name of the resource group.
@param publicIpPrefixName The name of the public IP prefix.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PublicIPPrefixInner object if successful. | [
"Updates",
"public",
"IP",
"prefix",
"tags",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/network/resource-manager/v2018_07_01/src/main/java/com/microsoft/azure/management/network/v2018_07_01/implementation/PublicIPPrefixesInner.java#L611-L613 |
apache/groovy | src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java | ClassNodeUtils.samePackageName | public static boolean samePackageName(ClassNode first, ClassNode second) {
"""
Determine if the given ClassNode values have the same package name.
@param first a ClassNode
@param second a ClassNode
@return true if both given nodes have the same package name
@throws NullPointerException if either of the given nodes are null
"""
return Objects.equals(first.getPackageName(), second.getPackageName());
} | java | public static boolean samePackageName(ClassNode first, ClassNode second) {
return Objects.equals(first.getPackageName(), second.getPackageName());
} | [
"public",
"static",
"boolean",
"samePackageName",
"(",
"ClassNode",
"first",
",",
"ClassNode",
"second",
")",
"{",
"return",
"Objects",
".",
"equals",
"(",
"first",
".",
"getPackageName",
"(",
")",
",",
"second",
".",
"getPackageName",
"(",
")",
")",
";",
... | Determine if the given ClassNode values have the same package name.
@param first a ClassNode
@param second a ClassNode
@return true if both given nodes have the same package name
@throws NullPointerException if either of the given nodes are null | [
"Determine",
"if",
"the",
"given",
"ClassNode",
"values",
"have",
"the",
"same",
"package",
"name",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/apache/groovy/ast/tools/ClassNodeUtils.java#L385-L387 |
briandilley/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcHttpClient.java | JsonRpcHttpClient.prepareConnection | private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
"""
Prepares a connection to the server.
@param extraHeaders extra headers to add to the request
@return the unopened connection
@throws IOException
"""
// create URLConnection
HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
connection.setConnectTimeout(connectionTimeoutMillis);
connection.setReadTimeout(readTimeoutMillis);
connection.setAllowUserInteraction(false);
connection.setDefaultUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
setupSsl(connection);
addHeaders(extraHeaders, connection);
return connection;
} | java | private HttpURLConnection prepareConnection(Map<String, String> extraHeaders) throws IOException {
// create URLConnection
HttpURLConnection connection = (HttpURLConnection) serviceUrl.openConnection(connectionProxy);
connection.setConnectTimeout(connectionTimeoutMillis);
connection.setReadTimeout(readTimeoutMillis);
connection.setAllowUserInteraction(false);
connection.setDefaultUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestMethod("POST");
setupSsl(connection);
addHeaders(extraHeaders, connection);
return connection;
} | [
"private",
"HttpURLConnection",
"prepareConnection",
"(",
"Map",
"<",
"String",
",",
"String",
">",
"extraHeaders",
")",
"throws",
"IOException",
"{",
"// create URLConnection",
"HttpURLConnection",
"connection",
"=",
"(",
"HttpURLConnection",
")",
"serviceUrl",
".",
... | Prepares a connection to the server.
@param extraHeaders extra headers to add to the request
@return the unopened connection
@throws IOException | [
"Prepares",
"a",
"connection",
"to",
"the",
"server",
"."
] | train | https://github.com/briandilley/jsonrpc4j/blob/d749762c9295b92d893677a8c7be2a14dd43b3bb/src/main/java/com/googlecode/jsonrpc4j/JsonRpcHttpClient.java#L195-L213 |
jfinal/jfinal | src/main/java/com/jfinal/aop/AopManager.java | AopManager.addMapping | public <T> void addMapping(Class<T> from, String to) {
"""
功能与 addMapping(Class<T> from, Class<? extends T> to) 相同,仅仅是第二个参数
由 Class 改为 String 类型,便于从外部配置文件传递 String 参数过来
<pre>
示例:
AopManager.me().addMapping(IService.class, "com.xxx.MyService")
以上代码的参数 "com.xxx.MyService" 可通过外部配置文件传入,便于通过配置文件切换接口的
实现类:
AopManager.me().addMapping(IService.class, PropKit.get("ServiceImpl");
</pre>
"""
Aop.aopFactory.addMapping(from, to);
} | java | public <T> void addMapping(Class<T> from, String to) {
Aop.aopFactory.addMapping(from, to);
} | [
"public",
"<",
"T",
">",
"void",
"addMapping",
"(",
"Class",
"<",
"T",
">",
"from",
",",
"String",
"to",
")",
"{",
"Aop",
".",
"aopFactory",
".",
"addMapping",
"(",
"from",
",",
"to",
")",
";",
"}"
] | 功能与 addMapping(Class<T> from, Class<? extends T> to) 相同,仅仅是第二个参数
由 Class 改为 String 类型,便于从外部配置文件传递 String 参数过来
<pre>
示例:
AopManager.me().addMapping(IService.class, "com.xxx.MyService")
以上代码的参数 "com.xxx.MyService" 可通过外部配置文件传入,便于通过配置文件切换接口的
实现类:
AopManager.me().addMapping(IService.class, PropKit.get("ServiceImpl");
</pre> | [
"功能与",
"addMapping",
"(",
"Class<T",
">",
"from",
"Class<?",
"extends",
"T",
">",
"to",
")",
"相同,仅仅是第二个参数",
"由",
"Class",
"改为",
"String",
"类型,便于从外部配置文件传递",
"String",
"参数过来"
] | train | https://github.com/jfinal/jfinal/blob/fc07f0f5d56e85ccd3cfcdd587b56b8dd9c663e9/src/main/java/com/jfinal/aop/AopManager.java#L159-L161 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/reflect/RecursiveObjectReader.java | RecursiveObjectReader.getProperty | public static Object getProperty(Object obj, String name) {
"""
Recursively gets value of object or its subobjects property specified by its
name.
The object can be a user defined object, map or array. The property name
correspondently must be object property, map key or array index.
@param obj an object to read property from.
@param name a name of the property to get.
@return the property value or null if property doesn't exist or introspection
failed.
"""
if (obj == null || name == null)
return null;
String[] names = name.split("\\.");
if (names == null || names.length == 0)
return null;
return performGetProperty(obj, names, 0);
} | java | public static Object getProperty(Object obj, String name) {
if (obj == null || name == null)
return null;
String[] names = name.split("\\.");
if (names == null || names.length == 0)
return null;
return performGetProperty(obj, names, 0);
} | [
"public",
"static",
"Object",
"getProperty",
"(",
"Object",
"obj",
",",
"String",
"name",
")",
"{",
"if",
"(",
"obj",
"==",
"null",
"||",
"name",
"==",
"null",
")",
"return",
"null",
";",
"String",
"[",
"]",
"names",
"=",
"name",
".",
"split",
"(",
... | Recursively gets value of object or its subobjects property specified by its
name.
The object can be a user defined object, map or array. The property name
correspondently must be object property, map key or array index.
@param obj an object to read property from.
@param name a name of the property to get.
@return the property value or null if property doesn't exist or introspection
failed. | [
"Recursively",
"gets",
"value",
"of",
"object",
"or",
"its",
"subobjects",
"property",
"specified",
"by",
"its",
"name",
"."
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/reflect/RecursiveObjectReader.java#L75-L84 |
tvesalainen/util | util/src/main/java/org/vesalainen/nio/file/attribute/PosixHelp.java | PosixHelp.setPermission | public static final void setPermission(Path path, String perms) throws IOException {
"""
Set posix permissions if supported.
@param path
@param perms 10 or 9 length E.g. -rwxr--r--
@throws java.io.IOException
"""
checkFileType(path, perms);
if (supports("posix"))
{
Set<PosixFilePermission> posixPerms = PosixFilePermissions.fromString(permsPart(perms));
Files.setPosixFilePermissions(path, posixPerms);
}
else
{
JavaLogging.getLogger(PosixHelp.class).warning("no posix support. setPermission(%s, %s)", path, perms);
}
} | java | public static final void setPermission(Path path, String perms) throws IOException
{
checkFileType(path, perms);
if (supports("posix"))
{
Set<PosixFilePermission> posixPerms = PosixFilePermissions.fromString(permsPart(perms));
Files.setPosixFilePermissions(path, posixPerms);
}
else
{
JavaLogging.getLogger(PosixHelp.class).warning("no posix support. setPermission(%s, %s)", path, perms);
}
} | [
"public",
"static",
"final",
"void",
"setPermission",
"(",
"Path",
"path",
",",
"String",
"perms",
")",
"throws",
"IOException",
"{",
"checkFileType",
"(",
"path",
",",
"perms",
")",
";",
"if",
"(",
"supports",
"(",
"\"posix\"",
")",
")",
"{",
"Set",
"<"... | Set posix permissions if supported.
@param path
@param perms 10 or 9 length E.g. -rwxr--r--
@throws java.io.IOException | [
"Set",
"posix",
"permissions",
"if",
"supported",
"."
] | train | https://github.com/tvesalainen/util/blob/bba7a44689f638ffabc8be40a75bdc9a33676433/util/src/main/java/org/vesalainen/nio/file/attribute/PosixHelp.java#L223-L235 |
xhsun/gw2wrapper | src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java | AsynchronousRequest.getWvWMatchStat | public void getWvWMatchStat(int worldID, Callback<WvWMatchStat> callback) throws NullPointerException {
"""
For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param worldID {@link World#id}
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@see WvWMatchStat WvW match stat info
"""
gw2API.getWvWMatchStatUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | java | public void getWvWMatchStat(int worldID, Callback<WvWMatchStat> callback) throws NullPointerException {
gw2API.getWvWMatchStatUsingWorld(Integer.toString(worldID)).enqueue(callback);
} | [
"public",
"void",
"getWvWMatchStat",
"(",
"int",
"worldID",
",",
"Callback",
"<",
"WvWMatchStat",
">",
"callback",
")",
"throws",
"NullPointerException",
"{",
"gw2API",
".",
"getWvWMatchStatUsingWorld",
"(",
"Integer",
".",
"toString",
"(",
"worldID",
")",
")",
... | For more info on WvW matches API go <a href="https://wiki.guildwars2.com/wiki/API:2/wvw/matches">here</a><br/>
Give user the access to {@link Callback#onResponse(Call, Response)} and {@link Callback#onFailure(Call, Throwable)} methods for custom interactions
@param worldID {@link World#id}
@param callback callback that is going to be used for {@link Call#enqueue(Callback)}
@throws NullPointerException if given {@link Callback} is empty
@see WvWMatchStat WvW match stat info | [
"For",
"more",
"info",
"on",
"WvW",
"matches",
"API",
"go",
"<a",
"href",
"=",
"https",
":",
"//",
"wiki",
".",
"guildwars2",
".",
"com",
"/",
"wiki",
"/",
"API",
":",
"2",
"/",
"wvw",
"/",
"matches",
">",
"here<",
"/",
"a",
">",
"<br",
"/",
">... | train | https://github.com/xhsun/gw2wrapper/blob/c8a43b51f363b032074fb152ee6efe657e33e525/src/main/java/me/xhsun/guildwars2wrapper/AsynchronousRequest.java#L2694-L2696 |
js-lib-com/template.xhtml | src/main/java/js/template/xhtml/Serializer.java | Serializer.writeAttributes | private void writeAttributes(Element element, Iterable<Attr> attributes) throws IOException {
"""
Traverse all element's attributes and delegates {@link #writeAttribute(String, String)}. Skip operators if
{@link #enableOperatorsSerialization} is false. This method is called after element start tag was opened.
@param element element whose attributes to write.
@throws IOException if underlying writer fails to write.
"""
for (Attr attr : attributes) {
final String attrName = attr.getName();
if (!enableOperatorsSerialization && Opcode.fromAttrName(attrName) != Opcode.NONE) {
// skip operator attributes if operators serialization is disabled
continue;
}
final String attrValue = attr.getValue();
if (attrValue.isEmpty()) {
// do not write the attribute if its value is empty
continue;
}
if (attrValue.equals(HTML.DEFAULT_ATTRS.get(attrName))) {
// do not write the attribute if it is a default one with a default value
continue;
}
writeAttribute(attrName, attrValue);
}
} | java | private void writeAttributes(Element element, Iterable<Attr> attributes) throws IOException {
for (Attr attr : attributes) {
final String attrName = attr.getName();
if (!enableOperatorsSerialization && Opcode.fromAttrName(attrName) != Opcode.NONE) {
// skip operator attributes if operators serialization is disabled
continue;
}
final String attrValue = attr.getValue();
if (attrValue.isEmpty()) {
// do not write the attribute if its value is empty
continue;
}
if (attrValue.equals(HTML.DEFAULT_ATTRS.get(attrName))) {
// do not write the attribute if it is a default one with a default value
continue;
}
writeAttribute(attrName, attrValue);
}
} | [
"private",
"void",
"writeAttributes",
"(",
"Element",
"element",
",",
"Iterable",
"<",
"Attr",
">",
"attributes",
")",
"throws",
"IOException",
"{",
"for",
"(",
"Attr",
"attr",
":",
"attributes",
")",
"{",
"final",
"String",
"attrName",
"=",
"attr",
".",
"... | Traverse all element's attributes and delegates {@link #writeAttribute(String, String)}. Skip operators if
{@link #enableOperatorsSerialization} is false. This method is called after element start tag was opened.
@param element element whose attributes to write.
@throws IOException if underlying writer fails to write. | [
"Traverse",
"all",
"element",
"s",
"attributes",
"and",
"delegates",
"{",
"@link",
"#writeAttribute",
"(",
"String",
"String",
")",
"}",
".",
"Skip",
"operators",
"if",
"{",
"@link",
"#enableOperatorsSerialization",
"}",
"is",
"false",
".",
"This",
"method",
"... | train | https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/Serializer.java#L354-L372 |
ops4j/org.ops4j.pax.logging | pax-logging-service/src/main/java/org/apache/log4j/OsgiThrowableRenderer.java | OsgiThrowableRenderer.formatElement | private String formatElement(final StackTraceElement element, final Map<String, String> classMap) {
"""
Format one element from stack trace.
@param element element, may not be null.
@param classMap map of class name to location.
@return string representation of element.
"""
StringBuilder buf = new StringBuilder("\tat ");
buf.append(element);
String className = element.getClassName();
String classDetails = classMap.get(className);
if (classDetails == null) {
try {
Class<?> cls = findClass(className);
classDetails = getClassDetail(cls);
classMap.put(className, classDetails);
} catch (Throwable th) {
// Ignore
}
}
if (classDetails != null) {
buf.append(classDetails);
}
return buf.toString();
} | java | private String formatElement(final StackTraceElement element, final Map<String, String> classMap) {
StringBuilder buf = new StringBuilder("\tat ");
buf.append(element);
String className = element.getClassName();
String classDetails = classMap.get(className);
if (classDetails == null) {
try {
Class<?> cls = findClass(className);
classDetails = getClassDetail(cls);
classMap.put(className, classDetails);
} catch (Throwable th) {
// Ignore
}
}
if (classDetails != null) {
buf.append(classDetails);
}
return buf.toString();
} | [
"private",
"String",
"formatElement",
"(",
"final",
"StackTraceElement",
"element",
",",
"final",
"Map",
"<",
"String",
",",
"String",
">",
"classMap",
")",
"{",
"StringBuilder",
"buf",
"=",
"new",
"StringBuilder",
"(",
"\"\\tat \"",
")",
";",
"buf",
".",
"a... | Format one element from stack trace.
@param element element, may not be null.
@param classMap map of class name to location.
@return string representation of element. | [
"Format",
"one",
"element",
"from",
"stack",
"trace",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-service/src/main/java/org/apache/log4j/OsgiThrowableRenderer.java#L161-L179 |
raydac/java-binary-block-parser | jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java | JBBPDslBuilder.Bits | public JBBPDslBuilder Bits(final String name, final JBBPBitNumber bits) {
"""
Add named fixed length bit field.
@param name name of the field, if null then anonymous one
@param bits number of bits as length of the field, must not be null
@return the builder instance, must not be null
"""
final Item item = new Item(BinType.BIT, name, this.byteOrder);
item.bitNumber = bits;
this.addItem(item);
return this;
} | java | public JBBPDslBuilder Bits(final String name, final JBBPBitNumber bits) {
final Item item = new Item(BinType.BIT, name, this.byteOrder);
item.bitNumber = bits;
this.addItem(item);
return this;
} | [
"public",
"JBBPDslBuilder",
"Bits",
"(",
"final",
"String",
"name",
",",
"final",
"JBBPBitNumber",
"bits",
")",
"{",
"final",
"Item",
"item",
"=",
"new",
"Item",
"(",
"BinType",
".",
"BIT",
",",
"name",
",",
"this",
".",
"byteOrder",
")",
";",
"item",
... | Add named fixed length bit field.
@param name name of the field, if null then anonymous one
@param bits number of bits as length of the field, must not be null
@return the builder instance, must not be null | [
"Add",
"named",
"fixed",
"length",
"bit",
"field",
"."
] | train | https://github.com/raydac/java-binary-block-parser/blob/6d98abcab01e0c72d525ebcc9e7b694f9ce49f5b/jbbp/src/main/java/com/igormaznitsa/jbbp/utils/JBBPDslBuilder.java#L636-L641 |
E7du/jfinal-ext3 | src/main/java/com/jfinal/ext/core/ControllerExt.java | ControllerExt.getParaToBigInteger | public BigInteger getParaToBigInteger(String name,BigInteger defaultValue) {
"""
Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
@param name a String specifying the name of the parameter
@return a BigInteger representing the single value of the parameter
"""
return this.toBigInteger(getPara(name), defaultValue);
} | java | public BigInteger getParaToBigInteger(String name,BigInteger defaultValue){
return this.toBigInteger(getPara(name), defaultValue);
} | [
"public",
"BigInteger",
"getParaToBigInteger",
"(",
"String",
"name",
",",
"BigInteger",
"defaultValue",
")",
"{",
"return",
"this",
".",
"toBigInteger",
"(",
"getPara",
"(",
"name",
")",
",",
"defaultValue",
")",
";",
"}"
] | Returns the value of a request parameter and convert to BigInteger with a default value if it is null.
@param name a String specifying the name of the parameter
@return a BigInteger representing the single value of the parameter | [
"Returns",
"the",
"value",
"of",
"a",
"request",
"parameter",
"and",
"convert",
"to",
"BigInteger",
"with",
"a",
"default",
"value",
"if",
"it",
"is",
"null",
"."
] | train | https://github.com/E7du/jfinal-ext3/blob/8ffcbd150fd50c72852bb778bd427b5eb19254dc/src/main/java/com/jfinal/ext/core/ControllerExt.java#L101-L103 |
headius/invokebinder | src/main/java/com/headius/invokebinder/SmartBinder.java | SmartBinder.invokeVirtualQuiet | public SmartHandle invokeVirtualQuiet(Lookup lookup, String name) {
"""
Terminate this binder by looking up the named virtual method on the
first argument's type. Perform the actual method lookup using the given
Lookup object. If the lookup fails, a RuntimeException will be raised,
containing the actual reason. This method is for convenience in (for
example) field declarations, where checked exceptions noise up code
that can't recover anyway.
Use this in situations where you would not expect your library to be
usable if the target method can't be acquired.
@param lookup the Lookup to use for handle lookups
@param name the name of the target virtual method
@return a SmartHandle with this binder's starting signature, bound
to the target method
"""
return new SmartHandle(start, binder.invokeVirtualQuiet(lookup, name));
} | java | public SmartHandle invokeVirtualQuiet(Lookup lookup, String name) {
return new SmartHandle(start, binder.invokeVirtualQuiet(lookup, name));
} | [
"public",
"SmartHandle",
"invokeVirtualQuiet",
"(",
"Lookup",
"lookup",
",",
"String",
"name",
")",
"{",
"return",
"new",
"SmartHandle",
"(",
"start",
",",
"binder",
".",
"invokeVirtualQuiet",
"(",
"lookup",
",",
"name",
")",
")",
";",
"}"
] | Terminate this binder by looking up the named virtual method on the
first argument's type. Perform the actual method lookup using the given
Lookup object. If the lookup fails, a RuntimeException will be raised,
containing the actual reason. This method is for convenience in (for
example) field declarations, where checked exceptions noise up code
that can't recover anyway.
Use this in situations where you would not expect your library to be
usable if the target method can't be acquired.
@param lookup the Lookup to use for handle lookups
@param name the name of the target virtual method
@return a SmartHandle with this binder's starting signature, bound
to the target method | [
"Terminate",
"this",
"binder",
"by",
"looking",
"up",
"the",
"named",
"virtual",
"method",
"on",
"the",
"first",
"argument",
"s",
"type",
".",
"Perform",
"the",
"actual",
"method",
"lookup",
"using",
"the",
"given",
"Lookup",
"object",
".",
"If",
"the",
"l... | train | https://github.com/headius/invokebinder/blob/ce6bfeb8e33265480daa7b797989dd915d51238d/src/main/java/com/headius/invokebinder/SmartBinder.java#L1001-L1003 |
redkale/redkale | src/org/redkale/util/SelectColumn.java | SelectColumn.createIncludes | @Deprecated
public static SelectColumn createIncludes(String[] cols, String... columns) {
"""
@deprecated
class中的字段名
@param cols 包含的字段名集合
@param columns 包含的字段名集合
@return SelectColumn
"""
return new SelectColumn(Utility.append(cols, columns), false);
} | java | @Deprecated
public static SelectColumn createIncludes(String[] cols, String... columns) {
return new SelectColumn(Utility.append(cols, columns), false);
} | [
"@",
"Deprecated",
"public",
"static",
"SelectColumn",
"createIncludes",
"(",
"String",
"[",
"]",
"cols",
",",
"String",
"...",
"columns",
")",
"{",
"return",
"new",
"SelectColumn",
"(",
"Utility",
".",
"append",
"(",
"cols",
",",
"columns",
")",
",",
"fal... | @deprecated
class中的字段名
@param cols 包含的字段名集合
@param columns 包含的字段名集合
@return SelectColumn | [
"@deprecated",
"class中的字段名"
] | train | https://github.com/redkale/redkale/blob/ea5169b5c5ea7412fd762331c0c497165832e901/src/org/redkale/util/SelectColumn.java#L105-L108 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/DistributedFileSystem.java | DistributedFileSystem.concat | @Deprecated
public void concat(Path trg, Path [] psrcs) throws IOException {
"""
THIS IS DFS only operations, it is not part of FileSystem
move blocks from srcs to trg
and delete srcs afterwards
All blocks should be of the same size
@param trg existing file to append to
@param psrcs list of files (same block size, same replication)
@throws IOException
"""
concat(trg, psrcs, true);
} | java | @Deprecated
public void concat(Path trg, Path [] psrcs) throws IOException {
concat(trg, psrcs, true);
} | [
"@",
"Deprecated",
"public",
"void",
"concat",
"(",
"Path",
"trg",
",",
"Path",
"[",
"]",
"psrcs",
")",
"throws",
"IOException",
"{",
"concat",
"(",
"trg",
",",
"psrcs",
",",
"true",
")",
";",
"}"
] | THIS IS DFS only operations, it is not part of FileSystem
move blocks from srcs to trg
and delete srcs afterwards
All blocks should be of the same size
@param trg existing file to append to
@param psrcs list of files (same block size, same replication)
@throws IOException | [
"THIS",
"IS",
"DFS",
"only",
"operations",
"it",
"is",
"not",
"part",
"of",
"FileSystem",
"move",
"blocks",
"from",
"srcs",
"to",
"trg",
"and",
"delete",
"srcs",
"afterwards",
"All",
"blocks",
"should",
"be",
"of",
"the",
"same",
"size"
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/DistributedFileSystem.java#L423-L426 |
windup/windup | reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationServiceCache.java | ClassificationServiceCache.cacheClassificationFileModel | static void cacheClassificationFileModel(GraphRewrite event, ClassificationModel classificationModel, FileModel fileModel, boolean linked) {
"""
Cache the status of the link between the provided {@link ClassificationModel} and the given {@link FileModel}.
"""
String key = getClassificationFileModelCacheKey(classificationModel, fileModel);
getCache(event).put(key, linked);
} | java | static void cacheClassificationFileModel(GraphRewrite event, ClassificationModel classificationModel, FileModel fileModel, boolean linked)
{
String key = getClassificationFileModelCacheKey(classificationModel, fileModel);
getCache(event).put(key, linked);
} | [
"static",
"void",
"cacheClassificationFileModel",
"(",
"GraphRewrite",
"event",
",",
"ClassificationModel",
"classificationModel",
",",
"FileModel",
"fileModel",
",",
"boolean",
"linked",
")",
"{",
"String",
"key",
"=",
"getClassificationFileModelCacheKey",
"(",
"classifi... | Cache the status of the link between the provided {@link ClassificationModel} and the given {@link FileModel}. | [
"Cache",
"the",
"status",
"of",
"the",
"link",
"between",
"the",
"provided",
"{"
] | train | https://github.com/windup/windup/blob/6668f09e7f012d24a0b4212ada8809417225b2ad/reporting/api/src/main/java/org/jboss/windup/reporting/service/ClassificationServiceCache.java#L64-L68 |
Azure/azure-sdk-for-java | datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java | ProjectsInner.getAsync | public Observable<ProjectInner> getAsync(String groupName, String serviceName, String projectName) {
"""
Get project information.
The project resource is a nested resource representing a stored migration project. The GET method retrieves information about a project.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProjectInner object
"""
return getWithServiceResponseAsync(groupName, serviceName, projectName).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() {
@Override
public ProjectInner call(ServiceResponse<ProjectInner> response) {
return response.body();
}
});
} | java | public Observable<ProjectInner> getAsync(String groupName, String serviceName, String projectName) {
return getWithServiceResponseAsync(groupName, serviceName, projectName).map(new Func1<ServiceResponse<ProjectInner>, ProjectInner>() {
@Override
public ProjectInner call(ServiceResponse<ProjectInner> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"ProjectInner",
">",
"getAsync",
"(",
"String",
"groupName",
",",
"String",
"serviceName",
",",
"String",
"projectName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"groupName",
",",
"serviceName",
",",
"projectName",
")",
... | Get project information.
The project resource is a nested resource representing a stored migration project. The GET method retrieves information about a project.
@param groupName Name of the resource group
@param serviceName Name of the service
@param projectName Name of the project
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the ProjectInner object | [
"Get",
"project",
"information",
".",
"The",
"project",
"resource",
"is",
"a",
"nested",
"resource",
"representing",
"a",
"stored",
"migration",
"project",
".",
"The",
"GET",
"method",
"retrieves",
"information",
"about",
"a",
"project",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/datamigration/resource-manager/v2017_11_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2017_11_15_preview/implementation/ProjectsInner.java#L366-L373 |
Azure/azure-sdk-for-java | mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java | LiveEventsInner.listAsync | public Observable<Page<LiveEventInner>> listAsync(final String resourceGroupName, final String accountName) {
"""
List Live Events.
Lists the Live Events in the account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<LiveEventInner> object
"""
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<LiveEventInner>>, Page<LiveEventInner>>() {
@Override
public Page<LiveEventInner> call(ServiceResponse<Page<LiveEventInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<LiveEventInner>> listAsync(final String resourceGroupName, final String accountName) {
return listWithServiceResponseAsync(resourceGroupName, accountName)
.map(new Func1<ServiceResponse<Page<LiveEventInner>>, Page<LiveEventInner>>() {
@Override
public Page<LiveEventInner> call(ServiceResponse<Page<LiveEventInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"LiveEventInner",
">",
">",
"listAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"accountName",
")",
"{",
"return",
"listWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"accountName",
"... | List Live Events.
Lists the Live Events in the account.
@param resourceGroupName The name of the resource group within the Azure subscription.
@param accountName The Media Services account name.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<LiveEventInner> object | [
"List",
"Live",
"Events",
".",
"Lists",
"the",
"Live",
"Events",
"in",
"the",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/mediaservices/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2018_06_01_preview/implementation/LiveEventsInner.java#L181-L189 |
JRebirth/JRebirth | org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/basic/impl/StageServiceImpl.java | StageServiceImpl.getScene | private Scene getScene(final StageWaveBean swb, final Region region) {
"""
Gets the scene.
@param swb the waveBean holding defaut values
@param region the region
@return the scene
"""
Scene scene = swb.scene();
if (scene == null) {
scene = new Scene(region);
} else {
scene.setRoot(region);
}
return scene;
} | java | private Scene getScene(final StageWaveBean swb, final Region region) {
Scene scene = swb.scene();
if (scene == null) {
scene = new Scene(region);
} else {
scene.setRoot(region);
}
return scene;
} | [
"private",
"Scene",
"getScene",
"(",
"final",
"StageWaveBean",
"swb",
",",
"final",
"Region",
"region",
")",
"{",
"Scene",
"scene",
"=",
"swb",
".",
"scene",
"(",
")",
";",
"if",
"(",
"scene",
"==",
"null",
")",
"{",
"scene",
"=",
"new",
"Scene",
"("... | Gets the scene.
@param swb the waveBean holding defaut values
@param region the region
@return the scene | [
"Gets",
"the",
"scene",
"."
] | train | https://github.com/JRebirth/JRebirth/blob/93f4fc087b83c73db540333b9686e97b4cec694d/org.jrebirth.af/core/src/main/java/org/jrebirth/af/core/service/basic/impl/StageServiceImpl.java#L112-L122 |
b3dgs/lionengine | lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/Drawable.java | Drawable.loadSpriteAnimated | public static SpriteAnimated loadSpriteAnimated(Media media, int horizontalFrames, int verticalFrames) {
"""
Load an animated sprite from a file, giving horizontal and vertical frames.
<p>
Once created, sprite must call {@link SpriteAnimated#load()} before any other operations.
</p>
@param media The sprite media (must not be <code>null</code>).
@param horizontalFrames The number of horizontal frames (must be strictly positive).
@param verticalFrames The number of vertical frames (must be strictly positive).
@return The loaded animated sprite.
@throws LionEngineException If arguments are invalid or image cannot be read.
"""
return new SpriteAnimatedImpl(getMediaDpi(media), horizontalFrames, verticalFrames);
} | java | public static SpriteAnimated loadSpriteAnimated(Media media, int horizontalFrames, int verticalFrames)
{
return new SpriteAnimatedImpl(getMediaDpi(media), horizontalFrames, verticalFrames);
} | [
"public",
"static",
"SpriteAnimated",
"loadSpriteAnimated",
"(",
"Media",
"media",
",",
"int",
"horizontalFrames",
",",
"int",
"verticalFrames",
")",
"{",
"return",
"new",
"SpriteAnimatedImpl",
"(",
"getMediaDpi",
"(",
"media",
")",
",",
"horizontalFrames",
",",
"... | Load an animated sprite from a file, giving horizontal and vertical frames.
<p>
Once created, sprite must call {@link SpriteAnimated#load()} before any other operations.
</p>
@param media The sprite media (must not be <code>null</code>).
@param horizontalFrames The number of horizontal frames (must be strictly positive).
@param verticalFrames The number of vertical frames (must be strictly positive).
@return The loaded animated sprite.
@throws LionEngineException If arguments are invalid or image cannot be read. | [
"Load",
"an",
"animated",
"sprite",
"from",
"a",
"file",
"giving",
"horizontal",
"and",
"vertical",
"frames",
".",
"<p",
">",
"Once",
"created",
"sprite",
"must",
"call",
"{",
"@link",
"SpriteAnimated#load",
"()",
"}",
"before",
"any",
"other",
"operations",
... | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-core/src/main/java/com/b3dgs/lionengine/graphic/drawable/Drawable.java#L179-L182 |
googleads/googleads-java-lib | examples/admanager_axis/src/main/java/admanager/axis/v201808/audiencesegmentservice/GetFirstPartyAudienceSegments.java | GetFirstPartyAudienceSegments.runExample | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
"""
Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.
"""
AudienceSegmentServiceInterface audienceSegmentService =
adManagerServices.get(session, AudienceSegmentServiceInterface.class);
// Create a statement to select audience segments.
StatementBuilder statementBuilder = new StatementBuilder()
.where("type = :type")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("type", AudienceSegmentType.FIRST_PARTY.toString());
// Retrieve a small amount of audience segments at a time, paging through
// until all audience segments have been retrieved.
int totalResultSetSize = 0;
do {
AudienceSegmentPage page =
audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each audience segment.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (AudienceSegment audienceSegment : page.getResults()) {
System.out.printf(
"%d) Audience segment with ID %d, name '%s', and size %d was found.%n",
i++,
audienceSegment.getId(),
audienceSegment.getName(),
audienceSegment.getSize()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | java | public static void runExample(AdManagerServices adManagerServices, AdManagerSession session)
throws RemoteException {
AudienceSegmentServiceInterface audienceSegmentService =
adManagerServices.get(session, AudienceSegmentServiceInterface.class);
// Create a statement to select audience segments.
StatementBuilder statementBuilder = new StatementBuilder()
.where("type = :type")
.orderBy("id ASC")
.limit(StatementBuilder.SUGGESTED_PAGE_LIMIT)
.withBindVariableValue("type", AudienceSegmentType.FIRST_PARTY.toString());
// Retrieve a small amount of audience segments at a time, paging through
// until all audience segments have been retrieved.
int totalResultSetSize = 0;
do {
AudienceSegmentPage page =
audienceSegmentService.getAudienceSegmentsByStatement(statementBuilder.toStatement());
if (page.getResults() != null) {
// Print out some information for each audience segment.
totalResultSetSize = page.getTotalResultSetSize();
int i = page.getStartIndex();
for (AudienceSegment audienceSegment : page.getResults()) {
System.out.printf(
"%d) Audience segment with ID %d, name '%s', and size %d was found.%n",
i++,
audienceSegment.getId(),
audienceSegment.getName(),
audienceSegment.getSize()
);
}
}
statementBuilder.increaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
} while (statementBuilder.getOffset() < totalResultSetSize);
System.out.printf("Number of results found: %d%n", totalResultSetSize);
} | [
"public",
"static",
"void",
"runExample",
"(",
"AdManagerServices",
"adManagerServices",
",",
"AdManagerSession",
"session",
")",
"throws",
"RemoteException",
"{",
"AudienceSegmentServiceInterface",
"audienceSegmentService",
"=",
"adManagerServices",
".",
"get",
"(",
"sessi... | Runs the example.
@param adManagerServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors. | [
"Runs",
"the",
"example",
"."
] | train | https://github.com/googleads/googleads-java-lib/blob/967957cc4f6076514e3a7926fe653e4f1f7cc9c9/examples/admanager_axis/src/main/java/admanager/axis/v201808/audiencesegmentservice/GetFirstPartyAudienceSegments.java#L52-L90 |
javagl/ND | nd-arrays/src/main/java/de/javagl/nd/arrays/j/LongArraysND.java | LongArraysND.wrap | public static MutableLongArrayND wrap(
MutableLongTuple t, IntTuple size) {
"""
Creates a <i>view</i> on the given tuple as a {@link LongArrayND}.
Changes in the given tuple will be visible in the returned array,
and vice versa.
@param t The tuple
@param size The size of the array
@return The view on the tuple
@throws NullPointerException If any argument is <code>null</code>
@throws IllegalArgumentException If the
{@link LongTuple#getSize() size} of the tuple does not match the
given array size (that is, the product of all elements of the given
tuple).
"""
Objects.requireNonNull(t, "The tuple is null");
Objects.requireNonNull(size, "The size is null");
int totalSize = IntTupleFunctions.reduce(size, 1, (a, b) -> a * b);
if (t.getSize() != totalSize)
{
throw new IllegalArgumentException(
"The tuple has a size of " + t.getSize() + ", the expected " +
"array size is " + size + " (total: " + totalSize + ")");
}
return new MutableTupleLongArrayND(t, size);
} | java | public static MutableLongArrayND wrap(
MutableLongTuple t, IntTuple size)
{
Objects.requireNonNull(t, "The tuple is null");
Objects.requireNonNull(size, "The size is null");
int totalSize = IntTupleFunctions.reduce(size, 1, (a, b) -> a * b);
if (t.getSize() != totalSize)
{
throw new IllegalArgumentException(
"The tuple has a size of " + t.getSize() + ", the expected " +
"array size is " + size + " (total: " + totalSize + ")");
}
return new MutableTupleLongArrayND(t, size);
} | [
"public",
"static",
"MutableLongArrayND",
"wrap",
"(",
"MutableLongTuple",
"t",
",",
"IntTuple",
"size",
")",
"{",
"Objects",
".",
"requireNonNull",
"(",
"t",
",",
"\"The tuple is null\"",
")",
";",
"Objects",
".",
"requireNonNull",
"(",
"size",
",",
"\"The size... | Creates a <i>view</i> on the given tuple as a {@link LongArrayND}.
Changes in the given tuple will be visible in the returned array,
and vice versa.
@param t The tuple
@param size The size of the array
@return The view on the tuple
@throws NullPointerException If any argument is <code>null</code>
@throws IllegalArgumentException If the
{@link LongTuple#getSize() size} of the tuple does not match the
given array size (that is, the product of all elements of the given
tuple). | [
"Creates",
"a",
"<i",
">",
"view<",
"/",
"i",
">",
"on",
"the",
"given",
"tuple",
"as",
"a",
"{",
"@link",
"LongArrayND",
"}",
".",
"Changes",
"in",
"the",
"given",
"tuple",
"will",
"be",
"visible",
"in",
"the",
"returned",
"array",
"and",
"vice",
"v... | train | https://github.com/javagl/ND/blob/bcb655aaf5fc88af6194f73a27cca079186ff559/nd-arrays/src/main/java/de/javagl/nd/arrays/j/LongArraysND.java#L141-L154 |
Azure/azure-sdk-for-java | network/resource-manager/v2018_04_01/src/main/java/com/microsoft/azure/management/network/v2018_04_01/implementation/RouteFiltersInner.java | RouteFiltersInner.createOrUpdate | public RouteFilterInner createOrUpdate(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
"""
Creates or updates a route filter in a specified resource group.
@param resourceGroupName The name of the resource group.
@param routeFilterName The name of the route filter.
@param routeFilterParameters Parameters supplied to the create or update route filter operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RouteFilterInner object if successful.
"""
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().last().body();
} | java | public RouteFilterInner createOrUpdate(String resourceGroupName, String routeFilterName, RouteFilterInner routeFilterParameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, routeFilterName, routeFilterParameters).toBlocking().last().body();
} | [
"public",
"RouteFilterInner",
"createOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"routeFilterName",
",",
"RouteFilterInner",
"routeFilterParameters",
")",
"{",
"return",
"createOrUpdateWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"routeFilterName"... | Creates or updates a route filter in a specified resource group.
@param resourceGroupName The name of the resource group.
@param routeFilterName The name of the route filter.
@param routeFilterParameters Parameters supplied to the create or update route filter operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws CloudException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the RouteFilterInner object if successful. | [
"Creates",
"or",
"updates",
"a",
"route",
"filter",
"in",
"a",
"specified",
"resource",
"group",
"."
] | 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/RouteFiltersInner.java#L443-L445 |
nguillaumin/slick2d-maven | slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/navmesh/NavMesh.java | NavMesh.isClear | private boolean isClear(float x1, float y1, float x2, float y2, float step) {
"""
Check if a particular path is clear
@param x1 The x coordinate of the starting point
@param y1 The y coordinate of the starting point
@param x2 The x coordinate of the ending point
@param y2 The y coordinate of the ending point
@param step The size of the step between points
@return True if there are no blockages along the path
"""
float dx = (x2 - x1);
float dy = (y2 - y1);
float len = (float) Math.sqrt((dx*dx)+(dy*dy));
dx *= step;
dx /= len;
dy *= step;
dy /= len;
int steps = (int) (len / step);
for (int i=0;i<steps;i++) {
float x = x1 + (dx*i);
float y = y1 + (dy*i);
if (findSpace(x,y) == null) {
return false;
}
}
return true;
} | java | private boolean isClear(float x1, float y1, float x2, float y2, float step) {
float dx = (x2 - x1);
float dy = (y2 - y1);
float len = (float) Math.sqrt((dx*dx)+(dy*dy));
dx *= step;
dx /= len;
dy *= step;
dy /= len;
int steps = (int) (len / step);
for (int i=0;i<steps;i++) {
float x = x1 + (dx*i);
float y = y1 + (dy*i);
if (findSpace(x,y) == null) {
return false;
}
}
return true;
} | [
"private",
"boolean",
"isClear",
"(",
"float",
"x1",
",",
"float",
"y1",
",",
"float",
"x2",
",",
"float",
"y2",
",",
"float",
"step",
")",
"{",
"float",
"dx",
"=",
"(",
"x2",
"-",
"x1",
")",
";",
"float",
"dy",
"=",
"(",
"y2",
"-",
"y1",
")",
... | Check if a particular path is clear
@param x1 The x coordinate of the starting point
@param y1 The y coordinate of the starting point
@param x2 The x coordinate of the ending point
@param y2 The y coordinate of the ending point
@param step The size of the step between points
@return True if there are no blockages along the path | [
"Check",
"if",
"a",
"particular",
"path",
"is",
"clear"
] | train | https://github.com/nguillaumin/slick2d-maven/blob/8251f88a0ed6a70e726d2468842455cd1f80893f/slick2d-core/src/main/java/org/newdawn/slick/util/pathfinding/navmesh/NavMesh.java#L132-L152 |
sarl/sarl | main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/vim/VimGenerator2.java | VimGenerator2.appendComment | @SuppressWarnings("static-method")
protected IStyleAppendable appendComment(IStyleAppendable it, boolean addNewLine, String text) {
"""
Append a Vim comment.
@param it the receiver of the generated elements.
@param addNewLine indicates if a new line must be appended.
@param text the text of the comment.
@return {@code it}.
"""
it.append("\" "); //$NON-NLS-1$
it.append(text);
if (addNewLine) {
it.newLine();
}
return it;
} | java | @SuppressWarnings("static-method")
protected IStyleAppendable appendComment(IStyleAppendable it, boolean addNewLine, String text) {
it.append("\" "); //$NON-NLS-1$
it.append(text);
if (addNewLine) {
it.newLine();
}
return it;
} | [
"@",
"SuppressWarnings",
"(",
"\"static-method\"",
")",
"protected",
"IStyleAppendable",
"appendComment",
"(",
"IStyleAppendable",
"it",
",",
"boolean",
"addNewLine",
",",
"String",
"text",
")",
"{",
"it",
".",
"append",
"(",
"\"\\\" \"",
")",
";",
"//$NON-NLS-1$"... | Append a Vim comment.
@param it the receiver of the generated elements.
@param addNewLine indicates if a new line must be appended.
@param text the text of the comment.
@return {@code it}. | [
"Append",
"a",
"Vim",
"comment",
"."
] | train | https://github.com/sarl/sarl/blob/ca00ff994598c730339972def4e19a60e0b8cace/main/coreplugins/io.sarl.lang.mwe2/src/io/sarl/lang/mwe2/externalspec/vim/VimGenerator2.java#L523-L531 |
ben-manes/caffeine | simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/membership/bloom/BloomFilter.java | BloomFilter.setAt | @SuppressWarnings("PMD.LinguisticNaming")
boolean setAt(int item, int seedIndex) {
"""
Sets the membership flag for the computed bit location.
@param item the element's hash
@param seedIndex the hash seed index
@return if the membership changed as a result of this operation
"""
int hash = seeded(item, seedIndex);
int index = hash >>> tableShift;
long previous = table[index];
table[index] |= bitmask(hash);
return (table[index] != previous);
} | java | @SuppressWarnings("PMD.LinguisticNaming")
boolean setAt(int item, int seedIndex) {
int hash = seeded(item, seedIndex);
int index = hash >>> tableShift;
long previous = table[index];
table[index] |= bitmask(hash);
return (table[index] != previous);
} | [
"@",
"SuppressWarnings",
"(",
"\"PMD.LinguisticNaming\"",
")",
"boolean",
"setAt",
"(",
"int",
"item",
",",
"int",
"seedIndex",
")",
"{",
"int",
"hash",
"=",
"seeded",
"(",
"item",
",",
"seedIndex",
")",
";",
"int",
"index",
"=",
"hash",
">>>",
"tableShift... | Sets the membership flag for the computed bit location.
@param item the element's hash
@param seedIndex the hash seed index
@return if the membership changed as a result of this operation | [
"Sets",
"the",
"membership",
"flag",
"for",
"the",
"computed",
"bit",
"location",
"."
] | train | https://github.com/ben-manes/caffeine/blob/4cf6d6e6a18ea2e8088f166261e5949343b0f2eb/simulator/src/main/java/com/github/benmanes/caffeine/cache/simulator/membership/bloom/BloomFilter.java#L114-L121 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.