repository_name
stringlengths
7
58
func_path_in_repository
stringlengths
18
194
func_name
stringlengths
6
111
whole_func_string
stringlengths
80
3.8k
language
stringclasses
1 value
func_code_string
stringlengths
80
3.8k
func_code_tokens
listlengths
20
697
func_documentation_string
stringlengths
61
2k
func_documentation_tokens
listlengths
1
434
split_name
stringclasses
1 value
func_code_url
stringlengths
111
308
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/Bar.java
Bar.setColorGradient
public void setColorGradient(int x1, int y1, ColorRgba color1, int x2, int y2, ColorRgba color2) { gradientColor = new ColorGradient(x1, y1, color1, x2, y2, color2); }
java
public void setColorGradient(int x1, int y1, ColorRgba color1, int x2, int y2, ColorRgba color2) { gradientColor = new ColorGradient(x1, y1, color1, x2, y2, color2); }
[ "public", "void", "setColorGradient", "(", "int", "x1", ",", "int", "y1", ",", "ColorRgba", "color1", ",", "int", "x2", ",", "int", "y2", ",", "ColorRgba", "color2", ")", "{", "gradientColor", "=", "new", "ColorGradient", "(", "x1", ",", "y1", ",", "co...
Set a gradient color from point 1 with color 1 to point2 with color 2. @param x1 The first horizontal location. @param y1 The first vertical location. @param color1 The first color. @param x2 The last horizontal location. @param y2 The last vertical location. @param color2 The last color.
[ "Set", "a", "gradient", "color", "from", "point", "1", "with", "color", "1", "to", "point2", "with", "color", "2", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/Bar.java#L209-L212
haraldk/TwelveMonkeys
sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java
DebugUtil.printTimeDifference
public static void printTimeDifference(final long pStartTime, final long pEndTime, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(buildTimeDifference(pStartTime, pEndTime)); }
java
public static void printTimeDifference(final long pStartTime, final long pEndTime, final PrintStream pPrintStream) { if (pPrintStream == null) { System.err.println(PRINTSTREAM_IS_NULL_ERROR_MESSAGE); return; } pPrintStream.println(buildTimeDifference(pStartTime, pEndTime)); }
[ "public", "static", "void", "printTimeDifference", "(", "final", "long", "pStartTime", ",", "final", "long", "pEndTime", ",", "final", "PrintStream", "pPrintStream", ")", "{", "if", "(", "pPrintStream", "==", "null", ")", "{", "System", ".", "err", ".", "pri...
Prints out the difference between two millisecond representations. The start time is subtracted from the end time. <p> @param pStartTime the start time. @param pEndTime the end time. @param pPrintStream the {@code java.io.PrintStream} for flushing the results.
[ "Prints", "out", "the", "difference", "between", "two", "millisecond", "representations", ".", "The", "start", "time", "is", "subtracted", "from", "the", "end", "time", ".", "<p", ">" ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/sandbox/sandbox-common/src/main/java/com/twelvemonkeys/util/DebugUtil.java#L896-L903
Azure/azure-sdk-for-java
edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java
DevicesInner.installUpdatesAsync
public Observable<Void> installUpdatesAsync(String deviceName, String resourceGroupName) { return installUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
java
public Observable<Void> installUpdatesAsync(String deviceName, String resourceGroupName) { return installUpdatesWithServiceResponseAsync(deviceName, resourceGroupName).map(new Func1<ServiceResponse<Void>, Void>() { @Override public Void call(ServiceResponse<Void> response) { return response.body(); } }); }
[ "public", "Observable", "<", "Void", ">", "installUpdatesAsync", "(", "String", "deviceName", ",", "String", "resourceGroupName", ")", "{", "return", "installUpdatesWithServiceResponseAsync", "(", "deviceName", ",", "resourceGroupName", ")", ".", "map", "(", "new", ...
Installs the updates on the data box edge/gateway device. @param deviceName The device name. @param resourceGroupName The resource group name. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable for the request
[ "Installs", "the", "updates", "on", "the", "data", "box", "edge", "/", "gateway", "device", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/edgegateway/resource-manager/v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/implementation/DevicesInner.java#L1467-L1474
kopihao/peasy-recyclerview
peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java
PeasyRecyclerView.configureRecyclerViewTouchEvent
private void configureRecyclerViewTouchEvent() { getRecyclerView().addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { if (isEnhancedFAB() && getFab() != null) { enhanceFAB(getFab(), e); } onViewInterceptTouchEvent(rv, e); return false; } @Override public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }); }
java
private void configureRecyclerViewTouchEvent() { getRecyclerView().addOnItemTouchListener(new RecyclerView.OnItemTouchListener() { @Override public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { if (isEnhancedFAB() && getFab() != null) { enhanceFAB(getFab(), e); } onViewInterceptTouchEvent(rv, e); return false; } @Override public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } }); }
[ "private", "void", "configureRecyclerViewTouchEvent", "(", ")", "{", "getRecyclerView", "(", ")", ".", "addOnItemTouchListener", "(", "new", "RecyclerView", ".", "OnItemTouchListener", "(", ")", "{", "@", "Override", "public", "boolean", "onInterceptTouchEvent", "(", ...
* Provide default {@link RecyclerView.OnItemTouchListener} of provided recyclerView
[ "*", "Provide", "default", "{" ]
train
https://github.com/kopihao/peasy-recyclerview/blob/a26071849e5d5b5b1febe685f205558b49908f87/peasy-recyclerview/src/main/java/com/kopirealm/peasyrecyclerview/PeasyRecyclerView.java#L142-L162
btrplace/scheduler
choco/src/main/java/org/btrplace/scheduler/choco/extensions/ChocoUtils.java
ChocoUtils.postIfOnlyIf
public static void postIfOnlyIf(ReconfigurationProblem rp, BoolVar b1, Constraint c2) { Model csp = rp.getModel(); BoolVar notBC1 = b1.not(); BoolVar bC2 = csp.boolVar(rp.makeVarLabel(c2.toString(), " satisfied")); c2.reifyWith(bC2); BoolVar notBC2 = bC2.not(); csp.post(rp.getModel().or(rp.getModel().or(b1, bC2), rp.getModel().or(notBC1, notBC2))); }
java
public static void postIfOnlyIf(ReconfigurationProblem rp, BoolVar b1, Constraint c2) { Model csp = rp.getModel(); BoolVar notBC1 = b1.not(); BoolVar bC2 = csp.boolVar(rp.makeVarLabel(c2.toString(), " satisfied")); c2.reifyWith(bC2); BoolVar notBC2 = bC2.not(); csp.post(rp.getModel().or(rp.getModel().or(b1, bC2), rp.getModel().or(notBC1, notBC2))); }
[ "public", "static", "void", "postIfOnlyIf", "(", "ReconfigurationProblem", "rp", ",", "BoolVar", "b1", ",", "Constraint", "c2", ")", "{", "Model", "csp", "=", "rp", ".", "getModel", "(", ")", ";", "BoolVar", "notBC1", "=", "b1", ".", "not", "(", ")", "...
Make and post a constraint that states and(or(b1, non c2), or(non b1, c2)) @param rp the problem to solve @param b1 the first constraint @param c2 the second constraint
[ "Make", "and", "post", "a", "constraint", "that", "states", "and", "(", "or", "(", "b1", "non", "c2", ")", "or", "(", "non", "b1", "c2", "))" ]
train
https://github.com/btrplace/scheduler/blob/611063aad0b47a016e57ebf36fa4dfdf24de09e8/choco/src/main/java/org/btrplace/scheduler/choco/extensions/ChocoUtils.java#L63-L70
lightbend/config
config/src/main/java/com/typesafe/config/impl/AbstractConfigObject.java
AbstractConfigObject.peekAssumingResolved
protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) { try { return attemptPeekWithPartialResolve(key); } catch (ConfigException.NotResolved e) { throw ConfigImpl.improveNotResolved(originalPath, e); } }
java
protected final AbstractConfigValue peekAssumingResolved(String key, Path originalPath) { try { return attemptPeekWithPartialResolve(key); } catch (ConfigException.NotResolved e) { throw ConfigImpl.improveNotResolved(originalPath, e); } }
[ "protected", "final", "AbstractConfigValue", "peekAssumingResolved", "(", "String", "key", ",", "Path", "originalPath", ")", "{", "try", "{", "return", "attemptPeekWithPartialResolve", "(", "key", ")", ";", "}", "catch", "(", "ConfigException", ".", "NotResolved", ...
This looks up the key with no transformation or type conversion of any kind, and returns null if the key is not present. The object must be resolved along the nodes needed to get the key or ConfigException.NotResolved will be thrown. @param key @return the unmodified raw value or null
[ "This", "looks", "up", "the", "key", "with", "no", "transformation", "or", "type", "conversion", "of", "any", "kind", "and", "returns", "null", "if", "the", "key", "is", "not", "present", ".", "The", "object", "must", "be", "resolved", "along", "the", "n...
train
https://github.com/lightbend/config/blob/68cebfde5e861e9a5fdc75ceff366ed95e17d475/config/src/main/java/com/typesafe/config/impl/AbstractConfigObject.java#L64-L70
nohana/Amalgam
amalgam/src/main/java/com/amalgam/content/pm/SignatureUtils.java
SignatureUtils.ensureSameSignature
public static boolean ensureSameSignature(Context context, String targetPackageName, String expectedHash) { if (targetPackageName == null || expectedHash == null) { // cannot proceed anymore. return false; } String hash = expectedHash.replace(" ", ""); return hash.equals(getSignatureHexCode(context, targetPackageName)); }
java
public static boolean ensureSameSignature(Context context, String targetPackageName, String expectedHash) { if (targetPackageName == null || expectedHash == null) { // cannot proceed anymore. return false; } String hash = expectedHash.replace(" ", ""); return hash.equals(getSignatureHexCode(context, targetPackageName)); }
[ "public", "static", "boolean", "ensureSameSignature", "(", "Context", "context", ",", "String", "targetPackageName", ",", "String", "expectedHash", ")", "{", "if", "(", "targetPackageName", "==", "null", "||", "expectedHash", "==", "null", ")", "{", "// cannot pro...
Ensure the running application and the target package has the same signature. @param context the running application context. @param targetPackageName the target package name. @param expectedHash signature hash that the target package is expected to have signed. @return true if the same signature.
[ "Ensure", "the", "running", "application", "and", "the", "target", "package", "has", "the", "same", "signature", "." ]
train
https://github.com/nohana/Amalgam/blob/57809ddbfe7897e979cf507982ce0b3aa5e0ed8a/amalgam/src/main/java/com/amalgam/content/pm/SignatureUtils.java#L56-L63
alkacon/opencms-core
src-gwt/org/opencms/gwt/client/util/CmsEmbeddedDialogHandler.java
CmsEmbeddedDialogHandler.openDialog
public void openDialog(String dialogId, String contextType, List<CmsUUID> resources) { openDialog(dialogId, contextType, resources, null); }
java
public void openDialog(String dialogId, String contextType, List<CmsUUID> resources) { openDialog(dialogId, contextType, resources, null); }
[ "public", "void", "openDialog", "(", "String", "dialogId", ",", "String", "contextType", ",", "List", "<", "CmsUUID", ">", "resources", ")", "{", "openDialog", "(", "dialogId", ",", "contextType", ",", "resources", ",", "null", ")", ";", "}" ]
Opens the dialog with the given id.<p> @param dialogId the dialog id @param contextType the context type, used to check the action visibility @param resources the resource to handle
[ "Opens", "the", "dialog", "with", "the", "given", "id", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/gwt/client/util/CmsEmbeddedDialogHandler.java#L158-L161
joniles/mpxj
src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java
DatatypeConverter.getLong
public static final long getLong(byte[] data, int offset) { long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
java
public static final long getLong(byte[] data, int offset) { long result = 0; int i = offset; for (int shiftBy = 0; shiftBy < 64; shiftBy += 8) { result |= ((long) (data[i] & 0xff)) << shiftBy; ++i; } return result; }
[ "public", "static", "final", "long", "getLong", "(", "byte", "[", "]", "data", ",", "int", "offset", ")", "{", "long", "result", "=", "0", ";", "int", "i", "=", "offset", ";", "for", "(", "int", "shiftBy", "=", "0", ";", "shiftBy", "<", "64", ";"...
Read a long int from a byte array. @param data byte array @param offset start offset @return long value
[ "Read", "a", "long", "int", "from", "a", "byte", "array", "." ]
train
https://github.com/joniles/mpxj/blob/143ea0e195da59cd108f13b3b06328e9542337e8/src/main/java/net/sf/mpxj/synchro/DatatypeConverter.java#L114-L124
zeroturnaround/zt-zip
src/main/java/org/zeroturnaround/zip/ZipUtil.java
ZipUtil.transformEntry
public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); }
java
public static boolean transformEntry(InputStream is, ZipEntryTransformerEntry entry, OutputStream os) { return transformEntries(is, new ZipEntryTransformerEntry[] { entry }, os); }
[ "public", "static", "boolean", "transformEntry", "(", "InputStream", "is", ",", "ZipEntryTransformerEntry", "entry", ",", "OutputStream", "os", ")", "{", "return", "transformEntries", "(", "is", ",", "new", "ZipEntryTransformerEntry", "[", "]", "{", "entry", "}", ...
Copies an existing ZIP file and transforms a given entry in it. @param is a ZIP input stream. @param entry transformer for a ZIP entry. @param os a ZIP output stream. @return <code>true</code> if the entry was replaced.
[ "Copies", "an", "existing", "ZIP", "file", "and", "transforms", "a", "given", "entry", "in", "it", "." ]
train
https://github.com/zeroturnaround/zt-zip/blob/abb4dc43583e4d19339c0c021035019798970a13/src/main/java/org/zeroturnaround/zip/ZipUtil.java#L2910-L2912
azkaban/azkaban
azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java
JdbcProjectImpl.addProjectToProjectVersions
private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values " + "(?,?,?,?,?,?,?,?,?)"; try { /* * As we don't know the num_chunks before uploading the file, we initialize it to 0, * and will update it after uploading completes. */ transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, Files.getFileExtension(localFile.getName()), localFile.getName(), md5, 0, resourceId); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }
java
private void addProjectToProjectVersions( final DatabaseTransOperator transOperator, final int projectId, final int version, final File localFile, final String uploader, final byte[] md5, final String resourceId) throws ProjectManagerException { final long updateTime = System.currentTimeMillis(); final String INSERT_PROJECT_VERSION = "INSERT INTO project_versions " + "(project_id, version, upload_time, uploader, file_type, file_name, md5, num_chunks, resource_id) values " + "(?,?,?,?,?,?,?,?,?)"; try { /* * As we don't know the num_chunks before uploading the file, we initialize it to 0, * and will update it after uploading completes. */ transOperator.update(INSERT_PROJECT_VERSION, projectId, version, updateTime, uploader, Files.getFileExtension(localFile.getName()), localFile.getName(), md5, 0, resourceId); } catch (final SQLException e) { final String msg = String .format("Error initializing project id: %d version: %d ", projectId, version); logger.error(msg, e); throw new ProjectManagerException(msg, e); } }
[ "private", "void", "addProjectToProjectVersions", "(", "final", "DatabaseTransOperator", "transOperator", ",", "final", "int", "projectId", ",", "final", "int", "version", ",", "final", "File", "localFile", ",", "final", "String", "uploader", ",", "final", "byte", ...
Insert a new version record to TABLE project_versions before uploading files. The reason for this operation: When error chunking happens in remote mysql server, incomplete file data remains in DB, and an SQL exception is thrown. If we don't have this operation before uploading file, the SQL exception prevents AZ from creating the new version record in Table project_versions. However, the Table project_files still reserve the incomplete files, which causes troubles when uploading a new file: Since the version in TABLE project_versions is still old, mysql will stop inserting new files to db. Why this operation is safe: When AZ uploads a new zip file, it always fetches the latest version proj_v from TABLE project_version, proj_v+1 will be used as the new version for the uploading files. Assume error chunking happens on day 1. proj_v is created for this bad file (old file version + 1). When we upload a new project zip in day2, new file in day 2 will use the new version (proj_v + 1). When file uploading completes, AZ will clean all old chunks in DB afterward.
[ "Insert", "a", "new", "version", "record", "to", "TABLE", "project_versions", "before", "uploading", "files", "." ]
train
https://github.com/azkaban/azkaban/blob/d258ea7d6e66807c6eff79c5325d6d3443618dff/azkaban-common/src/main/java/azkaban/project/JdbcProjectImpl.java#L344-L370
aws/aws-sdk-java
aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DeleteReservationResult.java
DeleteReservationResult.withTags
public DeleteReservationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
java
public DeleteReservationResult withTags(java.util.Map<String, String> tags) { setTags(tags); return this; }
[ "public", "DeleteReservationResult", "withTags", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "tags", ")", "{", "setTags", "(", "tags", ")", ";", "return", "this", ";", "}" ]
A collection of key-value pairs @param tags A collection of key-value pairs @return Returns a reference to this object so that method calls can be chained together.
[ "A", "collection", "of", "key", "-", "value", "pairs" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-medialive/src/main/java/com/amazonaws/services/medialive/model/DeleteReservationResult.java#L688-L691
google/closure-compiler
src/com/google/javascript/jscomp/Promises.java
Promises.getResolvedType
static final JSType getResolvedType(JSTypeRegistry registry, JSType type) { if (type.isUnknownType()) { return type; } if (type.isUnionType()) { UnionTypeBuilder unionTypeBuilder = UnionTypeBuilder.create(registry); for (JSType alternate : type.toMaybeUnionType().getAlternates()) { unionTypeBuilder.addAlternate(getResolvedType(registry, alternate)); } return unionTypeBuilder.build(); } // If we can find the "IThenable" template key (which is true for Promise and IThenable), return // the resolved value. e.g. for "!Promise<string>" return "string". TemplateTypeMap templates = type.getTemplateTypeMap(); if (templates.hasTemplateKey(registry.getIThenableTemplate())) { // Call getResolvedPromiseType again in case someone does something unusual like // !Promise<!Promise<number>> // TODO(lharker): we don't need to handle this case and should report an error for this in a // type annotation (not here, maybe in TypeCheck). A Promise cannot resolve to another Promise return getResolvedType( registry, templates.getResolvedTemplateType(registry.getIThenableTemplate())); } // Awaiting anything with a ".then" property (other than IThenable, handled above) should return // unknown, rather than the type itself. if (type.isSubtypeOf(registry.getNativeType(JSTypeNative.THENABLE_TYPE))) { return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } return type; }
java
static final JSType getResolvedType(JSTypeRegistry registry, JSType type) { if (type.isUnknownType()) { return type; } if (type.isUnionType()) { UnionTypeBuilder unionTypeBuilder = UnionTypeBuilder.create(registry); for (JSType alternate : type.toMaybeUnionType().getAlternates()) { unionTypeBuilder.addAlternate(getResolvedType(registry, alternate)); } return unionTypeBuilder.build(); } // If we can find the "IThenable" template key (which is true for Promise and IThenable), return // the resolved value. e.g. for "!Promise<string>" return "string". TemplateTypeMap templates = type.getTemplateTypeMap(); if (templates.hasTemplateKey(registry.getIThenableTemplate())) { // Call getResolvedPromiseType again in case someone does something unusual like // !Promise<!Promise<number>> // TODO(lharker): we don't need to handle this case and should report an error for this in a // type annotation (not here, maybe in TypeCheck). A Promise cannot resolve to another Promise return getResolvedType( registry, templates.getResolvedTemplateType(registry.getIThenableTemplate())); } // Awaiting anything with a ".then" property (other than IThenable, handled above) should return // unknown, rather than the type itself. if (type.isSubtypeOf(registry.getNativeType(JSTypeNative.THENABLE_TYPE))) { return registry.getNativeType(JSTypeNative.UNKNOWN_TYPE); } return type; }
[ "static", "final", "JSType", "getResolvedType", "(", "JSTypeRegistry", "registry", ",", "JSType", "type", ")", "{", "if", "(", "type", ".", "isUnknownType", "(", ")", ")", "{", "return", "type", ";", "}", "if", "(", "type", ".", "isUnionType", "(", ")", ...
Returns the type of `await [expr]`. <p>This is equivalent to the type of `result` in `Promise.resolve([expr]).then(result => ` <p>For example: <p>{@code !Promise<number>} becomes {@code number} <p>{@code !IThenable<number>} becomes {@code number} <p>{@code string} becomes {@code string} <p>{@code (!Promise<number>|string)} becomes {@code (number|string)} <p>{@code ?Promise<number>} becomes {@code (null|number)}
[ "Returns", "the", "type", "of", "await", "[", "expr", "]", "." ]
train
https://github.com/google/closure-compiler/blob/d81e36740f6a9e8ac31a825ee8758182e1dc5aae/src/com/google/javascript/jscomp/Promises.java#L70-L102
baidubce/bce-sdk-java
src/main/java/com/baidubce/services/lss/LssUtils.java
LssUtils.hmacSha256
public static String hmacSha256(String input, String secretKey) { if (input == null) { throw new NullPointerException("input"); } else if (secretKey == null) { throw new NullPointerException("secretKey"); } return hmacSha256(input.getBytes(CHARSET_UTF8), secretKey.getBytes(CHARSET_UTF8)); }
java
public static String hmacSha256(String input, String secretKey) { if (input == null) { throw new NullPointerException("input"); } else if (secretKey == null) { throw new NullPointerException("secretKey"); } return hmacSha256(input.getBytes(CHARSET_UTF8), secretKey.getBytes(CHARSET_UTF8)); }
[ "public", "static", "String", "hmacSha256", "(", "String", "input", ",", "String", "secretKey", ")", "{", "if", "(", "input", "==", "null", ")", "{", "throw", "new", "NullPointerException", "(", "\"input\"", ")", ";", "}", "else", "if", "(", "secretKey", ...
Encodes the input String using the UTF8 charset and calls hmacSha256; @param input data to calculate mac @param secretKey secret key @return String, sha256 mac
[ "Encodes", "the", "input", "String", "using", "the", "UTF8", "charset", "and", "calls", "hmacSha256", ";" ]
train
https://github.com/baidubce/bce-sdk-java/blob/f7140f28dd82121515c88ded7bfe769a37d0ec4a/src/main/java/com/baidubce/services/lss/LssUtils.java#L27-L34
EdwardRaff/JSAT
JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java
BOGD.guessRegularization
public static Distribution guessRegularization(DataSet d) { double T2 = d.size(); T2*=T2; return new LogUniform(Math.pow(2, -3)/T2, Math.pow(2, 3)/T2); }
java
public static Distribution guessRegularization(DataSet d) { double T2 = d.size(); T2*=T2; return new LogUniform(Math.pow(2, -3)/T2, Math.pow(2, 3)/T2); }
[ "public", "static", "Distribution", "guessRegularization", "(", "DataSet", "d", ")", "{", "double", "T2", "=", "d", ".", "size", "(", ")", ";", "T2", "*=", "T2", ";", "return", "new", "LogUniform", "(", "Math", ".", "pow", "(", "2", ",", "-", "3", ...
Guesses the distribution to use for the Regularization parameter @param d the dataset to get the guess for @return the guess for the Regularization parameter @see #setRegularization(double)
[ "Guesses", "the", "distribution", "to", "use", "for", "the", "Regularization", "parameter" ]
train
https://github.com/EdwardRaff/JSAT/blob/0ff53b7b39684b2379cc1da522f5b3a954b15cfb/JSAT/src/jsat/classifiers/linear/kernelized/BOGD.java#L388-L394
alkacon/opencms-core
src/org/opencms/jsp/CmsJspResourceWrapper.java
CmsJspResourceWrapper.readResource
private CmsJspResourceWrapper readResource(String sitePath) { CmsJspResourceWrapper result = null; try { result = new CmsJspResourceWrapper(m_cms, m_cms.readResource(sitePath)); } catch (CmsException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } return result; }
java
private CmsJspResourceWrapper readResource(String sitePath) { CmsJspResourceWrapper result = null; try { result = new CmsJspResourceWrapper(m_cms, m_cms.readResource(sitePath)); } catch (CmsException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } return result; }
[ "private", "CmsJspResourceWrapper", "readResource", "(", "String", "sitePath", ")", "{", "CmsJspResourceWrapper", "result", "=", "null", ";", "try", "{", "result", "=", "new", "CmsJspResourceWrapper", "(", "m_cms", ",", "m_cms", ".", "readResource", "(", "sitePath...
Reads a resource, suppressing possible exceptions.<p> @param sitePath the site path of the resource to read. @return the resource of <code>null</code> on case an exception occurred while reading
[ "Reads", "a", "resource", "suppressing", "possible", "exceptions", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/jsp/CmsJspResourceWrapper.java#L866-L877
stratosphere/stratosphere
stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java
VertexCentricIteration.createResult
@Override public DataSet<Tuple2<VertexKey, VertexValue>> createResult() { if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare some type information TypeInformation<Tuple2<VertexKey, VertexValue>> vertexTypes = initialVertices.getType(); TypeInformation<VertexKey> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<VertexKey, Message>> messageTypeInfo = new TupleTypeInfo<Tuple2<VertexKey,Message>>(keyType, messageType); // set up the iteration operator final String name = (this.name != null) ? this.name : "Vertex-centric iteration (" + updateFunction + " | " + messagingFunction + ")"; final int[] zeroKeyPos = new int[] {0}; final DeltaIteration<Tuple2<VertexKey, VertexValue>, Tuple2<VertexKey, VertexValue>> iteration = this.initialVertices.iterateDelta(this.initialVertices, this.maximumNumberOfIterations, zeroKeyPos); iteration.name(name); iteration.parallelism(parallelism); // register all aggregators for (Map.Entry<String, Class<? extends Aggregator<?>>> entry : this.aggregators.entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } // build the messaging function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, Message>> messages; if (edgesWithoutValue != null) { MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message> messenger = new MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message>(messagingFunction, messageTypeInfo); messages = this.edgesWithoutValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } else { MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue> messenger = new MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue>(messagingFunction, messageTypeInfo); messages = this.edgesWithValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } // configure coGroup message function with name and broadcast variables messages = messages.name("Messaging"); for (Tuple2<String, DataSet<?>> e : this.bcVarsMessaging) { messages = messages.withBroadcastSet(e.f1, e.f0); } VertexUpdateUdf<VertexKey, VertexValue, Message> updateUdf = new VertexUpdateUdf<VertexKey, VertexValue, Message>(updateFunction, vertexTypes); // build the update function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, VertexValue>> updates = messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf); // configure coGroup update function with name and broadcast variables updates = updates.name("Vertex State Updates"); for (Tuple2<String, DataSet<?>> e : this.bcVarsUpdate) { updates = updates.withBroadcastSet(e.f1, e.f0); } // let the operator know that we preserve the key field updates.withConstantSetFirst("0").withConstantSetSecond("0"); return iteration.closeWith(updates, updates); }
java
@Override public DataSet<Tuple2<VertexKey, VertexValue>> createResult() { if (this.initialVertices == null) { throw new IllegalStateException("The input data set has not been set."); } // prepare some type information TypeInformation<Tuple2<VertexKey, VertexValue>> vertexTypes = initialVertices.getType(); TypeInformation<VertexKey> keyType = ((TupleTypeInfo<?>) initialVertices.getType()).getTypeAt(0); TypeInformation<Tuple2<VertexKey, Message>> messageTypeInfo = new TupleTypeInfo<Tuple2<VertexKey,Message>>(keyType, messageType); // set up the iteration operator final String name = (this.name != null) ? this.name : "Vertex-centric iteration (" + updateFunction + " | " + messagingFunction + ")"; final int[] zeroKeyPos = new int[] {0}; final DeltaIteration<Tuple2<VertexKey, VertexValue>, Tuple2<VertexKey, VertexValue>> iteration = this.initialVertices.iterateDelta(this.initialVertices, this.maximumNumberOfIterations, zeroKeyPos); iteration.name(name); iteration.parallelism(parallelism); // register all aggregators for (Map.Entry<String, Class<? extends Aggregator<?>>> entry : this.aggregators.entrySet()) { iteration.registerAggregator(entry.getKey(), entry.getValue()); } // build the messaging function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, Message>> messages; if (edgesWithoutValue != null) { MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message> messenger = new MessagingUdfNoEdgeValues<VertexKey, VertexValue, Message>(messagingFunction, messageTypeInfo); messages = this.edgesWithoutValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } else { MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue> messenger = new MessagingUdfWithEdgeValues<VertexKey, VertexValue, Message, EdgeValue>(messagingFunction, messageTypeInfo); messages = this.edgesWithValue.coGroup(iteration.getWorkset()).where(0).equalTo(0).with(messenger); } // configure coGroup message function with name and broadcast variables messages = messages.name("Messaging"); for (Tuple2<String, DataSet<?>> e : this.bcVarsMessaging) { messages = messages.withBroadcastSet(e.f1, e.f0); } VertexUpdateUdf<VertexKey, VertexValue, Message> updateUdf = new VertexUpdateUdf<VertexKey, VertexValue, Message>(updateFunction, vertexTypes); // build the update function (co group) CoGroupOperator<?, ?, Tuple2<VertexKey, VertexValue>> updates = messages.coGroup(iteration.getSolutionSet()).where(0).equalTo(0).with(updateUdf); // configure coGroup update function with name and broadcast variables updates = updates.name("Vertex State Updates"); for (Tuple2<String, DataSet<?>> e : this.bcVarsUpdate) { updates = updates.withBroadcastSet(e.f1, e.f0); } // let the operator know that we preserve the key field updates.withConstantSetFirst("0").withConstantSetSecond("0"); return iteration.closeWith(updates, updates); }
[ "@", "Override", "public", "DataSet", "<", "Tuple2", "<", "VertexKey", ",", "VertexValue", ">", ">", "createResult", "(", ")", "{", "if", "(", "this", ".", "initialVertices", "==", "null", ")", "{", "throw", "new", "IllegalStateException", "(", "\"The input ...
Creates the operator that represents this vertex-centric graph computation. @return The operator that represents this vertex-centric graph computation.
[ "Creates", "the", "operator", "that", "represents", "this", "vertex", "-", "centric", "graph", "computation", "." ]
train
https://github.com/stratosphere/stratosphere/blob/c543a08f9676c5b2b0a7088123bd6e795a8ae0c8/stratosphere-addons/spargel/src/main/java/eu/stratosphere/spargel/java/VertexCentricIteration.java#L267-L327
anotheria/moskito
moskito-core/src/main/java/net/anotheria/moskito/core/util/annotation/AnnotationUtils.java
AnnotationUtils.findAnnotation
public static <A extends Annotation> A findAnnotation(final Annotation source, final Class<A> targetAnnotationClass) { Objects.requireNonNull(source, "incoming 'source' is not valid"); Objects.requireNonNull(targetAnnotationClass, "incoming 'targetAnnotationClass' is not valid"); return findAnnotation(source, targetAnnotationClass, new HashSet<Class<? extends Annotation>>()); }
java
public static <A extends Annotation> A findAnnotation(final Annotation source, final Class<A> targetAnnotationClass) { Objects.requireNonNull(source, "incoming 'source' is not valid"); Objects.requireNonNull(targetAnnotationClass, "incoming 'targetAnnotationClass' is not valid"); return findAnnotation(source, targetAnnotationClass, new HashSet<Class<? extends Annotation>>()); }
[ "public", "static", "<", "A", "extends", "Annotation", ">", "A", "findAnnotation", "(", "final", "Annotation", "source", ",", "final", "Class", "<", "A", ">", "targetAnnotationClass", ")", "{", "Objects", ".", "requireNonNull", "(", "source", ",", "\"incoming ...
Deep search of specified source considering "annotation as meta annotation" case (source annotated with specified source). @param source {@link Annotation} - source @param targetAnnotationClass represents class of the required annotaiton @param <A> type param @return {@link A} in case if found, {@code null} otherwise
[ "Deep", "search", "of", "specified", "source", "considering", "annotation", "as", "meta", "annotation", "case", "(", "source", "annotated", "with", "specified", "source", ")", "." ]
train
https://github.com/anotheria/moskito/blob/0fdb79053b98a6ece610fa159f59bc3331e4cf05/moskito-core/src/main/java/net/anotheria/moskito/core/util/annotation/AnnotationUtils.java#L76-L80
apache/flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java
AbstractFileStateBackend.validatePath
private static Path validatePath(Path path) { final URI uri = path.toUri(); final String scheme = uri.getScheme(); final String pathPart = uri.getPath(); // some validity checks if (scheme == null) { throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " + "Please specify the file system scheme explicitly in the URI."); } if (pathPart == null) { throw new IllegalArgumentException("The path to store the checkpoint data in is null. " + "Please specify a directory path for the checkpoint data."); } if (pathPart.length() == 0 || pathPart.equals("/")) { throw new IllegalArgumentException("Cannot use the root directory for checkpoints."); } return path; }
java
private static Path validatePath(Path path) { final URI uri = path.toUri(); final String scheme = uri.getScheme(); final String pathPart = uri.getPath(); // some validity checks if (scheme == null) { throw new IllegalArgumentException("The scheme (hdfs://, file://, etc) is null. " + "Please specify the file system scheme explicitly in the URI."); } if (pathPart == null) { throw new IllegalArgumentException("The path to store the checkpoint data in is null. " + "Please specify a directory path for the checkpoint data."); } if (pathPart.length() == 0 || pathPart.equals("/")) { throw new IllegalArgumentException("Cannot use the root directory for checkpoints."); } return path; }
[ "private", "static", "Path", "validatePath", "(", "Path", "path", ")", "{", "final", "URI", "uri", "=", "path", ".", "toUri", "(", ")", ";", "final", "String", "scheme", "=", "uri", ".", "getScheme", "(", ")", ";", "final", "String", "pathPart", "=", ...
Checks the validity of the path's scheme and path. @param path The path to check. @return The URI as a Path. @throws IllegalArgumentException Thrown, if the URI misses scheme or path.
[ "Checks", "the", "validity", "of", "the", "path", "s", "scheme", "and", "path", "." ]
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java#L180-L199
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/application/impl/metadata/ProcessesXmlParse.java
ProcessesXmlParse.parseProcessArchive
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) { ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl(); processArchive.setName(element.attribute(NAME)); processArchive.setTenantId(element.attribute(TENANT_ID)); List<String> processResourceNames = new ArrayList<String>(); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if(PROCESS_ENGINE.equals(childElement.getTagName())) { processArchive.setProcessEngineName(childElement.getText()); } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) { processResourceNames.add(childElement.getText()); } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } } // set properties processArchive.setProperties(properties); // add collected resource names. processArchive.setProcessResourceNames(processResourceNames); // add process archive to list of parsed archives. parsedProcessArchives.add(processArchive); }
java
protected void parseProcessArchive(Element element, List<ProcessArchiveXml> parsedProcessArchives) { ProcessArchiveXmlImpl processArchive = new ProcessArchiveXmlImpl(); processArchive.setName(element.attribute(NAME)); processArchive.setTenantId(element.attribute(TENANT_ID)); List<String> processResourceNames = new ArrayList<String>(); Map<String, String> properties = new HashMap<String, String>(); for (Element childElement : element.elements()) { if(PROCESS_ENGINE.equals(childElement.getTagName())) { processArchive.setProcessEngineName(childElement.getText()); } else if(PROCESS.equals(childElement.getTagName()) || RESOURCE.equals(childElement.getTagName())) { processResourceNames.add(childElement.getText()); } else if(PROPERTIES.equals(childElement.getTagName())) { parseProperties(childElement, properties); } } // set properties processArchive.setProperties(properties); // add collected resource names. processArchive.setProcessResourceNames(processResourceNames); // add process archive to list of parsed archives. parsedProcessArchives.add(processArchive); }
[ "protected", "void", "parseProcessArchive", "(", "Element", "element", ",", "List", "<", "ProcessArchiveXml", ">", "parsedProcessArchives", ")", "{", "ProcessArchiveXmlImpl", "processArchive", "=", "new", "ProcessArchiveXmlImpl", "(", ")", ";", "processArchive", ".", ...
parse a <code>&lt;process-archive .../&gt;</code> element and add it to the list of parsed elements
[ "parse", "a", "<code", ">", "&lt", ";", "process", "-", "archive", "...", "/", "&gt", ";", "<", "/", "code", ">", "element", "and", "add", "it", "to", "the", "list", "of", "parsed", "elements" ]
train
https://github.com/camunda/camunda-bpm-platform/blob/1a464fc887ef3760e53d6f91b9e5b871a0d77cc0/engine/src/main/java/org/camunda/bpm/application/impl/metadata/ProcessesXmlParse.java#L92-L124
fleipold/jproc
src/main/java/org/buildobjects/process/ProcBuilder.java
ProcBuilder.run
public ProcResult run() throws StartupException, TimeoutException, ExternalProcessFailureException { if (stdout != defaultStdout && outputConsumer != null) { throw new IllegalArgumentException("You can either ..."); } try { Proc proc = new Proc(command, args, env, stdin, outputConsumer != null ? outputConsumer : stdout , directory, timoutMillis, expectedExitStatuses, stderr); return new ProcResult(proc.toString(), defaultStdout == stdout && outputConsumer == null ? defaultStdout : null, proc.getExitValue(), proc.getExecutionTime(), proc.getErrorBytes()); } finally { stdout = defaultStdout = new ByteArrayOutputStream(); stdin = null; } }
java
public ProcResult run() throws StartupException, TimeoutException, ExternalProcessFailureException { if (stdout != defaultStdout && outputConsumer != null) { throw new IllegalArgumentException("You can either ..."); } try { Proc proc = new Proc(command, args, env, stdin, outputConsumer != null ? outputConsumer : stdout , directory, timoutMillis, expectedExitStatuses, stderr); return new ProcResult(proc.toString(), defaultStdout == stdout && outputConsumer == null ? defaultStdout : null, proc.getExitValue(), proc.getExecutionTime(), proc.getErrorBytes()); } finally { stdout = defaultStdout = new ByteArrayOutputStream(); stdin = null; } }
[ "public", "ProcResult", "run", "(", ")", "throws", "StartupException", ",", "TimeoutException", ",", "ExternalProcessFailureException", "{", "if", "(", "stdout", "!=", "defaultStdout", "&&", "outputConsumer", "!=", "null", ")", "{", "throw", "new", "IllegalArgumentE...
Spawn the actual execution. This will block until the process terminates. @return the result of the successful execution @throws StartupException if the process can't be started @throws TimeoutException if the timeout kicked in @throws ExternalProcessFailureException if the external process returned a non-null exit value
[ "Spawn", "the", "actual", "execution", ".", "This", "will", "block", "until", "the", "process", "terminates", "." ]
train
https://github.com/fleipold/jproc/blob/617f498c63a822c6b0506a2474b3bc954ea25c9a/src/main/java/org/buildobjects/process/ProcBuilder.java#L198-L212
apache/flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java
StreamExecutionEnvironment.readTextFile
public DataStreamSource<String> readTextFile(String filePath, String charsetName) { Preconditions.checkArgument(!StringUtils.isNullOrWhitespaceOnly(filePath), "The file path must not be null or blank."); TextInputFormat format = new TextInputFormat(new Path(filePath)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); TypeInformation<String> typeInfo = BasicTypeInfo.STRING_TYPE_INFO; format.setCharsetName(charsetName); return readFile(format, filePath, FileProcessingMode.PROCESS_ONCE, -1, typeInfo); }
java
public DataStreamSource<String> readTextFile(String filePath, String charsetName) { Preconditions.checkArgument(!StringUtils.isNullOrWhitespaceOnly(filePath), "The file path must not be null or blank."); TextInputFormat format = new TextInputFormat(new Path(filePath)); format.setFilesFilter(FilePathFilter.createDefaultFilter()); TypeInformation<String> typeInfo = BasicTypeInfo.STRING_TYPE_INFO; format.setCharsetName(charsetName); return readFile(format, filePath, FileProcessingMode.PROCESS_ONCE, -1, typeInfo); }
[ "public", "DataStreamSource", "<", "String", ">", "readTextFile", "(", "String", "filePath", ",", "String", "charsetName", ")", "{", "Preconditions", ".", "checkArgument", "(", "!", "StringUtils", ".", "isNullOrWhitespaceOnly", "(", "filePath", ")", ",", "\"The fi...
Reads the given file line-by-line and creates a data stream that contains a string with the contents of each such line. The {@link java.nio.charset.Charset} with the given name will be used to read the files. <p><b>NOTES ON CHECKPOINTING: </b> The source monitors the path, creates the {@link org.apache.flink.core.fs.FileInputSplit FileInputSplits} to be processed, forwards them to the downstream {@link ContinuousFileReaderOperator readers} to read the actual data, and exits, without waiting for the readers to finish reading. This implies that no more checkpoint barriers are going to be forwarded after the source exits, thus having no checkpoints after that point. @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path") @param charsetName The name of the character set used to read the file @return The data stream that represents the data read from the given file as text lines
[ "Reads", "the", "given", "file", "line", "-", "by", "-", "line", "and", "creates", "a", "data", "stream", "that", "contains", "a", "string", "with", "the", "contents", "of", "each", "such", "line", ".", "The", "{", "@link", "java", ".", "nio", ".", "...
train
https://github.com/apache/flink/blob/b62db93bf63cb3bb34dd03d611a779d9e3fc61ac/flink-streaming-java/src/main/java/org/apache/flink/streaming/api/environment/StreamExecutionEnvironment.java#L959-L968
dbracewell/hermes
hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java
DocumentFactory.createRaw
public Document createRaw(@NonNull String content, @NonNull Language language) { return createRaw("", content, language, Collections.emptyMap()); }
java
public Document createRaw(@NonNull String content, @NonNull Language language) { return createRaw("", content, language, Collections.emptyMap()); }
[ "public", "Document", "createRaw", "(", "@", "NonNull", "String", "content", ",", "@", "NonNull", "Language", "language", ")", "{", "return", "createRaw", "(", "\"\"", ",", "content", ",", "language", ",", "Collections", ".", "emptyMap", "(", ")", ")", ";"...
Creates a document with the given content written in the given language. This method does not apply any {@link TextNormalizer} @param content the content @param language the language @return the document
[ "Creates", "a", "document", "with", "the", "given", "content", "written", "in", "the", "given", "language", ".", "This", "method", "does", "not", "apply", "any", "{", "@link", "TextNormalizer", "}" ]
train
https://github.com/dbracewell/hermes/blob/9ebefe7ad5dea1b731ae6931a30771eb75325ea3/hermes-core/src/main/java/com/davidbracewell/hermes/DocumentFactory.java#L205-L207
aws/aws-sdk-java
aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/DescribeIdentityPoolResult.java
DescribeIdentityPoolResult.withSupportedLoginProviders
public DescribeIdentityPoolResult withSupportedLoginProviders(java.util.Map<String, String> supportedLoginProviders) { setSupportedLoginProviders(supportedLoginProviders); return this; }
java
public DescribeIdentityPoolResult withSupportedLoginProviders(java.util.Map<String, String> supportedLoginProviders) { setSupportedLoginProviders(supportedLoginProviders); return this; }
[ "public", "DescribeIdentityPoolResult", "withSupportedLoginProviders", "(", "java", ".", "util", ".", "Map", "<", "String", ",", "String", ">", "supportedLoginProviders", ")", "{", "setSupportedLoginProviders", "(", "supportedLoginProviders", ")", ";", "return", "this",...
<p> Optional key:value pairs mapping provider names to provider app IDs. </p> @param supportedLoginProviders Optional key:value pairs mapping provider names to provider app IDs. @return Returns a reference to this object so that method calls can be chained together.
[ "<p", ">", "Optional", "key", ":", "value", "pairs", "mapping", "provider", "names", "to", "provider", "app", "IDs", ".", "<", "/", "p", ">" ]
train
https://github.com/aws/aws-sdk-java/blob/aa38502458969b2d13a1c3665a56aba600e4dbd0/aws-java-sdk-cognitoidentity/src/main/java/com/amazonaws/services/cognitoidentity/model/DescribeIdentityPoolResult.java#L252-L255
mygreen/xlsmapper
src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java
XmlIO.load
public static AnnotationMappingInfo load(final Reader reader) throws XmlOperateException { ArgUtils.notNull(reader, "reader"); final AnnotationMappingInfo xmlInfo; try { xmlInfo = JAXB.unmarshal(reader, AnnotationMappingInfo.class); } catch (DataBindingException e) { throw new XmlOperateException("fail load xml with JAXB.", e); } return xmlInfo; }
java
public static AnnotationMappingInfo load(final Reader reader) throws XmlOperateException { ArgUtils.notNull(reader, "reader"); final AnnotationMappingInfo xmlInfo; try { xmlInfo = JAXB.unmarshal(reader, AnnotationMappingInfo.class); } catch (DataBindingException e) { throw new XmlOperateException("fail load xml with JAXB.", e); } return xmlInfo; }
[ "public", "static", "AnnotationMappingInfo", "load", "(", "final", "Reader", "reader", ")", "throws", "XmlOperateException", "{", "ArgUtils", ".", "notNull", "(", "reader", ",", "\"reader\"", ")", ";", "final", "AnnotationMappingInfo", "xmlInfo", ";", "try", "{", ...
XMLを読み込み、{@link AnnotationMappingInfo}として取得する。 @since 0.5 @param reader @return @throws XmlOperateException XMLの読み込みに失敗した場合。 @throws IllegalArgumentException in is null.
[ "XMLを読み込み、", "{" ]
train
https://github.com/mygreen/xlsmapper/blob/a0c6b25c622e5f3a50b199ef685d2ee46ad5483c/src/main/java/com/gh/mygreen/xlsmapper/xml/XmlIO.java#L62-L74
VoltDB/voltdb
src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java
JDBC4CallableStatement.setRowId
@Override public void setRowId(String parameterName, RowId x) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
java
@Override public void setRowId(String parameterName, RowId x) throws SQLException { checkClosed(); throw SQLError.noSupport(); }
[ "@", "Override", "public", "void", "setRowId", "(", "String", "parameterName", ",", "RowId", "x", ")", "throws", "SQLException", "{", "checkClosed", "(", ")", ";", "throw", "SQLError", ".", "noSupport", "(", ")", ";", "}" ]
Sets the designated parameter to the given java.sql.RowId object.
[ "Sets", "the", "designated", "parameter", "to", "the", "given", "java", ".", "sql", ".", "RowId", "object", "." ]
train
https://github.com/VoltDB/voltdb/blob/8afc1031e475835344b5497ea9e7203bc95475ac/src/frontend/org/voltdb/jdbc/JDBC4CallableStatement.java#L855-L860
craftercms/deployer
src/main/java/org/craftercms/deployer/utils/ConfigUtils.java
ConfigUtils.getIntegerProperty
public static Integer getIntegerProperty(Configuration config, String key) throws DeployerConfigurationException { return getIntegerProperty(config, key, null); }
java
public static Integer getIntegerProperty(Configuration config, String key) throws DeployerConfigurationException { return getIntegerProperty(config, key, null); }
[ "public", "static", "Integer", "getIntegerProperty", "(", "Configuration", "config", ",", "String", "key", ")", "throws", "DeployerConfigurationException", "{", "return", "getIntegerProperty", "(", "config", ",", "key", ",", "null", ")", ";", "}" ]
Returns the specified Integer property from the configuration @param config the configuration @param key the key of the property @return the Integer value of the property, or null if not found @throws DeployerConfigurationException if an error occurred
[ "Returns", "the", "specified", "Integer", "property", "from", "the", "configuration" ]
train
https://github.com/craftercms/deployer/blob/3ed446e3cc8af1055de2de6f871907f90ef27f63/src/main/java/org/craftercms/deployer/utils/ConfigUtils.java#L170-L172
acromusashi/acromusashi-stream-ml
src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java
LofCalculator.calculateReachDistance
protected static double calculateReachDistance(LofPoint basePoint, LofPoint targetPoint) { double distance = MathUtils.distance(basePoint.getDataPoint(), targetPoint.getDataPoint()); double reachDistance = (double) ComparatorUtils.max(distance, targetPoint.getkDistance(), ComparatorUtils.NATURAL_COMPARATOR); return reachDistance; }
java
protected static double calculateReachDistance(LofPoint basePoint, LofPoint targetPoint) { double distance = MathUtils.distance(basePoint.getDataPoint(), targetPoint.getDataPoint()); double reachDistance = (double) ComparatorUtils.max(distance, targetPoint.getkDistance(), ComparatorUtils.NATURAL_COMPARATOR); return reachDistance; }
[ "protected", "static", "double", "calculateReachDistance", "(", "LofPoint", "basePoint", ",", "LofPoint", "targetPoint", ")", "{", "double", "distance", "=", "MathUtils", ".", "distance", "(", "basePoint", ".", "getDataPoint", "(", ")", ",", "targetPoint", ".", ...
basePointのtargetPointに関する到達可能距離(Reachability distance)を算出する。 @param basePoint 算出元対象点 @param targetPoint 算出先対象点 @return 到達可能距離
[ "basePointのtargetPointに関する到達可能距離", "(", "Reachability", "distance", ")", "を算出する。" ]
train
https://github.com/acromusashi/acromusashi-stream-ml/blob/26d6799a917cacda68e21d506c75cfeb17d832a6/src/main/java/acromusashi/stream/ml/anomaly/lof/LofCalculator.java#L365-L372
czyzby/gdx-lml
kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/scene2d/Actors.java
Actors.setAlpha
public static void setAlpha(final Stage stage, final float alpha) { if (stage != null) { setAlpha(stage.getRoot(), alpha); } }
java
public static void setAlpha(final Stage stage, final float alpha) { if (stage != null) { setAlpha(stage.getRoot(), alpha); } }
[ "public", "static", "void", "setAlpha", "(", "final", "Stage", "stage", ",", "final", "float", "alpha", ")", "{", "if", "(", "stage", "!=", "null", ")", "{", "setAlpha", "(", "stage", ".", "getRoot", "(", ")", ",", "alpha", ")", ";", "}", "}" ]
Null-safe alpha setting method. @param stage its root actor's alpha will be modified, affecting all actors in the stage. Can be null. @param alpha will replace current actor's alpha.
[ "Null", "-", "safe", "alpha", "setting", "method", "." ]
train
https://github.com/czyzby/gdx-lml/blob/7623b322e6afe49ad4dd636c80c230150a1cfa4e/kiwi/src/main/java/com/github/czyzby/kiwi/util/gdx/scene2d/Actors.java#L154-L158
belaban/JGroups
src/org/jgroups/util/MessageBatch.java
MessageBatch.getMatchingMessages
public Collection<Message> getMatchingMessages(final short id, boolean remove) { return map((msg, batch) -> { if(msg != null && msg.getHeader(id) != null) { if(remove) batch.remove(msg); return msg; } return null; }); }
java
public Collection<Message> getMatchingMessages(final short id, boolean remove) { return map((msg, batch) -> { if(msg != null && msg.getHeader(id) != null) { if(remove) batch.remove(msg); return msg; } return null; }); }
[ "public", "Collection", "<", "Message", ">", "getMatchingMessages", "(", "final", "short", "id", ",", "boolean", "remove", ")", "{", "return", "map", "(", "(", "msg", ",", "batch", ")", "->", "{", "if", "(", "msg", "!=", "null", "&&", "msg", ".", "ge...
Removes and returns all messages which have a header with ID == id
[ "Removes", "and", "returns", "all", "messages", "which", "have", "a", "header", "with", "ID", "==", "id" ]
train
https://github.com/belaban/JGroups/blob/bd3ca786aa57fed41dfbc10a94b1281e388be03b/src/org/jgroups/util/MessageBatch.java#L285-L294
dwdyer/watchmaker
examples/src/java/main/org/uncommons/watchmaker/examples/sudoku/SudokuCellRenderer.java
SudokuCellRenderer.getBorder
private Border getBorder(int row, int column) { if (row % 3 == 2) { switch (column % 3) { case 2: return BOTTOM_RIGHT_BORDER; case 0: return BOTTOM_LEFT_BORDER; default: return BOTTOM_BORDER; } } else if (row % 3 == 0) { switch (column % 3) { case 2: return TOP_RIGHT_BORDER; case 0: return TOP_LEFT_BORDER; default: return TOP_BORDER; } } switch (column % 3) { case 2: return RIGHT_BORDER; case 0: return LEFT_BORDER; default: return null; } }
java
private Border getBorder(int row, int column) { if (row % 3 == 2) { switch (column % 3) { case 2: return BOTTOM_RIGHT_BORDER; case 0: return BOTTOM_LEFT_BORDER; default: return BOTTOM_BORDER; } } else if (row % 3 == 0) { switch (column % 3) { case 2: return TOP_RIGHT_BORDER; case 0: return TOP_LEFT_BORDER; default: return TOP_BORDER; } } switch (column % 3) { case 2: return RIGHT_BORDER; case 0: return LEFT_BORDER; default: return null; } }
[ "private", "Border", "getBorder", "(", "int", "row", ",", "int", "column", ")", "{", "if", "(", "row", "%", "3", "==", "2", ")", "{", "switch", "(", "column", "%", "3", ")", "{", "case", "2", ":", "return", "BOTTOM_RIGHT_BORDER", ";", "case", "0", ...
Get appropriate border for cell based on its position in the grid.
[ "Get", "appropriate", "border", "for", "cell", "based", "on", "its", "position", "in", "the", "grid", "." ]
train
https://github.com/dwdyer/watchmaker/blob/33d942350e6bf7d9a17b9262a4f898158530247e/examples/src/java/main/org/uncommons/watchmaker/examples/sudoku/SudokuCellRenderer.java#L134-L161
alkacon/opencms-core
src/org/opencms/util/CmsRequestUtil.java
CmsRequestUtil.redirectRequestSecure
public static void redirectRequestSecure(CmsJspActionElement jsp, String target) throws IOException { jsp.getResponse().sendRedirect(OpenCms.getLinkManager().substituteLink(jsp.getCmsObject(), target, null, true)); }
java
public static void redirectRequestSecure(CmsJspActionElement jsp, String target) throws IOException { jsp.getResponse().sendRedirect(OpenCms.getLinkManager().substituteLink(jsp.getCmsObject(), target, null, true)); }
[ "public", "static", "void", "redirectRequestSecure", "(", "CmsJspActionElement", "jsp", ",", "String", "target", ")", "throws", "IOException", "{", "jsp", ".", "getResponse", "(", ")", ".", "sendRedirect", "(", "OpenCms", ".", "getLinkManager", "(", ")", ".", ...
Redirects the response to the target link.<p> Use this method instead of {@link javax.servlet.http.HttpServletResponse#sendRedirect(java.lang.String)} to avoid relative links with secure sites (and issues with apache).<p> @param jsp the OpenCms JSP context @param target the target link @throws IOException if something goes wrong during redirection
[ "Redirects", "the", "response", "to", "the", "target", "link", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src/org/opencms/util/CmsRequestUtil.java#L870-L873
OpenLiberty/open-liberty
dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java
ConnectionDataGroup.createnewConnectionData
private ConnectionData createnewConnectionData(NetworkConnection vc) throws FrameworkException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createnewConnectionData", vc); ConnectionData connectionDataToUse; NetworkConnectionContext connLink = vc.getNetworkConnectionContext(); connectionDataToUse = new ConnectionData(this, groupEndpointDescriptor); connectionDataToUse.incrementUseCount(); // New connections start with a use count of zero and it is now in use // No need to lock as it's not in the connectionData list yet OutboundConnection oc = new OutboundConnection(connLink, vc, tracker, heartbeatInterval, heartbeatTimeout, connectionDataToUse); connectionDataToUse.setConnection(oc); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "createnewConnectionData", connectionDataToUse); return connectionDataToUse; }
java
private ConnectionData createnewConnectionData(NetworkConnection vc) throws FrameworkException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "createnewConnectionData", vc); ConnectionData connectionDataToUse; NetworkConnectionContext connLink = vc.getNetworkConnectionContext(); connectionDataToUse = new ConnectionData(this, groupEndpointDescriptor); connectionDataToUse.incrementUseCount(); // New connections start with a use count of zero and it is now in use // No need to lock as it's not in the connectionData list yet OutboundConnection oc = new OutboundConnection(connLink, vc, tracker, heartbeatInterval, heartbeatTimeout, connectionDataToUse); connectionDataToUse.setConnection(oc); if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "createnewConnectionData", connectionDataToUse); return connectionDataToUse; }
[ "private", "ConnectionData", "createnewConnectionData", "(", "NetworkConnection", "vc", ")", "throws", "FrameworkException", "{", "if", "(", "TraceComponent", ".", "isAnyTracingEnabled", "(", ")", "&&", "tc", ".", "isEntryEnabled", "(", ")", ")", "SibTr", ".", "en...
Create a new Connection data object @param vc The network connection over which to create a connection data @return ConnectionData A new connection data object @throws FrameworkException is thrown if the new connection data cannot be created
[ "Create", "a", "new", "Connection", "data", "object" ]
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.messaging.comms.client/src/com/ibm/ws/sib/jfapchannel/impl/octracker/ConnectionDataGroup.java#L800-L824
mojohaus/jaxb2-maven-plugin
src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java
DomHelper.addXmlDocumentAnnotationTo
public static void addXmlDocumentAnnotationTo(final Node aNode, final String formattedDocumentation) { if (aNode != null && formattedDocumentation != null && !formattedDocumentation.isEmpty()) { // Add the new Elements, as required. final Document doc = aNode.getOwnerDocument(); final Element annotation = doc.createElementNS( XMLConstants.W3C_XML_SCHEMA_NS_URI, ANNOTATION_ELEMENT_NAME); final Element docElement = doc.createElementNS( XMLConstants.W3C_XML_SCHEMA_NS_URI, DOCUMENTATION_ELEMENT_NAME); final CDATASection xsdDocumentation = doc.createCDATASection(formattedDocumentation); // Set the prefixes annotation.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX); docElement.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX); // Inject the formattedDocumentation into the CDATA section. annotation.appendChild(docElement); final Node firstChildOfCurrentNode = aNode.getFirstChild(); if (firstChildOfCurrentNode == null) { aNode.appendChild(annotation); } else { aNode.insertBefore(annotation, firstChildOfCurrentNode); } // All Done. docElement.appendChild(xsdDocumentation); } }
java
public static void addXmlDocumentAnnotationTo(final Node aNode, final String formattedDocumentation) { if (aNode != null && formattedDocumentation != null && !formattedDocumentation.isEmpty()) { // Add the new Elements, as required. final Document doc = aNode.getOwnerDocument(); final Element annotation = doc.createElementNS( XMLConstants.W3C_XML_SCHEMA_NS_URI, ANNOTATION_ELEMENT_NAME); final Element docElement = doc.createElementNS( XMLConstants.W3C_XML_SCHEMA_NS_URI, DOCUMENTATION_ELEMENT_NAME); final CDATASection xsdDocumentation = doc.createCDATASection(formattedDocumentation); // Set the prefixes annotation.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX); docElement.setPrefix(XSD_SCHEMA_NAMESPACE_PREFIX); // Inject the formattedDocumentation into the CDATA section. annotation.appendChild(docElement); final Node firstChildOfCurrentNode = aNode.getFirstChild(); if (firstChildOfCurrentNode == null) { aNode.appendChild(annotation); } else { aNode.insertBefore(annotation, firstChildOfCurrentNode); } // All Done. docElement.appendChild(xsdDocumentation); } }
[ "public", "static", "void", "addXmlDocumentAnnotationTo", "(", "final", "Node", "aNode", ",", "final", "String", "formattedDocumentation", ")", "{", "if", "(", "aNode", "!=", "null", "&&", "formattedDocumentation", "!=", "null", "&&", "!", "formattedDocumentation", ...
<p>Adds the given formattedDocumentation within an XML documentation annotation under the supplied Node. Only adds the documentation annotation if the formattedDocumentation is non-null and non-empty. The documentation annotation is on the form:</p> <pre> <code> &lt;xs:annotation&gt; &lt;xs:documentation&gt;(JavaDoc here, within a CDATA section)&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; </code> </pre> @param aNode The non-null Node to which an XML documentation annotation should be added. @param formattedDocumentation The documentation text to add.
[ "<p", ">", "Adds", "the", "given", "formattedDocumentation", "within", "an", "XML", "documentation", "annotation", "under", "the", "supplied", "Node", ".", "Only", "adds", "the", "documentation", "annotation", "if", "the", "formattedDocumentation", "is", "non", "-...
train
https://github.com/mojohaus/jaxb2-maven-plugin/blob/e3c4e47943b15282e5a6e850bbfb1588d8452a0a/src/main/java/org/codehaus/mojo/jaxb2/schemageneration/postprocessing/javadoc/DomHelper.java#L134-L162
googleapis/google-http-java-client
google-http-client/src/main/java/com/google/api/client/util/Types.java
Types.isAssignableToOrFrom
public static boolean isAssignableToOrFrom(Class<?> classToCheck, Class<?> anotherClass) { return classToCheck.isAssignableFrom(anotherClass) || anotherClass.isAssignableFrom(classToCheck); }
java
public static boolean isAssignableToOrFrom(Class<?> classToCheck, Class<?> anotherClass) { return classToCheck.isAssignableFrom(anotherClass) || anotherClass.isAssignableFrom(classToCheck); }
[ "public", "static", "boolean", "isAssignableToOrFrom", "(", "Class", "<", "?", ">", "classToCheck", ",", "Class", "<", "?", ">", "anotherClass", ")", "{", "return", "classToCheck", ".", "isAssignableFrom", "(", "anotherClass", ")", "||", "anotherClass", ".", "...
Returns whether a class is either assignable to or from another class. @param classToCheck class to check @param anotherClass another class
[ "Returns", "whether", "a", "class", "is", "either", "assignable", "to", "or", "from", "another", "class", "." ]
train
https://github.com/googleapis/google-http-java-client/blob/0988ae4e0f26a80f579b6adb2b276dd8254928de/google-http-client/src/main/java/com/google/api/client/util/Types.java#L97-L100
couchbase/java-dcp-client
src/main/java/com/couchbase/client/dcp/transport/netty/DcpControlHandler.java
DcpControlHandler.channelRead0
@Override protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception { ResponseStatus status = MessageUtil.getResponseStatus(msg); if (status.isSuccess()) { negotiate(ctx); } else { originalPromise().setFailure(new IllegalStateException("Could not configure DCP Controls: " + status)); } }
java
@Override protected void channelRead0(final ChannelHandlerContext ctx, final ByteBuf msg) throws Exception { ResponseStatus status = MessageUtil.getResponseStatus(msg); if (status.isSuccess()) { negotiate(ctx); } else { originalPromise().setFailure(new IllegalStateException("Could not configure DCP Controls: " + status)); } }
[ "@", "Override", "protected", "void", "channelRead0", "(", "final", "ChannelHandlerContext", "ctx", ",", "final", "ByteBuf", "msg", ")", "throws", "Exception", "{", "ResponseStatus", "status", "=", "MessageUtil", ".", "getResponseStatus", "(", "msg", ")", ";", "...
Since only one feature per req/res can be negotiated, repeat the process once a response comes back until the iterator is complete or a non-success response status is received.
[ "Since", "only", "one", "feature", "per", "req", "/", "res", "can", "be", "negotiated", "repeat", "the", "process", "once", "a", "response", "comes", "back", "until", "the", "iterator", "is", "complete", "or", "a", "non", "-", "success", "response", "statu...
train
https://github.com/couchbase/java-dcp-client/blob/75359d8c081d6c575f8087cf7c28d24ab24c6421/src/main/java/com/couchbase/client/dcp/transport/netty/DcpControlHandler.java#L103-L111
exoplatform/jcr
exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/IndexingConfigurationImpl.java
IndexingConfigurationImpl.isIncludedInNodeScopeIndex
public boolean isIncludedInNodeScopeIndex(NodeData state, InternalQName propertyName) { IndexingRule rule = getApplicableIndexingRule(state); if (rule != null) { return rule.isIncludedInNodeScopeIndex(propertyName); } // none of the config elements matched -> default is to include return true; }
java
public boolean isIncludedInNodeScopeIndex(NodeData state, InternalQName propertyName) { IndexingRule rule = getApplicableIndexingRule(state); if (rule != null) { return rule.isIncludedInNodeScopeIndex(propertyName); } // none of the config elements matched -> default is to include return true; }
[ "public", "boolean", "isIncludedInNodeScopeIndex", "(", "NodeData", "state", ",", "InternalQName", "propertyName", ")", "{", "IndexingRule", "rule", "=", "getApplicableIndexingRule", "(", "state", ")", ";", "if", "(", "rule", "!=", "null", ")", "{", "return", "r...
Returns <code>true</code> if the property with the given name should be included in the node scope fulltext index. If there is not configuration entry for that propery <code>false</code> is returned. @param state the node state. @param propertyName the name of a property. @return <code>true</code> if the property should be included in the node scope fulltext index.
[ "Returns", "<code", ">", "true<", "/", "code", ">", "if", "the", "property", "with", "the", "given", "name", "should", "be", "included", "in", "the", "node", "scope", "fulltext", "index", ".", "If", "there", "is", "not", "configuration", "entry", "for", ...
train
https://github.com/exoplatform/jcr/blob/3e7f9ee1b5683640d73a4316fb4b0ad5eac5b8a2/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/query/lucene/IndexingConfigurationImpl.java#L310-L319
OpenLiberty/open-liberty
dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java
JSONConverter.writeJMX
public void writeJMX(OutputStream out, JMXServerInfo value) throws IOException { writeStartObject(out); writeIntField(out, OM_VERSION, value.version); writeStringField(out, OM_MBEANS, value.mbeansURL); writeStringField(out, OM_CREATEMBEAN, value.createMBeanURL); writeStringField(out, OM_MBEANCOUNT, value.mbeanCountURL); writeStringField(out, OM_DEFAULTDOMAIN, value.defaultDomainURL); writeStringField(out, OM_DOMAINS, value.domainsURL); writeStringField(out, OM_NOTIFICATIONS, value.notificationsURL); writeStringField(out, OM_INSTANCEOF, value.instanceOfURL); writeStringField(out, OM_FILE_TRANSFER, value.fileTransferURL); writeStringField(out, OM_API, value.apiURL); writeStringField(out, OM_GRAPH, value.graphURL); writeEndObject(out); }
java
public void writeJMX(OutputStream out, JMXServerInfo value) throws IOException { writeStartObject(out); writeIntField(out, OM_VERSION, value.version); writeStringField(out, OM_MBEANS, value.mbeansURL); writeStringField(out, OM_CREATEMBEAN, value.createMBeanURL); writeStringField(out, OM_MBEANCOUNT, value.mbeanCountURL); writeStringField(out, OM_DEFAULTDOMAIN, value.defaultDomainURL); writeStringField(out, OM_DOMAINS, value.domainsURL); writeStringField(out, OM_NOTIFICATIONS, value.notificationsURL); writeStringField(out, OM_INSTANCEOF, value.instanceOfURL); writeStringField(out, OM_FILE_TRANSFER, value.fileTransferURL); writeStringField(out, OM_API, value.apiURL); writeStringField(out, OM_GRAPH, value.graphURL); writeEndObject(out); }
[ "public", "void", "writeJMX", "(", "OutputStream", "out", ",", "JMXServerInfo", "value", ")", "throws", "IOException", "{", "writeStartObject", "(", "out", ")", ";", "writeIntField", "(", "out", ",", "OM_VERSION", ",", "value", ".", "version", ")", ";", "wri...
Encode a JMX instance as JSON: { "version" : Integer, "mbeans" : URL, "createMBean" : URL, "mbeanCount" : URL, "defaultDomain" : URL, "domains" : URL, "notifications" : URL, "instanceOf" : URL } @param out The stream to write JSON to @param value The JMX instance to encode. Can't be null. @throws IOException If an I/O error occurs @see #readJMX(InputStream)
[ "Encode", "a", "JMX", "instance", "as", "JSON", ":", "{", "version", ":", "Integer", "mbeans", ":", "URL", "createMBean", ":", "URL", "mbeanCount", ":", "URL", "defaultDomain", ":", "URL", "domains", ":", "URL", "notifications", ":", "URL", "instanceOf", "...
train
https://github.com/OpenLiberty/open-liberty/blob/ca725d9903e63645018f9fa8cbda25f60af83a5d/dev/com.ibm.ws.jmx.connector.client.rest/src/com/ibm/ws/jmx/connector/converter/JSONConverter.java#L963-L977
apache/incubator-druid
processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/LimitedTemporaryStorage.java
LimitedTemporaryStorage.createFile
public LimitedOutputStream createFile() throws IOException { if (bytesUsed.get() >= maxBytesUsed) { throw new TemporaryStorageFullException(maxBytesUsed); } synchronized (files) { if (closed) { throw new ISE("Closed"); } FileUtils.forceMkdir(storageDirectory); if (!createdStorageDirectory) { createdStorageDirectory = true; } final File theFile = new File(storageDirectory, StringUtils.format("%08d.tmp", files.size())); final EnumSet<StandardOpenOption> openOptions = EnumSet.of( StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE ); final FileChannel channel = FileChannel.open(theFile.toPath(), openOptions); files.add(theFile); return new LimitedOutputStream(theFile, Channels.newOutputStream(channel)); } }
java
public LimitedOutputStream createFile() throws IOException { if (bytesUsed.get() >= maxBytesUsed) { throw new TemporaryStorageFullException(maxBytesUsed); } synchronized (files) { if (closed) { throw new ISE("Closed"); } FileUtils.forceMkdir(storageDirectory); if (!createdStorageDirectory) { createdStorageDirectory = true; } final File theFile = new File(storageDirectory, StringUtils.format("%08d.tmp", files.size())); final EnumSet<StandardOpenOption> openOptions = EnumSet.of( StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE ); final FileChannel channel = FileChannel.open(theFile.toPath(), openOptions); files.add(theFile); return new LimitedOutputStream(theFile, Channels.newOutputStream(channel)); } }
[ "public", "LimitedOutputStream", "createFile", "(", ")", "throws", "IOException", "{", "if", "(", "bytesUsed", ".", "get", "(", ")", ">=", "maxBytesUsed", ")", "{", "throw", "new", "TemporaryStorageFullException", "(", "maxBytesUsed", ")", ";", "}", "synchronize...
Create a new temporary file. All methods of the returned output stream may throw {@link TemporaryStorageFullException} if the temporary storage area fills up. @return output stream to the file @throws TemporaryStorageFullException if the temporary storage area is full @throws IOException if something goes wrong while creating the file
[ "Create", "a", "new", "temporary", "file", ".", "All", "methods", "of", "the", "returned", "output", "stream", "may", "throw", "{", "@link", "TemporaryStorageFullException", "}", "if", "the", "temporary", "storage", "area", "fills", "up", "." ]
train
https://github.com/apache/incubator-druid/blob/f776b9408962b9006cfcfe4d6c1794751972cc8e/processing/src/main/java/org/apache/druid/query/groupby/epinephelinae/LimitedTemporaryStorage.java#L74-L100
http-builder-ng/http-builder-ng
http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java
HttpBuilder.getAsync
public <T> CompletableFuture<T> getAsync(final Class<T> type, @DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> get(type, closure), getExecutor()); }
java
public <T> CompletableFuture<T> getAsync(final Class<T> type, @DelegatesTo(HttpConfig.class) final Closure closure) { return CompletableFuture.supplyAsync(() -> get(type, closure), getExecutor()); }
[ "public", "<", "T", ">", "CompletableFuture", "<", "T", ">", "getAsync", "(", "final", "Class", "<", "T", ">", "type", ",", "@", "DelegatesTo", "(", "HttpConfig", ".", "class", ")", "final", "Closure", "closure", ")", "{", "return", "CompletableFuture", ...
Executes asynchronous GET request on the configured URI (alias for the `get(Class, Closure)` method), with additional configuration provided by the configuration closure. The result will be cast to the specified `type`. [source,groovy] ---- def http = HttpBuilder.configure { request.uri = 'http://localhost:10101' } CompletableFuture future = http.getAsync(String){ request.uri.path = '/something' } String result = future.get() ---- The configuration `closure` allows additional configuration for this request based on the {@link HttpConfig} interface. @param type the type of the response content @param closure the additional configuration closure (delegated to {@link HttpConfig}) @return the {@link CompletableFuture} for the resulting content cast to the specified type
[ "Executes", "asynchronous", "GET", "request", "on", "the", "configured", "URI", "(", "alias", "for", "the", "get", "(", "Class", "Closure", ")", "method", ")", "with", "additional", "configuration", "provided", "by", "the", "configuration", "closure", ".", "Th...
train
https://github.com/http-builder-ng/http-builder-ng/blob/865f37732c102c748d3db8b905199dac9222a525/http-builder-ng-core/src/main/java/groovyx/net/http/HttpBuilder.java#L465-L467
facebookarchive/hadoop-20
src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataBlockScannerSet.java
DataBlockScannerSet.verifiedByClient
synchronized void verifiedByClient(int namespaceId, Block block) { DataBlockScanner nsScanner = getNSScanner(namespaceId); if (nsScanner != null) { nsScanner.updateScanStatusUpdateOnly(block, DataBlockScanner.ScanType.REMOTE_READ, true); } else { LOG.warn("No namespace scanner found for namespaceId: " + nsScanner); } }
java
synchronized void verifiedByClient(int namespaceId, Block block) { DataBlockScanner nsScanner = getNSScanner(namespaceId); if (nsScanner != null) { nsScanner.updateScanStatusUpdateOnly(block, DataBlockScanner.ScanType.REMOTE_READ, true); } else { LOG.warn("No namespace scanner found for namespaceId: " + nsScanner); } }
[ "synchronized", "void", "verifiedByClient", "(", "int", "namespaceId", ",", "Block", "block", ")", "{", "DataBlockScanner", "nsScanner", "=", "getNSScanner", "(", "namespaceId", ")", ";", "if", "(", "nsScanner", "!=", "null", ")", "{", "nsScanner", ".", "updat...
/* A reader will try to indicate a block is verified and will add blocks to the DataBlockScannerSet before they are finished (due to concurrent readers). fixed so a read verification can't add the block
[ "/", "*", "A", "reader", "will", "try", "to", "indicate", "a", "block", "is", "verified", "and", "will", "add", "blocks", "to", "the", "DataBlockScannerSet", "before", "they", "are", "finished", "(", "due", "to", "concurrent", "readers", ")", "." ]
train
https://github.com/facebookarchive/hadoop-20/blob/2a29bc6ecf30edb1ad8dbde32aa49a317b4d44f4/src/hdfs/org/apache/hadoop/hdfs/server/datanode/DataBlockScannerSet.java#L371-L379
livetribe/livetribe-slp
core/src/main/java/org/livetribe/slp/spi/msg/BytesBlock.java
BytesBlock.readInt
protected static int readInt(byte[] bytes, int offset, int length) { int result = 0; for (int i = 0; i < length; ++i) { result <<= 8; result += bytes[offset + i] & 0xFF; } return result; }
java
protected static int readInt(byte[] bytes, int offset, int length) { int result = 0; for (int i = 0; i < length; ++i) { result <<= 8; result += bytes[offset + i] & 0xFF; } return result; }
[ "protected", "static", "int", "readInt", "(", "byte", "[", "]", "bytes", ",", "int", "offset", ",", "int", "length", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ")", "{", ...
Reads an integer from <code>bytes</code> in network byte order. @param bytes The bytes from where the integer value is read @param offset The offset in <code>bytes</code> from where to start reading the integer @param length The number of bytes to read @return The integer value read
[ "Reads", "an", "integer", "from", "<code", ">", "bytes<", "/", "code", ">", "in", "network", "byte", "order", "." ]
train
https://github.com/livetribe/livetribe-slp/blob/6cc13dbe81feab133fe3dd291ca081cbc6e1f591/core/src/main/java/org/livetribe/slp/spi/msg/BytesBlock.java#L61-L70
zaproxy/zaproxy
src/org/zaproxy/zap/control/AddOn.java
AddOn.calculateExtensionRunRequirements
public AddOnRunRequirements calculateExtensionRunRequirements(String classname, Collection<AddOn> availableAddOns) { AddOnRunRequirements requirements = new AddOnRunRequirements(this); for (ExtensionWithDeps extensionWithDeps : extensionsWithDeps) { if (extensionWithDeps.getClassname().equals(classname)) { calculateExtensionRunRequirements(extensionWithDeps, availableAddOns, requirements, this); break; } } return requirements; }
java
public AddOnRunRequirements calculateExtensionRunRequirements(String classname, Collection<AddOn> availableAddOns) { AddOnRunRequirements requirements = new AddOnRunRequirements(this); for (ExtensionWithDeps extensionWithDeps : extensionsWithDeps) { if (extensionWithDeps.getClassname().equals(classname)) { calculateExtensionRunRequirements(extensionWithDeps, availableAddOns, requirements, this); break; } } return requirements; }
[ "public", "AddOnRunRequirements", "calculateExtensionRunRequirements", "(", "String", "classname", ",", "Collection", "<", "AddOn", ">", "availableAddOns", ")", "{", "AddOnRunRequirements", "requirements", "=", "new", "AddOnRunRequirements", "(", "this", ")", ";", "for"...
Calculates the requirements to run the extension with the given {@code classname}, in the current ZAP and Java versions and with the given {@code availableAddOns}. <p> If the extension depends on other add-ons, those add-ons are checked if are also runnable. <p> <strong>Note:</strong> All the given {@code availableAddOns} are expected to be loadable in the currently running ZAP version, that is, the method {@code AddOn.canLoadInCurrentVersion()}, returns {@code true}. @param classname the classname of extension that will be checked @param availableAddOns the add-ons available @return the requirements to run the extension, and if not runnable the reason why it's not. @since 2.4.0 @see AddOnRunRequirements#getExtensionRequirements()
[ "Calculates", "the", "requirements", "to", "run", "the", "extension", "with", "the", "given", "{", "@code", "classname", "}", "in", "the", "current", "ZAP", "and", "Java", "versions", "and", "with", "the", "given", "{", "@code", "availableAddOns", "}", ".", ...
train
https://github.com/zaproxy/zaproxy/blob/0cbe5121f2ae1ecca222513d182759210c569bec/src/org/zaproxy/zap/control/AddOn.java#L1372-L1381
Stratio/deep-spark
deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java
Cells.getLong
public Long getLong(String nameSpace, String cellName) { return getValue(nameSpace, cellName, Long.class); }
java
public Long getLong(String nameSpace, String cellName) { return getValue(nameSpace, cellName, Long.class); }
[ "public", "Long", "getLong", "(", "String", "nameSpace", ",", "String", "cellName", ")", "{", "return", "getValue", "(", "nameSpace", ",", "cellName", ",", "Long", ".", "class", ")", ";", "}" ]
Returns the {@code Long} value of the {@link Cell} (associated to {@code table}) whose name iscellName, or null if this Cells object contains no cell whose name is cellName. @param nameSpace the name of the owning table @param cellName the name of the Cell we want to retrieve from this Cells object. @return the {@code Long} value of the {@link Cell} (associated to {@code table}) whose name is cellName, or null if this Cells object contains no cell whose name is cellName
[ "Returns", "the", "{", "@code", "Long", "}", "value", "of", "the", "{", "@link", "Cell", "}", "(", "associated", "to", "{", "@code", "table", "}", ")", "whose", "name", "iscellName", "or", "null", "if", "this", "Cells", "object", "contains", "no", "cel...
train
https://github.com/Stratio/deep-spark/blob/b9621c9b7a6d996f80fce1d073d696a157bed095/deep-commons/src/main/java/com/stratio/deep/commons/entity/Cells.java#L1123-L1125
CenturyLinkCloud/mdw
mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java
SoapServlet.createSoapFaultResponse
protected String createSoapFaultResponse(String message) throws SOAPException, TransformerException { return createSoapFaultResponse(SOAPConstants.SOAP_1_1_PROTOCOL, null, message); }
java
protected String createSoapFaultResponse(String message) throws SOAPException, TransformerException { return createSoapFaultResponse(SOAPConstants.SOAP_1_1_PROTOCOL, null, message); }
[ "protected", "String", "createSoapFaultResponse", "(", "String", "message", ")", "throws", "SOAPException", ",", "TransformerException", "{", "return", "createSoapFaultResponse", "(", "SOAPConstants", ".", "SOAP_1_1_PROTOCOL", ",", "null", ",", "message", ")", ";", "}...
Original API (Defaults to using MessageFactory.newInstance(), i.e. SOAP 1.1) @param message @return Soap fault as string @throws SOAPException @throws TransformerException
[ "Original", "API", "(", "Defaults", "to", "using", "MessageFactory", ".", "newInstance", "()", "i", ".", "e", ".", "SOAP", "1", ".", "1", ")" ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-hub/src/com/centurylink/mdw/hub/servlet/SoapServlet.java#L376-L379
PistoiaHELM/HELM2NotationToolkit
src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java
HELM2NotationUtils.section2
private static void section2(List<ConnectionNotation> connections, Map<String, String> mapIds) throws NotationException { for (ConnectionNotation connection : connections) { HELMEntity first = connection.getSourceId(); String idFirst = first.getId(); HELMEntity second = connection.getTargetId(); String idSecond = second.getId(); if (mapIds.containsKey(idFirst)) { first = new ConnectionNotation(mapIds.get(idFirst)).getSourceId(); } if (mapIds.containsKey(idSecond)) { second = new ConnectionNotation(mapIds.get(idSecond)).getSourceId(); } ConnectionNotation newConnection = new ConnectionNotation(first, second, connection.getSourceUnit(), connection.getrGroupSource(), connection.getTargetUnit(), connection.getrGroupTarget(), connection.getAnnotation()); helm2notation.addConnection(newConnection); } }
java
private static void section2(List<ConnectionNotation> connections, Map<String, String> mapIds) throws NotationException { for (ConnectionNotation connection : connections) { HELMEntity first = connection.getSourceId(); String idFirst = first.getId(); HELMEntity second = connection.getTargetId(); String idSecond = second.getId(); if (mapIds.containsKey(idFirst)) { first = new ConnectionNotation(mapIds.get(idFirst)).getSourceId(); } if (mapIds.containsKey(idSecond)) { second = new ConnectionNotation(mapIds.get(idSecond)).getSourceId(); } ConnectionNotation newConnection = new ConnectionNotation(first, second, connection.getSourceUnit(), connection.getrGroupSource(), connection.getTargetUnit(), connection.getrGroupTarget(), connection.getAnnotation()); helm2notation.addConnection(newConnection); } }
[ "private", "static", "void", "section2", "(", "List", "<", "ConnectionNotation", ">", "connections", ",", "Map", "<", "String", ",", "String", ">", "mapIds", ")", "throws", "NotationException", "{", "for", "(", "ConnectionNotation", "connection", ":", "connectio...
method to add ConnectionNotation to the existent @param connections ConnectionNotatoin @param mapIds Map of old and new Ids @throws NotationException if notation is not valid
[ "method", "to", "add", "ConnectionNotation", "to", "the", "existent" ]
train
https://github.com/PistoiaHELM/HELM2NotationToolkit/blob/ac5bb01fd5b4082134a8ef226bbe2ff0f60fcd38/src/main/java/org/helm/notation2/tools/HELM2NotationUtils.java#L273-L296
codelibs/fess
src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java
FessMessages.addConstraintsDigitsMessage
public FessMessages addConstraintsDigitsMessage(String property, String fraction, String integer) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Digits_MESSAGE, fraction, integer)); return this; }
java
public FessMessages addConstraintsDigitsMessage(String property, String fraction, String integer) { assertPropertyNotNull(property); add(property, new UserMessage(CONSTRAINTS_Digits_MESSAGE, fraction, integer)); return this; }
[ "public", "FessMessages", "addConstraintsDigitsMessage", "(", "String", "property", ",", "String", "fraction", ",", "String", "integer", ")", "{", "assertPropertyNotNull", "(", "property", ")", ";", "add", "(", "property", ",", "new", "UserMessage", "(", "CONSTRAI...
Add the created action message for the key 'constraints.Digits.message' with parameters. <pre> message: {item} is numeric value out of bounds (&lt;{integer} digits&gt;.&lt;{fraction} digits&gt; expected). </pre> @param property The property name for the message. (NotNull) @param fraction The parameter fraction for message. (NotNull) @param integer The parameter integer for message. (NotNull) @return this. (NotNull)
[ "Add", "the", "created", "action", "message", "for", "the", "key", "constraints", ".", "Digits", ".", "message", "with", "parameters", ".", "<pre", ">", "message", ":", "{", "item", "}", "is", "numeric", "value", "out", "of", "bounds", "(", "&lt", ";", ...
train
https://github.com/codelibs/fess/blob/e5e4b722549d32a4958dfd94965b21937bfe64cf/src/main/java/org/codelibs/fess/mylasta/action/FessMessages.java#L667-L671
jboss/jboss-jsp-api_spec
src/main/java/javax/servlet/jsp/tagext/TagSupport.java
TagSupport.findAncestorWithClass
public static final Tag findAncestorWithClass(Tag from, Class klass) { boolean isInterface = false; if (from == null || klass == null || (!Tag.class.isAssignableFrom(klass) && !(isInterface = klass.isInterface()))) { return null; } for (;;) { Tag tag = from.getParent(); if (tag == null) { return null; } if ((isInterface && klass.isInstance(tag)) || klass.isAssignableFrom(tag.getClass())) return tag; else from = tag; } }
java
public static final Tag findAncestorWithClass(Tag from, Class klass) { boolean isInterface = false; if (from == null || klass == null || (!Tag.class.isAssignableFrom(klass) && !(isInterface = klass.isInterface()))) { return null; } for (;;) { Tag tag = from.getParent(); if (tag == null) { return null; } if ((isInterface && klass.isInstance(tag)) || klass.isAssignableFrom(tag.getClass())) return tag; else from = tag; } }
[ "public", "static", "final", "Tag", "findAncestorWithClass", "(", "Tag", "from", ",", "Class", "klass", ")", "{", "boolean", "isInterface", "=", "false", ";", "if", "(", "from", "==", "null", "||", "klass", "==", "null", "||", "(", "!", "Tag", ".", "cl...
Find the instance of a given class type that is closest to a given instance. This method uses the getParent method from the Tag interface. This method is used for coordination among cooperating tags. <p> The current version of the specification only provides one formal way of indicating the observable type of a tag handler: its tag handler implementation class, described in the tag-class subelement of the tag element. This is extended in an informal manner by allowing the tag library author to indicate in the description subelement an observable type. The type should be a subtype of the tag handler implementation class or void. This addititional constraint can be exploited by a specialized container that knows about that specific tag library, as in the case of the JSP standard tag library. <p> When a tag library author provides information on the observable type of a tag handler, client programmatic code should adhere to that constraint. Specifically, the Class passed to findAncestorWithClass should be a subtype of the observable type. @param from The instance from where to start looking. @param klass The subclass of Tag or interface to be matched @return the nearest ancestor that implements the interface or is an instance of the class specified
[ "Find", "the", "instance", "of", "a", "given", "class", "type", "that", "is", "closest", "to", "a", "given", "instance", ".", "This", "method", "uses", "the", "getParent", "method", "from", "the", "Tag", "interface", ".", "This", "method", "is", "used", ...
train
https://github.com/jboss/jboss-jsp-api_spec/blob/da53166619f33a5134dc3315a3264990cc1f541f/src/main/java/javax/servlet/jsp/tagext/TagSupport.java#L113-L136
apereo/cas
support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/web/response/callback/OAuth20AuthorizationCodeAuthorizationResponseBuilder.java
OAuth20AuthorizationCodeAuthorizationResponseBuilder.buildCallbackViewViaRedirectUri
protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId, final Authentication authentication, final OAuthCode code) { val attributes = authentication.getAttributes(); val state = attributes.get(OAuth20Constants.STATE).get(0).toString(); val nonce = attributes.get(OAuth20Constants.NONCE).get(0).toString(); val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI); LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri); var callbackUrl = redirectUri; callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId()); if (StringUtils.isNotBlank(state)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state); } if (StringUtils.isNotBlank(nonce)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce); } LOGGER.debug("Redirecting to URL [{}]", callbackUrl); val params = new LinkedHashMap<String, String>(); params.put(OAuth20Constants.CODE, code.getId()); params.put(OAuth20Constants.STATE, state); params.put(OAuth20Constants.NONCE, nonce); params.put(OAuth20Constants.CLIENT_ID, clientId); return buildResponseModelAndView(context, servicesManager, clientId, callbackUrl, params); }
java
protected ModelAndView buildCallbackViewViaRedirectUri(final J2EContext context, final String clientId, final Authentication authentication, final OAuthCode code) { val attributes = authentication.getAttributes(); val state = attributes.get(OAuth20Constants.STATE).get(0).toString(); val nonce = attributes.get(OAuth20Constants.NONCE).get(0).toString(); val redirectUri = context.getRequestParameter(OAuth20Constants.REDIRECT_URI); LOGGER.debug("Authorize request verification successful for client [{}] with redirect uri [{}]", clientId, redirectUri); var callbackUrl = redirectUri; callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.CODE, code.getId()); if (StringUtils.isNotBlank(state)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.STATE, state); } if (StringUtils.isNotBlank(nonce)) { callbackUrl = CommonHelper.addParameter(callbackUrl, OAuth20Constants.NONCE, nonce); } LOGGER.debug("Redirecting to URL [{}]", callbackUrl); val params = new LinkedHashMap<String, String>(); params.put(OAuth20Constants.CODE, code.getId()); params.put(OAuth20Constants.STATE, state); params.put(OAuth20Constants.NONCE, nonce); params.put(OAuth20Constants.CLIENT_ID, clientId); return buildResponseModelAndView(context, servicesManager, clientId, callbackUrl, params); }
[ "protected", "ModelAndView", "buildCallbackViewViaRedirectUri", "(", "final", "J2EContext", "context", ",", "final", "String", "clientId", ",", "final", "Authentication", "authentication", ",", "final", "OAuthCode", "code", ")", "{", "val", "attributes", "=", "authent...
Build callback view via redirect uri model and view. @param context the context @param clientId the client id @param authentication the authentication @param code the code @return the model and view
[ "Build", "callback", "view", "via", "redirect", "uri", "model", "and", "view", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/support/cas-server-support-oauth-core-api/src/main/java/org/apereo/cas/support/oauth/web/response/callback/OAuth20AuthorizationCodeAuthorizationResponseBuilder.java#L68-L92
kiegroup/droolsjbpm-integration
kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java
KieServicesFactory.newJMSConfiguration
public static KieServicesConfiguration newJMSConfiguration( InitialContext context, String username, String password ) { return new KieServicesConfigurationImpl( context, username, password ); }
java
public static KieServicesConfiguration newJMSConfiguration( InitialContext context, String username, String password ) { return new KieServicesConfigurationImpl( context, username, password ); }
[ "public", "static", "KieServicesConfiguration", "newJMSConfiguration", "(", "InitialContext", "context", ",", "String", "username", ",", "String", "password", ")", "{", "return", "new", "KieServicesConfigurationImpl", "(", "context", ",", "username", ",", "password", ...
Creates a new configuration object for JMS based service @param context a context to look up for the JMS request and response queues @param username user name @param password user password @return configuration instance
[ "Creates", "a", "new", "configuration", "object", "for", "JMS", "based", "service" ]
train
https://github.com/kiegroup/droolsjbpm-integration/blob/6c26200ab03855dbb92b56ca0c6363cdec0eaf2c/kie-server-parent/kie-server-remote/kie-server-client/src/main/java/org/kie/server/client/KieServicesFactory.java#L91-L93
b3dgs/lionengine
lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java
PathfindableModel.checkObjectId
private boolean checkObjectId(int dtx, int dty) { final int tw = transformable.getWidth() / map.getTileWidth(); final int th = transformable.getHeight() / map.getTileHeight(); for (int tx = dtx; tx < dtx + tw; tx++) { for (int ty = dty; ty < dty + th; ty++) { final Collection<Integer> ids = mapPath.getObjectsId(tx, ty); if (!ids.isEmpty() && !ids.contains(id)) { return false; } } } return mapPath.isAreaAvailable(this, dtx, dty, tw, th, id); }
java
private boolean checkObjectId(int dtx, int dty) { final int tw = transformable.getWidth() / map.getTileWidth(); final int th = transformable.getHeight() / map.getTileHeight(); for (int tx = dtx; tx < dtx + tw; tx++) { for (int ty = dty; ty < dty + th; ty++) { final Collection<Integer> ids = mapPath.getObjectsId(tx, ty); if (!ids.isEmpty() && !ids.contains(id)) { return false; } } } return mapPath.isAreaAvailable(this, dtx, dty, tw, th, id); }
[ "private", "boolean", "checkObjectId", "(", "int", "dtx", ",", "int", "dty", ")", "{", "final", "int", "tw", "=", "transformable", ".", "getWidth", "(", ")", "/", "map", ".", "getTileWidth", "(", ")", ";", "final", "int", "th", "=", "transformable", "....
Check if the object id location is available for the pathfindable. @param dtx The tile horizontal destination. @param dty The tile vertical destination. @return <code>true</code> if available, <code>false</code> else.
[ "Check", "if", "the", "object", "id", "location", "is", "available", "for", "the", "pathfindable", "." ]
train
https://github.com/b3dgs/lionengine/blob/cac3d5578532cf11724a737b9f09e71bf9995ab2/lionengine-game/src/main/java/com/b3dgs/lionengine/game/feature/tile/map/pathfinding/PathfindableModel.java#L434-L450
lettuce-io/lettuce-core
src/main/java/io/lettuce/core/masterslave/AsyncConnections.java
AsyncConnections.addConnection
public void addConnection(RedisURI redisURI, CompletableFuture<StatefulRedisConnection<String, String>> connection) { connections.put(redisURI, connection); }
java
public void addConnection(RedisURI redisURI, CompletableFuture<StatefulRedisConnection<String, String>> connection) { connections.put(redisURI, connection); }
[ "public", "void", "addConnection", "(", "RedisURI", "redisURI", ",", "CompletableFuture", "<", "StatefulRedisConnection", "<", "String", ",", "String", ">", ">", "connection", ")", "{", "connections", ".", "put", "(", "redisURI", ",", "connection", ")", ";", "...
Add a connection for a {@link RedisURI} @param redisURI @param connection
[ "Add", "a", "connection", "for", "a", "{", "@link", "RedisURI", "}" ]
train
https://github.com/lettuce-io/lettuce-core/blob/b6de74e384dea112e3656684ca3f50cdfd6c8e0d/src/main/java/io/lettuce/core/masterslave/AsyncConnections.java#L50-L52
looly/hutool
hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java
StrSpliter.split
public static List<String> split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty){ return split(str, separator, limit, isTrim, ignoreEmpty, false); }
java
public static List<String> split(String str, char separator, int limit, boolean isTrim, boolean ignoreEmpty){ return split(str, separator, limit, isTrim, ignoreEmpty, false); }
[ "public", "static", "List", "<", "String", ">", "split", "(", "String", "str", ",", "char", "separator", ",", "int", "limit", ",", "boolean", "isTrim", ",", "boolean", "ignoreEmpty", ")", "{", "return", "split", "(", "str", ",", "separator", ",", "limit"...
切分字符串,大小写敏感 @param str 被切分的字符串 @param separator 分隔符字符 @param limit 限制分片数,-1不限制 @param isTrim 是否去除切分字符串后每个元素两边的空格 @param ignoreEmpty 是否忽略空串 @return 切分后的集合 @since 3.0.8
[ "切分字符串,大小写敏感" ]
train
https://github.com/looly/hutool/blob/bbd74eda4c7e8a81fe7a991fa6c2276eec062e6a/hutool-core/src/main/java/cn/hutool/core/text/StrSpliter.java#L119-L121
protostuff/protostuff-compiler
protostuff-generator/src/main/java/io/protostuff/generator/html/uml/PlantUmlVerbatimSerializer.java
PlantUmlVerbatimSerializer.addToMap
public static void addToMap(final Map<String, VerbatimSerializer> serializerMap) { PlantUmlVerbatimSerializer serializer = new PlantUmlVerbatimSerializer(); for (Type type : Type.values()) { String name = type.getName(); serializerMap.put(name, serializer); } }
java
public static void addToMap(final Map<String, VerbatimSerializer> serializerMap) { PlantUmlVerbatimSerializer serializer = new PlantUmlVerbatimSerializer(); for (Type type : Type.values()) { String name = type.getName(); serializerMap.put(name, serializer); } }
[ "public", "static", "void", "addToMap", "(", "final", "Map", "<", "String", ",", "VerbatimSerializer", ">", "serializerMap", ")", "{", "PlantUmlVerbatimSerializer", "serializer", "=", "new", "PlantUmlVerbatimSerializer", "(", ")", ";", "for", "(", "Type", "type", ...
Register an instance of {@link PlantUmlVerbatimSerializer} in the given serializer's map.
[ "Register", "an", "instance", "of", "{" ]
train
https://github.com/protostuff/protostuff-compiler/blob/665256c42cb41da849e8321ffcab088350ace171/protostuff-generator/src/main/java/io/protostuff/generator/html/uml/PlantUmlVerbatimSerializer.java#L27-L33
fuinorg/srcgen4j-commons
src/main/java/org/fuin/srcgen4j/commons/JaxbHelper.java
JaxbHelper.containsStartTag
public boolean containsStartTag(@NotNull @FileExists @IsFile final File file, @NotNull final String tagName) { Contract.requireArgNotNull("file", file); FileExistsValidator.requireArgValid("file", file); IsFileValidator.requireArgValid("file", file); Contract.requireArgNotNull("tagName", tagName); final String xml = readFirstPartOfFile(file); return xml.indexOf("<" + tagName) > -1; }
java
public boolean containsStartTag(@NotNull @FileExists @IsFile final File file, @NotNull final String tagName) { Contract.requireArgNotNull("file", file); FileExistsValidator.requireArgValid("file", file); IsFileValidator.requireArgValid("file", file); Contract.requireArgNotNull("tagName", tagName); final String xml = readFirstPartOfFile(file); return xml.indexOf("<" + tagName) > -1; }
[ "public", "boolean", "containsStartTag", "(", "@", "NotNull", "@", "FileExists", "@", "IsFile", "final", "File", "file", ",", "@", "NotNull", "final", "String", "tagName", ")", "{", "Contract", ".", "requireArgNotNull", "(", "\"file\"", ",", "file", ")", ";"...
Checks if the given file contains a start tag within the first 1024 bytes. @param file File to check. @param tagName Name of the tag. A "&lt;" will be added to this name internally to locate the start tag. @return If the file contains the start tag TRUE else FALSE.
[ "Checks", "if", "the", "given", "file", "contains", "a", "start", "tag", "within", "the", "first", "1024", "bytes", "." ]
train
https://github.com/fuinorg/srcgen4j-commons/blob/bce26fd3167ea91fb2f3ad3fc9a1836d3d9fb14b/src/main/java/org/fuin/srcgen4j/commons/JaxbHelper.java#L76-L84
biojava/biojava
biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java
SymmetryAxes.getRepeatsCyclicForm
public List<List<Integer>> getRepeatsCyclicForm(int level, int firstRepeat) { Axis axis = axes.get(level); int m = getNumRepeats(level+1);//size of the children int d = axis.getOrder(); // degree of this node int n = m*d; // number of repeats included if(firstRepeat % n != 0) { throw new IllegalArgumentException(String.format("Repeat %d cannot start a block at level %s of this tree",firstRepeat,level)); } if(axis.getSymmType() == SymmetryType.OPEN) { n -= m; // leave off last child for open symm } List<List<Integer>> repeats = new ArrayList<>(m); for(int i=0;i<m;i++) { List<Integer> cycle = new ArrayList<>(d); for(int j=0;j<d;j++) { cycle.add(firstRepeat+i+j*m); } repeats.add(cycle); } return repeats; }
java
public List<List<Integer>> getRepeatsCyclicForm(int level, int firstRepeat) { Axis axis = axes.get(level); int m = getNumRepeats(level+1);//size of the children int d = axis.getOrder(); // degree of this node int n = m*d; // number of repeats included if(firstRepeat % n != 0) { throw new IllegalArgumentException(String.format("Repeat %d cannot start a block at level %s of this tree",firstRepeat,level)); } if(axis.getSymmType() == SymmetryType.OPEN) { n -= m; // leave off last child for open symm } List<List<Integer>> repeats = new ArrayList<>(m); for(int i=0;i<m;i++) { List<Integer> cycle = new ArrayList<>(d); for(int j=0;j<d;j++) { cycle.add(firstRepeat+i+j*m); } repeats.add(cycle); } return repeats; }
[ "public", "List", "<", "List", "<", "Integer", ">", ">", "getRepeatsCyclicForm", "(", "int", "level", ",", "int", "firstRepeat", ")", "{", "Axis", "axis", "=", "axes", ".", "get", "(", "level", ")", ";", "int", "m", "=", "getNumRepeats", "(", "level", ...
Get the indices of participating repeats in cyclic form. <p> Each inner list gives a set of equivalent repeats and should have length equal to the order of the axis' operator. @param level @param firstRepeat @return
[ "Get", "the", "indices", "of", "participating", "repeats", "in", "cyclic", "form", ".", "<p", ">", "Each", "inner", "list", "gives", "a", "set", "of", "equivalent", "repeats", "and", "should", "have", "length", "equal", "to", "the", "order", "of", "the", ...
train
https://github.com/biojava/biojava/blob/a1c71a8e3d40cc32104b1d387a3d3b560b43356e/biojava-structure/src/main/java/org/biojava/nbio/structure/symmetry/internal/SymmetryAxes.java#L333-L354
adyliu/jafka
src/main/java/io/jafka/api/FetchRequest.java
FetchRequest.readFrom
public static FetchRequest readFrom(ByteBuffer buffer) { String topic = Utils.readShortString(buffer); int partition = buffer.getInt(); long offset = buffer.getLong(); int size = buffer.getInt(); return new FetchRequest(topic, partition, offset, size); }
java
public static FetchRequest readFrom(ByteBuffer buffer) { String topic = Utils.readShortString(buffer); int partition = buffer.getInt(); long offset = buffer.getLong(); int size = buffer.getInt(); return new FetchRequest(topic, partition, offset, size); }
[ "public", "static", "FetchRequest", "readFrom", "(", "ByteBuffer", "buffer", ")", "{", "String", "topic", "=", "Utils", ".", "readShortString", "(", "buffer", ")", ";", "int", "partition", "=", "buffer", ".", "getInt", "(", ")", ";", "long", "offset", "=",...
Read a fetch request from buffer(socket data) @param buffer the buffer data @return a fetch request @throws IllegalArgumentException while error data format(no topic)
[ "Read", "a", "fetch", "request", "from", "buffer", "(", "socket", "data", ")" ]
train
https://github.com/adyliu/jafka/blob/cc14d2ed60c039b12d7b106bb5269ef21d0add7e/src/main/java/io/jafka/api/FetchRequest.java#L105-L111
pravega/pravega
client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java
ReaderGroupStateManager.releaseSegment
boolean releaseSegment(Segment segment, long lastOffset, long timeLag) throws ReaderNotInReaderGroupException { sync.updateState((state, updates) -> { Set<Segment> segments = state.getSegments(readerId); if (segments != null && segments.contains(segment) && state.getCheckpointForReader(readerId) == null && doesReaderOwnTooManySegments(state)) { updates.add(new ReleaseSegment(readerId, segment, lastOffset)); updates.add(new UpdateDistanceToTail(readerId, timeLag)); } }); ReaderGroupState state = sync.getState(); releaseTimer.reset(calculateReleaseTime(readerId, state)); acquireTimer.reset(calculateAcquireTime(readerId, state)); if (!state.isReaderOnline(readerId)) { throw new ReaderNotInReaderGroupException(readerId); } return !state.getSegments(readerId).contains(segment); }
java
boolean releaseSegment(Segment segment, long lastOffset, long timeLag) throws ReaderNotInReaderGroupException { sync.updateState((state, updates) -> { Set<Segment> segments = state.getSegments(readerId); if (segments != null && segments.contains(segment) && state.getCheckpointForReader(readerId) == null && doesReaderOwnTooManySegments(state)) { updates.add(new ReleaseSegment(readerId, segment, lastOffset)); updates.add(new UpdateDistanceToTail(readerId, timeLag)); } }); ReaderGroupState state = sync.getState(); releaseTimer.reset(calculateReleaseTime(readerId, state)); acquireTimer.reset(calculateAcquireTime(readerId, state)); if (!state.isReaderOnline(readerId)) { throw new ReaderNotInReaderGroupException(readerId); } return !state.getSegments(readerId).contains(segment); }
[ "boolean", "releaseSegment", "(", "Segment", "segment", ",", "long", "lastOffset", ",", "long", "timeLag", ")", "throws", "ReaderNotInReaderGroupException", "{", "sync", ".", "updateState", "(", "(", "state", ",", "updates", ")", "->", "{", "Set", "<", "Segmen...
Releases a segment to another reader. This reader should no longer read from the segment. @param segment The segment to be released @param lastOffset The offset from which the new owner should start reading from. @param timeLag How far the reader is from the tail of the stream in time. @return a boolean indicating if the segment was successfully released. @throws ReaderNotInReaderGroupException If the reader has been declared offline.
[ "Releases", "a", "segment", "to", "another", "reader", ".", "This", "reader", "should", "no", "longer", "read", "from", "the", "segment", "." ]
train
https://github.com/pravega/pravega/blob/6e24df7470669b3956a07018f52b2c6b3c2a3503/client/src/main/java/io/pravega/client/stream/impl/ReaderGroupStateManager.java#L251-L267
ksclarke/freelib-utils
src/main/java/info/freelibrary/util/Logger.java
Logger.getMessage
public String getMessage(final String aMessage, final Object... aDetails) { if (hasI18nKey(aMessage)) { return getI18n(aMessage, aDetails); } else if (aDetails.length == 0) { return aMessage; } else { return StringUtils.format(aMessage, aDetails); } }
java
public String getMessage(final String aMessage, final Object... aDetails) { if (hasI18nKey(aMessage)) { return getI18n(aMessage, aDetails); } else if (aDetails.length == 0) { return aMessage; } else { return StringUtils.format(aMessage, aDetails); } }
[ "public", "String", "getMessage", "(", "final", "String", "aMessage", ",", "final", "Object", "...", "aDetails", ")", "{", "if", "(", "hasI18nKey", "(", "aMessage", ")", ")", "{", "return", "getI18n", "(", "aMessage", ",", "aDetails", ")", ";", "}", "els...
Gets a message from the logger's backing resource bundle if what's passed in is a message key; if it's not then what's passed in is, itself, returned. If what's passed in is the same thing as what's returned, any additional details passed in are ignored. @param aMessage A message to check against the backing resource bundle @param aDetails An array of additional details @return A message value (potentially from the backing resource bundle)
[ "Gets", "a", "message", "from", "the", "logger", "s", "backing", "resource", "bundle", "if", "what", "s", "passed", "in", "is", "a", "message", "key", ";", "if", "it", "s", "not", "then", "what", "s", "passed", "in", "is", "itself", "returned", ".", ...
train
https://github.com/ksclarke/freelib-utils/blob/54e822ae4c11b3d74793fd82a1a535ffafffaf45/src/main/java/info/freelibrary/util/Logger.java#L1144-L1152
apereo/cas
core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java
AbstractCasWebflowConfigurer.createTransitionForState
public Transition createTransitionForState(final TransitionableState state, final String criteriaOutcome, final String targetState) { return createTransitionForState(state, criteriaOutcome, targetState, false); }
java
public Transition createTransitionForState(final TransitionableState state, final String criteriaOutcome, final String targetState) { return createTransitionForState(state, criteriaOutcome, targetState, false); }
[ "public", "Transition", "createTransitionForState", "(", "final", "TransitionableState", "state", ",", "final", "String", "criteriaOutcome", ",", "final", "String", "targetState", ")", "{", "return", "createTransitionForState", "(", "state", ",", "criteriaOutcome", ",",...
Create transition for state transition. @param state the state @param criteriaOutcome the criteria outcome @param targetState the target state @return the transition
[ "Create", "transition", "for", "state", "transition", "." ]
train
https://github.com/apereo/cas/blob/b4b306433a8782cef803a39bea5b1f96740e0e9b/core/cas-server-core-webflow-api/src/main/java/org/apereo/cas/web/flow/configurer/AbstractCasWebflowConfigurer.java#L295-L297
haraldk/TwelveMonkeys
common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java
MagickUtil.rgbToBuffered
private static BufferedImage rgbToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException { Dimension size = pImage.getDimension(); int length = size.width * size.height; int bands = pAlpha ? 4 : 3; byte[] pixels = new byte[length * bands]; // TODO: If we do multiple dispatches (one per line, typically), we could provide listener // feedback. But it's currently a lot slower than fetching all the pixels in one go. // Note: The ordering ABGR or BGR corresponds to BufferedImage // TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ABGR" : "BGR", pixels); // Init databuffer with array, to avoid allocation of empty array DataBuffer buffer = new DataBufferByte(pixels, pixels.length); int[] bandOffsets = pAlpha ? BAND_OFF_TRANS : BAND_OFF_OPAQUE; WritableRaster raster = Raster.createInterleavedRaster(buffer, size.width, size.height, size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT); return new BufferedImage(pAlpha ? CM_COLOR_ALPHA : CM_COLOR_OPAQUE, raster, pAlpha, null); }
java
private static BufferedImage rgbToBuffered(MagickImage pImage, boolean pAlpha) throws MagickException { Dimension size = pImage.getDimension(); int length = size.width * size.height; int bands = pAlpha ? 4 : 3; byte[] pixels = new byte[length * bands]; // TODO: If we do multiple dispatches (one per line, typically), we could provide listener // feedback. But it's currently a lot slower than fetching all the pixels in one go. // Note: The ordering ABGR or BGR corresponds to BufferedImage // TYPE_4BYTE_ABGR and TYPE_3BYTE_BGR respectively pImage.dispatchImage(0, 0, size.width, size.height, pAlpha ? "ABGR" : "BGR", pixels); // Init databuffer with array, to avoid allocation of empty array DataBuffer buffer = new DataBufferByte(pixels, pixels.length); int[] bandOffsets = pAlpha ? BAND_OFF_TRANS : BAND_OFF_OPAQUE; WritableRaster raster = Raster.createInterleavedRaster(buffer, size.width, size.height, size.width * bands, bands, bandOffsets, LOCATION_UPPER_LEFT); return new BufferedImage(pAlpha ? CM_COLOR_ALPHA : CM_COLOR_OPAQUE, raster, pAlpha, null); }
[ "private", "static", "BufferedImage", "rgbToBuffered", "(", "MagickImage", "pImage", ",", "boolean", "pAlpha", ")", "throws", "MagickException", "{", "Dimension", "size", "=", "pImage", ".", "getDimension", "(", ")", ";", "int", "length", "=", "size", ".", "wi...
Converts an (A)RGB {@code MagickImage} to a {@code BufferedImage}, of type {@code TYPE_4BYTE_ABGR} or {@code TYPE_3BYTE_BGR}. @param pImage the original {@code MagickImage} @param pAlpha keep alpha channel @return a new {@code BufferedImage} @throws MagickException if an exception occurs during conversion @see BufferedImage
[ "Converts", "an", "(", "A", ")", "RGB", "{", "@code", "MagickImage", "}", "to", "a", "{", "@code", "BufferedImage", "}", "of", "type", "{", "@code", "TYPE_4BYTE_ABGR", "}", "or", "{", "@code", "TYPE_3BYTE_BGR", "}", "." ]
train
https://github.com/haraldk/TwelveMonkeys/blob/7fad4d5cd8cb3a6728c7fd3f28a7b84d8ce0101d/common/common-image/src/main/java/com/twelvemonkeys/image/MagickUtil.java#L536-L559
SeaCloudsEU/SeaCloudsPlatform
sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRest.java
TemplateRest.createTemplate
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createTemplate(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload) { logger.debug("StartOf createTemplate - Insert /templates"); TemplateHelper templateRestHelper = getTemplateHelper(); try { String location = templateRestHelper.createTemplate(hh, uriInfo.getAbsolutePath().toString(), payload); logger.debug("EndOf createTemplate"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The template has been stored successfully in the SLA Repository Database"), location); } catch (HelperException e) { logger.info("createTemplate exception:"+e.getMessage()); return buildResponse(e); } }
java
@POST @Consumes(MediaType.APPLICATION_XML) @Produces(MediaType.APPLICATION_XML) public Response createTemplate(@Context HttpHeaders hh,@Context UriInfo uriInfo, String payload) { logger.debug("StartOf createTemplate - Insert /templates"); TemplateHelper templateRestHelper = getTemplateHelper(); try { String location = templateRestHelper.createTemplate(hh, uriInfo.getAbsolutePath().toString(), payload); logger.debug("EndOf createTemplate"); return buildResponsePOST( HttpStatus.CREATED, printMessage( HttpStatus.CREATED, "The template has been stored successfully in the SLA Repository Database"), location); } catch (HelperException e) { logger.info("createTemplate exception:"+e.getMessage()); return buildResponse(e); } }
[ "@", "POST", "@", "Consumes", "(", "MediaType", ".", "APPLICATION_XML", ")", "@", "Produces", "(", "MediaType", ".", "APPLICATION_XML", ")", "public", "Response", "createTemplate", "(", "@", "Context", "HttpHeaders", "hh", ",", "@", "Context", "UriInfo", "uriI...
Returns the information of an specific template If the template it is not in the database, it returns 404 with empty payload /** Creates a new agreement <pre> POST /templates Request: POST /templates HTTP/1.1 Accept: application/xml Response: HTTP/1.1 201 Created Content-type: application/xml Location: http://.../templates/$uuid {@code <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <message code="201" message= "The template has been stored successfully in the SLA Repository Database"/> } </pre> Example: <li>curl -H "Content-type: application/xml" -X POST -d @template01.xml localhost:8080/sla-service/templates</li> @return XML information that the template has been created successfully
[ "Returns", "the", "information", "of", "an", "specific", "template", "If", "the", "template", "it", "is", "not", "in", "the", "database", "it", "returns", "404", "with", "empty", "payload", "/", "**", "Creates", "a", "new", "agreement" ]
train
https://github.com/SeaCloudsEU/SeaCloudsPlatform/blob/b199fe6de2c63b808cb248d3aca947d802375df8/sla/sla-core/sla-service/src/main/java/eu/atos/sla/service/rest/TemplateRest.java#L302-L323
alkacon/opencms-core
src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryField.java
CmsGalleryField.setImagePreview
protected void setImagePreview(String realPath, String imagePath) { if ((m_croppingParam == null) || !getFormValueAsString().contains(m_croppingParam.toString())) { m_croppingParam = CmsCroppingParamBean.parseImagePath(getFormValueAsString()); } CmsCroppingParamBean restricted; int marginTop = 0; if (m_croppingParam.getScaleParam().isEmpty()) { imagePath += "?__scale=w:165,h:114,t:1,c:white,r:0"; } else { restricted = m_croppingParam.getRestrictedSizeParam(114, 165); imagePath += "?" + restricted.toString(); marginTop = (114 - restricted.getResultingHeight()) / 2; } Element image = DOM.createImg(); image.setAttribute("src", imagePath); image.getStyle().setMarginTop(marginTop, Unit.PX); if (CmsClientStringUtil.checkIsPathOrLinkToSvg(realPath)) { image.getStyle().setWidth(100, Unit.PCT); image.getStyle().setHeight(100, Unit.PCT); } m_imagePreview.setInnerHTML(""); m_imagePreview.appendChild(image); }
java
protected void setImagePreview(String realPath, String imagePath) { if ((m_croppingParam == null) || !getFormValueAsString().contains(m_croppingParam.toString())) { m_croppingParam = CmsCroppingParamBean.parseImagePath(getFormValueAsString()); } CmsCroppingParamBean restricted; int marginTop = 0; if (m_croppingParam.getScaleParam().isEmpty()) { imagePath += "?__scale=w:165,h:114,t:1,c:white,r:0"; } else { restricted = m_croppingParam.getRestrictedSizeParam(114, 165); imagePath += "?" + restricted.toString(); marginTop = (114 - restricted.getResultingHeight()) / 2; } Element image = DOM.createImg(); image.setAttribute("src", imagePath); image.getStyle().setMarginTop(marginTop, Unit.PX); if (CmsClientStringUtil.checkIsPathOrLinkToSvg(realPath)) { image.getStyle().setWidth(100, Unit.PCT); image.getStyle().setHeight(100, Unit.PCT); } m_imagePreview.setInnerHTML(""); m_imagePreview.appendChild(image); }
[ "protected", "void", "setImagePreview", "(", "String", "realPath", ",", "String", "imagePath", ")", "{", "if", "(", "(", "m_croppingParam", "==", "null", ")", "||", "!", "getFormValueAsString", "(", ")", ".", "contains", "(", "m_croppingParam", ".", "toString"...
Sets the image preview.<p> @param realPath the actual image path @param imagePath the image path
[ "Sets", "the", "image", "preview", ".", "<p", ">" ]
train
https://github.com/alkacon/opencms-core/blob/bc104acc75d2277df5864da939a1f2de5fdee504/src-gwt/org/opencms/ade/galleries/client/ui/CmsGalleryField.java#L572-L595
Jasig/uPortal
uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java
ParameterEditManager.getParmEditSet
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException { Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while (child != null) { if (child.getNodeName().equals(Constants.ELM_PARM_SET)) return (Element) child; child = child.getNextSibling(); } if (create == false) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e); } Element parmSet = plf.createElement(Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_ID, ID); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild(parmSet); return parmSet; }
java
private static Element getParmEditSet(Document plf, IPerson person, boolean create) throws PortalException { Node root = plf.getDocumentElement(); Node child = root.getFirstChild(); while (child != null) { if (child.getNodeName().equals(Constants.ELM_PARM_SET)) return (Element) child; child = child.getNextSibling(); } if (create == false) return null; String ID = null; try { ID = getDLS().getNextStructDirectiveId(person); } catch (Exception e) { throw new PortalException( "Exception encountered while " + "generating new parameter edit set node " + "Id for userId=" + person.getID(), e); } Element parmSet = plf.createElement(Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_TYPE, Constants.ELM_PARM_SET); parmSet.setAttribute(Constants.ATT_ID, ID); parmSet.setIdAttribute(Constants.ATT_ID, true); root.appendChild(parmSet); return parmSet; }
[ "private", "static", "Element", "getParmEditSet", "(", "Document", "plf", ",", "IPerson", "person", ",", "boolean", "create", ")", "throws", "PortalException", "{", "Node", "root", "=", "plf", ".", "getDocumentElement", "(", ")", ";", "Node", "child", "=", "...
Get the parameter edits set if any stored in the root of the document or create it if passed-in create flag is true.
[ "Get", "the", "parameter", "edits", "set", "if", "any", "stored", "in", "the", "root", "of", "the", "document", "or", "create", "it", "if", "passed", "-", "in", "create", "flag", "is", "true", "." ]
train
https://github.com/Jasig/uPortal/blob/c1986542abb9acd214268f2df21c6305ad2f262b/uPortal-layout/uPortal-layout-impl/src/main/java/org/apereo/portal/layout/dlm/ParameterEditManager.java#L174-L204
ahome-it/lienzo-core
src/main/java/com/ait/lienzo/client/core/shape/Ellipse.java
Ellipse.prepare
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double w = attr.getWidth(); final double h = attr.getHeight(); if ((w > 0) && (h > 0)) { context.beginPath(); context.ellipse(0, 0, w / 2, h / 2, 0, 0, Math.PI * 2, true); context.closePath(); return true; } return false; }
java
@Override protected boolean prepare(final Context2D context, final Attributes attr, final double alpha) { final double w = attr.getWidth(); final double h = attr.getHeight(); if ((w > 0) && (h > 0)) { context.beginPath(); context.ellipse(0, 0, w / 2, h / 2, 0, 0, Math.PI * 2, true); context.closePath(); return true; } return false; }
[ "@", "Override", "protected", "boolean", "prepare", "(", "final", "Context2D", "context", ",", "final", "Attributes", "attr", ",", "final", "double", "alpha", ")", "{", "final", "double", "w", "=", "attr", ".", "getWidth", "(", ")", ";", "final", "double",...
Draws this ellipse. @param context the {@link Context2D} used to draw this ellipse.
[ "Draws", "this", "ellipse", "." ]
train
https://github.com/ahome-it/lienzo-core/blob/8e03723700dec366f77064d12fb8676d8cd6be99/src/main/java/com/ait/lienzo/client/core/shape/Ellipse.java#L77-L95
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java
ThriftUtils.toBytes
public static byte[] toBytes(TBase<?, ?> record) throws TException { if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
java
public static byte[] toBytes(TBase<?, ?> record) throws TException { if (record == null) { return null; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); TTransport transport = new TIOStreamTransport(null, baos); TProtocol oProtocol = protocolFactory.getProtocol(transport); record.write(oProtocol); // baos.close(); return baos.toByteArray(); }
[ "public", "static", "byte", "[", "]", "toBytes", "(", "TBase", "<", "?", ",", "?", ">", "record", ")", "throws", "TException", "{", "if", "(", "record", "==", "null", ")", "{", "return", "null", ";", "}", "ByteArrayOutputStream", "baos", "=", "new", ...
Serializes a thrift object to byte array. @param record @return @throws TException
[ "Serializes", "a", "thrift", "object", "to", "byte", "array", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/ThriftUtils.java#L45-L55
phax/ph-commons
ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java
TypeConverter.convertToChar
public static char convertToChar (@Nonnull final Object aSrcValue) { if (aSrcValue == null) throw new TypeConverterException (char.class, EReason.NULL_SOURCE_NOT_ALLOWED); final Character aValue = convert (aSrcValue, Character.class); return aValue.charValue (); }
java
public static char convertToChar (@Nonnull final Object aSrcValue) { if (aSrcValue == null) throw new TypeConverterException (char.class, EReason.NULL_SOURCE_NOT_ALLOWED); final Character aValue = convert (aSrcValue, Character.class); return aValue.charValue (); }
[ "public", "static", "char", "convertToChar", "(", "@", "Nonnull", "final", "Object", "aSrcValue", ")", "{", "if", "(", "aSrcValue", "==", "null", ")", "throw", "new", "TypeConverterException", "(", "char", ".", "class", ",", "EReason", ".", "NULL_SOURCE_NOT_AL...
Convert the passed source value to char @param aSrcValue The source value. May not be <code>null</code>. @return The converted value. @throws TypeConverterException if the source value is <code>null</code> or if no converter was found or if the converter returned a <code>null</code> object. @throws RuntimeException If the converter itself throws an exception @see TypeConverterProviderBestMatch
[ "Convert", "the", "passed", "source", "value", "to", "char" ]
train
https://github.com/phax/ph-commons/blob/d28c03565f44a0b804d96028d0969f9bb38c4313/ph-commons/src/main/java/com/helger/commons/typeconvert/TypeConverter.java#L194-L200
calimero-project/calimero-core
src/tuwien/auto/calimero/mgmt/LocalDeviceManagementUsb.java
LocalDeviceManagementUsb.getProperty
public byte[] getProperty(final int objectType, final int objectInstance, final int propertyId, final int start, final int elements) throws KNXTimeoutException, KNXRemoteException, KNXPortClosedException, InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt(CEMIDevMgmt.MC_PROPREAD_REQ, objectType, objectInstance, propertyId, start, elements); send(req, null); return findFrame(CEMIDevMgmt.MC_PROPREAD_CON, req); }
java
public byte[] getProperty(final int objectType, final int objectInstance, final int propertyId, final int start, final int elements) throws KNXTimeoutException, KNXRemoteException, KNXPortClosedException, InterruptedException { final CEMIDevMgmt req = new CEMIDevMgmt(CEMIDevMgmt.MC_PROPREAD_REQ, objectType, objectInstance, propertyId, start, elements); send(req, null); return findFrame(CEMIDevMgmt.MC_PROPREAD_CON, req); }
[ "public", "byte", "[", "]", "getProperty", "(", "final", "int", "objectType", ",", "final", "int", "objectInstance", ",", "final", "int", "propertyId", ",", "final", "int", "start", ",", "final", "int", "elements", ")", "throws", "KNXTimeoutException", ",", ...
Gets property value elements of an interface object property. @param objectType the interface object type @param objectInstance the interface object instance (usually 1) @param propertyId the property identifier (PID) @param start start index in the property value to start writing to @param elements number of elements to set @return byte array containing the property element data @throws KNXTimeoutException on timeout setting the property elements @throws KNXRemoteException on remote error or invalid response @throws KNXPortClosedException if adapter is closed @throws InterruptedException on interrupt
[ "Gets", "property", "value", "elements", "of", "an", "interface", "object", "property", "." ]
train
https://github.com/calimero-project/calimero-core/blob/7e6f547c6bd75fa985bfeb5b47ba671df2ea01e8/src/tuwien/auto/calimero/mgmt/LocalDeviceManagementUsb.java#L146-L154
sporniket/core
sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java
FileTools.loadResourceBundle
public static Map<String, String> loadResourceBundle(String bundleName, Encoding encoding, String newline) throws IOException, SyntaxErrorException, MissingResourceException { return loadResourceBundle(bundleName, encoding, newline, Locale.getDefault()); }
java
public static Map<String, String> loadResourceBundle(String bundleName, Encoding encoding, String newline) throws IOException, SyntaxErrorException, MissingResourceException { return loadResourceBundle(bundleName, encoding, newline, Locale.getDefault()); }
[ "public", "static", "Map", "<", "String", ",", "String", ">", "loadResourceBundle", "(", "String", "bundleName", ",", "Encoding", "encoding", ",", "String", "newline", ")", "throws", "IOException", ",", "SyntaxErrorException", ",", "MissingResourceException", "{", ...
Load a properties file looking for localized versions like ResourceBundle, using the default Locale, supporting multiple line values. @param bundleName the bundle name, like <code>com.foo.MyBundle</code>. @param encoding the encoding of the bundle files. @param newline the sequence to use as a line separator for multiple line values. @return the properties, merged like a Java ResourceBundle. @throws IOException if there is a problem to deal with. @throws SyntaxErrorException if there is a problem to deal with. @throws MissingResourceException if no file at all is found. @see LineByLinePropertyParser @since 16.08.02
[ "Load", "a", "properties", "file", "looking", "for", "localized", "versions", "like", "ResourceBundle", "using", "the", "default", "Locale", "supporting", "multiple", "line", "values", "." ]
train
https://github.com/sporniket/core/blob/3480ebd72a07422fcc09971be2607ee25efb2c26/sporniket-core-io/src/main/java/com/sporniket/libre/io/FileTools.java#L288-L292
magro/memcached-session-manager
core/src/main/java/de/javakaffee/web/msm/NodeIdService.java
NodeIdService.getRandomNextNodeId
protected String getRandomNextNodeId( final String nodeId, final Collection<String> nodeIds ) { /* create a list of nodeIds to check randomly */ final List<String> otherNodeIds = new ArrayList<String>( nodeIds ); otherNodeIds.remove( nodeId ); while ( !otherNodeIds.isEmpty() ) { final String nodeIdToCheck = otherNodeIds.get( _random.nextInt( otherNodeIds.size() ) ); if ( isNodeAvailable( nodeIdToCheck ) ) { return nodeIdToCheck; } otherNodeIds.remove( nodeIdToCheck ); } return null; }
java
protected String getRandomNextNodeId( final String nodeId, final Collection<String> nodeIds ) { /* create a list of nodeIds to check randomly */ final List<String> otherNodeIds = new ArrayList<String>( nodeIds ); otherNodeIds.remove( nodeId ); while ( !otherNodeIds.isEmpty() ) { final String nodeIdToCheck = otherNodeIds.get( _random.nextInt( otherNodeIds.size() ) ); if ( isNodeAvailable( nodeIdToCheck ) ) { return nodeIdToCheck; } otherNodeIds.remove( nodeIdToCheck ); } return null; }
[ "protected", "String", "getRandomNextNodeId", "(", "final", "String", "nodeId", ",", "final", "Collection", "<", "String", ">", "nodeIds", ")", "{", "/* create a list of nodeIds to check randomly\n */", "final", "List", "<", "String", ">", "otherNodeIds", "=", ...
Determines (randomly) an available node id from the provided node ids. The returned node id will be different from the provided nodeId and will be available according to the local {@link NodeAvailabilityCache}. @param nodeId the original id @param nodeIds the node ids to choose from @return an available node or null
[ "Determines", "(", "randomly", ")", "an", "available", "node", "id", "from", "the", "provided", "node", "ids", ".", "The", "returned", "node", "id", "will", "be", "different", "from", "the", "provided", "nodeId", "and", "will", "be", "available", "according"...
train
https://github.com/magro/memcached-session-manager/blob/716e147c9840ab10298c4d2b9edd0662058331e6/core/src/main/java/de/javakaffee/web/msm/NodeIdService.java#L159-L175
QSFT/Doradus
doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java
SpiderSession.deleteObject
public ObjectResult deleteObject(String tableName, String objID) { Utils.require(!Utils.isEmpty(tableName), "tableName"); Utils.require(!Utils.isEmpty(objID), "objID"); TableDefinition tableDef = m_appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", m_appDef.getAppName(), tableName); DBObjectBatch dbObjBatch = new DBObjectBatch(); dbObjBatch.addObject(objID, tableName); BatchResult batchResult = deleteBatch(tableName, dbObjBatch); if (batchResult.isFailed()) { throw new RuntimeException(batchResult.getErrorMessage()); } return batchResult.getResultObjects().iterator().next(); }
java
public ObjectResult deleteObject(String tableName, String objID) { Utils.require(!Utils.isEmpty(tableName), "tableName"); Utils.require(!Utils.isEmpty(objID), "objID"); TableDefinition tableDef = m_appDef.getTableDef(tableName); Utils.require(tableDef != null, "Unknown table for application '%s': %s", m_appDef.getAppName(), tableName); DBObjectBatch dbObjBatch = new DBObjectBatch(); dbObjBatch.addObject(objID, tableName); BatchResult batchResult = deleteBatch(tableName, dbObjBatch); if (batchResult.isFailed()) { throw new RuntimeException(batchResult.getErrorMessage()); } return batchResult.getResultObjects().iterator().next(); }
[ "public", "ObjectResult", "deleteObject", "(", "String", "tableName", ",", "String", "objID", ")", "{", "Utils", ".", "require", "(", "!", "Utils", ".", "isEmpty", "(", "tableName", ")", ",", "\"tableName\"", ")", ";", "Utils", ".", "require", "(", "!", ...
Delete the object with the given ID from the given table. This is a convenience method that creates a {@link DBObjectBatch} consisting of a single {@link DBObject} with the given ID and then calls {@link #deleteBatch(String, DBObjectBatch)}. The {@link ObjectResult} for the object ID is then returned. It is not an error to delete an object that has already been deleted. @param tableName Name of table from which to delete object. It must belong to this session's application. @param objID ID of object to delete. @return {@link ObjectResult} of deletion request.
[ "Delete", "the", "object", "with", "the", "given", "ID", "from", "the", "given", "table", ".", "This", "is", "a", "convenience", "method", "that", "creates", "a", "{", "@link", "DBObjectBatch", "}", "consisting", "of", "a", "single", "{", "@link", "DBObjec...
train
https://github.com/QSFT/Doradus/blob/ad64d3c37922eefda68ec8869ef089c1ca604b70/doradus-client/src/main/java/com/dell/doradus/client/SpiderSession.java#L188-L201
leancloud/java-sdk-all
core/src/main/java/cn/leancloud/AVACL.java
AVACL.setReadAccess
public void setReadAccess(String userId, boolean allowed) { if (StringUtil.isEmpty(userId)) { throw new IllegalArgumentException("cannot setRead/WriteAccess for null userId"); } boolean writePermission = getWriteAccess(userId); setPermissionsIfNonEmpty(userId, allowed, writePermission); }
java
public void setReadAccess(String userId, boolean allowed) { if (StringUtil.isEmpty(userId)) { throw new IllegalArgumentException("cannot setRead/WriteAccess for null userId"); } boolean writePermission = getWriteAccess(userId); setPermissionsIfNonEmpty(userId, allowed, writePermission); }
[ "public", "void", "setReadAccess", "(", "String", "userId", ",", "boolean", "allowed", ")", "{", "if", "(", "StringUtil", ".", "isEmpty", "(", "userId", ")", ")", "{", "throw", "new", "IllegalArgumentException", "(", "\"cannot setRead/WriteAccess for null userId\"",...
Set whether the given user id is allowed to read this object.
[ "Set", "whether", "the", "given", "user", "id", "is", "allowed", "to", "read", "this", "object", "." ]
train
https://github.com/leancloud/java-sdk-all/blob/323f8e7ee38051b1350790e5192304768c5c9f5f/core/src/main/java/cn/leancloud/AVACL.java#L169-L175
timols/java-gitlab-api
src/main/java/org/gitlab/api/GitlabAPI.java
GitlabAPI.getBuildVariable
public GitlabBuildVariable getBuildVariable(GitlabProject project, String key) throws IOException { return getBuildVariable(project.getId(), key); }
java
public GitlabBuildVariable getBuildVariable(GitlabProject project, String key) throws IOException { return getBuildVariable(project.getId(), key); }
[ "public", "GitlabBuildVariable", "getBuildVariable", "(", "GitlabProject", "project", ",", "String", "key", ")", "throws", "IOException", "{", "return", "getBuildVariable", "(", "project", ".", "getId", "(", ")", ",", "key", ")", ";", "}" ]
Gets build variable associated with a project and key. @param project The project associated with the variable. @return A variable. @throws IOException on gitlab api call error
[ "Gets", "build", "variable", "associated", "with", "a", "project", "and", "key", "." ]
train
https://github.com/timols/java-gitlab-api/blob/f03eedf952cfbb40306be3bf9234dcf78fab029e/src/main/java/org/gitlab/api/GitlabAPI.java#L3661-L3664
BlueBrain/bluima
utils/blue_commons/src/main/java/ch/epfl/bbp/ResourceHelper.java
ResourceHelper.getFile
public static File getFile(String resourceOrFile) throws FileNotFoundException { try { File file = new File(resourceOrFile); if (file.exists()) { return file; } } catch (Exception e) {// nope } return getFile(resourceOrFile, Thread.class, false); }
java
public static File getFile(String resourceOrFile) throws FileNotFoundException { try { File file = new File(resourceOrFile); if (file.exists()) { return file; } } catch (Exception e) {// nope } return getFile(resourceOrFile, Thread.class, false); }
[ "public", "static", "File", "getFile", "(", "String", "resourceOrFile", ")", "throws", "FileNotFoundException", "{", "try", "{", "File", "file", "=", "new", "File", "(", "resourceOrFile", ")", ";", "if", "(", "file", ".", "exists", "(", ")", ")", "{", "r...
Use getInputStream instead, because Files are trouble, when in (maven) JARs
[ "Use", "getInputStream", "instead", "because", "Files", "are", "trouble", "when", "in", "(", "maven", ")", "JARs" ]
train
https://github.com/BlueBrain/bluima/blob/793ea3f46761dce72094e057a56cddfa677156ae/utils/blue_commons/src/main/java/ch/epfl/bbp/ResourceHelper.java#L31-L43
mongodb/stitch-android-sdk
core/sdk/src/main/java/com/mongodb/stitch/core/auth/internal/CoreStitchAuth.java
CoreStitchAuth.doAuthenticatedRequest
public <T> T doAuthenticatedRequest( final StitchAuthRequest stitchReq, final Class<T> resultClass, final CodecRegistry codecRegistry ) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return newReg.get(resultClass).decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
java
public <T> T doAuthenticatedRequest( final StitchAuthRequest stitchReq, final Class<T> resultClass, final CodecRegistry codecRegistry ) { final Response response = doAuthenticatedRequest(stitchReq); try { final String bodyStr = IoUtils.readAllToString(response.getBody()); final JsonReader bsonReader = new JsonReader(bodyStr); // We must check this condition because the decoder will throw trying to decode null if (bsonReader.readBsonType() == BsonType.NULL) { return null; } final CodecRegistry newReg = CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry); return newReg.get(resultClass).decode(bsonReader, DecoderContext.builder().build()); } catch (final Exception e) { throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR); } }
[ "public", "<", "T", ">", "T", "doAuthenticatedRequest", "(", "final", "StitchAuthRequest", "stitchReq", ",", "final", "Class", "<", "T", ">", "resultClass", ",", "final", "CodecRegistry", "codecRegistry", ")", "{", "final", "Response", "response", "=", "doAuthen...
Performs a request against Stitch using the provided {@link StitchAuthRequest} object, and decodes the JSON body of the response into a T value as specified by the provided class type. The type will be decoded using the codec found for T in the codec registry given. If the provided type is not supported by the codec registry to be used, the method will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}. @param stitchReq the request to perform. @param resultClass the class that the JSON response should be decoded as. @param codecRegistry the codec registry used for de/serialization. @param <T> the type into which the JSON response will be decoded into. @return the decoded value.
[ "Performs", "a", "request", "against", "Stitch", "using", "the", "provided", "{", "@link", "StitchAuthRequest", "}", "object", "and", "decodes", "the", "JSON", "body", "of", "the", "response", "into", "a", "T", "value", "as", "specified", "by", "the", "provi...
train
https://github.com/mongodb/stitch-android-sdk/blob/159b9334b1f1a827285544be5ee20cdf7b04e4cc/core/sdk/src/main/java/com/mongodb/stitch/core/auth/internal/CoreStitchAuth.java#L282-L304
Impetus/Kundera
src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexManager.java
IndexManager.write
public final void write(EntityMetadata metadata, Object entity) { if (indexer != null) { MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( metadata.getPersistenceUnit()); ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity); } }
java
public final void write(EntityMetadata metadata, Object entity) { if (indexer != null) { MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( metadata.getPersistenceUnit()); ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity); } }
[ "public", "final", "void", "write", "(", "EntityMetadata", "metadata", ",", "Object", "entity", ")", "{", "if", "(", "indexer", "!=", "null", ")", "{", "MetamodelImpl", "metamodel", "=", "(", "MetamodelImpl", ")", "kunderaMetadata", ".", "getApplicationMetadata"...
Indexes an object. @param metadata the metadata @param entity the entity
[ "Indexes", "an", "object", "." ]
train
https://github.com/Impetus/Kundera/blob/268958ab1ec09d14ec4d9184f0c8ded7a9158908/src/jpa-engine/core/src/main/java/com/impetus/kundera/index/IndexManager.java#L233-L241
deeplearning4j/deeplearning4j
nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java
SameDiff.putOrUpdateShapeForVarName
@Deprecated public void putOrUpdateShapeForVarName(String varName, long[] shape, boolean clearArrayOnShapeMismatch){ Preconditions.checkNotNull(shape, "Cannot put null shape for variable: %s", varName); if(variableNameToShape.containsKey(varName)){ // updateShapeForVarName(varName, shape, clearArrayOnShapeMismatch); //TODO } else { putShapeForVarName(varName, shape); } }
java
@Deprecated public void putOrUpdateShapeForVarName(String varName, long[] shape, boolean clearArrayOnShapeMismatch){ Preconditions.checkNotNull(shape, "Cannot put null shape for variable: %s", varName); if(variableNameToShape.containsKey(varName)){ // updateShapeForVarName(varName, shape, clearArrayOnShapeMismatch); //TODO } else { putShapeForVarName(varName, shape); } }
[ "@", "Deprecated", "public", "void", "putOrUpdateShapeForVarName", "(", "String", "varName", ",", "long", "[", "]", "shape", ",", "boolean", "clearArrayOnShapeMismatch", ")", "{", "Preconditions", ".", "checkNotNull", "(", "shape", ",", "\"Cannot put null shape for va...
Put or update the shape for the given variable name. Optionally supports clearing the specified variable's INDArray if it's shape does not match the new shape @param varName Variable name @param shape Shape to put @param clearArrayOnShapeMismatch If false: no change to arrays. If true: if an INDArray is defined for the specified variable name, it will be removed from the graph (to be later re-generated) if its shape does not match the specified shape
[ "Put", "or", "update", "the", "shape", "for", "the", "given", "variable", "name", ".", "Optionally", "supports", "clearing", "the", "specified", "variable", "s", "INDArray", "if", "it", "s", "shape", "does", "not", "match", "the", "new", "shape" ]
train
https://github.com/deeplearning4j/deeplearning4j/blob/effce52f2afd7eeb53c5bcca699fcd90bd06822f/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/samediff/SameDiff.java#L690-L699
pip-services3-java/pip-services3-components-java
src/org/pipservices3/components/config/YamlConfigReader.java
YamlConfigReader.readConfig
public static ConfigParams readConfig(String correlationId, String path, ConfigParams parameters) throws ApplicationException { return new YamlConfigReader(path).readConfig(correlationId, parameters); }
java
public static ConfigParams readConfig(String correlationId, String path, ConfigParams parameters) throws ApplicationException { return new YamlConfigReader(path).readConfig(correlationId, parameters); }
[ "public", "static", "ConfigParams", "readConfig", "(", "String", "correlationId", ",", "String", "path", ",", "ConfigParams", "parameters", ")", "throws", "ApplicationException", "{", "return", "new", "YamlConfigReader", "(", "path", ")", ".", "readConfig", "(", "...
Reads configuration from a file, parameterize it with given values and returns a new ConfigParams object. @param correlationId (optional) transaction id to trace execution through call chain. @param path a path to configuration file. @param parameters values to parameters the configuration or null to skip parameterization. @return ConfigParams configuration. @throws ApplicationException when error occured.
[ "Reads", "configuration", "from", "a", "file", "parameterize", "it", "with", "given", "values", "and", "returns", "a", "new", "ConfigParams", "object", "." ]
train
https://github.com/pip-services3-java/pip-services3-components-java/blob/122352fbf9b208f6417376da7b8ad725bc85ee58/src/org/pipservices3/components/config/YamlConfigReader.java#L130-L133
DDTH/ddth-commons
ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java
DateTimeUtils.addYears
public static Calendar addYears(Calendar origin, int value) { Calendar cal = sync((Calendar) origin.clone()); cal.add(Calendar.YEAR, value); return sync(cal); }
java
public static Calendar addYears(Calendar origin, int value) { Calendar cal = sync((Calendar) origin.clone()); cal.add(Calendar.YEAR, value); return sync(cal); }
[ "public", "static", "Calendar", "addYears", "(", "Calendar", "origin", ",", "int", "value", ")", "{", "Calendar", "cal", "=", "sync", "(", "(", "Calendar", ")", "origin", ".", "clone", "(", ")", ")", ";", "cal", ".", "add", "(", "Calendar", ".", "YEA...
Add/Subtract the specified amount of years to the given {@link Calendar}. <p> The returned {@link Calendar} has its fields synced. </p> @param origin @param value @return @since 0.9.2
[ "Add", "/", "Subtract", "the", "specified", "amount", "of", "years", "to", "the", "given", "{", "@link", "Calendar", "}", "." ]
train
https://github.com/DDTH/ddth-commons/blob/734f0e77321d41eeca78a557be9884df9874e46e/ddth-commons-core/src/main/java/com/github/ddth/commons/utils/DateTimeUtils.java#L965-L969
steveohara/j2mod
src/main/java/com/ghgande/j2mod/modbus/io/ModbusUDPTransport.java
ModbusUDPTransport.writeMessage
private void writeMessage(ModbusMessage msg) throws ModbusIOException { try { synchronized (byteOutputStream) { int len = msg.getOutputLength(); byteOutputStream.reset(); msg.writeTo(byteOutputStream); byte data[] = byteOutputStream.getBuffer(); data = Arrays.copyOf(data, len); terminal.sendMessage(data); } } catch (Exception ex) { throw new ModbusIOException("I/O exception - failed to write", ex); } }
java
private void writeMessage(ModbusMessage msg) throws ModbusIOException { try { synchronized (byteOutputStream) { int len = msg.getOutputLength(); byteOutputStream.reset(); msg.writeTo(byteOutputStream); byte data[] = byteOutputStream.getBuffer(); data = Arrays.copyOf(data, len); terminal.sendMessage(data); } } catch (Exception ex) { throw new ModbusIOException("I/O exception - failed to write", ex); } }
[ "private", "void", "writeMessage", "(", "ModbusMessage", "msg", ")", "throws", "ModbusIOException", "{", "try", "{", "synchronized", "(", "byteOutputStream", ")", "{", "int", "len", "=", "msg", ".", "getOutputLength", "(", ")", ";", "byteOutputStream", ".", "r...
Writes the request/response message to the port @param msg Message to write @throws ModbusIOException If the port cannot be written to
[ "Writes", "the", "request", "/", "response", "message", "to", "the", "port" ]
train
https://github.com/steveohara/j2mod/blob/67162c55d7c02564e50211a9df06b8314953b5f2/src/main/java/com/ghgande/j2mod/modbus/io/ModbusUDPTransport.java#L136-L150
hazelcast/hazelcast
hazelcast/src/main/java/com/hazelcast/internal/util/hashslot/impl/HashSlotArrayBase.java
HashSlotArrayBase.move
private long move(long fromBaseAddress, long capacity, MemoryAllocator fromMalloc, MemoryAllocator toMalloc) { final long allocatedSize = HEADER_SIZE + capacity * slotLength; final long toBaseAddress = toMalloc.allocate(allocatedSize) + HEADER_SIZE; mem.copyMemory(fromBaseAddress - HEADER_SIZE, toBaseAddress - HEADER_SIZE, allocatedSize); fromMalloc.free(fromBaseAddress - HEADER_SIZE, allocatedSize); return toBaseAddress; }
java
private long move(long fromBaseAddress, long capacity, MemoryAllocator fromMalloc, MemoryAllocator toMalloc) { final long allocatedSize = HEADER_SIZE + capacity * slotLength; final long toBaseAddress = toMalloc.allocate(allocatedSize) + HEADER_SIZE; mem.copyMemory(fromBaseAddress - HEADER_SIZE, toBaseAddress - HEADER_SIZE, allocatedSize); fromMalloc.free(fromBaseAddress - HEADER_SIZE, allocatedSize); return toBaseAddress; }
[ "private", "long", "move", "(", "long", "fromBaseAddress", ",", "long", "capacity", ",", "MemoryAllocator", "fromMalloc", ",", "MemoryAllocator", "toMalloc", ")", "{", "final", "long", "allocatedSize", "=", "HEADER_SIZE", "+", "capacity", "*", "slotLength", ";", ...
Copies a block from one allocator to another, then frees the source block.
[ "Copies", "a", "block", "from", "one", "allocator", "to", "another", "then", "frees", "the", "source", "block", "." ]
train
https://github.com/hazelcast/hazelcast/blob/8c4bc10515dbbfb41a33e0302c0caedf3cda1baf/hazelcast/src/main/java/com/hazelcast/internal/util/hashslot/impl/HashSlotArrayBase.java#L473-L479
querydsl/querydsl
querydsl-sql/src/main/java/com/querydsl/sql/dml/AbstractSQLUpdateClause.java
AbstractSQLUpdateClause.addBatch
@WithBridgeMethods(value = SQLUpdateClause.class, castRequired = true) public C addBatch() { batches.add(new SQLUpdateBatch(metadata, updates)); updates = Maps.newLinkedHashMap(); metadata = new DefaultQueryMetadata(); metadata.addJoin(JoinType.DEFAULT, entity); return (C) this; }
java
@WithBridgeMethods(value = SQLUpdateClause.class, castRequired = true) public C addBatch() { batches.add(new SQLUpdateBatch(metadata, updates)); updates = Maps.newLinkedHashMap(); metadata = new DefaultQueryMetadata(); metadata.addJoin(JoinType.DEFAULT, entity); return (C) this; }
[ "@", "WithBridgeMethods", "(", "value", "=", "SQLUpdateClause", ".", "class", ",", "castRequired", "=", "true", ")", "public", "C", "addBatch", "(", ")", "{", "batches", ".", "add", "(", "new", "SQLUpdateBatch", "(", "metadata", ",", "updates", ")", ")", ...
Add the current state of bindings as a batch item @return the current object
[ "Add", "the", "current", "state", "of", "bindings", "as", "a", "batch", "item" ]
train
https://github.com/querydsl/querydsl/blob/2bf234caf78549813a1e0f44d9c30ecc5ef734e3/querydsl-sql/src/main/java/com/querydsl/sql/dml/AbstractSQLUpdateClause.java#L109-L116
spotify/helios
helios-services/src/main/java/com/spotify/helios/agent/ZooKeeperAgentModel.java
ZooKeeperAgentModel.getTaskStatus
@Override public TaskStatus getTaskStatus(final JobId jobId) { final byte[] data = taskStatuses.get(jobId.toString()); if (data == null) { return null; } try { return parse(data, TaskStatus.class); } catch (IOException e) { throw new RuntimeException(e); } }
java
@Override public TaskStatus getTaskStatus(final JobId jobId) { final byte[] data = taskStatuses.get(jobId.toString()); if (data == null) { return null; } try { return parse(data, TaskStatus.class); } catch (IOException e) { throw new RuntimeException(e); } }
[ "@", "Override", "public", "TaskStatus", "getTaskStatus", "(", "final", "JobId", "jobId", ")", "{", "final", "byte", "[", "]", "data", "=", "taskStatuses", ".", "get", "(", "jobId", ".", "toString", "(", ")", ")", ";", "if", "(", "data", "==", "null", ...
Get the {@link TaskStatus} for the job identified by {@code jobId}.
[ "Get", "the", "{" ]
train
https://github.com/spotify/helios/blob/c9000bc1d6908651570be8b057d4981bba4df5b4/helios-services/src/main/java/com/spotify/helios/agent/ZooKeeperAgentModel.java#L180-L191
geomajas/geomajas-project-client-gwt
client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java
DomHelper.createOrUpdateGroup
public Element createOrUpdateGroup(Object parent, Object object, Matrix transformation, Style style) { switch (namespace) { case SVG: return createSvgGroup(parent, object, transformation, style); case VML: return createVmlGroup(parent, object, transformation); case HTML: default: return createHtmlGroup(parent, object, transformation, style); } }
java
public Element createOrUpdateGroup(Object parent, Object object, Matrix transformation, Style style) { switch (namespace) { case SVG: return createSvgGroup(parent, object, transformation, style); case VML: return createVmlGroup(parent, object, transformation); case HTML: default: return createHtmlGroup(parent, object, transformation, style); } }
[ "public", "Element", "createOrUpdateGroup", "(", "Object", "parent", ",", "Object", "object", ",", "Matrix", "transformation", ",", "Style", "style", ")", "{", "switch", "(", "namespace", ")", "{", "case", "SVG", ":", "return", "createSvgGroup", "(", "parent",...
Creates a group element in the technology (SVG/VML/...) of this context. A group is meant to group other elements together. Also this method gives you the opportunity to specify a specific width and height. @param parent parent group object @param object group object @param transformation On each group, it is possible to apply a matrix transformation (currently translation only). This is the real strength of a group element. Never apply transformations on any other kind of element. @param style Add a style to a group. @return the group element
[ "Creates", "a", "group", "element", "in", "the", "technology", "(", "SVG", "/", "VML", "/", "...", ")", "of", "this", "context", ".", "A", "group", "is", "meant", "to", "group", "other", "elements", "together", ".", "Also", "this", "method", "gives", "...
train
https://github.com/geomajas/geomajas-project-client-gwt/blob/1c1adc48deb192ed825265eebcc74d70bbf45670/client/src/main/java/org/geomajas/gwt/client/gfx/context/DomHelper.java#L336-L346
mbenson/therian
core/src/main/java/therian/operator/convert/Converter.java
Converter.supports
@Override public boolean supports(TherianContext context, Convert<? extends SOURCE, ? super TARGET> convert) { return !(isNoop(convert) && isRejectNoop()) && TypeUtils.isAssignable(convert.getSourceType().getType(), getSourceBound()) && TypeUtils.isAssignable(getTargetBound(), convert.getTargetType().getType()); }
java
@Override public boolean supports(TherianContext context, Convert<? extends SOURCE, ? super TARGET> convert) { return !(isNoop(convert) && isRejectNoop()) && TypeUtils.isAssignable(convert.getSourceType().getType(), getSourceBound()) && TypeUtils.isAssignable(getTargetBound(), convert.getTargetType().getType()); }
[ "@", "Override", "public", "boolean", "supports", "(", "TherianContext", "context", ",", "Convert", "<", "?", "extends", "SOURCE", ",", "?", "super", "TARGET", ">", "convert", ")", "{", "return", "!", "(", "isNoop", "(", "convert", ")", "&&", "isRejectNoop...
{@inheritDoc} @return {@code true} if the source value is an instance of our SOURCE bound and the target type is assignable from our TARGET bound. If, the source value is an instance of the target type, returns ! {@link #isRejectNoop()}.
[ "{", "@inheritDoc", "}" ]
train
https://github.com/mbenson/therian/blob/0653505f73e2a6f5b0abc394ea6d83af03408254/core/src/main/java/therian/operator/convert/Converter.java#L95-L100
Azure/azure-sdk-for-java
logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/MapsInner.java
MapsInner.createOrUpdateAsync
public Observable<IntegrationAccountMapInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String mapName, IntegrationAccountMapInner map) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, mapName, map).map(new Func1<ServiceResponse<IntegrationAccountMapInner>, IntegrationAccountMapInner>() { @Override public IntegrationAccountMapInner call(ServiceResponse<IntegrationAccountMapInner> response) { return response.body(); } }); }
java
public Observable<IntegrationAccountMapInner> createOrUpdateAsync(String resourceGroupName, String integrationAccountName, String mapName, IntegrationAccountMapInner map) { return createOrUpdateWithServiceResponseAsync(resourceGroupName, integrationAccountName, mapName, map).map(new Func1<ServiceResponse<IntegrationAccountMapInner>, IntegrationAccountMapInner>() { @Override public IntegrationAccountMapInner call(ServiceResponse<IntegrationAccountMapInner> response) { return response.body(); } }); }
[ "public", "Observable", "<", "IntegrationAccountMapInner", ">", "createOrUpdateAsync", "(", "String", "resourceGroupName", ",", "String", "integrationAccountName", ",", "String", "mapName", ",", "IntegrationAccountMapInner", "map", ")", "{", "return", "createOrUpdateWithSer...
Creates or updates an integration account map. @param resourceGroupName The resource group name. @param integrationAccountName The integration account name. @param mapName The integration account map name. @param map The integration account map. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the IntegrationAccountMapInner object
[ "Creates", "or", "updates", "an", "integration", "account", "map", "." ]
train
https://github.com/Azure/azure-sdk-for-java/blob/aab183ddc6686c82ec10386d5a683d2691039626/logic/resource-manager/v2016_06_01/src/main/java/com/microsoft/azure/management/logic/v2016_06_01/implementation/MapsInner.java#L477-L484
JoeKerouac/utils
src/main/java/com/joe/utils/common/DateUtil.java
DateUtil.convert
public static String convert(String date, String format, String newFormat) { return getFormatDate(newFormat, parse(date, format)); }
java
public static String convert(String date, String format, String newFormat) { return getFormatDate(newFormat, parse(date, format)); }
[ "public", "static", "String", "convert", "(", "String", "date", ",", "String", "format", ",", "String", "newFormat", ")", "{", "return", "getFormatDate", "(", "newFormat", ",", "parse", "(", "date", ",", "format", ")", ")", ";", "}" ]
将一种格式的日期转换为另一种格式 @param date 日期字符串 @param format 日期对应的格式 @param newFormat 要转换的新格式 @return 新格式的日期
[ "将一种格式的日期转换为另一种格式" ]
train
https://github.com/JoeKerouac/utils/blob/45e1b2dc4d736956674fc4dcbe6cf84eaee69278/src/main/java/com/joe/utils/common/DateUtil.java#L54-L56
primefaces-extensions/core
src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java
SheetRenderer.decodeSelection
private void decodeSelection(final FacesContext context, final Sheet sheet, final String jsonSelection) { if (LangUtils.isValueBlank(jsonSelection)) { return; } try { // data comes in: [ [row, col, oldValue, newValue] ... ] final JSONArray array = new JSONArray(jsonSelection); sheet.setSelectedRow(array.getInt(0)); sheet.setSelectedColumn(sheet.getMappedColumn(array.getInt(1))); sheet.setSelectedLastRow(array.getInt(2)); sheet.setSelectedLastColumn(array.getInt(3)); sheet.setSelection(jsonSelection); } catch (final JSONException e) { throw new FacesException("Failed parsing Ajax JSON message for cell selection event:" + e.getMessage(), e); } }
java
private void decodeSelection(final FacesContext context, final Sheet sheet, final String jsonSelection) { if (LangUtils.isValueBlank(jsonSelection)) { return; } try { // data comes in: [ [row, col, oldValue, newValue] ... ] final JSONArray array = new JSONArray(jsonSelection); sheet.setSelectedRow(array.getInt(0)); sheet.setSelectedColumn(sheet.getMappedColumn(array.getInt(1))); sheet.setSelectedLastRow(array.getInt(2)); sheet.setSelectedLastColumn(array.getInt(3)); sheet.setSelection(jsonSelection); } catch (final JSONException e) { throw new FacesException("Failed parsing Ajax JSON message for cell selection event:" + e.getMessage(), e); } }
[ "private", "void", "decodeSelection", "(", "final", "FacesContext", "context", ",", "final", "Sheet", "sheet", ",", "final", "String", "jsonSelection", ")", "{", "if", "(", "LangUtils", ".", "isValueBlank", "(", "jsonSelection", ")", ")", "{", "return", ";", ...
Decodes the user Selection JSON data @param context @param sheet @param jsonSelection
[ "Decodes", "the", "user", "Selection", "JSON", "data" ]
train
https://github.com/primefaces-extensions/core/blob/afdbca591f60f47898e3517e1e939bc2f63d5355/src/main/java/org/primefaces/extensions/component/sheet/SheetRenderer.java#L935-L952
ops4j/org.ops4j.pax.logging
pax-logging-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java
StructuredDataMessage.asString
public final String asString(final Format format, final StructuredDataId structuredDataId) { final StringBuilder sb = new StringBuilder(); asString(format, structuredDataId, sb); return sb.toString(); }
java
public final String asString(final Format format, final StructuredDataId structuredDataId) { final StringBuilder sb = new StringBuilder(); asString(format, structuredDataId, sb); return sb.toString(); }
[ "public", "final", "String", "asString", "(", "final", "Format", "format", ",", "final", "StructuredDataId", "structuredDataId", ")", "{", "final", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "asString", "(", "format", ",", "structuredData...
Formats the structured data as described in RFC 5424. @param format "full" will include the type and message. null will return only the STRUCTURED-DATA as described in RFC 5424 @param structuredDataId The SD-ID as described in RFC 5424. If null the value in the StructuredData will be used. @return The formatted String.
[ "Formats", "the", "structured", "data", "as", "described", "in", "RFC", "5424", "." ]
train
https://github.com/ops4j/org.ops4j.pax.logging/blob/493de4e1db4fe9f981f3dd78b8e40e5bf2b2e59d/pax-logging-api/src/main/java/org/apache/logging/log4j/message/StructuredDataMessage.java#L304-L308
Netflix/governator
governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java
ModulesEx.fromClass
public static Module fromClass(final Class<?> cls, final boolean override) { List<Module> modules = new ArrayList<>(); // Iterate through all annotations of the main class, create a binding for the annotation // and add the module to the list of modules to install for (final Annotation annot : cls.getDeclaredAnnotations()) { final Class<? extends Annotation> type = annot.annotationType(); Bootstrap bootstrap = type.getAnnotation(Bootstrap.class); if (bootstrap != null) { LOG.info("Adding Module {}", bootstrap.module()); try { modules.add(bootstrap.module().getConstructor(type).newInstance(annot)); } catch (Exception e) { throw new RuntimeException(e); } } } try { if (override) { return Modules.override(combineAndOverride(modules)).with((Module)cls.newInstance()); } else { return Modules.combine(Modules.combine(modules), (Module)cls.newInstance()); } } catch (Exception e) { throw new RuntimeException(e); } }
java
public static Module fromClass(final Class<?> cls, final boolean override) { List<Module> modules = new ArrayList<>(); // Iterate through all annotations of the main class, create a binding for the annotation // and add the module to the list of modules to install for (final Annotation annot : cls.getDeclaredAnnotations()) { final Class<? extends Annotation> type = annot.annotationType(); Bootstrap bootstrap = type.getAnnotation(Bootstrap.class); if (bootstrap != null) { LOG.info("Adding Module {}", bootstrap.module()); try { modules.add(bootstrap.module().getConstructor(type).newInstance(annot)); } catch (Exception e) { throw new RuntimeException(e); } } } try { if (override) { return Modules.override(combineAndOverride(modules)).with((Module)cls.newInstance()); } else { return Modules.combine(Modules.combine(modules), (Module)cls.newInstance()); } } catch (Exception e) { throw new RuntimeException(e); } }
[ "public", "static", "Module", "fromClass", "(", "final", "Class", "<", "?", ">", "cls", ",", "final", "boolean", "override", ")", "{", "List", "<", "Module", ">", "modules", "=", "new", "ArrayList", "<>", "(", ")", ";", "// Iterate through all annotations of...
Create a single module that derived from all bootstrap annotations on a class, where that class itself is a module. For example, <pre> {@code public class MainApplicationModule extends AbstractModule { @Override public void configure() { // Application specific bindings here } public static void main(String[] args) { Guice.createInjector(ModulesEx.fromClass(MainApplicationModule.class)); } } } </pre> @author elandau
[ "Create", "a", "single", "module", "that", "derived", "from", "all", "bootstrap", "annotations", "on", "a", "class", "where", "that", "class", "itself", "is", "a", "module", "." ]
train
https://github.com/Netflix/governator/blob/c1f4bb1518e759c61f2e9cad8a896ec6beba0294/governator-legacy/src/main/java/com/netflix/governator/guice/ModulesEx.java#L81-L109
theHilikus/JRoboCom
jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/World.java
World.getBotsCount
public int getBotsCount(int teamId, boolean invert) { int total = 0; for (Robot bot : robotsPosition.keySet()) { if (bot.getData().getTeamId() == teamId) { if (!invert) { total++; } } else { if (invert) { total++; } } } return total; }
java
public int getBotsCount(int teamId, boolean invert) { int total = 0; for (Robot bot : robotsPosition.keySet()) { if (bot.getData().getTeamId() == teamId) { if (!invert) { total++; } } else { if (invert) { total++; } } } return total; }
[ "public", "int", "getBotsCount", "(", "int", "teamId", ",", "boolean", "invert", ")", "{", "int", "total", "=", "0", ";", "for", "(", "Robot", "bot", ":", "robotsPosition", ".", "keySet", "(", ")", ")", "{", "if", "(", "bot", ".", "getData", "(", "...
Get the total number of living robots from or not from a team @param teamId the team to search for @param invert if true, find robots NOT in teamId @return number of robots in the specified group
[ "Get", "the", "total", "number", "of", "living", "robots", "from", "or", "not", "from", "a", "team" ]
train
https://github.com/theHilikus/JRoboCom/blob/0e31c1ecf1006e35f68c229ff66c37640effffac/jrobocom-core/src/main/java/com/github/thehilikus/jrobocom/World.java#L301-L316
logic-ng/LogicNG
src/main/java/org/logicng/cardinalityconstraints/CCEncoder.java
CCEncoder.encodeIncremental
public Pair<ImmutableFormulaList, CCIncrementalData> encodeIncremental(final PBConstraint cc) { final EncodingResult result = EncodingResult.resultForFormula(f); final CCIncrementalData incData = this.encodeIncremental(cc, result); return new Pair<>(new ImmutableFormulaList(FType.AND, result.result()), incData); }
java
public Pair<ImmutableFormulaList, CCIncrementalData> encodeIncremental(final PBConstraint cc) { final EncodingResult result = EncodingResult.resultForFormula(f); final CCIncrementalData incData = this.encodeIncremental(cc, result); return new Pair<>(new ImmutableFormulaList(FType.AND, result.result()), incData); }
[ "public", "Pair", "<", "ImmutableFormulaList", ",", "CCIncrementalData", ">", "encodeIncremental", "(", "final", "PBConstraint", "cc", ")", "{", "final", "EncodingResult", "result", "=", "EncodingResult", ".", "resultForFormula", "(", "f", ")", ";", "final", "CCIn...
Encodes an incremental cardinality constraint and returns its encoding. @param cc the cardinality constraint @return the encoding of the constraint and the incremental data
[ "Encodes", "an", "incremental", "cardinality", "constraint", "and", "returns", "its", "encoding", "." ]
train
https://github.com/logic-ng/LogicNG/blob/bb9eb88a768be4be8e02a76cfc4a59e6c3fb7f2e/src/main/java/org/logicng/cardinalityconstraints/CCEncoder.java#L140-L144
teatrove/teatrove
trove/src/main/java/org/teatrove/trove/classfile/ConstantUTFInfo.java
ConstantUTFInfo.make
static ConstantUTFInfo make(ConstantPool cp, String str) { ConstantInfo ci = new ConstantUTFInfo(str); return (ConstantUTFInfo)cp.addConstant(ci); }
java
static ConstantUTFInfo make(ConstantPool cp, String str) { ConstantInfo ci = new ConstantUTFInfo(str); return (ConstantUTFInfo)cp.addConstant(ci); }
[ "static", "ConstantUTFInfo", "make", "(", "ConstantPool", "cp", ",", "String", "str", ")", "{", "ConstantInfo", "ci", "=", "new", "ConstantUTFInfo", "(", "str", ")", ";", "return", "(", "ConstantUTFInfo", ")", "cp", ".", "addConstant", "(", "ci", ")", ";",...
Will return either a new ConstantUTFInfo object or one already in the constant pool. If it is a new ConstantUTFInfo, it will be inserted into the pool.
[ "Will", "return", "either", "a", "new", "ConstantUTFInfo", "object", "or", "one", "already", "in", "the", "constant", "pool", ".", "If", "it", "is", "a", "new", "ConstantUTFInfo", "it", "will", "be", "inserted", "into", "the", "pool", "." ]
train
https://github.com/teatrove/teatrove/blob/7039bdd4da6817ff8c737f7e4e07bac7e3ad8bea/trove/src/main/java/org/teatrove/trove/classfile/ConstantUTFInfo.java#L35-L38
CenturyLinkCloud/mdw
mdw-common/src/com/centurylink/mdw/common/service/ServiceRegistry.java
ServiceRegistry.addDynamicService
public void addDynamicService(String serviceInterface, String className) { if (dynamicServices.containsKey(serviceInterface)) { dynamicServices.get(serviceInterface).add(className); } else { Set<String> classNamesSet = new HashSet<String>(); classNamesSet.add(className); dynamicServices.put(serviceInterface, classNamesSet); } }
java
public void addDynamicService(String serviceInterface, String className) { if (dynamicServices.containsKey(serviceInterface)) { dynamicServices.get(serviceInterface).add(className); } else { Set<String> classNamesSet = new HashSet<String>(); classNamesSet.add(className); dynamicServices.put(serviceInterface, classNamesSet); } }
[ "public", "void", "addDynamicService", "(", "String", "serviceInterface", ",", "String", "className", ")", "{", "if", "(", "dynamicServices", ".", "containsKey", "(", "serviceInterface", ")", ")", "{", "dynamicServices", ".", "get", "(", "serviceInterface", ")", ...
Add Dynamic Java Registered Service class names for each service @param serviceInterface @param className
[ "Add", "Dynamic", "Java", "Registered", "Service", "class", "names", "for", "each", "service" ]
train
https://github.com/CenturyLinkCloud/mdw/blob/91167fe65a25a5d7022cdcf8b0fae8506f5b87ce/mdw-common/src/com/centurylink/mdw/common/service/ServiceRegistry.java#L140-L149
kmi/iserve
iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/impl/GenericLogicDiscoverer.java
GenericLogicDiscoverer.findOperationsConsumingSome
@Override public Map<URI, MatchResult> findOperationsConsumingSome(Set<URI> inputTypes) { return findServicesClassifiedBySome(inputTypes, LogicConceptMatchType.Plugin); }
java
@Override public Map<URI, MatchResult> findOperationsConsumingSome(Set<URI> inputTypes) { return findServicesClassifiedBySome(inputTypes, LogicConceptMatchType.Plugin); }
[ "@", "Override", "public", "Map", "<", "URI", ",", "MatchResult", ">", "findOperationsConsumingSome", "(", "Set", "<", "URI", ">", "inputTypes", ")", "{", "return", "findServicesClassifiedBySome", "(", "inputTypes", ",", "LogicConceptMatchType", ".", "Plugin", ")"...
Discover registered operations that consume some (i.e., at least one) of the types of input provided. That is, all those that have as input the types provided. @param inputTypes the types of input to be consumed @return a Set containing all the matching operations. If there are no solutions, the Set should be empty, not null.
[ "Discover", "registered", "operations", "that", "consume", "some", "(", "i", ".", "e", ".", "at", "least", "one", ")", "of", "the", "types", "of", "input", "provided", ".", "That", "is", "all", "those", "that", "have", "as", "input", "the", "types", "p...
train
https://github.com/kmi/iserve/blob/13e7016e64c1d5a539b838c6debf1a5cc4aefcb7/iserve-semantic-discovery/src/main/java/uk/ac/open/kmi/iserve/discovery/disco/impl/GenericLogicDiscoverer.java#L265-L268
spring-projects/spring-loaded
springloaded/src/main/java/org/springsource/loaded/Utils.java
Utils.getExecutorName
public static String getExecutorName(String name, String versionstamp) { StringBuilder s = new StringBuilder(name); s.append("$$E"); s.append(versionstamp); return s.toString(); }
java
public static String getExecutorName(String name, String versionstamp) { StringBuilder s = new StringBuilder(name); s.append("$$E"); s.append(versionstamp); return s.toString(); }
[ "public", "static", "String", "getExecutorName", "(", "String", "name", ",", "String", "versionstamp", ")", "{", "StringBuilder", "s", "=", "new", "StringBuilder", "(", "name", ")", ";", "s", ".", "append", "(", "\"$$E\"", ")", ";", "s", ".", "append", "...
Generate the name for the executor class. Must use '$' so that it is considered by some code (eclipse debugger for example) to be an inner type of the original class (thus able to consider itself as being from the same source file). @param name the name prefix for the executor class @param versionstamp the suffix string for the executor class name @return an executor class name
[ "Generate", "the", "name", "for", "the", "executor", "class", ".", "Must", "use", "$", "so", "that", "it", "is", "considered", "by", "some", "code", "(", "eclipse", "debugger", "for", "example", ")", "to", "be", "an", "inner", "type", "of", "the", "ori...
train
https://github.com/spring-projects/spring-loaded/blob/59b32f957a05c6d9f149148158053605e2a6205a/springloaded/src/main/java/org/springsource/loaded/Utils.java#L885-L890
liferay/com-liferay-commerce
commerce-notification-api/src/main/java/com/liferay/commerce/notification/service/persistence/CommerceNotificationTemplateUtil.java
CommerceNotificationTemplateUtil.removeByG_T_E
public static void removeByG_T_E(long groupId, String type, boolean enabled) { getPersistence().removeByG_T_E(groupId, type, enabled); }
java
public static void removeByG_T_E(long groupId, String type, boolean enabled) { getPersistence().removeByG_T_E(groupId, type, enabled); }
[ "public", "static", "void", "removeByG_T_E", "(", "long", "groupId", ",", "String", "type", ",", "boolean", "enabled", ")", "{", "getPersistence", "(", ")", ".", "removeByG_T_E", "(", "groupId", ",", "type", ",", "enabled", ")", ";", "}" ]
Removes all the commerce notification templates where groupId = &#63; and type = &#63; and enabled = &#63; from the database. @param groupId the group ID @param type the type @param enabled the enabled
[ "Removes", "all", "the", "commerce", "notification", "templates", "where", "groupId", "=", "&#63", ";", "and", "type", "=", "&#63", ";", "and", "enabled", "=", "&#63", ";", "from", "the", "database", "." ]
train
https://github.com/liferay/com-liferay-commerce/blob/9e54362d7f59531fc684016ba49ee7cdc3a2f22b/commerce-notification-api/src/main/java/com/liferay/commerce/notification/service/persistence/CommerceNotificationTemplateUtil.java#L1272-L1274
mapsforge/mapsforge
sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java
DatabaseUtils.queryNumEntries
public static long queryNumEntries(SQLiteDatabase db, String table, String selection, String[] selectionArgs) { String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : ""; return longForQuery(db, "select count(*) from " + table + s, selectionArgs); }
java
public static long queryNumEntries(SQLiteDatabase db, String table, String selection, String[] selectionArgs) { String s = (!TextUtils.isEmpty(selection)) ? " where " + selection : ""; return longForQuery(db, "select count(*) from " + table + s, selectionArgs); }
[ "public", "static", "long", "queryNumEntries", "(", "SQLiteDatabase", "db", ",", "String", "table", ",", "String", "selection", ",", "String", "[", "]", "selectionArgs", ")", "{", "String", "s", "=", "(", "!", "TextUtils", ".", "isEmpty", "(", "selection", ...
Query the table for the number of rows in the table. @param db the database the table is in @param table the name of the table to query @param selection A filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will count all rows for the given table @param selectionArgs You may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings. @return the number of rows in the table filtered by the selection
[ "Query", "the", "table", "for", "the", "number", "of", "rows", "in", "the", "table", "." ]
train
https://github.com/mapsforge/mapsforge/blob/c49c83f7f727552f793dff15cefa532ade030842/sqlite-android/src/main/java/org/sqlite/database/DatabaseUtils.java#L809-L814
geomajas/geomajas-project-client-gwt2
plugin/corewidget/example-jar/src/main/java/org/geomajas/gwt2/plugin/corewidget/example/client/sample/feature/controller/FeatureClickedListener.java
FeatureClickedListener.calculateBufferFromPixelTolerance
private double calculateBufferFromPixelTolerance() { Coordinate c1 = mapPresenter.getViewPort().getTransformationService() .transform(new Coordinate(0, 0), RenderSpace.SCREEN, RenderSpace.WORLD); Coordinate c2 = mapPresenter.getViewPort().getTransformationService() .transform(new Coordinate(pixelBuffer, 0), RenderSpace.SCREEN, RenderSpace.WORLD); return c1.distance(c2); }
java
private double calculateBufferFromPixelTolerance() { Coordinate c1 = mapPresenter.getViewPort().getTransformationService() .transform(new Coordinate(0, 0), RenderSpace.SCREEN, RenderSpace.WORLD); Coordinate c2 = mapPresenter.getViewPort().getTransformationService() .transform(new Coordinate(pixelBuffer, 0), RenderSpace.SCREEN, RenderSpace.WORLD); return c1.distance(c2); }
[ "private", "double", "calculateBufferFromPixelTolerance", "(", ")", "{", "Coordinate", "c1", "=", "mapPresenter", ".", "getViewPort", "(", ")", ".", "getTransformationService", "(", ")", ".", "transform", "(", "new", "Coordinate", "(", "0", ",", "0", ")", ",",...
Calculate a buffer in which the listener may include the features from the map. @return double buffer
[ "Calculate", "a", "buffer", "in", "which", "the", "listener", "may", "include", "the", "features", "from", "the", "map", "." ]
train
https://github.com/geomajas/geomajas-project-client-gwt2/blob/bd8d7904e861fa80522eed7b83c4ea99844180c7/plugin/corewidget/example-jar/src/main/java/org/geomajas/gwt2/plugin/corewidget/example/client/sample/feature/controller/FeatureClickedListener.java#L149-L157
Metatavu/edelphi
edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java
GoogleDriveUtils.exportFile
public static DownloadResponse exportFile(Drive drive, String fileId, String format) throws IOException { try (InputStream inputStream = drive.files().export(fileId, format).executeAsInputStream()) { return new DownloadResponse(format, IOUtils.toByteArray(inputStream)); } }
java
public static DownloadResponse exportFile(Drive drive, String fileId, String format) throws IOException { try (InputStream inputStream = drive.files().export(fileId, format).executeAsInputStream()) { return new DownloadResponse(format, IOUtils.toByteArray(inputStream)); } }
[ "public", "static", "DownloadResponse", "exportFile", "(", "Drive", "drive", ",", "String", "fileId", ",", "String", "format", ")", "throws", "IOException", "{", "try", "(", "InputStream", "inputStream", "=", "drive", ".", "files", "(", ")", ".", "export", "...
Exports file in requested format @param drive drive client @param fileId id of file to be exported @param format target format @return exported data @throws IOException thrown when exporting fails unexpectedly
[ "Exports", "file", "in", "requested", "format" ]
train
https://github.com/Metatavu/edelphi/blob/d91a0b54f954b33b4ee674a1bdf03612d76c3305/edelphi/src/main/java/fi/metatavu/edelphi/utils/GoogleDriveUtils.java#L258-L262