repository_name stringlengths 7 58 | func_path_in_repository stringlengths 11 218 | func_name stringlengths 4 140 | whole_func_string stringlengths 153 5.32k | language stringclasses 1
value | func_code_string stringlengths 72 4k | func_code_tokens listlengths 20 832 | func_documentation_string stringlengths 61 2k | func_documentation_tokens listlengths 1 647 | split_name stringclasses 1
value | func_code_url stringlengths 102 339 |
|---|---|---|---|---|---|---|---|---|---|---|
jmapper-framework/jmapper-core | JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java | Error.customMethod | public static void customMethod(String methodType,String methodName, Class<?> clazz) {
"""
Thrown when the bean doesn't respect the javabean conventions.
@param methodType method type
@param methodName name of the method doesn't exist
@param clazz class when this method isn't present
"""
String completeName = clazz.getCanonicalName();
String packageName = clazz.getPackage().getName();
String className = completeName.substring(packageName.length()+1);
throw new MalformedBeanException(MSG.INSTANCE.message(customMethodException, methodType, methodName,className));
} | java | public static void customMethod(String methodType,String methodName, Class<?> clazz){
String completeName = clazz.getCanonicalName();
String packageName = clazz.getPackage().getName();
String className = completeName.substring(packageName.length()+1);
throw new MalformedBeanException(MSG.INSTANCE.message(customMethodException, methodType, methodName,className));
} | [
"public",
"static",
"void",
"customMethod",
"(",
"String",
"methodType",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"clazz",
")",
"{",
"String",
"completeName",
"=",
"clazz",
".",
"getCanonicalName",
"(",
")",
";",
"String",
"packageName",
"="... | Thrown when the bean doesn't respect the javabean conventions.
@param methodType method type
@param methodName name of the method doesn't exist
@param clazz class when this method isn't present | [
"Thrown",
"when",
"the",
"bean",
"doesn",
"t",
"respect",
"the",
"javabean",
"conventions",
"."
] | train | https://github.com/jmapper-framework/jmapper-core/blob/b48fd3527f35055b8b4a30f53a51136f183acc90/JMapper Framework/src/main/java/com/googlecode/jmapper/config/Error.java#L423-L428 |
lucee/Lucee | core/src/main/java/lucee/commons/surveillance/HeapDumper.java | HeapDumper.dumpTo | public static void dumpTo(Resource res, boolean live) throws IOException {
"""
Dumps the heap to the outputFile file in the same format as the hprof heap dump. If this method
is called remotely from another process, the heap dump output is written to a file named
outputFile on the machine where the target VM is running. If outputFile is a relative path, it is
relative to the working directory where the target VM was started.
@param res Resource to write the .hprof file.
@param live if true dump only live objects i.e. objects that are reachable from others
@throws IOException
"""
MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy(mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
String path;
Resource tmp = null;
if (res instanceof FileResource) path = res.getAbsolutePath();
else {
tmp = SystemUtil.getTempFile("hprof", false);
path = tmp.getAbsolutePath();
}
try {
// it only
mxbean.dumpHeap(path, live);
}
finally {
if (tmp != null && tmp.exists()) {
tmp.moveTo(res);
}
}
} | java | public static void dumpTo(Resource res, boolean live) throws IOException {
MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy(mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);
String path;
Resource tmp = null;
if (res instanceof FileResource) path = res.getAbsolutePath();
else {
tmp = SystemUtil.getTempFile("hprof", false);
path = tmp.getAbsolutePath();
}
try {
// it only
mxbean.dumpHeap(path, live);
}
finally {
if (tmp != null && tmp.exists()) {
tmp.moveTo(res);
}
}
} | [
"public",
"static",
"void",
"dumpTo",
"(",
"Resource",
"res",
",",
"boolean",
"live",
")",
"throws",
"IOException",
"{",
"MBeanServer",
"mbserver",
"=",
"ManagementFactory",
".",
"getPlatformMBeanServer",
"(",
")",
";",
"HotSpotDiagnosticMXBean",
"mxbean",
"=",
"M... | Dumps the heap to the outputFile file in the same format as the hprof heap dump. If this method
is called remotely from another process, the heap dump output is written to a file named
outputFile on the machine where the target VM is running. If outputFile is a relative path, it is
relative to the working directory where the target VM was started.
@param res Resource to write the .hprof file.
@param live if true dump only live objects i.e. objects that are reachable from others
@throws IOException | [
"Dumps",
"the",
"heap",
"to",
"the",
"outputFile",
"file",
"in",
"the",
"same",
"format",
"as",
"the",
"hprof",
"heap",
"dump",
".",
"If",
"this",
"method",
"is",
"called",
"remotely",
"from",
"another",
"process",
"the",
"heap",
"dump",
"output",
"is",
... | train | https://github.com/lucee/Lucee/blob/29b153fc4e126e5edb97da937f2ee2e231b87593/core/src/main/java/lucee/commons/surveillance/HeapDumper.java#L44-L65 |
aequologica/geppaequo | geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java | MethodUtils.getAccessibleMethodFromSuperclass | private static Method getAccessibleMethodFromSuperclass
(Class<?> clazz, String methodName, Class<?>[] parameterTypes) {
"""
<p>Return an accessible method (that is, one that can be invoked via
reflection) by scanning through the superclasses. If no such method
can be found, return <code>null</code>.</p>
@param clazz Class to be checked
@param methodName Method name of the method we wish to call
@param parameterTypes The parameter type signatures
"""
Class<?> parentClazz = clazz.getSuperclass();
while (parentClazz != null) {
if (Modifier.isPublic(parentClazz.getModifiers())) {
try {
return parentClazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
parentClazz = parentClazz.getSuperclass();
}
return null;
} | java | private static Method getAccessibleMethodFromSuperclass
(Class<?> clazz, String methodName, Class<?>[] parameterTypes) {
Class<?> parentClazz = clazz.getSuperclass();
while (parentClazz != null) {
if (Modifier.isPublic(parentClazz.getModifiers())) {
try {
return parentClazz.getMethod(methodName, parameterTypes);
} catch (NoSuchMethodException e) {
return null;
}
}
parentClazz = parentClazz.getSuperclass();
}
return null;
} | [
"private",
"static",
"Method",
"getAccessibleMethodFromSuperclass",
"(",
"Class",
"<",
"?",
">",
"clazz",
",",
"String",
"methodName",
",",
"Class",
"<",
"?",
">",
"[",
"]",
"parameterTypes",
")",
"{",
"Class",
"<",
"?",
">",
"parentClazz",
"=",
"clazz",
"... | <p>Return an accessible method (that is, one that can be invoked via
reflection) by scanning through the superclasses. If no such method
can be found, return <code>null</code>.</p>
@param clazz Class to be checked
@param methodName Method name of the method we wish to call
@param parameterTypes The parameter type signatures | [
"<p",
">",
"Return",
"an",
"accessible",
"method",
"(",
"that",
"is",
"one",
"that",
"can",
"be",
"invoked",
"via",
"reflection",
")",
"by",
"scanning",
"through",
"the",
"superclasses",
".",
"If",
"no",
"such",
"method",
"can",
"be",
"found",
"return",
... | train | https://github.com/aequologica/geppaequo/blob/b72e5f6356535fd045a931f8c544d4a8ea6e35a2/geppaequo-core/src/main/java/net/aequologica/neo/geppaequo/auth/MethodUtils.java#L841-L856 |
rundeck/rundeck | core/src/main/java/com/dtolabs/utils/Mapper.java | Mapper.makeMap | public static Map makeMap(Mapper mapper, Enumeration en, boolean includeNull) {
"""
Create a new Map by using the enumeration objects as keys, and the mapping result as values.
@param mapper a Mapper to map the values
@param en Enumeration
@param includeNull true to include null
@return a new Map with values mapped
"""
HashMap h = new HashMap();
for (; en.hasMoreElements();) {
Object k = en.nextElement();
Object v = mapper.map(k);
if (includeNull || v != null) {
h.put(k, v);
}
}
return h;
} | java | public static Map makeMap(Mapper mapper, Enumeration en, boolean includeNull) {
HashMap h = new HashMap();
for (; en.hasMoreElements();) {
Object k = en.nextElement();
Object v = mapper.map(k);
if (includeNull || v != null) {
h.put(k, v);
}
}
return h;
} | [
"public",
"static",
"Map",
"makeMap",
"(",
"Mapper",
"mapper",
",",
"Enumeration",
"en",
",",
"boolean",
"includeNull",
")",
"{",
"HashMap",
"h",
"=",
"new",
"HashMap",
"(",
")",
";",
"for",
"(",
";",
"en",
".",
"hasMoreElements",
"(",
")",
";",
")",
... | Create a new Map by using the enumeration objects as keys, and the mapping result as values.
@param mapper a Mapper to map the values
@param en Enumeration
@param includeNull true to include null
@return a new Map with values mapped | [
"Create",
"a",
"new",
"Map",
"by",
"using",
"the",
"enumeration",
"objects",
"as",
"keys",
"and",
"the",
"mapping",
"result",
"as",
"values",
"."
] | train | https://github.com/rundeck/rundeck/blob/8070f774f55bffaa1118ff0c03aea319d40a9668/core/src/main/java/com/dtolabs/utils/Mapper.java#L601-L611 |
jdillon/gshell | gshell-util/src/main/java/com/planet57/gshell/util/converter/Converters.java | Converters.findEditor | private static PropertyEditor findEditor(final Type type) {
"""
Locate a property editor for given class of object.
@param type The target object class of the property.
@return The resolved editor, if any. Returns null if a suitable editor could not be located.
"""
assert type != null;
Class clazz = toClass(type);
// try to locate this directly from the editor manager first.
PropertyEditor editor = PropertyEditorManager.findEditor(clazz);
// we're outta here if we got one.
if (editor != null) {
return editor;
}
// it's possible this was a request for an array class. We might not
// recognize the array type directly, but the component type might be
// resolvable
if (clazz.isArray() && !clazz.getComponentType().isArray()) {
// do a recursive lookup on the base type
editor = findEditor(clazz.getComponentType());
// if we found a suitable editor for the base component type,
// wrapper this in an array adaptor for real use
if (editor != null) {
return new ArrayConverter(clazz, editor);
}
}
// nothing found
return null;
} | java | private static PropertyEditor findEditor(final Type type) {
assert type != null;
Class clazz = toClass(type);
// try to locate this directly from the editor manager first.
PropertyEditor editor = PropertyEditorManager.findEditor(clazz);
// we're outta here if we got one.
if (editor != null) {
return editor;
}
// it's possible this was a request for an array class. We might not
// recognize the array type directly, but the component type might be
// resolvable
if (clazz.isArray() && !clazz.getComponentType().isArray()) {
// do a recursive lookup on the base type
editor = findEditor(clazz.getComponentType());
// if we found a suitable editor for the base component type,
// wrapper this in an array adaptor for real use
if (editor != null) {
return new ArrayConverter(clazz, editor);
}
}
// nothing found
return null;
} | [
"private",
"static",
"PropertyEditor",
"findEditor",
"(",
"final",
"Type",
"type",
")",
"{",
"assert",
"type",
"!=",
"null",
";",
"Class",
"clazz",
"=",
"toClass",
"(",
"type",
")",
";",
"// try to locate this directly from the editor manager first.",
"PropertyEditor"... | Locate a property editor for given class of object.
@param type The target object class of the property.
@return The resolved editor, if any. Returns null if a suitable editor could not be located. | [
"Locate",
"a",
"property",
"editor",
"for",
"given",
"class",
"of",
"object",
"."
] | train | https://github.com/jdillon/gshell/blob/b587c1a4672d2e4905871462fa3b38a1f7b94e90/gshell-util/src/main/java/com/planet57/gshell/util/converter/Converters.java#L474-L502 |
graphhopper/graphhopper | core/src/main/java/com/graphhopper/reader/dem/AbstractTiffElevationProvider.java | AbstractTiffElevationProvider.downloadFile | private void downloadFile(File downloadFile, String url) throws IOException {
"""
Download a file at the provided url and save it as the given downloadFile if the downloadFile does not exist.
"""
if (!downloadFile.exists()) {
int max = 3;
for (int trial = 0; trial < max; trial++) {
try {
downloader.downloadFile(url, downloadFile.getAbsolutePath());
return;
} catch (SocketTimeoutException ex) {
if (trial >= max - 1)
throw new RuntimeException(ex);
try {
Thread.sleep(sleep);
} catch (InterruptedException ignored) {
}
}
}
}
} | java | private void downloadFile(File downloadFile, String url) throws IOException {
if (!downloadFile.exists()) {
int max = 3;
for (int trial = 0; trial < max; trial++) {
try {
downloader.downloadFile(url, downloadFile.getAbsolutePath());
return;
} catch (SocketTimeoutException ex) {
if (trial >= max - 1)
throw new RuntimeException(ex);
try {
Thread.sleep(sleep);
} catch (InterruptedException ignored) {
}
}
}
}
} | [
"private",
"void",
"downloadFile",
"(",
"File",
"downloadFile",
",",
"String",
"url",
")",
"throws",
"IOException",
"{",
"if",
"(",
"!",
"downloadFile",
".",
"exists",
"(",
")",
")",
"{",
"int",
"max",
"=",
"3",
";",
"for",
"(",
"int",
"trial",
"=",
... | Download a file at the provided url and save it as the given downloadFile if the downloadFile does not exist. | [
"Download",
"a",
"file",
"at",
"the",
"provided",
"url",
"and",
"save",
"it",
"as",
"the",
"given",
"downloadFile",
"if",
"the",
"downloadFile",
"does",
"not",
"exist",
"."
] | train | https://github.com/graphhopper/graphhopper/blob/c235e306e6e823043cadcc41ead0e685bdebf737/core/src/main/java/com/graphhopper/reader/dem/AbstractTiffElevationProvider.java#L150-L167 |
alkacon/opencms-core | src/org/opencms/main/CmsShell.java | CmsShell.validateUser | public boolean validateUser(String userName, String password, CmsRole requiredRole) {
"""
Validates the given user and password and checks if the user has the requested role.<p>
@param userName the user name
@param password the password
@param requiredRole the required role
@return <code>true</code> if the user is valid
"""
boolean result = false;
try {
CmsUser user = m_cms.readUser(userName, password);
result = OpenCms.getRoleManager().hasRole(m_cms, user.getName(), requiredRole);
} catch (CmsException e) {
// nothing to do
}
return result;
} | java | public boolean validateUser(String userName, String password, CmsRole requiredRole) {
boolean result = false;
try {
CmsUser user = m_cms.readUser(userName, password);
result = OpenCms.getRoleManager().hasRole(m_cms, user.getName(), requiredRole);
} catch (CmsException e) {
// nothing to do
}
return result;
} | [
"public",
"boolean",
"validateUser",
"(",
"String",
"userName",
",",
"String",
"password",
",",
"CmsRole",
"requiredRole",
")",
"{",
"boolean",
"result",
"=",
"false",
";",
"try",
"{",
"CmsUser",
"user",
"=",
"m_cms",
".",
"readUser",
"(",
"userName",
",",
... | Validates the given user and password and checks if the user has the requested role.<p>
@param userName the user name
@param password the password
@param requiredRole the required role
@return <code>true</code> if the user is valid | [
"Validates",
"the",
"given",
"user",
"and",
"password",
"and",
"checks",
"if",
"the",
"user",
"has",
"the",
"requested",
"role",
".",
"<p",
">"
] | train | https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/main/CmsShell.java#L1154-L1164 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java | ApiOvhEmaildomain.domain_redirection_GET | public ArrayList<String> domain_redirection_GET(String domain, String from, String to) throws IOException {
"""
Get redirections
REST: GET /email/domain/{domain}/redirection
@param from [required] Name of redirection
@param to [required] Email of redirection target
@param domain [required] Name of your domain name
"""
String qPath = "/email/domain/{domain}/redirection";
StringBuilder sb = path(qPath, domain);
query(sb, "from", from);
query(sb, "to", to);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | java | public ArrayList<String> domain_redirection_GET(String domain, String from, String to) throws IOException {
String qPath = "/email/domain/{domain}/redirection";
StringBuilder sb = path(qPath, domain);
query(sb, "from", from);
query(sb, "to", to);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, t1);
} | [
"public",
"ArrayList",
"<",
"String",
">",
"domain_redirection_GET",
"(",
"String",
"domain",
",",
"String",
"from",
",",
"String",
"to",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/domain/{domain}/redirection\"",
";",
"StringBuilder",
"sb",... | Get redirections
REST: GET /email/domain/{domain}/redirection
@param from [required] Name of redirection
@param to [required] Email of redirection target
@param domain [required] Name of your domain name | [
"Get",
"redirections"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emaildomain/src/main/java/net/minidev/ovh/api/ApiOvhEmaildomain.java#L1053-L1060 |
couchbase/CouchbaseMock | src/main/java/com/couchbase/mock/httpio/HandlerUtil.java | HandlerUtil.getAuth | public static AuthContext getAuth(HttpContext cx, HttpRequest req) throws IOException {
"""
Get any authorization credentials supplied over the connection. If no credentials were provided in the request,
an empty AuthContex is returned
@param cx The HTTP Context (from httpcomonents)
@param req The request
@return The authentication info
@throws IOException if an I/O error occurs
"""
AuthContext auth = (AuthContext) cx.getAttribute(HttpServer.CX_AUTH);
if (auth == null) {
Header authHdr = req.getLastHeader(HttpHeaders.AUTHORIZATION);
if (authHdr == null) {
auth = new AuthContext();
} else {
auth = new AuthContext(authHdr.getValue());
}
}
return auth;
} | java | public static AuthContext getAuth(HttpContext cx, HttpRequest req) throws IOException {
AuthContext auth = (AuthContext) cx.getAttribute(HttpServer.CX_AUTH);
if (auth == null) {
Header authHdr = req.getLastHeader(HttpHeaders.AUTHORIZATION);
if (authHdr == null) {
auth = new AuthContext();
} else {
auth = new AuthContext(authHdr.getValue());
}
}
return auth;
} | [
"public",
"static",
"AuthContext",
"getAuth",
"(",
"HttpContext",
"cx",
",",
"HttpRequest",
"req",
")",
"throws",
"IOException",
"{",
"AuthContext",
"auth",
"=",
"(",
"AuthContext",
")",
"cx",
".",
"getAttribute",
"(",
"HttpServer",
".",
"CX_AUTH",
")",
";",
... | Get any authorization credentials supplied over the connection. If no credentials were provided in the request,
an empty AuthContex is returned
@param cx The HTTP Context (from httpcomonents)
@param req The request
@return The authentication info
@throws IOException if an I/O error occurs | [
"Get",
"any",
"authorization",
"credentials",
"supplied",
"over",
"the",
"connection",
".",
"If",
"no",
"credentials",
"were",
"provided",
"in",
"the",
"request",
"an",
"empty",
"AuthContex",
"is",
"returned"
] | train | https://github.com/couchbase/CouchbaseMock/blob/2085bbebade1d5b6356480e7bf335139d08383da/src/main/java/com/couchbase/mock/httpio/HandlerUtil.java#L206-L217 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.metrics_fat/fat/src/com/ibm/ws/microprofile/metrics/fat/utils/MetricsConnection.java | MetricsConnection.connection_unauthorized | public static MetricsConnection connection_unauthorized(LibertyServer server) {
"""
Creates a connection for private (authorized) docs endpoint using HTTPS
and an unauthorized user ID
@param server - server to connect to
@return
"""
return new MetricsConnection(server, METRICS_ENDPOINT).secure(true)
.header("Authorization",
"Basic " + Base64Coder
.base64Encode(UNAUTHORIZED_USER_USERNAME + ":" + UNAUTHORIZED_USER_PASSWORD));
} | java | public static MetricsConnection connection_unauthorized(LibertyServer server) {
return new MetricsConnection(server, METRICS_ENDPOINT).secure(true)
.header("Authorization",
"Basic " + Base64Coder
.base64Encode(UNAUTHORIZED_USER_USERNAME + ":" + UNAUTHORIZED_USER_PASSWORD));
} | [
"public",
"static",
"MetricsConnection",
"connection_unauthorized",
"(",
"LibertyServer",
"server",
")",
"{",
"return",
"new",
"MetricsConnection",
"(",
"server",
",",
"METRICS_ENDPOINT",
")",
".",
"secure",
"(",
"true",
")",
".",
"header",
"(",
"\"Authorization\"",... | Creates a connection for private (authorized) docs endpoint using HTTPS
and an unauthorized user ID
@param server - server to connect to
@return | [
"Creates",
"a",
"connection",
"for",
"private",
"(",
"authorized",
")",
"docs",
"endpoint",
"using",
"HTTPS",
"and",
"an",
"unauthorized",
"user",
"ID"
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.microprofile.metrics_fat/fat/src/com/ibm/ws/microprofile/metrics/fat/utils/MetricsConnection.java#L227-L232 |
petergeneric/stdlib | stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java | TimecodeBuilder.compensateForDropFrame | static long compensateForDropFrame(final long framenumber, final double framerate) {
"""
@param framenumber
@param framerate
should be 29.97, 59.94, or 23.976, otherwise the calculations will be off.
@return a frame number that lets us use non-dropframe computations to extract time components
"""
//Code by David Heidelberger, adapted from Andrew Duncan
//Number of frames to drop on the minute marks is the nearest integer to 6% of the framerate
final long dropFrames = Math.round(framerate * .066666);
final long framesPer10Minutes = Math.round(framerate * 60 * 10);
final long framesPerMinute = (Math.round(framerate) * 60) - dropFrames;
final long d = framenumber / framesPer10Minutes;
final long m = framenumber % framesPer10Minutes;
//In the original post, the next line read m>1, which only worked for 29.97. Jean-Baptiste Mardelle correctly pointed out that m should be compared to dropFrames.
if (m > dropFrames)
return framenumber + (dropFrames * 9 * d) + dropFrames * ((m - dropFrames) / framesPerMinute);
else
return framenumber + dropFrames * 9 * d;
} | java | static long compensateForDropFrame(final long framenumber, final double framerate)
{
//Code by David Heidelberger, adapted from Andrew Duncan
//Number of frames to drop on the minute marks is the nearest integer to 6% of the framerate
final long dropFrames = Math.round(framerate * .066666);
final long framesPer10Minutes = Math.round(framerate * 60 * 10);
final long framesPerMinute = (Math.round(framerate) * 60) - dropFrames;
final long d = framenumber / framesPer10Minutes;
final long m = framenumber % framesPer10Minutes;
//In the original post, the next line read m>1, which only worked for 29.97. Jean-Baptiste Mardelle correctly pointed out that m should be compared to dropFrames.
if (m > dropFrames)
return framenumber + (dropFrames * 9 * d) + dropFrames * ((m - dropFrames) / framesPerMinute);
else
return framenumber + dropFrames * 9 * d;
} | [
"static",
"long",
"compensateForDropFrame",
"(",
"final",
"long",
"framenumber",
",",
"final",
"double",
"framerate",
")",
"{",
"//Code by David Heidelberger, adapted from Andrew Duncan",
"//Number of frames to drop on the minute marks is the nearest integer to 6% of the framerate",
"f... | @param framenumber
@param framerate
should be 29.97, 59.94, or 23.976, otherwise the calculations will be off.
@return a frame number that lets us use non-dropframe computations to extract time components | [
"@param",
"framenumber",
"@param",
"framerate",
"should",
"be",
"29",
".",
"97",
"59",
".",
"94",
"or",
"23",
".",
"976",
"otherwise",
"the",
"calculations",
"will",
"be",
"off",
"."
] | train | https://github.com/petergeneric/stdlib/blob/d4025d2f881bc0542b1e004c5f65a1ccaf895836/stdlib/src/main/java/com/peterphi/std/types/TimecodeBuilder.java#L375-L393 |
centic9/commons-dost | src/main/java/org/dstadler/commons/svn/SVNCommands.java | SVNCommands.getBranchLogStream | public static InputStream getBranchLogStream(String[] branches, Date startDate, Date endDate, String baseUrl, String user, String pwd) throws IOException {
"""
Retrieve the XML-log of changes on the given branch, starting from and ending with a specific date
This method returns an {@link InputStream} that can be used
to read and process the XML data without storing the complete result. This is useful
when you are potentially reading many revisions and thus need to avoid being limited
in memory or disk.
@param branches The list of branches to fetch logs for, currently only the first entry is used!
@param startDate The starting date for the log-entries that are fetched
@param endDate In case <code>endDate</code> is not specified, the current date is used
@param baseUrl The SVN url to connect to
@param user The SVN user or null if the default user from the machine should be used
@param pwd The SVN password or null if the default user from the machine should be used @return A stream that can be used to read the XML data, should be closed by the caller
@return An InputStream which provides the XML-log response
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure
"""
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ROOT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
CommandLine cmdLine = getCommandLineForXMLLog(user, pwd);
cmdLine.addArgument("{" + dateFormat.format(startDate) + "}:{" + dateFormat.format(endDate) + "}");
cmdLine.addArgument(baseUrl + branches[0]);
return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000);
} | java | public static InputStream getBranchLogStream(String[] branches, Date startDate, Date endDate, String baseUrl, String user, String pwd) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ", Locale.ROOT);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
CommandLine cmdLine = getCommandLineForXMLLog(user, pwd);
cmdLine.addArgument("{" + dateFormat.format(startDate) + "}:{" + dateFormat.format(endDate) + "}");
cmdLine.addArgument(baseUrl + branches[0]);
return ExecutionHelper.getCommandResult(cmdLine, new File("."), 0, 120000);
} | [
"public",
"static",
"InputStream",
"getBranchLogStream",
"(",
"String",
"[",
"]",
"branches",
",",
"Date",
"startDate",
",",
"Date",
"endDate",
",",
"String",
"baseUrl",
",",
"String",
"user",
",",
"String",
"pwd",
")",
"throws",
"IOException",
"{",
"SimpleDat... | Retrieve the XML-log of changes on the given branch, starting from and ending with a specific date
This method returns an {@link InputStream} that can be used
to read and process the XML data without storing the complete result. This is useful
when you are potentially reading many revisions and thus need to avoid being limited
in memory or disk.
@param branches The list of branches to fetch logs for, currently only the first entry is used!
@param startDate The starting date for the log-entries that are fetched
@param endDate In case <code>endDate</code> is not specified, the current date is used
@param baseUrl The SVN url to connect to
@param user The SVN user or null if the default user from the machine should be used
@param pwd The SVN password or null if the default user from the machine should be used @return A stream that can be used to read the XML data, should be closed by the caller
@return An InputStream which provides the XML-log response
@throws IOException Execution of the SVN sub-process failed or the
sub-process returned a exit value indicating a failure | [
"Retrieve",
"the",
"XML",
"-",
"log",
"of",
"changes",
"on",
"the",
"given",
"branch",
"starting",
"from",
"and",
"ending",
"with",
"a",
"specific",
"date",
"This",
"method",
"returns",
"an",
"{",
"@link",
"InputStream",
"}",
"that",
"can",
"be",
"used",
... | train | https://github.com/centic9/commons-dost/blob/f6fa4e3e0b943ff103f918824319d8abf33d0e0f/src/main/java/org/dstadler/commons/svn/SVNCommands.java#L194-L203 |
deeplearning4j/deeplearning4j | deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/solvers/accumulation/IndexedTail.java | IndexedTail.put | public void put(@NonNull INDArray update) {
"""
This mehtod adds update, with optional collapse
@param update
"""
try {
lock.writeLock().lock();
//if we're already in collapsed mode - we just insta-decompress
if (collapsedMode.get()) {
val lastUpdateIndex = collapsedIndex.get();
val lastUpdate = updates.get(lastUpdateIndex);
Preconditions.checkArgument(!lastUpdate.isCompressed(), "lastUpdate should NOT be compressed during collapse mode");
smartDecompress(update, lastUpdate);
// collapser only can work if all consumers are already introduced
} else if (allowCollapse && positions.size() >= expectedConsumers) {
// getting last added update
val lastUpdateIndex = updatesCounter.get();
// looking for max common non-applied update
long maxIdx = firstNotAppliedIndexEverywhere();
val array = Nd4j.create(shape);
val delta = lastUpdateIndex - maxIdx;
if (delta >= collapseThreshold) {
log.trace("Max delta to collapse: {}; Range: <{}...{}>", delta, maxIdx, lastUpdateIndex);
for (long e = maxIdx; e < lastUpdateIndex; e++) {
val u = updates.get(e);
if (u == null)
log.error("Failed on index {}", e);
// continue;
smartDecompress(u, array);
// removing updates array
updates.remove(e);
}
// decode latest update
smartDecompress(update, array);
// putting collapsed array back at last index
updates.put(lastUpdateIndex, array);
collapsedIndex.set(lastUpdateIndex);
// shift counter by 1
updatesCounter.getAndIncrement();
// we're saying that right now all updates within some range are collapsed into 1 update
collapsedMode.set(true);
} else {
updates.put(updatesCounter.getAndIncrement(), update);
}
} else {
updates.put(updatesCounter.getAndIncrement(), update);
}
} finally {
lock.writeLock().unlock();
}
} | java | public void put(@NonNull INDArray update) {
try {
lock.writeLock().lock();
//if we're already in collapsed mode - we just insta-decompress
if (collapsedMode.get()) {
val lastUpdateIndex = collapsedIndex.get();
val lastUpdate = updates.get(lastUpdateIndex);
Preconditions.checkArgument(!lastUpdate.isCompressed(), "lastUpdate should NOT be compressed during collapse mode");
smartDecompress(update, lastUpdate);
// collapser only can work if all consumers are already introduced
} else if (allowCollapse && positions.size() >= expectedConsumers) {
// getting last added update
val lastUpdateIndex = updatesCounter.get();
// looking for max common non-applied update
long maxIdx = firstNotAppliedIndexEverywhere();
val array = Nd4j.create(shape);
val delta = lastUpdateIndex - maxIdx;
if (delta >= collapseThreshold) {
log.trace("Max delta to collapse: {}; Range: <{}...{}>", delta, maxIdx, lastUpdateIndex);
for (long e = maxIdx; e < lastUpdateIndex; e++) {
val u = updates.get(e);
if (u == null)
log.error("Failed on index {}", e);
// continue;
smartDecompress(u, array);
// removing updates array
updates.remove(e);
}
// decode latest update
smartDecompress(update, array);
// putting collapsed array back at last index
updates.put(lastUpdateIndex, array);
collapsedIndex.set(lastUpdateIndex);
// shift counter by 1
updatesCounter.getAndIncrement();
// we're saying that right now all updates within some range are collapsed into 1 update
collapsedMode.set(true);
} else {
updates.put(updatesCounter.getAndIncrement(), update);
}
} else {
updates.put(updatesCounter.getAndIncrement(), update);
}
} finally {
lock.writeLock().unlock();
}
} | [
"public",
"void",
"put",
"(",
"@",
"NonNull",
"INDArray",
"update",
")",
"{",
"try",
"{",
"lock",
".",
"writeLock",
"(",
")",
".",
"lock",
"(",
")",
";",
"//if we're already in collapsed mode - we just insta-decompress",
"if",
"(",
"collapsedMode",
".",
"get",
... | This mehtod adds update, with optional collapse
@param update | [
"This",
"mehtod",
"adds",
"update",
"with",
"optional",
"collapse"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/optimize/solvers/accumulation/IndexedTail.java#L91-L149 |
threerings/narya | core/src/main/java/com/threerings/presents/util/ClassUtil.java | ClassUtil.getMethod | public static Method getMethod (String name, Object target, Map<String, Method> cache) {
"""
Locates and returns the first method in the supplied class whose name is equal to the
specified name. If a method is located, it will be cached in the supplied cache so that
subsequent requests will immediately return the method from the cache rather than
re-reflecting.
@return the method with the specified name or null if no method with that name could be
found.
"""
Class<?> tclass = target.getClass();
String key = tclass.getName() + ":" + name;
Method method = cache.get(key);
if (method == null) {
method = findMethod(tclass, name);
if (method != null) {
cache.put(key, method);
}
}
return method;
} | java | public static Method getMethod (String name, Object target, Map<String, Method> cache)
{
Class<?> tclass = target.getClass();
String key = tclass.getName() + ":" + name;
Method method = cache.get(key);
if (method == null) {
method = findMethod(tclass, name);
if (method != null) {
cache.put(key, method);
}
}
return method;
} | [
"public",
"static",
"Method",
"getMethod",
"(",
"String",
"name",
",",
"Object",
"target",
",",
"Map",
"<",
"String",
",",
"Method",
">",
"cache",
")",
"{",
"Class",
"<",
"?",
">",
"tclass",
"=",
"target",
".",
"getClass",
"(",
")",
";",
"String",
"k... | Locates and returns the first method in the supplied class whose name is equal to the
specified name. If a method is located, it will be cached in the supplied cache so that
subsequent requests will immediately return the method from the cache rather than
re-reflecting.
@return the method with the specified name or null if no method with that name could be
found. | [
"Locates",
"and",
"returns",
"the",
"first",
"method",
"in",
"the",
"supplied",
"class",
"whose",
"name",
"is",
"equal",
"to",
"the",
"specified",
"name",
".",
"If",
"a",
"method",
"is",
"located",
"it",
"will",
"be",
"cached",
"in",
"the",
"supplied",
"... | train | https://github.com/threerings/narya/blob/5b01edc8850ed0c32d004b4049e1ac4a02027ede/core/src/main/java/com/threerings/presents/util/ClassUtil.java#L46-L60 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockInlineChecksumWriter.java | BlockInlineChecksumWriter.computePartialChunkCrc | private void computePartialChunkCrc(long blkoff, int bytesPerChecksum,
DataChecksum checksum) throws IOException {
"""
reads in the partial crc chunk and computes checksum of pre-existing data
in partial chunk.
"""
// find offset of the beginning of partial chunk.
//
int sizePartialChunk = (int) (blkoff % bytesPerChecksum);
int checksumSize = checksum.getChecksumSize();
long fileOff = BlockInlineChecksumReader.getPosFromBlockOffset(blkoff
- sizePartialChunk, bytesPerChecksum, checksumSize);
LOG.info("computePartialChunkCrc sizePartialChunk " + sizePartialChunk
+ " block " + block + " offset in block " + blkoff);
// create an input stream from the block file
// and read in partial crc chunk into temporary buffer
//
byte[] buf = new byte[sizePartialChunk];
byte[] crcbuf = new byte[checksumSize];
// FileInputStream dataIn = null;
/*
RandomAccessFile blockInFile = new RandomAccessFile(blockFile, "r");
dataIn = new FileInputStream(blockInFile.getFD());
if (fileOff > 0) {
blockInFile.seek(fileOff);
}
IOUtils.readFully(dataIn, buf, 0, sizePartialChunk);
// open meta file and read in crc value computer earlier
IOUtils.readFully(dataIn, crcbuf, 0, crcbuf.length);
*/
BlockDataFile.Reader blockReader = blockDataFile.getReader(datanode);
blockReader.readFully(buf, 0, sizePartialChunk, fileOff, true);
blockReader.readFully(crcbuf, 0, crcbuf.length, fileOff + sizePartialChunk,
true);
// compute crc of partial chunk from data read in the block file.
Checksum partialCrc = new CRC32();
partialCrc.update(buf, 0, sizePartialChunk);
LOG.info("Read in partial CRC chunk from disk for block " + block);
// paranoia! verify that the pre-computed crc matches what we
// recalculated just now
if (partialCrc.getValue() != FSInputChecker.checksum2long(crcbuf)) {
String msg = "Partial CRC " + partialCrc.getValue()
+ " does not match value computed the "
+ " last time file was closed "
+ FSInputChecker.checksum2long(crcbuf);
throw new IOException(msg);
}
partialCrcInt = (int) partialCrc.getValue();
} | java | private void computePartialChunkCrc(long blkoff, int bytesPerChecksum,
DataChecksum checksum) throws IOException {
// find offset of the beginning of partial chunk.
//
int sizePartialChunk = (int) (blkoff % bytesPerChecksum);
int checksumSize = checksum.getChecksumSize();
long fileOff = BlockInlineChecksumReader.getPosFromBlockOffset(blkoff
- sizePartialChunk, bytesPerChecksum, checksumSize);
LOG.info("computePartialChunkCrc sizePartialChunk " + sizePartialChunk
+ " block " + block + " offset in block " + blkoff);
// create an input stream from the block file
// and read in partial crc chunk into temporary buffer
//
byte[] buf = new byte[sizePartialChunk];
byte[] crcbuf = new byte[checksumSize];
// FileInputStream dataIn = null;
/*
RandomAccessFile blockInFile = new RandomAccessFile(blockFile, "r");
dataIn = new FileInputStream(blockInFile.getFD());
if (fileOff > 0) {
blockInFile.seek(fileOff);
}
IOUtils.readFully(dataIn, buf, 0, sizePartialChunk);
// open meta file and read in crc value computer earlier
IOUtils.readFully(dataIn, crcbuf, 0, crcbuf.length);
*/
BlockDataFile.Reader blockReader = blockDataFile.getReader(datanode);
blockReader.readFully(buf, 0, sizePartialChunk, fileOff, true);
blockReader.readFully(crcbuf, 0, crcbuf.length, fileOff + sizePartialChunk,
true);
// compute crc of partial chunk from data read in the block file.
Checksum partialCrc = new CRC32();
partialCrc.update(buf, 0, sizePartialChunk);
LOG.info("Read in partial CRC chunk from disk for block " + block);
// paranoia! verify that the pre-computed crc matches what we
// recalculated just now
if (partialCrc.getValue() != FSInputChecker.checksum2long(crcbuf)) {
String msg = "Partial CRC " + partialCrc.getValue()
+ " does not match value computed the "
+ " last time file was closed "
+ FSInputChecker.checksum2long(crcbuf);
throw new IOException(msg);
}
partialCrcInt = (int) partialCrc.getValue();
} | [
"private",
"void",
"computePartialChunkCrc",
"(",
"long",
"blkoff",
",",
"int",
"bytesPerChecksum",
",",
"DataChecksum",
"checksum",
")",
"throws",
"IOException",
"{",
"// find offset of the beginning of partial chunk.",
"//",
"int",
"sizePartialChunk",
"=",
"(",
"int",
... | reads in the partial crc chunk and computes checksum of pre-existing data
in partial chunk. | [
"reads",
"in",
"the",
"partial",
"crc",
"chunk",
"and",
"computes",
"checksum",
"of",
"pre",
"-",
"existing",
"data",
"in",
"partial",
"chunk",
"."
] | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/BlockInlineChecksumWriter.java#L326-L378 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/ops/SDBaseOps.java | SDBaseOps.squaredNorm | public SDVariable squaredNorm(String name, SDVariable x, boolean keepDims, int... dimensions) {
"""
Squared L2 norm: see {@link #norm2(String, SDVariable, boolean, int...)}
"""
validateNumerical("squaredNorm", x);
SDVariable result = f().squaredNorm(x, keepDims, dimensions);
return updateVariableNameAndReference(result, name);
} | java | public SDVariable squaredNorm(String name, SDVariable x, boolean keepDims, int... dimensions) {
validateNumerical("squaredNorm", x);
SDVariable result = f().squaredNorm(x, keepDims, dimensions);
return updateVariableNameAndReference(result, name);
} | [
"public",
"SDVariable",
"squaredNorm",
"(",
"String",
"name",
",",
"SDVariable",
"x",
",",
"boolean",
"keepDims",
",",
"int",
"...",
"dimensions",
")",
"{",
"validateNumerical",
"(",
"\"squaredNorm\"",
",",
"x",
")",
";",
"SDVariable",
"result",
"=",
"f",
"(... | Squared L2 norm: see {@link #norm2(String, SDVariable, boolean, int...)} | [
"Squared",
"L2",
"norm",
":",
"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/SDBaseOps.java#L2497-L2501 |
hyperledger/fabric-sdk-java | src/main/java/org/hyperledger/fabric/sdk/Channel.java | Channel.sendLifecycleApproveChaincodeDefinitionForMyOrgProposal | public LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest, Peer peer) throws ProposalException, InvalidArgumentException {
"""
Approve chaincode to be run on this peer's organization.
@param lifecycleApproveChaincodeDefinitionForMyOrgRequest the request see {@link LifecycleApproveChaincodeDefinitionForMyOrgRequest}
@param peer
@return A {@link LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse}
@throws ProposalException
@throws InvalidArgumentException
"""
if (null == lifecycleApproveChaincodeDefinitionForMyOrgRequest) {
throw new InvalidArgumentException("The lifecycleApproveChaincodeDefinitionForMyOrgRequest parameter can not be null.");
}
Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses =
sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest, Collections.singleton(peer));
return lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses.iterator().next();
} | java | public LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(LifecycleApproveChaincodeDefinitionForMyOrgRequest lifecycleApproveChaincodeDefinitionForMyOrgRequest, Peer peer) throws ProposalException, InvalidArgumentException {
if (null == lifecycleApproveChaincodeDefinitionForMyOrgRequest) {
throw new InvalidArgumentException("The lifecycleApproveChaincodeDefinitionForMyOrgRequest parameter can not be null.");
}
Collection<LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse> lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses =
sendLifecycleApproveChaincodeDefinitionForMyOrgProposal(lifecycleApproveChaincodeDefinitionForMyOrgRequest, Collections.singleton(peer));
return lifecycleApproveChaincodeDefinitionForMyOrgProposalResponses.iterator().next();
} | [
"public",
"LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse",
"sendLifecycleApproveChaincodeDefinitionForMyOrgProposal",
"(",
"LifecycleApproveChaincodeDefinitionForMyOrgRequest",
"lifecycleApproveChaincodeDefinitionForMyOrgRequest",
",",
"Peer",
"peer",
")",
"throws",
"ProposalExce... | Approve chaincode to be run on this peer's organization.
@param lifecycleApproveChaincodeDefinitionForMyOrgRequest the request see {@link LifecycleApproveChaincodeDefinitionForMyOrgRequest}
@param peer
@return A {@link LifecycleApproveChaincodeDefinitionForMyOrgProposalResponse}
@throws ProposalException
@throws InvalidArgumentException | [
"Approve",
"chaincode",
"to",
"be",
"run",
"on",
"this",
"peer",
"s",
"organization",
"."
] | train | https://github.com/hyperledger/fabric-sdk-java/blob/4a2d7b3408b8b0a1ed812aa36942c438159c37a0/src/main/java/org/hyperledger/fabric/sdk/Channel.java#L3431-L3441 |
jbundle/jbundle | app/program/project/src/main/java/org/jbundle/app/program/project/db/UpdateDependenciesHandler.java | UpdateDependenciesHandler.doRecordChange | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption) {
"""
Called when a change is the record status is about to happen/has happened.
@param field If this file change is due to a field, this is the field.
@param iChangeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
ADD_TYPE - Before a write.
UPDATE_TYPE - Before an update.
DELETE_TYPE - Before a delete.
AFTER_UPDATE_TYPE - After a write or update.
LOCK_TYPE - Before a lock.
SELECT_TYPE - After a select.
DESELECT_TYPE - After a deselect.
MOVE_NEXT_TYPE - After a move.
AFTER_REQUERY_TYPE - Record opened.
SELECT_EOF_TYPE - EOF Hit.
"""
if ((iChangeType == DBConstants.AFTER_ADD_TYPE)
|| (iChangeType == DBConstants.AFTER_UPDATE_TYPE)
|| (iChangeType == DBConstants.AFTER_DELETE_TYPE))
{
if ((iChangeType == DBConstants.AFTER_DELETE_TYPE)
|| (this.getOwner().getField(ProjectTask.START_DATE_TIME).isModified())
|| (this.getOwner().getField(ProjectTask.END_DATE_TIME).isModified()))
{
if (iChangeType == DBConstants.AFTER_UPDATE_TYPE)
((ProjectTask)this.getOwner()).updateDependencies(m_bMoveSiblings, bDisplayOption);
}
}
return super.doRecordChange(field, iChangeType, bDisplayOption);
} | java | public int doRecordChange(FieldInfo field, int iChangeType, boolean bDisplayOption)
{
if ((iChangeType == DBConstants.AFTER_ADD_TYPE)
|| (iChangeType == DBConstants.AFTER_UPDATE_TYPE)
|| (iChangeType == DBConstants.AFTER_DELETE_TYPE))
{
if ((iChangeType == DBConstants.AFTER_DELETE_TYPE)
|| (this.getOwner().getField(ProjectTask.START_DATE_TIME).isModified())
|| (this.getOwner().getField(ProjectTask.END_DATE_TIME).isModified()))
{
if (iChangeType == DBConstants.AFTER_UPDATE_TYPE)
((ProjectTask)this.getOwner()).updateDependencies(m_bMoveSiblings, bDisplayOption);
}
}
return super.doRecordChange(field, iChangeType, bDisplayOption);
} | [
"public",
"int",
"doRecordChange",
"(",
"FieldInfo",
"field",
",",
"int",
"iChangeType",
",",
"boolean",
"bDisplayOption",
")",
"{",
"if",
"(",
"(",
"iChangeType",
"==",
"DBConstants",
".",
"AFTER_ADD_TYPE",
")",
"||",
"(",
"iChangeType",
"==",
"DBConstants",
... | Called when a change is the record status is about to happen/has happened.
@param field If this file change is due to a field, this is the field.
@param iChangeType The type of change that occurred.
@param bDisplayOption If true, display any changes.
@return an error code.
ADD_TYPE - Before a write.
UPDATE_TYPE - Before an update.
DELETE_TYPE - Before a delete.
AFTER_UPDATE_TYPE - After a write or update.
LOCK_TYPE - Before a lock.
SELECT_TYPE - After a select.
DESELECT_TYPE - After a deselect.
MOVE_NEXT_TYPE - After a move.
AFTER_REQUERY_TYPE - Record opened.
SELECT_EOF_TYPE - EOF Hit. | [
"Called",
"when",
"a",
"change",
"is",
"the",
"record",
"status",
"is",
"about",
"to",
"happen",
"/",
"has",
"happened",
"."
] | train | https://github.com/jbundle/jbundle/blob/4037fcfa85f60c7d0096c453c1a3cd573c2b0abc/app/program/project/src/main/java/org/jbundle/app/program/project/db/UpdateDependenciesHandler.java#L71-L86 |
micronaut-projects/micronaut-core | inject/src/main/java/io/micronaut/inject/annotation/AbstractAnnotationMetadataBuilder.java | AbstractAnnotationMetadataBuilder.buildForMethod | public AnnotationMetadata buildForMethod(T element) {
"""
Build the meta data for the given method element excluding any class metadata.
@param element The element
@return The {@link AnnotationMetadata}
"""
final AnnotationMetadata existing = MUTATED_ANNOTATION_METADATA.get(element);
if (existing != null) {
return existing;
} else {
DefaultAnnotationMetadata annotationMetadata = new DefaultAnnotationMetadata();
return buildInternal(null, element, annotationMetadata, false, false);
}
} | java | public AnnotationMetadata buildForMethod(T element) {
final AnnotationMetadata existing = MUTATED_ANNOTATION_METADATA.get(element);
if (existing != null) {
return existing;
} else {
DefaultAnnotationMetadata annotationMetadata = new DefaultAnnotationMetadata();
return buildInternal(null, element, annotationMetadata, false, false);
}
} | [
"public",
"AnnotationMetadata",
"buildForMethod",
"(",
"T",
"element",
")",
"{",
"final",
"AnnotationMetadata",
"existing",
"=",
"MUTATED_ANNOTATION_METADATA",
".",
"get",
"(",
"element",
")",
";",
"if",
"(",
"existing",
"!=",
"null",
")",
"{",
"return",
"existi... | Build the meta data for the given method element excluding any class metadata.
@param element The element
@return The {@link AnnotationMetadata} | [
"Build",
"the",
"meta",
"data",
"for",
"the",
"given",
"method",
"element",
"excluding",
"any",
"class",
"metadata",
"."
] | train | https://github.com/micronaut-projects/micronaut-core/blob/c31f5b03ce0eb88c2f6470710987db03b8967d5c/inject/src/main/java/io/micronaut/inject/annotation/AbstractAnnotationMetadataBuilder.java#L148-L156 |
HiddenStage/divide | Shared/src/main/java/io/divide/otto/AnnotatedHandlerFinder.java | AnnotatedHandlerFinder.findAllProducers | public static Map<Class<?>, EventProducer> findAllProducers(Object listener) {
"""
This implementation finds all methods marked with a {@link io.divide.otto.Produce} annotation.
"""
final Class<?> listenerClass = listener.getClass();
Map<Class<?>, EventProducer> handlersInMethod = new HashMap<Class<?>, EventProducer>();
if (!PRODUCERS_CACHE.containsKey(listenerClass)) {
loadAnnotatedMethods(listenerClass);
}
Map<Class<?>, Method> methods = PRODUCERS_CACHE.get(listenerClass);
if (!methods.isEmpty()) {
for (Map.Entry<Class<?>, Method> e : methods.entrySet()) {
EventProducer producer = new EventProducer(listener, e.getValue());
handlersInMethod.put(e.getKey(), producer);
}
}
return handlersInMethod;
} | java | public static Map<Class<?>, EventProducer> findAllProducers(Object listener) {
final Class<?> listenerClass = listener.getClass();
Map<Class<?>, EventProducer> handlersInMethod = new HashMap<Class<?>, EventProducer>();
if (!PRODUCERS_CACHE.containsKey(listenerClass)) {
loadAnnotatedMethods(listenerClass);
}
Map<Class<?>, Method> methods = PRODUCERS_CACHE.get(listenerClass);
if (!methods.isEmpty()) {
for (Map.Entry<Class<?>, Method> e : methods.entrySet()) {
EventProducer producer = new EventProducer(listener, e.getValue());
handlersInMethod.put(e.getKey(), producer);
}
}
return handlersInMethod;
} | [
"public",
"static",
"Map",
"<",
"Class",
"<",
"?",
">",
",",
"EventProducer",
">",
"findAllProducers",
"(",
"Object",
"listener",
")",
"{",
"final",
"Class",
"<",
"?",
">",
"listenerClass",
"=",
"listener",
".",
"getClass",
"(",
")",
";",
"Map",
"<",
"... | This implementation finds all methods marked with a {@link io.divide.otto.Produce} annotation. | [
"This",
"implementation",
"finds",
"all",
"methods",
"marked",
"with",
"a",
"{"
] | train | https://github.com/HiddenStage/divide/blob/14e36598c50d92b4393e6649915e32b86141c598/Shared/src/main/java/io/divide/otto/AnnotatedHandlerFinder.java#L114-L130 |
UrielCh/ovh-java-sdk | ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java | ApiOvhEmailpro.service_externalContact_externalEmailAddress_GET | public OvhExternalContact service_externalContact_externalEmailAddress_GET(String service, String externalEmailAddress) throws IOException {
"""
Get this object properties
REST: GET /email/pro/{service}/externalContact/{externalEmailAddress}
@param service [required] The internal name of your pro organization
@param externalEmailAddress [required] Contact email
API beta
"""
String qPath = "/email/pro/{service}/externalContact/{externalEmailAddress}";
StringBuilder sb = path(qPath, service, externalEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhExternalContact.class);
} | java | public OvhExternalContact service_externalContact_externalEmailAddress_GET(String service, String externalEmailAddress) throws IOException {
String qPath = "/email/pro/{service}/externalContact/{externalEmailAddress}";
StringBuilder sb = path(qPath, service, externalEmailAddress);
String resp = exec(qPath, "GET", sb.toString(), null);
return convertTo(resp, OvhExternalContact.class);
} | [
"public",
"OvhExternalContact",
"service_externalContact_externalEmailAddress_GET",
"(",
"String",
"service",
",",
"String",
"externalEmailAddress",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/email/pro/{service}/externalContact/{externalEmailAddress}\"",
";",
... | Get this object properties
REST: GET /email/pro/{service}/externalContact/{externalEmailAddress}
@param service [required] The internal name of your pro organization
@param externalEmailAddress [required] Contact email
API beta | [
"Get",
"this",
"object",
"properties"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-emailpro/src/main/java/net/minidev/ovh/api/ApiOvhEmailpro.java#L76-L81 |
rFlex/SCJavaTools | src/main/java/me/corsin/javatools/task/TaskQueue.java | TaskQueue.executeAsyncTimed | public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) {
"""
Add a Task to the queue. The Task will be executed after "inMs" milliseconds.
@param the runnable to be executed
@param inMs The time after which the task should be processed
@return the runnable, as a convenience method
"""
final Runnable theRunnable = runnable;
// This implementation is not really suitable for now as the timer uses its own thread
// The TaskQueue itself should be able in the future to handle this without using a new thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TaskQueue.this.executeAsync(theRunnable);
}
}, inMs);
return runnable;
} | java | public <T extends Runnable> T executeAsyncTimed(T runnable, long inMs) {
final Runnable theRunnable = runnable;
// This implementation is not really suitable for now as the timer uses its own thread
// The TaskQueue itself should be able in the future to handle this without using a new thread
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
TaskQueue.this.executeAsync(theRunnable);
}
}, inMs);
return runnable;
} | [
"public",
"<",
"T",
"extends",
"Runnable",
">",
"T",
"executeAsyncTimed",
"(",
"T",
"runnable",
",",
"long",
"inMs",
")",
"{",
"final",
"Runnable",
"theRunnable",
"=",
"runnable",
";",
"// This implementation is not really suitable for now as the timer uses its own thread... | Add a Task to the queue. The Task will be executed after "inMs" milliseconds.
@param the runnable to be executed
@param inMs The time after which the task should be processed
@return the runnable, as a convenience method | [
"Add",
"a",
"Task",
"to",
"the",
"queue",
".",
"The",
"Task",
"will",
"be",
"executed",
"after",
"inMs",
"milliseconds",
"."
] | train | https://github.com/rFlex/SCJavaTools/blob/6bafee99f12a6ad73265db64776edac2bab71f67/src/main/java/me/corsin/javatools/task/TaskQueue.java#L197-L212 |
b3dgs/lionengine | lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java | MapCircuitExtractor.getCircuit | public Circuit getCircuit(Tile tile) {
"""
Get the tile circuit.
@param tile The current tile.
@return The tile circuit, <code>null</code> if none.
"""
final Collection<String> neighborGroups = getNeighborGroups(tile);
final Collection<String> groups = new HashSet<>(neighborGroups);
final String group = mapGroup.getGroup(tile);
final Circuit circuit;
if (groups.size() == 1)
{
if (group.equals(groups.iterator().next()))
{
circuit = new Circuit(CircuitType.MIDDLE, group, group);
}
else
{
circuit = new Circuit(CircuitType.BLOCK, group, groups.iterator().next());
}
}
else
{
circuit = getCircuitGroups(group, neighborGroups);
}
return circuit;
} | java | public Circuit getCircuit(Tile tile)
{
final Collection<String> neighborGroups = getNeighborGroups(tile);
final Collection<String> groups = new HashSet<>(neighborGroups);
final String group = mapGroup.getGroup(tile);
final Circuit circuit;
if (groups.size() == 1)
{
if (group.equals(groups.iterator().next()))
{
circuit = new Circuit(CircuitType.MIDDLE, group, group);
}
else
{
circuit = new Circuit(CircuitType.BLOCK, group, groups.iterator().next());
}
}
else
{
circuit = getCircuitGroups(group, neighborGroups);
}
return circuit;
} | [
"public",
"Circuit",
"getCircuit",
"(",
"Tile",
"tile",
")",
"{",
"final",
"Collection",
"<",
"String",
">",
"neighborGroups",
"=",
"getNeighborGroups",
"(",
"tile",
")",
";",
"final",
"Collection",
"<",
"String",
">",
"groups",
"=",
"new",
"HashSet",
"<>",
... | Get the tile circuit.
@param tile The current tile.
@return The tile circuit, <code>null</code> if none. | [
"Get",
"the",
"tile",
"circuit",
"."
] | train | https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/transition/circuit/MapCircuitExtractor.java#L111-L135 |
jpaoletti/java-presentation-manager | modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java | Highlights.getHighlight | public Highlight getHighlight(Entity entity, Object instance) {
"""
Return the first highlight that match in any value of this instance with
some of the highlights values.
@param entity The entity
@param instance The instance
@return The Highlinght
"""
for (Highlight highlight : highlights) {
if (highlight.getScope().equals(INSTANCE)) {
for (Field field : entity.getOrderedFields()) {
if (match(instance, field, highlight)) {
return highlight;
}
}
}
}
return null;
} | java | public Highlight getHighlight(Entity entity, Object instance) {
for (Highlight highlight : highlights) {
if (highlight.getScope().equals(INSTANCE)) {
for (Field field : entity.getOrderedFields()) {
if (match(instance, field, highlight)) {
return highlight;
}
}
}
}
return null;
} | [
"public",
"Highlight",
"getHighlight",
"(",
"Entity",
"entity",
",",
"Object",
"instance",
")",
"{",
"for",
"(",
"Highlight",
"highlight",
":",
"highlights",
")",
"{",
"if",
"(",
"highlight",
".",
"getScope",
"(",
")",
".",
"equals",
"(",
"INSTANCE",
")",
... | Return the first highlight that match in any value of this instance with
some of the highlights values.
@param entity The entity
@param instance The instance
@return The Highlinght | [
"Return",
"the",
"first",
"highlight",
"that",
"match",
"in",
"any",
"value",
"of",
"this",
"instance",
"with",
"some",
"of",
"the",
"highlights",
"values",
"."
] | train | https://github.com/jpaoletti/java-presentation-manager/blob/d5aab55638383695db244744b4bfe27c5200e04f/modules/jpm-core/src/main/java/jpaoletti/jpm/core/Highlights.java#L81-L92 |
lotaris/jee-validation | src/main/java/com/lotaris/jee/validation/JsonValidationContext.java | JsonValidationContext.addState | public <T> JsonValidationContext addState(T state, Class<? extends T> stateClass) throws IllegalArgumentException {
"""
Adds the specified state object to this validation context. It can be retrieved by passing
the identifying class to {@link #getState(java.lang.Class)}.
@param <T> the type of state
@param state the state object to register
@param stateClass the class identifying the state
@return this context
@throws IllegalArgumentException if a state is already registered for that class
"""
// only accept one state of each class
if (this.states.containsKey(state.getClass())) {
throw new IllegalArgumentException("A state object is already registered for class " + state.getClass().getName());
}
this.states.put(state.getClass(), state);
return this;
} | java | public <T> JsonValidationContext addState(T state, Class<? extends T> stateClass) throws IllegalArgumentException {
// only accept one state of each class
if (this.states.containsKey(state.getClass())) {
throw new IllegalArgumentException("A state object is already registered for class " + state.getClass().getName());
}
this.states.put(state.getClass(), state);
return this;
} | [
"public",
"<",
"T",
">",
"JsonValidationContext",
"addState",
"(",
"T",
"state",
",",
"Class",
"<",
"?",
"extends",
"T",
">",
"stateClass",
")",
"throws",
"IllegalArgumentException",
"{",
"// only accept one state of each class",
"if",
"(",
"this",
".",
"states",
... | Adds the specified state object to this validation context. It can be retrieved by passing
the identifying class to {@link #getState(java.lang.Class)}.
@param <T> the type of state
@param state the state object to register
@param stateClass the class identifying the state
@return this context
@throws IllegalArgumentException if a state is already registered for that class | [
"Adds",
"the",
"specified",
"state",
"object",
"to",
"this",
"validation",
"context",
".",
"It",
"can",
"be",
"retrieved",
"by",
"passing",
"the",
"identifying",
"class",
"to",
"{",
"@link",
"#getState",
"(",
"java",
".",
"lang",
".",
"Class",
")",
"}",
... | train | https://github.com/lotaris/jee-validation/blob/feefff820b5a67c7471a13e08fdaf2d60bb3ad16/src/main/java/com/lotaris/jee/validation/JsonValidationContext.java#L140-L150 |
redisson/redisson | redisson/src/main/java/org/redisson/api/CronSchedule.java | CronSchedule.dailyAtHourAndMinute | public static CronSchedule dailyAtHourAndMinute(int hour, int minute) {
"""
Creates cron expression which schedule task execution
every day at the given time
@param hour of schedule
@param minute of schedule
@return object
@throws IllegalArgumentException
wrapping a ParseException if the expression is invalid
"""
String expression = String.format("0 %d %d ? * *", minute, hour);
return of(expression);
} | java | public static CronSchedule dailyAtHourAndMinute(int hour, int minute) {
String expression = String.format("0 %d %d ? * *", minute, hour);
return of(expression);
} | [
"public",
"static",
"CronSchedule",
"dailyAtHourAndMinute",
"(",
"int",
"hour",
",",
"int",
"minute",
")",
"{",
"String",
"expression",
"=",
"String",
".",
"format",
"(",
"\"0 %d %d ? * *\"",
",",
"minute",
",",
"hour",
")",
";",
"return",
"of",
"(",
"expres... | Creates cron expression which schedule task execution
every day at the given time
@param hour of schedule
@param minute of schedule
@return object
@throws IllegalArgumentException
wrapping a ParseException if the expression is invalid | [
"Creates",
"cron",
"expression",
"which",
"schedule",
"task",
"execution",
"every",
"day",
"at",
"the",
"given",
"time"
] | train | https://github.com/redisson/redisson/blob/d3acc0249b2d5d658d36d99e2c808ce49332ea44/redisson/src/main/java/org/redisson/api/CronSchedule.java#L60-L63 |
apollographql/apollo-android | apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java | ResponseField.forDouble | public static ResponseField forDouble(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
"""
Factory method for creating a Field instance representing {@link Type#DOUBLE}.
@param responseName alias for the result of a field
@param fieldName name of the field in the GraphQL operation
@param arguments arguments to be passed along with the field
@param optional whether the arguments passed along are optional or required
@param conditions list of conditions for this field
@return Field instance representing {@link Type#DOUBLE}
"""
return new ResponseField(Type.DOUBLE, responseName, fieldName, arguments, optional, conditions);
} | java | public static ResponseField forDouble(String responseName, String fieldName, Map<String, Object> arguments,
boolean optional, List<Condition> conditions) {
return new ResponseField(Type.DOUBLE, responseName, fieldName, arguments, optional, conditions);
} | [
"public",
"static",
"ResponseField",
"forDouble",
"(",
"String",
"responseName",
",",
"String",
"fieldName",
",",
"Map",
"<",
"String",
",",
"Object",
">",
"arguments",
",",
"boolean",
"optional",
",",
"List",
"<",
"Condition",
">",
"conditions",
")",
"{",
"... | Factory method for creating a Field instance representing {@link Type#DOUBLE}.
@param responseName alias for the result of a field
@param fieldName name of the field in the GraphQL operation
@param arguments arguments to be passed along with the field
@param optional whether the arguments passed along are optional or required
@param conditions list of conditions for this field
@return Field instance representing {@link Type#DOUBLE} | [
"Factory",
"method",
"for",
"creating",
"a",
"Field",
"instance",
"representing",
"{",
"@link",
"Type#DOUBLE",
"}",
"."
] | train | https://github.com/apollographql/apollo-android/blob/a78869a76e17f77e42c7a88f0099914fe7ffa5b6/apollo-api/src/main/java/com/apollographql/apollo/api/ResponseField.java#L85-L88 |
jayantk/jklol | src/com/jayantkrish/jklol/models/dynamic/DynamicFactorGraphBuilder.java | DynamicFactorGraphBuilder.addUnreplicatedFactor | public void addUnreplicatedFactor(String factorName, Factor factor, VariableNumMap vars) {
"""
Adds an unreplicated factor to the model being
constructed. The factor will match only the variables which it is
defined over.
@param factor
"""
plateFactors.add(new ReplicatedFactor(factor, new WrapperVariablePattern(vars)));
plateFactorNames.add(factorName);
} | java | public void addUnreplicatedFactor(String factorName, Factor factor, VariableNumMap vars) {
plateFactors.add(new ReplicatedFactor(factor, new WrapperVariablePattern(vars)));
plateFactorNames.add(factorName);
} | [
"public",
"void",
"addUnreplicatedFactor",
"(",
"String",
"factorName",
",",
"Factor",
"factor",
",",
"VariableNumMap",
"vars",
")",
"{",
"plateFactors",
".",
"add",
"(",
"new",
"ReplicatedFactor",
"(",
"factor",
",",
"new",
"WrapperVariablePattern",
"(",
"vars",
... | Adds an unreplicated factor to the model being
constructed. The factor will match only the variables which it is
defined over.
@param factor | [
"Adds",
"an",
"unreplicated",
"factor",
"to",
"the",
"model",
"being",
"constructed",
".",
"The",
"factor",
"will",
"match",
"only",
"the",
"variables",
"which",
"it",
"is",
"defined",
"over",
"."
] | train | https://github.com/jayantk/jklol/blob/d27532ca83e212d51066cf28f52621acc3fd44cc/src/com/jayantkrish/jklol/models/dynamic/DynamicFactorGraphBuilder.java#L33-L36 |
WASdev/tool.accelerate.core | liberty-starter-application/src/main/java/com/ibm/liberty/starter/build/maven/DomUtil.java | DomUtil.hasChildNode | public static boolean hasChildNode(Node parentNode, String nodeName) {
"""
Determine if the parent node contains a child node with matching name
@param parentNode - the parent node
@param nodeName - name of child node to match
@return boolean value to indicate whether the parent node contains matching child node
"""
return getChildNode(parentNode, nodeName, null) != null ? true : false;
} | java | public static boolean hasChildNode(Node parentNode, String nodeName){
return getChildNode(parentNode, nodeName, null) != null ? true : false;
} | [
"public",
"static",
"boolean",
"hasChildNode",
"(",
"Node",
"parentNode",
",",
"String",
"nodeName",
")",
"{",
"return",
"getChildNode",
"(",
"parentNode",
",",
"nodeName",
",",
"null",
")",
"!=",
"null",
"?",
"true",
":",
"false",
";",
"}"
] | Determine if the parent node contains a child node with matching name
@param parentNode - the parent node
@param nodeName - name of child node to match
@return boolean value to indicate whether the parent node contains matching child node | [
"Determine",
"if",
"the",
"parent",
"node",
"contains",
"a",
"child",
"node",
"with",
"matching",
"name"
] | train | https://github.com/WASdev/tool.accelerate.core/blob/6511da654a69a25a76573eb76eefff349d9c4d80/liberty-starter-application/src/main/java/com/ibm/liberty/starter/build/maven/DomUtil.java#L39-L41 |
ops4j/org.ops4j.pax.logging | pax-logging-api/src/main/java/org/apache/logging/log4j/Level.java | Level.toLevel | public static Level toLevel(final String name, final Level defaultLevel) {
"""
Converts the string passed as argument to a level. If the conversion fails, then this method returns the value of
<code>defaultLevel</code>.
@param name The name of the desired Level.
@param defaultLevel The Level to use if the String is invalid.
@return The Level associated with the String.
"""
if (name == null) {
return defaultLevel;
}
final Level level = LEVELS.get(toUpperCase(name));
return level == null ? defaultLevel : level;
} | java | public static Level toLevel(final String name, final Level defaultLevel) {
if (name == null) {
return defaultLevel;
}
final Level level = LEVELS.get(toUpperCase(name));
return level == null ? defaultLevel : level;
} | [
"public",
"static",
"Level",
"toLevel",
"(",
"final",
"String",
"name",
",",
"final",
"Level",
"defaultLevel",
")",
"{",
"if",
"(",
"name",
"==",
"null",
")",
"{",
"return",
"defaultLevel",
";",
"}",
"final",
"Level",
"level",
"=",
"LEVELS",
".",
"get",
... | Converts the string passed as argument to a level. If the conversion fails, then this method returns the value of
<code>defaultLevel</code>.
@param name The name of the desired Level.
@param defaultLevel The Level to use if the String is invalid.
@return The Level associated with the String. | [
"Converts",
"the",
"string",
"passed",
"as",
"argument",
"to",
"a",
"level",
".",
"If",
"the",
"conversion",
"fails",
"then",
"this",
"method",
"returns",
"the",
"value",
"of",
"<code",
">",
"defaultLevel<",
"/",
"code",
">",
"."
] | train | https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/Level.java#L283-L289 |
pgjdbc/pgjdbc | pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java | TimestampUtils.toLocalDateTimeBin | public LocalDateTime toLocalDateTimeBin(TimeZone tz, byte[] bytes) throws PSQLException {
"""
Returns the local date time object matching the given bytes with {@link Oid#TIMESTAMP} or
{@link Oid#TIMESTAMPTZ}.
@param tz time zone to use
@param bytes The binary encoded local date time value.
@return The parsed local date time object.
@throws PSQLException If binary format could not be parsed.
"""
ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(tz, bytes, true);
if (parsedTimestamp.infinity == Infinity.POSITIVE) {
return LocalDateTime.MAX;
} else if (parsedTimestamp.infinity == Infinity.NEGATIVE) {
return LocalDateTime.MIN;
}
return LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, ZoneOffset.UTC);
} | java | public LocalDateTime toLocalDateTimeBin(TimeZone tz, byte[] bytes) throws PSQLException {
ParsedBinaryTimestamp parsedTimestamp = this.toParsedTimestampBin(tz, bytes, true);
if (parsedTimestamp.infinity == Infinity.POSITIVE) {
return LocalDateTime.MAX;
} else if (parsedTimestamp.infinity == Infinity.NEGATIVE) {
return LocalDateTime.MIN;
}
return LocalDateTime.ofEpochSecond(parsedTimestamp.millis / 1000L, parsedTimestamp.nanos, ZoneOffset.UTC);
} | [
"public",
"LocalDateTime",
"toLocalDateTimeBin",
"(",
"TimeZone",
"tz",
",",
"byte",
"[",
"]",
"bytes",
")",
"throws",
"PSQLException",
"{",
"ParsedBinaryTimestamp",
"parsedTimestamp",
"=",
"this",
".",
"toParsedTimestampBin",
"(",
"tz",
",",
"bytes",
",",
"true",... | Returns the local date time object matching the given bytes with {@link Oid#TIMESTAMP} or
{@link Oid#TIMESTAMPTZ}.
@param tz time zone to use
@param bytes The binary encoded local date time value.
@return The parsed local date time object.
@throws PSQLException If binary format could not be parsed. | [
"Returns",
"the",
"local",
"date",
"time",
"object",
"matching",
"the",
"given",
"bytes",
"with",
"{",
"@link",
"Oid#TIMESTAMP",
"}",
"or",
"{",
"@link",
"Oid#TIMESTAMPTZ",
"}",
"."
] | train | https://github.com/pgjdbc/pgjdbc/blob/95ba7b261e39754674c5817695ae5ebf9a341fae/pgjdbc/src/main/java/org/postgresql/jdbc/TimestampUtils.java#L1133-L1143 |
camunda/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java | LegacyBehavior.getScopeExecution | public static PvmExecutionImpl getScopeExecution(ScopeImpl scope, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
"""
In case the process instance was migrated from a previous version, activities which are now parsed as scopes
do not have scope executions. Use the flow scopes of these activities in order to find their execution.
- For an event subprocess this is the scope execution of the scope in which the event subprocess is embeded in
- For a multi instance sequential subprocess this is the multi instace scope body.
@param scope
@param activityExecutionMapping
@return
"""
ScopeImpl flowScope = scope.getFlowScope();
return activityExecutionMapping.get(flowScope);
} | java | public static PvmExecutionImpl getScopeExecution(ScopeImpl scope, Map<ScopeImpl, PvmExecutionImpl> activityExecutionMapping) {
ScopeImpl flowScope = scope.getFlowScope();
return activityExecutionMapping.get(flowScope);
} | [
"public",
"static",
"PvmExecutionImpl",
"getScopeExecution",
"(",
"ScopeImpl",
"scope",
",",
"Map",
"<",
"ScopeImpl",
",",
"PvmExecutionImpl",
">",
"activityExecutionMapping",
")",
"{",
"ScopeImpl",
"flowScope",
"=",
"scope",
".",
"getFlowScope",
"(",
")",
";",
"r... | In case the process instance was migrated from a previous version, activities which are now parsed as scopes
do not have scope executions. Use the flow scopes of these activities in order to find their execution.
- For an event subprocess this is the scope execution of the scope in which the event subprocess is embeded in
- For a multi instance sequential subprocess this is the multi instace scope body.
@param scope
@param activityExecutionMapping
@return | [
"In",
"case",
"the",
"process",
"instance",
"was",
"migrated",
"from",
"a",
"previous",
"version",
"activities",
"which",
"are",
"now",
"parsed",
"as",
"scopes",
"do",
"not",
"have",
"scope",
"executions",
".",
"Use",
"the",
"flow",
"scopes",
"of",
"these",
... | train | https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/engine/impl/pvm/runtime/LegacyBehavior.java#L231-L234 |
stapler/stapler | jruby/src/main/java/org/kohsuke/stapler/jelly/jruby/AbstractRubyTearOff.java | AbstractRubyTearOff.createDispatcher | public RequestDispatcher createDispatcher(Object it, String viewName) throws IOException {
"""
Creates a {@link RequestDispatcher} that forwards to the jelly view, if available.
"""
Script script = findScript(viewName+getDefaultScriptExtension());
if(script!=null)
return new JellyRequestDispatcher(it,script);
return null;
} | java | public RequestDispatcher createDispatcher(Object it, String viewName) throws IOException {
Script script = findScript(viewName+getDefaultScriptExtension());
if(script!=null)
return new JellyRequestDispatcher(it,script);
return null;
} | [
"public",
"RequestDispatcher",
"createDispatcher",
"(",
"Object",
"it",
",",
"String",
"viewName",
")",
"throws",
"IOException",
"{",
"Script",
"script",
"=",
"findScript",
"(",
"viewName",
"+",
"getDefaultScriptExtension",
"(",
")",
")",
";",
"if",
"(",
"script... | Creates a {@link RequestDispatcher} that forwards to the jelly view, if available. | [
"Creates",
"a",
"{"
] | train | https://github.com/stapler/stapler/blob/11ad5af185e062fb46e01bf9fbed66f3ebf2a8f7/jruby/src/main/java/org/kohsuke/stapler/jelly/jruby/AbstractRubyTearOff.java#L36-L41 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-native-api/src/main/java/org/nd4j/autodiff/execution/NativeGraphExecutioner.java | NativeGraphExecutioner.executeGraph | @Override
public INDArray[] executeGraph(SameDiff sd) {
"""
This method executes given graph and returns results
PLEASE NOTE: Default configuration is used
@param sd
@return
"""
return executeGraph(sd, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).executionMode(ExecutionMode.SEQUENTIAL).profilingMode(OpExecutioner.ProfilingMode.DISABLED).build());
} | java | @Override
public INDArray[] executeGraph(SameDiff sd) {
return executeGraph(sd, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).executionMode(ExecutionMode.SEQUENTIAL).profilingMode(OpExecutioner.ProfilingMode.DISABLED).build());
} | [
"@",
"Override",
"public",
"INDArray",
"[",
"]",
"executeGraph",
"(",
"SameDiff",
"sd",
")",
"{",
"return",
"executeGraph",
"(",
"sd",
",",
"ExecutorConfiguration",
".",
"builder",
"(",
")",
".",
"outputMode",
"(",
"OutputMode",
".",
"IMPLICIT",
")",
".",
... | This method executes given graph and returns results
PLEASE NOTE: Default configuration is used
@param sd
@return | [
"This",
"method",
"executes",
"given",
"graph",
"and",
"returns",
"results"
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-native-api/src/main/java/org/nd4j/autodiff/execution/NativeGraphExecutioner.java#L73-L76 |
twitter/hbc | hbc-core/src/main/java/com/twitter/hbc/common/IOUtils.java | IOUtils.readFully | public static void readFully(Reader reader, char[] buffer, int offset) throws IOException {
"""
Reads enough chars from the reader to fill the remainder of the buffer (reads length - offset chars).
@throws IOException if an I/O error occurs, or if the stream ends before filling the entire buffer.
"""
int originalOffset = offset;
int expected = buffer.length - offset;
while (offset < buffer.length) {
int numRead = reader.read(buffer, offset, buffer.length - offset);
if (numRead < 0) {
throw new IOException(
String.format("Reached end of stream earlier than expected. Expected to read %d bytes. Actual: %d",
expected, offset - originalOffset));
}
offset += numRead;
}
} | java | public static void readFully(Reader reader, char[] buffer, int offset) throws IOException {
int originalOffset = offset;
int expected = buffer.length - offset;
while (offset < buffer.length) {
int numRead = reader.read(buffer, offset, buffer.length - offset);
if (numRead < 0) {
throw new IOException(
String.format("Reached end of stream earlier than expected. Expected to read %d bytes. Actual: %d",
expected, offset - originalOffset));
}
offset += numRead;
}
} | [
"public",
"static",
"void",
"readFully",
"(",
"Reader",
"reader",
",",
"char",
"[",
"]",
"buffer",
",",
"int",
"offset",
")",
"throws",
"IOException",
"{",
"int",
"originalOffset",
"=",
"offset",
";",
"int",
"expected",
"=",
"buffer",
".",
"length",
"-",
... | Reads enough chars from the reader to fill the remainder of the buffer (reads length - offset chars).
@throws IOException if an I/O error occurs, or if the stream ends before filling the entire buffer. | [
"Reads",
"enough",
"chars",
"from",
"the",
"reader",
"to",
"fill",
"the",
"remainder",
"of",
"the",
"buffer",
"(",
"reads",
"length",
"-",
"offset",
"chars",
")",
"."
] | train | https://github.com/twitter/hbc/blob/72a8d0b44ba824a722cf4ee7ed9f9bc34d02d92c/hbc-core/src/main/java/com/twitter/hbc/common/IOUtils.java#L24-L36 |
Azure/azure-sdk-for-java | cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java | ModelsImpl.getPrebuilt | public PrebuiltEntityExtractor getPrebuilt(UUID appId, String versionId, UUID prebuiltId) {
"""
Gets information about the prebuilt entity model.
@param appId The application ID.
@param versionId The version ID.
@param prebuiltId The prebuilt entity extractor ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PrebuiltEntityExtractor object if successful.
"""
return getPrebuiltWithServiceResponseAsync(appId, versionId, prebuiltId).toBlocking().single().body();
} | java | public PrebuiltEntityExtractor getPrebuilt(UUID appId, String versionId, UUID prebuiltId) {
return getPrebuiltWithServiceResponseAsync(appId, versionId, prebuiltId).toBlocking().single().body();
} | [
"public",
"PrebuiltEntityExtractor",
"getPrebuilt",
"(",
"UUID",
"appId",
",",
"String",
"versionId",
",",
"UUID",
"prebuiltId",
")",
"{",
"return",
"getPrebuiltWithServiceResponseAsync",
"(",
"appId",
",",
"versionId",
",",
"prebuiltId",
")",
".",
"toBlocking",
"("... | Gets information about the prebuilt entity model.
@param appId The application ID.
@param versionId The version ID.
@param prebuiltId The prebuilt entity extractor ID.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the PrebuiltEntityExtractor object if successful. | [
"Gets",
"information",
"about",
"the",
"prebuilt",
"entity",
"model",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/cognitiveservices/data-plane/language/luis/authoring/src/main/java/com/microsoft/azure/cognitiveservices/language/luis/authoring/implementation/ModelsImpl.java#L4689-L4691 |
facebookarchive/hadoop-20 | src/hdfs/org/apache/hadoop/hdfs/BlockReader.java | BlockReader.sendReadResult | void sendReadResult(Socket sock, int statusCode) {
"""
When the reader reaches end of the read, it sends a status response
(e.g. CHECKSUM_OK) to the DN. Failure to do so could lead to the DN
closing our connection (which we will re-open), but won't affect
data correctness.
@param sock
@param statusCode
"""
assert !sentStatusCode : "already sent status code to " + sock;
try {
OutputStream out = NetUtils.getOutputStream(sock, HdfsConstants.WRITE_TIMEOUT);
byte buf[] = { (byte) ((statusCode >>> 8) & 0xff),
(byte) ((statusCode) & 0xff) };
out.write(buf);
out.flush();
sentStatusCode = true;
} catch (IOException e) {
// its ok not to be able to send this.
LOG.debug("Could not write to datanode " + sock.getInetAddress() +
": " + e.getMessage());
}
} | java | void sendReadResult(Socket sock, int statusCode) {
assert !sentStatusCode : "already sent status code to " + sock;
try {
OutputStream out = NetUtils.getOutputStream(sock, HdfsConstants.WRITE_TIMEOUT);
byte buf[] = { (byte) ((statusCode >>> 8) & 0xff),
(byte) ((statusCode) & 0xff) };
out.write(buf);
out.flush();
sentStatusCode = true;
} catch (IOException e) {
// its ok not to be able to send this.
LOG.debug("Could not write to datanode " + sock.getInetAddress() +
": " + e.getMessage());
}
} | [
"void",
"sendReadResult",
"(",
"Socket",
"sock",
",",
"int",
"statusCode",
")",
"{",
"assert",
"!",
"sentStatusCode",
":",
"\"already sent status code to \"",
"+",
"sock",
";",
"try",
"{",
"OutputStream",
"out",
"=",
"NetUtils",
".",
"getOutputStream",
"(",
"soc... | When the reader reaches end of the read, it sends a status response
(e.g. CHECKSUM_OK) to the DN. Failure to do so could lead to the DN
closing our connection (which we will re-open), but won't affect
data correctness.
@param sock
@param statusCode | [
"When",
"the",
"reader",
"reaches",
"end",
"of",
"the",
"read",
"it",
"sends",
"a",
"status",
"response",
"(",
"e",
".",
"g",
".",
"CHECKSUM_OK",
")",
"to",
"the",
"DN",
".",
"Failure",
"to",
"do",
"so",
"could",
"lead",
"to",
"the",
"DN",
"closing",... | train | https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/BlockReader.java#L653-L668 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/StatisticsInner.java | StatisticsInner.listByAutomationAccount | public List<StatisticsModelInner> listByAutomationAccount(String resourceGroupName, String automationAccountName, String filter) {
"""
Retrieve the statistics for the account.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param filter The filter to apply on the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<StatisticsModelInner> object if successful.
"""
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName, filter).toBlocking().single().body();
} | java | public List<StatisticsModelInner> listByAutomationAccount(String resourceGroupName, String automationAccountName, String filter) {
return listByAutomationAccountWithServiceResponseAsync(resourceGroupName, automationAccountName, filter).toBlocking().single().body();
} | [
"public",
"List",
"<",
"StatisticsModelInner",
">",
"listByAutomationAccount",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"filter",
")",
"{",
"return",
"listByAutomationAccountWithServiceResponseAsync",
"(",
"resourceGroupName",... | Retrieve the statistics for the account.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param filter The filter to apply on the operation.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the List<StatisticsModelInner> object if successful. | [
"Retrieve",
"the",
"statistics",
"for",
"the",
"account",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/StatisticsInner.java#L155-L157 |
mabe02/lanterna | src/main/java/com/googlecode/lanterna/gui2/dialogs/ListSelectDialog.java | ListSelectDialog.showDialog | public static <T> T showDialog(WindowBasedTextGUI textGUI, String title, String description, T... items) {
"""
Shortcut for quickly creating a new dialog
@param textGUI Text GUI to add the dialog to
@param title Title of the dialog
@param description Description of the dialog
@param items Items in the dialog
@param <T> Type of items in the dialog
@return The selected item or {@code null} if cancelled
"""
return showDialog(textGUI, title, description, null, items);
} | java | public static <T> T showDialog(WindowBasedTextGUI textGUI, String title, String description, T... items) {
return showDialog(textGUI, title, description, null, items);
} | [
"public",
"static",
"<",
"T",
">",
"T",
"showDialog",
"(",
"WindowBasedTextGUI",
"textGUI",
",",
"String",
"title",
",",
"String",
"description",
",",
"T",
"...",
"items",
")",
"{",
"return",
"showDialog",
"(",
"textGUI",
",",
"title",
",",
"description",
... | Shortcut for quickly creating a new dialog
@param textGUI Text GUI to add the dialog to
@param title Title of the dialog
@param description Description of the dialog
@param items Items in the dialog
@param <T> Type of items in the dialog
@return The selected item or {@code null} if cancelled | [
"Shortcut",
"for",
"quickly",
"creating",
"a",
"new",
"dialog"
] | train | https://github.com/mabe02/lanterna/blob/8dfd62206ff46ab10223b2ef2dbb0a2c51850954/src/main/java/com/googlecode/lanterna/gui2/dialogs/ListSelectDialog.java#L128-L130 |
jbundle/webapp | proxy/src/main/java/org/jbundle/util/webapp/proxy/ProxyServlet.java | ProxyServlet.transferURLStream | public static void transferURLStream(InputStream streamIn, OutputStream streamOut) {
"""
Transfer the data stream from this URL to another stream.
@param strURL The URL to read.
@param strFilename If non-null, create this file and send the URL data here.
@param strFilename If null, return the stream as a string.
@param in If this is non-null, read from this input source.
@return The stream as a string if filename is null.
"""
try {
byte[] cbuf = new byte[1000];
int iLen = 0;
while ((iLen = streamIn.read(cbuf, 0, cbuf.length)) > 0)
{ // Write the entire file to the output buffer
streamOut.write(cbuf, 0, iLen);
}
streamIn.close();
if (streamIn != null)
streamIn.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
} | java | public static void transferURLStream(InputStream streamIn, OutputStream streamOut)
{
try {
byte[] cbuf = new byte[1000];
int iLen = 0;
while ((iLen = streamIn.read(cbuf, 0, cbuf.length)) > 0)
{ // Write the entire file to the output buffer
streamOut.write(cbuf, 0, iLen);
}
streamIn.close();
if (streamIn != null)
streamIn.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
} | [
"public",
"static",
"void",
"transferURLStream",
"(",
"InputStream",
"streamIn",
",",
"OutputStream",
"streamOut",
")",
"{",
"try",
"{",
"byte",
"[",
"]",
"cbuf",
"=",
"new",
"byte",
"[",
"1000",
"]",
";",
"int",
"iLen",
"=",
"0",
";",
"while",
"(",
"(... | Transfer the data stream from this URL to another stream.
@param strURL The URL to read.
@param strFilename If non-null, create this file and send the URL data here.
@param strFilename If null, return the stream as a string.
@param in If this is non-null, read from this input source.
@return The stream as a string if filename is null. | [
"Transfer",
"the",
"data",
"stream",
"from",
"this",
"URL",
"to",
"another",
"stream",
"."
] | train | https://github.com/jbundle/webapp/blob/af2cf32bd92254073052f1f9b4bcd47c2f76ba7d/proxy/src/main/java/org/jbundle/util/webapp/proxy/ProxyServlet.java#L225-L242 |
openengsb/openengsb | components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/RemoveLeadingOperation.java | RemoveLeadingOperation.performRemoveLeading | private String performRemoveLeading(String source, Integer length, Matcher matcher) {
"""
Perform the remove leading operation. Returns the original string if the matcher does not match with the string
"""
if (length != null && length != 0) {
matcher.region(0, length);
}
if (matcher.find()) {
String matched = matcher.group();
return source.substring(matched.length());
}
return source;
} | java | private String performRemoveLeading(String source, Integer length, Matcher matcher) {
if (length != null && length != 0) {
matcher.region(0, length);
}
if (matcher.find()) {
String matched = matcher.group();
return source.substring(matched.length());
}
return source;
} | [
"private",
"String",
"performRemoveLeading",
"(",
"String",
"source",
",",
"Integer",
"length",
",",
"Matcher",
"matcher",
")",
"{",
"if",
"(",
"length",
"!=",
"null",
"&&",
"length",
"!=",
"0",
")",
"{",
"matcher",
".",
"region",
"(",
"0",
",",
"length"... | Perform the remove leading operation. Returns the original string if the matcher does not match with the string | [
"Perform",
"the",
"remove",
"leading",
"operation",
".",
"Returns",
"the",
"original",
"string",
"if",
"the",
"matcher",
"does",
"not",
"match",
"with",
"the",
"string"
] | train | https://github.com/openengsb/openengsb/blob/d39058000707f617cd405629f9bc7f17da7b414a/components/ekb/transformation-wonderland/src/main/java/org/openengsb/core/ekb/transformation/wonderland/internal/operation/RemoveLeadingOperation.java#L75-L84 |
google/error-prone-javac | src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java | TreeScanner.visitArrayAccess | @Override
public R visitArrayAccess(ArrayAccessTree node, P p) {
"""
{@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning
"""
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getIndex(), p, r);
return r;
} | java | @Override
public R visitArrayAccess(ArrayAccessTree node, P p) {
R r = scan(node.getExpression(), p);
r = scanAndReduce(node.getIndex(), p, r);
return r;
} | [
"@",
"Override",
"public",
"R",
"visitArrayAccess",
"(",
"ArrayAccessTree",
"node",
",",
"P",
"p",
")",
"{",
"R",
"r",
"=",
"scan",
"(",
"node",
".",
"getExpression",
"(",
")",
",",
"p",
")",
";",
"r",
"=",
"scanAndReduce",
"(",
"node",
".",
"getInde... | {@inheritDoc} This implementation scans the children in left to right order.
@param node {@inheritDoc}
@param p {@inheritDoc}
@return the result of scanning | [
"{",
"@inheritDoc",
"}",
"This",
"implementation",
"scans",
"the",
"children",
"in",
"left",
"to",
"right",
"order",
"."
] | train | https://github.com/google/error-prone-javac/blob/a53d069bbdb2c60232ed3811c19b65e41c3e60e0/src/jdk.compiler/share/classes/com/sun/source/util/TreeScanner.java#L664-L669 |
matthewhorridge/owlapi-gwt | owlapi-gwt-serialization/src/main/java/org/semanticweb/owlapi/model/EntityType_CustomFieldSerializer.java | EntityType_CustomFieldSerializer.serializeInstance | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, EntityType instance) throws SerializationException {
"""
Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful
"""
serialize(streamWriter, instance);
} | java | @Override
public void serializeInstance(SerializationStreamWriter streamWriter, EntityType instance) throws SerializationException {
serialize(streamWriter, instance);
} | [
"@",
"Override",
"public",
"void",
"serializeInstance",
"(",
"SerializationStreamWriter",
"streamWriter",
",",
"EntityType",
"instance",
")",
"throws",
"SerializationException",
"{",
"serialize",
"(",
"streamWriter",
",",
"instance",
")",
";",
"}"
] | Serializes the content of the object into the
{@link com.google.gwt.user.client.rpc.SerializationStreamWriter}.
@param streamWriter the {@link com.google.gwt.user.client.rpc.SerializationStreamWriter} to write the
object's content to
@param instance the object instance to serialize
@throws com.google.gwt.user.client.rpc.SerializationException
if the serialization operation is not
successful | [
"Serializes",
"the",
"content",
"of",
"the",
"object",
"into",
"the",
"{"
] | train | https://github.com/matthewhorridge/owlapi-gwt/blob/7ab975fb6cef3c8947099983551672a3b5d4e2fd/owlapi-gwt-serialization/src/main/java/org/semanticweb/owlapi/model/EntityType_CustomFieldSerializer.java#L95-L98 |
sagiegurari/fax4j | src/main/java/org/fax4j/common/JDKLogger.java | JDKLogger.logImpl | @Override
protected void logImpl(LogLevel level,Object[] message,Throwable throwable) {
"""
Logs the provided data.
@param level
The log level
@param message
The message parts (may be null)
@param throwable
The error (may be null)
"""
//get log level
int levelValue=level.getValue();
Level jdkLevel=null;
switch(levelValue)
{
case LogLevel.DEBUG_LOG_LEVEL_VALUE:
jdkLevel=Level.FINEST;
break;
case LogLevel.ERROR_LOG_LEVEL_VALUE:
jdkLevel=Level.SEVERE;
break;
case LogLevel.INFO_LOG_LEVEL_VALUE:
default:
jdkLevel=Level.FINE;
break;
}
if(jdkLevel!=null)
{
//format log message (without exception)
String text=this.formatLogMessage(level,message,null);
//log
this.JDK_LOGGER.log(jdkLevel,text,throwable);
}
} | java | @Override
protected void logImpl(LogLevel level,Object[] message,Throwable throwable)
{
//get log level
int levelValue=level.getValue();
Level jdkLevel=null;
switch(levelValue)
{
case LogLevel.DEBUG_LOG_LEVEL_VALUE:
jdkLevel=Level.FINEST;
break;
case LogLevel.ERROR_LOG_LEVEL_VALUE:
jdkLevel=Level.SEVERE;
break;
case LogLevel.INFO_LOG_LEVEL_VALUE:
default:
jdkLevel=Level.FINE;
break;
}
if(jdkLevel!=null)
{
//format log message (without exception)
String text=this.formatLogMessage(level,message,null);
//log
this.JDK_LOGGER.log(jdkLevel,text,throwable);
}
} | [
"@",
"Override",
"protected",
"void",
"logImpl",
"(",
"LogLevel",
"level",
",",
"Object",
"[",
"]",
"message",
",",
"Throwable",
"throwable",
")",
"{",
"//get log level",
"int",
"levelValue",
"=",
"level",
".",
"getValue",
"(",
")",
";",
"Level",
"jdkLevel",... | Logs the provided data.
@param level
The log level
@param message
The message parts (may be null)
@param throwable
The error (may be null) | [
"Logs",
"the",
"provided",
"data",
"."
] | train | https://github.com/sagiegurari/fax4j/blob/42fa51acabe7bf279e27ab3dd1cf76146b27955f/src/main/java/org/fax4j/common/JDKLogger.java#L76-L104 |
Ordinastie/MalisisCore | src/main/java/net/malisis/core/client/gui/element/position/Positions.java | Positions.middleAlignedTo | public static <T extends IPositioned & ISized> IntSupplier middleAlignedTo(ISized owner, T other, int offset) {
"""
Middle aligns the owner to the other.
@param <T> the generic type
@param other the other
@param offset the offset
@return the int supplier
"""
checkNotNull(other);
return () -> {
return (int) (other.position().y() + Math.ceil(((float) other.size().height() - owner.size().height()) / 2) + offset);
};
} | java | public static <T extends IPositioned & ISized> IntSupplier middleAlignedTo(ISized owner, T other, int offset)
{
checkNotNull(other);
return () -> {
return (int) (other.position().y() + Math.ceil(((float) other.size().height() - owner.size().height()) / 2) + offset);
};
} | [
"public",
"static",
"<",
"T",
"extends",
"IPositioned",
"&",
"ISized",
">",
"IntSupplier",
"middleAlignedTo",
"(",
"ISized",
"owner",
",",
"T",
"other",
",",
"int",
"offset",
")",
"{",
"checkNotNull",
"(",
"other",
")",
";",
"return",
"(",
")",
"->",
"{"... | Middle aligns the owner to the other.
@param <T> the generic type
@param other the other
@param offset the offset
@return the int supplier | [
"Middle",
"aligns",
"the",
"owner",
"to",
"the",
"other",
"."
] | train | https://github.com/Ordinastie/MalisisCore/blob/4f8e1fa462d5c372fc23414482ba9f429881cc54/src/main/java/net/malisis/core/client/gui/element/position/Positions.java#L307-L313 |
Azure/azure-sdk-for-java | appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java | AppServiceCertificateOrdersInner.beginCreateOrUpdate | public AppServiceCertificateOrderInner beginCreateOrUpdate(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) {
"""
Create or update a certificate purchase order.
Create or update a certificate purchase order.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param certificateOrderName Name of the certificate order.
@param certificateDistinguishedName Distinguished name to to use for the certificate order.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the AppServiceCertificateOrderInner object if successful.
"""
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).toBlocking().single().body();
} | java | public AppServiceCertificateOrderInner beginCreateOrUpdate(String resourceGroupName, String certificateOrderName, AppServiceCertificateOrderInner certificateDistinguishedName) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, certificateOrderName, certificateDistinguishedName).toBlocking().single().body();
} | [
"public",
"AppServiceCertificateOrderInner",
"beginCreateOrUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"certificateOrderName",
",",
"AppServiceCertificateOrderInner",
"certificateDistinguishedName",
")",
"{",
"return",
"beginCreateOrUpdateWithServiceResponseAsync",
"(... | Create or update a certificate purchase order.
Create or update a certificate purchase order.
@param resourceGroupName Name of the resource group to which the resource belongs.
@param certificateOrderName Name of the certificate order.
@param certificateDistinguishedName Distinguished name to to use for the certificate order.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws DefaultErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the AppServiceCertificateOrderInner object if successful. | [
"Create",
"or",
"update",
"a",
"certificate",
"purchase",
"order",
".",
"Create",
"or",
"update",
"a",
"certificate",
"purchase",
"order",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/appservice/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/appservice/v2018_02_01/implementation/AppServiceCertificateOrdersInner.java#L675-L677 |
Alluxio/alluxio | core/client/fs/src/main/java/alluxio/client/file/FileSystemUtils.java | FileSystemUtils.waitCompleted | public static boolean waitCompleted(FileSystem fs, AlluxioURI uri)
throws IOException, AlluxioException, InterruptedException {
"""
Shortcut for {@code waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS)}, i.e., wait for an
indefinite amount of time. Note that if a file is never completed, the thread will block
forever, so use with care.
@param fs a {@link FileSystem} instance
@param uri the URI of the file on which the thread should wait
@return true if the file is complete when this method returns and false if the method timed out
before the file was complete.
@throws InterruptedException if the thread receives an interrupt while waiting for file
completion
@see #waitCompleted(FileSystem, AlluxioURI, long, TimeUnit)
"""
return FileSystemUtils.waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS);
} | java | public static boolean waitCompleted(FileSystem fs, AlluxioURI uri)
throws IOException, AlluxioException, InterruptedException {
return FileSystemUtils.waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS);
} | [
"public",
"static",
"boolean",
"waitCompleted",
"(",
"FileSystem",
"fs",
",",
"AlluxioURI",
"uri",
")",
"throws",
"IOException",
",",
"AlluxioException",
",",
"InterruptedException",
"{",
"return",
"FileSystemUtils",
".",
"waitCompleted",
"(",
"fs",
",",
"uri",
",... | Shortcut for {@code waitCompleted(fs, uri, -1, TimeUnit.MILLISECONDS)}, i.e., wait for an
indefinite amount of time. Note that if a file is never completed, the thread will block
forever, so use with care.
@param fs a {@link FileSystem} instance
@param uri the URI of the file on which the thread should wait
@return true if the file is complete when this method returns and false if the method timed out
before the file was complete.
@throws InterruptedException if the thread receives an interrupt while waiting for file
completion
@see #waitCompleted(FileSystem, AlluxioURI, long, TimeUnit) | [
"Shortcut",
"for",
"{",
"@code",
"waitCompleted",
"(",
"fs",
"uri",
"-",
"1",
"TimeUnit",
".",
"MILLISECONDS",
")",
"}",
"i",
".",
"e",
".",
"wait",
"for",
"an",
"indefinite",
"amount",
"of",
"time",
".",
"Note",
"that",
"if",
"a",
"file",
"is",
"nev... | train | https://github.com/Alluxio/alluxio/blob/af38cf3ab44613355b18217a3a4d961f8fec3a10/core/client/fs/src/main/java/alluxio/client/file/FileSystemUtils.java#L55-L58 |
bramp/ffmpeg-cli-wrapper | src/main/java/net/bramp/ffmpeg/builder/AbstractFFmpegStreamBuilder.java | AbstractFFmpegStreamBuilder.setDuration | public T setDuration(long duration, TimeUnit units) {
"""
Stop writing the output after duration is reached.
@param duration The duration
@param units The units the duration is in
@return this
"""
checkNotNull(units);
this.duration = units.toMillis(duration);
return getThis();
} | java | public T setDuration(long duration, TimeUnit units) {
checkNotNull(units);
this.duration = units.toMillis(duration);
return getThis();
} | [
"public",
"T",
"setDuration",
"(",
"long",
"duration",
",",
"TimeUnit",
"units",
")",
"{",
"checkNotNull",
"(",
"units",
")",
";",
"this",
".",
"duration",
"=",
"units",
".",
"toMillis",
"(",
"duration",
")",
";",
"return",
"getThis",
"(",
")",
";",
"}... | Stop writing the output after duration is reached.
@param duration The duration
@param units The units the duration is in
@return this | [
"Stop",
"writing",
"the",
"output",
"after",
"duration",
"is",
"reached",
"."
] | train | https://github.com/bramp/ffmpeg-cli-wrapper/blob/3819b155edf9132acc75bb6af66dcef1b98c64b2/src/main/java/net/bramp/ffmpeg/builder/AbstractFFmpegStreamBuilder.java#L447-L453 |
hazelcast/hazelcast | hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortableUtils.java | PortableUtils.getStreamPositionOfTheField | static int getStreamPositionOfTheField(FieldDefinition fd, BufferObjectDataInput in, int offset) throws IOException {
"""
Calculates the position of the given field in the portable byte stream
@param fd given field definition
@param in data input stream
@param offset offset to use while stream reading
@return position of the given field
@throws IOException on any stream errors
"""
int pos = in.readInt(offset + fd.getIndex() * Bits.INT_SIZE_IN_BYTES);
short len = in.readShort(pos);
// name + len + type
return pos + Bits.SHORT_SIZE_IN_BYTES + len + 1;
} | java | static int getStreamPositionOfTheField(FieldDefinition fd, BufferObjectDataInput in, int offset) throws IOException {
int pos = in.readInt(offset + fd.getIndex() * Bits.INT_SIZE_IN_BYTES);
short len = in.readShort(pos);
// name + len + type
return pos + Bits.SHORT_SIZE_IN_BYTES + len + 1;
} | [
"static",
"int",
"getStreamPositionOfTheField",
"(",
"FieldDefinition",
"fd",
",",
"BufferObjectDataInput",
"in",
",",
"int",
"offset",
")",
"throws",
"IOException",
"{",
"int",
"pos",
"=",
"in",
".",
"readInt",
"(",
"offset",
"+",
"fd",
".",
"getIndex",
"(",
... | Calculates the position of the given field in the portable byte stream
@param fd given field definition
@param in data input stream
@param offset offset to use while stream reading
@return position of the given field
@throws IOException on any stream errors | [
"Calculates",
"the",
"position",
"of",
"the",
"given",
"field",
"in",
"the",
"portable",
"byte",
"stream"
] | train | https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/serialization/impl/PortableUtils.java#L79-L84 |
FINRAOS/JTAF-ExtWebDriver | src/main/java/org/finra/jtaf/ewd/session/SessionManager.java | SessionManager.getNewSession | public ExtWebDriver getNewSession(boolean setAsCurrent) throws Exception {
"""
Create and return new ExtWebDriver instance with default options. If
setAsCurrent is true, set the new session as the current session for this
SessionManager.
@param setAsCurrent
set to true if the new session should become the current
session for this SessionManager
@return A new ExtWebDriver session
@throws Exception
"""
Map<String, String> options = sessionFactory.get().createDefaultOptions();
return getNewSessionDo(options, setAsCurrent);
} | java | public ExtWebDriver getNewSession(boolean setAsCurrent) throws Exception {
Map<String, String> options = sessionFactory.get().createDefaultOptions();
return getNewSessionDo(options, setAsCurrent);
} | [
"public",
"ExtWebDriver",
"getNewSession",
"(",
"boolean",
"setAsCurrent",
")",
"throws",
"Exception",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"options",
"=",
"sessionFactory",
".",
"get",
"(",
")",
".",
"createDefaultOptions",
"(",
")",
";",
"return",
... | Create and return new ExtWebDriver instance with default options. If
setAsCurrent is true, set the new session as the current session for this
SessionManager.
@param setAsCurrent
set to true if the new session should become the current
session for this SessionManager
@return A new ExtWebDriver session
@throws Exception | [
"Create",
"and",
"return",
"new",
"ExtWebDriver",
"instance",
"with",
"default",
"options",
".",
"If",
"setAsCurrent",
"is",
"true",
"set",
"the",
"new",
"session",
"as",
"the",
"current",
"session",
"for",
"this",
"SessionManager",
"."
] | train | https://github.com/FINRAOS/JTAF-ExtWebDriver/blob/78d646def1bf0904f79b19a81df0241e07f2c73a/src/main/java/org/finra/jtaf/ewd/session/SessionManager.java#L248-L251 |
igniterealtime/Smack | smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java | AdHocCommandManager.respondError | private static IQ respondError(AdHocCommandData response, StanzaError.Builder error) {
"""
Responds an error with an specific error.
@param response the response to send.
@param error the error to send.
@throws NotConnectedException
"""
response.setType(IQ.Type.error);
response.setError(error);
return response;
} | java | private static IQ respondError(AdHocCommandData response, StanzaError.Builder error) {
response.setType(IQ.Type.error);
response.setError(error);
return response;
} | [
"private",
"static",
"IQ",
"respondError",
"(",
"AdHocCommandData",
"response",
",",
"StanzaError",
".",
"Builder",
"error",
")",
"{",
"response",
".",
"setType",
"(",
"IQ",
".",
"Type",
".",
"error",
")",
";",
"response",
".",
"setError",
"(",
"error",
")... | Responds an error with an specific error.
@param response the response to send.
@param error the error to send.
@throws NotConnectedException | [
"Responds",
"an",
"error",
"with",
"an",
"specific",
"error",
"."
] | train | https://github.com/igniterealtime/Smack/blob/870756997faec1e1bfabfac0cd6c2395b04da873/smack-extensions/src/main/java/org/jivesoftware/smackx/commands/AdHocCommandManager.java#L594-L598 |
LearnLib/learnlib | algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java | AbstractTTTLearner.markAndPropagate | private static <I, D> void markAndPropagate(AbstractBaseDTNode<I, D> node, D label) {
"""
Marks a node, and propagates the label up to all nodes on the path from the block root to this node.
@param node
the node to mark
@param label
the label to mark the node with
"""
AbstractBaseDTNode<I, D> curr = node;
while (curr != null && curr.getSplitData() != null) {
if (!curr.getSplitData().mark(label)) {
return;
}
curr = curr.getParent();
}
} | java | private static <I, D> void markAndPropagate(AbstractBaseDTNode<I, D> node, D label) {
AbstractBaseDTNode<I, D> curr = node;
while (curr != null && curr.getSplitData() != null) {
if (!curr.getSplitData().mark(label)) {
return;
}
curr = curr.getParent();
}
} | [
"private",
"static",
"<",
"I",
",",
"D",
">",
"void",
"markAndPropagate",
"(",
"AbstractBaseDTNode",
"<",
"I",
",",
"D",
">",
"node",
",",
"D",
"label",
")",
"{",
"AbstractBaseDTNode",
"<",
"I",
",",
"D",
">",
"curr",
"=",
"node",
";",
"while",
"(",
... | Marks a node, and propagates the label up to all nodes on the path from the block root to this node.
@param node
the node to mark
@param label
the label to mark the node with | [
"Marks",
"a",
"node",
"and",
"propagates",
"the",
"label",
"up",
"to",
"all",
"nodes",
"on",
"the",
"path",
"from",
"the",
"block",
"root",
"to",
"this",
"node",
"."
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/algorithms/active/ttt/src/main/java/de/learnlib/algorithms/ttt/base/AbstractTTTLearner.java#L99-L108 |
JOML-CI/JOML | src/org/joml/Matrix4f.java | Matrix4f.transformProject | public Vector4f transformProject(float x, float y, float z, float w, Vector4f dest) {
"""
/* (non-Javadoc)
@see org.joml.Matrix4fc#transformProject(float, float, float, float, org.joml.Vector4f)
"""
dest.x = x;
dest.y = y;
dest.z = z;
dest.w = w;
return dest.mulProject(this);
} | java | public Vector4f transformProject(float x, float y, float z, float w, Vector4f dest) {
dest.x = x;
dest.y = y;
dest.z = z;
dest.w = w;
return dest.mulProject(this);
} | [
"public",
"Vector4f",
"transformProject",
"(",
"float",
"x",
",",
"float",
"y",
",",
"float",
"z",
",",
"float",
"w",
",",
"Vector4f",
"dest",
")",
"{",
"dest",
".",
"x",
"=",
"x",
";",
"dest",
".",
"y",
"=",
"y",
";",
"dest",
".",
"z",
"=",
"z... | /* (non-Javadoc)
@see org.joml.Matrix4fc#transformProject(float, float, float, float, org.joml.Vector4f) | [
"/",
"*",
"(",
"non",
"-",
"Javadoc",
")"
] | train | https://github.com/JOML-CI/JOML/blob/ce2652fc236b42bda3875c591f8e6645048a678f/src/org/joml/Matrix4f.java#L4553-L4559 |
beangle/beangle3 | commons/core/src/main/java/org/beangle/commons/lang/Strings.java | Strings.substringBefore | public static String substringBefore(String str, String separator) {
"""
<p>
Gets the substring before the first occurrence of a separator. The separator is not returned.
</p>
<p>
A {@code null} string input will return {@code null}. An empty ("") string input will return
the empty string. A {@code null} separator will return the input string.
</p>
<p>
If nothing is found, the string input is returned.
</p>
<pre>
substringBefore(null, *) = null
substringBefore("", *) = ""
substringBefore("abc", "a") = ""
substringBefore("abcba", "b") = "a"
substringBefore("abc", "c") = "ab"
substringBefore("abc", "d") = "abc"
substringBefore("abc", "") = ""
substringBefore("abc", null) = "abc"
</pre>
@param str the String to get a substring from, may be null
@param separator the String to search for, may be null
@return the substring before the first occurrence of the separator, {@code null} if null String
input
@since 2.0
"""
if (isEmpty(str) || separator == null) { return str; }
if (separator.length() == 0) { return Empty; }
int pos = str.indexOf(separator);
if (pos == Index_not_found) { return str; }
return str.substring(0, pos);
} | java | public static String substringBefore(String str, String separator) {
if (isEmpty(str) || separator == null) { return str; }
if (separator.length() == 0) { return Empty; }
int pos = str.indexOf(separator);
if (pos == Index_not_found) { return str; }
return str.substring(0, pos);
} | [
"public",
"static",
"String",
"substringBefore",
"(",
"String",
"str",
",",
"String",
"separator",
")",
"{",
"if",
"(",
"isEmpty",
"(",
"str",
")",
"||",
"separator",
"==",
"null",
")",
"{",
"return",
"str",
";",
"}",
"if",
"(",
"separator",
".",
"leng... | <p>
Gets the substring before the first occurrence of a separator. The separator is not returned.
</p>
<p>
A {@code null} string input will return {@code null}. An empty ("") string input will return
the empty string. A {@code null} separator will return the input string.
</p>
<p>
If nothing is found, the string input is returned.
</p>
<pre>
substringBefore(null, *) = null
substringBefore("", *) = ""
substringBefore("abc", "a") = ""
substringBefore("abcba", "b") = "a"
substringBefore("abc", "c") = "ab"
substringBefore("abc", "d") = "abc"
substringBefore("abc", "") = ""
substringBefore("abc", null) = "abc"
</pre>
@param str the String to get a substring from, may be null
@param separator the String to search for, may be null
@return the substring before the first occurrence of the separator, {@code null} if null String
input
@since 2.0 | [
"<p",
">",
"Gets",
"the",
"substring",
"before",
"the",
"first",
"occurrence",
"of",
"a",
"separator",
".",
"The",
"separator",
"is",
"not",
"returned",
".",
"<",
"/",
"p",
">",
"<p",
">",
"A",
"{",
"@code",
"null",
"}",
"string",
"input",
"will",
"r... | train | https://github.com/beangle/beangle3/blob/33df2873a5f38e28ac174a1d3b8144eb2f808e64/commons/core/src/main/java/org/beangle/commons/lang/Strings.java#L1206-L1212 |
VoltDB/voltdb | src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java | JDBC4DatabaseMetaData.supportsConvert | @Override
public boolean supportsConvert(int fromType, int toType) throws SQLException {
"""
Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType.
"""
checkClosed();
switch (fromType) {
/*
* ALL types can be converted to VARCHAR /VoltType.String
*/
case java.sql.Types.VARCHAR:
case java.sql.Types.VARBINARY:
case java.sql.Types.TIMESTAMP:
case java.sql.Types.OTHER:
switch (toType) {
case java.sql.Types.VARCHAR:
return true;
default:
return false;
}
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
case java.sql.Types.BIGINT:
case java.sql.Types.FLOAT:
case java.sql.Types.DECIMAL:
switch (toType) {
case java.sql.Types.VARCHAR:
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
case java.sql.Types.BIGINT:
case java.sql.Types.FLOAT:
case java.sql.Types.DECIMAL:
return true;
default:
return false;
}
default:
return false;
}
} | java | @Override
public boolean supportsConvert(int fromType, int toType) throws SQLException {
checkClosed();
switch (fromType) {
/*
* ALL types can be converted to VARCHAR /VoltType.String
*/
case java.sql.Types.VARCHAR:
case java.sql.Types.VARBINARY:
case java.sql.Types.TIMESTAMP:
case java.sql.Types.OTHER:
switch (toType) {
case java.sql.Types.VARCHAR:
return true;
default:
return false;
}
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
case java.sql.Types.BIGINT:
case java.sql.Types.FLOAT:
case java.sql.Types.DECIMAL:
switch (toType) {
case java.sql.Types.VARCHAR:
case java.sql.Types.TINYINT:
case java.sql.Types.SMALLINT:
case java.sql.Types.INTEGER:
case java.sql.Types.BIGINT:
case java.sql.Types.FLOAT:
case java.sql.Types.DECIMAL:
return true;
default:
return false;
}
default:
return false;
}
} | [
"@",
"Override",
"public",
"boolean",
"supportsConvert",
"(",
"int",
"fromType",
",",
"int",
"toType",
")",
"throws",
"SQLException",
"{",
"checkClosed",
"(",
")",
";",
"switch",
"(",
"fromType",
")",
"{",
"/*\n * ALL types can be converted to VARCHAR /VoltTyp... | Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType. | [
"Retrieves",
"whether",
"this",
"database",
"supports",
"the",
"JDBC",
"scalar",
"function",
"CONVERT",
"for",
"conversions",
"between",
"the",
"JDBC",
"types",
"fromType",
"and",
"toType",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java#L1206-L1246 |
lightblueseas/jcommons-lang | src/main/java/de/alpharogroup/lang/BooleanExtensions.java | BooleanExtensions.trueOrFalse | public static <T> T trueOrFalse(final T trueCase, final T falseCase, final boolean... flags) {
"""
Decides over the given flags if the true-case or the false-case will be return.
@param <T>
the generic type
@param trueCase
the object to return in true case
@param falseCase
the object to return in false case
@param flags
the flags whice decide what to return
@return the false-case if all false or empty otherwise the true-case.
"""
boolean interlink = true;
if (flags != null && 0 < flags.length)
{
interlink = false;
}
for (int i = 0; i < flags.length; i++)
{
if (i == 0)
{
interlink = !flags[i];
continue;
}
interlink &= !flags[i];
}
if (interlink)
{
return falseCase;
}
return trueCase;
} | java | public static <T> T trueOrFalse(final T trueCase, final T falseCase, final boolean... flags)
{
boolean interlink = true;
if (flags != null && 0 < flags.length)
{
interlink = false;
}
for (int i = 0; i < flags.length; i++)
{
if (i == 0)
{
interlink = !flags[i];
continue;
}
interlink &= !flags[i];
}
if (interlink)
{
return falseCase;
}
return trueCase;
} | [
"public",
"static",
"<",
"T",
">",
"T",
"trueOrFalse",
"(",
"final",
"T",
"trueCase",
",",
"final",
"T",
"falseCase",
",",
"final",
"boolean",
"...",
"flags",
")",
"{",
"boolean",
"interlink",
"=",
"true",
";",
"if",
"(",
"flags",
"!=",
"null",
"&&",
... | Decides over the given flags if the true-case or the false-case will be return.
@param <T>
the generic type
@param trueCase
the object to return in true case
@param falseCase
the object to return in false case
@param flags
the flags whice decide what to return
@return the false-case if all false or empty otherwise the true-case. | [
"Decides",
"over",
"the",
"given",
"flags",
"if",
"the",
"true",
"-",
"case",
"or",
"the",
"false",
"-",
"case",
"will",
"be",
"return",
"."
] | train | https://github.com/lightblueseas/jcommons-lang/blob/000e1f198e949ec3e721fd0fc3f5946e945232a3/src/main/java/de/alpharogroup/lang/BooleanExtensions.java#L49-L70 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/translator/document/XMLEncodingDetector.java | XMLEncodingDetector.skipString | public boolean skipString(String s) throws IOException {
"""
Skips the specified string appearing immediately on the input.
<p>
<strong>Note:</strong> The characters are consumed only if they are
space characters.
@param s The string to skip.
@return Returns true if the string was skipped.
@throws IOException Thrown if i/o error occurs.
@throws EOFException Thrown on end of file.
"""
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
return false;
}
}
}
fCurrentEntity.columnNumber += length;
return true;
} | java | public boolean skipString(String s) throws IOException {
// load more characters, if needed
if (fCurrentEntity.position == fCurrentEntity.count) {
load(0, true);
}
// skip string
final int length = s.length();
for (int i = 0; i < length; i++) {
char c = fCurrentEntity.ch[fCurrentEntity.position++];
if (c != s.charAt(i)) {
fCurrentEntity.position -= i + 1;
return false;
}
if (i < length - 1 && fCurrentEntity.position == fCurrentEntity.count) {
System.arraycopy(fCurrentEntity.ch, fCurrentEntity.count - i - 1, fCurrentEntity.ch, 0, i + 1);
// REVISIT: Can a string to be skipped cross an
// entity boundary? -Ac
if (load(i + 1, false)) {
fCurrentEntity.position -= i + 1;
return false;
}
}
}
fCurrentEntity.columnNumber += length;
return true;
} | [
"public",
"boolean",
"skipString",
"(",
"String",
"s",
")",
"throws",
"IOException",
"{",
"// load more characters, if needed",
"if",
"(",
"fCurrentEntity",
".",
"position",
"==",
"fCurrentEntity",
".",
"count",
")",
"{",
"load",
"(",
"0",
",",
"true",
")",
";... | Skips the specified string appearing immediately on the input.
<p>
<strong>Note:</strong> The characters are consumed only if they are
space characters.
@param s The string to skip.
@return Returns true if the string was skipped.
@throws IOException Thrown if i/o error occurs.
@throws EOFException Thrown on end of file. | [
"Skips",
"the",
"specified",
"string",
"appearing",
"immediately",
"on",
"the",
"input",
".",
"<p",
">",
"<strong",
">",
"Note",
":",
"<",
"/",
"strong",
">",
"The",
"characters",
"are",
"consumed",
"only",
"if",
"they",
"are",
"space",
"characters",
"."
] | train | https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/translator/document/XMLEncodingDetector.java#L940-L968 |
drapostolos/type-parser | src/main/java/com/github/drapostolos/typeparser/Helper.java | Helper.getParameterizedClassArgumentByIndex | public final <T> Class<T> getParameterizedClassArgumentByIndex(int index) {
"""
Convenient method that returns the specified element in the list (as returned from method
{@link ParserHelper#getParameterizedClassArguments()}).
@param index index of the element to return
@return the element at the specified position in the list (as returned from method
{@link ParserHelper#getParameterizedClassArguments()}).
@throws IndexOutOfBoundsException if the index is out of range
(<tt>index < 0 || index >= size()</tt>)
@throws UnsupportedOperationException if the {@code targetType} is not a parameterized type.
@throws UnsupportedOperationException if any of the parameterized type arguments is of a
parameterized type (with exception of {@link Class}).
"""
List<Class<?>> list = getParameterizedClassArguments();
if (index > list.size() - 1 || index < 0) {
String message = "index %s is out of bounds. Should be within [0, %s]";
throw new IndexOutOfBoundsException(String.format(message, index, list.size() - 1));
}
@SuppressWarnings("unchecked")
Class<T> temp = (Class<T>) list.get(index);
return temp;
} | java | public final <T> Class<T> getParameterizedClassArgumentByIndex(int index) {
List<Class<?>> list = getParameterizedClassArguments();
if (index > list.size() - 1 || index < 0) {
String message = "index %s is out of bounds. Should be within [0, %s]";
throw new IndexOutOfBoundsException(String.format(message, index, list.size() - 1));
}
@SuppressWarnings("unchecked")
Class<T> temp = (Class<T>) list.get(index);
return temp;
} | [
"public",
"final",
"<",
"T",
">",
"Class",
"<",
"T",
">",
"getParameterizedClassArgumentByIndex",
"(",
"int",
"index",
")",
"{",
"List",
"<",
"Class",
"<",
"?",
">",
">",
"list",
"=",
"getParameterizedClassArguments",
"(",
")",
";",
"if",
"(",
"index",
"... | Convenient method that returns the specified element in the list (as returned from method
{@link ParserHelper#getParameterizedClassArguments()}).
@param index index of the element to return
@return the element at the specified position in the list (as returned from method
{@link ParserHelper#getParameterizedClassArguments()}).
@throws IndexOutOfBoundsException if the index is out of range
(<tt>index < 0 || index >= size()</tt>)
@throws UnsupportedOperationException if the {@code targetType} is not a parameterized type.
@throws UnsupportedOperationException if any of the parameterized type arguments is of a
parameterized type (with exception of {@link Class}). | [
"Convenient",
"method",
"that",
"returns",
"the",
"specified",
"element",
"in",
"the",
"list",
"(",
"as",
"returned",
"from",
"method",
"{",
"@link",
"ParserHelper#getParameterizedClassArguments",
"()",
"}",
")",
"."
] | train | https://github.com/drapostolos/type-parser/blob/74c66311f8dd009897c74ab5069e36c045cda073/src/main/java/com/github/drapostolos/typeparser/Helper.java#L76-L85 |
geomajas/geomajas-project-server | impl/src/main/java/org/geomajas/spring/ThreadScopeContext.java | ThreadScopeContext.registerDestructionCallback | public void registerDestructionCallback(String name, Runnable callback) {
"""
Register the given callback as to be executed after request completion.
@param name The name of the bean.
@param callback The callback of the bean to be executed for destruction.
"""
Bean bean = beans.get(name);
if (null == bean) {
bean = new Bean();
beans.put(name, bean);
}
bean.destructionCallback = callback;
} | java | public void registerDestructionCallback(String name, Runnable callback) {
Bean bean = beans.get(name);
if (null == bean) {
bean = new Bean();
beans.put(name, bean);
}
bean.destructionCallback = callback;
} | [
"public",
"void",
"registerDestructionCallback",
"(",
"String",
"name",
",",
"Runnable",
"callback",
")",
"{",
"Bean",
"bean",
"=",
"beans",
".",
"get",
"(",
"name",
")",
";",
"if",
"(",
"null",
"==",
"bean",
")",
"{",
"bean",
"=",
"new",
"Bean",
"(",
... | Register the given callback as to be executed after request completion.
@param name The name of the bean.
@param callback The callback of the bean to be executed for destruction. | [
"Register",
"the",
"given",
"callback",
"as",
"to",
"be",
"executed",
"after",
"request",
"completion",
"."
] | train | https://github.com/geomajas/geomajas-project-server/blob/904b7d7deed1350d28955589098dd1e0a786d76e/impl/src/main/java/org/geomajas/spring/ThreadScopeContext.java#L78-L85 |
structr/structr | structr-ui/src/main/java/org/structr/web/common/FileHelper.java | FileHelper.createFile | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final String contentType, final Class<T> fileType, final String name)
throws FrameworkException, IOException {
"""
Create a new file node from the given input stream
@param <T>
@param securityContext
@param fileStream
@param contentType
@param fileType defaults to File.class if null
@param name
@return file
@throws FrameworkException
@throws IOException
"""
return createFile(securityContext, fileStream, contentType, fileType, name, null);
} | java | public static <T extends File> T createFile(final SecurityContext securityContext, final InputStream fileStream, final String contentType, final Class<T> fileType, final String name)
throws FrameworkException, IOException {
return createFile(securityContext, fileStream, contentType, fileType, name, null);
} | [
"public",
"static",
"<",
"T",
"extends",
"File",
">",
"T",
"createFile",
"(",
"final",
"SecurityContext",
"securityContext",
",",
"final",
"InputStream",
"fileStream",
",",
"final",
"String",
"contentType",
",",
"final",
"Class",
"<",
"T",
">",
"fileType",
","... | Create a new file node from the given input stream
@param <T>
@param securityContext
@param fileStream
@param contentType
@param fileType defaults to File.class if null
@param name
@return file
@throws FrameworkException
@throws IOException | [
"Create",
"a",
"new",
"file",
"node",
"from",
"the",
"given",
"input",
"stream"
] | train | https://github.com/structr/structr/blob/c111a1d0c0201c7fea5574ed69aa5a5053185a97/structr-ui/src/main/java/org/structr/web/common/FileHelper.java#L131-L136 |
google/j2objc | jre_emul/android/platform/libcore/luni/src/main/java/org/xml/sax/helpers/AttributesImpl.java | AttributesImpl.setLocalName | public void setLocalName (int index, String localName) {
"""
Set the local name of a specific attribute.
@param index The index of the attribute (zero-based).
@param localName The attribute's local name, or the empty
string for none.
@exception java.lang.ArrayIndexOutOfBoundsException When the
supplied index does not point to an attribute
in the list.
"""
if (index >= 0 && index < length) {
data[index*5+1] = localName;
} else {
badIndex(index);
}
} | java | public void setLocalName (int index, String localName)
{
if (index >= 0 && index < length) {
data[index*5+1] = localName;
} else {
badIndex(index);
}
} | [
"public",
"void",
"setLocalName",
"(",
"int",
"index",
",",
"String",
"localName",
")",
"{",
"if",
"(",
"index",
">=",
"0",
"&&",
"index",
"<",
"length",
")",
"{",
"data",
"[",
"index",
"*",
"5",
"+",
"1",
"]",
"=",
"localName",
";",
"}",
"else",
... | Set the local name of a specific attribute.
@param index The index of the attribute (zero-based).
@param localName The attribute's local name, or the empty
string for none.
@exception java.lang.ArrayIndexOutOfBoundsException When the
supplied index does not point to an attribute
in the list. | [
"Set",
"the",
"local",
"name",
"of",
"a",
"specific",
"attribute",
"."
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/luni/src/main/java/org/xml/sax/helpers/AttributesImpl.java#L486-L493 |
codeprimate-software/cp-elements | src/main/java/org/cp/elements/lang/ObjectUtils.java | ObjectUtils.safeGetValue | public static <T> T safeGetValue(Supplier<T> supplier, T defaultValue) {
"""
Safely returns the value supplied by the given {@link Supplier}. If an {@link Exception} or {@link Error} occurs
then the {@code defaultValue} will be returned.
@param <T> {@link Class} type of the value to get.
@param supplier {@link Supplier} of the value.
@param defaultValue value to return if the {@link Supplier} is unable to supply the value.
@return a value from the given {@link Supplier} in an error safe manner. If an {@link Exception} or {@link Error}
occurs then the {@code defaultValue} will be returned.
@see java.util.function.Supplier
"""
try {
return supplier.get();
}
catch (Throwable ignore) {
return defaultValue;
}
} | java | public static <T> T safeGetValue(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
}
catch (Throwable ignore) {
return defaultValue;
}
} | [
"public",
"static",
"<",
"T",
">",
"T",
"safeGetValue",
"(",
"Supplier",
"<",
"T",
">",
"supplier",
",",
"T",
"defaultValue",
")",
"{",
"try",
"{",
"return",
"supplier",
".",
"get",
"(",
")",
";",
"}",
"catch",
"(",
"Throwable",
"ignore",
")",
"{",
... | Safely returns the value supplied by the given {@link Supplier}. If an {@link Exception} or {@link Error} occurs
then the {@code defaultValue} will be returned.
@param <T> {@link Class} type of the value to get.
@param supplier {@link Supplier} of the value.
@param defaultValue value to return if the {@link Supplier} is unable to supply the value.
@return a value from the given {@link Supplier} in an error safe manner. If an {@link Exception} or {@link Error}
occurs then the {@code defaultValue} will be returned.
@see java.util.function.Supplier | [
"Safely",
"returns",
"the",
"value",
"supplied",
"by",
"the",
"given",
"{",
"@link",
"Supplier",
"}",
".",
"If",
"an",
"{",
"@link",
"Exception",
"}",
"or",
"{",
"@link",
"Error",
"}",
"occurs",
"then",
"the",
"{",
"@code",
"defaultValue",
"}",
"will",
... | train | https://github.com/codeprimate-software/cp-elements/blob/f2163c149fbbef05015e688132064ebcac7c49ab/src/main/java/org/cp/elements/lang/ObjectUtils.java#L263-L271 |
ehcache/ehcache3 | impl/src/main/java/org/ehcache/impl/internal/util/Pacer.java | Pacer.pacedCall | public void pacedCall(Runnable call, Runnable orElse) {
"""
Execute the call at the request page or call the alternative the rest of the time. An example would be to log
a repetitive error once every 30 seconds or always if in debug.
<p>
<pre>{@code
Pacer pacer = new Pacer(30_000);
String errorMessage = "my error";
pacer.pacedCall(() -> log.error(errorMessage), () -> log.debug(errorMessage);
}
</pre>
@param call call to be paced
@param orElse call to be done everytime
"""
long now = timeSource.getTimeMillis();
long end = nextLogTime.get();
if(now >= end && nextLogTime.compareAndSet(end, now + delay)) {
call.run();
} else {
orElse.run();
}
} | java | public void pacedCall(Runnable call, Runnable orElse) {
long now = timeSource.getTimeMillis();
long end = nextLogTime.get();
if(now >= end && nextLogTime.compareAndSet(end, now + delay)) {
call.run();
} else {
orElse.run();
}
} | [
"public",
"void",
"pacedCall",
"(",
"Runnable",
"call",
",",
"Runnable",
"orElse",
")",
"{",
"long",
"now",
"=",
"timeSource",
".",
"getTimeMillis",
"(",
")",
";",
"long",
"end",
"=",
"nextLogTime",
".",
"get",
"(",
")",
";",
"if",
"(",
"now",
">=",
... | Execute the call at the request page or call the alternative the rest of the time. An example would be to log
a repetitive error once every 30 seconds or always if in debug.
<p>
<pre>{@code
Pacer pacer = new Pacer(30_000);
String errorMessage = "my error";
pacer.pacedCall(() -> log.error(errorMessage), () -> log.debug(errorMessage);
}
</pre>
@param call call to be paced
@param orElse call to be done everytime | [
"Execute",
"the",
"call",
"at",
"the",
"request",
"page",
"or",
"call",
"the",
"alternative",
"the",
"rest",
"of",
"the",
"time",
".",
"An",
"example",
"would",
"be",
"to",
"log",
"a",
"repetitive",
"error",
"once",
"every",
"30",
"seconds",
"or",
"alway... | train | https://github.com/ehcache/ehcache3/blob/3cceda57185e522f8d241ddb75146d67ee2af898/impl/src/main/java/org/ehcache/impl/internal/util/Pacer.java#L56-L64 |
Azure/azure-sdk-for-java | resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java | ResourcesInner.beginUpdate | public GenericResourceInner beginUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) {
"""
Updates a resource.
@param resourceGroupName The name of the resource group for the resource. The name is case insensitive.
@param resourceProviderNamespace The namespace of the resource provider.
@param parentResourcePath The parent resource identity.
@param resourceType The resource type of the resource to update.
@param resourceName The name of the resource to update.
@param apiVersion The API version to use for the operation.
@param parameters Parameters for updating the 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 GenericResourceInner object if successful.
"""
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body();
} | java | public GenericResourceInner beginUpdate(String resourceGroupName, String resourceProviderNamespace, String parentResourcePath, String resourceType, String resourceName, String apiVersion, GenericResourceInner parameters) {
return beginUpdateWithServiceResponseAsync(resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters).toBlocking().single().body();
} | [
"public",
"GenericResourceInner",
"beginUpdate",
"(",
"String",
"resourceGroupName",
",",
"String",
"resourceProviderNamespace",
",",
"String",
"parentResourcePath",
",",
"String",
"resourceType",
",",
"String",
"resourceName",
",",
"String",
"apiVersion",
",",
"GenericRe... | Updates a resource.
@param resourceGroupName The name of the resource group for the resource. The name is case insensitive.
@param resourceProviderNamespace The namespace of the resource provider.
@param parentResourcePath The parent resource identity.
@param resourceType The resource type of the resource to update.
@param resourceName The name of the resource to update.
@param apiVersion The API version to use for the operation.
@param parameters Parameters for updating the 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 GenericResourceInner object if successful. | [
"Updates",
"a",
"resource",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/resources/resource-manager/v2018_02_01/src/main/java/com/microsoft/azure/management/resources/v2018_02_01/implementation/ResourcesInner.java#L1619-L1621 |
j-a-w-r/jawr-main-repo | jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/mappings/BundlePathMappingBuilder.java | BundlePathMappingBuilder.joinPaths | private String joinPaths(String dirName, String folderName, boolean generatedResource) {
"""
Normalizes two paths and joins them as a single path.
@param prefix
the path prefix
@param path
the path
@param generatedResource
the flag indicating if the resource has been generated
@return the normalized path
"""
return PathNormalizer.joinPaths(dirName, folderName, generatedResource);
} | java | private String joinPaths(String dirName, String folderName, boolean generatedResource) {
return PathNormalizer.joinPaths(dirName, folderName, generatedResource);
} | [
"private",
"String",
"joinPaths",
"(",
"String",
"dirName",
",",
"String",
"folderName",
",",
"boolean",
"generatedResource",
")",
"{",
"return",
"PathNormalizer",
".",
"joinPaths",
"(",
"dirName",
",",
"folderName",
",",
"generatedResource",
")",
";",
"}"
] | Normalizes two paths and joins them as a single path.
@param prefix
the path prefix
@param path
the path
@param generatedResource
the flag indicating if the resource has been generated
@return the normalized path | [
"Normalizes",
"two",
"paths",
"and",
"joins",
"them",
"as",
"a",
"single",
"path",
"."
] | train | https://github.com/j-a-w-r/jawr-main-repo/blob/5381f6acf461cd2502593c67a77bd6ef9eab848d/jawr/jawr-core/src/main/java/net/jawr/web/resource/bundle/mappings/BundlePathMappingBuilder.java#L333-L336 |
trustathsh/ifmapj | src/main/java/util/CanonicalXML.java | CanonicalXML.toCanonicalXml2 | public String toCanonicalXml2(XMLReader parser, InputSource inputSource, boolean stripSpace) throws Exception {
"""
Create canonical XML silently, throwing exceptions rather than displaying messages
@param parser
@param inputSource
@param stripSpace
@return
@throws Exception
"""
mStrip = stripSpace;
mOut = new StringWriter();
parser.setContentHandler(this);
parser.setErrorHandler(this);
parser.parse(inputSource);
return mOut.toString();
} | java | public String toCanonicalXml2(XMLReader parser, InputSource inputSource, boolean stripSpace) throws Exception {
mStrip = stripSpace;
mOut = new StringWriter();
parser.setContentHandler(this);
parser.setErrorHandler(this);
parser.parse(inputSource);
return mOut.toString();
} | [
"public",
"String",
"toCanonicalXml2",
"(",
"XMLReader",
"parser",
",",
"InputSource",
"inputSource",
",",
"boolean",
"stripSpace",
")",
"throws",
"Exception",
"{",
"mStrip",
"=",
"stripSpace",
";",
"mOut",
"=",
"new",
"StringWriter",
"(",
")",
";",
"parser",
... | Create canonical XML silently, throwing exceptions rather than displaying messages
@param parser
@param inputSource
@param stripSpace
@return
@throws Exception | [
"Create",
"canonical",
"XML",
"silently",
"throwing",
"exceptions",
"rather",
"than",
"displaying",
"messages"
] | train | https://github.com/trustathsh/ifmapj/blob/44ece9e95a3d2a1b7019573ba6178598a6cbdaa3/src/main/java/util/CanonicalXML.java#L132-L139 |
PureSolTechnologies/parsers | parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java | PackratParser.processIgnoredTokens | private void processIgnoredTokens(ParseTreeNode node, int position, int line, MemoEntry progress)
throws TreeException, ParserException {
"""
<p>
This method reads all hidden and ignored tokens from the text and puts them
into the node as children.
</p>
<p>
This is the non-recursive part of the procedure to be called by the packrat
parser. The procedure itself is implemented recursively in
{@link #processIgnoredTrailingTokens(ParseTreeNode, int, int, MemoEntry)}.
</p>
<p>
Attention: This method is package private for testing purposes!
</p>
@param node
is the current node in the {@link ParseTreeNode}
@param position
is the current parsing position.
@throws TreeException
@throws ParserException
"""
MemoEntry newProgress = processIgnoredTokens(node, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if ((!newProgress.getAnswer().equals(Status.FAILED)))
progress.add(newProgress);
} | java | private void processIgnoredTokens(ParseTreeNode node, int position, int line, MemoEntry progress)
throws TreeException, ParserException {
MemoEntry newProgress = processIgnoredTokens(node, position + progress.getDeltaPosition(),
line + progress.getDeltaLine());
if ((!newProgress.getAnswer().equals(Status.FAILED)))
progress.add(newProgress);
} | [
"private",
"void",
"processIgnoredTokens",
"(",
"ParseTreeNode",
"node",
",",
"int",
"position",
",",
"int",
"line",
",",
"MemoEntry",
"progress",
")",
"throws",
"TreeException",
",",
"ParserException",
"{",
"MemoEntry",
"newProgress",
"=",
"processIgnoredTokens",
"... | <p>
This method reads all hidden and ignored tokens from the text and puts them
into the node as children.
</p>
<p>
This is the non-recursive part of the procedure to be called by the packrat
parser. The procedure itself is implemented recursively in
{@link #processIgnoredTrailingTokens(ParseTreeNode, int, int, MemoEntry)}.
</p>
<p>
Attention: This method is package private for testing purposes!
</p>
@param node
is the current node in the {@link ParseTreeNode}
@param position
is the current parsing position.
@throws TreeException
@throws ParserException | [
"<p",
">",
"This",
"method",
"reads",
"all",
"hidden",
"and",
"ignored",
"tokens",
"from",
"the",
"text",
"and",
"puts",
"them",
"into",
"the",
"node",
"as",
"children",
".",
"<",
"/",
"p",
">",
"<p",
">",
"This",
"is",
"the",
"non",
"-",
"recursive"... | train | https://github.com/PureSolTechnologies/parsers/blob/61077223b90d3768ff9445ae13036343c98b63cd/parsers/src/main/java/com/puresoltechnologies/parsers/parser/packrat/PackratParser.java#L612-L618 |
VoltDB/voltdb | src/frontend/org/voltdb/SnapshotDaemon.java | SnapshotDaemon.processUserSnapshotRequestEvent | private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
"""
/*
Process the event generated when the node for a user snapshot request
is created.
"""
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
final JSONObject jsObj = new JSONObject(jsonString);
final String requestId = jsObj.getString("requestId");
final boolean blocking = jsObj.getBoolean(SnapshotUtil.JSON_BLOCK);
/*
* Going to reuse the request object, remove the requestId
* field now that it is consumed
*/
jsObj.remove("requestId");
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
String nonce = jsObj.getString(SnapshotUtil.JSON_NONCE);
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
m_lastInitiationTs = null;
try {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
loggingLog.info("Deferring user snapshot with nonce " + nonce + " until after in-progress snapshot completes");
scheduleSnapshotForLater(jsObj.toString(4), requestId, true);
} else {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing user snapshot request", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e2) {
VoltDB.crashLocalVoltDB("Error resetting watch for user snapshots", true, e2);
}
}
}
});
loggingLog.info("Initiating user snapshot with nonce " + nonce);
initiateSnapshotSave(handle, new Object[]{jsObj.toString(4)}, blocking);
return;
}
} | java | private void processUserSnapshotRequestEvent(final WatchedEvent event) throws Exception {
if (event.getType() == EventType.NodeCreated) {
byte data[] = m_zk.getData(event.getPath(), false, null);
String jsonString = new String(data, "UTF-8");
final JSONObject jsObj = new JSONObject(jsonString);
final String requestId = jsObj.getString("requestId");
final boolean blocking = jsObj.getBoolean(SnapshotUtil.JSON_BLOCK);
/*
* Going to reuse the request object, remove the requestId
* field now that it is consumed
*/
jsObj.remove("requestId");
jsObj.put("perPartitionTxnIds", retrievePerPartitionTransactionIds());
String nonce = jsObj.getString(SnapshotUtil.JSON_NONCE);
final long handle = m_nextCallbackHandle++;
m_procedureCallbacks.put(handle, new ProcedureCallback() {
@Override
public void clientCallback(ClientResponse clientResponse) {
m_lastInitiationTs = null;
try {
/*
* If there is an error then we are done.
*/
if (clientResponse.getStatus() != ClientResponse.SUCCESS) {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
/*
* Now analyze the response. If a snapshot was in progress
* we have to reattempt it later, and send a response to the client
* saying it was queued. Otherwise, forward the response
* failure/success to the client.
*/
if (isSnapshotInProgressResponse(clientResponse)) {
loggingLog.info("Deferring user snapshot with nonce " + nonce + " until after in-progress snapshot completes");
scheduleSnapshotForLater(jsObj.toString(4), requestId, true);
} else {
ClientResponseImpl rimpl = (ClientResponseImpl)clientResponse;
saveResponseToZKAndReset(requestId, rimpl);
return;
}
} catch (Exception e) {
SNAP_LOG.error("Error processing user snapshot request", e);
try {
userSnapshotRequestExistenceCheck(true);
} catch (Exception e2) {
VoltDB.crashLocalVoltDB("Error resetting watch for user snapshots", true, e2);
}
}
}
});
loggingLog.info("Initiating user snapshot with nonce " + nonce);
initiateSnapshotSave(handle, new Object[]{jsObj.toString(4)}, blocking);
return;
}
} | [
"private",
"void",
"processUserSnapshotRequestEvent",
"(",
"final",
"WatchedEvent",
"event",
")",
"throws",
"Exception",
"{",
"if",
"(",
"event",
".",
"getType",
"(",
")",
"==",
"EventType",
".",
"NodeCreated",
")",
"{",
"byte",
"data",
"[",
"]",
"=",
"m_zk"... | /*
Process the event generated when the node for a user snapshot request
is created. | [
"/",
"*",
"Process",
"the",
"event",
"generated",
"when",
"the",
"node",
"for",
"a",
"user",
"snapshot",
"request",
"is",
"created",
"."
] | train | https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/SnapshotDaemon.java#L898-L956 |
apache/groovy | src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java | DefaultGroovyMethods.getMetaClass | public static MetaClass getMetaClass(Object obj) {
"""
Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself.
@param obj The object in question
@return The MetaClass
@since 1.5.0
"""
MetaClass mc = InvokerHelper.getMetaClass(obj);
return new HandleMetaClass(mc, obj);
} | java | public static MetaClass getMetaClass(Object obj) {
MetaClass mc = InvokerHelper.getMetaClass(obj);
return new HandleMetaClass(mc, obj);
} | [
"public",
"static",
"MetaClass",
"getMetaClass",
"(",
"Object",
"obj",
")",
"{",
"MetaClass",
"mc",
"=",
"InvokerHelper",
".",
"getMetaClass",
"(",
"obj",
")",
";",
"return",
"new",
"HandleMetaClass",
"(",
"mc",
",",
"obj",
")",
";",
"}"
] | Obtains a MetaClass for an object either from the registry or in the case of
a GroovyObject from the object itself.
@param obj The object in question
@return The MetaClass
@since 1.5.0 | [
"Obtains",
"a",
"MetaClass",
"for",
"an",
"object",
"either",
"from",
"the",
"registry",
"or",
"in",
"the",
"case",
"of",
"a",
"GroovyObject",
"from",
"the",
"object",
"itself",
"."
] | train | https://github.com/apache/groovy/blob/71cf20addb611bb8d097a59e395fd20bc7f31772/src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java#L17245-L17248 |
jeremybrooks/jinx | src/main/java/net/jeremybrooks/jinx/api/StatsApi.java | StatsApi.getPopularPhotos | public Photos getPopularPhotos(Date date, JinxConstants.PopularPhotoSort sort, Integer perPage, Integer page) throws JinxException {
"""
List the photos with the most views, comments or favorites
This method requires authentication with 'read' permission.
@param date stats will be returned for this date. Optional.
@param sort order in which to sort returned photos. Defaults to views. Optional.
@param perPage number of referrers to return per page. If this argument is omitted, it defaults to
25. The maximum allowed value is 100. Optional.
@param page page of results to return. If this argument is omitted, it defaults to 1. Optional.
@return photos with the most views, comments, or favorites.
@throws JinxException if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.stats.getPopularPhotos.html">flickr.stats.getPopularPhotos</a>
"""
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.stats.getPopularPhotos");
if (date != null) {
params.put("date", JinxUtils.formatDateAsYMD(date));
}
if (sort != null) {
params.put("sort", sort.toString());
}
if (perPage != null) {
params.put("per_page", perPage.toString());
}
if (page != null) {
params.put("page", page.toString());
}
return jinx.flickrGet(params, Photos.class);
} | java | public Photos getPopularPhotos(Date date, JinxConstants.PopularPhotoSort sort, Integer perPage, Integer page) throws JinxException {
Map<String, String> params = new TreeMap<>();
params.put("method", "flickr.stats.getPopularPhotos");
if (date != null) {
params.put("date", JinxUtils.formatDateAsYMD(date));
}
if (sort != null) {
params.put("sort", sort.toString());
}
if (perPage != null) {
params.put("per_page", perPage.toString());
}
if (page != null) {
params.put("page", page.toString());
}
return jinx.flickrGet(params, Photos.class);
} | [
"public",
"Photos",
"getPopularPhotos",
"(",
"Date",
"date",
",",
"JinxConstants",
".",
"PopularPhotoSort",
"sort",
",",
"Integer",
"perPage",
",",
"Integer",
"page",
")",
"throws",
"JinxException",
"{",
"Map",
"<",
"String",
",",
"String",
">",
"params",
"=",... | List the photos with the most views, comments or favorites
This method requires authentication with 'read' permission.
@param date stats will be returned for this date. Optional.
@param sort order in which to sort returned photos. Defaults to views. Optional.
@param perPage number of referrers to return per page. If this argument is omitted, it defaults to
25. The maximum allowed value is 100. Optional.
@param page page of results to return. If this argument is omitted, it defaults to 1. Optional.
@return photos with the most views, comments, or favorites.
@throws JinxException if there are any errors.
@see <a href="https://www.flickr.com/services/api/flickr.stats.getPopularPhotos.html">flickr.stats.getPopularPhotos</a> | [
"List",
"the",
"photos",
"with",
"the",
"most",
"views",
"comments",
"or",
"favorites"
] | train | https://github.com/jeremybrooks/jinx/blob/ab7a4b7462d08bcbfd9b98bd3f5029771c20f6c6/src/main/java/net/jeremybrooks/jinx/api/StatsApi.java#L427-L443 |
sitoolkit/sit-wt-all | sit-wt-runtime/src/main/java/io/sitoolkit/wt/domain/evidence/LogRecord.java | LogRecord.create | public static LogRecord create(SitLogger logger, ElementPosition position, TestStep testStep,
MessagePattern pattern, Object... params) {
"""
次のメッセージを持つ操作ログオブジェクトを作成します。
@param logger
ロガー
@param position
要素位置
@param testStep
テストステップ
@param pattern
メッセージパターン
@param params
メッセージパラメーター
@return 操作ログ
"""
Object[] newParams = new Object[] { testStep.getItemName(), testStep.getLocator() };
newParams = ArrayUtils.addAll(newParams, params);
return create(logger, position, testStep, pattern.getPattern(), newParams);
} | java | public static LogRecord create(SitLogger logger, ElementPosition position, TestStep testStep,
MessagePattern pattern, Object... params) {
Object[] newParams = new Object[] { testStep.getItemName(), testStep.getLocator() };
newParams = ArrayUtils.addAll(newParams, params);
return create(logger, position, testStep, pattern.getPattern(), newParams);
} | [
"public",
"static",
"LogRecord",
"create",
"(",
"SitLogger",
"logger",
",",
"ElementPosition",
"position",
",",
"TestStep",
"testStep",
",",
"MessagePattern",
"pattern",
",",
"Object",
"...",
"params",
")",
"{",
"Object",
"[",
"]",
"newParams",
"=",
"new",
"Ob... | 次のメッセージを持つ操作ログオブジェクトを作成します。
@param logger
ロガー
@param position
要素位置
@param testStep
テストステップ
@param pattern
メッセージパターン
@param params
メッセージパラメーター
@return 操作ログ | [
"次のメッセージを持つ操作ログオブジェクトを作成します。"
] | train | https://github.com/sitoolkit/sit-wt-all/blob/efabde27aa731a5602d2041e137721a22f4fd27a/sit-wt-runtime/src/main/java/io/sitoolkit/wt/domain/evidence/LogRecord.java#L102-L109 |
lievendoclo/Valkyrie-RCP | valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/editor/DefaultDataEditorWidget.java | DefaultDataEditorWidget.executeFilter | @Override
public synchronized void executeFilter(Map<String, Object> parameters) {
"""
Executes filter and fills table in specific manner:
<p/>
<ul>
<li>set baseCriteria if needed</li>
<li>set searchCriteria on filterForm</li>
<li>set searchCriteria on worker</li>
<li>pass parameter map to worker</li>
<li>launch worker to retrieve list from back-end and fill table</li>
<li>when done, set list and execute additional code taking the parameters
into account</li>
</ul>
@param parameters
a number of parameters that can influence this run. Should be
a non-modifiable map or a specific instance.
"""
if (listWorker == null) {
if (dataProvider.supportsBaseCriteria()) {
dataProvider.setBaseCriteria(getBaseCriteria());
}
StatusBar statusBar = getApplicationConfig().windowManager()
.getActiveWindow().getStatusBar();
statusBar.getProgressMonitor().taskStarted(
getApplicationConfig().messageResolver().getMessage("statusBar",
"loadTable", MessageConstants.LABEL),
StatusBarProgressMonitor.UNKNOWN);
// getFilterForm().getCommitCommand().setEnabled(false);
// getRefreshCommand().setEnabled(false);
listWorker = new ListRetrievingWorker();
if (dataProvider.supportsFiltering()) {
if (parameters.containsKey(PARAMETER_FILTER)) {
setFilterModel(parameters.get(PARAMETER_FILTER));
}
listWorker.filterCriteria = getFilterForm().getFilterCriteria();
}
listWorker.parameters = parameters;
log.debug("Execute Filter with criteria: "
+ listWorker.filterCriteria + " and parameters: "
+ parameters);
listWorker.execute();
}
} | java | @Override
public synchronized void executeFilter(Map<String, Object> parameters) {
if (listWorker == null) {
if (dataProvider.supportsBaseCriteria()) {
dataProvider.setBaseCriteria(getBaseCriteria());
}
StatusBar statusBar = getApplicationConfig().windowManager()
.getActiveWindow().getStatusBar();
statusBar.getProgressMonitor().taskStarted(
getApplicationConfig().messageResolver().getMessage("statusBar",
"loadTable", MessageConstants.LABEL),
StatusBarProgressMonitor.UNKNOWN);
// getFilterForm().getCommitCommand().setEnabled(false);
// getRefreshCommand().setEnabled(false);
listWorker = new ListRetrievingWorker();
if (dataProvider.supportsFiltering()) {
if (parameters.containsKey(PARAMETER_FILTER)) {
setFilterModel(parameters.get(PARAMETER_FILTER));
}
listWorker.filterCriteria = getFilterForm().getFilterCriteria();
}
listWorker.parameters = parameters;
log.debug("Execute Filter with criteria: "
+ listWorker.filterCriteria + " and parameters: "
+ parameters);
listWorker.execute();
}
} | [
"@",
"Override",
"public",
"synchronized",
"void",
"executeFilter",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"parameters",
")",
"{",
"if",
"(",
"listWorker",
"==",
"null",
")",
"{",
"if",
"(",
"dataProvider",
".",
"supportsBaseCriteria",
"(",
")",
")... | Executes filter and fills table in specific manner:
<p/>
<ul>
<li>set baseCriteria if needed</li>
<li>set searchCriteria on filterForm</li>
<li>set searchCriteria on worker</li>
<li>pass parameter map to worker</li>
<li>launch worker to retrieve list from back-end and fill table</li>
<li>when done, set list and execute additional code taking the parameters
into account</li>
</ul>
@param parameters
a number of parameters that can influence this run. Should be
a non-modifiable map or a specific instance. | [
"Executes",
"filter",
"and",
"fills",
"table",
"in",
"specific",
"manner",
":",
"<p",
"/",
">",
"<ul",
">",
"<li",
">",
"set",
"baseCriteria",
"if",
"needed<",
"/",
"li",
">",
"<li",
">",
"set",
"searchCriteria",
"on",
"filterForm<",
"/",
"li",
">",
"<... | train | https://github.com/lievendoclo/Valkyrie-RCP/blob/6aad6e640b348cda8f3b0841f6e42025233f1eb8/valkyrie-rcp-core/src/main/java/org/valkyriercp/widget/editor/DefaultDataEditorWidget.java#L480-L511 |
Azure/azure-sdk-for-java | sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java | ManagedDatabasesInner.listByInstanceAsync | public Observable<Page<ManagedDatabaseInner>> listByInstanceAsync(final String resourceGroupName, final String managedInstanceName) {
"""
Gets a list of managed databases.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param managedInstanceName The name of the managed instance.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ManagedDatabaseInner> object
"""
return listByInstanceWithServiceResponseAsync(resourceGroupName, managedInstanceName)
.map(new Func1<ServiceResponse<Page<ManagedDatabaseInner>>, Page<ManagedDatabaseInner>>() {
@Override
public Page<ManagedDatabaseInner> call(ServiceResponse<Page<ManagedDatabaseInner>> response) {
return response.body();
}
});
} | java | public Observable<Page<ManagedDatabaseInner>> listByInstanceAsync(final String resourceGroupName, final String managedInstanceName) {
return listByInstanceWithServiceResponseAsync(resourceGroupName, managedInstanceName)
.map(new Func1<ServiceResponse<Page<ManagedDatabaseInner>>, Page<ManagedDatabaseInner>>() {
@Override
public Page<ManagedDatabaseInner> call(ServiceResponse<Page<ManagedDatabaseInner>> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Page",
"<",
"ManagedDatabaseInner",
">",
">",
"listByInstanceAsync",
"(",
"final",
"String",
"resourceGroupName",
",",
"final",
"String",
"managedInstanceName",
")",
"{",
"return",
"listByInstanceWithServiceResponseAsync",
"(",
"resourceGroup... | Gets a list of managed databases.
@param resourceGroupName The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal.
@param managedInstanceName The name of the managed instance.
@throws IllegalArgumentException thrown if parameters fail the validation
@return the observable to the PagedList<ManagedDatabaseInner> object | [
"Gets",
"a",
"list",
"of",
"managed",
"databases",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/sql/resource-manager/v2017_03_01_preview/src/main/java/com/microsoft/azure/management/sql/v2017_03_01_preview/implementation/ManagedDatabasesInner.java#L336-L344 |
google/j2objc | jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/LanguageTag.java | LanguageTag.parse | public static LanguageTag parse(String languageTag, ParseStatus sts) {
"""
/*
BNF in RFC5464
Language-Tag = langtag ; normal language tags
/ privateuse ; private use tag
/ grandfathered ; grandfathered tags
langtag = language
["-" script]
["-" region]
*("-" variant)
*("-" extension)
["-" privateuse]
language = 2*3ALPHA ; shortest ISO 639 code
["-" extlang] ; sometimes followed by
; extended language subtags
/ 4ALPHA ; or reserved for future use
/ 5*8ALPHA ; or registered language subtag
extlang = 3ALPHA ; selected ISO 639 codes
*2("-" 3ALPHA) ; permanently reserved
script = 4ALPHA ; ISO 15924 code
region = 2ALPHA ; ISO 3166-1 code
/ 3DIGIT ; UN M.49 code
variant = 5*8alphanum ; registered variants
/ (DIGIT 3alphanum)
extension = singleton 1*("-" (2*8alphanum))
; Single alphanumerics
; "x" reserved for private use
singleton = DIGIT ; 0 - 9
/ %x41-57 ; A - W
/ %x59-5A ; Y - Z
/ %x61-77 ; a - w
/ %x79-7A ; y - z
privateuse = "x" 1*("-" (1*8alphanum))
"""
if (sts == null) {
sts = new ParseStatus();
} else {
sts.reset();
}
StringTokenIterator itr;
// Check if the tag is grandfathered
String[] gfmap = GRANDFATHERED.get(LocaleUtils.toLowerString(languageTag));
if (gfmap != null) {
// use preferred mapping
itr = new StringTokenIterator(gfmap[1], SEP);
} else {
itr = new StringTokenIterator(languageTag, SEP);
}
LanguageTag tag = new LanguageTag();
// langtag must start with either language or privateuse
if (tag.parseLanguage(itr, sts)) {
tag.parseExtlangs(itr, sts);
tag.parseScript(itr, sts);
tag.parseRegion(itr, sts);
tag.parseVariants(itr, sts);
tag.parseExtensions(itr, sts);
}
tag.parsePrivateuse(itr, sts);
if (!itr.isDone() && !sts.isError()) {
String s = itr.current();
sts.errorIndex = itr.currentStart();
if (s.length() == 0) {
sts.errorMsg = "Empty subtag";
} else {
sts.errorMsg = "Invalid subtag: " + s;
}
}
return tag;
} | java | public static LanguageTag parse(String languageTag, ParseStatus sts) {
if (sts == null) {
sts = new ParseStatus();
} else {
sts.reset();
}
StringTokenIterator itr;
// Check if the tag is grandfathered
String[] gfmap = GRANDFATHERED.get(LocaleUtils.toLowerString(languageTag));
if (gfmap != null) {
// use preferred mapping
itr = new StringTokenIterator(gfmap[1], SEP);
} else {
itr = new StringTokenIterator(languageTag, SEP);
}
LanguageTag tag = new LanguageTag();
// langtag must start with either language or privateuse
if (tag.parseLanguage(itr, sts)) {
tag.parseExtlangs(itr, sts);
tag.parseScript(itr, sts);
tag.parseRegion(itr, sts);
tag.parseVariants(itr, sts);
tag.parseExtensions(itr, sts);
}
tag.parsePrivateuse(itr, sts);
if (!itr.isDone() && !sts.isError()) {
String s = itr.current();
sts.errorIndex = itr.currentStart();
if (s.length() == 0) {
sts.errorMsg = "Empty subtag";
} else {
sts.errorMsg = "Invalid subtag: " + s;
}
}
return tag;
} | [
"public",
"static",
"LanguageTag",
"parse",
"(",
"String",
"languageTag",
",",
"ParseStatus",
"sts",
")",
"{",
"if",
"(",
"sts",
"==",
"null",
")",
"{",
"sts",
"=",
"new",
"ParseStatus",
"(",
")",
";",
"}",
"else",
"{",
"sts",
".",
"reset",
"(",
")",... | /*
BNF in RFC5464
Language-Tag = langtag ; normal language tags
/ privateuse ; private use tag
/ grandfathered ; grandfathered tags
langtag = language
["-" script]
["-" region]
*("-" variant)
*("-" extension)
["-" privateuse]
language = 2*3ALPHA ; shortest ISO 639 code
["-" extlang] ; sometimes followed by
; extended language subtags
/ 4ALPHA ; or reserved for future use
/ 5*8ALPHA ; or registered language subtag
extlang = 3ALPHA ; selected ISO 639 codes
*2("-" 3ALPHA) ; permanently reserved
script = 4ALPHA ; ISO 15924 code
region = 2ALPHA ; ISO 3166-1 code
/ 3DIGIT ; UN M.49 code
variant = 5*8alphanum ; registered variants
/ (DIGIT 3alphanum)
extension = singleton 1*("-" (2*8alphanum))
; Single alphanumerics
; "x" reserved for private use
singleton = DIGIT ; 0 - 9
/ %x41-57 ; A - W
/ %x59-5A ; Y - Z
/ %x61-77 ; a - w
/ %x79-7A ; y - z
privateuse = "x" 1*("-" (1*8alphanum)) | [
"/",
"*",
"BNF",
"in",
"RFC5464"
] | train | https://github.com/google/j2objc/blob/471504a735b48d5d4ace51afa1542cc4790a921a/jre_emul/android/platform/libcore/ojluni/src/main/java/sun/util/locale/LanguageTag.java#L181-L222 |
twilio/twilio-java | src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java | FlexFlowReader.previousPage | @Override
public Page<FlexFlow> previousPage(final Page<FlexFlow> page,
final TwilioRestClient client) {
"""
Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page
"""
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.FLEXAPI.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | java | @Override
public Page<FlexFlow> previousPage(final Page<FlexFlow> page,
final TwilioRestClient client) {
Request request = new Request(
HttpMethod.GET,
page.getPreviousPageUrl(
Domains.FLEXAPI.toString(),
client.getRegion()
)
);
return pageForRequest(client, request);
} | [
"@",
"Override",
"public",
"Page",
"<",
"FlexFlow",
">",
"previousPage",
"(",
"final",
"Page",
"<",
"FlexFlow",
">",
"page",
",",
"final",
"TwilioRestClient",
"client",
")",
"{",
"Request",
"request",
"=",
"new",
"Request",
"(",
"HttpMethod",
".",
"GET",
"... | Retrieve the previous page from the Twilio API.
@param page current page
@param client TwilioRestClient with which to make the request
@return Previous Page | [
"Retrieve",
"the",
"previous",
"page",
"from",
"the",
"Twilio",
"API",
"."
] | train | https://github.com/twilio/twilio-java/blob/0318974c0a6a152994af167d430255684d5e9b9f/src/main/java/com/twilio/rest/flexapi/v1/FlexFlowReader.java#L112-L123 |
LAW-Unimi/BUbiNG | src/it/unimi/di/law/bubing/util/URLRespectsRobots.java | URLRespectsRobots.apply | public static boolean apply(final char[][] robotsFilter, final URI url) {
"""
Checks whether a specified URL passes a specified robots filter.
@param robotsFilter a robot filter.
@param url a URL to check against {@code robotsFilter}.
@return true if {@code url} passes {@code robotsFilter}.
"""
if (robotsFilter.length == 0) return true;
final String pathQuery = BURL.pathAndQuery(url);
int from = 0;
int to = robotsFilter.length - 1;
while (from <= to) {
final int mid = (from + to) >>> 1;
final int cmp = compare(robotsFilter[mid], pathQuery);
if (cmp < 0) from = mid + 1;
else if (cmp > 0) to = mid - 1;
else return false; // key found (unlikely, but possible)
}
return from == 0 ? true : doesNotStartsWith(pathQuery, robotsFilter[from - 1]);
} | java | public static boolean apply(final char[][] robotsFilter, final URI url) {
if (robotsFilter.length == 0) return true;
final String pathQuery = BURL.pathAndQuery(url);
int from = 0;
int to = robotsFilter.length - 1;
while (from <= to) {
final int mid = (from + to) >>> 1;
final int cmp = compare(robotsFilter[mid], pathQuery);
if (cmp < 0) from = mid + 1;
else if (cmp > 0) to = mid - 1;
else return false; // key found (unlikely, but possible)
}
return from == 0 ? true : doesNotStartsWith(pathQuery, robotsFilter[from - 1]);
} | [
"public",
"static",
"boolean",
"apply",
"(",
"final",
"char",
"[",
"]",
"[",
"]",
"robotsFilter",
",",
"final",
"URI",
"url",
")",
"{",
"if",
"(",
"robotsFilter",
".",
"length",
"==",
"0",
")",
"return",
"true",
";",
"final",
"String",
"pathQuery",
"="... | Checks whether a specified URL passes a specified robots filter.
@param robotsFilter a robot filter.
@param url a URL to check against {@code robotsFilter}.
@return true if {@code url} passes {@code robotsFilter}. | [
"Checks",
"whether",
"a",
"specified",
"URL",
"passes",
"a",
"specified",
"robots",
"filter",
"."
] | train | https://github.com/LAW-Unimi/BUbiNG/blob/e148acc90031a4f3967422705a9fb07ddaf155e4/src/it/unimi/di/law/bubing/util/URLRespectsRobots.java#L214-L227 |
elki-project/elki | addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java | SVGUtil.svgRect | public static Element svgRect(Document document, double x, double y, double w, double h) {
"""
Create a SVG rectangle element.
@param document document to create in (factory)
@param x X coordinate
@param y Y coordinate
@param w Width
@param h Height
@return new element
"""
Element rect = SVGUtil.svgElement(document, SVGConstants.SVG_RECT_TAG);
SVGUtil.setAtt(rect, SVGConstants.SVG_X_ATTRIBUTE, x);
SVGUtil.setAtt(rect, SVGConstants.SVG_Y_ATTRIBUTE, y);
SVGUtil.setAtt(rect, SVGConstants.SVG_WIDTH_ATTRIBUTE, w);
SVGUtil.setAtt(rect, SVGConstants.SVG_HEIGHT_ATTRIBUTE, h);
return rect;
} | java | public static Element svgRect(Document document, double x, double y, double w, double h) {
Element rect = SVGUtil.svgElement(document, SVGConstants.SVG_RECT_TAG);
SVGUtil.setAtt(rect, SVGConstants.SVG_X_ATTRIBUTE, x);
SVGUtil.setAtt(rect, SVGConstants.SVG_Y_ATTRIBUTE, y);
SVGUtil.setAtt(rect, SVGConstants.SVG_WIDTH_ATTRIBUTE, w);
SVGUtil.setAtt(rect, SVGConstants.SVG_HEIGHT_ATTRIBUTE, h);
return rect;
} | [
"public",
"static",
"Element",
"svgRect",
"(",
"Document",
"document",
",",
"double",
"x",
",",
"double",
"y",
",",
"double",
"w",
",",
"double",
"h",
")",
"{",
"Element",
"rect",
"=",
"SVGUtil",
".",
"svgElement",
"(",
"document",
",",
"SVGConstants",
"... | Create a SVG rectangle element.
@param document document to create in (factory)
@param x X coordinate
@param y Y coordinate
@param w Width
@param h Height
@return new element | [
"Create",
"a",
"SVG",
"rectangle",
"element",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/addons/batikvis/src/main/java/de/lmu/ifi/dbs/elki/visualization/svg/SVGUtil.java#L428-L435 |
UrielCh/ovh-java-sdk | ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java | ApiOvhMe.payment_thod_paymentMethodId_finalize_POST | public OvhPaymentMethod payment_thod_paymentMethodId_finalize_POST(Long paymentMethodId, Long expirationMonth, Long expirationYear, String registrationId) throws IOException {
"""
Finalize one payment method registration
REST: POST /me/payment/method/{paymentMethodId}/finalize
@param paymentMethodId [required] Payment method ID
@param expirationMonth [required] Expiration month
@param expirationYear [required] Expiration year
@param registrationId [required] Registration ID
API beta
"""
String qPath = "/me/payment/method/{paymentMethodId}/finalize";
StringBuilder sb = path(qPath, paymentMethodId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "expirationMonth", expirationMonth);
addBody(o, "expirationYear", expirationYear);
addBody(o, "registrationId", registrationId);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhPaymentMethod.class);
} | java | public OvhPaymentMethod payment_thod_paymentMethodId_finalize_POST(Long paymentMethodId, Long expirationMonth, Long expirationYear, String registrationId) throws IOException {
String qPath = "/me/payment/method/{paymentMethodId}/finalize";
StringBuilder sb = path(qPath, paymentMethodId);
HashMap<String, Object>o = new HashMap<String, Object>();
addBody(o, "expirationMonth", expirationMonth);
addBody(o, "expirationYear", expirationYear);
addBody(o, "registrationId", registrationId);
String resp = exec(qPath, "POST", sb.toString(), o);
return convertTo(resp, OvhPaymentMethod.class);
} | [
"public",
"OvhPaymentMethod",
"payment_thod_paymentMethodId_finalize_POST",
"(",
"Long",
"paymentMethodId",
",",
"Long",
"expirationMonth",
",",
"Long",
"expirationYear",
",",
"String",
"registrationId",
")",
"throws",
"IOException",
"{",
"String",
"qPath",
"=",
"\"/me/pa... | Finalize one payment method registration
REST: POST /me/payment/method/{paymentMethodId}/finalize
@param paymentMethodId [required] Payment method ID
@param expirationMonth [required] Expiration month
@param expirationYear [required] Expiration year
@param registrationId [required] Registration ID
API beta | [
"Finalize",
"one",
"payment",
"method",
"registration"
] | train | https://github.com/UrielCh/ovh-java-sdk/blob/6d531a40e56e09701943e334c25f90f640c55701/ovh-java-sdk-me/src/main/java/net/minidev/ovh/api/ApiOvhMe.java#L1112-L1121 |
strator-dev/greenpepper | samples-application/src/main/java/com/greenpepper/samples/application/system/AccountManager.java | AccountManager.insertUser | public boolean insertUser(String name) {
"""
<p>insertUser.</p>
@param name a {@link java.lang.String} object.
@return a boolean.
"""
if (isUserExist(name))
{
throw new SystemException(String.format("User '%s' already exist.", name));
}
return allUsers.add(name);
} | java | public boolean insertUser(String name)
{
if (isUserExist(name))
{
throw new SystemException(String.format("User '%s' already exist.", name));
}
return allUsers.add(name);
} | [
"public",
"boolean",
"insertUser",
"(",
"String",
"name",
")",
"{",
"if",
"(",
"isUserExist",
"(",
"name",
")",
")",
"{",
"throw",
"new",
"SystemException",
"(",
"String",
".",
"format",
"(",
"\"User '%s' already exist.\"",
",",
"name",
")",
")",
";",
"}",... | <p>insertUser.</p>
@param name a {@link java.lang.String} object.
@return a boolean. | [
"<p",
">",
"insertUser",
".",
"<",
"/",
"p",
">"
] | train | https://github.com/strator-dev/greenpepper/blob/2a61e6c179b74085babcc559d677490b0cad2d30/samples-application/src/main/java/com/greenpepper/samples/application/system/AccountManager.java#L122-L130 |
seedstack/shed | src/main/java/org/seedstack/shed/text/TextUtils.java | TextUtils.leftPad | public static String leftPad(String text, String padding, int linesToIgnore) {
"""
Inserts the specified string at the beginning of each newline of the specified text.
@param text the text to pad.
@param padding the padding.
@param linesToIgnore the number of lines to ignore before starting the padding.
@return the padded text.
"""
StringBuilder result = new StringBuilder();
Matcher matcher = LINE_START_PATTERN.matcher(text);
while (matcher.find()) {
if (linesToIgnore > 0) {
linesToIgnore--;
} else {
result.append(padding);
}
result.append(matcher.group()).append("\n");
}
return result.toString();
} | java | public static String leftPad(String text, String padding, int linesToIgnore) {
StringBuilder result = new StringBuilder();
Matcher matcher = LINE_START_PATTERN.matcher(text);
while (matcher.find()) {
if (linesToIgnore > 0) {
linesToIgnore--;
} else {
result.append(padding);
}
result.append(matcher.group()).append("\n");
}
return result.toString();
} | [
"public",
"static",
"String",
"leftPad",
"(",
"String",
"text",
",",
"String",
"padding",
",",
"int",
"linesToIgnore",
")",
"{",
"StringBuilder",
"result",
"=",
"new",
"StringBuilder",
"(",
")",
";",
"Matcher",
"matcher",
"=",
"LINE_START_PATTERN",
".",
"match... | Inserts the specified string at the beginning of each newline of the specified text.
@param text the text to pad.
@param padding the padding.
@param linesToIgnore the number of lines to ignore before starting the padding.
@return the padded text. | [
"Inserts",
"the",
"specified",
"string",
"at",
"the",
"beginning",
"of",
"each",
"newline",
"of",
"the",
"specified",
"text",
"."
] | train | https://github.com/seedstack/shed/blob/49ecb25aa3777539ab0f29f89abaae5ee93b572e/src/main/java/org/seedstack/shed/text/TextUtils.java#L37-L50 |
dyu/protostuff-1.0.x | protostuff-model-json/src/main/java/com/dyuproject/protostuff/json/ReflectionJSON.java | ReflectionJSON.getField | protected Field getField(String name, Model<Field> model) throws IOException {
"""
/*
public <T extends MessageLite, B extends Builder> LiteConvertor getConvertor(Class<?> messageType)
{
return _convertors.get(messageType.getName());
}
"""
return model.getProperty(name);
} | java | protected Field getField(String name, Model<Field> model) throws IOException
{
return model.getProperty(name);
} | [
"protected",
"Field",
"getField",
"(",
"String",
"name",
",",
"Model",
"<",
"Field",
">",
"model",
")",
"throws",
"IOException",
"{",
"return",
"model",
".",
"getProperty",
"(",
"name",
")",
";",
"}"
] | /*
public <T extends MessageLite, B extends Builder> LiteConvertor getConvertor(Class<?> messageType)
{
return _convertors.get(messageType.getName());
} | [
"/",
"*",
"public",
"<T",
"extends",
"MessageLite",
"B",
"extends",
"Builder",
">",
"LiteConvertor",
"getConvertor",
"(",
"Class<?",
">",
"messageType",
")",
"{",
"return",
"_convertors",
".",
"get",
"(",
"messageType",
".",
"getName",
"()",
")",
";",
"}"
] | train | https://github.com/dyu/protostuff-1.0.x/blob/d7c964ec20da3fe44699d86ee95c2677ddffde96/protostuff-model-json/src/main/java/com/dyuproject/protostuff/json/ReflectionJSON.java#L141-L144 |
elki-project/elki | elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java | FormatUtil.format | public static String format(double[] v, int w, int d) {
"""
Returns a string representation of this vector.
@param w column width
@param d number of digits after the decimal
@return a string representation of this matrix
"""
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
int width = w + 1;
StringBuilder msg = new StringBuilder() //
.append('\n'); // start on new line.
for(int i = 0; i < v.length; i++) {
String s = format.format(v[i]); // format the number
// At _least_ 1 whitespace is added
whitespace(msg, Math.max(1, width - s.length())).append(s);
}
return msg.toString();
} | java | public static String format(double[] v, int w, int d) {
DecimalFormat format = new DecimalFormat();
format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
format.setMinimumIntegerDigits(1);
format.setMaximumFractionDigits(d);
format.setMinimumFractionDigits(d);
format.setGroupingUsed(false);
int width = w + 1;
StringBuilder msg = new StringBuilder() //
.append('\n'); // start on new line.
for(int i = 0; i < v.length; i++) {
String s = format.format(v[i]); // format the number
// At _least_ 1 whitespace is added
whitespace(msg, Math.max(1, width - s.length())).append(s);
}
return msg.toString();
} | [
"public",
"static",
"String",
"format",
"(",
"double",
"[",
"]",
"v",
",",
"int",
"w",
",",
"int",
"d",
")",
"{",
"DecimalFormat",
"format",
"=",
"new",
"DecimalFormat",
"(",
")",
";",
"format",
".",
"setDecimalFormatSymbols",
"(",
"new",
"DecimalFormatSym... | Returns a string representation of this vector.
@param w column width
@param d number of digits after the decimal
@return a string representation of this matrix | [
"Returns",
"a",
"string",
"representation",
"of",
"this",
"vector",
"."
] | train | https://github.com/elki-project/elki/blob/b54673327e76198ecd4c8a2a901021f1a9174498/elki-core-util/src/main/java/de/lmu/ifi/dbs/elki/utilities/io/FormatUtil.java#L240-L257 |
lessthanoptimal/ejml | main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java | MatrixFeatures_DDRM.isSkewSymmetric | public static boolean isSkewSymmetric(DMatrixRMaj A , double tol ) {
"""
<p>
Checks to see if a matrix is skew symmetric with in tolerance:<br>
<br>
-A = A<sup>T</sup><br>
or<br>
|a<sub>ij</sub> + a<sub>ji</sub>| ≤ tol
</p>
@param A The matrix being tested.
@param tol Tolerance for being skew symmetric.
@return True if it is skew symmetric and false if it is not.
"""
if( A.numCols != A.numRows )
return false;
for( int i = 0; i < A.numRows; i++ ) {
for( int j = 0; j < i; j++ ) {
double a = A.get(i,j);
double b = A.get(j,i);
double diff = Math.abs(a+b);
if( !(diff <= tol) ) {
return false;
}
}
}
return true;
} | java | public static boolean isSkewSymmetric(DMatrixRMaj A , double tol ){
if( A.numCols != A.numRows )
return false;
for( int i = 0; i < A.numRows; i++ ) {
for( int j = 0; j < i; j++ ) {
double a = A.get(i,j);
double b = A.get(j,i);
double diff = Math.abs(a+b);
if( !(diff <= tol) ) {
return false;
}
}
}
return true;
} | [
"public",
"static",
"boolean",
"isSkewSymmetric",
"(",
"DMatrixRMaj",
"A",
",",
"double",
"tol",
")",
"{",
"if",
"(",
"A",
".",
"numCols",
"!=",
"A",
".",
"numRows",
")",
"return",
"false",
";",
"for",
"(",
"int",
"i",
"=",
"0",
";",
"i",
"<",
"A",... | <p>
Checks to see if a matrix is skew symmetric with in tolerance:<br>
<br>
-A = A<sup>T</sup><br>
or<br>
|a<sub>ij</sub> + a<sub>ji</sub>| ≤ tol
</p>
@param A The matrix being tested.
@param tol Tolerance for being skew symmetric.
@return True if it is skew symmetric and false if it is not. | [
"<p",
">",
"Checks",
"to",
"see",
"if",
"a",
"matrix",
"is",
"skew",
"symmetric",
"with",
"in",
"tolerance",
":",
"<br",
">",
"<br",
">",
"-",
"A",
"=",
"A<sup",
">",
"T<",
"/",
"sup",
">",
"<br",
">",
"or<br",
">",
"|a<sub",
">",
"ij<",
"/",
"... | train | https://github.com/lessthanoptimal/ejml/blob/1444680cc487af5e866730e62f48f5f9636850d9/main/ejml-ddense/src/org/ejml/dense/row/MatrixFeatures_DDRM.java#L240-L257 |
bazaarvoice/jolt | jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java | Key.parseSpec | public static Set<Key> parseSpec( Map<String, Object> spec ) {
"""
Factory-ish method that recursively processes a Map<String, Object> into a Set<Key> objects.
@param spec Simple Jackson default Map<String,Object> input
@return Set of Keys from this level in the spec
"""
return processSpec( false, spec );
} | java | public static Set<Key> parseSpec( Map<String, Object> spec ) {
return processSpec( false, spec );
} | [
"public",
"static",
"Set",
"<",
"Key",
">",
"parseSpec",
"(",
"Map",
"<",
"String",
",",
"Object",
">",
"spec",
")",
"{",
"return",
"processSpec",
"(",
"false",
",",
"spec",
")",
";",
"}"
] | Factory-ish method that recursively processes a Map<String, Object> into a Set<Key> objects.
@param spec Simple Jackson default Map<String,Object> input
@return Set of Keys from this level in the spec | [
"Factory",
"-",
"ish",
"method",
"that",
"recursively",
"processes",
"a",
"Map<String",
"Object",
">",
"into",
"a",
"Set<Key",
">",
"objects",
"."
] | train | https://github.com/bazaarvoice/jolt/blob/4cf866a9f4222142da41b50dbcccce022a956bff/jolt-core/src/main/java/com/bazaarvoice/jolt/defaultr/Key.java#L41-L43 |
hawkular/hawkular-agent | hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java | Util.copyStream | public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
throws RuntimeException {
"""
Copies one stream to another, optionally closing the streams.
@param input the data to copy
@param output where to copy the data
@param closeStreams if true input and output will be closed when the method returns
@return the number of bytes copied
@throws RuntimeException if the copy failed
"""
long numBytesCopied = 0;
int bufferSize = BUFFER_SIZE;
try {
// make sure we buffer the input
input = new BufferedInputStream(input, bufferSize);
byte[] buffer = new byte[bufferSize];
for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
output.write(buffer, 0, bytesRead);
numBytesCopied += bytesRead;
}
output.flush();
} catch (IOException ioe) {
throw new RuntimeException("Stream data cannot be copied", ioe);
} finally {
if (closeStreams) {
try {
output.close();
} catch (IOException ioe2) {
// what to do?
}
try {
input.close();
} catch (IOException ioe2) {
// what to do?
}
}
}
return numBytesCopied;
} | java | public static long copyStream(InputStream input, OutputStream output, boolean closeStreams)
throws RuntimeException {
long numBytesCopied = 0;
int bufferSize = BUFFER_SIZE;
try {
// make sure we buffer the input
input = new BufferedInputStream(input, bufferSize);
byte[] buffer = new byte[bufferSize];
for (int bytesRead = input.read(buffer); bytesRead != -1; bytesRead = input.read(buffer)) {
output.write(buffer, 0, bytesRead);
numBytesCopied += bytesRead;
}
output.flush();
} catch (IOException ioe) {
throw new RuntimeException("Stream data cannot be copied", ioe);
} finally {
if (closeStreams) {
try {
output.close();
} catch (IOException ioe2) {
// what to do?
}
try {
input.close();
} catch (IOException ioe2) {
// what to do?
}
}
}
return numBytesCopied;
} | [
"public",
"static",
"long",
"copyStream",
"(",
"InputStream",
"input",
",",
"OutputStream",
"output",
",",
"boolean",
"closeStreams",
")",
"throws",
"RuntimeException",
"{",
"long",
"numBytesCopied",
"=",
"0",
";",
"int",
"bufferSize",
"=",
"BUFFER_SIZE",
";",
"... | Copies one stream to another, optionally closing the streams.
@param input the data to copy
@param output where to copy the data
@param closeStreams if true input and output will be closed when the method returns
@return the number of bytes copied
@throws RuntimeException if the copy failed | [
"Copies",
"one",
"stream",
"to",
"another",
"optionally",
"closing",
"the",
"streams",
"."
] | train | https://github.com/hawkular/hawkular-agent/blob/a7a88fc7e4f12302e4c4306d1c91e11f81c8b811/hawkular-agent-core/src/main/java/org/hawkular/agent/monitor/util/Util.java#L189-L219 |
salesforce/Argus | ArgusCore/src/main/java/com/salesforce/dva/argus/entity/SubsystemSuspensionLevels.java | SubsystemSuspensionLevels.getSuspensionLevelsBySubsystem | public static Map<Integer, Long> getSuspensionLevelsBySubsystem(EntityManager em, SubSystem subSystem) {
"""
Retrieves the suspension levels for the given subsystem.
@param em The EntityManager to use.
@param subSystem The subsystem for which to retrieve suspension levels.
@return The suspension levels for the given subsystem.
"""
return findBySubsystem(em, subSystem).getLevels();
} | java | public static Map<Integer, Long> getSuspensionLevelsBySubsystem(EntityManager em, SubSystem subSystem) {
return findBySubsystem(em, subSystem).getLevels();
} | [
"public",
"static",
"Map",
"<",
"Integer",
",",
"Long",
">",
"getSuspensionLevelsBySubsystem",
"(",
"EntityManager",
"em",
",",
"SubSystem",
"subSystem",
")",
"{",
"return",
"findBySubsystem",
"(",
"em",
",",
"subSystem",
")",
".",
"getLevels",
"(",
")",
";",
... | Retrieves the suspension levels for the given subsystem.
@param em The EntityManager to use.
@param subSystem The subsystem for which to retrieve suspension levels.
@return The suspension levels for the given subsystem. | [
"Retrieves",
"the",
"suspension",
"levels",
"for",
"the",
"given",
"subsystem",
"."
] | train | https://github.com/salesforce/Argus/blob/121b59a268da264316cded6a3e9271366a23cd86/ArgusCore/src/main/java/com/salesforce/dva/argus/entity/SubsystemSuspensionLevels.java#L156-L158 |
LearnLib/learnlib | commons/counterexamples/src/main/java/de/learnlib/counterexamples/GlobalSuffixFinders.java | GlobalSuffixFinders.suffixesForLocalOutput | public static <I, D> List<Word<I>> suffixesForLocalOutput(Query<I, D> ceQuery, int localSuffixIdx) {
"""
Transforms a suffix index returned by a {@link LocalSuffixFinder} into a list containing the single
distinguishing suffix.
"""
return suffixesForLocalOutput(ceQuery, localSuffixIdx, false);
} | java | public static <I, D> List<Word<I>> suffixesForLocalOutput(Query<I, D> ceQuery, int localSuffixIdx) {
return suffixesForLocalOutput(ceQuery, localSuffixIdx, false);
} | [
"public",
"static",
"<",
"I",
",",
"D",
">",
"List",
"<",
"Word",
"<",
"I",
">",
">",
"suffixesForLocalOutput",
"(",
"Query",
"<",
"I",
",",
"D",
">",
"ceQuery",
",",
"int",
"localSuffixIdx",
")",
"{",
"return",
"suffixesForLocalOutput",
"(",
"ceQuery",
... | Transforms a suffix index returned by a {@link LocalSuffixFinder} into a list containing the single
distinguishing suffix. | [
"Transforms",
"a",
"suffix",
"index",
"returned",
"by",
"a",
"{"
] | train | https://github.com/LearnLib/learnlib/blob/fa38a14adcc0664099f180d671ffa42480318d7b/commons/counterexamples/src/main/java/de/learnlib/counterexamples/GlobalSuffixFinders.java#L182-L184 |
Azure/azure-sdk-for-java | batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java | PoolsImpl.updatePropertiesAsync | public Observable<Void> updatePropertiesAsync(String poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions) {
"""
Updates the properties of the specified pool.
This fully replaces all the updatable properties of the pool. For example, if the pool has a start task associated with it and if start task is not specified with this request, then the Batch service will remove the existing start task.
@param poolId The ID of the pool to update.
@param poolUpdatePropertiesParameter The parameters for the request.
@param poolUpdatePropertiesOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful.
"""
return updatePropertiesWithServiceResponseAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions).map(new Func1<ServiceResponseWithHeaders<Void, PoolUpdatePropertiesHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolUpdatePropertiesHeaders> response) {
return response.body();
}
});
} | java | public Observable<Void> updatePropertiesAsync(String poolId, PoolUpdatePropertiesParameter poolUpdatePropertiesParameter, PoolUpdatePropertiesOptions poolUpdatePropertiesOptions) {
return updatePropertiesWithServiceResponseAsync(poolId, poolUpdatePropertiesParameter, poolUpdatePropertiesOptions).map(new Func1<ServiceResponseWithHeaders<Void, PoolUpdatePropertiesHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, PoolUpdatePropertiesHeaders> response) {
return response.body();
}
});
} | [
"public",
"Observable",
"<",
"Void",
">",
"updatePropertiesAsync",
"(",
"String",
"poolId",
",",
"PoolUpdatePropertiesParameter",
"poolUpdatePropertiesParameter",
",",
"PoolUpdatePropertiesOptions",
"poolUpdatePropertiesOptions",
")",
"{",
"return",
"updatePropertiesWithServiceRe... | Updates the properties of the specified pool.
This fully replaces all the updatable properties of the pool. For example, if the pool has a start task associated with it and if start task is not specified with this request, then the Batch service will remove the existing start task.
@param poolId The ID of the pool to update.
@param poolUpdatePropertiesParameter The parameters for the request.
@param poolUpdatePropertiesOptions Additional parameters for the operation
@throws IllegalArgumentException thrown if parameters fail the validation
@return the {@link ServiceResponseWithHeaders} object if successful. | [
"Updates",
"the",
"properties",
"of",
"the",
"specified",
"pool",
".",
"This",
"fully",
"replaces",
"all",
"the",
"updatable",
"properties",
"of",
"the",
"pool",
".",
"For",
"example",
"if",
"the",
"pool",
"has",
"a",
"start",
"task",
"associated",
"with",
... | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/batch/data-plane/src/main/java/com/microsoft/azure/batch/protocol/implementation/PoolsImpl.java#L3318-L3325 |
JodaOrg/joda-money | src/main/java/org/joda/money/BigMoney.java | BigMoney.plusRetainScale | public BigMoney plusRetainScale(double amountToAdd, RoundingMode roundingMode) {
"""
Returns a copy of this monetary value with the amount added retaining
the scale by rounding the result.
<p>
The scale of the result will be the same as the scale of this instance.
For example,'USD 25.95' plus '3.021d' gives 'USD 28.97' with most rounding modes.
<p>
The amount is converted via {@link BigDecimal#valueOf(double)} which yields
the most expected answer for most programming scenarios.
Any {@code double} literal in code will be converted to
exactly the same BigDecimal with the same scale.
For example, the literal '1.45d' will be converted to '1.45'.
<p>
This instance is immutable and unaffected by this method.
@param amountToAdd the monetary value to add, not null
@param roundingMode the rounding mode to use to adjust the scale, not null
@return the new instance with the input amount added, never null
"""
if (amountToAdd == 0) {
return this;
}
BigDecimal newAmount = amount.add(BigDecimal.valueOf(amountToAdd));
newAmount = newAmount.setScale(getScale(), roundingMode);
return BigMoney.of(currency, newAmount);
} | java | public BigMoney plusRetainScale(double amountToAdd, RoundingMode roundingMode) {
if (amountToAdd == 0) {
return this;
}
BigDecimal newAmount = amount.add(BigDecimal.valueOf(amountToAdd));
newAmount = newAmount.setScale(getScale(), roundingMode);
return BigMoney.of(currency, newAmount);
} | [
"public",
"BigMoney",
"plusRetainScale",
"(",
"double",
"amountToAdd",
",",
"RoundingMode",
"roundingMode",
")",
"{",
"if",
"(",
"amountToAdd",
"==",
"0",
")",
"{",
"return",
"this",
";",
"}",
"BigDecimal",
"newAmount",
"=",
"amount",
".",
"add",
"(",
"BigDe... | Returns a copy of this monetary value with the amount added retaining
the scale by rounding the result.
<p>
The scale of the result will be the same as the scale of this instance.
For example,'USD 25.95' plus '3.021d' gives 'USD 28.97' with most rounding modes.
<p>
The amount is converted via {@link BigDecimal#valueOf(double)} which yields
the most expected answer for most programming scenarios.
Any {@code double} literal in code will be converted to
exactly the same BigDecimal with the same scale.
For example, the literal '1.45d' will be converted to '1.45'.
<p>
This instance is immutable and unaffected by this method.
@param amountToAdd the monetary value to add, not null
@param roundingMode the rounding mode to use to adjust the scale, not null
@return the new instance with the input amount added, never null | [
"Returns",
"a",
"copy",
"of",
"this",
"monetary",
"value",
"with",
"the",
"amount",
"added",
"retaining",
"the",
"scale",
"by",
"rounding",
"the",
"result",
".",
"<p",
">",
"The",
"scale",
"of",
"the",
"result",
"will",
"be",
"the",
"same",
"as",
"the",
... | train | https://github.com/JodaOrg/joda-money/blob/e1f2de75aa36610a695358696c8a88a18ca66cde/src/main/java/org/joda/money/BigMoney.java#L1014-L1021 |
openbase/jul | extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java | TimestampProcessor.updateTimestamp | public static <M extends MessageOrBuilder> M updateTimestamp(final long time, final M messageOrBuilder, final TimeUnit timeUnit) throws CouldNotPerformException {
"""
Method updates the timestamp field of the given message with the given time in the given timeUnit.
@param <M> the message type of the message which is updated
@param time the time which is put in the timestamp field
@param messageOrBuilder the message
@param timeUnit the unit of time
@return the updated message
@throws CouldNotPerformException is thrown in case the copy could not be performed e.g. because of a missing timestamp field.
"""
long milliseconds = TimeUnit.MILLISECONDS.convert(time, timeUnit);
try {
if (messageOrBuilder == null) {
throw new NotAvailableException("messageOrBuilder");
}
try {
// handle builder
if (messageOrBuilder.getClass().getSimpleName().equals("Builder")) {
messageOrBuilder.getClass().getMethod(SET + TIMESTAMP_NAME, Timestamp.class).invoke(messageOrBuilder, TimestampJavaTimeTransform.transform(milliseconds));
return messageOrBuilder;
}
//handle message
final Object builder = messageOrBuilder.getClass().getMethod("toBuilder").invoke(messageOrBuilder);
builder.getClass().getMethod(SET + TIMESTAMP_NAME, Timestamp.class).invoke(builder, TimestampJavaTimeTransform.transform(milliseconds));
return (M) builder.getClass().getMethod("build").invoke(builder);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException ex) {
throw new NotSupportedException("Field[Timestamp]", messageOrBuilder.getClass().getName(), ex);
}
} catch (CouldNotPerformException ex) {
throw new CouldNotPerformException("Could not update timestemp! ", ex);
}
} | java | public static <M extends MessageOrBuilder> M updateTimestamp(final long time, final M messageOrBuilder, final TimeUnit timeUnit) throws CouldNotPerformException {
long milliseconds = TimeUnit.MILLISECONDS.convert(time, timeUnit);
try {
if (messageOrBuilder == null) {
throw new NotAvailableException("messageOrBuilder");
}
try {
// handle builder
if (messageOrBuilder.getClass().getSimpleName().equals("Builder")) {
messageOrBuilder.getClass().getMethod(SET + TIMESTAMP_NAME, Timestamp.class).invoke(messageOrBuilder, TimestampJavaTimeTransform.transform(milliseconds));
return messageOrBuilder;
}
//handle message
final Object builder = messageOrBuilder.getClass().getMethod("toBuilder").invoke(messageOrBuilder);
builder.getClass().getMethod(SET + TIMESTAMP_NAME, Timestamp.class).invoke(builder, TimestampJavaTimeTransform.transform(milliseconds));
return (M) builder.getClass().getMethod("build").invoke(builder);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException ex) {
throw new NotSupportedException("Field[Timestamp]", messageOrBuilder.getClass().getName(), ex);
}
} catch (CouldNotPerformException ex) {
throw new CouldNotPerformException("Could not update timestemp! ", ex);
}
} | [
"public",
"static",
"<",
"M",
"extends",
"MessageOrBuilder",
">",
"M",
"updateTimestamp",
"(",
"final",
"long",
"time",
",",
"final",
"M",
"messageOrBuilder",
",",
"final",
"TimeUnit",
"timeUnit",
")",
"throws",
"CouldNotPerformException",
"{",
"long",
"millisecon... | Method updates the timestamp field of the given message with the given time in the given timeUnit.
@param <M> the message type of the message which is updated
@param time the time which is put in the timestamp field
@param messageOrBuilder the message
@param timeUnit the unit of time
@return the updated message
@throws CouldNotPerformException is thrown in case the copy could not be performed e.g. because of a missing timestamp field. | [
"Method",
"updates",
"the",
"timestamp",
"field",
"of",
"the",
"given",
"message",
"with",
"the",
"given",
"time",
"in",
"the",
"given",
"timeUnit",
"."
] | train | https://github.com/openbase/jul/blob/662e98c3a853085e475be54c3be3deb72193c72d/extension/type/processing/src/main/java/org/openbase/jul/extension/type/processing/TimestampProcessor.java#L99-L125 |
radkovo/CSSBox | src/main/java/org/fit/cssbox/layout/TableCellBox.java | TableCellBox.applyVerticalAlign | public void applyVerticalAlign(int origHeight, int newHeight, int baseline) {
"""
Applies the vertical alignment after the row height is computed. Moves all child boxes
according to the vertical-align value of the cell and the difference between the original
height (after the cell layout) and the new (required by the row) height.
@param origHeight the original cell height obtained from the content layout
@param newHeight the cell height required by the row. It should be greater or equal to origHeight.
@param baseline the row's baseline offset
"""
int yofs = 0;
CSSProperty.VerticalAlign valign = style.getProperty("vertical-align");
if (valign == null) valign = CSSProperty.VerticalAlign.MIDDLE;
switch (valign)
{
case TOP: yofs = 0;
break;
case BOTTOM: yofs = newHeight - origHeight;
break;
case MIDDLE: yofs = (newHeight - origHeight) / 2;
break;
default: yofs = baseline - getFirstInlineBoxBaseline(); //all other values should behave as BASELINE
break;
}
if (yofs > 0)
coffset = yofs;
} | java | public void applyVerticalAlign(int origHeight, int newHeight, int baseline)
{
int yofs = 0;
CSSProperty.VerticalAlign valign = style.getProperty("vertical-align");
if (valign == null) valign = CSSProperty.VerticalAlign.MIDDLE;
switch (valign)
{
case TOP: yofs = 0;
break;
case BOTTOM: yofs = newHeight - origHeight;
break;
case MIDDLE: yofs = (newHeight - origHeight) / 2;
break;
default: yofs = baseline - getFirstInlineBoxBaseline(); //all other values should behave as BASELINE
break;
}
if (yofs > 0)
coffset = yofs;
} | [
"public",
"void",
"applyVerticalAlign",
"(",
"int",
"origHeight",
",",
"int",
"newHeight",
",",
"int",
"baseline",
")",
"{",
"int",
"yofs",
"=",
"0",
";",
"CSSProperty",
".",
"VerticalAlign",
"valign",
"=",
"style",
".",
"getProperty",
"(",
"\"vertical-align\"... | Applies the vertical alignment after the row height is computed. Moves all child boxes
according to the vertical-align value of the cell and the difference between the original
height (after the cell layout) and the new (required by the row) height.
@param origHeight the original cell height obtained from the content layout
@param newHeight the cell height required by the row. It should be greater or equal to origHeight.
@param baseline the row's baseline offset | [
"Applies",
"the",
"vertical",
"alignment",
"after",
"the",
"row",
"height",
"is",
"computed",
".",
"Moves",
"all",
"child",
"boxes",
"according",
"to",
"the",
"vertical",
"-",
"align",
"value",
"of",
"the",
"cell",
"and",
"the",
"difference",
"between",
"the... | train | https://github.com/radkovo/CSSBox/blob/38aaf8f22d233d7b4dbc12a56cdbc72b447bc559/src/main/java/org/fit/cssbox/layout/TableCellBox.java#L220-L239 |
sdl/Testy | src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java | WebLocatorAbstractBuilder.setTitle | @SuppressWarnings("unchecked")
public <T extends WebLocatorAbstractBuilder> T setTitle(String title, SearchType... searchTypes) {
"""
<p><b>Used for finding element process (to generate xpath address)</b></p>
@param title of element
@param searchTypes see {@link SearchType}
@param <T> the element which calls this method
@return this element
"""
pathBuilder.setTitle(title, searchTypes);
return (T) this;
} | java | @SuppressWarnings("unchecked")
public <T extends WebLocatorAbstractBuilder> T setTitle(String title, SearchType... searchTypes) {
pathBuilder.setTitle(title, searchTypes);
return (T) this;
} | [
"@",
"SuppressWarnings",
"(",
"\"unchecked\"",
")",
"public",
"<",
"T",
"extends",
"WebLocatorAbstractBuilder",
">",
"T",
"setTitle",
"(",
"String",
"title",
",",
"SearchType",
"...",
"searchTypes",
")",
"{",
"pathBuilder",
".",
"setTitle",
"(",
"title",
",",
... | <p><b>Used for finding element process (to generate xpath address)</b></p>
@param title of element
@param searchTypes see {@link SearchType}
@param <T> the element which calls this method
@return this element | [
"<p",
">",
"<b",
">",
"Used",
"for",
"finding",
"element",
"process",
"(",
"to",
"generate",
"xpath",
"address",
")",
"<",
"/",
"b",
">",
"<",
"/",
"p",
">"
] | train | https://github.com/sdl/Testy/blob/b3ae061554016f926f04694a39ff00dab7576609/src/main/java/com/sdl/selenium/web/WebLocatorAbstractBuilder.java#L261-L265 |
hibernate/hibernate-ogm | neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java | BaseNeo4jAssociationQueries.getEntityKey | private EntityKey getEntityKey(AssociationKey associationKey, RowKey rowKey) {
"""
Returns the entity key on the other side of association row represented by the given row key.
<p>
<b>Note:</b> May only be invoked if the row key actually contains all the columns making up that entity key.
Specifically, it may <b>not</b> be invoked if the association has index columns (maps, ordered collections), as
the entity key columns will not be part of the row key in this case.
"""
String[] associationKeyColumns = associationKey.getMetadata().getAssociatedEntityKeyMetadata().getAssociationKeyColumns();
Object[] columnValues = new Object[associationKeyColumns.length];
int i = 0;
for ( String associationKeyColumn : associationKeyColumns ) {
columnValues[i] = rowKey.getColumnValue( associationKeyColumn );
i++;
}
EntityKeyMetadata entityKeyMetadata = associationKey.getMetadata().getAssociatedEntityKeyMetadata().getEntityKeyMetadata();
return new EntityKey( entityKeyMetadata, columnValues );
} | java | private EntityKey getEntityKey(AssociationKey associationKey, RowKey rowKey) {
String[] associationKeyColumns = associationKey.getMetadata().getAssociatedEntityKeyMetadata().getAssociationKeyColumns();
Object[] columnValues = new Object[associationKeyColumns.length];
int i = 0;
for ( String associationKeyColumn : associationKeyColumns ) {
columnValues[i] = rowKey.getColumnValue( associationKeyColumn );
i++;
}
EntityKeyMetadata entityKeyMetadata = associationKey.getMetadata().getAssociatedEntityKeyMetadata().getEntityKeyMetadata();
return new EntityKey( entityKeyMetadata, columnValues );
} | [
"private",
"EntityKey",
"getEntityKey",
"(",
"AssociationKey",
"associationKey",
",",
"RowKey",
"rowKey",
")",
"{",
"String",
"[",
"]",
"associationKeyColumns",
"=",
"associationKey",
".",
"getMetadata",
"(",
")",
".",
"getAssociatedEntityKeyMetadata",
"(",
")",
"."... | Returns the entity key on the other side of association row represented by the given row key.
<p>
<b>Note:</b> May only be invoked if the row key actually contains all the columns making up that entity key.
Specifically, it may <b>not</b> be invoked if the association has index columns (maps, ordered collections), as
the entity key columns will not be part of the row key in this case. | [
"Returns",
"the",
"entity",
"key",
"on",
"the",
"other",
"side",
"of",
"association",
"row",
"represented",
"by",
"the",
"given",
"row",
"key",
".",
"<p",
">",
"<b",
">",
"Note",
":",
"<",
"/",
"b",
">",
"May",
"only",
"be",
"invoked",
"if",
"the",
... | train | https://github.com/hibernate/hibernate-ogm/blob/9ea971df7c27277029006a6f748d8272fb1d69d2/neo4j/src/main/java/org/hibernate/ogm/datastore/neo4j/dialect/impl/BaseNeo4jAssociationQueries.java#L288-L300 |
iig-uni-freiburg/SEWOL | ext/org/deckfour/xes/id/XID.java | XID.write | public static void write(XID id, DataOutputStream dos) throws IOException {
"""
Serializes an XID object binarily to a data output stream.
@param id
XID to be serialized.
@param dos
Data output stream to store XID serialization.
"""
dos.writeLong(id.uuid.getMostSignificantBits());
dos.writeLong(id.uuid.getLeastSignificantBits());
} | java | public static void write(XID id, DataOutputStream dos) throws IOException {
dos.writeLong(id.uuid.getMostSignificantBits());
dos.writeLong(id.uuid.getLeastSignificantBits());
} | [
"public",
"static",
"void",
"write",
"(",
"XID",
"id",
",",
"DataOutputStream",
"dos",
")",
"throws",
"IOException",
"{",
"dos",
".",
"writeLong",
"(",
"id",
".",
"uuid",
".",
"getMostSignificantBits",
"(",
")",
")",
";",
"dos",
".",
"writeLong",
"(",
"i... | Serializes an XID object binarily to a data output stream.
@param id
XID to be serialized.
@param dos
Data output stream to store XID serialization. | [
"Serializes",
"an",
"XID",
"object",
"binarily",
"to",
"a",
"data",
"output",
"stream",
"."
] | train | https://github.com/iig-uni-freiburg/SEWOL/blob/e791cb07a6e62ecf837d760d58a25f32fbf6bbca/ext/org/deckfour/xes/id/XID.java#L102-L105 |
Azure/azure-sdk-for-java | automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ConnectionTypesInner.java | ConnectionTypesInner.get | public ConnectionTypeInner get(String resourceGroupName, String automationAccountName, String connectionTypeName) {
"""
Retrieve the connectiontype identified by connectiontype name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param connectionTypeName The name of connectiontype.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ConnectionTypeInner object if successful.
"""
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, connectionTypeName).toBlocking().single().body();
} | java | public ConnectionTypeInner get(String resourceGroupName, String automationAccountName, String connectionTypeName) {
return getWithServiceResponseAsync(resourceGroupName, automationAccountName, connectionTypeName).toBlocking().single().body();
} | [
"public",
"ConnectionTypeInner",
"get",
"(",
"String",
"resourceGroupName",
",",
"String",
"automationAccountName",
",",
"String",
"connectionTypeName",
")",
"{",
"return",
"getWithServiceResponseAsync",
"(",
"resourceGroupName",
",",
"automationAccountName",
",",
"connecti... | Retrieve the connectiontype identified by connectiontype name.
@param resourceGroupName Name of an Azure Resource group.
@param automationAccountName The name of the automation account.
@param connectionTypeName The name of connectiontype.
@throws IllegalArgumentException thrown if parameters fail the validation
@throws ErrorResponseException thrown if the request is rejected by server
@throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
@return the ConnectionTypeInner object if successful. | [
"Retrieve",
"the",
"connectiontype",
"identified",
"by",
"connectiontype",
"name",
"."
] | train | https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/automation/resource-manager/v2015_10_31/src/main/java/com/microsoft/azure/management/automation/v2015_10_31/implementation/ConnectionTypesInner.java#L189-L191 |
apereo/cas | support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/actions/SendPasswordResetInstructionsAction.java | SendPasswordResetInstructionsAction.sendPasswordResetEmailToAccount | protected boolean sendPasswordResetEmailToAccount(final String to, final String url) {
"""
Send password reset email to account.
@param to the to
@param url the url
@return true/false
"""
val reset = casProperties.getAuthn().getPm().getReset().getMail();
val text = reset.getFormattedBody(url);
return this.communicationsManager.email(reset, to, text);
} | java | protected boolean sendPasswordResetEmailToAccount(final String to, final String url) {
val reset = casProperties.getAuthn().getPm().getReset().getMail();
val text = reset.getFormattedBody(url);
return this.communicationsManager.email(reset, to, text);
} | [
"protected",
"boolean",
"sendPasswordResetEmailToAccount",
"(",
"final",
"String",
"to",
",",
"final",
"String",
"url",
")",
"{",
"val",
"reset",
"=",
"casProperties",
".",
"getAuthn",
"(",
")",
".",
"getPm",
"(",
")",
".",
"getReset",
"(",
")",
".",
"getM... | Send password reset email to account.
@param to the to
@param url the url
@return true/false | [
"Send",
"password",
"reset",
"email",
"to",
"account",
"."
] | train | https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-pm-webflow/src/main/java/org/apereo/cas/pm/web/flow/actions/SendPasswordResetInstructionsAction.java#L137-L141 |
wildfly/wildfly-core | controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java | AttributeDefinition.resolveModelAttribute | public ModelNode resolveModelAttribute(final OperationContext context, final ModelNode model) throws OperationFailedException {
"""
Finds a value in the given {@code model} whose key matches this attribute's {@link #getName() name},
uses the given {@code context} to {@link OperationContext#resolveExpressions(org.jboss.dmr.ModelNode) resolve}
it and validates it using this attribute's {@link #getValidator() validator}. If the value is
undefined and a {@link #getDefaultValue() default value} is available, the default value is used.
@param context the operation context
@param model model node of type {@link ModelType#OBJECT}, typically representing a model resource
@return the resolved value, possibly the default value if the model does not have a defined value matching
this attribute's name
@throws OperationFailedException if the value is not valid
"""
return resolveModelAttribute(new ExpressionResolver() {
@Override
public ModelNode resolveExpressions(ModelNode node) throws OperationFailedException {
return context.resolveExpressions(node);
}
}, model);
} | java | public ModelNode resolveModelAttribute(final OperationContext context, final ModelNode model) throws OperationFailedException {
return resolveModelAttribute(new ExpressionResolver() {
@Override
public ModelNode resolveExpressions(ModelNode node) throws OperationFailedException {
return context.resolveExpressions(node);
}
}, model);
} | [
"public",
"ModelNode",
"resolveModelAttribute",
"(",
"final",
"OperationContext",
"context",
",",
"final",
"ModelNode",
"model",
")",
"throws",
"OperationFailedException",
"{",
"return",
"resolveModelAttribute",
"(",
"new",
"ExpressionResolver",
"(",
")",
"{",
"@",
"O... | Finds a value in the given {@code model} whose key matches this attribute's {@link #getName() name},
uses the given {@code context} to {@link OperationContext#resolveExpressions(org.jboss.dmr.ModelNode) resolve}
it and validates it using this attribute's {@link #getValidator() validator}. If the value is
undefined and a {@link #getDefaultValue() default value} is available, the default value is used.
@param context the operation context
@param model model node of type {@link ModelType#OBJECT}, typically representing a model resource
@return the resolved value, possibly the default value if the model does not have a defined value matching
this attribute's name
@throws OperationFailedException if the value is not valid | [
"Finds",
"a",
"value",
"in",
"the",
"given",
"{",
"@code",
"model",
"}",
"whose",
"key",
"matches",
"this",
"attribute",
"s",
"{",
"@link",
"#getName",
"()",
"name",
"}",
"uses",
"the",
"given",
"{",
"@code",
"context",
"}",
"to",
"{",
"@link",
"Operat... | train | https://github.com/wildfly/wildfly-core/blob/cfaf0479dcbb2d320a44c5374b93b944ec39fade/controller/src/main/java/org/jboss/as/controller/AttributeDefinition.java#L599-L606 |
deeplearning4j/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/eigen/Eigen.java | Eigen.symmetricGeneralizedEigenvalues | public static INDArray symmetricGeneralizedEigenvalues(INDArray A, INDArray B) {
"""
Compute generalized eigenvalues of the problem A x = L B x.
The data will be unchanged, no eigenvectors returned.
@param A symmetric Matrix A.
@param B symmetric Matrix B.
@return a vector of eigenvalues L.
"""
Preconditions.checkArgument(A.isMatrix() && A.isSquare(), "Argument A must be a square matrix: has shape %s", A.shape());
Preconditions.checkArgument(B.isMatrix() && B.isSquare(), "Argument B must be a square matrix: has shape %s", B.shape());
INDArray W = Nd4j.create(A.rows());
A = InvertMatrix.invert(B, false).mmuli(A);
Nd4j.getBlasWrapper().syev('V', 'L', A, W);
return W;
} | java | public static INDArray symmetricGeneralizedEigenvalues(INDArray A, INDArray B) {
Preconditions.checkArgument(A.isMatrix() && A.isSquare(), "Argument A must be a square matrix: has shape %s", A.shape());
Preconditions.checkArgument(B.isMatrix() && B.isSquare(), "Argument B must be a square matrix: has shape %s", B.shape());
INDArray W = Nd4j.create(A.rows());
A = InvertMatrix.invert(B, false).mmuli(A);
Nd4j.getBlasWrapper().syev('V', 'L', A, W);
return W;
} | [
"public",
"static",
"INDArray",
"symmetricGeneralizedEigenvalues",
"(",
"INDArray",
"A",
",",
"INDArray",
"B",
")",
"{",
"Preconditions",
".",
"checkArgument",
"(",
"A",
".",
"isMatrix",
"(",
")",
"&&",
"A",
".",
"isSquare",
"(",
")",
",",
"\"Argument A must b... | Compute generalized eigenvalues of the problem A x = L B x.
The data will be unchanged, no eigenvectors returned.
@param A symmetric Matrix A.
@param B symmetric Matrix B.
@return a vector of eigenvalues L. | [
"Compute",
"generalized",
"eigenvalues",
"of",
"the",
"problem",
"A",
"x",
"=",
"L",
"B",
"x",
".",
"The",
"data",
"will",
"be",
"unchanged",
"no",
"eigenvectors",
"returned",
"."
] | train | https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/eigen/Eigen.java#L70-L78 |
rapidpro/expressions | java/src/main/java/io/rapidpro/expressions/evaluator/Evaluator.java | Evaluator.evaluateTemplate | public EvaluatedTemplate evaluateTemplate(String template, EvaluationContext context) {
"""
Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
@param template the template string
@param context the evaluation context
@return a tuple of the evaluated template and a list of evaluation errors
"""
return evaluateTemplate(template, context, false);
} | java | public EvaluatedTemplate evaluateTemplate(String template, EvaluationContext context) {
return evaluateTemplate(template, context, false);
} | [
"public",
"EvaluatedTemplate",
"evaluateTemplate",
"(",
"String",
"template",
",",
"EvaluationContext",
"context",
")",
"{",
"return",
"evaluateTemplate",
"(",
"template",
",",
"context",
",",
"false",
")",
";",
"}"
] | Evaluates a template string, e.g. "Hello @contact.name you have @(contact.reports * 2) reports"
@param template the template string
@param context the evaluation context
@return a tuple of the evaluated template and a list of evaluation errors | [
"Evaluates",
"a",
"template",
"string",
"e",
".",
"g",
".",
"Hello"
] | train | https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/java/src/main/java/io/rapidpro/expressions/evaluator/Evaluator.java#L77-L79 |
apache/flink | flink-mesos/src/main/java/org/apache/flink/mesos/runtime/clusterframework/MesosTaskManagerParameters.java | MesosTaskManagerParameters.buildVolumes | public static List<Protos.Volume> buildVolumes(Option<String> containerVolumes) {
"""
Used to build volume specs for mesos. This allows for mounting additional volumes into a container
@param containerVolumes a comma delimited optional string of [host_path:]container_path[:RO|RW] that
defines mount points for a container volume. If None or empty string, returns
an empty iterator
"""
if (containerVolumes.isEmpty()) {
return Collections.emptyList();
} else {
String[] volumeSpecifications = containerVolumes.get().split(",");
List<Protos.Volume> volumes = new ArrayList<>(volumeSpecifications.length);
for (String volumeSpecification : volumeSpecifications) {
if (!volumeSpecification.trim().isEmpty()) {
Protos.Volume.Builder volume = Protos.Volume.newBuilder();
volume.setMode(Protos.Volume.Mode.RW);
String[] parts = volumeSpecification.split(":");
switch (parts.length) {
case 1:
volume.setContainerPath(parts[0]);
break;
case 2:
try {
Protos.Volume.Mode mode = Protos.Volume.Mode.valueOf(parts[1].trim().toUpperCase());
volume.setMode(mode)
.setContainerPath(parts[0]);
} catch (IllegalArgumentException e) {
volume.setHostPath(parts[0])
.setContainerPath(parts[1]);
}
break;
case 3:
Protos.Volume.Mode mode = Protos.Volume.Mode.valueOf(parts[2].trim().toUpperCase());
volume.setMode(mode)
.setHostPath(parts[0])
.setContainerPath(parts[1]);
break;
default:
throw new IllegalArgumentException("volume specification is invalid, given: " + volumeSpecification);
}
volumes.add(volume.build());
}
}
return volumes;
}
} | java | public static List<Protos.Volume> buildVolumes(Option<String> containerVolumes) {
if (containerVolumes.isEmpty()) {
return Collections.emptyList();
} else {
String[] volumeSpecifications = containerVolumes.get().split(",");
List<Protos.Volume> volumes = new ArrayList<>(volumeSpecifications.length);
for (String volumeSpecification : volumeSpecifications) {
if (!volumeSpecification.trim().isEmpty()) {
Protos.Volume.Builder volume = Protos.Volume.newBuilder();
volume.setMode(Protos.Volume.Mode.RW);
String[] parts = volumeSpecification.split(":");
switch (parts.length) {
case 1:
volume.setContainerPath(parts[0]);
break;
case 2:
try {
Protos.Volume.Mode mode = Protos.Volume.Mode.valueOf(parts[1].trim().toUpperCase());
volume.setMode(mode)
.setContainerPath(parts[0]);
} catch (IllegalArgumentException e) {
volume.setHostPath(parts[0])
.setContainerPath(parts[1]);
}
break;
case 3:
Protos.Volume.Mode mode = Protos.Volume.Mode.valueOf(parts[2].trim().toUpperCase());
volume.setMode(mode)
.setHostPath(parts[0])
.setContainerPath(parts[1]);
break;
default:
throw new IllegalArgumentException("volume specification is invalid, given: " + volumeSpecification);
}
volumes.add(volume.build());
}
}
return volumes;
}
} | [
"public",
"static",
"List",
"<",
"Protos",
".",
"Volume",
">",
"buildVolumes",
"(",
"Option",
"<",
"String",
">",
"containerVolumes",
")",
"{",
"if",
"(",
"containerVolumes",
".",
"isEmpty",
"(",
")",
")",
"{",
"return",
"Collections",
".",
"emptyList",
"(... | Used to build volume specs for mesos. This allows for mounting additional volumes into a container
@param containerVolumes a comma delimited optional string of [host_path:]container_path[:RO|RW] that
defines mount points for a container volume. If None or empty string, returns
an empty iterator | [
"Used",
"to",
"build",
"volume",
"specs",
"for",
"mesos",
".",
"This",
"allows",
"for",
"mounting",
"additional",
"volumes",
"into",
"a",
"container"
] | train | https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-mesos/src/main/java/org/apache/flink/mesos/runtime/clusterframework/MesosTaskManagerParameters.java#L452-L496 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.