repository_name stringlengths 7 54 | func_path_in_repository stringlengths 18 196 | func_name stringlengths 7 107 | whole_func_string stringlengths 76 3.82k | language stringclasses 1
value | func_code_string stringlengths 76 3.82k | func_code_tokens listlengths 22 717 | func_documentation_string stringlengths 61 1.98k | func_documentation_tokens listlengths 1 508 | split_name stringclasses 1
value | func_code_url stringlengths 111 310 |
|---|---|---|---|---|---|---|---|---|---|---|
toddfast/typeconverter | src/main/java/com/toddfast/util/convert/TypeConverter.java | TypeConverter.asBoolean | public static boolean asBoolean(Object value, boolean nullValue) {
value=convert(Boolean.class,value);
return (value!=null)
? ((Boolean)value).booleanValue()
: nullValue;
} | java | public static boolean asBoolean(Object value, boolean nullValue) {
value=convert(Boolean.class,value);
return (value!=null)
? ((Boolean)value).booleanValue()
: nullValue;
} | [
"public",
"static",
"boolean",
"asBoolean",
"(",
"Object",
"value",
",",
"boolean",
"nullValue",
")",
"{",
"value",
"=",
"convert",
"(",
"Boolean",
".",
"class",
",",
"value",
")",
";",
"return",
"(",
"value",
"!=",
"null",
")",
"?",
"(",
"(",
"Boolean... | Return the value converted to a boolean
or the specified alternate value if the original value is null. Note,
this method still throws {@link IllegalArgumentException} if the value
is not null and could not be converted.
@param value
The value to be converted
@param nullValue
The value to be returned if {@link value} is null. Note, this
value will not be returned if the conversion fails otherwise.
@throws IllegalArgumentException
If the value cannot be converted | [
"Return",
"the",
"value",
"converted",
"to",
"a",
"boolean",
"or",
"the",
"specified",
"alternate",
"value",
"if",
"the",
"original",
"value",
"is",
"null",
".",
"Note",
"this",
"method",
"still",
"throws",
"{",
"@link",
"IllegalArgumentException",
"}",
"if",
... | train | https://github.com/toddfast/typeconverter/blob/44efa352254faa49edaba5c5935389705aa12b90/src/main/java/com/toddfast/util/convert/TypeConverter.java#L701-L706 |
azkaban/azkaban | az-core/src/main/java/azkaban/utils/Utils.java | Utils.runProcess | public static ArrayList<String> runProcess(String... commands)
throws InterruptedException, IOException {
final java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder(commands);
final ArrayList<String> output = new ArrayList<>();
final Process process = processBuilder.start();
process.waitFor();
final InputStream inputStream = process.getInputStream();
try {
final java.io.BufferedReader reader = new java.io.BufferedReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
output.add(line);
}
} finally {
inputStream.close();
}
return output;
} | java | public static ArrayList<String> runProcess(String... commands)
throws InterruptedException, IOException {
final java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder(commands);
final ArrayList<String> output = new ArrayList<>();
final Process process = processBuilder.start();
process.waitFor();
final InputStream inputStream = process.getInputStream();
try {
final java.io.BufferedReader reader = new java.io.BufferedReader(
new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = reader.readLine()) != null) {
output.add(line);
}
} finally {
inputStream.close();
}
return output;
} | [
"public",
"static",
"ArrayList",
"<",
"String",
">",
"runProcess",
"(",
"String",
"...",
"commands",
")",
"throws",
"InterruptedException",
",",
"IOException",
"{",
"final",
"java",
".",
"lang",
".",
"ProcessBuilder",
"processBuilder",
"=",
"new",
"java",
".",
... | Run a sequence of commands
@param commands sequence of commands
@return list of output result | [
"Run",
"a",
"sequence",
"of",
"commands"
] | train | https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/az-core/src/main/java/azkaban/utils/Utils.java#L422-L440 |
sitoolkit/sit-wt-all | sit-wt-runtime/src/main/java/io/sitoolkit/wt/app/compareevidence/ScreenshotComparator.java | ScreenshotComparator.compareOneScreenshot | public boolean compareOneScreenshot(File baseImg, File targetImg, int rows, int columns) {
boolean match = true;
BufferedImage[][] baseBfImg = splitImage(baseImg, rows, columns);
BufferedImage[][] targetBfImg = splitImage(targetImg, rows, columns);
BufferedImage[][] diffImg = new BufferedImage[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
byte[] baseImgBytes = toByteArray(baseBfImg[i][j]);
byte[] targetImgBytes = toByteArray(targetBfImg[i][j]);
if (Arrays.equals(baseImgBytes, targetImgBytes)) {
diffImg[i][j] = darken(targetBfImg[i][j]);
} else {
match = false;
diffImg[i][j] = targetBfImg[i][j];
}
}
}
if (match) {
LOG.info("screenshot.match", targetImg.getName());
} else {
LOG.error("screenshot.unmatch", targetImg.getName());
writeDiffImg(targetImg, diffImg);
}
return match;
} | java | public boolean compareOneScreenshot(File baseImg, File targetImg, int rows, int columns) {
boolean match = true;
BufferedImage[][] baseBfImg = splitImage(baseImg, rows, columns);
BufferedImage[][] targetBfImg = splitImage(targetImg, rows, columns);
BufferedImage[][] diffImg = new BufferedImage[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
byte[] baseImgBytes = toByteArray(baseBfImg[i][j]);
byte[] targetImgBytes = toByteArray(targetBfImg[i][j]);
if (Arrays.equals(baseImgBytes, targetImgBytes)) {
diffImg[i][j] = darken(targetBfImg[i][j]);
} else {
match = false;
diffImg[i][j] = targetBfImg[i][j];
}
}
}
if (match) {
LOG.info("screenshot.match", targetImg.getName());
} else {
LOG.error("screenshot.unmatch", targetImg.getName());
writeDiffImg(targetImg, diffImg);
}
return match;
} | [
"public",
"boolean",
"compareOneScreenshot",
"(",
"File",
"baseImg",
",",
"File",
"targetImg",
",",
"int",
"rows",
",",
"int",
"columns",
")",
"{",
"boolean",
"match",
"=",
"true",
";",
"BufferedImage",
"[",
"]",
"[",
"]",
"baseBfImg",
"=",
"splitImage",
"... | スクリーンショットが一致する場合にtrueを返します。 一致しない場合には差分スクリーンショットを生成します。
@param baseImg
基準スクリーンショット
@param targetImg
比較対象スクリーンショット
@param rows
分割行数
@param columns
分割列数
@return スクリーンショットが一致する場合にtrue | [
"スクリーンショットが一致する場合にtrueを返します。",
"一致しない場合には差分スクリーンショットを生成します。"
] | train | https://github.com/sitoolkit/sit-wt-all/blob/efabde27aa731a5602d2041e137721a22f4fd27a/sit-wt-runtime/src/main/java/io/sitoolkit/wt/app/compareevidence/ScreenshotComparator.java#L99-L129 |
selendroid/selendroid | selendroid-common/src/main/java/io/selendroid/common/SelendroidCapabilities.java | SelendroidCapabilities.getDefaultApp | public String getDefaultApp(Set<String> supportedApps) {
String defaultApp = getAut();
// if the launch activity is specified, just return.
if (getLaunchActivity() != null) {
return defaultApp;
}
// App version is not specified. Get the latest version from the apps store.
if (!defaultApp.contains(":")) {
return getDefaultVersion(supportedApps, defaultApp);
}
return supportedApps.contains(defaultApp) ? defaultApp : null;
} | java | public String getDefaultApp(Set<String> supportedApps) {
String defaultApp = getAut();
// if the launch activity is specified, just return.
if (getLaunchActivity() != null) {
return defaultApp;
}
// App version is not specified. Get the latest version from the apps store.
if (!defaultApp.contains(":")) {
return getDefaultVersion(supportedApps, defaultApp);
}
return supportedApps.contains(defaultApp) ? defaultApp : null;
} | [
"public",
"String",
"getDefaultApp",
"(",
"Set",
"<",
"String",
">",
"supportedApps",
")",
"{",
"String",
"defaultApp",
"=",
"getAut",
"(",
")",
";",
"// if the launch activity is specified, just return.",
"if",
"(",
"getLaunchActivity",
"(",
")",
"!=",
"null",
")... | Returns the application under test in the format of "appName:appVersion", or "appName" if the supported application
does not have any version associated with it, or returns null if the requested app is not in the apps store. If the
launch activity is also specified with requested application then just return the requested application as app under
test so it can be later installed to the device by SelendroidStandaloneDriver.
@param supportedApps The list of supported apps in the apps store.
@return The application under test in "appName" or "appName:appVersion" format, or null if the application is not
in the list of supported apps and the launch activity is not specified. | [
"Returns",
"the",
"application",
"under",
"test",
"in",
"the",
"format",
"of",
"appName",
":",
"appVersion",
"or",
"appName",
"if",
"the",
"supported",
"application",
"does",
"not",
"have",
"any",
"version",
"associated",
"with",
"it",
"or",
"returns",
"null",... | train | https://github.com/selendroid/selendroid/blob/a32c1a96c973b80c14a588b1075f084201f7fe94/selendroid-common/src/main/java/io/selendroid/common/SelendroidCapabilities.java#L460-L471 |
logic-ng/LogicNG | src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java | Encoder.updatePB | public void updatePB(final MiniSatStyleSolver s, int rhs) {
switch (this.pbEncoding) {
case SWC:
this.swc.update(s, rhs);
break;
default:
throw new IllegalStateException("Unknown pseudo-Boolean encoding: " + this.pbEncoding);
}
} | java | public void updatePB(final MiniSatStyleSolver s, int rhs) {
switch (this.pbEncoding) {
case SWC:
this.swc.update(s, rhs);
break;
default:
throw new IllegalStateException("Unknown pseudo-Boolean encoding: " + this.pbEncoding);
}
} | [
"public",
"void",
"updatePB",
"(",
"final",
"MiniSatStyleSolver",
"s",
",",
"int",
"rhs",
")",
"{",
"switch",
"(",
"this",
".",
"pbEncoding",
")",
"{",
"case",
"SWC",
":",
"this",
".",
"swc",
".",
"update",
"(",
"s",
",",
"rhs",
")",
";",
"break",
... | Updates a pseudo-Boolean encoding.
@param s the solver
@param rhs the new right hand side
@throws IllegalStateException if the pseudo-Boolean encoding is unknown | [
"Updates",
"a",
"pseudo",
"-",
"Boolean",
"encoding",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/solvers/maxsat/encodings/Encoder.java#L268-L276 |
sksamuel/scrimage | scrimage-core/src/main/java/com/sksamuel/scrimage/PixelTools.java | PixelTools.approx | public static boolean approx(Color color, int tolerance, Pixel[] pixels) {
RGBColor refColor = color.toRGB();
RGBColor minColor = new RGBColor(
Math.max(refColor.red() - tolerance, 0),
Math.max(refColor.green() - tolerance, 0),
Math.max(refColor.blue() - tolerance, 0),
refColor.alpha()
);
RGBColor maxColor = new RGBColor(
Math.min(refColor.red() + tolerance, 255),
Math.min(refColor.green() + tolerance, 255),
Math.min(refColor.blue() + tolerance, 255),
refColor.alpha()
);
return Arrays.stream(pixels).allMatch(p -> p.toInt() >= minColor.toInt() && p.toInt() <= maxColor.toInt());
} | java | public static boolean approx(Color color, int tolerance, Pixel[] pixels) {
RGBColor refColor = color.toRGB();
RGBColor minColor = new RGBColor(
Math.max(refColor.red() - tolerance, 0),
Math.max(refColor.green() - tolerance, 0),
Math.max(refColor.blue() - tolerance, 0),
refColor.alpha()
);
RGBColor maxColor = new RGBColor(
Math.min(refColor.red() + tolerance, 255),
Math.min(refColor.green() + tolerance, 255),
Math.min(refColor.blue() + tolerance, 255),
refColor.alpha()
);
return Arrays.stream(pixels).allMatch(p -> p.toInt() >= minColor.toInt() && p.toInt() <= maxColor.toInt());
} | [
"public",
"static",
"boolean",
"approx",
"(",
"Color",
"color",
",",
"int",
"tolerance",
",",
"Pixel",
"[",
"]",
"pixels",
")",
"{",
"RGBColor",
"refColor",
"=",
"color",
".",
"toRGB",
"(",
")",
";",
"RGBColor",
"minColor",
"=",
"new",
"RGBColor",
"(",
... | Returns true if the colors of all pixels in the array are within the given tolerance
compared to the referenced color | [
"Returns",
"true",
"if",
"the",
"colors",
"of",
"all",
"pixels",
"in",
"the",
"array",
"are",
"within",
"the",
"given",
"tolerance",
"compared",
"to",
"the",
"referenced",
"color"
] | train | https://github.com/sksamuel/scrimage/blob/52dab448136e6657a71951b0e6b7d5e64dc979ac/scrimage-core/src/main/java/com/sksamuel/scrimage/PixelTools.java#L93-L112 |
wcm-io/wcm-io-wcm | commons/src/main/java/io/wcm/wcm/commons/util/Template.java | Template.is | public static boolean is(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
if (page == null || templates == null || templates.length == 0) {
return false;
}
String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
for (TemplatePathInfo template : templates) {
if (template.getTemplatePath().equals(templatePath)) {
return true;
}
}
return false;
} | java | public static boolean is(@NotNull Page page, @NotNull TemplatePathInfo @NotNull... templates) {
if (page == null || templates == null || templates.length == 0) {
return false;
}
String templatePath = page.getProperties().get(NameConstants.PN_TEMPLATE, String.class);
for (TemplatePathInfo template : templates) {
if (template.getTemplatePath().equals(templatePath)) {
return true;
}
}
return false;
} | [
"public",
"static",
"boolean",
"is",
"(",
"@",
"NotNull",
"Page",
"page",
",",
"@",
"NotNull",
"TemplatePathInfo",
"@",
"NotNull",
".",
".",
".",
"templates",
")",
"{",
"if",
"(",
"page",
"==",
"null",
"||",
"templates",
"==",
"null",
"||",
"templates",
... | Checks if the given page uses a specific template.
@param page AEM page
@param templates Template(s)
@return true if the page uses the template | [
"Checks",
"if",
"the",
"given",
"page",
"uses",
"a",
"specific",
"template",
"."
] | train | https://github.com/wcm-io/wcm-io-wcm/blob/8eff9434f2f4b6462fdb718f8769ad793c55b8d7/commons/src/main/java/io/wcm/wcm/commons/util/Template.java#L79-L90 |
landawn/AbacusUtil | src/com/landawn/abacus/util/Primitives.java | Primitives.unbox | public static char[] unbox(final Character[] a, final char valueForNull) {
if (a == null) {
return null;
}
return unbox(a, 0, a.length, valueForNull);
} | java | public static char[] unbox(final Character[] a, final char valueForNull) {
if (a == null) {
return null;
}
return unbox(a, 0, a.length, valueForNull);
} | [
"public",
"static",
"char",
"[",
"]",
"unbox",
"(",
"final",
"Character",
"[",
"]",
"a",
",",
"final",
"char",
"valueForNull",
")",
"{",
"if",
"(",
"a",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"return",
"unbox",
"(",
"a",
",",
"0",
",... | <p>
Converts an array of object Character to primitives handling {@code null}
.
</p>
<p>
This method returns {@code null} for a {@code null} input array.
</p>
@param a
a {@code Character} array, may be {@code null}
@param valueForNull
the value to insert if {@code null} found
@return a {@code char} array, {@code null} if null array input | [
"<p",
">",
"Converts",
"an",
"array",
"of",
"object",
"Character",
"to",
"primitives",
"handling",
"{",
"@code",
"null",
"}",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/landawn/AbacusUtil/blob/544b7720175d15e9329f83dd22a8cc5fa4515e12/src/com/landawn/abacus/util/Primitives.java#L842-L848 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/AbstractCommand.java | AbstractCommand.createButton | public final AbstractButton createButton(String faceDescriptorId, ButtonFactory buttonFactory) {
return createButton(faceDescriptorId, buttonFactory, getDefaultButtonConfigurer());
} | java | public final AbstractButton createButton(String faceDescriptorId, ButtonFactory buttonFactory) {
return createButton(faceDescriptorId, buttonFactory, getDefaultButtonConfigurer());
} | [
"public",
"final",
"AbstractButton",
"createButton",
"(",
"String",
"faceDescriptorId",
",",
"ButtonFactory",
"buttonFactory",
")",
"{",
"return",
"createButton",
"(",
"faceDescriptorId",
",",
"buttonFactory",
",",
"getDefaultButtonConfigurer",
"(",
")",
")",
";",
"}"... | Create a button using the default buttonConfigurer.
@see #createButton(String, ButtonFactory, CommandButtonConfigurer) | [
"Create",
"a",
"button",
"using",
"the",
"default",
"buttonConfigurer",
"."
] | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/command/support/AbstractCommand.java#L757-L759 |
classgraph/classgraph | src/main/java/nonapi/io/github/classgraph/utils/ReflectionUtils.java | ReflectionUtils.invokeStaticMethod | public static Object invokeStaticMethod(final Class<?> cls, final String methodName, final Class<?> argType,
final Object param, final boolean throwException) throws IllegalArgumentException {
if (cls == null || methodName == null) {
if (throwException) {
throw new NullPointerException();
} else {
return null;
}
}
return invokeMethod(cls, null, methodName, true, argType, param, throwException);
} | java | public static Object invokeStaticMethod(final Class<?> cls, final String methodName, final Class<?> argType,
final Object param, final boolean throwException) throws IllegalArgumentException {
if (cls == null || methodName == null) {
if (throwException) {
throw new NullPointerException();
} else {
return null;
}
}
return invokeMethod(cls, null, methodName, true, argType, param, throwException);
} | [
"public",
"static",
"Object",
"invokeStaticMethod",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"String",
"methodName",
",",
"final",
"Class",
"<",
"?",
">",
"argType",
",",
"final",
"Object",
"param",
",",
"final",
"boolean",
"throwException"... | Invoke the named static method. If an exception is thrown while trying to call the method, and throwException
is true, then IllegalArgumentException is thrown wrapping the cause, otherwise this will return null. If
passed a null class reference, returns null unless throwException is true, then throws
IllegalArgumentException.
@param cls
The class.
@param methodName
The method name.
@param argType
The type of the method argument.
@param param
The parameter value to use when invoking the method.
@param throwException
Whether to throw an exception on failure.
@return The result of the method invocation.
@throws IllegalArgumentException
If the method could not be invoked. | [
"Invoke",
"the",
"named",
"static",
"method",
".",
"If",
"an",
"exception",
"is",
"thrown",
"while",
"trying",
"to",
"call",
"the",
"method",
"and",
"throwException",
"is",
"true",
"then",
"IllegalArgumentException",
"is",
"thrown",
"wrapping",
"the",
"cause",
... | train | https://github.com/classgraph/classgraph/blob/c8c8b2ca1eb76339f69193fdac33d735c864215c/src/main/java/nonapi/io/github/classgraph/utils/ReflectionUtils.java#L384-L394 |
ManfredTremmel/gwt-commons-lang3 | src/main/java/org/apache/commons/lang3/ClassUtils.java | ClassUtils.getName | public static String getName(final Class<?> cls, final String valueIfNull) {
return cls == null ? valueIfNull : cls.getName();
} | java | public static String getName(final Class<?> cls, final String valueIfNull) {
return cls == null ? valueIfNull : cls.getName();
} | [
"public",
"static",
"String",
"getName",
"(",
"final",
"Class",
"<",
"?",
">",
"cls",
",",
"final",
"String",
"valueIfNull",
")",
"{",
"return",
"cls",
"==",
"null",
"?",
"valueIfNull",
":",
"cls",
".",
"getName",
"(",
")",
";",
"}"
] | <p>Null-safe version of <code>aClass.getName()</code></p>
@param cls the class for which to get the class name; may be null
@param valueIfNull the return value if <code>cls</code> is <code>null</code>
@return the class name or {@code valueIfNull}
@since 3.7
@see Class#getName() | [
"<p",
">",
"Null",
"-",
"safe",
"version",
"of",
"<code",
">",
"aClass",
".",
"getName",
"()",
"<",
"/",
"code",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/ManfredTremmel/gwt-commons-lang3/blob/9e2dfbbda3668cfa5d935fe76479d1426c294504/src/main/java/org/apache/commons/lang3/ClassUtils.java#L316-L318 |
liyiorg/weixin-popular | src/main/java/weixin/popular/util/JsUtil.java | JsUtil.generateConfigSignature | public static String generateConfigSignature(String noncestr,String jsapi_ticket,String timestamp,String url){
Map<String, String> map = new HashMap<String, String>();
map.put("noncestr", noncestr);
map.put("jsapi_ticket", jsapi_ticket);
map.put("timestamp", timestamp);
map.put("url", url);
Map<String, String> tmap = MapUtil.order(map);
String str = MapUtil.mapJoin(tmap,true,false);
return DigestUtils.shaHex(str);
} | java | public static String generateConfigSignature(String noncestr,String jsapi_ticket,String timestamp,String url){
Map<String, String> map = new HashMap<String, String>();
map.put("noncestr", noncestr);
map.put("jsapi_ticket", jsapi_ticket);
map.put("timestamp", timestamp);
map.put("url", url);
Map<String, String> tmap = MapUtil.order(map);
String str = MapUtil.mapJoin(tmap,true,false);
return DigestUtils.shaHex(str);
} | [
"public",
"static",
"String",
"generateConfigSignature",
"(",
"String",
"noncestr",
",",
"String",
"jsapi_ticket",
",",
"String",
"timestamp",
",",
"String",
"url",
")",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"map",
"=",
"new",
"HashMap",
"<",
"Strin... | 生成 config接口 signature
@param noncestr noncestr
@param jsapi_ticket jsapi_ticket
@param timestamp timestamp
@param url url
@return sign | [
"生成",
"config接口",
"signature"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/util/JsUtil.java#L80-L90 |
spring-cloud/spring-cloud-netflix | spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java | RibbonUtils.updateToSecureConnectionIfNeeded | static URI updateToSecureConnectionIfNeeded(URI uri, ServiceInstance ribbonServer) {
String scheme = uri.getScheme();
if (StringUtils.isEmpty(scheme)) {
scheme = "http";
}
if (!StringUtils.isEmpty(uri.toString())
&& unsecureSchemeMapping.containsKey(scheme) && ribbonServer.isSecure()) {
return upgradeConnection(uri, unsecureSchemeMapping.get(scheme));
}
return uri;
} | java | static URI updateToSecureConnectionIfNeeded(URI uri, ServiceInstance ribbonServer) {
String scheme = uri.getScheme();
if (StringUtils.isEmpty(scheme)) {
scheme = "http";
}
if (!StringUtils.isEmpty(uri.toString())
&& unsecureSchemeMapping.containsKey(scheme) && ribbonServer.isSecure()) {
return upgradeConnection(uri, unsecureSchemeMapping.get(scheme));
}
return uri;
} | [
"static",
"URI",
"updateToSecureConnectionIfNeeded",
"(",
"URI",
"uri",
",",
"ServiceInstance",
"ribbonServer",
")",
"{",
"String",
"scheme",
"=",
"uri",
".",
"getScheme",
"(",
")",
";",
"if",
"(",
"StringUtils",
".",
"isEmpty",
"(",
"scheme",
")",
")",
"{",... | Replace the scheme to the secure variant if needed. If the
{@link #unsecureSchemeMapping} map contains the uri scheme and
{@link #isSecure(IClientConfig, ServerIntrospector, Server)} is true, update the
scheme. This assumes the uri is already encoded to avoid double encoding.
@param uri to modify if required
@param ribbonServer to verify if it provides secure connections
@return {@link URI} updated if required | [
"Replace",
"the",
"scheme",
"to",
"the",
"secure",
"variant",
"if",
"needed",
".",
"If",
"the",
"{"
] | train | https://github.com/spring-cloud/spring-cloud-netflix/blob/03b1e326ce5971c41239890dc71cae616366cff8/spring-cloud-netflix-ribbon/src/main/java/org/springframework/cloud/netflix/ribbon/RibbonUtils.java#L134-L146 |
iipc/webarchive-commons | src/main/java/org/archive/util/Recorder.java | Recorder.getContentReplayPrefixString | public String getContentReplayPrefixString(int size, Charset cs) {
try {
InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs);
char[] chars = new char[size];
int count = isr.read(chars);
isr.close();
if (count > 0) {
return new String(chars,0,count);
} else {
return "";
}
} catch (IOException e) {
logger.log(Level.SEVERE,"unable to get replay prefix string", e);
return "";
}
} | java | public String getContentReplayPrefixString(int size, Charset cs) {
try {
InputStreamReader isr = new InputStreamReader(getContentReplayInputStream(), cs);
char[] chars = new char[size];
int count = isr.read(chars);
isr.close();
if (count > 0) {
return new String(chars,0,count);
} else {
return "";
}
} catch (IOException e) {
logger.log(Level.SEVERE,"unable to get replay prefix string", e);
return "";
}
} | [
"public",
"String",
"getContentReplayPrefixString",
"(",
"int",
"size",
",",
"Charset",
"cs",
")",
"{",
"try",
"{",
"InputStreamReader",
"isr",
"=",
"new",
"InputStreamReader",
"(",
"getContentReplayInputStream",
"(",
")",
",",
"cs",
")",
";",
"char",
"[",
"]"... | Return a short prefix of the presumed-textual content as a String.
@param size max length of String to return
@return String prefix, or empty String (with logged exception) on any error | [
"Return",
"a",
"short",
"prefix",
"of",
"the",
"presumed",
"-",
"textual",
"content",
"as",
"a",
"String",
"."
] | train | https://github.com/iipc/webarchive-commons/blob/988bec707c27a01333becfc3bd502af4441ea1e1/src/main/java/org/archive/util/Recorder.java#L509-L524 |
httl/httl | httl/src/main/java/httl/spi/engines/DefaultEngine.java | DefaultEngine.parseTemplate | public Template parseTemplate(String source, Object parameterTypes) throws ParseException {
String name = "/$" + Digest.getMD5(source);
if (!hasResource(name)) {
stringLoader.add(name, source);
}
try {
return getTemplate(name, parameterTypes);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
} | java | public Template parseTemplate(String source, Object parameterTypes) throws ParseException {
String name = "/$" + Digest.getMD5(source);
if (!hasResource(name)) {
stringLoader.add(name, source);
}
try {
return getTemplate(name, parameterTypes);
} catch (IOException e) {
throw new IllegalStateException(e.getMessage(), e);
}
} | [
"public",
"Template",
"parseTemplate",
"(",
"String",
"source",
",",
"Object",
"parameterTypes",
")",
"throws",
"ParseException",
"{",
"String",
"name",
"=",
"\"/$\"",
"+",
"Digest",
".",
"getMD5",
"(",
"source",
")",
";",
"if",
"(",
"!",
"hasResource",
"(",... | Parse string template.
@param source - template source
@return template instance
@throws IOException - If an I/O error occurs
@throws ParseException - If the template cannot be parsed
@see #getEngine() | [
"Parse",
"string",
"template",
"."
] | train | https://github.com/httl/httl/blob/e13e00f4ab41252a8f53d6dafd4a6610be9dcaad/httl/src/main/java/httl/spi/engines/DefaultEngine.java#L278-L288 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BusinessExceptionMappingStrategy.java | BusinessExceptionMappingStrategy.mapCSITransactionRolledBackException | @Override
public Exception mapCSITransactionRolledBackException
(EJSDeployedSupport s, CSITransactionRolledbackException ex)
throws com.ibm.websphere.csi.CSIException
{
Throwable cause = null;
Exception causeEx = null;
// If the invoked method threw a System exception, or an Application
// exception that was marked for rollback, or the application called
// setRollBackOnly... then use the exception thrown by the method
// as the cause of the rollback exception.
if (s.exType == ExceptionType.UNCHECKED_EXCEPTION)
{
cause = s.ivException;
}
// Otherwise, use the cause of the CSIException as the cause,
// unless it has no cause... then use the app exception.
else
{
cause = ExceptionUtil.findCause(ex);
if (cause == null)
cause = s.ivException;
}
// Because this will be mapped to an EJBException, and Throwable
// is not supported on the constructor... insure the cause is
// either an Exception, or wrap it in an Exception.
if (cause != null)
{
if (cause instanceof Exception)
{
causeEx = (Exception) cause;
}
else
{
causeEx = new Exception("See nested Throwable", cause);
}
}
// Now, map this CSIException... this will take care of getting
// the stack set appropriately and will set the 'cause' on
// Throwable, so getCause works.
Exception mappedEx = mapCSIException(ex, causeEx, cause);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "mapped exception = " + mappedEx);
return mappedEx;
} | java | @Override
public Exception mapCSITransactionRolledBackException
(EJSDeployedSupport s, CSITransactionRolledbackException ex)
throws com.ibm.websphere.csi.CSIException
{
Throwable cause = null;
Exception causeEx = null;
// If the invoked method threw a System exception, or an Application
// exception that was marked for rollback, or the application called
// setRollBackOnly... then use the exception thrown by the method
// as the cause of the rollback exception.
if (s.exType == ExceptionType.UNCHECKED_EXCEPTION)
{
cause = s.ivException;
}
// Otherwise, use the cause of the CSIException as the cause,
// unless it has no cause... then use the app exception.
else
{
cause = ExceptionUtil.findCause(ex);
if (cause == null)
cause = s.ivException;
}
// Because this will be mapped to an EJBException, and Throwable
// is not supported on the constructor... insure the cause is
// either an Exception, or wrap it in an Exception.
if (cause != null)
{
if (cause instanceof Exception)
{
causeEx = (Exception) cause;
}
else
{
causeEx = new Exception("See nested Throwable", cause);
}
}
// Now, map this CSIException... this will take care of getting
// the stack set appropriately and will set the 'cause' on
// Throwable, so getCause works.
Exception mappedEx = mapCSIException(ex, causeEx, cause);
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
Tr.debug(tc, "mapped exception = " + mappedEx);
return mappedEx;
} | [
"@",
"Override",
"public",
"Exception",
"mapCSITransactionRolledBackException",
"(",
"EJSDeployedSupport",
"s",
",",
"CSITransactionRolledbackException",
"ex",
")",
"throws",
"com",
".",
"ibm",
".",
"websphere",
".",
"csi",
".",
"CSIException",
"{",
"Throwable",
"caus... | This method is specifically designed for use during EJSContainer
postInvoke processing. It maps the internal exception indicating
a rollback has occurred to the appropriate one for the interface
(i.e. local, remote, business, etc). <p> | [
"This",
"method",
"is",
"specifically",
"designed",
"for",
"use",
"during",
"EJSContainer",
"postInvoke",
"processing",
".",
"It",
"maps",
"the",
"internal",
"exception",
"indicating",
"a",
"rollback",
"has",
"occurred",
"to",
"the",
"appropriate",
"one",
"for",
... | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/ejs/container/BusinessExceptionMappingStrategy.java#L539-L589 |
moparisthebest/beehive | beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java | FlowControllerFactory.getSharedFlowsForRequest | public Map/*< String, SharedFlowController >*/ getSharedFlowsForRequest( RequestContext context )
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
String path = InternalUtils.getDecodedServletPath( context.getHttpRequest() );
return getSharedFlowsForPath( context, path );
} | java | public Map/*< String, SharedFlowController >*/ getSharedFlowsForRequest( RequestContext context )
throws ClassNotFoundException, InstantiationException, IllegalAccessException
{
String path = InternalUtils.getDecodedServletPath( context.getHttpRequest() );
return getSharedFlowsForPath( context, path );
} | [
"public",
"Map",
"/*< String, SharedFlowController >*/",
"getSharedFlowsForRequest",
"(",
"RequestContext",
"context",
")",
"throws",
"ClassNotFoundException",
",",
"InstantiationException",
",",
"IllegalAccessException",
"{",
"String",
"path",
"=",
"InternalUtils",
".",
"get... | Get the map of shared flows for the given request. The map is derived from the shared flows
that are declared (through the <code>sharedFlowRefs</code> attribute of
{@link org.apache.beehive.netui.pageflow.annotations.Jpf.Controller @Jpf.Controller}) in the
page flow for the request.
@param context a {@link RequestContext} object which contains the current request and response.
@return a Map of shared-flow-name (String) to {@link SharedFlowController}.
@throws ClassNotFoundException if a declared shared flow class could not be found.
@throws InstantiationException if a declared shared flow class could not be instantiated.
@throws IllegalAccessException if a declared shared flow class was not accessible. | [
"Get",
"the",
"map",
"of",
"shared",
"flows",
"for",
"the",
"given",
"request",
".",
"The",
"map",
"is",
"derived",
"from",
"the",
"shared",
"flows",
"that",
"are",
"declared",
"(",
"through",
"the",
"<code",
">",
"sharedFlowRefs<",
"/",
"code",
">",
"at... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-core/src/main/java/org/apache/beehive/netui/pageflow/FlowControllerFactory.java#L452-L457 |
ops4j/org.ops4j.pax.wicket | service/src/main/java/org/ops4j/pax/wicket/internal/filter/FilterDelegator.java | FilterDelegator.doFilter | public void doFilter(Filter[] superFilter, ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
List<Filter> filters = new ArrayList<Filter>();
if (superFilter != null && superFilter.length > 0) {
// First add all superfilter...
filters.addAll(Arrays.asList(superFilter));
}
List<Filter> filterList = getFiltersSortedWithHighestPriorityAsFirstFilter(filters, servlet.getServletConfig());
FilterChain chain = new PAXWicketFilterChain(filterList, servlet);
chain.doFilter(servletRequest, servletResponse);
} | java | public void doFilter(Filter[] superFilter, ServletRequest servletRequest, ServletResponse servletResponse)
throws ServletException, IOException {
List<Filter> filters = new ArrayList<Filter>();
if (superFilter != null && superFilter.length > 0) {
// First add all superfilter...
filters.addAll(Arrays.asList(superFilter));
}
List<Filter> filterList = getFiltersSortedWithHighestPriorityAsFirstFilter(filters, servlet.getServletConfig());
FilterChain chain = new PAXWicketFilterChain(filterList, servlet);
chain.doFilter(servletRequest, servletResponse);
} | [
"public",
"void",
"doFilter",
"(",
"Filter",
"[",
"]",
"superFilter",
",",
"ServletRequest",
"servletRequest",
",",
"ServletResponse",
"servletResponse",
")",
"throws",
"ServletException",
",",
"IOException",
"{",
"List",
"<",
"Filter",
">",
"filters",
"=",
"new",... | <p>doFilter.</p>
@param superFilter an array of {@link javax.servlet.Filter} objects.
@param servletRequest a {@link javax.servlet.ServletRequest} object.
@param servletResponse a {@link javax.servlet.ServletResponse} object.
@throws javax.servlet.ServletException if any.
@throws java.io.IOException if any. | [
"<p",
">",
"doFilter",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/ops4j/org.ops4j.pax.wicket/blob/ef7cb4bdf918e9e61ec69789b9c690567616faa9/service/src/main/java/org/ops4j/pax/wicket/internal/filter/FilterDelegator.java#L96-L106 |
Nexmo/nexmo-java | src/main/java/com/nexmo/client/numbers/NumbersClient.java | NumbersClient.linkNumber | public void linkNumber(String msisdn, String country, String appId) throws IOException, NexmoClientException {
UpdateNumberRequest request = new UpdateNumberRequest(msisdn, country);
request.setVoiceCallbackType(UpdateNumberRequest.CallbackType.APP);
request.setVoiceCallbackValue(appId);
this.updateNumber(request);
} | java | public void linkNumber(String msisdn, String country, String appId) throws IOException, NexmoClientException {
UpdateNumberRequest request = new UpdateNumberRequest(msisdn, country);
request.setVoiceCallbackType(UpdateNumberRequest.CallbackType.APP);
request.setVoiceCallbackValue(appId);
this.updateNumber(request);
} | [
"public",
"void",
"linkNumber",
"(",
"String",
"msisdn",
",",
"String",
"country",
",",
"String",
"appId",
")",
"throws",
"IOException",
",",
"NexmoClientException",
"{",
"UpdateNumberRequest",
"request",
"=",
"new",
"UpdateNumberRequest",
"(",
"msisdn",
",",
"cou... | Link a given Nexmo Virtual Number to a Nexmo Application with the given ID.
@param msisdn The Nexmo Virtual Number to be updated.
@param country The country for the given msisdn.
@param appId The ID for the Nexmo Application to be associated with the number.
@throws IOException if an error occurs contacting the Nexmo API
@throws NexmoClientException if an error is returned by the server. | [
"Link",
"a",
"given",
"Nexmo",
"Virtual",
"Number",
"to",
"a",
"Nexmo",
"Application",
"with",
"the",
"given",
"ID",
"."
] | train | https://github.com/Nexmo/nexmo-java/blob/7427eff6d6baa5a5bd9197fa096bcf2564191cf5/src/main/java/com/nexmo/client/numbers/NumbersClient.java#L136-L141 |
logic-ng/LogicNG | src/main/java/org/logicng/datastructures/EncodingResult.java | EncodingResult.resultForMiniSat | public static EncodingResult resultForMiniSat(final FormulaFactory f, final MiniSat miniSat) {
return new EncodingResult(f, miniSat, null);
} | java | public static EncodingResult resultForMiniSat(final FormulaFactory f, final MiniSat miniSat) {
return new EncodingResult(f, miniSat, null);
} | [
"public",
"static",
"EncodingResult",
"resultForMiniSat",
"(",
"final",
"FormulaFactory",
"f",
",",
"final",
"MiniSat",
"miniSat",
")",
"{",
"return",
"new",
"EncodingResult",
"(",
"f",
",",
"miniSat",
",",
"null",
")",
";",
"}"
] | Constructs a new result which adds the result directly to a given MiniSat solver.
@param f the formula factory
@param miniSat the solver
@return the result | [
"Constructs",
"a",
"new",
"result",
"which",
"adds",
"the",
"result",
"directly",
"to",
"a",
"given",
"MiniSat",
"solver",
"."
] | train | https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/datastructures/EncodingResult.java#L88-L90 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/HFClient.java | HFClient.loadChannelFromConfig | public Channel loadChannelFromConfig(String channelName, NetworkConfig networkConfig) throws InvalidArgumentException, NetworkConfigurationException {
clientCheck();
// Sanity checks
if (channelName == null || channelName.isEmpty()) {
throw new InvalidArgumentException("channelName must be specified");
}
if (networkConfig == null) {
throw new InvalidArgumentException("networkConfig must be specified");
}
if (channels.containsKey(channelName)) {
throw new InvalidArgumentException(format("Channel with name %s already exists", channelName));
}
return networkConfig.loadChannel(this, channelName);
} | java | public Channel loadChannelFromConfig(String channelName, NetworkConfig networkConfig) throws InvalidArgumentException, NetworkConfigurationException {
clientCheck();
// Sanity checks
if (channelName == null || channelName.isEmpty()) {
throw new InvalidArgumentException("channelName must be specified");
}
if (networkConfig == null) {
throw new InvalidArgumentException("networkConfig must be specified");
}
if (channels.containsKey(channelName)) {
throw new InvalidArgumentException(format("Channel with name %s already exists", channelName));
}
return networkConfig.loadChannel(this, channelName);
} | [
"public",
"Channel",
"loadChannelFromConfig",
"(",
"String",
"channelName",
",",
"NetworkConfig",
"networkConfig",
")",
"throws",
"InvalidArgumentException",
",",
"NetworkConfigurationException",
"{",
"clientCheck",
"(",
")",
";",
"// Sanity checks",
"if",
"(",
"channelNa... | Configures a channel based on information loaded from a Network Config file.
Note that it is up to the caller to initialize the returned channel.
@param channelName The name of the channel to be configured
@param networkConfig The network configuration to use to configure the channel
@return The configured channel, or null if the channel is not defined in the configuration
@throws InvalidArgumentException | [
"Configures",
"a",
"channel",
"based",
"on",
"information",
"loaded",
"from",
"a",
"Network",
"Config",
"file",
".",
"Note",
"that",
"it",
"is",
"up",
"to",
"the",
"caller",
"to",
"initialize",
"the",
"returned",
"channel",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/HFClient.java#L203-L220 |
UrielCh/ovh-java-sdk | ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java | ApiOvhSms.serviceName_transferCredits_POST | public void serviceName_transferCredits_POST(String serviceName, Double credits, String smsAccountTarget) throws IOException {
String qPath = "/sms/{serviceName}/transferCredits";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "credits", credits);
addBody(o, "smsAccountTarget", smsAccountTarget);
exec(qPath, "POST", sb.toString(), o);
} | java | public void serviceName_transferCredits_POST(String serviceName, Double credits, String smsAccountTarget) throws IOException {
String qPath = "/sms/{serviceName}/transferCredits";
StringBuilder sb = path(qPath, serviceName);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "credits", credits);
addBody(o, "smsAccountTarget", smsAccountTarget);
exec(qPath, "POST", sb.toString(), o);
} | [
"public",
"void",
"serviceName_transferCredits_POST",
"(",
"String",
"serviceName",
",",
"Double",
"credits",
",",
"String",
"smsAccountTarget",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/sms/{serviceName}/transferCredits\"",
";",
"StringBuilder",
"sb"... | Credit transfer between two sms accounts.
REST: POST /sms/{serviceName}/transferCredits
@param smsAccountTarget [required] Sms account destination.
@param credits [required] Amount of credits to transfer.
@param serviceName [required] The internal name of your SMS offer | [
"Credit",
"transfer",
"between",
"two",
"sms",
"accounts",
"."
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-sms/src/main/java/net/minidev/ovh/api/ApiOvhSms.java#L1535-L1542 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyPairGenerator.java | KeyPairGenerator.getInstance | public static KeyPairGenerator getInstance(String algorithm,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = GetInstance.getInstance("KeyPairGenerator",
KeyPairGeneratorSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
} | java | public static KeyPairGenerator getInstance(String algorithm,
String provider)
throws NoSuchAlgorithmException, NoSuchProviderException {
Instance instance = GetInstance.getInstance("KeyPairGenerator",
KeyPairGeneratorSpi.class, algorithm, provider);
return getInstance(instance, algorithm);
} | [
"public",
"static",
"KeyPairGenerator",
"getInstance",
"(",
"String",
"algorithm",
",",
"String",
"provider",
")",
"throws",
"NoSuchAlgorithmException",
",",
"NoSuchProviderException",
"{",
"Instance",
"instance",
"=",
"GetInstance",
".",
"getInstance",
"(",
"\"KeyPairG... | Returns a KeyPairGenerator object that generates public/private
key pairs for the specified algorithm.
<p> A new KeyPairGenerator object encapsulating the
KeyPairGeneratorSpi implementation from the specified provider
is returned. The specified provider must be registered
in the security provider list.
<p> Note that the list of registered providers may be retrieved via
the {@link Security#getProviders() Security.getProviders()} method.
@param algorithm the standard string name of the algorithm.
See the KeyPairGenerator section in the <a href=
"{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/StandardNames.html#KeyPairGenerator">
Java Cryptography Architecture Standard Algorithm Name Documentation</a>
for information about standard algorithm names.
@param provider the string name of the provider.
@return the new KeyPairGenerator object.
@exception NoSuchAlgorithmException if a KeyPairGeneratorSpi
implementation for the specified algorithm is not
available from the specified provider.
@exception NoSuchProviderException if the specified provider is not
registered in the security provider list.
@exception IllegalArgumentException if the provider name is null
or empty.
@see Provider | [
"Returns",
"a",
"KeyPairGenerator",
"object",
"that",
"generates",
"public",
"/",
"private",
"key",
"pairs",
"for",
"the",
"specified",
"algorithm",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/java/security/KeyPairGenerator.java#L304-L310 |
apache/flink | flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AllWindowedStream.java | AllWindowedStream.minBy | public SingleOutputStreamOperator<T> minBy(String field, boolean first) {
return aggregate(new ComparableAggregator<>(field, input.getType(), AggregationFunction.AggregationType.MINBY, first, input.getExecutionConfig()));
} | java | public SingleOutputStreamOperator<T> minBy(String field, boolean first) {
return aggregate(new ComparableAggregator<>(field, input.getType(), AggregationFunction.AggregationType.MINBY, first, input.getExecutionConfig()));
} | [
"public",
"SingleOutputStreamOperator",
"<",
"T",
">",
"minBy",
"(",
"String",
"field",
",",
"boolean",
"first",
")",
"{",
"return",
"aggregate",
"(",
"new",
"ComparableAggregator",
"<>",
"(",
"field",
",",
"input",
".",
"getType",
"(",
")",
",",
"Aggregatio... | Applies an aggregation that that gives the minimum element of the pojo
data stream by the given field expression for every window. A field
expression is either the name of a public field or a getter method with
parentheses of the {@link DataStream DataStreams} underlying type. A dot can be used
to drill down into objects, as in {@code "field1.getInnerField2()" }.
@param field The field expression based on which the aggregation will be applied.
@param first If True then in case of field equality the first object will be returned
@return The transformed DataStream. | [
"Applies",
"an",
"aggregation",
"that",
"that",
"gives",
"the",
"minimum",
"element",
"of",
"the",
"pojo",
"data",
"stream",
"by",
"the",
"given",
"field",
"expression",
"for",
"every",
"window",
".",
"A",
"field",
"expression",
"is",
"either",
"the",
"name"... | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/datastream/AllWindowedStream.java#L1473-L1475 |
Javacord/Javacord | javacord-core/src/main/java/org/javacord/core/entity/auditlog/AuditLogImpl.java | AuditLogImpl.addEntries | public void addEntries(JsonNode data) {
for (JsonNode webhookJson : data.get("webhooks")) {
boolean alreadyAdded = involvedWebhooks.stream()
.anyMatch(webhook -> webhook.getId() == webhookJson.get("id").asLong());
if (!alreadyAdded) {
involvedWebhooks.add(new WebhookImpl(api, webhookJson));
}
}
for (JsonNode userJson : data.get("users")) {
boolean alreadyAdded = involvedUsers.stream()
.anyMatch(user -> user.getId() == userJson.get("id").asLong());
if (!alreadyAdded) {
involvedUsers.add(((DiscordApiImpl) api).getOrCreateUser(userJson));
}
}
for (JsonNode entry : data.get("audit_log_entries")) {
entries.add(new AuditLogEntryImpl(this, entry));
}
} | java | public void addEntries(JsonNode data) {
for (JsonNode webhookJson : data.get("webhooks")) {
boolean alreadyAdded = involvedWebhooks.stream()
.anyMatch(webhook -> webhook.getId() == webhookJson.get("id").asLong());
if (!alreadyAdded) {
involvedWebhooks.add(new WebhookImpl(api, webhookJson));
}
}
for (JsonNode userJson : data.get("users")) {
boolean alreadyAdded = involvedUsers.stream()
.anyMatch(user -> user.getId() == userJson.get("id").asLong());
if (!alreadyAdded) {
involvedUsers.add(((DiscordApiImpl) api).getOrCreateUser(userJson));
}
}
for (JsonNode entry : data.get("audit_log_entries")) {
entries.add(new AuditLogEntryImpl(this, entry));
}
} | [
"public",
"void",
"addEntries",
"(",
"JsonNode",
"data",
")",
"{",
"for",
"(",
"JsonNode",
"webhookJson",
":",
"data",
".",
"get",
"(",
"\"webhooks\"",
")",
")",
"{",
"boolean",
"alreadyAdded",
"=",
"involvedWebhooks",
".",
"stream",
"(",
")",
".",
"anyMat... | Adds entries to the audit log.
@param data The json data of the audit log. | [
"Adds",
"entries",
"to",
"the",
"audit",
"log",
"."
] | train | https://github.com/Javacord/Javacord/blob/915aad084dc5e863284267529d0dccd625fc6886/javacord-core/src/main/java/org/javacord/core/entity/auditlog/AuditLogImpl.java#L63-L81 |
anotheria/moskito | moskito-core/src/main/java/net/anotheria/moskito/core/snapshot/SnapshotCreator.java | SnapshotCreator.createSnapshot | public static ProducerSnapshot createSnapshot(IStatsProducer producer, String intervalName){
ProducerSnapshot ret = new ProducerSnapshot();
ret.setCategory(producer.getCategory());
ret.setSubsystem(producer.getSubsystem());
ret.setProducerId(producer.getProducerId());
ret.setIntervalName(intervalName);
List<IStats> stats = producer.getStats();
if (stats!=null && stats.size()>0)
ret.setStatClassName(stats.get(0).getClass().getName());
//optimization
if (stats==null || stats.size()==0)
return ret;
List<String> cachedValueNames = stats.get(0).getAvailableValueNames();
for (IStats stat : stats){
ret.addSnapshot(createStatSnapshot(stat, intervalName, cachedValueNames));
}
return ret;
} | java | public static ProducerSnapshot createSnapshot(IStatsProducer producer, String intervalName){
ProducerSnapshot ret = new ProducerSnapshot();
ret.setCategory(producer.getCategory());
ret.setSubsystem(producer.getSubsystem());
ret.setProducerId(producer.getProducerId());
ret.setIntervalName(intervalName);
List<IStats> stats = producer.getStats();
if (stats!=null && stats.size()>0)
ret.setStatClassName(stats.get(0).getClass().getName());
//optimization
if (stats==null || stats.size()==0)
return ret;
List<String> cachedValueNames = stats.get(0).getAvailableValueNames();
for (IStats stat : stats){
ret.addSnapshot(createStatSnapshot(stat, intervalName, cachedValueNames));
}
return ret;
} | [
"public",
"static",
"ProducerSnapshot",
"createSnapshot",
"(",
"IStatsProducer",
"producer",
",",
"String",
"intervalName",
")",
"{",
"ProducerSnapshot",
"ret",
"=",
"new",
"ProducerSnapshot",
"(",
")",
";",
"ret",
".",
"setCategory",
"(",
"producer",
".",
"getCat... | Creates a snapshot for a producer.
@param producer
@param intervalName
@return | [
"Creates",
"a",
"snapshot",
"for",
"a",
"producer",
"."
] | train | https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/snapshot/SnapshotCreator.java#L22-L46 |
offbynull/coroutines | maven-plugin/src/main/java/com/offbynull/coroutines/mavenplugin/AbstractInstrumentMojo.java | AbstractInstrumentMojo.getInstrumenter | private Instrumenter getInstrumenter(Log log, List<String> classpath) throws MojoExecutionException {
List<File> classpathFiles;
try {
log.debug("Getting compile classpath");
classpathFiles = classpath
.stream().map(x -> new File(x)).collect(Collectors.toList());
log.debug("Classpath for instrumentation is as follows: " + classpathFiles);
} catch (Exception ex) {
throw new MojoExecutionException("Unable to get compile classpath elements", ex);
}
log.debug("Creating instrumenter...");
try {
return new Instrumenter(classpathFiles);
} catch (Exception ex) {
throw new MojoExecutionException("Unable to create instrumenter", ex);
}
} | java | private Instrumenter getInstrumenter(Log log, List<String> classpath) throws MojoExecutionException {
List<File> classpathFiles;
try {
log.debug("Getting compile classpath");
classpathFiles = classpath
.stream().map(x -> new File(x)).collect(Collectors.toList());
log.debug("Classpath for instrumentation is as follows: " + classpathFiles);
} catch (Exception ex) {
throw new MojoExecutionException("Unable to get compile classpath elements", ex);
}
log.debug("Creating instrumenter...");
try {
return new Instrumenter(classpathFiles);
} catch (Exception ex) {
throw new MojoExecutionException("Unable to create instrumenter", ex);
}
} | [
"private",
"Instrumenter",
"getInstrumenter",
"(",
"Log",
"log",
",",
"List",
"<",
"String",
">",
"classpath",
")",
"throws",
"MojoExecutionException",
"{",
"List",
"<",
"File",
">",
"classpathFiles",
";",
"try",
"{",
"log",
".",
"debug",
"(",
"\"Getting compi... | Creates an {@link Instrumenter} instance.
@param log maven logger
@param classpath classpath for classes being instrumented
@return a new {@link Instrumenter}
@throws MojoExecutionException if any exception occurs | [
"Creates",
"an",
"{"
] | train | https://github.com/offbynull/coroutines/blob/b1b83c293945f53a2f63fca8f15a53e88b796bf5/maven-plugin/src/main/java/com/offbynull/coroutines/mavenplugin/AbstractInstrumentMojo.java#L76-L95 |
google/j2objc | jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java | DateFormat.get | private static DateFormat get(int dateStyle, int timeStyle, ULocale loc, Calendar cal) {
if((timeStyle != DateFormat.NONE && (timeStyle & RELATIVE)>0) ||
(dateStyle != DateFormat.NONE && (dateStyle & RELATIVE)>0)) {
RelativeDateFormat r = new RelativeDateFormat(timeStyle, dateStyle /* offset? */, loc, cal);
return r;
}
if (timeStyle < DateFormat.NONE || timeStyle > DateFormat.SHORT) {
throw new IllegalArgumentException("Illegal time style " + timeStyle);
}
if (dateStyle < DateFormat.NONE || dateStyle > DateFormat.SHORT) {
throw new IllegalArgumentException("Illegal date style " + dateStyle);
}
if (cal == null) {
cal = Calendar.getInstance(loc);
}
try {
DateFormat result = cal.getDateTimeFormat(dateStyle, timeStyle, loc);
result.setLocale(cal.getLocale(ULocale.VALID_LOCALE),
cal.getLocale(ULocale.ACTUAL_LOCALE));
return result;
} catch (MissingResourceException e) {
///CLOVER:OFF
// coverage requires separate run with no data, so skip
return new SimpleDateFormat("M/d/yy h:mm a");
///CLOVER:ON
}
} | java | private static DateFormat get(int dateStyle, int timeStyle, ULocale loc, Calendar cal) {
if((timeStyle != DateFormat.NONE && (timeStyle & RELATIVE)>0) ||
(dateStyle != DateFormat.NONE && (dateStyle & RELATIVE)>0)) {
RelativeDateFormat r = new RelativeDateFormat(timeStyle, dateStyle /* offset? */, loc, cal);
return r;
}
if (timeStyle < DateFormat.NONE || timeStyle > DateFormat.SHORT) {
throw new IllegalArgumentException("Illegal time style " + timeStyle);
}
if (dateStyle < DateFormat.NONE || dateStyle > DateFormat.SHORT) {
throw new IllegalArgumentException("Illegal date style " + dateStyle);
}
if (cal == null) {
cal = Calendar.getInstance(loc);
}
try {
DateFormat result = cal.getDateTimeFormat(dateStyle, timeStyle, loc);
result.setLocale(cal.getLocale(ULocale.VALID_LOCALE),
cal.getLocale(ULocale.ACTUAL_LOCALE));
return result;
} catch (MissingResourceException e) {
///CLOVER:OFF
// coverage requires separate run with no data, so skip
return new SimpleDateFormat("M/d/yy h:mm a");
///CLOVER:ON
}
} | [
"private",
"static",
"DateFormat",
"get",
"(",
"int",
"dateStyle",
",",
"int",
"timeStyle",
",",
"ULocale",
"loc",
",",
"Calendar",
"cal",
")",
"{",
"if",
"(",
"(",
"timeStyle",
"!=",
"DateFormat",
".",
"NONE",
"&&",
"(",
"timeStyle",
"&",
"RELATIVE",
")... | Creates a DateFormat with the given time and/or date style in the given
locale.
@param dateStyle a value from 0 to 3 indicating the time format,
or -1 to indicate no date
@param timeStyle a value from 0 to 3 indicating the time format,
or -1 to indicate no time
@param loc the locale for the format
@param cal the calendar to be used, or null | [
"Creates",
"a",
"DateFormat",
"with",
"the",
"given",
"time",
"and",
"/",
"or",
"date",
"style",
"in",
"the",
"given",
"locale",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/external/icu/android_icu4j/src/main/java/android/icu/text/DateFormat.java#L1672-L1701 |
ModeShape/modeshape | modeshape-common/src/main/java/org/modeshape/common/util/StringUtil.java | StringUtil.getHexString | public static String getHexString( byte[] bytes ) {
try {
byte[] hex = new byte[2 * bytes.length];
int index = 0;
for (byte b : bytes) {
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
} catch (UnsupportedEncodingException e) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bi);
}
} | java | public static String getHexString( byte[] bytes ) {
try {
byte[] hex = new byte[2 * bytes.length];
int index = 0;
for (byte b : bytes) {
int v = b & 0xFF;
hex[index++] = HEX_CHAR_TABLE[v >>> 4];
hex[index++] = HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
} catch (UnsupportedEncodingException e) {
BigInteger bi = new BigInteger(1, bytes);
return String.format("%0" + (bytes.length << 1) + "x", bi);
}
} | [
"public",
"static",
"String",
"getHexString",
"(",
"byte",
"[",
"]",
"bytes",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"hex",
"=",
"new",
"byte",
"[",
"2",
"*",
"bytes",
".",
"length",
"]",
";",
"int",
"index",
"=",
"0",
";",
"for",
"(",
"byte",
... | Get the hexadecimal string representation of the supplied byte array.
@param bytes the byte array
@return the hex string representation of the byte array; never null | [
"Get",
"the",
"hexadecimal",
"string",
"representation",
"of",
"the",
"supplied",
"byte",
"array",
"."
] | train | https://github.com/ModeShape/modeshape/blob/794cfdabb67a90f24629c4fff0424a6125f8f95b/modeshape-common/src/main/java/org/modeshape/common/util/StringUtil.java#L530-L545 |
wisdom-framework/wisdom | framework/default-error-handler/src/main/java/org/wisdom/error/InterestingLines.java | InterestingLines.extractInterestedLines | public static InterestingLines extractInterestedLines(String source, int line, int border, Logger logger) {
try {
if (source == null) {
return null;
}
String[] lines = source.split("\n");
int firstLine = Math.max(0, line - border);
int lastLine = Math.min(lines.length - 1, line + border);
List<String> focusOn = new ArrayList<>();
focusOn.addAll(Arrays.asList(lines).subList(firstLine, lastLine + 1));
return new InterestingLines(firstLine + 1, focusOn.toArray(new String[focusOn.size()]), line - firstLine - 1);
} catch (Exception e) {
logger.error("Cannot extract the interesting lines", e);
return null;
}
} | java | public static InterestingLines extractInterestedLines(String source, int line, int border, Logger logger) {
try {
if (source == null) {
return null;
}
String[] lines = source.split("\n");
int firstLine = Math.max(0, line - border);
int lastLine = Math.min(lines.length - 1, line + border);
List<String> focusOn = new ArrayList<>();
focusOn.addAll(Arrays.asList(lines).subList(firstLine, lastLine + 1));
return new InterestingLines(firstLine + 1, focusOn.toArray(new String[focusOn.size()]), line - firstLine - 1);
} catch (Exception e) {
logger.error("Cannot extract the interesting lines", e);
return null;
}
} | [
"public",
"static",
"InterestingLines",
"extractInterestedLines",
"(",
"String",
"source",
",",
"int",
"line",
",",
"int",
"border",
",",
"Logger",
"logger",
")",
"{",
"try",
"{",
"if",
"(",
"source",
"==",
"null",
")",
"{",
"return",
"null",
";",
"}",
"... | Extracts interesting lines to be displayed to the user.
@param source the source
@param line the line responsible of the error
@param border number of lines to use as a border
@param logger the logger to use to report errors
@return the interested line structure | [
"Extracts",
"interesting",
"lines",
"to",
"be",
"displayed",
"to",
"the",
"user",
"."
] | train | https://github.com/wisdom-framework/wisdom/blob/a35b6431200fec56b178c0ff60837ed73fd7874d/framework/default-error-handler/src/main/java/org/wisdom/error/InterestingLines.java#L71-L86 |
baidubce/bce-sdk-java | src/main/java/com/baidubce/services/vod/VodClient.java | VodClient.updateMediaResource | public UpdateMediaResourceResponse updateMediaResource(String mediaId, String title, String description) {
UpdateMediaResourceRequest request =
new UpdateMediaResourceRequest().withMediaId(mediaId).withTitle(title).withDescription(description);
return updateMediaResource(request);
} | java | public UpdateMediaResourceResponse updateMediaResource(String mediaId, String title, String description) {
UpdateMediaResourceRequest request =
new UpdateMediaResourceRequest().withMediaId(mediaId).withTitle(title).withDescription(description);
return updateMediaResource(request);
} | [
"public",
"UpdateMediaResourceResponse",
"updateMediaResource",
"(",
"String",
"mediaId",
",",
"String",
"title",
",",
"String",
"description",
")",
"{",
"UpdateMediaResourceRequest",
"request",
"=",
"new",
"UpdateMediaResourceRequest",
"(",
")",
".",
"withMediaId",
"("... | Update the title and description for the specific media resource managed by VOD service.
<p>
The caller <i>must</i> authenticate with a valid BCE Access Key / Private Key pair.
@param mediaId The unique ID for each media resource
@param title New title string
@param description New description string
@return empty response will be returned | [
"Update",
"the",
"title",
"and",
"description",
"for",
"the",
"specific",
"media",
"resource",
"managed",
"by",
"VOD",
"service",
"."
] | train | https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/vod/VodClient.java#L633-L638 |
alibaba/transmittable-thread-local | src/main/java/com/alibaba/ttl/TtlRunnable.java | TtlRunnable.gets | @Nonnull
public static List<TtlRunnable> gets(@Nullable Collection<? extends Runnable> tasks, boolean releaseTtlValueReferenceAfterRun) {
return gets(tasks, releaseTtlValueReferenceAfterRun, false);
} | java | @Nonnull
public static List<TtlRunnable> gets(@Nullable Collection<? extends Runnable> tasks, boolean releaseTtlValueReferenceAfterRun) {
return gets(tasks, releaseTtlValueReferenceAfterRun, false);
} | [
"@",
"Nonnull",
"public",
"static",
"List",
"<",
"TtlRunnable",
">",
"gets",
"(",
"@",
"Nullable",
"Collection",
"<",
"?",
"extends",
"Runnable",
">",
"tasks",
",",
"boolean",
"releaseTtlValueReferenceAfterRun",
")",
"{",
"return",
"gets",
"(",
"tasks",
",",
... | wrap input {@link Runnable} Collection to {@link TtlRunnable} Collection.
@param tasks task to be wrapped. if input is {@code null}, return {@code null}.
@param releaseTtlValueReferenceAfterRun release TTL value reference after run, avoid memory leak even if {@link TtlRunnable} is referred.
@return wrapped tasks
@throws IllegalStateException when input is {@link TtlRunnable} already. | [
"wrap",
"input",
"{",
"@link",
"Runnable",
"}",
"Collection",
"to",
"{",
"@link",
"TtlRunnable",
"}",
"Collection",
"."
] | train | https://github.com/alibaba/transmittable-thread-local/blob/30b4d99cdb7064b4c1797d2e40bfa07adce8e7f9/src/main/java/com/alibaba/ttl/TtlRunnable.java#L153-L156 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java | BaseSparseNDArrayCOO.reverseIndexes | public int reverseIndexes(int... indexes) {
long[] idx = translateToPhysical(ArrayUtil.toLongArray(indexes));
sort();
// FIXME: int cast
return indexesBinarySearch(0, (int) length(), ArrayUtil.toInts(idx));
} | java | public int reverseIndexes(int... indexes) {
long[] idx = translateToPhysical(ArrayUtil.toLongArray(indexes));
sort();
// FIXME: int cast
return indexesBinarySearch(0, (int) length(), ArrayUtil.toInts(idx));
} | [
"public",
"int",
"reverseIndexes",
"(",
"int",
"...",
"indexes",
")",
"{",
"long",
"[",
"]",
"idx",
"=",
"translateToPhysical",
"(",
"ArrayUtil",
".",
"toLongArray",
"(",
"indexes",
")",
")",
";",
"sort",
"(",
")",
";",
"// FIXME: int cast",
"return",
"ind... | Return the index of the value corresponding to the indexes
@param indexes
@return index of the value | [
"Return",
"the",
"index",
"of",
"the",
"value",
"corresponding",
"to",
"the",
"indexes"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ndarray/BaseSparseNDArrayCOO.java#L615-L621 |
hawkular/hawkular-agent | hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java | InventoryIdUtil.generateMetricInstanceId | public static ID generateMetricInstanceId(String feedId, ID resourceId, MetricType<?> metricType) {
ID id = new ID(String.format("MI~R~[%s/%s]~MT~%s", feedId, resourceId, metricType.getID()));
return id;
} | java | public static ID generateMetricInstanceId(String feedId, ID resourceId, MetricType<?> metricType) {
ID id = new ID(String.format("MI~R~[%s/%s]~MT~%s", feedId, resourceId, metricType.getID()));
return id;
} | [
"public",
"static",
"ID",
"generateMetricInstanceId",
"(",
"String",
"feedId",
",",
"ID",
"resourceId",
",",
"MetricType",
"<",
"?",
">",
"metricType",
")",
"{",
"ID",
"id",
"=",
"new",
"ID",
"(",
"String",
".",
"format",
"(",
"\"MI~R~[%s/%s]~MT~%s\"",
",",
... | Generates an ID for an {@link MetricInstance}.
@param resource the resource that owns the MetricInstance
@param metricType the type of the MetricInstance whose ID is being generated
@return the ID | [
"Generates",
"an",
"ID",
"for",
"an",
"{",
"@link",
"MetricInstance",
"}",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/inventory/InventoryIdUtil.java#L96-L99 |
FasterXML/woodstox | src/main/java/com/ctc/wstx/sr/AttributeCollector.java | AttributeCollector.buildAttrOb | public ElemAttrs buildAttrOb()
{
int count = mAttrCount;
if (count == 0) {
return null;
}
// If we have actual attributes, let's first just create the
// raw array that has all attribute information:
String[] raw = new String[count << 2];
for (int i = 0; i < count; ++i) {
Attribute attr = mAttributes[i];
int ix = (i << 2);
raw[ix] = attr.mLocalName;
raw[ix+1] = attr.mNamespaceURI;
raw[ix+2] = attr.mPrefix;
raw[ix+3] = getValue(i);
}
// Do we have a "short" list?
if (count < LONG_ATTR_LIST_LEN) {
return new ElemAttrs(raw, mNonDefCount);
}
// Ok, nope; we need to also pass the Map information...
/* 02-Feb-2009, TSa: Must make a copy of the Map array now,
* otherwise could get overwritten.
*/
int amapLen = mAttrMap.length;
int[] amap = new int[amapLen];
// TODO: JDK 1.6 has Arrays.copyOf(), should use with Woodstox 6
System.arraycopy(mAttrMap, 0, amap, 0, amapLen);
return new ElemAttrs(raw, mNonDefCount,
amap, mAttrHashSize, mAttrSpillEnd);
} | java | public ElemAttrs buildAttrOb()
{
int count = mAttrCount;
if (count == 0) {
return null;
}
// If we have actual attributes, let's first just create the
// raw array that has all attribute information:
String[] raw = new String[count << 2];
for (int i = 0; i < count; ++i) {
Attribute attr = mAttributes[i];
int ix = (i << 2);
raw[ix] = attr.mLocalName;
raw[ix+1] = attr.mNamespaceURI;
raw[ix+2] = attr.mPrefix;
raw[ix+3] = getValue(i);
}
// Do we have a "short" list?
if (count < LONG_ATTR_LIST_LEN) {
return new ElemAttrs(raw, mNonDefCount);
}
// Ok, nope; we need to also pass the Map information...
/* 02-Feb-2009, TSa: Must make a copy of the Map array now,
* otherwise could get overwritten.
*/
int amapLen = mAttrMap.length;
int[] amap = new int[amapLen];
// TODO: JDK 1.6 has Arrays.copyOf(), should use with Woodstox 6
System.arraycopy(mAttrMap, 0, amap, 0, amapLen);
return new ElemAttrs(raw, mNonDefCount,
amap, mAttrHashSize, mAttrSpillEnd);
} | [
"public",
"ElemAttrs",
"buildAttrOb",
"(",
")",
"{",
"int",
"count",
"=",
"mAttrCount",
";",
"if",
"(",
"count",
"==",
"0",
")",
"{",
"return",
"null",
";",
"}",
"// If we have actual attributes, let's first just create the",
"// raw array that has all attribute informa... | Method needed by event creating code, to build a non-transient
attribute container, to use with XMLEvent objects (specifically
implementation of StartElement event). | [
"Method",
"needed",
"by",
"event",
"creating",
"code",
"to",
"build",
"a",
"non",
"-",
"transient",
"attribute",
"container",
"to",
"use",
"with",
"XMLEvent",
"objects",
"(",
"specifically",
"implementation",
"of",
"StartElement",
"event",
")",
"."
] | train | https://github.com/FasterXML/woodstox/blob/ffcaabdc06672d9564c48c25d601d029b7fd6548/src/main/java/com/ctc/wstx/sr/AttributeCollector.java#L727-L760 |
liyiorg/weixin-popular | src/main/java/weixin/popular/api/MessageAPI.java | MessageAPI.templateApi_add_template | public static ApiAddTemplateResult templateApi_add_template(String access_token, String template_id_short) {
String json = String.format("{\"template_id_short\":\"%s\"}", template_id_short);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/template/api_add_template")
.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
.setEntity(new StringEntity(json, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, ApiAddTemplateResult.class);
} | java | public static ApiAddTemplateResult templateApi_add_template(String access_token, String template_id_short) {
String json = String.format("{\"template_id_short\":\"%s\"}", template_id_short);
HttpUriRequest httpUriRequest = RequestBuilder.post()
.setHeader(jsonHeader)
.setUri(BASE_URI + "/cgi-bin/template/api_add_template")
.addParameter(PARAM_ACCESS_TOKEN, API.accessToken(access_token))
.setEntity(new StringEntity(json, Charset.forName("utf-8")))
.build();
return LocalHttpClient.executeJsonResult(httpUriRequest, ApiAddTemplateResult.class);
} | [
"public",
"static",
"ApiAddTemplateResult",
"templateApi_add_template",
"(",
"String",
"access_token",
",",
"String",
"template_id_short",
")",
"{",
"String",
"json",
"=",
"String",
".",
"format",
"(",
"\"{\\\"template_id_short\\\":\\\"%s\\\"}\"",
",",
"template_id_short",
... | 模板消息 获得模板ID
@param access_token access_token
@param template_id_short template_id_short
@return ApiAddTemplateResult
@since 2.6.1 | [
"模板消息",
"获得模板ID"
] | train | https://github.com/liyiorg/weixin-popular/blob/c64255292d41463bdb671938feaabf42a335d82c/src/main/java/weixin/popular/api/MessageAPI.java#L393-L402 |
elki-project/elki | elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/optics/DeLiClu.java | DeLiClu.expandLeafNodes | private void expandLeafNodes(SpatialPrimitiveDistanceFunction<V> distFunction, DeLiCluNode node1, DeLiCluNode node2, DataStore<KNNList> knns) {
if(LOG.isDebuggingFinest()) {
LOG.debugFinest("ExpandLeafNodes: " + node1.getPageID() + " + " + node2.getPageID());
}
int numEntries_1 = node1.getNumEntries();
int numEntries_2 = node2.getNumEntries();
// insert all combinations of unhandled - handled children of
// node1-node2 into pq
for(int i = 0; i < numEntries_1; i++) {
DeLiCluEntry entry1 = node1.getEntry(i);
if(!entry1.hasUnhandled()) {
continue;
}
for(int j = 0; j < numEntries_2; j++) {
DeLiCluEntry entry2 = node2.getEntry(j);
if(!entry2.hasHandled()) {
continue;
}
double distance = distFunction.minDist(entry1, entry2);
double reach = MathUtil.max(distance, knns.get(((LeafEntry) entry2).getDBID()).getKNNDistance());
heap.add(new SpatialObjectPair(reach, entry1, entry2, false));
}
}
} | java | private void expandLeafNodes(SpatialPrimitiveDistanceFunction<V> distFunction, DeLiCluNode node1, DeLiCluNode node2, DataStore<KNNList> knns) {
if(LOG.isDebuggingFinest()) {
LOG.debugFinest("ExpandLeafNodes: " + node1.getPageID() + " + " + node2.getPageID());
}
int numEntries_1 = node1.getNumEntries();
int numEntries_2 = node2.getNumEntries();
// insert all combinations of unhandled - handled children of
// node1-node2 into pq
for(int i = 0; i < numEntries_1; i++) {
DeLiCluEntry entry1 = node1.getEntry(i);
if(!entry1.hasUnhandled()) {
continue;
}
for(int j = 0; j < numEntries_2; j++) {
DeLiCluEntry entry2 = node2.getEntry(j);
if(!entry2.hasHandled()) {
continue;
}
double distance = distFunction.minDist(entry1, entry2);
double reach = MathUtil.max(distance, knns.get(((LeafEntry) entry2).getDBID()).getKNNDistance());
heap.add(new SpatialObjectPair(reach, entry1, entry2, false));
}
}
} | [
"private",
"void",
"expandLeafNodes",
"(",
"SpatialPrimitiveDistanceFunction",
"<",
"V",
">",
"distFunction",
",",
"DeLiCluNode",
"node1",
",",
"DeLiCluNode",
"node2",
",",
"DataStore",
"<",
"KNNList",
">",
"knns",
")",
"{",
"if",
"(",
"LOG",
".",
"isDebuggingFi... | Expands the specified leaf nodes.
@param distFunction the spatial distance function of this algorithm
@param node1 the first node
@param node2 the second node
@param knns the knn list | [
"Expands",
"the",
"specified",
"leaf",
"nodes",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki/src/main/java/de/lmu/ifi/dbs/elki/algorithm/clustering/optics/DeLiClu.java#L264-L289 |
couchbase/couchbase-java-client | src/main/java/com/couchbase/client/java/transcoder/TranscoderUtils.java | TranscoderUtils.byteBufToByteArray | public static ByteBufToArray byteBufToByteArray(ByteBuf input) {
byte[] inputBytes;
int offset = 0;
int length = input.readableBytes();
if (input.hasArray()) {
inputBytes = input.array();
offset = input.arrayOffset() + input.readerIndex();
} else {
inputBytes = new byte[length];
input.getBytes(input.readerIndex(), inputBytes);
}
return new ByteBufToArray(inputBytes, offset, length);
} | java | public static ByteBufToArray byteBufToByteArray(ByteBuf input) {
byte[] inputBytes;
int offset = 0;
int length = input.readableBytes();
if (input.hasArray()) {
inputBytes = input.array();
offset = input.arrayOffset() + input.readerIndex();
} else {
inputBytes = new byte[length];
input.getBytes(input.readerIndex(), inputBytes);
}
return new ByteBufToArray(inputBytes, offset, length);
} | [
"public",
"static",
"ByteBufToArray",
"byteBufToByteArray",
"(",
"ByteBuf",
"input",
")",
"{",
"byte",
"[",
"]",
"inputBytes",
";",
"int",
"offset",
"=",
"0",
";",
"int",
"length",
"=",
"input",
".",
"readableBytes",
"(",
")",
";",
"if",
"(",
"input",
".... | Converts a {@link ByteBuf} to a byte[] in the most straightforward manner available.
@param input the ByteBuf to convert.
@return a {@link ByteBufToArray} containing the byte[] array, as well as the offset and length to use (in case
the actual array is longer than the data the ByteBuf represents for instance). | [
"Converts",
"a",
"{"
] | train | https://github.com/couchbase/couchbase-java-client/blob/f36a0ee0c66923bdde47838ca543e50cbaa99e14/src/main/java/com/couchbase/client/java/transcoder/TranscoderUtils.java#L279-L291 |
twilio/twilio-java | src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java | AssignedAddOnExtensionReader.firstPage | @Override
@SuppressWarnings("checkstyle:linelength")
public Page<AssignedAddOnExtension> firstPage(final TwilioRestClient client) {
this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
Request request = new Request(
HttpMethod.GET,
Domains.API.toString(),
"/2010-04-01/Accounts/" + this.pathAccountSid + "/IncomingPhoneNumbers/" + this.pathResourceSid + "/AssignedAddOns/" + this.pathAssignedAddOnSid + "/Extensions.json",
client.getRegion()
);
addQueryParams(request);
return pageForRequest(client, request);
} | java | @Override
@SuppressWarnings("checkstyle:linelength")
public Page<AssignedAddOnExtension> firstPage(final TwilioRestClient client) {
this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
Request request = new Request(
HttpMethod.GET,
Domains.API.toString(),
"/2010-04-01/Accounts/" + this.pathAccountSid + "/IncomingPhoneNumbers/" + this.pathResourceSid + "/AssignedAddOns/" + this.pathAssignedAddOnSid + "/Extensions.json",
client.getRegion()
);
addQueryParams(request);
return pageForRequest(client, request);
} | [
"@",
"Override",
"@",
"SuppressWarnings",
"(",
"\"checkstyle:linelength\"",
")",
"public",
"Page",
"<",
"AssignedAddOnExtension",
">",
"firstPage",
"(",
"final",
"TwilioRestClient",
"client",
")",
"{",
"this",
".",
"pathAccountSid",
"=",
"this",
".",
"pathAccountSid... | Make the request to the Twilio API to perform the read.
@param client TwilioRestClient with which to make the request
@return AssignedAddOnExtension ResourceSet | [
"Make",
"the",
"request",
"to",
"the",
"Twilio",
"API",
"to",
"perform",
"the",
"read",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/api/v2010/account/incomingphonenumber/assignedaddon/AssignedAddOnExtensionReader.java#L80-L93 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/input/category/CmsDataValue.java | CmsDataValue.matchesFilter | public boolean matchesFilter(String filter, int priValue, int secValue) {
filter = filter.toLowerCase();
return m_parameters[priValue].toLowerCase().contains(filter)
|| m_parameters[secValue].toLowerCase().contains(filter);
} | java | public boolean matchesFilter(String filter, int priValue, int secValue) {
filter = filter.toLowerCase();
return m_parameters[priValue].toLowerCase().contains(filter)
|| m_parameters[secValue].toLowerCase().contains(filter);
} | [
"public",
"boolean",
"matchesFilter",
"(",
"String",
"filter",
",",
"int",
"priValue",
",",
"int",
"secValue",
")",
"{",
"filter",
"=",
"filter",
".",
"toLowerCase",
"(",
")",
";",
"return",
"m_parameters",
"[",
"priValue",
"]",
".",
"toLowerCase",
"(",
")... | Returns if the category matches the given filter.<p>
@param filter the filter to match
@param priValue the first search value
@param secValue the second search value
@return <code>true</code> if the gallery matches the given filter.<p> | [
"Returns",
"if",
"the",
"category",
"matches",
"the",
"given",
"filter",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/input/category/CmsDataValue.java#L258-L263 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/StringUtils.java | StringUtils.replaceAll | @NullSafe
public static String replaceAll(String value, String pattern, String replacement) {
if (!ObjectUtils.areAnyNull(value, pattern, replacement)) {
value = Pattern.compile(pattern).matcher(value).replaceAll(replacement);
}
return value;
} | java | @NullSafe
public static String replaceAll(String value, String pattern, String replacement) {
if (!ObjectUtils.areAnyNull(value, pattern, replacement)) {
value = Pattern.compile(pattern).matcher(value).replaceAll(replacement);
}
return value;
} | [
"@",
"NullSafe",
"public",
"static",
"String",
"replaceAll",
"(",
"String",
"value",
",",
"String",
"pattern",
",",
"String",
"replacement",
")",
"{",
"if",
"(",
"!",
"ObjectUtils",
".",
"areAnyNull",
"(",
"value",
",",
"pattern",
",",
"replacement",
")",
... | Null-safe method to replace the specified pattern in the given {@link String} value with
the replacement {@link String}.
For example, given the following String...
<code>
"///absolute//path/to/////some////file.ext"
</code>
When 'pattern' is "/+" and 'replacement' is "/", the resulting, returned String value will be...
<code>
"/absolute/path/to/some/file.ext"
</code>
@param value the {@link String} value on which to perform the pattern search and replace operation.
@param pattern the pattern of characters in the {@link String} value to replace.
@param replacement the replacement {@link String} used to replace all occurrences of the pattern of characters.
@return a modified {@link String} value with the pattern of characters replaced with the replacement.
Returns the original {@link String} value if
@see java.util.regex.Pattern#compile(String)
@see java.util.regex.Pattern#matcher(CharSequence)
@see java.util.regex.Matcher#replaceAll(String) | [
"Null",
"-",
"safe",
"method",
"to",
"replace",
"the",
"specified",
"pattern",
"in",
"the",
"given",
"{",
"@link",
"String",
"}",
"value",
"with",
"the",
"replacement",
"{",
"@link",
"String",
"}",
"."
] | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/StringUtils.java#L490-L498 |
b3dgs/lionengine | lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java | NetworkMessageEntity.addAction | public void addAction(M element, byte value)
{
actions.put(element, Byte.valueOf(value));
} | java | public void addAction(M element, byte value)
{
actions.put(element, Byte.valueOf(value));
} | [
"public",
"void",
"addAction",
"(",
"M",
"element",
",",
"byte",
"value",
")",
"{",
"actions",
".",
"put",
"(",
"element",
",",
"Byte",
".",
"valueOf",
"(",
"value",
")",
")",
";",
"}"
] | Add an action.
@param element The action type.
@param value The action value. | [
"Add",
"an",
"action",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-network/src/main/java/com/b3dgs/lionengine/network/message/NetworkMessageEntity.java#L133-L136 |
OpenTSDB/opentsdb | src/tools/OpenTSDBMain.java | OpenTSDBMain.insertPattern | protected static String insertPattern(final String logFileName, final String rollPattern) {
int index = logFileName.lastIndexOf('.');
if(index==-1) return logFileName + rollPattern;
return logFileName.substring(0, index) + rollPattern + logFileName.substring(index);
} | java | protected static String insertPattern(final String logFileName, final String rollPattern) {
int index = logFileName.lastIndexOf('.');
if(index==-1) return logFileName + rollPattern;
return logFileName.substring(0, index) + rollPattern + logFileName.substring(index);
} | [
"protected",
"static",
"String",
"insertPattern",
"(",
"final",
"String",
"logFileName",
",",
"final",
"String",
"rollPattern",
")",
"{",
"int",
"index",
"=",
"logFileName",
".",
"lastIndexOf",
"(",
"'",
"'",
")",
";",
"if",
"(",
"index",
"==",
"-",
"1",
... | Merges the roll pattern name into the file name
@param logFileName The log file name
@param rollPattern The rolling log file appender roll pattern
@return the merged file pattern | [
"Merges",
"the",
"roll",
"pattern",
"name",
"into",
"the",
"file",
"name"
] | train | https://github.com/OpenTSDB/opentsdb/blob/3fc2d491c3c1ad397252c0a80203a69a3f9e3ef3/src/tools/OpenTSDBMain.java#L526-L530 |
raphw/byte-buddy | byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/AbstractUserConfiguration.java | AbstractUserConfiguration.getClassPath | public Iterable<? extends File> getClassPath(File root, Iterable<? extends File> classPath) {
return this.classPath == null
? new PrefixIterable(root, classPath)
: this.classPath;
} | java | public Iterable<? extends File> getClassPath(File root, Iterable<? extends File> classPath) {
return this.classPath == null
? new PrefixIterable(root, classPath)
: this.classPath;
} | [
"public",
"Iterable",
"<",
"?",
"extends",
"File",
">",
"getClassPath",
"(",
"File",
"root",
",",
"Iterable",
"<",
"?",
"extends",
"File",
">",
"classPath",
")",
"{",
"return",
"this",
".",
"classPath",
"==",
"null",
"?",
"new",
"PrefixIterable",
"(",
"r... | Returns the class path or builds a class path from the supplied arguments if no class path was set.
@param root The root directory of the project being built.
@param classPath The class path dependencies.
@return An iterable of all elements of the class path to be used. | [
"Returns",
"the",
"class",
"path",
"or",
"builds",
"a",
"class",
"path",
"from",
"the",
"supplied",
"arguments",
"if",
"no",
"class",
"path",
"was",
"set",
"."
] | train | https://github.com/raphw/byte-buddy/blob/4d2dac80efb6bed89367567260f6811c2f712d12/byte-buddy-gradle-plugin/src/main/java/net/bytebuddy/build/gradle/AbstractUserConfiguration.java#L38-L42 |
apache/reef | lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/time/runtime/RuntimeClock.java | RuntimeClock.scheduleAlarm | @Override
public Time scheduleAlarm(final int offset, final EventHandler<Alarm> handler) {
final Time alarm = new ClientAlarm(this.timer.getCurrent() + offset, handler);
if (LOG.isLoggable(Level.FINEST)) {
final int eventQueueLen;
synchronized (this.schedule) {
eventQueueLen = this.numClientAlarms;
}
LOG.log(Level.FINEST,
"Schedule alarm: {0} Outstanding client alarms: {1}",
new Object[] {alarm, eventQueueLen});
}
synchronized (this.schedule) {
if (this.isClosed) {
throw new IllegalStateException("Scheduling alarm on a closed clock");
}
if (alarm.getTimestamp() > this.lastClientAlarm) {
this.lastClientAlarm = alarm.getTimestamp();
}
assert this.numClientAlarms >= 0;
++this.numClientAlarms;
this.schedule.add(alarm);
this.schedule.notify();
}
return alarm;
} | java | @Override
public Time scheduleAlarm(final int offset, final EventHandler<Alarm> handler) {
final Time alarm = new ClientAlarm(this.timer.getCurrent() + offset, handler);
if (LOG.isLoggable(Level.FINEST)) {
final int eventQueueLen;
synchronized (this.schedule) {
eventQueueLen = this.numClientAlarms;
}
LOG.log(Level.FINEST,
"Schedule alarm: {0} Outstanding client alarms: {1}",
new Object[] {alarm, eventQueueLen});
}
synchronized (this.schedule) {
if (this.isClosed) {
throw new IllegalStateException("Scheduling alarm on a closed clock");
}
if (alarm.getTimestamp() > this.lastClientAlarm) {
this.lastClientAlarm = alarm.getTimestamp();
}
assert this.numClientAlarms >= 0;
++this.numClientAlarms;
this.schedule.add(alarm);
this.schedule.notify();
}
return alarm;
} | [
"@",
"Override",
"public",
"Time",
"scheduleAlarm",
"(",
"final",
"int",
"offset",
",",
"final",
"EventHandler",
"<",
"Alarm",
">",
"handler",
")",
"{",
"final",
"Time",
"alarm",
"=",
"new",
"ClientAlarm",
"(",
"this",
".",
"timer",
".",
"getCurrent",
"(",... | Schedule a new Alarm event in `offset` milliseconds into the future,
and supply an event handler to be called at that time.
@param offset Number of milliseconds into the future relative to current time.
@param handler Event handler to be invoked.
@return Newly scheduled alarm.
@throws IllegalStateException if the clock is already closed. | [
"Schedule",
"a",
"new",
"Alarm",
"event",
"in",
"offset",
"milliseconds",
"into",
"the",
"future",
"and",
"supply",
"an",
"event",
"handler",
"to",
"be",
"called",
"at",
"that",
"time",
"."
] | train | https://github.com/apache/reef/blob/e2c47121cde21108a602c560cf76565a40d0e916/lang/java/reef-wake/wake/src/main/java/org/apache/reef/wake/time/runtime/RuntimeClock.java#L121-L156 |
ironjacamar/ironjacamar | validator/src/main/java/org/ironjacamar/validator/Validation.java | Validation.createAdminObject | private static List<Validate> createAdminObject(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (cmd.getVersion() != Version.V_10 &&
cmd.getResourceadapter() != null &&
cmd.getResourceadapter().getAdminObjects() != null)
{
List<AdminObject> aoMetas = cmd.getResourceadapter().getAdminObjects();
if (!aoMetas.isEmpty())
{
for (AdminObject aoMeta : aoMetas)
{
if (aoMeta.getAdminobjectClass() != null
&& !aoMeta.getAdminobjectClass().equals(XsdString.NULL_XSDSTRING))
{
try
{
Class<?> clazz = Class.forName(aoMeta.getAdminobjectClass().getValue(), true, cl);
List<ConfigProperty> configProperties = aoMeta.getConfigProperties();
ValidateClass vc = new ValidateClass(Key.ADMIN_OBJECT, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("ao.cnfe"),
e.getMessage());
failures.add(failure);
}
}
}
}
}
return result;
} | java | private static List<Validate> createAdminObject(Connector cmd,
List<Failure> failures, ResourceBundle rb, ClassLoader cl)
{
List<Validate> result = new ArrayList<Validate>();
if (cmd.getVersion() != Version.V_10 &&
cmd.getResourceadapter() != null &&
cmd.getResourceadapter().getAdminObjects() != null)
{
List<AdminObject> aoMetas = cmd.getResourceadapter().getAdminObjects();
if (!aoMetas.isEmpty())
{
for (AdminObject aoMeta : aoMetas)
{
if (aoMeta.getAdminobjectClass() != null
&& !aoMeta.getAdminobjectClass().equals(XsdString.NULL_XSDSTRING))
{
try
{
Class<?> clazz = Class.forName(aoMeta.getAdminobjectClass().getValue(), true, cl);
List<ConfigProperty> configProperties = aoMeta.getConfigProperties();
ValidateClass vc = new ValidateClass(Key.ADMIN_OBJECT, clazz, configProperties);
result.add(vc);
}
catch (ClassNotFoundException e)
{
Failure failure = new Failure(Severity.ERROR,
rb.getString("uncategorized"),
rb.getString("ao.cnfe"),
e.getMessage());
failures.add(failure);
}
}
}
}
}
return result;
} | [
"private",
"static",
"List",
"<",
"Validate",
">",
"createAdminObject",
"(",
"Connector",
"cmd",
",",
"List",
"<",
"Failure",
">",
"failures",
",",
"ResourceBundle",
"rb",
",",
"ClassLoader",
"cl",
")",
"{",
"List",
"<",
"Validate",
">",
"result",
"=",
"ne... | createAdminObject
@param cmd connector metadata
@param failures list of failures
@param rb ResourceBundle
@param cl classloador
@return list of validate objects | [
"createAdminObject"
] | train | https://github.com/ironjacamar/ironjacamar/blob/f0389ee7e62aa8b40ba09b251edad76d220ea796/validator/src/main/java/org/ironjacamar/validator/Validation.java#L444-L483 |
playn/playn | html/src/playn/super/java/nio/CharBuffer.java | CharBuffer.put | public CharBuffer put (String str, int start, int end) {
int length = str.length();
if (start < 0 || end < start || end > length) {
throw new IndexOutOfBoundsException();
}
if (end - start > remaining()) {
throw new BufferOverflowException();
}
for (int i = start; i < end; i++) {
put(str.charAt(i));
}
return this;
} | java | public CharBuffer put (String str, int start, int end) {
int length = str.length();
if (start < 0 || end < start || end > length) {
throw new IndexOutOfBoundsException();
}
if (end - start > remaining()) {
throw new BufferOverflowException();
}
for (int i = start; i < end; i++) {
put(str.charAt(i));
}
return this;
} | [
"public",
"CharBuffer",
"put",
"(",
"String",
"str",
",",
"int",
"start",
",",
"int",
"end",
")",
"{",
"int",
"length",
"=",
"str",
".",
"length",
"(",
")",
";",
"if",
"(",
"start",
"<",
"0",
"||",
"end",
"<",
"start",
"||",
"end",
">",
"length",... | Writes chars of the given string to the current position of this buffer, and increases the
position by the number of chars written.
@param str the string to write.
@param start the first char to write, must not be negative and not greater than {@code
str.length()}.
@param end the last char to write (excluding), must be less than {@code start} and not
greater than {@code str.length()}.
@return this buffer.
@exception BufferOverflowException if {@code remaining()} is less than {@code end - start}.
@exception IndexOutOfBoundsException if either {@code start} or {@code end} is invalid.
@exception ReadOnlyBufferException if no changes may be made to the contents of this buffer. | [
"Writes",
"chars",
"of",
"the",
"given",
"string",
"to",
"the",
"current",
"position",
"of",
"this",
"buffer",
"and",
"increases",
"the",
"position",
"by",
"the",
"number",
"of",
"chars",
"written",
"."
] | train | https://github.com/playn/playn/blob/7e7a9d048ba6afe550dc0cdeaca3e1d5b0d01c66/html/src/playn/super/java/nio/CharBuffer.java#L413-L426 |
UrielCh/ovh-java-sdk | ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java | ApiOvhPackxdsl.packName_voipLine_services_domain_GET | public OvhVoipLineService packName_voipLine_services_domain_GET(String packName, String domain) throws IOException {
String qPath = "/pack/xdsl/{packName}/voipLine/services/{domain}";
StringBuilder sb = path(qPath, packName, domain);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhVoipLineService.class);
} | java | public OvhVoipLineService packName_voipLine_services_domain_GET(String packName, String domain) throws IOException {
String qPath = "/pack/xdsl/{packName}/voipLine/services/{domain}";
StringBuilder sb = path(qPath, packName, domain);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhVoipLineService.class);
} | [
"public",
"OvhVoipLineService",
"packName_voipLine_services_domain_GET",
"(",
"String",
"packName",
",",
"String",
"domain",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/pack/xdsl/{packName}/voipLine/services/{domain}\"",
";",
"StringBuilder",
"sb",
"=",
"... | Get this object properties
REST: GET /pack/xdsl/{packName}/voipLine/services/{domain}
@param packName [required] The internal name of your pack
@param domain [required] | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-packxdsl/src/main/java/net/minidev/ovh/api/ApiOvhPackxdsl.java#L274-L279 |
aws/aws-sdk-java | aws-java-sdk-core/src/main/java/com/amazonaws/util/URLEncodedUtils.java | URLEncodedUtils.encUric | static String encUric(final String content, final Charset charset) {
return urlEncode(content, charset, URIC, false);
} | java | static String encUric(final String content, final Charset charset) {
return urlEncode(content, charset, URIC, false);
} | [
"static",
"String",
"encUric",
"(",
"final",
"String",
"content",
",",
"final",
"Charset",
"charset",
")",
"{",
"return",
"urlEncode",
"(",
"content",
",",
"charset",
",",
"URIC",
",",
"false",
")",
";",
"}"
] | Encode a String using the {@link #URIC} set of characters.
<p>
Used by URIBuilder to encode the query and fragment segments.
@param content the string to encode, does not convert space to '+'
@param charset the charset to use
@return the encoded string | [
"Encode",
"a",
"String",
"using",
"the",
"{",
"@link",
"#URIC",
"}",
"set",
"of",
"characters",
".",
"<p",
">",
"Used",
"by",
"URIBuilder",
"to",
"encode",
"the",
"query",
"and",
"fragment",
"segments",
"."
] | train | https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-core/src/main/java/com/amazonaws/util/URLEncodedUtils.java#L331-L333 |
52inc/android-52Kit | library/src/main/java/com/ftinc/kit/font/FontLoader.java | FontLoader.getTypeface | public static Typeface getTypeface(Context ctx, String fontName){
Typeface existing = mLoadedTypefaces.get(fontName);
if(existing == null){
existing = Typeface.createFromAsset(ctx.getAssets(), fontName);
mLoadedTypefaces.put(fontName, existing);
}
return existing;
} | java | public static Typeface getTypeface(Context ctx, String fontName){
Typeface existing = mLoadedTypefaces.get(fontName);
if(existing == null){
existing = Typeface.createFromAsset(ctx.getAssets(), fontName);
mLoadedTypefaces.put(fontName, existing);
}
return existing;
} | [
"public",
"static",
"Typeface",
"getTypeface",
"(",
"Context",
"ctx",
",",
"String",
"fontName",
")",
"{",
"Typeface",
"existing",
"=",
"mLoadedTypefaces",
".",
"get",
"(",
"fontName",
")",
";",
"if",
"(",
"existing",
"==",
"null",
")",
"{",
"existing",
"=... | Get a typeface for a given the font name/path
@param ctx the context to load the typeface from assets
@param fontName the name/path of of the typeface to load
@return the loaded typeface, or null | [
"Get",
"a",
"typeface",
"for",
"a",
"given",
"the",
"font",
"name",
"/",
"path"
] | train | https://github.com/52inc/android-52Kit/blob/8644fab0f633477b1bb1dddd8147a9ef8bc03516/library/src/main/java/com/ftinc/kit/font/FontLoader.java#L115-L122 |
linkedin/dexmaker | dexmaker/src/main/java/com/android/dx/Code.java | Code.arrayLength | public <T> void arrayLength(Local<Integer> target, Local<T> array) {
addInstruction(new ThrowingInsn(Rops.ARRAY_LENGTH, sourcePosition,
RegisterSpecList.make(array.spec()), catches));
moveResult(target, true);
} | java | public <T> void arrayLength(Local<Integer> target, Local<T> array) {
addInstruction(new ThrowingInsn(Rops.ARRAY_LENGTH, sourcePosition,
RegisterSpecList.make(array.spec()), catches));
moveResult(target, true);
} | [
"public",
"<",
"T",
">",
"void",
"arrayLength",
"(",
"Local",
"<",
"Integer",
">",
"target",
",",
"Local",
"<",
"T",
">",
"array",
")",
"{",
"addInstruction",
"(",
"new",
"ThrowingInsn",
"(",
"Rops",
".",
"ARRAY_LENGTH",
",",
"sourcePosition",
",",
"Regi... | Sets {@code target} to the length of the array in {@code array}. | [
"Sets",
"{"
] | train | https://github.com/linkedin/dexmaker/blob/c58ffebcbb2564c7d1fa6fb58b48f351c330296d/dexmaker/src/main/java/com/android/dx/Code.java#L784-L788 |
jenkinsci/java-client-api | jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java | JenkinsServer.updateJob | public JenkinsServer updateJob(String jobName, String jobXml, boolean crumbFlag) throws IOException {
return updateJob(null, jobName, jobXml, crumbFlag);
} | java | public JenkinsServer updateJob(String jobName, String jobXml, boolean crumbFlag) throws IOException {
return updateJob(null, jobName, jobXml, crumbFlag);
} | [
"public",
"JenkinsServer",
"updateJob",
"(",
"String",
"jobName",
",",
"String",
"jobXml",
",",
"boolean",
"crumbFlag",
")",
"throws",
"IOException",
"{",
"return",
"updateJob",
"(",
"null",
",",
"jobName",
",",
"jobXml",
",",
"crumbFlag",
")",
";",
"}"
] | Update the xml description of an existing job
@param jobName name of the job to be updated.
@param jobXml the configuration to be used for updating.
@param crumbFlag true/false.
@throws IOException in case of an error. | [
"Update",
"the",
"xml",
"description",
"of",
"an",
"existing",
"job"
] | train | https://github.com/jenkinsci/java-client-api/blob/c4f5953d3d4dda92cd946ad3bf2b811524c32da9/jenkins-client/src/main/java/com/offbytwo/jenkins/JenkinsServer.java#L620-L622 |
Alluxio/alluxio | core/server/common/src/main/java/alluxio/ProcessUtils.java | ProcessUtils.fatalError | public static void fatalError(Logger logger, String format, Object... args) {
fatalError(logger, null, format, args);
} | java | public static void fatalError(Logger logger, String format, Object... args) {
fatalError(logger, null, format, args);
} | [
"public",
"static",
"void",
"fatalError",
"(",
"Logger",
"logger",
",",
"String",
"format",
",",
"Object",
"...",
"args",
")",
"{",
"fatalError",
"(",
"logger",
",",
"null",
",",
"format",
",",
"args",
")",
";",
"}"
] | Logs a fatal error and then exits the system.
@param logger the logger to log to
@param format the error message format string
@param args args for the format string | [
"Logs",
"a",
"fatal",
"error",
"and",
"then",
"exits",
"the",
"system",
"."
] | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/server/common/src/main/java/alluxio/ProcessUtils.java#L57-L59 |
JM-Lab/utils-java8 | src/main/java/kr/jm/utils/helper/JMOptional.java | JMOptional.orElseGetIfNull | public static <T> T orElseGetIfNull(T target, Supplier<T> elseGetSupplier) {
return Optional.ofNullable(target).orElseGet(elseGetSupplier);
} | java | public static <T> T orElseGetIfNull(T target, Supplier<T> elseGetSupplier) {
return Optional.ofNullable(target).orElseGet(elseGetSupplier);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"orElseGetIfNull",
"(",
"T",
"target",
",",
"Supplier",
"<",
"T",
">",
"elseGetSupplier",
")",
"{",
"return",
"Optional",
".",
"ofNullable",
"(",
"target",
")",
".",
"orElseGet",
"(",
"elseGetSupplier",
")",
";",
"... | Or else get if null t.
@param <T> the type parameter
@param target the target
@param elseGetSupplier the else get supplier
@return the t | [
"Or",
"else",
"get",
"if",
"null",
"t",
"."
] | train | https://github.com/JM-Lab/utils-java8/blob/9e407b3f28a7990418a1e877229fa8344f4d78a5/src/main/java/kr/jm/utils/helper/JMOptional.java#L229-L231 |
apptik/jus | examples-android/src/main/java/io/apptik/comm/jus/examples/adapter/RecyclerAdapter.java | RecyclerAdapter.onBindViewHolder | @Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
Log.e("jus", jarr.get(position).asJsonObject().getString("pic"));
viewHolder.niv.setImageUrl(jarr.get(position).asJsonObject().getString("pic"), imageLoader);
viewHolder.txt1.setText(position + " : " + jarr.get(position).asJsonObject().getString
("txt1"));
/// COOL ANIM
View v = (View) viewHolder.niv.getParent().getParent();
if (v != null && !positionsMapper.get(position) && position > lastPosition) {
speed = scrollListener.getSpeed();
animDuration = (((int) speed) == 0) ? ANIM_DEFAULT_SPEED : (long) ((1 / speed) * 3000);
Log.d(TAG, "scroll speed/dur : " + speed + " / " + animDuration);
//animDuration = ANIM_DEFAULT_SPEED;
if (animDuration > ANIM_DEFAULT_SPEED)
animDuration = ANIM_DEFAULT_SPEED;
lastPosition = position;
v.setTranslationX(0.0F);
v.setTranslationY(height);
v.setRotationX(35.0F);
v.setScaleX(0.7F);
v.setScaleY(0.55F);
ViewPropertyAnimator localViewPropertyAnimator =
v.animate().rotationX(0.0F).rotationY(0.0F).translationX(0).translationY(0)
.setDuration(animDuration).scaleX(
1.0F).scaleY(1.0F).setInterpolator(interpolator);
localViewPropertyAnimator.setStartDelay(0).start();
positionsMapper.put(position, true);
}
} | java | @Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
Log.d(TAG, "Element " + position + " set.");
// Get element from your dataset at this position and replace the contents of the view
// with that element
Log.e("jus", jarr.get(position).asJsonObject().getString("pic"));
viewHolder.niv.setImageUrl(jarr.get(position).asJsonObject().getString("pic"), imageLoader);
viewHolder.txt1.setText(position + " : " + jarr.get(position).asJsonObject().getString
("txt1"));
/// COOL ANIM
View v = (View) viewHolder.niv.getParent().getParent();
if (v != null && !positionsMapper.get(position) && position > lastPosition) {
speed = scrollListener.getSpeed();
animDuration = (((int) speed) == 0) ? ANIM_DEFAULT_SPEED : (long) ((1 / speed) * 3000);
Log.d(TAG, "scroll speed/dur : " + speed + " / " + animDuration);
//animDuration = ANIM_DEFAULT_SPEED;
if (animDuration > ANIM_DEFAULT_SPEED)
animDuration = ANIM_DEFAULT_SPEED;
lastPosition = position;
v.setTranslationX(0.0F);
v.setTranslationY(height);
v.setRotationX(35.0F);
v.setScaleX(0.7F);
v.setScaleY(0.55F);
ViewPropertyAnimator localViewPropertyAnimator =
v.animate().rotationX(0.0F).rotationY(0.0F).translationX(0).translationY(0)
.setDuration(animDuration).scaleX(
1.0F).scaleY(1.0F).setInterpolator(interpolator);
localViewPropertyAnimator.setStartDelay(0).start();
positionsMapper.put(position, true);
}
} | [
"@",
"Override",
"public",
"void",
"onBindViewHolder",
"(",
"ViewHolder",
"viewHolder",
",",
"final",
"int",
"position",
")",
"{",
"Log",
".",
"d",
"(",
"TAG",
",",
"\"Element \"",
"+",
"position",
"+",
"\" set.\"",
")",
";",
"// Get element from your dataset at... | Replace the contents of a view (invoked by the layout manager) | [
"Replace",
"the",
"contents",
"of",
"a",
"view",
"(",
"invoked",
"by",
"the",
"layout",
"manager",
")"
] | train | https://github.com/apptik/jus/blob/8a37a21b41f897d68eaeaab07368ec22a1e5a60e/examples-android/src/main/java/io/apptik/comm/jus/examples/adapter/RecyclerAdapter.java#L128-L166 |
virgo47/javasimon | core/src/main/java/org/javasimon/callback/quantiles/ExponentialBuckets.java | ExponentialBuckets.estimateQuantile | protected double estimateQuantile(Bucket bucket, double expectedCount, double lastCount) {
return bucket.getMin() + (bucket.getMax() - bucket.getMin()) * Math.exp(Math.log(expectedCount - lastCount) / Math.log(bucket.getCount()));
} | java | protected double estimateQuantile(Bucket bucket, double expectedCount, double lastCount) {
return bucket.getMin() + (bucket.getMax() - bucket.getMin()) * Math.exp(Math.log(expectedCount - lastCount) / Math.log(bucket.getCount()));
} | [
"protected",
"double",
"estimateQuantile",
"(",
"Bucket",
"bucket",
",",
"double",
"expectedCount",
",",
"double",
"lastCount",
")",
"{",
"return",
"bucket",
".",
"getMin",
"(",
")",
"+",
"(",
"bucket",
".",
"getMax",
"(",
")",
"-",
"bucket",
".",
"getMin"... | {@inheritDoc}
<p/>
Used during quantiles computation to do exponential regression over one bucket. | [
"{"
] | train | https://github.com/virgo47/javasimon/blob/17dfaa93cded9ce8ef64a134b28ccbf4d0284d2f/core/src/main/java/org/javasimon/callback/quantiles/ExponentialBuckets.java#L66-L68 |
pip-services3-java/pip-services3-commons-java | src/org/pipservices3/commons/random/RandomDateTime.java | RandomDateTime.nextDateTime | public static ZonedDateTime nextDateTime(int minYear, int maxYear) {
return nextDate(minYear, maxYear).plusSeconds(RandomInteger.nextInteger(3600 * 24 * 365));
} | java | public static ZonedDateTime nextDateTime(int minYear, int maxYear) {
return nextDate(minYear, maxYear).plusSeconds(RandomInteger.nextInteger(3600 * 24 * 365));
} | [
"public",
"static",
"ZonedDateTime",
"nextDateTime",
"(",
"int",
"minYear",
",",
"int",
"maxYear",
")",
"{",
"return",
"nextDate",
"(",
"minYear",
",",
"maxYear",
")",
".",
"plusSeconds",
"(",
"RandomInteger",
".",
"nextInteger",
"(",
"3600",
"*",
"24",
"*",... | Generates a random ZonedDateTime and time in the range ['minYear',
'maxYear']. This method generate dates without time (or time set to 00:00:00)
@param minYear (optional) minimum range value
@param maxYear max range value
@return a random ZonedDateTime and time value. | [
"Generates",
"a",
"random",
"ZonedDateTime",
"and",
"time",
"in",
"the",
"range",
"[",
"minYear",
"maxYear",
"]",
".",
"This",
"method",
"generate",
"dates",
"without",
"time",
"(",
"or",
"time",
"set",
"to",
"00",
":",
"00",
":",
"00",
")"
] | train | https://github.com/pip-services3-java/pip-services3-commons-java/blob/a8a0c3e5ec58f0663c295aa855c6b3afad2af86a/src/org/pipservices3/commons/random/RandomDateTime.java#L66-L68 |
nguyenq/tess4j | src/main/java/net/sourceforge/tess4j/util/ImageHelper.java | ImageHelper.invertImageColor | public static BufferedImage invertImageColor(BufferedImage image) {
BufferedImage tmp = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
BufferedImageOp invertOp = new LookupOp(new ShortLookupTable(0, invertTable), null);
return invertOp.filter(image, tmp);
} | java | public static BufferedImage invertImageColor(BufferedImage image) {
BufferedImage tmp = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
BufferedImageOp invertOp = new LookupOp(new ShortLookupTable(0, invertTable), null);
return invertOp.filter(image, tmp);
} | [
"public",
"static",
"BufferedImage",
"invertImageColor",
"(",
"BufferedImage",
"image",
")",
"{",
"BufferedImage",
"tmp",
"=",
"new",
"BufferedImage",
"(",
"image",
".",
"getWidth",
"(",
")",
",",
"image",
".",
"getHeight",
"(",
")",
",",
"image",
".",
"getT... | Inverts image color.
@param image input image
@return an inverted-color image | [
"Inverts",
"image",
"color",
"."
] | train | https://github.com/nguyenq/tess4j/blob/cfcd4a8a44042f150b4aaf7bdf5ffc485a2236e1/src/main/java/net/sourceforge/tess4j/util/ImageHelper.java#L151-L155 |
RobotiumTech/robotium | robotium-solo/src/main/java/com/robotium/solo/Solo.java | Solo.waitForActivity | public boolean waitForActivity(Class<? extends Activity> activityClass, int timeout)
{
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForActivity("+activityClass+", "+timeout+")");
}
return waiter.waitForActivity(activityClass, timeout);
} | java | public boolean waitForActivity(Class<? extends Activity> activityClass, int timeout)
{
if(config.commandLogging){
Log.d(config.commandLoggingTag, "waitForActivity("+activityClass+", "+timeout+")");
}
return waiter.waitForActivity(activityClass, timeout);
} | [
"public",
"boolean",
"waitForActivity",
"(",
"Class",
"<",
"?",
"extends",
"Activity",
">",
"activityClass",
",",
"int",
"timeout",
")",
"{",
"if",
"(",
"config",
".",
"commandLogging",
")",
"{",
"Log",
".",
"d",
"(",
"config",
".",
"commandLoggingTag",
",... | Waits for an Activity matching the specified class.
@param activityClass the class of the {@code Activity} to wait for. Example is: {@code MyActivity.class}
@param timeout the amount of time in milliseconds to wait
@return {@code true} if {@link Activity} appears before the timeout and {@code false} if it does not | [
"Waits",
"for",
"an",
"Activity",
"matching",
"the",
"specified",
"class",
"."
] | train | https://github.com/RobotiumTech/robotium/blob/75e567c38f26a6a87dc8bef90b3886a20e28d291/robotium-solo/src/main/java/com/robotium/solo/Solo.java#L3623-L3630 |
alkacon/opencms-core | src-gwt/org/opencms/gwt/client/ui/CmsScrollPanelImpl.java | CmsScrollPanelImpl.setVerticalScrollbar | private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {
// Validate.
if ((scrollbar == m_scrollbar) || (scrollbar == null)) {
return;
}
// Detach new child.
scrollbar.asWidget().removeFromParent();
// Remove old child.
if (m_scrollbar != null) {
if (m_verticalScrollbarHandlerRegistration != null) {
m_verticalScrollbarHandlerRegistration.removeHandler();
m_verticalScrollbarHandlerRegistration = null;
}
remove(m_scrollbar);
}
m_scrollLayer.appendChild(scrollbar.asWidget().getElement());
adopt(scrollbar.asWidget());
// Logical attach.
m_scrollbar = scrollbar;
m_verticalScrollbarWidth = width;
// Initialize the new scrollbar.
m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {
public void onValueChange(ValueChangeEvent<Integer> event) {
int vPos = scrollbar.getVerticalScrollPosition();
int v = getVerticalScrollPosition();
if (v != vPos) {
setVerticalScrollPosition(vPos);
}
}
});
maybeUpdateScrollbars();
} | java | private void setVerticalScrollbar(final CmsScrollBar scrollbar, int width) {
// Validate.
if ((scrollbar == m_scrollbar) || (scrollbar == null)) {
return;
}
// Detach new child.
scrollbar.asWidget().removeFromParent();
// Remove old child.
if (m_scrollbar != null) {
if (m_verticalScrollbarHandlerRegistration != null) {
m_verticalScrollbarHandlerRegistration.removeHandler();
m_verticalScrollbarHandlerRegistration = null;
}
remove(m_scrollbar);
}
m_scrollLayer.appendChild(scrollbar.asWidget().getElement());
adopt(scrollbar.asWidget());
// Logical attach.
m_scrollbar = scrollbar;
m_verticalScrollbarWidth = width;
// Initialize the new scrollbar.
m_verticalScrollbarHandlerRegistration = scrollbar.addValueChangeHandler(new ValueChangeHandler<Integer>() {
public void onValueChange(ValueChangeEvent<Integer> event) {
int vPos = scrollbar.getVerticalScrollPosition();
int v = getVerticalScrollPosition();
if (v != vPos) {
setVerticalScrollPosition(vPos);
}
}
});
maybeUpdateScrollbars();
} | [
"private",
"void",
"setVerticalScrollbar",
"(",
"final",
"CmsScrollBar",
"scrollbar",
",",
"int",
"width",
")",
"{",
"// Validate.\r",
"if",
"(",
"(",
"scrollbar",
"==",
"m_scrollbar",
")",
"||",
"(",
"scrollbar",
"==",
"null",
")",
")",
"{",
"return",
";",
... | Set the scrollbar used for vertical scrolling.
@param scrollbar the scrollbar, or null to clear it
@param width the width of the scrollbar in pixels | [
"Set",
"the",
"scrollbar",
"used",
"for",
"vertical",
"scrolling",
"."
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/ui/CmsScrollPanelImpl.java#L416-L454 |
before/quality-check | modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java | Check.isNumeric | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class })
public static <T extends CharSequence> T isNumeric(@Nonnull final T value, @Nullable final String name) {
Check.notNull(value, "value");
if (!matches(NumericRegularExpressionHolder.getPattern(), value)) {
throw new IllegalNumericArgumentException(name, value);
}
return value;
} | java | @ArgumentsChecked
@Throws({ IllegalNullArgumentException.class, IllegalNumericArgumentException.class })
public static <T extends CharSequence> T isNumeric(@Nonnull final T value, @Nullable final String name) {
Check.notNull(value, "value");
if (!matches(NumericRegularExpressionHolder.getPattern(), value)) {
throw new IllegalNumericArgumentException(name, value);
}
return value;
} | [
"@",
"ArgumentsChecked",
"@",
"Throws",
"(",
"{",
"IllegalNullArgumentException",
".",
"class",
",",
"IllegalNumericArgumentException",
".",
"class",
"}",
")",
"public",
"static",
"<",
"T",
"extends",
"CharSequence",
">",
"T",
"isNumeric",
"(",
"@",
"Nonnull",
"... | Ensures that a readable sequence of {@code char} values is numeric. Numeric arguments consist only of the
characters 0-9 and may start with 0 (compared to number arguments, which must be valid numbers - think of a bank
account number).
@param value
a readable sequence of {@code char} values which must be a number
@param name
name of object reference (in source code)
@return the given string argument
@throws IllegalNumberArgumentException
if the given argument {@code value} is no number | [
"Ensures",
"that",
"a",
"readable",
"sequence",
"of",
"{",
"@code",
"char",
"}",
"values",
"is",
"numeric",
".",
"Numeric",
"arguments",
"consist",
"only",
"of",
"the",
"characters",
"0",
"-",
"9",
"and",
"may",
"start",
"with",
"0",
"(",
"compared",
"to... | train | https://github.com/before/quality-check/blob/a75c32c39434ddb1f89bece57acae0536724c15a/modules/quality-check/src/main/java/net/sf/qualitycheck/Check.java#L1348-L1356 |
greenjoe/sergeants | src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java | UpdatableGameState.createInitialGameState | public static UpdatableGameState createInitialGameState(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
return new UpdatableGameState(
firstUpdateData.getTurn(), startData, MapPatcher.patch(firstUpdateData.getMapDiff(), new int[]{}),
MapPatcher.patch(firstUpdateData.getCitiesDiff(), new int[]{}),
firstUpdateData.getGenerals(),
createPlayersInfo(startData, firstUpdateData),
firstUpdateData.getAttackIndex());
} | java | public static UpdatableGameState createInitialGameState(GameStartApiResponse startData, GameUpdateApiResponse firstUpdateData) {
return new UpdatableGameState(
firstUpdateData.getTurn(), startData, MapPatcher.patch(firstUpdateData.getMapDiff(), new int[]{}),
MapPatcher.patch(firstUpdateData.getCitiesDiff(), new int[]{}),
firstUpdateData.getGenerals(),
createPlayersInfo(startData, firstUpdateData),
firstUpdateData.getAttackIndex());
} | [
"public",
"static",
"UpdatableGameState",
"createInitialGameState",
"(",
"GameStartApiResponse",
"startData",
",",
"GameUpdateApiResponse",
"firstUpdateData",
")",
"{",
"return",
"new",
"UpdatableGameState",
"(",
"firstUpdateData",
".",
"getTurn",
"(",
")",
",",
"startDat... | Creates the first game state just after the game is started. Can be done only after both messages are received from server:
{@link GameStartApiResponse} and {@link GameUpdateApiResponse}. Cannot be use for further updates, as later game updates
from server contain only differences. | [
"Creates",
"the",
"first",
"game",
"state",
"just",
"after",
"the",
"game",
"is",
"started",
".",
"Can",
"be",
"done",
"only",
"after",
"both",
"messages",
"are",
"received",
"from",
"server",
":",
"{"
] | train | https://github.com/greenjoe/sergeants/blob/db624bcea8597843210f138b82bc4a26b3ec92ca/src/main/java/pl/joegreen/sergeants/framework/model/api/UpdatableGameState.java#L44-L51 |
jbundle/jbundle | base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/BaseConvertToNative.java | BaseConvertToNative.setPayloadProperty | public void setPayloadProperty(BaseMessage message, Object msg, String strKey, Class<?> classKey)
{
Object data = message.get(strKey);
if (data == null)
return;
this.setPayloadProperty(data, msg, strKey, classKey);
} | java | public void setPayloadProperty(BaseMessage message, Object msg, String strKey, Class<?> classKey)
{
Object data = message.get(strKey);
if (data == null)
return;
this.setPayloadProperty(data, msg, strKey, classKey);
} | [
"public",
"void",
"setPayloadProperty",
"(",
"BaseMessage",
"message",
",",
"Object",
"msg",
",",
"String",
"strKey",
",",
"Class",
"<",
"?",
">",
"classKey",
")",
"{",
"Object",
"data",
"=",
"message",
".",
"get",
"(",
"strKey",
")",
";",
"if",
"(",
"... | Move this standard payload properties from the message to the xml.
@param message
@param msg
@param strKey | [
"Move",
"this",
"standard",
"payload",
"properties",
"from",
"the",
"message",
"to",
"the",
"xml",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/base/message/trx/src/main/java/org/jbundle/base/message/trx/message/external/convert/BaseConvertToNative.java#L196-L202 |
the-fascinator/plugin-roles-internal | src/main/java/com/googlecode/fascinator/roles/internal/InternalRoles.java | InternalRoles.setRole | @Override
public void setRole(String username, String newrole) throws RolesException {
List<String> users_with_role = new ArrayList<String>();
if (user_list.containsKey(username)) {
List<String> roles_of_user = user_list.get(username);
if (!roles_of_user.contains(newrole)) {
// Update our user list
roles_of_user.add(newrole);
user_list.put(username, roles_of_user);
// Update our roles list
if (role_list.containsKey(newrole))
users_with_role = role_list.get(newrole);
users_with_role.add(username);
role_list.put(newrole, users_with_role);
// Don't forget to update our file_store
String roles = StringUtils.join(roles_of_user.toArray(new String[0]), ",");
file_store.setProperty(username, roles);
// And commit the file_store to disk
try {
saveRoles();
} catch (IOException e) {
throw new RolesException(e);
}
} else {
throw new RolesException("User '" + username + "' already has role '" + newrole + "'!");
}
} else {
// Add the user
List<String> empty = new ArrayList<String>();
user_list.put(username, empty);
// Try again
this.setRole(username, newrole);
}
} | java | @Override
public void setRole(String username, String newrole) throws RolesException {
List<String> users_with_role = new ArrayList<String>();
if (user_list.containsKey(username)) {
List<String> roles_of_user = user_list.get(username);
if (!roles_of_user.contains(newrole)) {
// Update our user list
roles_of_user.add(newrole);
user_list.put(username, roles_of_user);
// Update our roles list
if (role_list.containsKey(newrole))
users_with_role = role_list.get(newrole);
users_with_role.add(username);
role_list.put(newrole, users_with_role);
// Don't forget to update our file_store
String roles = StringUtils.join(roles_of_user.toArray(new String[0]), ",");
file_store.setProperty(username, roles);
// And commit the file_store to disk
try {
saveRoles();
} catch (IOException e) {
throw new RolesException(e);
}
} else {
throw new RolesException("User '" + username + "' already has role '" + newrole + "'!");
}
} else {
// Add the user
List<String> empty = new ArrayList<String>();
user_list.put(username, empty);
// Try again
this.setRole(username, newrole);
}
} | [
"@",
"Override",
"public",
"void",
"setRole",
"(",
"String",
"username",
",",
"String",
"newrole",
")",
"throws",
"RolesException",
"{",
"List",
"<",
"String",
">",
"users_with_role",
"=",
"new",
"ArrayList",
"<",
"String",
">",
"(",
")",
";",
"if",
"(",
... | Assign a role to a user.
@param username
The username of the user.
@param newrole
The new role to assign the user.
@throws RolesException
if there was an error during assignment. | [
"Assign",
"a",
"role",
"to",
"a",
"user",
"."
] | train | https://github.com/the-fascinator/plugin-roles-internal/blob/5f75f802a92ef907acf030692d462aec4b4d3aae/src/main/java/com/googlecode/fascinator/roles/internal/InternalRoles.java#L289-L325 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.beanMap | public static Collection beanMap(String property, Object[] objs) {
return beanMap(property, java.util.Arrays.asList(objs), false);
} | java | public static Collection beanMap(String property, Object[] objs) {
return beanMap(property, java.util.Arrays.asList(objs), false);
} | [
"public",
"static",
"Collection",
"beanMap",
"(",
"String",
"property",
",",
"Object",
"[",
"]",
"objs",
")",
"{",
"return",
"beanMap",
"(",
"property",
",",
"java",
".",
"util",
".",
"Arrays",
".",
"asList",
"(",
"objs",
")",
",",
"false",
")",
";",
... | Map dynamically using a bean property name.
@param property the name of a bean property
@param objs an array of objects
@return collection
@throws ClassCastException if there is an error invoking the method on any object. | [
"Map",
"dynamically",
"using",
"a",
"bean",
"property",
"name",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L658-L660 |
wildfly/wildfly-core | host-controller/src/main/java/org/jboss/as/host/controller/mgmt/HostControllerRegistrationHandler.java | HostControllerRegistrationHandler.sendFailedResponse | static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {
final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
final FlushableDataOutput output = context.writeMessage(header);
try {
// This is an error
output.writeByte(DomainControllerProtocol.PARAM_ERROR);
// send error code
output.writeByte(errorCode);
// error message
if (message == null) {
output.writeUTF("unknown error");
} else {
output.writeUTF(message);
}
// response end
output.writeByte(ManagementProtocol.RESPONSE_END);
output.close();
} finally {
StreamUtils.safeClose(output);
}
} | java | static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {
final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
final FlushableDataOutput output = context.writeMessage(header);
try {
// This is an error
output.writeByte(DomainControllerProtocol.PARAM_ERROR);
// send error code
output.writeByte(errorCode);
// error message
if (message == null) {
output.writeUTF("unknown error");
} else {
output.writeUTF(message);
}
// response end
output.writeByte(ManagementProtocol.RESPONSE_END);
output.close();
} finally {
StreamUtils.safeClose(output);
}
} | [
"static",
"void",
"sendFailedResponse",
"(",
"final",
"ManagementRequestContext",
"<",
"RegistrationContext",
">",
"context",
",",
"final",
"byte",
"errorCode",
",",
"final",
"String",
"message",
")",
"throws",
"IOException",
"{",
"final",
"ManagementResponseHeader",
... | Send a failed operation response.
@param context the request context
@param errorCode the error code
@param message the operation message
@throws IOException for any error | [
"Send",
"a",
"failed",
"operation",
"response",
"."
] | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/host-controller/src/main/java/org/jboss/as/host/controller/mgmt/HostControllerRegistrationHandler.java#L745-L765 |
opsmatters/opsmatters-core | src/main/java/com/opsmatters/core/util/StringUtilities.java | StringUtilities.isValidEmailAddress | public static boolean isValidEmailAddress(String email, boolean strict)
{
Pattern p = strict ? strictEmailPattern : laxEmailPattern;
return p.matcher(email).matches();
} | java | public static boolean isValidEmailAddress(String email, boolean strict)
{
Pattern p = strict ? strictEmailPattern : laxEmailPattern;
return p.matcher(email).matches();
} | [
"public",
"static",
"boolean",
"isValidEmailAddress",
"(",
"String",
"email",
",",
"boolean",
"strict",
")",
"{",
"Pattern",
"p",
"=",
"strict",
"?",
"strictEmailPattern",
":",
"laxEmailPattern",
";",
"return",
"p",
".",
"matcher",
"(",
"email",
")",
".",
"m... | Returns <CODE>true</CODE> if the given string is a valid email address.
@param email The email address to be checked
@param strict <CODE>true</CODE> if strict rules should be applied when checking the email address
@return <CODE>true</CODE> if the given string is a valid email address | [
"Returns",
"<CODE",
">",
"true<",
"/",
"CODE",
">",
"if",
"the",
"given",
"string",
"is",
"a",
"valid",
"email",
"address",
"."
] | train | https://github.com/opsmatters/opsmatters-core/blob/c48904f7e8d029fd45357811ec38a735e261e3fd/src/main/java/com/opsmatters/core/util/StringUtilities.java#L612-L616 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfContentByte.java | PdfContentByte.roundRectangle | public void roundRectangle(float x, float y, float w, float h, float r) {
if (w < 0) {
x += w;
w = -w;
}
if (h < 0) {
y += h;
h = -h;
}
if (r < 0)
r = -r;
float b = 0.4477f;
moveTo(x + r, y);
lineTo(x + w - r, y);
curveTo(x + w - r * b, y, x + w, y + r * b, x + w, y + r);
lineTo(x + w, y + h - r);
curveTo(x + w, y + h - r * b, x + w - r * b, y + h, x + w - r, y + h);
lineTo(x + r, y + h);
curveTo(x + r * b, y + h, x, y + h - r * b, x, y + h - r);
lineTo(x, y + r);
curveTo(x, y + r * b, x + r * b, y, x + r, y);
} | java | public void roundRectangle(float x, float y, float w, float h, float r) {
if (w < 0) {
x += w;
w = -w;
}
if (h < 0) {
y += h;
h = -h;
}
if (r < 0)
r = -r;
float b = 0.4477f;
moveTo(x + r, y);
lineTo(x + w - r, y);
curveTo(x + w - r * b, y, x + w, y + r * b, x + w, y + r);
lineTo(x + w, y + h - r);
curveTo(x + w, y + h - r * b, x + w - r * b, y + h, x + w - r, y + h);
lineTo(x + r, y + h);
curveTo(x + r * b, y + h, x, y + h - r * b, x, y + h - r);
lineTo(x, y + r);
curveTo(x, y + r * b, x + r * b, y, x + r, y);
} | [
"public",
"void",
"roundRectangle",
"(",
"float",
"x",
",",
"float",
"y",
",",
"float",
"w",
",",
"float",
"h",
",",
"float",
"r",
")",
"{",
"if",
"(",
"w",
"<",
"0",
")",
"{",
"x",
"+=",
"w",
";",
"w",
"=",
"-",
"w",
";",
"}",
"if",
"(",
... | Adds a round rectangle to the current path.
@param x x-coordinate of the starting point
@param y y-coordinate of the starting point
@param w width
@param h height
@param r radius of the arc corner | [
"Adds",
"a",
"round",
"rectangle",
"to",
"the",
"current",
"path",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfContentByte.java#L2586-L2607 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java | ComputerVisionImpl.analyzeImage | public ImageAnalysis analyzeImage(String url, AnalyzeImageOptionalParameter analyzeImageOptionalParameter) {
return analyzeImageWithServiceResponseAsync(url, analyzeImageOptionalParameter).toBlocking().single().body();
} | java | public ImageAnalysis analyzeImage(String url, AnalyzeImageOptionalParameter analyzeImageOptionalParameter) {
return analyzeImageWithServiceResponseAsync(url, analyzeImageOptionalParameter).toBlocking().single().body();
} | [
"public",
"ImageAnalysis",
"analyzeImage",
"(",
"String",
"url",
",",
"AnalyzeImageOptionalParameter",
"analyzeImageOptionalParameter",
")",
"{",
"return",
"analyzeImageWithServiceResponseAsync",
"(",
"url",
",",
"analyzeImageOptionalParameter",
")",
".",
"toBlocking",
"(",
... | This operation extracts a rich set of visual features based on the image content. Two input methods are supported -- (1) Uploading an image or (2) specifying an image URL. Within your request, there is an optional parameter to allow you to choose which features to return. By default, image categories are returned in the response.
@param url Publicly reachable URL of an image
@param analyzeImageOptionalParameter the object representing the optional parameters to be set before calling this API
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ComputerVisionErrorException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ImageAnalysis object if successful. | [
"This",
"operation",
"extracts",
"a",
"rich",
"set",
"of",
"visual",
"features",
"based",
"on",
"the",
"image",
"content",
".",
"Two",
"input",
"methods",
"are",
"supported",
"--",
"(",
"1",
")",
"Uploading",
"an",
"image",
"or",
"(",
"2",
")",
"specifyi... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/vision/computervision/src/main/java/com/microsoft/azure/cognitiveservices/vision/computervision/implementation/ComputerVisionImpl.java#L2241-L2243 |
OpenLiberty/open-liberty | dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/tai/TAIRequestHelper.java | TAIRequestHelper.requestShouldBeHandledByTAI | public boolean requestShouldBeHandledByTAI(HttpServletRequest request, SocialTaiRequest socialTaiRequest) {
// 241526 don't process jmx requests with this interceptor
if (isJmxConnectorRequest(request)) {
return false;
}
String loginHint = webUtils.getLoginHint(request);
socialTaiRequest = setSocialTaiRequestConfigInfo(request, loginHint, socialTaiRequest);
return socialTaiRequest.hasServices();
} | java | public boolean requestShouldBeHandledByTAI(HttpServletRequest request, SocialTaiRequest socialTaiRequest) {
// 241526 don't process jmx requests with this interceptor
if (isJmxConnectorRequest(request)) {
return false;
}
String loginHint = webUtils.getLoginHint(request);
socialTaiRequest = setSocialTaiRequestConfigInfo(request, loginHint, socialTaiRequest);
return socialTaiRequest.hasServices();
} | [
"public",
"boolean",
"requestShouldBeHandledByTAI",
"(",
"HttpServletRequest",
"request",
",",
"SocialTaiRequest",
"socialTaiRequest",
")",
"{",
"// 241526 don't process jmx requests with this interceptor",
"if",
"(",
"isJmxConnectorRequest",
"(",
"request",
")",
")",
"{",
"r... | Returns whether the provided request should be handled by the social login TAI, based on the request path and information
in the {@link SocialTaiRequest} object provided.
@param request
@param socialTaiRequest
@return | [
"Returns",
"whether",
"the",
"provided",
"request",
"should",
"be",
"handled",
"by",
"the",
"social",
"login",
"TAI",
"based",
"on",
"the",
"request",
"path",
"and",
"information",
"in",
"the",
"{",
"@link",
"SocialTaiRequest",
"}",
"object",
"provided",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.security.social/src/com/ibm/ws/security/social/tai/TAIRequestHelper.java#L53-L61 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java | SDLoss.meanSquaredError | public SDVariable meanSquaredError(String name, @NonNull SDVariable label, @NonNull SDVariable predictions) {
return meanSquaredError(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT);
} | java | public SDVariable meanSquaredError(String name, @NonNull SDVariable label, @NonNull SDVariable predictions) {
return meanSquaredError(name, label, predictions, null, LossReduce.MEAN_BY_NONZERO_WEIGHT_COUNT);
} | [
"public",
"SDVariable",
"meanSquaredError",
"(",
"String",
"name",
",",
"@",
"NonNull",
"SDVariable",
"label",
",",
"@",
"NonNull",
"SDVariable",
"predictions",
")",
"{",
"return",
"meanSquaredError",
"(",
"name",
",",
"label",
",",
"predictions",
",",
"null",
... | See {@link #meanSquaredError(String, SDVariable, SDVariable, SDVariable, LossReduce)}. | [
"See",
"{"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDLoss.java#L355-L357 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java | ElementsExceptionsFactory.newIllegalTypeException | public static IllegalTypeException newIllegalTypeException(Throwable cause, String message, Object... args) {
return new IllegalTypeException(format(message, args), cause);
} | java | public static IllegalTypeException newIllegalTypeException(Throwable cause, String message, Object... args) {
return new IllegalTypeException(format(message, args), cause);
} | [
"public",
"static",
"IllegalTypeException",
"newIllegalTypeException",
"(",
"Throwable",
"cause",
",",
"String",
"message",
",",
"Object",
"...",
"args",
")",
"{",
"return",
"new",
"IllegalTypeException",
"(",
"format",
"(",
"message",
",",
"args",
")",
",",
"ca... | Constructs and initializes a new {@link IllegalTypeException} with the given {@link Throwable cause}
and {@link String message} formatted with the given {@link Object[] arguments}.
@param cause {@link Throwable} identified as the reason this {@link IllegalTypeException} was thrown.
@param message {@link String} describing the {@link IllegalTypeException exception}.
@param args {@link Object[] arguments} used to replace format placeholders in the {@link String message}.
@return a new {@link IllegalTypeException} with the given {@link Throwable cause} and {@link String message}.
@see org.cp.elements.lang.IllegalTypeException | [
"Constructs",
"and",
"initializes",
"a",
"new",
"{",
"@link",
"IllegalTypeException",
"}",
"with",
"the",
"given",
"{",
"@link",
"Throwable",
"cause",
"}",
"and",
"{",
"@link",
"String",
"message",
"}",
"formatted",
"with",
"the",
"given",
"{",
"@link",
"Obj... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ElementsExceptionsFactory.java#L397-L399 |
line/centraldogma | server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java | MetadataService.addToken | public CompletableFuture<Revision> addToken(Author author, String projectName,
Token token, ProjectRole role) {
return addToken(author, projectName, requireNonNull(token, "token").appId(), role);
} | java | public CompletableFuture<Revision> addToken(Author author, String projectName,
Token token, ProjectRole role) {
return addToken(author, projectName, requireNonNull(token, "token").appId(), role);
} | [
"public",
"CompletableFuture",
"<",
"Revision",
">",
"addToken",
"(",
"Author",
"author",
",",
"String",
"projectName",
",",
"Token",
"token",
",",
"ProjectRole",
"role",
")",
"{",
"return",
"addToken",
"(",
"author",
",",
"projectName",
",",
"requireNonNull",
... | Adds the specified {@link Token} to the specified {@code projectName}. | [
"Adds",
"the",
"specified",
"{"
] | train | https://github.com/line/centraldogma/blob/b9e46c67fbc26628c2186ce2f46e7fb303c831e9/server/src/main/java/com/linecorp/centraldogma/server/internal/metadata/MetadataService.java#L326-L329 |
lastaflute/lastaflute | src/main/java/org/lastaflute/web/hook/GodHandEpilogue.java | GodHandEpilogue.handleSqlCount | protected void handleSqlCount(ActionRuntime runtime) {
final CallbackContext context = CallbackContext.getCallbackContextOnThread();
if (context == null) {
return;
}
final SqlStringFilter filter = context.getSqlStringFilter();
if (filter == null || !(filter instanceof ExecutedSqlCounter)) {
return;
}
final ExecutedSqlCounter counter = ((ExecutedSqlCounter) filter);
final int sqlExecutionCountLimit = getSqlExecutionCountLimit(runtime);
if (sqlExecutionCountLimit >= 0 && counter.getTotalCountOfSql() > sqlExecutionCountLimit) {
// minus means no check here, by-annotation cannot specify it, can only as default limit
// if it needs to specify it by-annotation, enough to set large size
handleTooManySqlExecution(runtime, counter, sqlExecutionCountLimit);
}
saveRequestedSqlCount(counter);
} | java | protected void handleSqlCount(ActionRuntime runtime) {
final CallbackContext context = CallbackContext.getCallbackContextOnThread();
if (context == null) {
return;
}
final SqlStringFilter filter = context.getSqlStringFilter();
if (filter == null || !(filter instanceof ExecutedSqlCounter)) {
return;
}
final ExecutedSqlCounter counter = ((ExecutedSqlCounter) filter);
final int sqlExecutionCountLimit = getSqlExecutionCountLimit(runtime);
if (sqlExecutionCountLimit >= 0 && counter.getTotalCountOfSql() > sqlExecutionCountLimit) {
// minus means no check here, by-annotation cannot specify it, can only as default limit
// if it needs to specify it by-annotation, enough to set large size
handleTooManySqlExecution(runtime, counter, sqlExecutionCountLimit);
}
saveRequestedSqlCount(counter);
} | [
"protected",
"void",
"handleSqlCount",
"(",
"ActionRuntime",
"runtime",
")",
"{",
"final",
"CallbackContext",
"context",
"=",
"CallbackContext",
".",
"getCallbackContextOnThread",
"(",
")",
";",
"if",
"(",
"context",
"==",
"null",
")",
"{",
"return",
";",
"}",
... | Handle count of SQL execution in the request.
@param runtime The runtime meta of action execute. (NotNull) | [
"Handle",
"count",
"of",
"SQL",
"execution",
"in",
"the",
"request",
"."
] | train | https://github.com/lastaflute/lastaflute/blob/17b56dda8322e4c6d79043532c1dda917d6b60a8/src/main/java/org/lastaflute/web/hook/GodHandEpilogue.java#L89-L106 |
craftercms/profile | security-provider/src/main/java/org/craftercms/security/processors/impl/SecurityExceptionProcessor.java | SecurityExceptionProcessor.handleAccessDeniedException | protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
SecurityProviderException, IOException {
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
// If user is anonymous, authentication is required
if (auth == null) {
try {
// Throw ex just to initialize stack trace
throw new AuthenticationRequiredException("Authentication required to access the resource", e);
} catch (AuthenticationRequiredException ae) {
logger.debug("Authentication is required", ae);
authenticationRequiredHandler.handle(context, ae);
}
} else {
logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e);
accessDeniedHandler.handle(context, e);
}
} | java | protected void handleAccessDeniedException(RequestContext context, AccessDeniedException e) throws
SecurityProviderException, IOException {
Authentication auth = SecurityUtils.getAuthentication(context.getRequest());
// If user is anonymous, authentication is required
if (auth == null) {
try {
// Throw ex just to initialize stack trace
throw new AuthenticationRequiredException("Authentication required to access the resource", e);
} catch (AuthenticationRequiredException ae) {
logger.debug("Authentication is required", ae);
authenticationRequiredHandler.handle(context, ae);
}
} else {
logger.debug("Access denied to user '" + auth.getProfile().getUsername() + "'", e);
accessDeniedHandler.handle(context, e);
}
} | [
"protected",
"void",
"handleAccessDeniedException",
"(",
"RequestContext",
"context",
",",
"AccessDeniedException",
"e",
")",
"throws",
"SecurityProviderException",
",",
"IOException",
"{",
"Authentication",
"auth",
"=",
"SecurityUtils",
".",
"getAuthentication",
"(",
"co... | Handles the specified {@link AccessDeniedException}, by calling the {@link AccessDeniedHandler}. | [
"Handles",
"the",
"specified",
"{"
] | train | https://github.com/craftercms/profile/blob/d829c1136b0fd21d87dc925cb7046cbd38a300a4/security-provider/src/main/java/org/craftercms/security/processors/impl/SecurityExceptionProcessor.java#L127-L145 |
Azure/azure-sdk-for-java | servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java | ClientFactory.createMessageReceiverFromEntityPathAsync | public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath, ReceiveMode receiveMode) {
return createMessageReceiverFromEntityPathAsync(messagingFactory, entityPath, null, receiveMode);
} | java | public static CompletableFuture<IMessageReceiver> createMessageReceiverFromEntityPathAsync(MessagingFactory messagingFactory, String entityPath, ReceiveMode receiveMode) {
return createMessageReceiverFromEntityPathAsync(messagingFactory, entityPath, null, receiveMode);
} | [
"public",
"static",
"CompletableFuture",
"<",
"IMessageReceiver",
">",
"createMessageReceiverFromEntityPathAsync",
"(",
"MessagingFactory",
"messagingFactory",
",",
"String",
"entityPath",
",",
"ReceiveMode",
"receiveMode",
")",
"{",
"return",
"createMessageReceiverFromEntityPa... | Asynchronously creates a new message receiver to the entity on the messagingFactory.
@param messagingFactory messaging factory (which represents a connection) on which receiver needs to be created.
@param entityPath path of entity
@param receiveMode PeekLock or ReceiveAndDelete
@return a CompletableFuture representing the pending creation of message receiver | [
"Asynchronously",
"creates",
"a",
"new",
"message",
"receiver",
"to",
"the",
"entity",
"on",
"the",
"messagingFactory",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/servicebus/data-plane/azure-servicebus/src/main/java/com/microsoft/azure/servicebus/ClientFactory.java#L466-L468 |
overturetool/overture | core/interpreter/src/main/java/CSV.java | CSV.freadval | public static Value freadval(Value fval, Value indexVal)
{
ValueList result = new ValueList();
try
{
File file = getFile(fval);
long index = indexVal.intValue(null);
SeqValue lineCells = new SeqValue();
boolean success = false;
try
{
CsvParser parser = new CsvParser(new CsvValueBuilder()
{
@Override
public Value createValue(String value)
throws Exception
{
return CSV.createValue("CSV", "freadval", value);
}
});
CsvResult res = parser.parseValues(getLine(file, index));
if(!res.dataOk())
{
lastError = res.getErrorMsg();
success = false;
}
else
{
lineCells.values.addAll(res.getValues());
success = true;
}
} catch (Exception e)
{
success = false;
lastError = e.getMessage();
// OK
}
result.add(new BooleanValue(success));
result.add(lineCells);
} catch (Exception e)
{
lastError = e.toString();
result = new ValueList();
result.add(new BooleanValue(false));
result.add(new NilValue());
}
return new TupleValue(result);
} | java | public static Value freadval(Value fval, Value indexVal)
{
ValueList result = new ValueList();
try
{
File file = getFile(fval);
long index = indexVal.intValue(null);
SeqValue lineCells = new SeqValue();
boolean success = false;
try
{
CsvParser parser = new CsvParser(new CsvValueBuilder()
{
@Override
public Value createValue(String value)
throws Exception
{
return CSV.createValue("CSV", "freadval", value);
}
});
CsvResult res = parser.parseValues(getLine(file, index));
if(!res.dataOk())
{
lastError = res.getErrorMsg();
success = false;
}
else
{
lineCells.values.addAll(res.getValues());
success = true;
}
} catch (Exception e)
{
success = false;
lastError = e.getMessage();
// OK
}
result.add(new BooleanValue(success));
result.add(lineCells);
} catch (Exception e)
{
lastError = e.toString();
result = new ValueList();
result.add(new BooleanValue(false));
result.add(new NilValue());
}
return new TupleValue(result);
} | [
"public",
"static",
"Value",
"freadval",
"(",
"Value",
"fval",
",",
"Value",
"indexVal",
")",
"{",
"ValueList",
"result",
"=",
"new",
"ValueList",
"(",
")",
";",
"try",
"{",
"File",
"file",
"=",
"getFile",
"(",
"fval",
")",
";",
"long",
"index",
"=",
... | Read a CSV live as a seq of ? in VDM
@param fval
name of the file to read from
@param indexVal
the line index
@return true + seq of ? or false and nil | [
"Read",
"a",
"CSV",
"live",
"as",
"a",
"seq",
"of",
"?",
"in",
"VDM"
] | train | https://github.com/overturetool/overture/blob/83175dc6c24fa171cde4fcf61ecb648eba3bdbc1/core/interpreter/src/main/java/CSV.java#L99-L152 |
aspectran/aspectran | core/src/main/java/com/aspectran/core/util/ResourceUtils.java | ResourceUtils.getResource | public static URL getResource(String resource, ClassLoader classLoader) throws IOException {
URL url = null;
if (classLoader != null) {
url = classLoader.getResource(resource);
}
if (url == null) {
url = ClassLoader.getSystemResource(resource);
}
if (url == null) {
throw new IOException("Could not find resource '" + resource + "'");
}
return url;
} | java | public static URL getResource(String resource, ClassLoader classLoader) throws IOException {
URL url = null;
if (classLoader != null) {
url = classLoader.getResource(resource);
}
if (url == null) {
url = ClassLoader.getSystemResource(resource);
}
if (url == null) {
throw new IOException("Could not find resource '" + resource + "'");
}
return url;
} | [
"public",
"static",
"URL",
"getResource",
"(",
"String",
"resource",
",",
"ClassLoader",
"classLoader",
")",
"throws",
"IOException",
"{",
"URL",
"url",
"=",
"null",
";",
"if",
"(",
"classLoader",
"!=",
"null",
")",
"{",
"url",
"=",
"classLoader",
".",
"ge... | Returns the URL of the resource on the classpath.
@param classLoader the class loader used to load the resource
@param resource the resource to find
@return {@code URL} object for reading the resource;
{@code null} if the resource could not be found
@throws IOException if the resource cannot be found or read | [
"Returns",
"the",
"URL",
"of",
"the",
"resource",
"on",
"the",
"classpath",
"."
] | train | https://github.com/aspectran/aspectran/blob/2d758a2a28b71ee85b42823c12dc44674d7f2c70/core/src/main/java/com/aspectran/core/util/ResourceUtils.java#L229-L241 |
datasalt/pangool | core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java | InstancesDistributor.removeFromCache | public static void removeFromCache(Configuration conf, String filename) throws IOException {
FileSystem fS = FileSystem.get(conf);
fS.delete(locateFileInCache(conf, filename), true);
} | java | public static void removeFromCache(Configuration conf, String filename) throws IOException {
FileSystem fS = FileSystem.get(conf);
fS.delete(locateFileInCache(conf, filename), true);
} | [
"public",
"static",
"void",
"removeFromCache",
"(",
"Configuration",
"conf",
",",
"String",
"filename",
")",
"throws",
"IOException",
"{",
"FileSystem",
"fS",
"=",
"FileSystem",
".",
"get",
"(",
"conf",
")",
";",
"fS",
".",
"delete",
"(",
"locateFileInCache",
... | Delete a file that has been distributed using
{@link #distribute(Object, String, Configuration)}. | [
"Delete",
"a",
"file",
"that",
"has",
"been",
"distributed",
"using",
"{"
] | train | https://github.com/datasalt/pangool/blob/bfd312dd78cba03febaf7988ae96a3d4bc585408/core/src/main/java/com/datasalt/pangool/utils/InstancesDistributor.java#L157-L160 |
marvinlabs/android-intents | library/src/main/java/com/marvinlabs/intents/SystemIntents.java | SystemIntents.newGooglePlayIntent | public static Intent newGooglePlayIntent(Context context, String packageName) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
if (!IntentUtils.isIntentAvailable(context, intent)) {
intent = MediaIntents.newOpenWebBrowserIntent("https://play.google.com/store/apps/details?id="
+ packageName);
}
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
return intent;
} | java | public static Intent newGooglePlayIntent(Context context, String packageName) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageName));
if (!IntentUtils.isIntentAvailable(context, intent)) {
intent = MediaIntents.newOpenWebBrowserIntent("https://play.google.com/store/apps/details?id="
+ packageName);
}
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
}
return intent;
} | [
"public",
"static",
"Intent",
"newGooglePlayIntent",
"(",
"Context",
"context",
",",
"String",
"packageName",
")",
"{",
"Intent",
"intent",
"=",
"new",
"Intent",
"(",
"Intent",
".",
"ACTION_VIEW",
",",
"Uri",
".",
"parse",
"(",
"\"market://details?id=\"",
"+",
... | Intent that should open either the Google Play app or if not available, the web browser on the Google Play website
@param context The context associated to the application
@param packageName The package name of the application to find on the market
@return the intent for native application or an intent to redirect to the browser if google play is not installed | [
"Intent",
"that",
"should",
"open",
"either",
"the",
"Google",
"Play",
"app",
"or",
"if",
"not",
"available",
"the",
"web",
"browser",
"on",
"the",
"Google",
"Play",
"website"
] | train | https://github.com/marvinlabs/android-intents/blob/33e79c825188b6a97601869522533cc825801f6e/library/src/main/java/com/marvinlabs/intents/SystemIntents.java#L70-L83 |
akamai/AkamaiOPEN-edgegrid-java | edgegrid-signer-core/src/main/java/com/akamai/edgegrid/signer/EdgeGridV1Signer.java | EdgeGridV1Signer.getSignature | public String getSignature(Request request, ClientCredential credential)
throws RequestSigningException {
return getSignature(request, credential, System.currentTimeMillis(), generateNonce());
} | java | public String getSignature(Request request, ClientCredential credential)
throws RequestSigningException {
return getSignature(request, credential, System.currentTimeMillis(), generateNonce());
} | [
"public",
"String",
"getSignature",
"(",
"Request",
"request",
",",
"ClientCredential",
"credential",
")",
"throws",
"RequestSigningException",
"{",
"return",
"getSignature",
"(",
"request",
",",
"credential",
",",
"System",
".",
"currentTimeMillis",
"(",
")",
",",
... | Generates signature for a given HTTP request and client credential. The result of this method
call should be appended as the "Authorization" header to an HTTP request.
@param request a HTTP request to sign
@param credential client credential used to sign a request
@return signature for Authorization HTTP header
@throws RequestSigningException if signing of a given request failed
@throws NullPointerException if {@code request} or {@code credential} is {@code null}
@throws IllegalArgumentException if request contains multiple request headers with the same
header name | [
"Generates",
"signature",
"for",
"a",
"given",
"HTTP",
"request",
"and",
"client",
"credential",
".",
"The",
"result",
"of",
"this",
"method",
"call",
"should",
"be",
"appended",
"as",
"the",
"Authorization",
"header",
"to",
"an",
"HTTP",
"request",
"."
] | train | https://github.com/akamai/AkamaiOPEN-edgegrid-java/blob/29aa39f0f70f62503e6a434c4470ee25cb640f58/edgegrid-signer-core/src/main/java/com/akamai/edgegrid/signer/EdgeGridV1Signer.java#L111-L114 |
Azure/azure-sdk-for-java | applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ComponentQuotaStatusInner.java | ComponentQuotaStatusInner.get | public ApplicationInsightsComponentQuotaStatusInner get(String resourceGroupName, String resourceName) {
return getWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | java | public ApplicationInsightsComponentQuotaStatusInner get(String resourceGroupName, String resourceName) {
return getWithServiceResponseAsync(resourceGroupName, resourceName).toBlocking().single().body();
} | [
"public",
"ApplicationInsightsComponentQuotaStatusInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"resourceName",
")",
".",
"toBlocking",
"(",
")",
".",
"... | Returns daily data volume cap (quota) status for an Application Insights component.
@param resourceGroupName The name of the resource group.
@param resourceName The name of the Application Insights component resource.
@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 ApplicationInsightsComponentQuotaStatusInner object if successful. | [
"Returns",
"daily",
"data",
"volume",
"cap",
"(",
"quota",
")",
"status",
"for",
"an",
"Application",
"Insights",
"component",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/applicationinsights/resource-manager/v2015_05_01/src/main/java/com/microsoft/azure/management/applicationinsights/v2015_05_01/implementation/ComponentQuotaStatusInner.java#L70-L72 |
structurizr/java | structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java | Arc42DocumentationTemplate.addGlossarySection | public Section addGlossarySection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Glossary", files);
} | java | public Section addGlossarySection(SoftwareSystem softwareSystem, File... files) throws IOException {
return addSection(softwareSystem, "Glossary", files);
} | [
"public",
"Section",
"addGlossarySection",
"(",
"SoftwareSystem",
"softwareSystem",
",",
"File",
"...",
"files",
")",
"throws",
"IOException",
"{",
"return",
"addSection",
"(",
"softwareSystem",
",",
"\"Glossary\"",
",",
"files",
")",
";",
"}"
] | Adds a "Glossary" section relating to a {@link SoftwareSystem} from one or more files.
@param softwareSystem the {@link SoftwareSystem} the documentation content relates to
@param files one or more File objects that point to the documentation content
@return a documentation {@link Section}
@throws IOException if there is an error reading the files | [
"Adds",
"a",
"Glossary",
"section",
"relating",
"to",
"a",
"{",
"@link",
"SoftwareSystem",
"}",
"from",
"one",
"or",
"more",
"files",
"."
] | train | https://github.com/structurizr/java/blob/4b204f077877a24bcac363f5ecf0e129a0f9f4c5/structurizr-core/src/com/structurizr/documentation/Arc42DocumentationTemplate.java#L313-L315 |
alkacon/opencms-core | src/org/opencms/main/OpenCmsCore.java | OpenCmsCore.initCmsObject | protected CmsObject initCmsObject(CmsObject adminCms, CmsContextInfo contextInfo)
throws CmsRoleViolationException, CmsException {
String userName = contextInfo.getUserName();
if ((adminCms == null) || !m_roleManager.hasRole(adminCms, CmsRole.ROOT_ADMIN)) {
if (!userName.endsWith(getDefaultUsers().getUserGuest())
&& !userName.endsWith(getDefaultUsers().getUserExport())) {
// if no admin object is provided, only "Guest" or "Export" user can be generated
CmsMessageContainer message = Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
userName,
((adminCms != null) ? (adminCms.getRequestContext().getCurrentUser().getName()) : ""));
if (LOG.isWarnEnabled()) {
LOG.warn(message.key());
}
throw new CmsRoleViolationException(message);
}
}
return initCmsObject(contextInfo);
} | java | protected CmsObject initCmsObject(CmsObject adminCms, CmsContextInfo contextInfo)
throws CmsRoleViolationException, CmsException {
String userName = contextInfo.getUserName();
if ((adminCms == null) || !m_roleManager.hasRole(adminCms, CmsRole.ROOT_ADMIN)) {
if (!userName.endsWith(getDefaultUsers().getUserGuest())
&& !userName.endsWith(getDefaultUsers().getUserExport())) {
// if no admin object is provided, only "Guest" or "Export" user can be generated
CmsMessageContainer message = Messages.get().container(
Messages.ERR_INVALID_INIT_USER_2,
userName,
((adminCms != null) ? (adminCms.getRequestContext().getCurrentUser().getName()) : ""));
if (LOG.isWarnEnabled()) {
LOG.warn(message.key());
}
throw new CmsRoleViolationException(message);
}
}
return initCmsObject(contextInfo);
} | [
"protected",
"CmsObject",
"initCmsObject",
"(",
"CmsObject",
"adminCms",
",",
"CmsContextInfo",
"contextInfo",
")",
"throws",
"CmsRoleViolationException",
",",
"CmsException",
"{",
"String",
"userName",
"=",
"contextInfo",
".",
"getUserName",
"(",
")",
";",
"if",
"(... | Returns an initialized CmsObject with the user and context initialized as provided.<p>
Note: Only if the provided <code>adminCms</code> CmsObject has admin permissions,
this method allows the creation a CmsObject for any existing user. Otherwise
only the default users 'Guest' and 'Export' can initialized with
this method, all other user names will throw an Exception.<p>
@param adminCms must either be initialized with "Admin" permissions, or null
@param contextInfo the context info to create a CmsObject for
@return an initialized CmsObject with the given users permissions
@throws CmsException if an invalid user name was provided
@throws CmsRoleViolationException if the current user does not have the role permissions to create a context for the requested user
@see org.opencms.db.CmsDefaultUsers#getUserGuest()
@see org.opencms.db.CmsDefaultUsers#getUserExport()
@see OpenCms#initCmsObject(CmsObject)
@see OpenCms#initCmsObject(CmsObject, CmsContextInfo)
@see OpenCms#initCmsObject(String) | [
"Returns",
"an",
"initialized",
"CmsObject",
"with",
"the",
"user",
"and",
"context",
"initialized",
"as",
"provided",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/OpenCmsCore.java#L1046-L1068 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java | Types.asOuterSuper | public Type asOuterSuper(Type t, Symbol sym) {
switch (t.getTag()) {
case CLASS:
do {
Type s = asSuper(t, sym);
if (s != null) return s;
t = t.getEnclosingType();
} while (t.hasTag(CLASS));
return null;
case ARRAY:
return isSubtype(t, sym.type) ? sym.type : null;
case TYPEVAR:
return asSuper(t, sym);
case ERROR:
return t;
default:
return null;
}
} | java | public Type asOuterSuper(Type t, Symbol sym) {
switch (t.getTag()) {
case CLASS:
do {
Type s = asSuper(t, sym);
if (s != null) return s;
t = t.getEnclosingType();
} while (t.hasTag(CLASS));
return null;
case ARRAY:
return isSubtype(t, sym.type) ? sym.type : null;
case TYPEVAR:
return asSuper(t, sym);
case ERROR:
return t;
default:
return null;
}
} | [
"public",
"Type",
"asOuterSuper",
"(",
"Type",
"t",
",",
"Symbol",
"sym",
")",
"{",
"switch",
"(",
"t",
".",
"getTag",
"(",
")",
")",
"{",
"case",
"CLASS",
":",
"do",
"{",
"Type",
"s",
"=",
"asSuper",
"(",
"t",
",",
"sym",
")",
";",
"if",
"(",
... | Return the base type of t or any of its outer types that starts
with the given symbol. If none exists, return null.
@param t a type
@param sym a symbol | [
"Return",
"the",
"base",
"type",
"of",
"t",
"or",
"any",
"of",
"its",
"outer",
"types",
"that",
"starts",
"with",
"the",
"given",
"symbol",
".",
"If",
"none",
"exists",
"return",
"null",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Types.java#L1923-L1941 |
lucee/Lucee | core/src/main/java/lucee/commons/lang/StringUtil.java | StringUtil.startsWith | public static boolean startsWith(String str, char prefix) {
return str != null && str.length() > 0 && str.charAt(0) == prefix;
} | java | public static boolean startsWith(String str, char prefix) {
return str != null && str.length() > 0 && str.charAt(0) == prefix;
} | [
"public",
"static",
"boolean",
"startsWith",
"(",
"String",
"str",
",",
"char",
"prefix",
")",
"{",
"return",
"str",
"!=",
"null",
"&&",
"str",
".",
"length",
"(",
")",
">",
"0",
"&&",
"str",
".",
"charAt",
"(",
"0",
")",
"==",
"prefix",
";",
"}"
] | Tests if this string starts with the specified prefix.
@param str string to check first char
@param prefix the prefix.
@return is first of given type | [
"Tests",
"if",
"this",
"string",
"starts",
"with",
"the",
"specified",
"prefix",
"."
] | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/lang/StringUtil.java#L851-L853 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java | JSONConverter.readAttributeList | public AttributeList readAttributeList(InputStream in) throws ConversionException, IOException, ClassNotFoundException {
JSONArray json = parseArray(in);
AttributeList ret = new AttributeList();
for (Object item : json) {
if (!(item instanceof JSONObject)) {
throwConversionException("readAttributeList() receives an items that's not a JSONObject.", item);
}
JSONObject jo = (JSONObject) item;
String name = readStringInternal(jo.get(N_NAME));
Object value = readPOJOInternal(jo.get(N_VALUE));
ret.add(new Attribute(name, value));
}
return ret;
} | java | public AttributeList readAttributeList(InputStream in) throws ConversionException, IOException, ClassNotFoundException {
JSONArray json = parseArray(in);
AttributeList ret = new AttributeList();
for (Object item : json) {
if (!(item instanceof JSONObject)) {
throwConversionException("readAttributeList() receives an items that's not a JSONObject.", item);
}
JSONObject jo = (JSONObject) item;
String name = readStringInternal(jo.get(N_NAME));
Object value = readPOJOInternal(jo.get(N_VALUE));
ret.add(new Attribute(name, value));
}
return ret;
} | [
"public",
"AttributeList",
"readAttributeList",
"(",
"InputStream",
"in",
")",
"throws",
"ConversionException",
",",
"IOException",
",",
"ClassNotFoundException",
"{",
"JSONArray",
"json",
"=",
"parseArray",
"(",
"in",
")",
";",
"AttributeList",
"ret",
"=",
"new",
... | Decode a JSON document to retrieve an AttributeList instance.
@param in The stream to read JSON from
@return The decoded AttributeList instance
@throws ConversionException If JSON uses unexpected structure/format
@throws IOException If an I/O error occurs or if JSON is ill-formed.
@throws ClassNotFoundException If needed class can't be found.
@see #writeAttributeList(OutputStream, AttributeList) | [
"Decode",
"a",
"JSON",
"document",
"to",
"retrieve",
"an",
"AttributeList",
"instance",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java#L1375-L1388 |
google/error-prone-javac | src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java | AbstractIndexWriter.addDescription | protected void addDescription(TypeElement typeElement, Content dlTree, SearchIndexItem si) {
Content link = getLink(new LinkInfoImpl(configuration,
LinkInfoImpl.Kind.INDEX, typeElement).strong(true));
si.setContainingPackage(utils.getPackageName(utils.containingPackage(typeElement)));
si.setLabel(utils.getSimpleName(typeElement));
si.setCategory(resources.getText("doclet.Types"));
Content dt = HtmlTree.DT(link);
dt.addContent(" - ");
addClassInfo(typeElement, dt);
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addComment(typeElement, dd);
dlTree.addContent(dd);
} | java | protected void addDescription(TypeElement typeElement, Content dlTree, SearchIndexItem si) {
Content link = getLink(new LinkInfoImpl(configuration,
LinkInfoImpl.Kind.INDEX, typeElement).strong(true));
si.setContainingPackage(utils.getPackageName(utils.containingPackage(typeElement)));
si.setLabel(utils.getSimpleName(typeElement));
si.setCategory(resources.getText("doclet.Types"));
Content dt = HtmlTree.DT(link);
dt.addContent(" - ");
addClassInfo(typeElement, dt);
dlTree.addContent(dt);
Content dd = new HtmlTree(HtmlTag.DD);
addComment(typeElement, dd);
dlTree.addContent(dd);
} | [
"protected",
"void",
"addDescription",
"(",
"TypeElement",
"typeElement",
",",
"Content",
"dlTree",
",",
"SearchIndexItem",
"si",
")",
"{",
"Content",
"link",
"=",
"getLink",
"(",
"new",
"LinkInfoImpl",
"(",
"configuration",
",",
"LinkInfoImpl",
".",
"Kind",
"."... | Add one line summary comment for the class.
@param typeElement the class being documented
@param dlTree the content tree to which the description will be added
@param si the search index item to be updated | [
"Add",
"one",
"line",
"summary",
"comment",
"for",
"the",
"class",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/AbstractIndexWriter.java#L272-L285 |
google/auto | common/src/main/java/com/google/auto/common/MoreElements.java | MoreElements.isAnnotationPresent | public static boolean isAnnotationPresent(Element element,
Class<? extends Annotation> annotationClass) {
return getAnnotationMirror(element, annotationClass).isPresent();
} | java | public static boolean isAnnotationPresent(Element element,
Class<? extends Annotation> annotationClass) {
return getAnnotationMirror(element, annotationClass).isPresent();
} | [
"public",
"static",
"boolean",
"isAnnotationPresent",
"(",
"Element",
"element",
",",
"Class",
"<",
"?",
"extends",
"Annotation",
">",
"annotationClass",
")",
"{",
"return",
"getAnnotationMirror",
"(",
"element",
",",
"annotationClass",
")",
".",
"isPresent",
"(",... | Returns {@code true} iff the given element has an {@link AnnotationMirror} whose
{@linkplain AnnotationMirror#getAnnotationType() annotation type} has the same canonical name
as that of {@code annotationClass}. This method is a safer alternative to calling
{@link Element#getAnnotation} and checking for {@code null} as it avoids any interaction with
annotation proxies. | [
"Returns",
"{"
] | train | https://github.com/google/auto/blob/4158a5fa71f1ef763e683b627f4d29bc04cfde9d/common/src/main/java/com/google/auto/common/MoreElements.java#L220-L223 |
smartsheet-platform/smartsheet-java-sdk | src/main/java/com/smartsheet/api/SmartsheetFactory.java | SmartsheetFactory.createDefaultClient | public static Smartsheet createDefaultClient() {
String accessToken = System.getenv("SMARTSHEET_ACCESS_TOKEN");
SmartsheetImpl smartsheet = new SmartsheetImpl(DEFAULT_BASE_URI, accessToken);
return smartsheet;
} | java | public static Smartsheet createDefaultClient() {
String accessToken = System.getenv("SMARTSHEET_ACCESS_TOKEN");
SmartsheetImpl smartsheet = new SmartsheetImpl(DEFAULT_BASE_URI, accessToken);
return smartsheet;
} | [
"public",
"static",
"Smartsheet",
"createDefaultClient",
"(",
")",
"{",
"String",
"accessToken",
"=",
"System",
".",
"getenv",
"(",
"\"SMARTSHEET_ACCESS_TOKEN\"",
")",
";",
"SmartsheetImpl",
"smartsheet",
"=",
"new",
"SmartsheetImpl",
"(",
"DEFAULT_BASE_URI",
",",
"... | <p>Creates a Smartsheet client with default parameters. SMARTSHEET_ACCESS_TOKEN
must be set in the environment.</p>
@return the Smartsheet client | [
"<p",
">",
"Creates",
"a",
"Smartsheet",
"client",
"with",
"default",
"parameters",
".",
"SMARTSHEET_ACCESS_TOKEN",
"must",
"be",
"set",
"in",
"the",
"environment",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/SmartsheetFactory.java#L47-L51 |
js-lib-com/template.xhtml | src/main/java/js/template/xhtml/NumberingOperator.java | NumberingOperator.getNumberingFormat | public static NumberingFormat getNumberingFormat(char formatCode)
{
switch(formatCode) {
case 'n':
return new ArabicNumeralNumbering();
case 's':
return new LowerCaseStringNumbering();
case 'S':
return new UpperCaseStringNumbering();
case 'i':
return new LowerCaseRomanNumbering();
case 'I':
return new UpperCaseRomanNumbering();
}
throw new TemplateException("Invalid numbering format code |%s|.", formatCode);
} | java | public static NumberingFormat getNumberingFormat(char formatCode)
{
switch(formatCode) {
case 'n':
return new ArabicNumeralNumbering();
case 's':
return new LowerCaseStringNumbering();
case 'S':
return new UpperCaseStringNumbering();
case 'i':
return new LowerCaseRomanNumbering();
case 'I':
return new UpperCaseRomanNumbering();
}
throw new TemplateException("Invalid numbering format code |%s|.", formatCode);
} | [
"public",
"static",
"NumberingFormat",
"getNumberingFormat",
"(",
"char",
"formatCode",
")",
"{",
"switch",
"(",
"formatCode",
")",
"{",
"case",
"'",
"'",
":",
"return",
"new",
"ArabicNumeralNumbering",
"(",
")",
";",
"case",
"'",
"'",
":",
"return",
"new",
... | Factory method for numbering format implementations. If format code is not recognized throws templates exception; anyway
validation tool catches this condition. See {@link NumberingFormat} for the list of valid format codes.
@param formatCode single char format code.
@return requested numbering format instance.
@throws TemplateException if format code is not recognized. | [
"Factory",
"method",
"for",
"numbering",
"format",
"implementations",
".",
"If",
"format",
"code",
"is",
"not",
"recognized",
"throws",
"templates",
"exception",
";",
"anyway",
"validation",
"tool",
"catches",
"this",
"condition",
".",
"See",
"{",
"@link",
"Numb... | train | https://github.com/js-lib-com/template.xhtml/blob/d50cec08aca9ab9680baebe2a26a341c096564fb/src/main/java/js/template/xhtml/NumberingOperator.java#L147-L162 |
beckchr/juel | modules/api/src/main/java/javax/el/ELContext.java | ELContext.putContext | public void putContext(Class<?> key, Object contextObject) {
if (key == null) {
throw new NullPointerException("key is null");
}
if (context == null) {
context = new HashMap<Class<?>, Object>();
}
context.put(key, contextObject);
} | java | public void putContext(Class<?> key, Object contextObject) {
if (key == null) {
throw new NullPointerException("key is null");
}
if (context == null) {
context = new HashMap<Class<?>, Object>();
}
context.put(key, contextObject);
} | [
"public",
"void",
"putContext",
"(",
"Class",
"<",
"?",
">",
"key",
",",
"Object",
"contextObject",
")",
"{",
"if",
"(",
"key",
"==",
"null",
")",
"{",
"throw",
"new",
"NullPointerException",
"(",
"\"key is null\"",
")",
";",
"}",
"if",
"(",
"context",
... | Associates a context object with this ELContext. The ELContext maintains a collection of
context objects relevant to the evaluation of an expression. These context objects are used
by ELResolvers. This method is used to add a context object to that collection. By
convention, the contextObject will be of the type specified by the key. However, this is not
required and the key is used strictly as a unique identifier.
@param key
The key used by an {@link ELResolver} to identify this context object.
@param contextObject
The context object to add to the collection.
@throws NullPointerException
if key is null or contextObject is null. | [
"Associates",
"a",
"context",
"object",
"with",
"this",
"ELContext",
".",
"The",
"ELContext",
"maintains",
"a",
"collection",
"of",
"context",
"objects",
"relevant",
"to",
"the",
"evaluation",
"of",
"an",
"expression",
".",
"These",
"context",
"objects",
"are",
... | train | https://github.com/beckchr/juel/blob/1a8fb366b7349ddae81f806dee1ab2de11b672c7/modules/api/src/main/java/javax/el/ELContext.java#L138-L146 |
ujmp/universal-java-matrix-package | ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java | Ginv.addRowTimes | public static void addRowTimes(double[][] matrix, int diag, int fromCol, int row, double factor) {
int cols = matrix[0].length;
double[] d = matrix[diag];
double[] r = matrix[row];
for (int col = fromCol; col < cols; col++) {
r[col] -= factor * d[col];
}
} | java | public static void addRowTimes(double[][] matrix, int diag, int fromCol, int row, double factor) {
int cols = matrix[0].length;
double[] d = matrix[diag];
double[] r = matrix[row];
for (int col = fromCol; col < cols; col++) {
r[col] -= factor * d[col];
}
} | [
"public",
"static",
"void",
"addRowTimes",
"(",
"double",
"[",
"]",
"[",
"]",
"matrix",
",",
"int",
"diag",
",",
"int",
"fromCol",
",",
"int",
"row",
",",
"double",
"factor",
")",
"{",
"int",
"cols",
"=",
"matrix",
"[",
"0",
"]",
".",
"length",
";"... | Add a factor times one row to another row
@param matrix
the matrix to modify
@param diag
coordinate on the diagonal
@param fromCol
first column to process
@param row
row to process
@param factor
factor to multiply | [
"Add",
"a",
"factor",
"times",
"one",
"row",
"to",
"another",
"row"
] | train | https://github.com/ujmp/universal-java-matrix-package/blob/b7e1d293adeadaf35d208ffe8884028d6c06b63b/ujmp-core/src/main/java/org/ujmp/core/doublematrix/calculation/general/decomposition/Ginv.java#L631-L638 |
Shusshu/Android-RecurrencePicker | library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java | Utils.singleDayEvent | private static boolean singleDayEvent(long startMillis, long endMillis, long localGmtOffset) {
if (startMillis == endMillis) {
return true;
}
// An event ending at midnight should still be a single-day event, so check
// time end-1.
int startDay = Time.getJulianDay(startMillis, localGmtOffset);
int endDay = Time.getJulianDay(endMillis - 1, localGmtOffset);
return startDay == endDay;
} | java | private static boolean singleDayEvent(long startMillis, long endMillis, long localGmtOffset) {
if (startMillis == endMillis) {
return true;
}
// An event ending at midnight should still be a single-day event, so check
// time end-1.
int startDay = Time.getJulianDay(startMillis, localGmtOffset);
int endDay = Time.getJulianDay(endMillis - 1, localGmtOffset);
return startDay == endDay;
} | [
"private",
"static",
"boolean",
"singleDayEvent",
"(",
"long",
"startMillis",
",",
"long",
"endMillis",
",",
"long",
"localGmtOffset",
")",
"{",
"if",
"(",
"startMillis",
"==",
"endMillis",
")",
"{",
"return",
"true",
";",
"}",
"// An event ending at midnight shou... | Returns whether the specified time interval is in a single day. | [
"Returns",
"whether",
"the",
"specified",
"time",
"interval",
"is",
"in",
"a",
"single",
"day",
"."
] | train | https://github.com/Shusshu/Android-RecurrencePicker/blob/4f0ae74482e4d46d57a8fb13b4b7980a8613f4af/library/src/main/java/be/billington/calendar/recurrencepicker/Utils.java#L735-L745 |
jbundle/webapp | upload-unjar/src/main/java/org/jbundle/util/webapp/upload/unjar/UploadServletUnjar.java | UploadServletUnjar.writeAfterHTML | public void writeAfterHTML(PrintWriter out, HttpServletRequest req, Properties properties)
{
String strDefault = properties.getProperty(DESTINATION, "");
out.write("<input type=\"hidden\" value=\"" + strDefault + "\" name=\"" + DESTINATION + "\" />" + RETURN);
} | java | public void writeAfterHTML(PrintWriter out, HttpServletRequest req, Properties properties)
{
String strDefault = properties.getProperty(DESTINATION, "");
out.write("<input type=\"hidden\" value=\"" + strDefault + "\" name=\"" + DESTINATION + "\" />" + RETURN);
} | [
"public",
"void",
"writeAfterHTML",
"(",
"PrintWriter",
"out",
",",
"HttpServletRequest",
"req",
",",
"Properties",
"properties",
")",
"{",
"String",
"strDefault",
"=",
"properties",
".",
"getProperty",
"(",
"DESTINATION",
",",
"\"\"",
")",
";",
"out",
".",
"w... | /*
Write HTML after the form (Override this to do something). | [
"/",
"*",
"Write",
"HTML",
"after",
"the",
"form",
"(",
"Override",
"this",
"to",
"do",
"something",
")",
"."
] | train | https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/upload-unjar/src/main/java/org/jbundle/util/webapp/upload/unjar/UploadServletUnjar.java#L94-L98 |
keenlabs/KeenClient-Java | core/src/main/java/io/keen/client/java/FileEventStore.java | FileEventStore.getProjectDir | private File getProjectDir(String projectId, boolean create) throws IOException {
File projectDir = new File(getKeenCacheDirectory(), projectId);
if (create && !projectDir.exists()) {
KeenLogging.log("Cache directory for project '" + projectId + "' doesn't exist. " +
"Creating it.");
if (!projectDir.mkdirs()) {
throw new IOException("Could not create project cache directory '" +
projectDir.getAbsolutePath() + "'");
}
}
return projectDir;
} | java | private File getProjectDir(String projectId, boolean create) throws IOException {
File projectDir = new File(getKeenCacheDirectory(), projectId);
if (create && !projectDir.exists()) {
KeenLogging.log("Cache directory for project '" + projectId + "' doesn't exist. " +
"Creating it.");
if (!projectDir.mkdirs()) {
throw new IOException("Could not create project cache directory '" +
projectDir.getAbsolutePath() + "'");
}
}
return projectDir;
} | [
"private",
"File",
"getProjectDir",
"(",
"String",
"projectId",
",",
"boolean",
"create",
")",
"throws",
"IOException",
"{",
"File",
"projectDir",
"=",
"new",
"File",
"(",
"getKeenCacheDirectory",
"(",
")",
",",
"projectId",
")",
";",
"if",
"(",
"create",
"&... | Gets the cache directory for the given project. Optionally creates the directory if it
doesn't exist.
@param projectId The project ID.
@return The cache directory for the project.
@throws IOException | [
"Gets",
"the",
"cache",
"directory",
"for",
"the",
"given",
"project",
".",
"Optionally",
"creates",
"the",
"directory",
"if",
"it",
"doesn",
"t",
"exist",
"."
] | train | https://github.com/keenlabs/KeenClient-Java/blob/2ea021547b5338257c951a2596bd49749038d018/core/src/main/java/io/keen/client/java/FileEventStore.java#L275-L286 |
albfernandez/itext2 | src/main/java/com/lowagie/text/pdf/PdfPageLabels.java | PdfPageLabels.addPageLabel | public void addPageLabel(int page, int numberStyle, String text, int firstPage) {
if (page < 1 || firstPage < 1)
throw new IllegalArgumentException("In a page label the page numbers must be greater or equal to 1.");
PdfDictionary dic = new PdfDictionary();
if (numberStyle >= 0 && numberStyle < numberingStyle.length)
dic.put(PdfName.S, numberingStyle[numberStyle]);
if (text != null)
dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE));
if (firstPage != 1)
dic.put(PdfName.ST, new PdfNumber(firstPage));
map.put(Integer.valueOf(page - 1), dic);
} | java | public void addPageLabel(int page, int numberStyle, String text, int firstPage) {
if (page < 1 || firstPage < 1)
throw new IllegalArgumentException("In a page label the page numbers must be greater or equal to 1.");
PdfDictionary dic = new PdfDictionary();
if (numberStyle >= 0 && numberStyle < numberingStyle.length)
dic.put(PdfName.S, numberingStyle[numberStyle]);
if (text != null)
dic.put(PdfName.P, new PdfString(text, PdfObject.TEXT_UNICODE));
if (firstPage != 1)
dic.put(PdfName.ST, new PdfNumber(firstPage));
map.put(Integer.valueOf(page - 1), dic);
} | [
"public",
"void",
"addPageLabel",
"(",
"int",
"page",
",",
"int",
"numberStyle",
",",
"String",
"text",
",",
"int",
"firstPage",
")",
"{",
"if",
"(",
"page",
"<",
"1",
"||",
"firstPage",
"<",
"1",
")",
"throw",
"new",
"IllegalArgumentException",
"(",
"\"... | Adds or replaces a page label.
@param page the real page to start the numbering. First page is 1
@param numberStyle the numbering style such as LOWERCASE_ROMAN_NUMERALS
@param text the text to prefix the number. Can be <CODE>null</CODE> or empty
@param firstPage the first logical page number | [
"Adds",
"or",
"replaces",
"a",
"page",
"label",
"."
] | train | https://github.com/albfernandez/itext2/blob/438fc1899367fd13dfdfa8dfdca9a3c1a7783b84/src/main/java/com/lowagie/text/pdf/PdfPageLabels.java#L110-L121 |
pravega/pravega | segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java | EntrySerializer.serializeUpdate | private int serializeUpdate(@NonNull TableEntry entry, byte[] target, int targetOffset, long version) {
val key = entry.getKey().getKey();
val value = entry.getValue();
Preconditions.checkArgument(key.getLength() <= MAX_KEY_LENGTH, "Key too large.");
int serializationLength = getUpdateLength(entry);
Preconditions.checkArgument(serializationLength <= MAX_SERIALIZATION_LENGTH, "Key+Value serialization too large.");
Preconditions.checkElementIndex(targetOffset + serializationLength - 1, target.length, "serialization does not fit in target buffer");
// Serialize Header.
targetOffset = writeHeader(target, targetOffset, key.getLength(), value.getLength(), version);
// Key
System.arraycopy(key.array(), key.arrayOffset(), target, targetOffset, key.getLength());
targetOffset += key.getLength();
// Value.
System.arraycopy(value.array(), value.arrayOffset(), target, targetOffset, value.getLength());
targetOffset += value.getLength();
return targetOffset;
} | java | private int serializeUpdate(@NonNull TableEntry entry, byte[] target, int targetOffset, long version) {
val key = entry.getKey().getKey();
val value = entry.getValue();
Preconditions.checkArgument(key.getLength() <= MAX_KEY_LENGTH, "Key too large.");
int serializationLength = getUpdateLength(entry);
Preconditions.checkArgument(serializationLength <= MAX_SERIALIZATION_LENGTH, "Key+Value serialization too large.");
Preconditions.checkElementIndex(targetOffset + serializationLength - 1, target.length, "serialization does not fit in target buffer");
// Serialize Header.
targetOffset = writeHeader(target, targetOffset, key.getLength(), value.getLength(), version);
// Key
System.arraycopy(key.array(), key.arrayOffset(), target, targetOffset, key.getLength());
targetOffset += key.getLength();
// Value.
System.arraycopy(value.array(), value.arrayOffset(), target, targetOffset, value.getLength());
targetOffset += value.getLength();
return targetOffset;
} | [
"private",
"int",
"serializeUpdate",
"(",
"@",
"NonNull",
"TableEntry",
"entry",
",",
"byte",
"[",
"]",
"target",
",",
"int",
"targetOffset",
",",
"long",
"version",
")",
"{",
"val",
"key",
"=",
"entry",
".",
"getKey",
"(",
")",
".",
"getKey",
"(",
")"... | Serializes the given {@link TableEntry} to the given byte array.
@param entry The {@link TableEntry} to serialize.
@param target The byte array to serialize to.
@param targetOffset The first offset within the byte array to serialize at.
@param version The version to serialize. This will be encoded in the {@link Header}.
@return The first offset in the given byte array after the serialization. | [
"Serializes",
"the",
"given",
"{",
"@link",
"TableEntry",
"}",
"to",
"the",
"given",
"byte",
"array",
"."
] | train | https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/segmentstore/server/src/main/java/io/pravega/segmentstore/server/tables/EntrySerializer.java#L84-L104 |
Azure/azure-sdk-for-java | hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java | ClustersInner.beginResizeAsync | public Observable<Void> beginResizeAsync(String resourceGroupName, String clusterName) {
return beginResizeWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | java | public Observable<Void> beginResizeAsync(String resourceGroupName, String clusterName) {
return beginResizeWithServiceResponseAsync(resourceGroupName, clusterName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"beginResizeAsync",
"(",
"String",
"resourceGroupName",
",",
"String",
"clusterName",
")",
"{",
"return",
"beginResizeWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"clusterName",
")",
".",
"map",
"(",
"new",
"Fun... | Resizes the specified HDInsight cluster to the specified size.
@param resourceGroupName The name of the resource group.
@param clusterName The name of the cluster.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponse} object if successful. | [
"Resizes",
"the",
"specified",
"HDInsight",
"cluster",
"to",
"the",
"specified",
"size",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/hdinsight/resource-manager/v2018_06_01_preview/src/main/java/com/microsoft/azure/management/hdinsight/v2018_06_01_preview/implementation/ClustersInner.java#L1035-L1042 |
moparisthebest/beehive | beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/internal/PageFlowTagUtils.java | PageFlowTagUtils.getToken | public static String getToken(HttpServletRequest request, ActionMapping mapping)
{
if (mapping instanceof PageFlowActionMapping && ((PageFlowActionMapping) mapping).isPreventDoubleSubmit()) {
HttpSession session = request.getSession();
String token = (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
if (token != null) return token;
token = TokenProcessor.getInstance().generateToken(request);
request.getSession().setAttribute(Globals.TRANSACTION_TOKEN_KEY, token);
return token;
}
return null;
} | java | public static String getToken(HttpServletRequest request, ActionMapping mapping)
{
if (mapping instanceof PageFlowActionMapping && ((PageFlowActionMapping) mapping).isPreventDoubleSubmit()) {
HttpSession session = request.getSession();
String token = (String) session.getAttribute(Globals.TRANSACTION_TOKEN_KEY);
if (token != null) return token;
token = TokenProcessor.getInstance().generateToken(request);
request.getSession().setAttribute(Globals.TRANSACTION_TOKEN_KEY, token);
return token;
}
return null;
} | [
"public",
"static",
"String",
"getToken",
"(",
"HttpServletRequest",
"request",
",",
"ActionMapping",
"mapping",
")",
"{",
"if",
"(",
"mapping",
"instanceof",
"PageFlowActionMapping",
"&&",
"(",
"(",
"PageFlowActionMapping",
")",
"mapping",
")",
".",
"isPreventDoubl... | Get or generate a token used to prevent double submits to an action. The token is stored in the session,
and checked (and removed) when processing an action with the <code>preventDoubleSubmit</code> attribute
set to <code>true</code>. | [
"Get",
"or",
"generate",
"a",
"token",
"used",
"to",
"prevent",
"double",
"submits",
"to",
"an",
"action",
".",
"The",
"token",
"is",
"stored",
"in",
"the",
"session",
"and",
"checked",
"(",
"and",
"removed",
")",
"when",
"processing",
"an",
"action",
"w... | train | https://github.com/moparisthebest/beehive/blob/4246a0cc40ce3c05f1a02c2da2653ac622703d77/beehive-netui-tags/src/main/java/org/apache/beehive/netui/tags/internal/PageFlowTagUtils.java#L161-L173 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.