method
stringlengths 13
441k
| clean_method
stringlengths 7
313k
| doc
stringlengths 17
17.3k
| comment
stringlengths 3
1.42k
| method_name
stringlengths 1
273
| extra
dict | imports
sequence | imports_info
stringlengths 19
34.8k
| cluster_imports_info
stringlengths 15
3.66k
| libraries
sequence | libraries_info
stringlengths 6
661
| id
int64 0
2.92M
|
---|---|---|---|---|---|---|---|---|---|---|---|
@Test
public void testDecompileClassFiles() throws DecompilationException, IOException
{
final Decompiler dec = this.getDecompiler();
Path archive = Paths.get("target/TestJars/wicket-core-6.11.0.jar");
Path decompDir = testTempDir.resolve("decompiled");
Path unzipDir = testTempDir.resolve("unzipped");
ZipUtil.unzip(archive.toFile(), unzipDir.toFile());
// DECOMPILE
Path classFile1 = unzipDir.resolve("org/apache/wicket/ajax/AbstractAjaxResponse.class");
Path classFile2 = unzipDir.resolve("org/apache/wicket/ajax/AbstractAjaxResponse$1.class");
Path classFile3 = unzipDir.resolve("org/apache/wicket/ajax/AbstractAjaxResponse$AjaxResponse.class");
Path classFile4 = unzipDir.resolve("org/apache/wicket/ajax/AbstractAjaxResponse$AjaxHeaderResponse.class");
Path classFile5 = unzipDir.resolve("org/apache/wicket/ajax/AbstractAjaxResponse$AjaxHtmlHeaderContainer.class");
List<ClassDecompileRequest> requests = new ArrayList<>();
requests.add(new ClassDecompileRequest(unzipDir, classFile1, decompDir));
requests.add(new ClassDecompileRequest(unzipDir, classFile2, decompDir));
requests.add(new ClassDecompileRequest(unzipDir, classFile3, decompDir));
requests.add(new ClassDecompileRequest(unzipDir, classFile4, decompDir));
requests.add(new ClassDecompileRequest(unzipDir, classFile5, decompDir)); | void function() throws DecompilationException, IOException { final Decompiler dec = this.getDecompiler(); Path archive = Paths.get(STR); Path decompDir = testTempDir.resolve(STR); Path unzipDir = testTempDir.resolve(STR); ZipUtil.unzip(archive.toFile(), unzipDir.toFile()); Path classFile1 = unzipDir.resolve(STR); Path classFile2 = unzipDir.resolve(STR); Path classFile3 = unzipDir.resolve(STR); Path classFile4 = unzipDir.resolve(STR); Path classFile5 = unzipDir.resolve(STR); List<ClassDecompileRequest> requests = new ArrayList<>(); requests.add(new ClassDecompileRequest(unzipDir, classFile1, decompDir)); requests.add(new ClassDecompileRequest(unzipDir, classFile2, decompDir)); requests.add(new ClassDecompileRequest(unzipDir, classFile3, decompDir)); requests.add(new ClassDecompileRequest(unzipDir, classFile4, decompDir)); requests.add(new ClassDecompileRequest(unzipDir, classFile5, decompDir)); | /**
* Tests the {@link FernflowerDecompiler#decompileClassFiles(Collection, DecompilationListener)} method.
*/ | Tests the <code>FernflowerDecompiler#decompileClassFiles(Collection, DecompilationListener)</code> method | testDecompileClassFiles | {
"repo_name": "lincolnthree/windup",
"path": "decompiler/impl-fernflower/src/test/java/org/jboss/windup/decompiler/fernflower/FernflowerDecompilerTest.java",
"license": "epl-1.0",
"size": 3705
} | [
"java.io.IOException",
"java.nio.file.Path",
"java.nio.file.Paths",
"java.util.ArrayList",
"java.util.List",
"org.jboss.windup.decompiler.api.ClassDecompileRequest",
"org.jboss.windup.decompiler.api.DecompilationException",
"org.jboss.windup.decompiler.api.Decompiler",
"org.jboss.windup.decompiler.util.ZipUtil"
] | import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.jboss.windup.decompiler.api.ClassDecompileRequest; import org.jboss.windup.decompiler.api.DecompilationException; import org.jboss.windup.decompiler.api.Decompiler; import org.jboss.windup.decompiler.util.ZipUtil; | import java.io.*; import java.nio.file.*; import java.util.*; import org.jboss.windup.decompiler.api.*; import org.jboss.windup.decompiler.util.*; | [
"java.io",
"java.nio",
"java.util",
"org.jboss.windup"
] | java.io; java.nio; java.util; org.jboss.windup; | 1,037,001 |
public BlockConditionsDTO getBlockCondition(int conditionId) throws APIManagementException {
Connection connection = null;
PreparedStatement selectPreparedStatement = null;
ResultSet resultSet = null;
BlockConditionsDTO blockCondition = null;
try {
String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_SQL;
connection = APIMgtDBUtil.getConnection();
connection.setAutoCommit(true);
selectPreparedStatement = connection.prepareStatement(query);
selectPreparedStatement.setInt(1, conditionId);
resultSet = selectPreparedStatement.executeQuery();
if (resultSet.next()) {
blockCondition = new BlockConditionsDTO();
blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
blockCondition.setConditionType(resultSet.getString("TYPE"));
blockCondition.setConditionValue(resultSet.getString("VALUE"));
blockCondition.setConditionId(conditionId);
blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
blockCondition.setUUID(resultSet.getString("UUID"));
}
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
handleException("Failed to rollback getting Block condition with id " + conditionId, ex);
}
}
handleException("Failed to get Block condition with id " + conditionId, e);
} finally {
APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
}
return blockCondition;
} | BlockConditionsDTO function(int conditionId) throws APIManagementException { Connection connection = null; PreparedStatement selectPreparedStatement = null; ResultSet resultSet = null; BlockConditionsDTO blockCondition = null; try { String query = SQLConstants.ThrottleSQLConstants.GET_BLOCK_CONDITION_SQL; connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(true); selectPreparedStatement = connection.prepareStatement(query); selectPreparedStatement.setInt(1, conditionId); resultSet = selectPreparedStatement.executeQuery(); if (resultSet.next()) { blockCondition = new BlockConditionsDTO(); blockCondition.setEnabled(resultSet.getBoolean(STR)); blockCondition.setConditionType(resultSet.getString("TYPE")); blockCondition.setConditionValue(resultSet.getString("VALUE")); blockCondition.setConditionId(conditionId); blockCondition.setTenantDomain(resultSet.getString(STR)); blockCondition.setUUID(resultSet.getString("UUID")); } } catch (SQLException e) { if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { handleException(STR + conditionId, ex); } } handleException(STR + conditionId, e); } finally { APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet); } return blockCondition; } | /**
* Get details of a block condition by Id
*
* @param conditionId id of the condition
* @return Block conditoin represented by the UUID
* @throws APIManagementException
*/ | Get details of a block condition by Id | getBlockCondition | {
"repo_name": "knPerera/carbon-apimgt",
"path": "components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java",
"license": "apache-2.0",
"size": 493075
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.ResultSet",
"java.sql.SQLException",
"org.wso2.carbon.apimgt.api.APIManagementException",
"org.wso2.carbon.apimgt.api.model.BlockConditionsDTO",
"org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants",
"org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; | import java.sql.*; import org.wso2.carbon.apimgt.api.*; import org.wso2.carbon.apimgt.api.model.*; import org.wso2.carbon.apimgt.impl.dao.constants.*; import org.wso2.carbon.apimgt.impl.utils.*; | [
"java.sql",
"org.wso2.carbon"
] | java.sql; org.wso2.carbon; | 1,052,175 |
public void execute(Runnable onSuccess, ICallback<Pair<String, Throwable>> onFailure) {
doLoad(0, onSuccess, onFailure);
} | void function(Runnable onSuccess, ICallback<Pair<String, Throwable>> onFailure) { doLoad(0, onSuccess, onFailure); } | /**
* Attempt to load page objects.
* Because most/all of the work is asynchronous, the eventual success or failure
* will be reported via the onSuccess and onFailure callbacks.
*
* @param onSuccess callback if all page objects are loaded successfully
* @param onFailure callback if any of the page objects can't be loaded
*/ | Attempt to load page objects. Because most/all of the work is asynchronous, the eventual success or failure will be reported via the onSuccess and onFailure callbacks | execute | {
"repo_name": "aayushmudgal/CloudCoder",
"path": "CloudCoder/src/org/cloudcoder/app/client/page/LoadPageObjects.java",
"license": "agpl-3.0",
"size": 13472
} | [
"org.cloudcoder.app.shared.model.ICallback",
"org.cloudcoder.app.shared.model.Pair"
] | import org.cloudcoder.app.shared.model.ICallback; import org.cloudcoder.app.shared.model.Pair; | import org.cloudcoder.app.shared.model.*; | [
"org.cloudcoder.app"
] | org.cloudcoder.app; | 547,119 |
public SensorLocation getLocation(String id) throws IdNotFoundException; | SensorLocation function(String id) throws IdNotFoundException; | /**
* Retrieves the Location with the given id from the WattDepot Server.
*
* @param id
* The Location's id.
* @return the Location with the given id or null.
* @exception IdNotFoundException
* if the given id is not a Location's id.
*/ | Retrieves the Location with the given id from the WattDepot Server | getLocation | {
"repo_name": "cammoore/wattdepot3",
"path": "src/main/java/org/wattdepot3/client/WattDepotInterface.java",
"license": "gpl-3.0",
"size": 13247
} | [
"org.wattdepot3.datamodel.SensorLocation",
"org.wattdepot3.exception.IdNotFoundException"
] | import org.wattdepot3.datamodel.SensorLocation; import org.wattdepot3.exception.IdNotFoundException; | import org.wattdepot3.datamodel.*; import org.wattdepot3.exception.*; | [
"org.wattdepot3.datamodel",
"org.wattdepot3.exception"
] | org.wattdepot3.datamodel; org.wattdepot3.exception; | 135,600 |
public CreatePathResult createPath(RpcContext rpcContext, LockedInodePath inodePath,
CreatePathOptions<?> options) throws FileAlreadyExistsException, BlockInfoException,
InvalidPathException, IOException, FileDoesNotExistException {
// TODO(gpang): consider splitting this into createFilePath and createDirectoryPath, with a
// helper method for the shared logic.
AlluxioURI path = inodePath.getUri();
if (path.isRoot()) {
String errorMessage = ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(path);
LOG.error(errorMessage);
throw new FileAlreadyExistsException(errorMessage);
}
if (inodePath.fullPathExists()) {
if (!(options instanceof CreateDirectoryOptions)
|| !((CreateDirectoryOptions) options).isAllowExists()) {
throw new FileAlreadyExistsException(path);
}
}
if (options instanceof CreateFileOptions) {
CreateFileOptions fileOptions = (CreateFileOptions) options;
if (fileOptions.getBlockSizeBytes() < 1) {
throw new BlockInfoException("Invalid block size " + fileOptions.getBlockSizeBytes());
}
}
if (!(inodePath instanceof MutableLockedInodePath)) {
throw new InvalidPathException(
ExceptionMessage.NOT_MUTABLE_INODE_PATH.getMessage(inodePath.getUri()));
}
LOG.debug("createPath {}", path);
TraversalResult traversalResult = traverseToInode(inodePath, inodePath.getLockPattern());
MutableLockedInodePath extensibleInodePath = (MutableLockedInodePath) inodePath;
String[] pathComponents = extensibleInodePath.getPathComponents();
String name = path.getName();
// pathIndex is the index into pathComponents where we start filling in the path from the inode.
int pathIndex = extensibleInodePath.size();
if (pathIndex < pathComponents.length - 1) {
// The immediate parent was not found. If it's not recursive, we throw an exception here.
// Otherwise we add the remaining path components to the list of components to create.
if (!options.isRecursive()) {
final String msg = new StringBuilder().append("File ").append(path)
.append(" creation failed. Component ")
.append(pathIndex).append("(")
.append(pathComponents[pathIndex])
.append(") does not exist").toString();
LOG.error("FileDoesNotExistException: {}", msg);
throw new FileDoesNotExistException(msg);
}
}
// The ancestor inode (parent or ancestor) of the target path.
InodeView ancestorInode = extensibleInodePath.getAncestorInode();
if (!ancestorInode.isDirectory()) {
throw new InvalidPathException("Could not traverse to parent directory of path " + path
+ ". Component " + pathComponents[pathIndex - 1] + " is not a directory.");
}
InodeDirectoryView currentInodeDirectory = (InodeDirectoryView) ancestorInode;
List<InodeView> createdInodes = new ArrayList<>();
List<InodeView> modifiedInodes = new ArrayList<>();
if (options.isPersisted()) {
// Synchronously persist directories. These inodes are already READ locked.
for (InodeView inode : traversalResult.getNonPersisted()) {
// This cast is safe because we've already verified that the file inode doesn't exist.
syncPersistExistingDirectory(rpcContext, (InodeDirectoryView) inode);
}
}
if ((pathIndex < (pathComponents.length - 1) || currentInodeDirectory.getChild(name) == null)
&& options.getOperationTimeMs() > currentInodeDirectory.getLastModificationTimeMs()) {
// (1) There are components in parent paths that need to be created. Or
// (2) The last component of the path needs to be created.
// In these two cases, the last traversed Inode will be modified if the new timestamp is after
// the existing last modified time.
mState.applyAndJournal(rpcContext, UpdateInodeEntry.newBuilder()
.setId(currentInodeDirectory.getId())
.setLastModificationTimeMs(options.getOperationTimeMs())
.build());
modifiedInodes.add(currentInodeDirectory);
}
// Fill in the ancestor directories that were missing.
// NOTE, we set the mode of missing ancestor directories to be the default value, rather
// than inheriting the option of the final file to create, because it may not have
// "execute" permission.
CreateDirectoryOptions missingDirOptions = CreateDirectoryOptions.defaults()
.setMountPoint(false)
.setPersisted(options.isPersisted())
.setOperationTimeMs(options.getOperationTimeMs())
.setOwner(options.getOwner())
.setGroup(options.getGroup())
.setTtl(options.getTtl())
.setTtlAction(options.getTtlAction());
for (int k = pathIndex; k < (pathComponents.length - 1); k++) {
InodeDirectoryView dir = null;
while (dir == null) {
InodeDirectory newDir = InodeDirectory.create(
mDirectoryIdGenerator.getNewDirectoryId(rpcContext.getJournalContext()),
currentInodeDirectory.getId(), pathComponents[k], missingDirOptions);
// Lock the newly created inode before subsequent operations, and add it to the lock group.
extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newDir,
currentInodeDirectory, pathComponents[k]);
newDir.setPinned(currentInodeDirectory.isPinned());
// if the parent has default ACL, copy that default ACL as the new directory's default
// and access acl, ANDed with the umask
// if it is part of a metadata load operation, we ignore the umask and simply inherit
// the default ACL as the directory's new default and access ACL
short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort()
: newDir.getMode();
DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL();
if (!dAcl.isEmpty()) {
Pair<AccessControlList, DefaultAccessControlList> pair =
dAcl.generateChildDirACL(mode);
newDir.setInternalAcl(pair.getFirst());
newDir.setDefaultACL(pair.getSecond());
}
if (mState.applyAndJournal(rpcContext, newDir)) {
// After creation and journaling, downgrade to a read lock.
extensibleInodePath.getLockList().downgradeLast();
dir = newDir;
} else {
// The child directory inode already exists. Get the existing child inode.
extensibleInodePath.getLockList().unlockLast();
InodeView existing = currentInodeDirectory.getChildReadLock(pathComponents[k],
extensibleInodePath.getLockList());
if (existing == null) {
// The competing directory could have been removed.
continue;
}
if (existing.isFile()) {
throw new FileAlreadyExistsException(String.format(
"Directory creation for %s failed. Inode %s is a file", path, existing.getName()));
}
dir = (InodeDirectoryView) existing;
}
// Persist the directory *after* it exists in the inode tree. This prevents multiple
// concurrent creates from trying to persist the same directory name.
if (options.isPersisted()) {
syncPersistExistingDirectory(rpcContext, dir);
}
}
createdInodes.add(dir);
currentInodeDirectory = dir;
}
// Create the final path component. First we need to make sure that there isn't already a file
// here with that name. If there is an existing file that is a directory and we're creating a
// directory, update persistence property of the directories if needed, otherwise, throw
// FileAlreadyExistsException unless options.allowExists is true.
while (true) {
// Try to lock the last inode with the lock mode of the path.
InodeView lastLockedInode;
switch (extensibleInodePath.getLockPattern()) {
case READ:
lastLockedInode = currentInodeDirectory.getChildReadLock(name,
extensibleInodePath.getLockList());
break;
case WRITE_LAST:
lastLockedInode = currentInodeDirectory.getChildWriteLock(name,
extensibleInodePath.getLockList());
break;
default:
// This should not be reachable.
throw new IllegalStateException(String.format("Unexpected lock mode encountered: %s",
extensibleInodePath.getLockPattern()));
}
if (lastLockedInode != null) {
// inode to create already exists
// We need to remove the last inode from the locklist because it was locked during
// traversal and locked here again
extensibleInodePath.getLockList().unlockLast();
if (lastLockedInode.isDirectory() && options instanceof CreateDirectoryOptions
&& !lastLockedInode.isPersisted() && options.isPersisted()) {
// The final path component already exists and is not persisted, so it should be added
// to the non-persisted Inodes of traversalResult.
syncPersistExistingDirectory(rpcContext, (InodeDirectoryView) lastLockedInode);
} else if (!lastLockedInode.isDirectory() || !(options instanceof CreateDirectoryOptions
&& ((CreateDirectoryOptions) options).isAllowExists())) {
String errorMessage = ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(path);
LOG.error(errorMessage);
throw new FileAlreadyExistsException(errorMessage);
}
break;
}
Inode<?> newInode;
// create the new inode, with a write lock
if (options instanceof CreateDirectoryOptions) {
CreateDirectoryOptions directoryOptions = (CreateDirectoryOptions) options;
InodeDirectory newDir = InodeDirectory.create(
mDirectoryIdGenerator.getNewDirectoryId(rpcContext.getJournalContext()),
currentInodeDirectory.getId(), name, directoryOptions);
// Lock the created inode before subsequent operations, and add it to the lock group.
extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newDir,
currentInodeDirectory, name);
// if the parent has default ACL, take the default ACL ANDed with the umask as the new
// directory's default and access acl
// WHen it is a metadata load operation, do not take the umask into account
short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort()
: newDir.getMode();
DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL();
if (!dAcl.isEmpty()) {
Pair<AccessControlList, DefaultAccessControlList> pair =
dAcl.generateChildDirACL(mode);
newDir.setInternalAcl(pair.getFirst());
newDir.setDefaultACL(pair.getSecond());
}
if (directoryOptions.isPersisted()) {
// Do not journal the persist entry, since a creation entry will be journaled instead.
if (options.isMetadataLoad()) {
// if we are creating the file as a result of loading metadata, the newDir is already
// persisted, and we got the permissions info from the ufs.
newDir.setOwner(options.getOwner())
.setGroup(options.getGroup())
.setMode(options.getMode().toShort());
Long lastModificationTime = options.getOperationTimeMs();
if (lastModificationTime != null) {
newDir.setLastModificationTimeMs(lastModificationTime, true);
}
newDir.setPersistenceState(PersistenceState.PERSISTED);
} else {
syncPersistNewDirectory(newDir);
}
}
newInode = newDir;
} else if (options instanceof CreateFileOptions) {
CreateFileOptions fileOptions = (CreateFileOptions) options;
InodeFile newFile = InodeFile.create(mContainerIdGenerator.getNewContainerId(),
currentInodeDirectory.getId(), name, System.currentTimeMillis(), fileOptions);
// Lock the created inode before subsequent operations, and add it to the lock group.
extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newFile,
currentInodeDirectory, name);
// if the parent has a default ACL, copy that default ACL ANDed with the umask as the new
// file's access ACL.
// If it is a metadata load operation, do not consider the umask.
DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL();
short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort()
: newFile.getMode();
if (!dAcl.isEmpty()) {
AccessControlList acl = dAcl.generateChildFileACL(mode);
newFile.setInternalAcl(acl);
}
if (fileOptions.isCacheable()) {
newFile.setCacheable(true);
}
newInode = newFile;
} else {
throw new IllegalStateException(String.format("Unrecognized create options: %s", options));
}
newInode.setPinned(currentInodeDirectory.isPinned());
if (!mState.applyAndJournal(rpcContext, newInode)) {
// Could not add the child inode to the parent. Continue and try again.
// Cleanup is not necessary, since other state is updated later, after a successful add.
extensibleInodePath.getLockList().unlockLast();
continue;
}
createdInodes.add(newInode);
LOG.debug("createFile: File Created: {} parent: {}", newInode, currentInodeDirectory);
break;
}
return new CreatePathResult(modifiedInodes, createdInodes);
} | CreatePathResult function(RpcContext rpcContext, LockedInodePath inodePath, CreatePathOptions<?> options) throws FileAlreadyExistsException, BlockInfoException, InvalidPathException, IOException, FileDoesNotExistException { AlluxioURI path = inodePath.getUri(); if (path.isRoot()) { String errorMessage = ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(path); LOG.error(errorMessage); throw new FileAlreadyExistsException(errorMessage); } if (inodePath.fullPathExists()) { if (!(options instanceof CreateDirectoryOptions) !((CreateDirectoryOptions) options).isAllowExists()) { throw new FileAlreadyExistsException(path); } } if (options instanceof CreateFileOptions) { CreateFileOptions fileOptions = (CreateFileOptions) options; if (fileOptions.getBlockSizeBytes() < 1) { throw new BlockInfoException(STR + fileOptions.getBlockSizeBytes()); } } if (!(inodePath instanceof MutableLockedInodePath)) { throw new InvalidPathException( ExceptionMessage.NOT_MUTABLE_INODE_PATH.getMessage(inodePath.getUri())); } LOG.debug(STR, path); TraversalResult traversalResult = traverseToInode(inodePath, inodePath.getLockPattern()); MutableLockedInodePath extensibleInodePath = (MutableLockedInodePath) inodePath; String[] pathComponents = extensibleInodePath.getPathComponents(); String name = path.getName(); int pathIndex = extensibleInodePath.size(); if (pathIndex < pathComponents.length - 1) { if (!options.isRecursive()) { final String msg = new StringBuilder().append(STR).append(path) .append(STR) .append(pathIndex).append("(") .append(pathComponents[pathIndex]) .append(STR).toString(); LOG.error(STR, msg); throw new FileDoesNotExistException(msg); } } InodeView ancestorInode = extensibleInodePath.getAncestorInode(); if (!ancestorInode.isDirectory()) { throw new InvalidPathException(STR + path + STR + pathComponents[pathIndex - 1] + STR); } InodeDirectoryView currentInodeDirectory = (InodeDirectoryView) ancestorInode; List<InodeView> createdInodes = new ArrayList<>(); List<InodeView> modifiedInodes = new ArrayList<>(); if (options.isPersisted()) { for (InodeView inode : traversalResult.getNonPersisted()) { syncPersistExistingDirectory(rpcContext, (InodeDirectoryView) inode); } } if ((pathIndex < (pathComponents.length - 1) currentInodeDirectory.getChild(name) == null) && options.getOperationTimeMs() > currentInodeDirectory.getLastModificationTimeMs()) { mState.applyAndJournal(rpcContext, UpdateInodeEntry.newBuilder() .setId(currentInodeDirectory.getId()) .setLastModificationTimeMs(options.getOperationTimeMs()) .build()); modifiedInodes.add(currentInodeDirectory); } CreateDirectoryOptions missingDirOptions = CreateDirectoryOptions.defaults() .setMountPoint(false) .setPersisted(options.isPersisted()) .setOperationTimeMs(options.getOperationTimeMs()) .setOwner(options.getOwner()) .setGroup(options.getGroup()) .setTtl(options.getTtl()) .setTtlAction(options.getTtlAction()); for (int k = pathIndex; k < (pathComponents.length - 1); k++) { InodeDirectoryView dir = null; while (dir == null) { InodeDirectory newDir = InodeDirectory.create( mDirectoryIdGenerator.getNewDirectoryId(rpcContext.getJournalContext()), currentInodeDirectory.getId(), pathComponents[k], missingDirOptions); extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newDir, currentInodeDirectory, pathComponents[k]); newDir.setPinned(currentInodeDirectory.isPinned()); short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort() : newDir.getMode(); DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL(); if (!dAcl.isEmpty()) { Pair<AccessControlList, DefaultAccessControlList> pair = dAcl.generateChildDirACL(mode); newDir.setInternalAcl(pair.getFirst()); newDir.setDefaultACL(pair.getSecond()); } if (mState.applyAndJournal(rpcContext, newDir)) { extensibleInodePath.getLockList().downgradeLast(); dir = newDir; } else { extensibleInodePath.getLockList().unlockLast(); InodeView existing = currentInodeDirectory.getChildReadLock(pathComponents[k], extensibleInodePath.getLockList()); if (existing == null) { continue; } if (existing.isFile()) { throw new FileAlreadyExistsException(String.format( STR, path, existing.getName())); } dir = (InodeDirectoryView) existing; } if (options.isPersisted()) { syncPersistExistingDirectory(rpcContext, dir); } } createdInodes.add(dir); currentInodeDirectory = dir; } while (true) { InodeView lastLockedInode; switch (extensibleInodePath.getLockPattern()) { case READ: lastLockedInode = currentInodeDirectory.getChildReadLock(name, extensibleInodePath.getLockList()); break; case WRITE_LAST: lastLockedInode = currentInodeDirectory.getChildWriteLock(name, extensibleInodePath.getLockList()); break; default: throw new IllegalStateException(String.format(STR, extensibleInodePath.getLockPattern())); } if (lastLockedInode != null) { extensibleInodePath.getLockList().unlockLast(); if (lastLockedInode.isDirectory() && options instanceof CreateDirectoryOptions && !lastLockedInode.isPersisted() && options.isPersisted()) { syncPersistExistingDirectory(rpcContext, (InodeDirectoryView) lastLockedInode); } else if (!lastLockedInode.isDirectory() !(options instanceof CreateDirectoryOptions && ((CreateDirectoryOptions) options).isAllowExists())) { String errorMessage = ExceptionMessage.FILE_ALREADY_EXISTS.getMessage(path); LOG.error(errorMessage); throw new FileAlreadyExistsException(errorMessage); } break; } Inode<?> newInode; if (options instanceof CreateDirectoryOptions) { CreateDirectoryOptions directoryOptions = (CreateDirectoryOptions) options; InodeDirectory newDir = InodeDirectory.create( mDirectoryIdGenerator.getNewDirectoryId(rpcContext.getJournalContext()), currentInodeDirectory.getId(), name, directoryOptions); extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newDir, currentInodeDirectory, name); short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort() : newDir.getMode(); DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL(); if (!dAcl.isEmpty()) { Pair<AccessControlList, DefaultAccessControlList> pair = dAcl.generateChildDirACL(mode); newDir.setInternalAcl(pair.getFirst()); newDir.setDefaultACL(pair.getSecond()); } if (directoryOptions.isPersisted()) { if (options.isMetadataLoad()) { newDir.setOwner(options.getOwner()) .setGroup(options.getGroup()) .setMode(options.getMode().toShort()); Long lastModificationTime = options.getOperationTimeMs(); if (lastModificationTime != null) { newDir.setLastModificationTimeMs(lastModificationTime, true); } newDir.setPersistenceState(PersistenceState.PERSISTED); } else { syncPersistNewDirectory(newDir); } } newInode = newDir; } else if (options instanceof CreateFileOptions) { CreateFileOptions fileOptions = (CreateFileOptions) options; InodeFile newFile = InodeFile.create(mContainerIdGenerator.getNewContainerId(), currentInodeDirectory.getId(), name, System.currentTimeMillis(), fileOptions); extensibleInodePath.getLockList().lockWriteAndCheckNameAndParent(newFile, currentInodeDirectory, name); DefaultAccessControlList dAcl = currentInodeDirectory.getDefaultACL(); short mode = options.isMetadataLoad() ? Mode.createFullAccess().toShort() : newFile.getMode(); if (!dAcl.isEmpty()) { AccessControlList acl = dAcl.generateChildFileACL(mode); newFile.setInternalAcl(acl); } if (fileOptions.isCacheable()) { newFile.setCacheable(true); } newInode = newFile; } else { throw new IllegalStateException(String.format(STR, options)); } newInode.setPinned(currentInodeDirectory.isPinned()); if (!mState.applyAndJournal(rpcContext, newInode)) { extensibleInodePath.getLockList().unlockLast(); continue; } createdInodes.add(newInode); LOG.debug(STR, newInode, currentInodeDirectory); break; } return new CreatePathResult(modifiedInodes, createdInodes); } | /**
* Creates a file or directory at path.
*
* @param rpcContext the rpc context
* @param inodePath the path
* @param options method options
* @return a {@link CreatePathResult} representing the modified inodes and created inodes during
* path creation
* @throws FileAlreadyExistsException when there is already a file at path if we want to create a
* directory there
* @throws BlockInfoException when blockSizeBytes is invalid
* @throws InvalidPathException when path is invalid, for example, (1) when there is nonexistent
* necessary parent directories and recursive is false, (2) when one of the necessary
* parent directories is actually a file
* @throws FileDoesNotExistException if the parent of the path does not exist and the recursive
* option is false
*/ | Creates a file or directory at path | createPath | {
"repo_name": "aaudiber/alluxio",
"path": "core/server/master/src/main/java/alluxio/master/file/meta/InodeTree.java",
"license": "apache-2.0",
"size": 61702
} | [
"java.io.IOException",
"java.util.ArrayList",
"java.util.List"
] | import java.io.IOException; import java.util.ArrayList; import java.util.List; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 2,729,578 |
@Override
public List<Identity> getNewIdentityCreated(final Date from) {
if (from == null) { return Collections.emptyList(); }
final BaseSecurity manager = BaseSecurityManager.getInstance();
final PermissionOnResourceable[] permissions = { new PermissionOnResourceable(Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY) };
final List<Identity> guests = manager
.getIdentitiesByPowerSearch(null, null, true, null, permissions, null, from, null, null, null, Identity.STATUS_VISIBLE_LIMIT);
final List<Identity> identities = manager.getIdentitiesByPowerSearch(null, null, true, null, null, null, from, null, null, null, Identity.STATUS_VISIBLE_LIMIT);
if (!identities.isEmpty() && !guests.isEmpty()) {
identities.removeAll(guests);
}
for (final Iterator<Identity> identityIt = identities.iterator(); identityIt.hasNext();) {
final Identity identity = identityIt.next();
if (identity.getCreationDate().before(from)) {
identityIt.remove();
}
}
return identities;
} | List<Identity> function(final Date from) { if (from == null) { return Collections.emptyList(); } final BaseSecurity manager = BaseSecurityManager.getInstance(); final PermissionOnResourceable[] permissions = { new PermissionOnResourceable(Constants.PERMISSION_HASROLE, Constants.ORESOURCE_GUESTONLY) }; final List<Identity> guests = manager .getIdentitiesByPowerSearch(null, null, true, null, permissions, null, from, null, null, null, Identity.STATUS_VISIBLE_LIMIT); final List<Identity> identities = manager.getIdentitiesByPowerSearch(null, null, true, null, null, null, from, null, null, null, Identity.STATUS_VISIBLE_LIMIT); if (!identities.isEmpty() && !guests.isEmpty()) { identities.removeAll(guests); } for (final Iterator<Identity> identityIt = identities.iterator(); identityIt.hasNext();) { final Identity identity = identityIt.next(); if (identity.getCreationDate().before(from)) { identityIt.remove(); } } return identities; } | /**
* The search in the ManagerFactory is date based and not timestamp based. The guest are also removed from the list.
*/ | The search in the ManagerFactory is date based and not timestamp based. The guest are also removed from the list | getNewIdentityCreated | {
"repo_name": "RLDevOps/Scholastic",
"path": "src/main/java/org/olat/user/notification/UsersSubscriptionManagerImpl.java",
"license": "apache-2.0",
"size": 6173
} | [
"java.util.Collections",
"java.util.Date",
"java.util.Iterator",
"java.util.List",
"org.olat.basesecurity.BaseSecurity",
"org.olat.basesecurity.BaseSecurityManager",
"org.olat.basesecurity.Constants",
"org.olat.basesecurity.PermissionOnResourceable",
"org.olat.core.id.Identity"
] | import java.util.Collections; import java.util.Date; import java.util.Iterator; import java.util.List; import org.olat.basesecurity.BaseSecurity; import org.olat.basesecurity.BaseSecurityManager; import org.olat.basesecurity.Constants; import org.olat.basesecurity.PermissionOnResourceable; import org.olat.core.id.Identity; | import java.util.*; import org.olat.basesecurity.*; import org.olat.core.id.*; | [
"java.util",
"org.olat.basesecurity",
"org.olat.core"
] | java.util; org.olat.basesecurity; org.olat.core; | 1,064,663 |
public AuthToken getToken() {
return caller.getToken();
} | AuthToken function() { return caller.getToken(); } | /** Get the token this client uses to communicate with the server.
* @return the authorization token.
*/ | Get the token this client uses to communicate with the server | getToken | {
"repo_name": "arfathpasha/kb_cufflinks",
"path": "lib/src/us/kbase/kbcufflinks/KbCufflinksClient.java",
"license": "mit",
"size": 10743
} | [
"us.kbase.auth.AuthToken"
] | import us.kbase.auth.AuthToken; | import us.kbase.auth.*; | [
"us.kbase.auth"
] | us.kbase.auth; | 585,054 |
public static <E> ArrayList<E> readArrayList(DataInput in)
throws IOException, ClassNotFoundException {
InternalDataSerializer.checkIn(in);
int size = InternalDataSerializer.readArrayLength(in);
if (size == -1) {
return null;
} else {
ArrayList<E> list = new ArrayList<E>(size);
for (int i = 0; i < size; i++) {
E element = DataSerializer.<E>readObject(in);
list.add(element);
}
if (logger.isTraceEnabled(LogMarker.SERIALIZER)) {
logger.trace(LogMarker.SERIALIZER, "Read ArrayList with {} elements: {}", size, list);
}
return list;
}
} | static <E> ArrayList<E> function(DataInput in) throws IOException, ClassNotFoundException { InternalDataSerializer.checkIn(in); int size = InternalDataSerializer.readArrayLength(in); if (size == -1) { return null; } else { ArrayList<E> list = new ArrayList<E>(size); for (int i = 0; i < size; i++) { E element = DataSerializer.<E>readObject(in); list.add(element); } if (logger.isTraceEnabled(LogMarker.SERIALIZER)) { logger.trace(LogMarker.SERIALIZER, STR, size, list); } return list; } } | /**
* Reads an <code>ArrayList</code> from a <code>DataInput</code>.
*
* @throws IOException
* A problem occurs while reading from <code>in</code>
* @throws ClassNotFoundException
* The class of one of the <Code>ArrayList</code>'s
* elements cannot be found.
*
* @see #writeArrayList
*/ | Reads an <code>ArrayList</code> from a <code>DataInput</code> | readArrayList | {
"repo_name": "sshcherbakov/incubator-geode",
"path": "gemfire-core/src/main/java/com/gemstone/gemfire/DataSerializer.java",
"license": "apache-2.0",
"size": 109153
} | [
"com.gemstone.gemfire.internal.InternalDataSerializer",
"com.gemstone.gemfire.internal.logging.log4j.LogMarker",
"java.io.DataInput",
"java.io.IOException",
"java.util.ArrayList"
] | import com.gemstone.gemfire.internal.InternalDataSerializer; import com.gemstone.gemfire.internal.logging.log4j.LogMarker; import java.io.DataInput; import java.io.IOException; import java.util.ArrayList; | import com.gemstone.gemfire.internal.*; import com.gemstone.gemfire.internal.logging.log4j.*; import java.io.*; import java.util.*; | [
"com.gemstone.gemfire",
"java.io",
"java.util"
] | com.gemstone.gemfire; java.io; java.util; | 2,384,479 |
public String getGbLeft() {
long space = size;
space/=1024L; // convert to KB
space/=1024L; // convert to MB
return new BigDecimal(space).scaleByPowerOfTen(-3).toPlainString();
} | String function() { long space = size; space/=1024L; space/=1024L; return new BigDecimal(space).scaleByPowerOfTen(-3).toPlainString(); } | /**
* Gets GB left.
*/ | Gets GB left | getGbLeft | {
"repo_name": "ErikVerheul/jenkins",
"path": "core/src/main/java/hudson/node_monitors/DiskSpaceMonitorDescriptor.java",
"license": "mit",
"size": 6290
} | [
"java.math.BigDecimal"
] | import java.math.BigDecimal; | import java.math.*; | [
"java.math"
] | java.math; | 2,016,927 |
public static String formatISO8601(final Date date, final TimeZone timeZone) {
final DateFormat dateFormat = createDateFormat(ISO_8601_DATE_PATTERN,
timeZone);
return formatDate(date, dateFormat, ':', false);
} | static String function(final Date date, final TimeZone timeZone) { final DateFormat dateFormat = createDateFormat(ISO_8601_DATE_PATTERN, timeZone); return formatDate(date, dateFormat, ':', false); } | /**
* Formats the date according to ISO 8601 standard.
*
* @param date
* The date time to format
* @param timeZone
* The time zone used to format the date
* @return a formatted date according to ISO 8601
*/ | Formats the date according to ISO 8601 standard | formatISO8601 | {
"repo_name": "Guronzan/Apache-XmlGraphics",
"path": "src/main/java/org/apache/xmlgraphics/util/DateFormatUtil.java",
"license": "apache-2.0",
"size": 6648
} | [
"java.text.DateFormat",
"java.util.Date",
"java.util.TimeZone"
] | import java.text.DateFormat; import java.util.Date; import java.util.TimeZone; | import java.text.*; import java.util.*; | [
"java.text",
"java.util"
] | java.text; java.util; | 206,885 |
public static void getChars(@NotNull CharSequence src, @NotNull char[] dst, int dstOffset, int len) {
getChars(src, dst, 0, dstOffset, len);
} | static void function(@NotNull CharSequence src, @NotNull char[] dst, int dstOffset, int len) { getChars(src, dst, 0, dstOffset, len); } | /**
* Copies necessary number of symbols from the given char sequence start to the given array.
*
* @param src source data holder
* @param dst output data buffer
* @param dstOffset start offset to use within the given output data buffer
* @param len number of source data symbols to copy to the given buffer
*/ | Copies necessary number of symbols from the given char sequence start to the given array | getChars | {
"repo_name": "ernestp/consulo",
"path": "platform/util/src/com/intellij/util/text/CharArrayUtil.java",
"license": "apache-2.0",
"size": 21283
} | [
"org.jetbrains.annotations.NotNull"
] | import org.jetbrains.annotations.NotNull; | import org.jetbrains.annotations.*; | [
"org.jetbrains.annotations"
] | org.jetbrains.annotations; | 2,338,416 |
protected static Map<MapiPropertyType, MapiTypeConverterMapEntry>
getMapiTypeConverterMap() {
return mapiTypeConverterMap.getMember();
}
| static Map<MapiPropertyType, MapiTypeConverterMapEntry> function() { return mapiTypeConverterMap.getMember(); } | /**
* Gets the MAPI type converter map.
*
* @return the mapi type converter map
*/ | Gets the MAPI type converter map | getMapiTypeConverterMap | {
"repo_name": "daitangio/exchangews",
"path": "src/main/java/microsoft/exchange/webservices/data/MapiTypeConverter.java",
"license": "lgpl-3.0",
"size": 13825
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 1,795,660 |
@NonNull
public ListBuilder addSelection(@NonNull SelectionBuilder selectionBuilder) {
mImpl.addSelection(selectionBuilder);
return this;
}
public static class RangeBuilder {
private int mValue;
private int mMax = 100;
private boolean mValueSet = false;
private CharSequence mTitle;
private CharSequence mSubtitle;
private SliceAction mPrimaryAction;
private CharSequence mContentDescription;
private int mLayoutDirection = -1;
private int mMode = RANGE_MODE_DETERMINATE;
private IconCompat mTitleIcon;
private int mTitleImageMode;
private boolean mTitleItemLoading;
public RangeBuilder() {
} | ListBuilder function(@NonNull SelectionBuilder selectionBuilder) { mImpl.addSelection(selectionBuilder); return this; } public static class RangeBuilder { private int mValue; private int mMax = 100; private boolean mValueSet = false; private CharSequence mTitle; private CharSequence mSubtitle; private SliceAction mPrimaryAction; private CharSequence mContentDescription; private int mLayoutDirection = -1; private int mMode = RANGE_MODE_DETERMINATE; private IconCompat mTitleIcon; private int mTitleImageMode; private boolean mTitleItemLoading; public RangeBuilder() { } | /**
* Add a selection row to the list builder.
*/ | Add a selection row to the list builder | addSelection | {
"repo_name": "AndroidX/androidx",
"path": "slice/slice-builders/src/main/java/androidx/slice/builders/ListBuilder.java",
"license": "apache-2.0",
"size": 74588
} | [
"androidx.annotation.NonNull",
"androidx.core.graphics.drawable.IconCompat"
] | import androidx.annotation.NonNull; import androidx.core.graphics.drawable.IconCompat; | import androidx.annotation.*; import androidx.core.graphics.drawable.*; | [
"androidx.annotation",
"androidx.core"
] | androidx.annotation; androidx.core; | 1,530,949 |
List<Attribute> getAttributes(PerunSession sess, Member member, Resource resource, boolean workWithUserAttributes) throws MemberResourceMismatchException; | List<Attribute> getAttributes(PerunSession sess, Member member, Resource resource, boolean workWithUserAttributes) throws MemberResourceMismatchException; | /**
* Gets all <b>non-empty</b> attributes associated with the member on the resource and if workWithUserAttributes is
* true, gets also all <b>non-empty</b> user, user-facility and member attributes.
*
* @param sess perun session
* @param member to get the attributes from
* @param resource to get the attributes from
* @param workWithUserAttributes if true returns also user-facility, user and member attributes (user is automatically get from member a facility is get from resource)
* @return list of attributes
*
* @throws InternalErrorException if an exception raise in concrete implementation, the exception is wrapped in InternalErrorException
* @throws MemberResourceMismatchException
*
* !!WARNING THIS IS VERY TIME-CONSUMING METHOD. DON'T USE IT IN BATCH!!
*/ | Gets all non-empty attributes associated with the member on the resource and if workWithUserAttributes is true, gets also all non-empty user, user-facility and member attributes | getAttributes | {
"repo_name": "zlamalp/perun",
"path": "perun-core/src/main/java/cz/metacentrum/perun/core/bl/AttributesManagerBl.java",
"license": "bsd-2-clause",
"size": 244560
} | [
"cz.metacentrum.perun.core.api.Attribute",
"cz.metacentrum.perun.core.api.Member",
"cz.metacentrum.perun.core.api.PerunSession",
"cz.metacentrum.perun.core.api.Resource",
"cz.metacentrum.perun.core.api.exceptions.MemberResourceMismatchException",
"java.util.List"
] | import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.Member; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.exceptions.MemberResourceMismatchException; import java.util.List; | import cz.metacentrum.perun.core.api.*; import cz.metacentrum.perun.core.api.exceptions.*; import java.util.*; | [
"cz.metacentrum.perun",
"java.util"
] | cz.metacentrum.perun; java.util; | 1,813,904 |
public String format(JCas jcas) throws Exception;
| String function(JCas jcas) throws Exception; | /**
* Formats result
*
* @param jcas JCas object containing annotations - result
* @return Formatted result
*/ | Formats result | format | {
"repo_name": "reboutli-crim/heideltime",
"path": "src/main/java/de/unihd/dbs/heideltime/standalone/components/ResultFormatter.java",
"license": "gpl-3.0",
"size": 1021
} | [
"org.apache.uima.jcas.JCas"
] | import org.apache.uima.jcas.JCas; | import org.apache.uima.jcas.*; | [
"org.apache.uima"
] | org.apache.uima; | 2,237,200 |
public void setCashierShift(CashierShift newCashierShift) {
if (newCashierShift != cashierShift) {
NotificationChain msgs = null;
if (cashierShift != null)
msgs = ((InternalEObject)cashierShift).eInverseRemove(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs);
if (newCashierShift != null)
msgs = ((InternalEObject)newCashierShift).eInverseAdd(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs);
msgs = basicSetCashierShift(newCashierShift, msgs);
if (msgs != null) msgs.dispatch();
}
} | void function(CashierShift newCashierShift) { if (newCashierShift != cashierShift) { NotificationChain msgs = null; if (cashierShift != null) msgs = ((InternalEObject)cashierShift).eInverseRemove(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs); if (newCashierShift != null) msgs = ((InternalEObject)newCashierShift).eInverseAdd(this, PaymentMeteringPackage.CASHIER_SHIFT__RECEIPTS, CashierShift.class, msgs); msgs = basicSetCashierShift(newCashierShift, msgs); if (msgs != null) msgs.dispatch(); } } | /**
* Sets the value of the '{@link CIM15.IEC61968.PaymentMetering.Receipt#getCashierShift <em>Cashier Shift</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Cashier Shift</em>' reference.
* @see #getCashierShift()
* @generated
*/ | Sets the value of the '<code>CIM15.IEC61968.PaymentMetering.Receipt#getCashierShift Cashier Shift</code>' reference. | setCashierShift | {
"repo_name": "SES-fortiss/SmartGridCoSimulation",
"path": "core/cim15/src/CIM15/IEC61968/PaymentMetering/Receipt.java",
"license": "apache-2.0",
"size": 18452
} | [
"org.eclipse.emf.common.notify.NotificationChain",
"org.eclipse.emf.ecore.InternalEObject"
] | import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.InternalEObject; | import org.eclipse.emf.common.notify.*; import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,101,523 |
interface WithCertificate {
WithCreate withCertificate(String certificate);
}
interface WithCreate extends Creatable<CertificateDescription> {
}
}
interface Update extends Appliable<CertificateDescription>, UpdateStages.WithIfMatch, UpdateStages.WithCertificate {
} | interface WithCertificate { WithCreate withCertificate(String certificate); } interface WithCreate extends Creatable<CertificateDescription> { } } interface Update extends Appliable<CertificateDescription>, UpdateStages.WithIfMatch, UpdateStages.WithCertificate { } | /**
* Specifies certificate.
* @param certificate base-64 representation of the X509 leaf certificate .cer file or just .pem file content
* @return the next definition stage
*/ | Specifies certificate | withCertificate | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/iothub/mgmt-v2018_04_01/src/main/java/com/microsoft/azure/management/iothub/v2018_04_01/CertificateDescription.java",
"license": "mit",
"size": 5084
} | [
"com.microsoft.azure.arm.model.Appliable",
"com.microsoft.azure.arm.model.Creatable"
] | import com.microsoft.azure.arm.model.Appliable; import com.microsoft.azure.arm.model.Creatable; | import com.microsoft.azure.arm.model.*; | [
"com.microsoft.azure"
] | com.microsoft.azure; | 1,205,551 |
public void update(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException,
Types.SrOperationNotSupported {
String method_call = "VDI.update";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
} | void function(Connection c) throws BadServerResponse, XenAPIException, XmlRpcException, Types.SrOperationNotSupported { String method_call = STR; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); return; } | /**
* Ask the storage backend to refresh the fields in the VDI object
*
*/ | Ask the storage backend to refresh the fields in the VDI object | update | {
"repo_name": "mufaddalq/cloudstack-datera-driver",
"path": "deps/XenServerJava/src/com/xensource/xenapi/VDI.java",
"license": "apache-2.0",
"size": 84941
} | [
"com.xensource.xenapi.Types",
"java.util.Map",
"org.apache.xmlrpc.XmlRpcException"
] | import com.xensource.xenapi.Types; import java.util.Map; import org.apache.xmlrpc.XmlRpcException; | import com.xensource.xenapi.*; import java.util.*; import org.apache.xmlrpc.*; | [
"com.xensource.xenapi",
"java.util",
"org.apache.xmlrpc"
] | com.xensource.xenapi; java.util; org.apache.xmlrpc; | 963,004 |
void onModelContextUpdated(@NonNull EffectiveModelContext newModelContext); | void onModelContextUpdated(@NonNull EffectiveModelContext newModelContext); | /**
* Invoked when the model context changes.
*
* @param newModelContext New model context being installed
*/ | Invoked when the model context changes | onModelContextUpdated | {
"repo_name": "opendaylight/yangtools",
"path": "model/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/EffectiveModelContextListener.java",
"license": "epl-1.0",
"size": 860
} | [
"org.eclipse.jdt.annotation.NonNull"
] | import org.eclipse.jdt.annotation.NonNull; | import org.eclipse.jdt.annotation.*; | [
"org.eclipse.jdt"
] | org.eclipse.jdt; | 2,902,455 |
public int diff_levenshtein(LinkedList<Diff> diffs) {
int levenshtein = 0;
int insertions = 0;
int deletions = 0;
for (Diff aDiff : diffs) {
switch (aDiff.operation) {
case INSERT:
insertions += aDiff.text.length();
break;
case DELETE:
deletions += aDiff.text.length();
break;
case EQUAL:
// A deletion and an insertion is one substitution.
levenshtein += Math.max(insertions, deletions);
insertions = 0;
deletions = 0;
break;
}
}
levenshtein += Math.max(insertions, deletions);
return levenshtein;
} | int function(LinkedList<Diff> diffs) { int levenshtein = 0; int insertions = 0; int deletions = 0; for (Diff aDiff : diffs) { switch (aDiff.operation) { case INSERT: insertions += aDiff.text.length(); break; case DELETE: deletions += aDiff.text.length(); break; case EQUAL: levenshtein += Math.max(insertions, deletions); insertions = 0; deletions = 0; break; } } levenshtein += Math.max(insertions, deletions); return levenshtein; } | /**
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param diffs LinkedList of Diff objects.
* @return Number of changes.
*/ | Compute the Levenshtein distance; the number of inserted, deleted or substituted characters | diff_levenshtein | {
"repo_name": "HTML5MSc/HTML5ParserComparator",
"path": "Utils/src/com/html5tools/Utils/diff_match_patch.java",
"license": "mit",
"size": 89015
} | [
"java.util.LinkedList"
] | import java.util.LinkedList; | import java.util.*; | [
"java.util"
] | java.util; | 540,584 |
private void notifyListener() {
if (listener != null) {
listener.update(bytesRead, contentLength, items);
}
}
}
// ----------------------------------------------------- Manifest constants
public static final byte CR = 0x0D;
public static final byte LF = 0x0A;
public static final byte DASH = 0x2D;
public static final int HEADER_PART_SIZE_MAX = 10240;
protected static final int DEFAULT_BUFSIZE = 4096;
protected static final byte[] HEADER_SEPARATOR = {CR, LF, CR, LF};
protected static final byte[] FIELD_SEPARATOR = {CR, LF};
protected static final byte[] STREAM_TERMINATOR = {DASH, DASH};
protected static final byte[] BOUNDARY_PREFIX = {CR, LF, DASH, DASH};
// ----------------------------------------------------------- Data members
private final InputStream input;
private int boundaryLength;
private int keepRegion;
private byte[] boundary;
private final int bufSize;
private final byte[] buffer;
private int head;
private int tail;
private String headerEncoding;
private final ProgressNotifier notifier;
// ----------------------------------------------------------- Constructors
@Deprecated
public MultipartStream() {
this(null, null, null);
}
@Deprecated
public MultipartStream(InputStream input, byte[] boundary, int bufSize) {
this(input, boundary, bufSize, null);
}
MultipartStream(InputStream input,
byte[] boundary,
int bufSize,
ProgressNotifier pNotifier) {
this.input = input;
this.bufSize = bufSize;
this.buffer = new byte[bufSize];
this.notifier = pNotifier;
// We prepend CR/LF to the boundary to chop trailing CR/LF from
// body-data tokens.
this.boundary = new byte[boundary.length + BOUNDARY_PREFIX.length];
this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length;
this.keepRegion = this.boundary.length;
System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0,
BOUNDARY_PREFIX.length);
System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length,
boundary.length);
head = 0;
tail = 0;
}
MultipartStream(InputStream input,
byte[] boundary,
ProgressNotifier pNotifier) {
this(input, boundary, DEFAULT_BUFSIZE, pNotifier);
}
@Deprecated
public MultipartStream(InputStream input,
byte[] boundary) {
this(input, boundary, DEFAULT_BUFSIZE, null);
}
// --------------------------------------------------------- Public methods | void function() { if (listener != null) { listener.update(bytesRead, contentLength, items); } } } public static final byte CR = 0x0D; public static final byte LF = 0x0A; public static final byte DASH = 0x2D; public static final int HEADER_PART_SIZE_MAX = 10240; protected static final int DEFAULT_BUFSIZE = 4096; protected static final byte[] HEADER_SEPARATOR = {CR, LF, CR, LF}; protected static final byte[] FIELD_SEPARATOR = {CR, LF}; protected static final byte[] STREAM_TERMINATOR = {DASH, DASH}; protected static final byte[] BOUNDARY_PREFIX = {CR, LF, DASH, DASH}; private final InputStream input; private int boundaryLength; private int keepRegion; private byte[] boundary; private final int bufSize; private final byte[] buffer; private int head; private int tail; private String headerEncoding; private final ProgressNotifier notifier; public MultipartStream() { this(null, null, null); } public MultipartStream(InputStream input, byte[] boundary, int bufSize) { this(input, boundary, bufSize, null); } MultipartStream(InputStream input, byte[] boundary, int bufSize, ProgressNotifier pNotifier) { this.input = input; this.bufSize = bufSize; this.buffer = new byte[bufSize]; this.notifier = pNotifier; this.boundary = new byte[boundary.length + BOUNDARY_PREFIX.length]; this.boundaryLength = boundary.length + BOUNDARY_PREFIX.length; this.keepRegion = this.boundary.length; System.arraycopy(BOUNDARY_PREFIX, 0, this.boundary, 0, BOUNDARY_PREFIX.length); System.arraycopy(boundary, 0, this.boundary, BOUNDARY_PREFIX.length, boundary.length); head = 0; tail = 0; } MultipartStream(InputStream input, byte[] boundary, ProgressNotifier pNotifier) { this(input, boundary, DEFAULT_BUFSIZE, pNotifier); } public MultipartStream(InputStream input, byte[] boundary) { this(input, boundary, DEFAULT_BUFSIZE, null); } | /**
* Called for notifying the listener.
*/ | Called for notifying the listener | notifyListener | {
"repo_name": "sabob/ratel",
"path": "ratel/src/com/google/ratel/deps/fileupload/MultipartStream.java",
"license": "apache-2.0",
"size": 33301
} | [
"java.io.InputStream"
] | import java.io.InputStream; | import java.io.*; | [
"java.io"
] | java.io; | 1,559,667 |
List<Tree.Parameter> initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Functional m) {
List<Tree.Parameter> rparams = null;
for (final Tree.Parameter param : params.getParameters()) {
Parameter pd = param.getParameterModel();
String paramName = names.name(pd);
if (pd.isDefaulted() || pd.isSequenced()) {
out("if(", paramName, "===undefined){", paramName, "=");
if (pd.isDefaulted()) {
boolean done = false;
if (m instanceof Function) {
Function mf = (Function)m;
if (mf.getRefinedDeclaration() != mf) {
mf = (Function)mf.getRefinedDeclaration();
if (mf.isMember() || !mf.isImplemented()) {
qualify(params, mf);
out(names.name(mf), "$defs$", pd.getName(), "(");
boolean firstParam=true;
for (Parameter p : m.getFirstParameterList().getParameters()) {
if (firstParam){firstParam=false;}else out(",");
out(names.name(p));
}
out(")");
done = true;
}
}
} else if (pd.getDeclaration() instanceof Class) {
Class cdec = (Class)pd.getDeclaration().getRefinedDeclaration();
out(TypeGenerator.pathToType(params, cdec, this),
".$defs$", pd.getName(), "(", names.self(cdec));
for (Parameter p : ((Class)pd.getDeclaration()).getParameterList().getParameters()) {
if (!p.equals(pd)) {
out(",", names.name(p));
}
}
out(")");
if (rparams == null) {
rparams = new ArrayList<>(3);
}
rparams.add(param);
done = true;
}
if (!done) {
final SpecifierOrInitializerExpression expr = getDefaultExpression(param);
if (expr == null) {
param.addUnexpectedError("Default expression missing for " + pd.getName(), Backend.JavaScript);
out("undefined");
} else {
generateParameterExpression(param, expr,
pd.getDeclaration() instanceof Scope? (Scope)pd.getDeclaration() : null);
}
}
} else {
out(getClAlias(), "empty()");
}
out(";}");
endLine();
}
if (typeDecl != null && !(typeDecl instanceof ClassAlias)
&& (pd.getModel().isJsCaptured() || pd.getDeclaration() instanceof Class)) {
out(names.self(typeDecl), ".", names.valueName(pd.getModel()), "=", paramName);
if (!opts.isOptimize() && pd.isHidden()) { //belt and suspenders...
out(";", names.self(typeDecl), ".", paramName, "=", paramName);
}
endLine(true);
}
}
return rparams;
} | List<Tree.Parameter> initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Functional m) { List<Tree.Parameter> rparams = null; for (final Tree.Parameter param : params.getParameters()) { Parameter pd = param.getParameterModel(); String paramName = names.name(pd); if (pd.isDefaulted() pd.isSequenced()) { out("if(", paramName, STR, paramName, "="); if (pd.isDefaulted()) { boolean done = false; if (m instanceof Function) { Function mf = (Function)m; if (mf.getRefinedDeclaration() != mf) { mf = (Function)mf.getRefinedDeclaration(); if (mf.isMember() !mf.isImplemented()) { qualify(params, mf); out(names.name(mf), STR, pd.getName(), "("); boolean firstParam=true; for (Parameter p : m.getFirstParameterList().getParameters()) { if (firstParam){firstParam=false;}else out(","); out(names.name(p)); } out(")"); done = true; } } } else if (pd.getDeclaration() instanceof Class) { Class cdec = (Class)pd.getDeclaration().getRefinedDeclaration(); out(TypeGenerator.pathToType(params, cdec, this), STR, pd.getName(), "(", names.self(cdec)); for (Parameter p : ((Class)pd.getDeclaration()).getParameterList().getParameters()) { if (!p.equals(pd)) { out(",", names.name(p)); } } out(")"); if (rparams == null) { rparams = new ArrayList<>(3); } rparams.add(param); done = true; } if (!done) { final SpecifierOrInitializerExpression expr = getDefaultExpression(param); if (expr == null) { param.addUnexpectedError(STR + pd.getName(), Backend.JavaScript); out(STR); } else { generateParameterExpression(param, expr, pd.getDeclaration() instanceof Scope? (Scope)pd.getDeclaration() : null); } } } else { out(getClAlias(), STR); } out(";}"); endLine(); } if (typeDecl != null && !(typeDecl instanceof ClassAlias) && (pd.getModel().isJsCaptured() pd.getDeclaration() instanceof Class)) { out(names.self(typeDecl), ".", names.valueName(pd.getModel()), "=", paramName); if (!opts.isOptimize() && pd.isHidden()) { out(";", names.self(typeDecl), ".", paramName, "=", paramName); } endLine(true); } } return rparams; } | /** Initialize the sequenced, defaulted and captured parameters in a type declaration.
* @return The defaulted parameters that belong to a class, since their values have to be
* set later on. */ | Initialize the sequenced, defaulted and captured parameters in a type declaration | initParameters | {
"repo_name": "ceylon/ceylon",
"path": "compiler-js/src/main/java/org/eclipse/ceylon/compiler/js/GenerateJsVisitor.java",
"license": "apache-2.0",
"size": 170897
} | [
"java.util.ArrayList",
"java.util.List",
"org.eclipse.ceylon.common.Backend",
"org.eclipse.ceylon.compiler.typechecker.tree.Tree",
"org.eclipse.ceylon.model.typechecker.model.Class",
"org.eclipse.ceylon.model.typechecker.model.ClassAlias",
"org.eclipse.ceylon.model.typechecker.model.Function",
"org.eclipse.ceylon.model.typechecker.model.Functional",
"org.eclipse.ceylon.model.typechecker.model.Parameter",
"org.eclipse.ceylon.model.typechecker.model.ParameterList",
"org.eclipse.ceylon.model.typechecker.model.Scope",
"org.eclipse.ceylon.model.typechecker.model.TypeDeclaration"
] | import java.util.ArrayList; import java.util.List; import org.eclipse.ceylon.common.Backend; import org.eclipse.ceylon.compiler.typechecker.tree.Tree; import org.eclipse.ceylon.model.typechecker.model.Class; import org.eclipse.ceylon.model.typechecker.model.ClassAlias; import org.eclipse.ceylon.model.typechecker.model.Function; import org.eclipse.ceylon.model.typechecker.model.Functional; import org.eclipse.ceylon.model.typechecker.model.Parameter; import org.eclipse.ceylon.model.typechecker.model.ParameterList; import org.eclipse.ceylon.model.typechecker.model.Scope; import org.eclipse.ceylon.model.typechecker.model.TypeDeclaration; | import java.util.*; import org.eclipse.ceylon.common.*; import org.eclipse.ceylon.compiler.typechecker.tree.*; import org.eclipse.ceylon.model.typechecker.model.*; | [
"java.util",
"org.eclipse.ceylon"
] | java.util; org.eclipse.ceylon; | 942,934 |
void init(Properties properties); | void init(Properties properties); | /**
* Initializes this model with the given properties.
* @param properties the given properties.
*/ | Initializes this model with the given properties | init | {
"repo_name": "apucher/pinot",
"path": "thirdeye/thirdeye-pinot/src/main/java/com/linkedin/thirdeye/anomalydetection/model/transform/TransformationFunction.java",
"license": "apache-2.0",
"size": 1928
} | [
"java.util.Properties"
] | import java.util.Properties; | import java.util.*; | [
"java.util"
] | java.util; | 1,835,726 |
protected void validate(X509Certificate[] certPath) throws ProxyPathValidatorException {
validate(certPath, (TrustedCertificates) null, (CertificateRevocationLists) null);
} | void function(X509Certificate[] certPath) throws ProxyPathValidatorException { validate(certPath, (TrustedCertificates) null, (CertificateRevocationLists) null); } | /**
* Performs certificate path validation. Does <B>not</B> check the cert
* signatures but it performs all other checks like the extension checking,
* validity checking, restricted policy checking, CRL checking, etc.
*
* @param certPath
* the certificate path to validate.
* @exception ProxyPathValidatorException
* if certificate path validation fails.
*/ | Performs certificate path validation. Does not check the cert signatures but it performs all other checks like the extension checking, validity checking, restricted policy checking, CRL checking, etc | validate | {
"repo_name": "NCIP/cagrid-core",
"path": "caGrid/projects/gts/src/gov/nih/nci/cagrid/gts/service/ProxyPathValidator.java",
"license": "bsd-3-clause",
"size": 27728
} | [
"java.security.cert.X509Certificate",
"org.globus.gsi.TrustedCertificates",
"org.globus.gsi.proxy.ProxyPathValidatorException"
] | import java.security.cert.X509Certificate; import org.globus.gsi.TrustedCertificates; import org.globus.gsi.proxy.ProxyPathValidatorException; | import java.security.cert.*; import org.globus.gsi.*; import org.globus.gsi.proxy.*; | [
"java.security",
"org.globus.gsi"
] | java.security; org.globus.gsi; | 189,187 |
public void saveOrUpdate(org.jchlabs.gharonda.domain.model.Favorites favorites, Session s) {
saveOrUpdate((Object) favorites, s);
}
| void function(org.jchlabs.gharonda.domain.model.Favorites favorites, Session s) { saveOrUpdate((Object) favorites, s); } | /**
* Either save() or update() the given instance, depending upon the value of its identifier property. By default the
* instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the
* identifier property mapping. Use the Session given.
* @param favorites a transient instance containing new or updated state.
* @param s the Session.
*/ | Either save() or update() the given instance, depending upon the value of its identifier property. By default the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the identifier property mapping. Use the Session given | saveOrUpdate | {
"repo_name": "jchaganti/gharonda",
"path": "server/src/main/java/org/jchlabs/gharonda/domain/pom/base/BaseFavoritesDAO.java",
"license": "mit",
"size": 7990
} | [
"org.hibernate.Session"
] | import org.hibernate.Session; | import org.hibernate.*; | [
"org.hibernate"
] | org.hibernate; | 916,783 |
public boolean validatePropertyModification(Property property)
{
if(property == statusMessageInterval)
return statusMessageInterval.intValue() > 100;
else if(property == checkInteval)
return checkInteval.intValue() > 100;
else return super.validatePropertyModification(property);
}
| boolean function(Property property) { if(property == statusMessageInterval) return statusMessageInterval.intValue() > 100; else if(property == checkInteval) return checkInteval.intValue() > 100; else return super.validatePropertyModification(property); } | /**
* Validates a modification of a property's value. This method validates various properties like
* statusMessageInterval and checkInteval.
*
* @param property The property to be validated.
*
* @return boolean value indicating if the property passed (true) validation or not (false).
*
* @see com.teletalk.jserver.property.PropertyOwner
*/ | Validates a modification of a property's value. This method validates various properties like statusMessageInterval and checkInteval | validatePropertyModification | {
"repo_name": "tolo/JServer",
"path": "src/java/com/teletalk/jserver/queue/legacy/DefaultQueueSystemCollaborationManager.java",
"license": "apache-2.0",
"size": 34502
} | [
"com.teletalk.jserver.property.Property"
] | import com.teletalk.jserver.property.Property; | import com.teletalk.jserver.property.*; | [
"com.teletalk.jserver"
] | com.teletalk.jserver; | 656,993 |
public void saveProperties() {
FileOutputStream outStream = null;
if (getActualProperties() != null) {
try {
outStream = new FileOutputStream(new File(getPropertyFileName()));
getActualProperties().store(outStream, "QVCS Project Properties for project: " + projectName);
} catch (IOException e) {
// Catch any exception. If the property file is missing, we'll just go
// with the defaults.
LOGGER.warn(e.getMessage());
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
LOGGER.warn("Exception in closing project properties file: [{}]. . Exception: [{}]: [{}]", getPropertyFileName(),
e.getClass(), e.getLocalizedMessage());
}
}
}
}
} | void function() { FileOutputStream outStream = null; if (getActualProperties() != null) { try { outStream = new FileOutputStream(new File(getPropertyFileName())); getActualProperties().store(outStream, STR + projectName); } catch (IOException e) { LOGGER.warn(e.getMessage()); } finally { if (outStream != null) { try { outStream.close(); } catch (IOException e) { LOGGER.warn(STR, getPropertyFileName(), e.getClass(), e.getLocalizedMessage()); } } } } } | /**
* Save the properties.
*/ | Save the properties | saveProperties | {
"repo_name": "jimv39/qvcsos",
"path": "qvcse-qvcslib/src/main/java/com/qumasoft/qvcslib/AbstractProjectProperties.java",
"license": "apache-2.0",
"size": 12318
} | [
"java.io.File",
"java.io.FileOutputStream",
"java.io.IOException"
] | import java.io.File; import java.io.FileOutputStream; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 620,290 |
private void handleCompletedReceives(List<ClientResponse> responses, long now) {
for (NetworkReceive receive : this.selector.completedReceives()) {
int source = receive.source();
ClientRequest req = inFlightRequests.completeNext(source);
ResponseHeader header = ResponseHeader.parse(receive.payload());
short apiKey = req.request().header().apiKey();
Struct body = (Struct) ProtoUtils.currentResponseSchema(apiKey).read(receive.payload());
correlate(req.request().header(), header);
if (apiKey == ApiKeys.METADATA.id) {
handleMetadataResponse(req.request().header(), body, now);
} else {
// need to add body/header to response here
responses.add(new ClientResponse(req, now, false, body));
}
}
} | void function(List<ClientResponse> responses, long now) { for (NetworkReceive receive : this.selector.completedReceives()) { int source = receive.source(); ClientRequest req = inFlightRequests.completeNext(source); ResponseHeader header = ResponseHeader.parse(receive.payload()); short apiKey = req.request().header().apiKey(); Struct body = (Struct) ProtoUtils.currentResponseSchema(apiKey).read(receive.payload()); correlate(req.request().header(), header); if (apiKey == ApiKeys.METADATA.id) { handleMetadataResponse(req.request().header(), body, now); } else { responses.add(new ClientResponse(req, now, false, body)); } } } | /**
* Handle any completed receives and update the response list with the responses received.
*
* @param responses The list of responses to update
* @param now The current time
*/ | Handle any completed receives and update the response list with the responses received | handleCompletedReceives | {
"repo_name": "WillCh/cs286A",
"path": "dataMover/kafka/clients/src/main/java/org/apache/kafka/clients/NetworkClient.java",
"license": "bsd-2-clause",
"size": 21125
} | [
"java.util.List",
"org.apache.kafka.common.network.NetworkReceive",
"org.apache.kafka.common.protocol.ApiKeys",
"org.apache.kafka.common.protocol.ProtoUtils",
"org.apache.kafka.common.protocol.types.Struct",
"org.apache.kafka.common.requests.ResponseHeader"
] | import java.util.List; import org.apache.kafka.common.network.NetworkReceive; import org.apache.kafka.common.protocol.ApiKeys; import org.apache.kafka.common.protocol.ProtoUtils; import org.apache.kafka.common.protocol.types.Struct; import org.apache.kafka.common.requests.ResponseHeader; | import java.util.*; import org.apache.kafka.common.network.*; import org.apache.kafka.common.protocol.*; import org.apache.kafka.common.protocol.types.*; import org.apache.kafka.common.requests.*; | [
"java.util",
"org.apache.kafka"
] | java.util; org.apache.kafka; | 2,422,698 |
void setAttributes(PerunSession sess, Host host, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException;
void setAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException; | void setAttributes(PerunSession sess, Host host, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException; void setAttributes(PerunSession sess, Resource resource, Group group, List<Attribute> attributes) throws InternalErrorException, WrongAttributeValueException, WrongAttributeAssignmentException, WrongReferenceAttributeValueException; | /**
* Stores the group-resource attributes.
* @param sess
* @param resource
* @param group
* @param attributes
* @throws InternalErrorException
* @throws WrongAttributeValueException
* @throws WrongAttributeAssignmentException
*/ | Stores the group-resource attributes | setAttributes | {
"repo_name": "jirmauritz/perun",
"path": "perun-core/src/main/java/cz/metacentrum/perun/core/bl/AttributesManagerBl.java",
"license": "bsd-2-clause",
"size": 193360
} | [
"cz.metacentrum.perun.core.api.Attribute",
"cz.metacentrum.perun.core.api.Group",
"cz.metacentrum.perun.core.api.Host",
"cz.metacentrum.perun.core.api.PerunSession",
"cz.metacentrum.perun.core.api.Resource",
"cz.metacentrum.perun.core.api.exceptions.InternalErrorException",
"cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException",
"cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException",
"cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException",
"java.util.List"
] | import cz.metacentrum.perun.core.api.Attribute; import cz.metacentrum.perun.core.api.Group; import cz.metacentrum.perun.core.api.Host; import cz.metacentrum.perun.core.api.PerunSession; import cz.metacentrum.perun.core.api.Resource; import cz.metacentrum.perun.core.api.exceptions.InternalErrorException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException; import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException; import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException; import java.util.List; | import cz.metacentrum.perun.core.api.*; import cz.metacentrum.perun.core.api.exceptions.*; import java.util.*; | [
"cz.metacentrum.perun",
"java.util"
] | cz.metacentrum.perun; java.util; | 1,296,484 |
@Override
public int hashCode() {
return Objects.hash(locale, text);
} | int function() { return Objects.hash(locale, text); } | /**
* Returns a hash code value for this string.
*/ | Returns a hash code value for this string | hashCode | {
"repo_name": "apache/sis",
"path": "core/sis-metadata/src/main/java/org/apache/sis/internal/jaxb/lan/LocalisedCharacterString.java",
"license": "apache-2.0",
"size": 5153
} | [
"java.util.Objects"
] | import java.util.Objects; | import java.util.*; | [
"java.util"
] | java.util; | 1,158,790 |
public Context initControlContext() throws Exception
{
XmlToAppData xmlParser;
if (xmlFile == null && filesets.isEmpty())
{
throw new BuildException("You must specify an XML schema or "
+ "fileset of XML schemas!");
}
try
{
if (xmlFile != null)
{
// Transform the XML database schema into
// data model object.
xmlParser = new XmlToAppData(getTargetDatabase(),
getTargetPackage());
Database ad = xmlParser.parseFile(xmlFile);
ad.setFileName(grokName(xmlFile));
dataModels.add(ad);
}
else
{
// Deal with the filesets.
for (int i = 0; i < filesets.size(); i++)
{
FileSet fs = (FileSet) filesets.get(i);
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
File srcDir = fs.getDir(getProject());
String[] dataModelFiles = ds.getIncludedFiles();
// Make a transaction for each file
for (int j = 0; j < dataModelFiles.length; j++)
{
File f = new File(srcDir, dataModelFiles[j]);
xmlParser = new XmlToAppData(getTargetDatabase(),
getTargetPackage());
Database ad = xmlParser.parseFile(f.toString());
ad.setFileName(grokName(f.toString()));
dataModels.add(ad);
}
}
}
Iterator i = dataModels.iterator();
databaseNames = new Hashtable();
dataModelDbMap = new Hashtable();
// Different datamodels may state the same database
// names, we just want the unique names of databases.
while (i.hasNext())
{
Database database = (Database) i.next();
databaseNames.put(database.getName(), database.getName());
dataModelDbMap.put(database.getFileName(), database.getName());
}
}
catch (EngineException ee)
{
throw new BuildException(ee);
}
context = new VelocityContext();
// Place our set of data models into the context along
// with the names of the databases as a convenience for now.
context.put("dataModels", dataModels);
context.put("databaseNames", databaseNames);
context.put("targetDatabase", targetDatabase);
context.put("targetPackage", targetPackage);
return context;
} | Context function() throws Exception { XmlToAppData xmlParser; if (xmlFile == null && filesets.isEmpty()) { throw new BuildException(STR + STR); } try { if (xmlFile != null) { xmlParser = new XmlToAppData(getTargetDatabase(), getTargetPackage()); Database ad = xmlParser.parseFile(xmlFile); ad.setFileName(grokName(xmlFile)); dataModels.add(ad); } else { for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet) filesets.get(i); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); File srcDir = fs.getDir(getProject()); String[] dataModelFiles = ds.getIncludedFiles(); for (int j = 0; j < dataModelFiles.length; j++) { File f = new File(srcDir, dataModelFiles[j]); xmlParser = new XmlToAppData(getTargetDatabase(), getTargetPackage()); Database ad = xmlParser.parseFile(f.toString()); ad.setFileName(grokName(f.toString())); dataModels.add(ad); } } } Iterator i = dataModels.iterator(); databaseNames = new Hashtable(); dataModelDbMap = new Hashtable(); while (i.hasNext()) { Database database = (Database) i.next(); databaseNames.put(database.getName(), database.getName()); dataModelDbMap.put(database.getFileName(), database.getName()); } } catch (EngineException ee) { throw new BuildException(ee); } context = new VelocityContext(); context.put(STR, dataModels); context.put(STR, databaseNames); context.put(STR, targetDatabase); context.put(STR, targetPackage); return context; } | /**
* Set up the initial context for generating the SQL from the XML schema.
*
* @return the context
* @throws Exception
*/ | Set up the initial context for generating the SQL from the XML schema | initControlContext | {
"repo_name": "ua-eas/ua-kfs-5.3",
"path": "work/db/kfs-db/db-impex/impex/src/org/apache/torque/task/TorqueDataModelTask.java",
"license": "agpl-3.0",
"size": 11315
} | [
"java.io.File",
"java.util.Hashtable",
"java.util.Iterator",
"org.apache.tools.ant.BuildException",
"org.apache.tools.ant.DirectoryScanner",
"org.apache.tools.ant.types.FileSet",
"org.apache.torque.engine.EngineException",
"org.apache.torque.engine.database.model.Database",
"org.apache.torque.engine.database.transform.XmlToAppData",
"org.apache.velocity.VelocityContext",
"org.apache.velocity.context.Context"
] | import java.io.File; import java.util.Hashtable; import java.util.Iterator; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.types.FileSet; import org.apache.torque.engine.EngineException; import org.apache.torque.engine.database.model.Database; import org.apache.torque.engine.database.transform.XmlToAppData; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; | import java.io.*; import java.util.*; import org.apache.tools.ant.*; import org.apache.tools.ant.types.*; import org.apache.torque.engine.*; import org.apache.torque.engine.database.model.*; import org.apache.torque.engine.database.transform.*; import org.apache.velocity.*; import org.apache.velocity.context.*; | [
"java.io",
"java.util",
"org.apache.tools",
"org.apache.torque",
"org.apache.velocity"
] | java.io; java.util; org.apache.tools; org.apache.torque; org.apache.velocity; | 91,145 |
public static Future<?> removeQueueItem(final Context context,
final FeedItem item, final boolean performAutoDownload) {
return dbExec.submit(new Runnable() { | static Future<?> function(final Context context, final FeedItem item, final boolean performAutoDownload) { return dbExec.submit(new Runnable() { | /**
* Removes a FeedItem object from the queue.
*
* @param context A context that is used for opening a database connection.
* @param item FeedItem that should be removed.
* @param performAutoDownload true if an auto-download process should be started after the operation.
*/ | Removes a FeedItem object from the queue | removeQueueItem | {
"repo_name": "volhol/AntennaPod",
"path": "core/src/main/java/de/danoeh/antennapod/core/storage/DBWriter.java",
"license": "mit",
"size": 45090
} | [
"android.content.Context",
"de.danoeh.antennapod.core.feed.FeedItem",
"java.util.concurrent.Future"
] | import android.content.Context; import de.danoeh.antennapod.core.feed.FeedItem; import java.util.concurrent.Future; | import android.content.*; import de.danoeh.antennapod.core.feed.*; import java.util.concurrent.*; | [
"android.content",
"de.danoeh.antennapod",
"java.util"
] | android.content; de.danoeh.antennapod; java.util; | 844,917 |
File journalDir = tempDir.newFolder();
Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir));
File ledgerDir = tempDir.newFolder();
Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(ledgerDir));
ServerConfiguration conf = TestBKConfiguration.newServerConfiguration();
conf.setJournalDirName(journalDir.getPath())
.setLedgerDirNames(new String[]{ledgerDir.getPath()})
.setMetadataServiceUri(null);
BookieSocketAddress bookieAddress = Bookie.getBookieAddress(conf);
CountDownLatch journalJoinLatch = new CountDownLatch(1);
Journal journal = mock(Journal.class);
MutableBoolean effectiveAckBeforeSync = new MutableBoolean(false);
doAnswer((Answer) (InvocationOnMock iom) -> {
ByteBuf entry = iom.getArgument(0);
long ledgerId = entry.getLong(entry.readerIndex() + 0);
long entryId = entry.getLong(entry.readerIndex() + 8);
boolean ackBeforeSync = iom.getArgument(1);
WriteCallback callback = iom.getArgument(2);
Object ctx = iom.getArgument(3);
effectiveAckBeforeSync.setValue(ackBeforeSync);
callback.writeComplete(BKException.Code.OK, ledgerId, entryId, bookieAddress, ctx);
return null;
}).when(journal).logAddEntry(any(ByteBuf.class), anyBoolean(), any(WriteCallback.class), any());
// bookie will continue to work as soon as the journal thread is alive
doAnswer((Answer) (InvocationOnMock iom) -> {
journalJoinLatch.await();
return null;
}).when(journal).joinThread();
whenNew(Journal.class).withAnyArguments().thenReturn(journal);
Bookie b = new Bookie(conf);
b.start();
long ledgerId = 1;
long entryId = 0;
Object expectedCtx = "foo";
byte[] masterKey = new byte[64];
for (boolean ackBeforeSync : new boolean[]{true, false}) {
CountDownLatch latch = new CountDownLatch(1);
final ByteBuf data = buildEntry(ledgerId, entryId, -1);
final long expectedEntryId = entryId;
b.addEntry(data, ackBeforeSync, (int rc, long ledgerId1, long entryId1,
BookieSocketAddress addr, Object ctx) -> {
assertSame(expectedCtx, ctx);
assertEquals(ledgerId, ledgerId1);
assertEquals(expectedEntryId, entryId1);
latch.countDown();
}, expectedCtx, masterKey);
latch.await(30, TimeUnit.SECONDS);
assertEquals(ackBeforeSync, effectiveAckBeforeSync.booleanValue());
entryId++;
}
// let bookie exit main thread
journalJoinLatch.countDown();
b.shutdown();
} | File journalDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(journalDir)); File ledgerDir = tempDir.newFolder(); Bookie.checkDirectoryStructure(Bookie.getCurrentDirectory(ledgerDir)); ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setJournalDirName(journalDir.getPath()) .setLedgerDirNames(new String[]{ledgerDir.getPath()}) .setMetadataServiceUri(null); BookieSocketAddress bookieAddress = Bookie.getBookieAddress(conf); CountDownLatch journalJoinLatch = new CountDownLatch(1); Journal journal = mock(Journal.class); MutableBoolean effectiveAckBeforeSync = new MutableBoolean(false); doAnswer((Answer) (InvocationOnMock iom) -> { ByteBuf entry = iom.getArgument(0); long ledgerId = entry.getLong(entry.readerIndex() + 0); long entryId = entry.getLong(entry.readerIndex() + 8); boolean ackBeforeSync = iom.getArgument(1); WriteCallback callback = iom.getArgument(2); Object ctx = iom.getArgument(3); effectiveAckBeforeSync.setValue(ackBeforeSync); callback.writeComplete(BKException.Code.OK, ledgerId, entryId, bookieAddress, ctx); return null; }).when(journal).logAddEntry(any(ByteBuf.class), anyBoolean(), any(WriteCallback.class), any()); doAnswer((Answer) (InvocationOnMock iom) -> { journalJoinLatch.await(); return null; }).when(journal).joinThread(); whenNew(Journal.class).withAnyArguments().thenReturn(journal); Bookie b = new Bookie(conf); b.start(); long ledgerId = 1; long entryId = 0; Object expectedCtx = "foo"; byte[] masterKey = new byte[64]; for (boolean ackBeforeSync : new boolean[]{true, false}) { CountDownLatch latch = new CountDownLatch(1); final ByteBuf data = buildEntry(ledgerId, entryId, -1); final long expectedEntryId = entryId; b.addEntry(data, ackBeforeSync, (int rc, long ledgerId1, long entryId1, BookieSocketAddress addr, Object ctx) -> { assertSame(expectedCtx, ctx); assertEquals(ledgerId, ledgerId1); assertEquals(expectedEntryId, entryId1); latch.countDown(); }, expectedCtx, masterKey); latch.await(30, TimeUnit.SECONDS); assertEquals(ackBeforeSync, effectiveAckBeforeSync.booleanValue()); entryId++; } journalJoinLatch.countDown(); b.shutdown(); } | /**
* test that Bookie calls correctly Journal.logAddEntry about "ackBeforeSync" parameter.
*/ | test that Bookie calls correctly Journal.logAddEntry about "ackBeforeSync" parameter | testJournalLogAddEntryCalledCorrectly | {
"repo_name": "ivankelly/bookkeeper",
"path": "bookkeeper-server/src/test/java/org/apache/bookkeeper/bookie/BookieWriteToJournalTest.java",
"license": "apache-2.0",
"size": 8454
} | [
"io.netty.buffer.ByteBuf",
"java.io.File",
"java.util.concurrent.CountDownLatch",
"java.util.concurrent.TimeUnit",
"org.apache.bookkeeper.client.api.BKException",
"org.apache.bookkeeper.conf.ServerConfiguration",
"org.apache.bookkeeper.conf.TestBKConfiguration",
"org.apache.bookkeeper.net.BookieSocketAddress",
"org.apache.bookkeeper.proto.BookkeeperInternalCallbacks",
"org.apache.commons.lang3.mutable.MutableBoolean",
"org.junit.Assert",
"org.mockito.ArgumentMatchers",
"org.mockito.Mockito",
"org.mockito.invocation.InvocationOnMock",
"org.mockito.stubbing.Answer",
"org.powermock.api.mockito.PowerMockito"
] | import io.netty.buffer.ByteBuf; import java.io.File; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.apache.bookkeeper.client.api.BKException; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.conf.TestBKConfiguration; import org.apache.bookkeeper.net.BookieSocketAddress; import org.apache.bookkeeper.proto.BookkeeperInternalCallbacks; import org.apache.commons.lang3.mutable.MutableBoolean; import org.junit.Assert; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.powermock.api.mockito.PowerMockito; | import io.netty.buffer.*; import java.io.*; import java.util.concurrent.*; import org.apache.bookkeeper.client.api.*; import org.apache.bookkeeper.conf.*; import org.apache.bookkeeper.net.*; import org.apache.bookkeeper.proto.*; import org.apache.commons.lang3.mutable.*; import org.junit.*; import org.mockito.*; import org.mockito.invocation.*; import org.mockito.stubbing.*; import org.powermock.api.mockito.*; | [
"io.netty.buffer",
"java.io",
"java.util",
"org.apache.bookkeeper",
"org.apache.commons",
"org.junit",
"org.mockito",
"org.mockito.invocation",
"org.mockito.stubbing",
"org.powermock.api"
] | io.netty.buffer; java.io; java.util; org.apache.bookkeeper; org.apache.commons; org.junit; org.mockito; org.mockito.invocation; org.mockito.stubbing; org.powermock.api; | 554,836 |
public Field newField(Class<?> declaringClass,
String name,
Class<?> type,
int modifiers,
int slot,
String signature,
byte[] annotations)
{
return langReflectAccess().newField(declaringClass,
name,
type,
modifiers,
slot,
signature,
annotations);
} | Field function(Class<?> declaringClass, String name, Class<?> type, int modifiers, int slot, String signature, byte[] annotations) { return langReflectAccess().newField(declaringClass, name, type, modifiers, slot, signature, annotations); } | /** Creates a new java.lang.reflect.Field. Access checks as per
java.lang.reflect.AccessibleObject are not overridden. */ | Creates a new java.lang.reflect.Field. Access checks as per | newField | {
"repo_name": "JetBrains/jdk8u_jdk",
"path": "src/share/classes/sun/reflect/ReflectionFactory.java",
"license": "gpl-2.0",
"size": 30127
} | [
"java.lang.reflect.Field"
] | import java.lang.reflect.Field; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 719,392 |
@XmlElement(name = "snmpInterface")
@ManyToOne(optional=true, fetch=FetchType.LAZY)
@JoinColumn(name="snmpInterfaceId")
public OnmsSnmpInterface getSnmpInterface() {
return m_snmpInterface;
} | @XmlElement(name = STR) @ManyToOne(optional=true, fetch=FetchType.LAZY) @JoinColumn(name=STR) OnmsSnmpInterface function() { return m_snmpInterface; } | /**
* The SnmpInterface associated with this interface if any
*
* @return a {@link org.opennms.netmgt.model.OnmsSnmpInterface} object.
*/ | The SnmpInterface associated with this interface if any | getSnmpInterface | {
"repo_name": "tharindum/opennms_dashboard",
"path": "opennms-model/src/main/java/org/opennms/netmgt/model/OnmsIpInterface.java",
"license": "gpl-2.0",
"size": 17664
} | [
"javax.persistence.FetchType",
"javax.persistence.JoinColumn",
"javax.persistence.ManyToOne",
"javax.xml.bind.annotation.XmlElement"
] | import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.xml.bind.annotation.XmlElement; | import javax.persistence.*; import javax.xml.bind.annotation.*; | [
"javax.persistence",
"javax.xml"
] | javax.persistence; javax.xml; | 1,698,571 |
public void addArgument(String type, Context c, HashMap map, DataFactory factory) {
IVPValue value = null;
if (type.equals(IVPValue.INTEGER_TYPE)) {
value = factory.createIVPNumber();
c.addInt(value.getUniqueID(), new Integer(IVPValue.DEFAULT_INTEGER).intValue());
} else if (type.equals(IVPValue.DOUBLE_TYPE)) {
value = factory.createIVPNumber();
c.addDouble(value.getUniqueID(), new Double(IVPValue.DEFAULT_DOUBLE).doubleValue());
} else if (type.equals(IVPValue.STRING_TYPE)) {
value = factory.createIVPString();
c.addString(value.getUniqueID(), IVPValue.DEFAULT_STRING);
} else {
value = factory.createIVPBoolean();
c.addBoolean(value.getUniqueID(), new Boolean(IVPValue.DEFAULT_BOOLEAN));
}
value.setValueType(type);
map.put(value.getUniqueID(), value);
argumentList.add(value.getUniqueID());
}
| void function(String type, Context c, HashMap map, DataFactory factory) { IVPValue value = null; if (type.equals(IVPValue.INTEGER_TYPE)) { value = factory.createIVPNumber(); c.addInt(value.getUniqueID(), new Integer(IVPValue.DEFAULT_INTEGER).intValue()); } else if (type.equals(IVPValue.DOUBLE_TYPE)) { value = factory.createIVPNumber(); c.addDouble(value.getUniqueID(), new Double(IVPValue.DEFAULT_DOUBLE).doubleValue()); } else if (type.equals(IVPValue.STRING_TYPE)) { value = factory.createIVPString(); c.addString(value.getUniqueID(), IVPValue.DEFAULT_STRING); } else { value = factory.createIVPBoolean(); c.addBoolean(value.getUniqueID(), new Boolean(IVPValue.DEFAULT_BOOLEAN)); } value.setValueType(type); map.put(value.getUniqueID(), value); argumentList.add(value.getUniqueID()); } | /**
* Add a parameter to this function. It automatically put a value in the
* memory.
*
* @param integerType
*/ | Add a parameter to this function. It automatically put a value in the memory | addArgument | {
"repo_name": "Romenig/iVProg_2",
"path": "src/usp/ime/line/ivprog/interpreter/execution/code/Function.java",
"license": "gpl-2.0",
"size": 8849
} | [
"java.util.HashMap"
] | import java.util.HashMap; | import java.util.*; | [
"java.util"
] | java.util; | 1,973,329 |
CapabilityServiceBuilder<SessionManagerFactory> getBuilder(ServiceName name, DistributableSessionManagerConfiguration configuration); | CapabilityServiceBuilder<SessionManagerFactory> getBuilder(ServiceName name, DistributableSessionManagerConfiguration configuration); | /**
* Builds a {@link SessionManagerFactory} service.
* @param target the service target
* @param name the service name of the {@link SessionManagerFactory} service
* @param deploymentServiceName service name of the web application
* @param module the deployment module
* @param metaData the web application meta data
* @return a session manager factory service builder
*/ | Builds a <code>SessionManagerFactory</code> service | getBuilder | {
"repo_name": "tomazzupan/wildfly",
"path": "undertow/src/main/java/org/wildfly/extension/undertow/session/DistributableSessionManagerFactoryBuilderProvider.java",
"license": "lgpl-2.1",
"size": 2354
} | [
"io.undertow.servlet.api.SessionManagerFactory",
"org.jboss.as.clustering.controller.CapabilityServiceBuilder",
"org.jboss.msc.service.ServiceName"
] | import io.undertow.servlet.api.SessionManagerFactory; import org.jboss.as.clustering.controller.CapabilityServiceBuilder; import org.jboss.msc.service.ServiceName; | import io.undertow.servlet.api.*; import org.jboss.as.clustering.controller.*; import org.jboss.msc.service.*; | [
"io.undertow.servlet",
"org.jboss.as",
"org.jboss.msc"
] | io.undertow.servlet; org.jboss.as; org.jboss.msc; | 2,267,154 |
public String handleRequest(ComponentSessionController componentSC,
HttpServletRequest request) throws SILVERMAILException {
HttpRequest httpRequest = HttpRequest.decorate(request);
SILVERMAILSessionController silvermailScc = (SILVERMAILSessionController) componentSC;
// Selection
httpRequest.mergeSelectedItemsInto(silvermailScc.getSelectedUserNotificationIds());
try {
SILVERMAILPersistence
.deleteMessages(componentSC.getUserId(), silvermailScc.getSelectedUserNotificationIds());
} catch (NumberFormatException e) {
SilverLogger.getLogger(this).error(e.getMessage(), e);
}
silvermailScc.getSelectedUserNotificationIds().clear();
return "/SILVERMAIL/jsp/main.jsp";
} | String function(ComponentSessionController componentSC, HttpServletRequest request) throws SILVERMAILException { HttpRequest httpRequest = HttpRequest.decorate(request); SILVERMAILSessionController silvermailScc = (SILVERMAILSessionController) componentSC; httpRequest.mergeSelectedItemsInto(silvermailScc.getSelectedUserNotificationIds()); try { SILVERMAILPersistence .deleteMessages(componentSC.getUserId(), silvermailScc.getSelectedUserNotificationIds()); } catch (NumberFormatException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } silvermailScc.getSelectedUserNotificationIds().clear(); return STR; } | /**
* Method declaration
* @param componentSC
* @param request
* @return
* @throws SILVERMAILException
* @see
*/ | Method declaration | handleRequest | {
"repo_name": "auroreallibe/Silverpeas-Core",
"path": "core-war/src/main/java/org/silverpeas/web/notificationserver/channel/silvermail/requesthandlers/DeleteSelectedMessages.java",
"license": "agpl-3.0",
"size": 2900
} | [
"javax.servlet.http.HttpServletRequest",
"org.silverpeas.core.notification.user.server.channel.silvermail.SILVERMAILException",
"org.silverpeas.core.notification.user.server.channel.silvermail.SILVERMAILPersistence",
"org.silverpeas.core.util.logging.SilverLogger",
"org.silverpeas.core.web.http.HttpRequest",
"org.silverpeas.core.web.mvc.controller.ComponentSessionController",
"org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILSessionController"
] | import javax.servlet.http.HttpServletRequest; import org.silverpeas.core.notification.user.server.channel.silvermail.SILVERMAILException; import org.silverpeas.core.notification.user.server.channel.silvermail.SILVERMAILPersistence; import org.silverpeas.core.util.logging.SilverLogger; import org.silverpeas.core.web.http.HttpRequest; import org.silverpeas.core.web.mvc.controller.ComponentSessionController; import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILSessionController; | import javax.servlet.http.*; import org.silverpeas.core.notification.user.server.channel.silvermail.*; import org.silverpeas.core.util.logging.*; import org.silverpeas.core.web.http.*; import org.silverpeas.core.web.mvc.controller.*; import org.silverpeas.web.notificationserver.channel.silvermail.*; | [
"javax.servlet",
"org.silverpeas.core",
"org.silverpeas.web"
] | javax.servlet; org.silverpeas.core; org.silverpeas.web; | 2,827,038 |
@Test
public void testGetPersonLatest() throws MovieDbException {
LOG.info("getPersonLatest");
PersonInfo result = instance.getPersonLatest();
// All we get on the latest person is usually id and name
assertTrue("No id", result.getId() > 0);
assertTrue("No name", StringUtils.isNotBlank(result.getName()));
} | void function() throws MovieDbException { LOG.info(STR); PersonInfo result = instance.getPersonLatest(); assertTrue(STR, result.getId() > 0); assertTrue(STR, StringUtils.isNotBlank(result.getName())); } | /**
* Test of getPersonLatest method, of class TmdbPeople.
*
* @throws com.omertron.themoviedbapi.MovieDbException
*/ | Test of getPersonLatest method, of class TmdbPeople | testGetPersonLatest | {
"repo_name": "mebrah2/api-themoviedb",
"path": "src/test/java/com/omertron/themoviedbapi/methods/TmdbPeopleTest.java",
"license": "gpl-3.0",
"size": 13551
} | [
"com.omertron.themoviedbapi.MovieDbException",
"com.omertron.themoviedbapi.model.person.PersonInfo",
"org.apache.commons.lang3.StringUtils",
"org.junit.Assert"
] | import com.omertron.themoviedbapi.MovieDbException; import com.omertron.themoviedbapi.model.person.PersonInfo; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; | import com.omertron.themoviedbapi.*; import com.omertron.themoviedbapi.model.person.*; import org.apache.commons.lang3.*; import org.junit.*; | [
"com.omertron.themoviedbapi",
"org.apache.commons",
"org.junit"
] | com.omertron.themoviedbapi; org.apache.commons; org.junit; | 1,613,681 |
@Override
public Pair<ByteBuffer, BlockType> beforeWriteToDisk(ByteBuffer in,
boolean includesMemstoreTS, byte[] dummyHeader) {
if (onDisk == DataBlockEncoding.NONE) {
// there is no need to encode the block before writing it to disk
return new Pair<ByteBuffer, BlockType>(in, BlockType.DATA);
}
ByteBuffer encodedBuffer = encodeBufferToHFileBlockBuffer(in,
onDisk, includesMemstoreTS, dummyHeader);
return new Pair<ByteBuffer, BlockType>(encodedBuffer,
BlockType.ENCODED_DATA);
} | Pair<ByteBuffer, BlockType> function(ByteBuffer in, boolean includesMemstoreTS, byte[] dummyHeader) { if (onDisk == DataBlockEncoding.NONE) { return new Pair<ByteBuffer, BlockType>(in, BlockType.DATA); } ByteBuffer encodedBuffer = encodeBufferToHFileBlockBuffer(in, onDisk, includesMemstoreTS, dummyHeader); return new Pair<ByteBuffer, BlockType>(encodedBuffer, BlockType.ENCODED_DATA); } | /**
* Precondition: a non-encoded buffer.
* Postcondition: on-disk encoding.
*/ | Precondition: a non-encoded buffer. Postcondition: on-disk encoding | beforeWriteToDisk | {
"repo_name": "zqxjjj/NobidaBase",
"path": "target/hbase-0.94.9/hbase-0.94.9/src/main/java/org/apache/hadoop/hbase/io/hfile/HFileDataBlockEncoderImpl.java",
"license": "apache-2.0",
"size": 8303
} | [
"java.nio.ByteBuffer",
"org.apache.hadoop.hbase.io.encoding.DataBlockEncoding",
"org.apache.hadoop.hbase.util.Pair"
] | import java.nio.ByteBuffer; import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding; import org.apache.hadoop.hbase.util.Pair; | import java.nio.*; import org.apache.hadoop.hbase.io.encoding.*; import org.apache.hadoop.hbase.util.*; | [
"java.nio",
"org.apache.hadoop"
] | java.nio; org.apache.hadoop; | 96,416 |
public static <D> Predicate inAny(Expression<D> left, Iterable<? extends Collection<? extends D>> lists) {
BooleanBuilder rv = new BooleanBuilder();
for (Collection<? extends D> list : lists) {
rv.or(in(left, list));
}
return rv;
} | static <D> Predicate function(Expression<D> left, Iterable<? extends Collection<? extends D>> lists) { BooleanBuilder rv = new BooleanBuilder(); for (Collection<? extends D> list : lists) { rv.or(in(left, list)); } return rv; } | /**
* Create a {@code left in right or...} expression for each list
*
* @param <D> element type
* @param left
* @param lists
* @return a {@code left in right or...} expression
*/ | Create a left in right or... expression for each list | inAny | {
"repo_name": "dharaburda/querydsl",
"path": "querydsl-core/src/main/java/com/querydsl/core/types/ExpressionUtils.java",
"license": "apache-2.0",
"size": 26720
} | [
"com.querydsl.core.BooleanBuilder",
"java.util.Collection"
] | import com.querydsl.core.BooleanBuilder; import java.util.Collection; | import com.querydsl.core.*; import java.util.*; | [
"com.querydsl.core",
"java.util"
] | com.querydsl.core; java.util; | 2,687,073 |
private void readHeaders()
throws IOException
{
readIdentificationHeader();
readCommentAndCodebookHeaders();
processComments();
} | void function() throws IOException { readIdentificationHeader(); readCommentAndCodebookHeaders(); processComments(); } | /** Read and process all three vorbis headers.
*/ | Read and process all three vorbis headers | readHeaders | {
"repo_name": "srnsw/xena",
"path": "plugins/audio/ext/src/tritonus/src/classes/org/tritonus/sampled/convert/pvorbis/VorbisFormatConversionProvider.java",
"license": "gpl-3.0",
"size": 30079
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,896,876 |
public int getMetaFromState(IBlockState state)
{
int i = 0;
if (state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER)
{
i = i | 8;
if (state.getValue(HINGE) == BlockDoor.EnumHingePosition.RIGHT)
{
i |= 1;
}
if (((Boolean)state.getValue(POWERED)).booleanValue())
{
i |= 2;
}
}
else
{
i = i | ((EnumFacing)state.getValue(FACING)).rotateY().getHorizontalIndex();
if (((Boolean)state.getValue(OPEN)).booleanValue())
{
i |= 4;
}
}
return i;
} | int function(IBlockState state) { int i = 0; if (state.getValue(HALF) == BlockDoor.EnumDoorHalf.UPPER) { i = i 8; if (state.getValue(HINGE) == BlockDoor.EnumHingePosition.RIGHT) { i = 1; } if (((Boolean)state.getValue(POWERED)).booleanValue()) { i = 2; } } else { i = i ((EnumFacing)state.getValue(FACING)).rotateY().getHorizontalIndex(); if (((Boolean)state.getValue(OPEN)).booleanValue()) { i = 4; } } return i; } | /**
* Convert the BlockState into the correct metadata value
*/ | Convert the BlockState into the correct metadata value | getMetaFromState | {
"repo_name": "TheGreatAndPowerfulWeegee/wipunknown",
"path": "build/tmp/recompileMc/sources/net/minecraft/block/BlockDoor.java",
"license": "gpl-3.0",
"size": 18499
} | [
"net.minecraft.block.state.IBlockState",
"net.minecraft.util.EnumFacing"
] | import net.minecraft.block.state.IBlockState; import net.minecraft.util.EnumFacing; | import net.minecraft.block.state.*; import net.minecraft.util.*; | [
"net.minecraft.block",
"net.minecraft.util"
] | net.minecraft.block; net.minecraft.util; | 2,664,035 |
private byte[] readSampleData(String filePath) {
File sampleFile = new File(filePath);
byte[] buffer = new byte[(int) sampleFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(sampleFile);
readFill(fis, buffer);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return buffer;
} | byte[] function(String filePath) { File sampleFile = new File(filePath); byte[] buffer = new byte[(int) sampleFile.length()]; FileInputStream fis = null; try { fis = new FileInputStream(sampleFile); readFill(fis, buffer); } catch (IOException e) { throw new RuntimeException(e); } finally { try { fis.close(); } catch (IOException e) { throw new RuntimeException(e); } } return buffer; } | /**
* Sample mainframe data for a single record come from a file.
* <p>
* In a real situation there would be more than one record in the file but
* we keep things simple here.
*
* @return a buffer full of mainframe data
*/ | Sample mainframe data for a single record come from a file. In a real situation there would be more than one record in the file but we keep things simple here | readSampleData | {
"repo_name": "legsem/legstar-core2",
"path": "legstar-base-generator/src/test/java/legstar/samples/custdat/CustdatSample.java",
"license": "agpl-3.0",
"size": 3405
} | [
"java.io.File",
"java.io.FileInputStream",
"java.io.IOException"
] | import java.io.File; import java.io.FileInputStream; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,402,080 |
private Component createComboRender() {
ComboBoxModel<ResultRenderer> nodesModel = new DefaultComboBoxModel<>();
// drop-down list for renderer
selectRenderPanel = new JComboBox<>(nodesModel);
selectRenderPanel.setActionCommand(COMBO_CHANGE_COMMAND);
selectRenderPanel.addActionListener(this);
// if no results render in jmeter.properties, load Standard (default)
List<String> classesToAdd = Collections.<String>emptyList();
try {
classesToAdd = JMeterUtils.findClassesThatExtend(ResultRenderer.class);
} catch (IOException e1) {
// ignored
}
String textRenderer = JMeterUtils.getResString("view_results_render_text"); // $NON-NLS-1$
Object textObject = null;
Map<String, ResultRenderer> map = new HashMap<>(classesToAdd.size());
for (String clazz : classesToAdd) {
try {
// Instantiate render classes
final ResultRenderer renderer = (ResultRenderer) Class.forName(clazz).newInstance();
if (textRenderer.equals(renderer.toString())){
textObject=renderer;
}
renderer.setBackgroundColor(getBackground());
map.put(renderer.getClass().getName(), renderer);
} catch (Exception e) {
log.warn("Error loading result renderer:" + clazz, e);
}
}
if(VIEWERS_ORDER.length()>0) {
String[] keys = VIEWERS_ORDER.split(",");
for (String key : keys) {
if(key.startsWith(".")) {
key = "org.apache.jmeter.visualizers"+key; //$NON-NLS-1$
}
ResultRenderer renderer = map.remove(key);
if(renderer != null) {
selectRenderPanel.addItem(renderer);
} else {
log.warn("Missing (check spelling error in renderer name) or already added(check doublon) " +
"result renderer, check property 'view.results.tree.renderers_order', renderer name:'"+key+"'");
}
}
}
// Add remaining (plugins or missed in property)
for (ResultRenderer renderer : map.values()) {
selectRenderPanel.addItem(renderer);
}
nodesModel.setSelectedItem(textObject); // preset to "Text" option
return selectRenderPanel;
} | Component function() { ComboBoxModel<ResultRenderer> nodesModel = new DefaultComboBoxModel<>(); selectRenderPanel = new JComboBox<>(nodesModel); selectRenderPanel.setActionCommand(COMBO_CHANGE_COMMAND); selectRenderPanel.addActionListener(this); List<String> classesToAdd = Collections.<String>emptyList(); try { classesToAdd = JMeterUtils.findClassesThatExtend(ResultRenderer.class); } catch (IOException e1) { } String textRenderer = JMeterUtils.getResString(STR); Object textObject = null; Map<String, ResultRenderer> map = new HashMap<>(classesToAdd.size()); for (String clazz : classesToAdd) { try { final ResultRenderer renderer = (ResultRenderer) Class.forName(clazz).newInstance(); if (textRenderer.equals(renderer.toString())){ textObject=renderer; } renderer.setBackgroundColor(getBackground()); map.put(renderer.getClass().getName(), renderer); } catch (Exception e) { log.warn(STR + clazz, e); } } if(VIEWERS_ORDER.length()>0) { String[] keys = VIEWERS_ORDER.split(","); for (String key : keys) { if(key.startsWith(".")) { key = STR+key; } ResultRenderer renderer = map.remove(key); if(renderer != null) { selectRenderPanel.addItem(renderer); } else { log.warn(STR + STR+key+"'"); } } } for (ResultRenderer renderer : map.values()) { selectRenderPanel.addItem(renderer); } nodesModel.setSelectedItem(textObject); return selectRenderPanel; } | /**
* Create the drop-down list to changer render
* @return List of all render (implement ResultsRender)
*/ | Create the drop-down list to changer render | createComboRender | {
"repo_name": "hemikak/jmeter",
"path": "src/components/org/apache/jmeter/visualizers/ViewResultsFullVisualizer.java",
"license": "apache-2.0",
"size": 17457
} | [
"java.awt.Component",
"java.io.IOException",
"java.util.Collections",
"java.util.HashMap",
"java.util.List",
"java.util.Map",
"javax.swing.ComboBoxModel",
"javax.swing.DefaultComboBoxModel",
"javax.swing.JComboBox",
"org.apache.jmeter.util.JMeterUtils"
] | import java.awt.Component; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import org.apache.jmeter.util.JMeterUtils; | import java.awt.*; import java.io.*; import java.util.*; import javax.swing.*; import org.apache.jmeter.util.*; | [
"java.awt",
"java.io",
"java.util",
"javax.swing",
"org.apache.jmeter"
] | java.awt; java.io; java.util; javax.swing; org.apache.jmeter; | 1,607,083 |
public HashMap<String, Mat> process( HashMap<String, Mat> inputs ){
if(!inputs.containsKey(INPUT_KEY))
throw new IllegalArgumentException("The input to process must contain: " + INPUT_KEY);
HashMap<String, Mat> result = new HashMap<String, Mat>();
Mat input = inputs.get(INPUT_KEY);
result.put(OUTPUT_KEY, this._filter.applyFilter(input) );
return result;
} | HashMap<String, Mat> function( HashMap<String, Mat> inputs ){ if(!inputs.containsKey(INPUT_KEY)) throw new IllegalArgumentException(STR + INPUT_KEY); HashMap<String, Mat> result = new HashMap<String, Mat>(); Mat input = inputs.get(INPUT_KEY); result.put(OUTPUT_KEY, this._filter.applyFilter(input) ); return result; } | /**
*
* Feeds the input passed in at INPUT_KEY through a filter
* and returns the result at the key OUTPUT_KEY.
*
* @author Kyle Bartush
* @since 0.1
*/ | Feeds the input passed in at INPUT_KEY through a filter and returns the result at the key OUTPUT_KEY | process | {
"repo_name": "bartushk/picle",
"path": "src/main/java/net/bartushk/picle/Filter/FilterOperation.java",
"license": "mit",
"size": 2435
} | [
"java.util.HashMap",
"org.opencv.core.Mat"
] | import java.util.HashMap; import org.opencv.core.Mat; | import java.util.*; import org.opencv.core.*; | [
"java.util",
"org.opencv.core"
] | java.util; org.opencv.core; | 739,919 |
public void build(Map searchParams) throws SQLException, InvalidFormException {
if (searchParams != null) {
setParams(searchParams);
// setTempTblName();
// setInputTempTblName();
setWholeGenomeFlag();
DBconnection conn = null;
try {
conn = getConnection();
// populate the inputTempTbl with locus names provided by
// text box or file
setLociList(conn);
// Use just one query id, since results will be the same if the locus list is the same
setQueryID(getInputQueryID());
deleteRows(conn, "all");
storeSlimEntries(conn);
groupRows(conn);
deleteRows(conn, "ancount");
deleteNullSQL(conn);
} finally {
if (conn != null)
returnConnection(conn);
}
}
} | void function(Map searchParams) throws SQLException, InvalidFormException { if (searchParams != null) { setParams(searchParams); setWholeGenomeFlag(); DBconnection conn = null; try { conn = getConnection(); setLociList(conn); setQueryID(getInputQueryID()); deleteRows(conn, "all"); storeSlimEntries(conn); groupRows(conn); deleteRows(conn, STR); deleteNullSQL(conn); } finally { if (conn != null) returnConnection(conn); } } } | /**
* takes in the user-supplied parameters from the form and the user's session
* id and builds the set of goslim terms for the provided set of loci
*/ | takes in the user-supplied parameters from the form and the user's session id and builds the set of goslim terms for the provided set of loci | build | {
"repo_name": "tair/tairwebapp",
"path": "src/org/tair/search/goslim/GOSlimBuilder.java",
"license": "gpl-3.0",
"size": 20997
} | [
"java.sql.SQLException",
"java.util.Map",
"org.tair.tfc.DBconnection",
"org.tair.utilities.InvalidFormException"
] | import java.sql.SQLException; import java.util.Map; import org.tair.tfc.DBconnection; import org.tair.utilities.InvalidFormException; | import java.sql.*; import java.util.*; import org.tair.tfc.*; import org.tair.utilities.*; | [
"java.sql",
"java.util",
"org.tair.tfc",
"org.tair.utilities"
] | java.sql; java.util; org.tair.tfc; org.tair.utilities; | 835,930 |
private Object serializeAndDeserialize(Object value) throws Exception {
ScriptResponseMessage msg = new ScriptResponseMessage();
msg.Results.set(value);
RexProSerializer serializer = getSerializer();
byte[] bytes = serializer.serialize(msg, ScriptResponseMessage.class);
return serializer.deserialize(bytes, ScriptResponseMessage.class);
} | Object function(Object value) throws Exception { ScriptResponseMessage msg = new ScriptResponseMessage(); msg.Results.set(value); RexProSerializer serializer = getSerializer(); byte[] bytes = serializer.serialize(msg, ScriptResponseMessage.class); return serializer.deserialize(bytes, ScriptResponseMessage.class); } | /**
* puts the given value into a serialized response message, then
* deserializes it and returns the result
*
* @param value the value to serialize
* @return
*/ | puts the given value into a serialized response message, then deserializes it and returns the result | serializeAndDeserialize | {
"repo_name": "alszeb/rexster",
"path": "rexster-protocol/src/test/java/com/tinkerpop/rexster/protocol/serializer/AbstractResultSerializerTest.java",
"license": "bsd-3-clause",
"size": 7887
} | [
"com.tinkerpop.rexster.protocol.msg.ScriptResponseMessage"
] | import com.tinkerpop.rexster.protocol.msg.ScriptResponseMessage; | import com.tinkerpop.rexster.protocol.msg.*; | [
"com.tinkerpop.rexster"
] | com.tinkerpop.rexster; | 2,352,968 |
public Task setNameLabelAsync(Connection c, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.VDI.set_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
} | Task function(Connection c, String value) throws BadServerResponse, XenAPIException, XmlRpcException { String method_call = STR; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)}; Map response = c.dispatch(method_call, method_params); Object result = response.get("Value"); return Types.toTask(result); } | /**
* Set the name label of the VDI. This can only happen when then its SR is currently attached.
*
* @param value The name lable for the VDI
* @return Task
*/ | Set the name label of the VDI. This can only happen when then its SR is currently attached | setNameLabelAsync | {
"repo_name": "mufaddalq/cloudstack-datera-driver",
"path": "deps/XenServerJava/src/com/xensource/xenapi/VDI.java",
"license": "apache-2.0",
"size": 84941
} | [
"com.xensource.xenapi.Types",
"java.util.Map",
"org.apache.xmlrpc.XmlRpcException"
] | import com.xensource.xenapi.Types; import java.util.Map; import org.apache.xmlrpc.XmlRpcException; | import com.xensource.xenapi.*; import java.util.*; import org.apache.xmlrpc.*; | [
"com.xensource.xenapi",
"java.util",
"org.apache.xmlrpc"
] | com.xensource.xenapi; java.util; org.apache.xmlrpc; | 963,019 |
public void setRemoteAddress(InetAddress adr) {
m_RemoteAddress = adr;
}//setAddress | void function(InetAddress adr) { m_RemoteAddress = adr; } | /**
* Sets the destination <tt>InetAddress</tt> of this
* <tt>UDPSlaveTerminal</tt>.
*
* @param adr the destination address as <tt>InetAddress</tt>.
*/ | Sets the destination InetAddress of this UDPSlaveTerminal | setRemoteAddress | {
"repo_name": "dog-gateway/jamod-rtu-over-tcp",
"path": "src/net/wimpi/modbus/net/UDPMasterTerminal.java",
"license": "apache-2.0",
"size": 6278
} | [
"java.net.InetAddress"
] | import java.net.InetAddress; | import java.net.*; | [
"java.net"
] | java.net; | 184,061 |
protected void init()
{
setPaint(Color.BLACK);
setFont(FONT);
isOptimized = true;
} | void function() { setPaint(Color.BLACK); setFont(FONT); isOptimized = true; } | /**
* Initializes this graphics object. This must be called by subclasses in
* order to correctly initialize the state of this object.
*/ | Initializes this graphics object. This must be called by subclasses in order to correctly initialize the state of this object | init | {
"repo_name": "SanDisk-Open-Source/SSD_Dashboard",
"path": "uefi/gcc/gcc-4.6.3/libjava/classpath/gnu/java/awt/java2d/AbstractGraphics2D.java",
"license": "gpl-2.0",
"size": 64351
} | [
"java.awt.Color"
] | import java.awt.Color; | import java.awt.*; | [
"java.awt"
] | java.awt; | 15,815 |
public final native void setStyles(JsArray<Style> styles); | final native void function(JsArray<Style> styles); | /** sets FeatureOverlay style
*
* @param styles
*/ | sets FeatureOverlay style | setStyles | {
"repo_name": "grandeemme/v-ol3",
"path": "gwt-ol3/src/main/java/org/vaadin/gwtol3/client/interaction/ModifyInteractionOptions.java",
"license": "apache-2.0",
"size": 1227
} | [
"com.google.gwt.core.client.JsArray",
"org.vaadin.gwtol3.client.style.Style"
] | import com.google.gwt.core.client.JsArray; import org.vaadin.gwtol3.client.style.Style; | import com.google.gwt.core.client.*; import org.vaadin.gwtol3.client.style.*; | [
"com.google.gwt",
"org.vaadin.gwtol3"
] | com.google.gwt; org.vaadin.gwtol3; | 250,584 |
@Override
public void onAudioPatchListUpdate(AudioPatch[] patchList) {
if (mPowerStatus != POWER_UP) {
Log.d(TAG, "onAudioPatchListUpdate, not power up");
return;
}
if (!mIsAudioFocusHeld) {
Log.d(TAG, "onAudioPatchListUpdate no audio focus");
return;
}
if (mAudioPatch != null) {
ArrayList<AudioPatch> patches = new ArrayList<AudioPatch>();
mAudioManager.listAudioPatches(patches);
// When BT or WFD is connected, native will remove the patch (mixer -> device).
// Need to recreate AudioRecord and AudioTrack for this case.
if (isPatchMixerToDeviceRemoved(patches)) {
Log.d(TAG, "onAudioPatchListUpdate reinit for BT or WFD connected");
initAudioRecordSink();
startRender();
return;
}
if (isPatchMixerToEarphone(patches)) {
stopRender();
} else {
releaseAudioPatch();
startRender();
}
} else if (mIsRender) {
ArrayList<AudioPatch> patches = new ArrayList<AudioPatch>();
mAudioManager.listAudioPatches(patches);
if (isPatchMixerToEarphone(patches)) {
int status;
stopAudioTrack();
stopRender();
status = createAudioPatch();
if (status != AudioManager.SUCCESS){
Log.d(TAG, "onAudioPatchListUpdate: fallback as createAudioPatch failed");
startRender();
}
}
}
} | void function(AudioPatch[] patchList) { if (mPowerStatus != POWER_UP) { Log.d(TAG, STR); return; } if (!mIsAudioFocusHeld) { Log.d(TAG, STR); return; } if (mAudioPatch != null) { ArrayList<AudioPatch> patches = new ArrayList<AudioPatch>(); mAudioManager.listAudioPatches(patches); if (isPatchMixerToDeviceRemoved(patches)) { Log.d(TAG, STR); initAudioRecordSink(); startRender(); return; } if (isPatchMixerToEarphone(patches)) { stopRender(); } else { releaseAudioPatch(); startRender(); } } else if (mIsRender) { ArrayList<AudioPatch> patches = new ArrayList<AudioPatch>(); mAudioManager.listAudioPatches(patches); if (isPatchMixerToEarphone(patches)) { int status; stopAudioTrack(); stopRender(); status = createAudioPatch(); if (status != AudioManager.SUCCESS){ Log.d(TAG, STR); startRender(); } } } } | /**
* Callback method called upon audio patch list update.
*
* @param patchList the updated list of audio patches
*/ | Callback method called upon audio patch list update | onAudioPatchListUpdate | {
"repo_name": "KobeMing/FMRadio",
"path": "src/com/android/fmradio/FmService.java",
"license": "apache-2.0",
"size": 97210
} | [
"android.media.AudioManager",
"android.media.AudioPatch",
"android.util.Log",
"java.util.ArrayList"
] | import android.media.AudioManager; import android.media.AudioPatch; import android.util.Log; import java.util.ArrayList; | import android.media.*; import android.util.*; import java.util.*; | [
"android.media",
"android.util",
"java.util"
] | android.media; android.util; java.util; | 353,840 |
@Test
public void testValidatity() {
assertEquals(Validity.True, testXmlModule.isWellFormed());
assertEquals(Validity.True, testXmlModule.isValid());
}
| void function() { assertEquals(Validity.True, testXmlModule.isWellFormed()); assertEquals(Validity.True, testXmlModule.isValid()); } | /**
* Test method for Validity
*/ | Test method for Validity | testValidatity | {
"repo_name": "opf-labs/jhove2",
"path": "src/test/java/org/jhove2/module/format/xml/XmlExternalParsedEntityTest.java",
"license": "bsd-2-clause",
"size": 2970
} | [
"org.jhove2.module.format.Validator",
"org.junit.Assert"
] | import org.jhove2.module.format.Validator; import org.junit.Assert; | import org.jhove2.module.format.*; import org.junit.*; | [
"org.jhove2.module",
"org.junit"
] | org.jhove2.module; org.junit; | 1,895,237 |
public Object[] getVisibleExpandedElements() {
ArrayList v = new ArrayList();
internalCollectVisibleExpanded(v, getControl());
return v.toArray();
} | Object[] function() { ArrayList v = new ArrayList(); internalCollectVisibleExpanded(v, getControl()); return v.toArray(); } | /**
* Gets the expanded elements that are visible to the user. An expanded
* element is only visible if the parent is expanded.
*
* @return the visible expanded elements
* @since 2.0
*/ | Gets the expanded elements that are visible to the user. An expanded element is only visible if the parent is expanded | getVisibleExpandedElements | {
"repo_name": "neelance/jface4ruby",
"path": "jface4ruby/src/org/eclipse/jface/viewers/AbstractTreeViewer.java",
"license": "epl-1.0",
"size": 91053
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 677,676 |
private String buildListContext(SessionState state, Context context)
{
// put the service in the context (used for allow update calls on each site)
context.put("service", SiteService.getInstance());
// prepare the paging of realms
List sites = prepPage(state);
context.put("sites", sites);
// we need the Realms, too!
context.put("realms", AuthzGroupService.getInstance());
// build the menu
Menu bar = new MenuImpl();
if (SiteService.allowAddSite(null))
{
bar.add(new MenuEntry(rb.getString("sitact.newsit"), "doNew"));
}
// add the paging commands
//addListPagingMenus(bar, state);
int pageSize = Integer.valueOf(state.getAttribute(STATE_PAGESIZE).toString()).intValue();
int currentPageNubmer = Integer.valueOf(state.getAttribute(STATE_CURRENT_PAGE).toString()).intValue();
int startNumber = pageSize * (currentPageNubmer - 1) + 1;
int endNumber = pageSize * currentPageNubmer;
int totalNumber = 0;
try
{
totalNumber = Integer.valueOf(state.getAttribute(STATE_NUM_MESSAGES).toString()).intValue();
}
catch (java.lang.NullPointerException ignore) {}
catch (java.lang.NumberFormatException ignore) {}
if (totalNumber < endNumber) endNumber = totalNumber;
context.put("startEndTotalNumbers", new Integer[]{Integer.valueOf(startNumber),Integer.valueOf(endNumber),Integer.valueOf(totalNumber)});
context.put("totalNumber", Integer.valueOf(totalNumber));
pagingInfoToContext(state, context);
// add the search commands
addSearchMenus(bar, state);
// more search
bar.add(new MenuDivider());
bar
.add(new MenuField(FORM_SEARCH_SITEID, "toolbar2", "doSearch_site_id", (String) state
.getAttribute(STATE_SEARCH_SITE_ID)));
bar.add(new MenuEntry(rb.getString("sitlis.sid"), null, true, MenuItem.CHECKED_NA, "doSearch_site_id", "toolbar2"));
if (state.getAttribute(STATE_SEARCH_SITE_ID) != null)
{
bar.add(new MenuEntry(rb_praII.getString("sea.cleasea"), "doSearch_clear"));
}
bar.add(new MenuDivider());
bar
.add(new MenuField(FORM_SEARCH_USERID, "toolbar3", "doSearch_user_id", (String) state
.getAttribute(STATE_SEARCH_USER_ID)));
bar.add(new MenuEntry(rb.getString("sitlis.uid"), null, true, MenuItem.CHECKED_NA, "doSearch_user_id", "toolbar3"));
if (state.getAttribute(STATE_SEARCH_USER_ID) != null)
{
bar.add(new MenuEntry(rb_praII.getString("sea.cleasea"), "doSearch_clear"));
}
// add the refresh commands
addRefreshMenus(bar, state);
if (bar.size() > 0)
{
context.put(Menu.CONTEXT_MENU, bar);
}
// inform the observing courier that we just updated the page...
// if there are pending requests to do so they can be cleared
justDelivered(state);
return "_list";
} // buildListContext | String function(SessionState state, Context context) { context.put(STR, SiteService.getInstance()); List sites = prepPage(state); context.put("sites", sites); context.put(STR, AuthzGroupService.getInstance()); Menu bar = new MenuImpl(); if (SiteService.allowAddSite(null)) { bar.add(new MenuEntry(rb.getString(STR), "doNew")); } int pageSize = Integer.valueOf(state.getAttribute(STATE_PAGESIZE).toString()).intValue(); int currentPageNubmer = Integer.valueOf(state.getAttribute(STATE_CURRENT_PAGE).toString()).intValue(); int startNumber = pageSize * (currentPageNubmer - 1) + 1; int endNumber = pageSize * currentPageNubmer; int totalNumber = 0; try { totalNumber = Integer.valueOf(state.getAttribute(STATE_NUM_MESSAGES).toString()).intValue(); } catch (java.lang.NullPointerException ignore) {} catch (java.lang.NumberFormatException ignore) {} if (totalNumber < endNumber) endNumber = totalNumber; context.put(STR, new Integer[]{Integer.valueOf(startNumber),Integer.valueOf(endNumber),Integer.valueOf(totalNumber)}); context.put(STR, Integer.valueOf(totalNumber)); pagingInfoToContext(state, context); addSearchMenus(bar, state); bar.add(new MenuDivider()); bar .add(new MenuField(FORM_SEARCH_SITEID, STR, STR, (String) state .getAttribute(STATE_SEARCH_SITE_ID))); bar.add(new MenuEntry(rb.getString(STR), null, true, MenuItem.CHECKED_NA, STR, STR)); if (state.getAttribute(STATE_SEARCH_SITE_ID) != null) { bar.add(new MenuEntry(rb_praII.getString(STR), STR)); } bar.add(new MenuDivider()); bar .add(new MenuField(FORM_SEARCH_USERID, STR, STR, (String) state .getAttribute(STATE_SEARCH_USER_ID))); bar.add(new MenuEntry(rb.getString(STR), null, true, MenuItem.CHECKED_NA, STR, STR)); if (state.getAttribute(STATE_SEARCH_USER_ID) != null) { bar.add(new MenuEntry(rb_praII.getString(STR), STR)); } addRefreshMenus(bar, state); if (bar.size() > 0) { context.put(Menu.CONTEXT_MENU, bar); } justDelivered(state); return "_list"; } | /**
* Build the context for the main list mode.
*/ | Build the context for the main list mode | buildListContext | {
"repo_name": "kingmook/sakai",
"path": "site/site-tool/tool/src/java/org/sakaiproject/site/tool/AdminSitesAction.java",
"license": "apache-2.0",
"size": 77028
} | [
"java.util.List",
"org.sakaiproject.authz.cover.AuthzGroupService",
"org.sakaiproject.cheftool.Context",
"org.sakaiproject.cheftool.api.Menu",
"org.sakaiproject.cheftool.api.MenuItem",
"org.sakaiproject.cheftool.menu.MenuDivider",
"org.sakaiproject.cheftool.menu.MenuEntry",
"org.sakaiproject.cheftool.menu.MenuField",
"org.sakaiproject.cheftool.menu.MenuImpl",
"org.sakaiproject.event.api.SessionState",
"org.sakaiproject.site.cover.SiteService"
] | import java.util.List; import org.sakaiproject.authz.cover.AuthzGroupService; import org.sakaiproject.cheftool.Context; import org.sakaiproject.cheftool.api.Menu; import org.sakaiproject.cheftool.api.MenuItem; import org.sakaiproject.cheftool.menu.MenuDivider; import org.sakaiproject.cheftool.menu.MenuEntry; import org.sakaiproject.cheftool.menu.MenuField; import org.sakaiproject.cheftool.menu.MenuImpl; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.site.cover.SiteService; | import java.util.*; import org.sakaiproject.authz.cover.*; import org.sakaiproject.cheftool.*; import org.sakaiproject.cheftool.api.*; import org.sakaiproject.cheftool.menu.*; import org.sakaiproject.event.api.*; import org.sakaiproject.site.cover.*; | [
"java.util",
"org.sakaiproject.authz",
"org.sakaiproject.cheftool",
"org.sakaiproject.event",
"org.sakaiproject.site"
] | java.util; org.sakaiproject.authz; org.sakaiproject.cheftool; org.sakaiproject.event; org.sakaiproject.site; | 2,458,985 |
@Override
public boolean serviceStopped(ComponentIOService service) {
boolean result = super.serviceStopped(service);
if (result) {
Map<String, Object> sessionData = service.getSessionData();
String hostname = (String) sessionData.get(ComponentIOService.HOSTNAME_KEY);
if ((hostname != null) && !hostname.isEmpty()) {
List<ComponentConnection> conns = service.getRefObject();
if (conns != null) {
for (ComponentConnection conn : conns) {
boolean moreConnections = removeComponentConnection(conn.getDomain(), conn);
if (!moreConnections) {
removeRoutings(conn.getDomain());
}
}
} else {
// Nothing to do, let's log this however.
log.finer("Closing XMPPIOService has not yet set ComponentConnection as RefObject: "
+ hostname + ", id: " + service.getUniqueId());
}
} else {
// Stopped service which hasn't sent initial stream open yet
log.finer("Stopped service which hasn't sent initial stream open yet"
+ service.getUniqueId());
}
ConnectionType type = service.connectionType();
if (type == ConnectionType.connect) {
addWaitingTask(sessionData);
// reconnectService(sessionData, connectionDelay);
} // end of if (type == ConnectionType.connect)
}
return result;
}
// ~--- set methods ---------------------------------------------------------- | boolean function(ComponentIOService service) { boolean result = super.serviceStopped(service); if (result) { Map<String, Object> sessionData = service.getSessionData(); String hostname = (String) sessionData.get(ComponentIOService.HOSTNAME_KEY); if ((hostname != null) && !hostname.isEmpty()) { List<ComponentConnection> conns = service.getRefObject(); if (conns != null) { for (ComponentConnection conn : conns) { boolean moreConnections = removeComponentConnection(conn.getDomain(), conn); if (!moreConnections) { removeRoutings(conn.getDomain()); } } } else { log.finer(STR + hostname + STR + service.getUniqueId()); } } else { log.finer(STR + service.getUniqueId()); } ConnectionType type = service.connectionType(); if (type == ConnectionType.connect) { addWaitingTask(sessionData); } } return result; } | /**
* Method description
*
*
* @param service
*
* @return
*/ | Method description | serviceStopped | {
"repo_name": "Smartupz/tigase-server",
"path": "src/main/java/tigase/server/ext/ComponentProtocol.java",
"license": "agpl-3.0",
"size": 30001
} | [
"java.util.List",
"java.util.Map"
] | import java.util.List; import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 827,086 |
public void setStateDescription(@Nullable CharSequence stateDescription) {
if (BuildCompat.isAtLeastR()) {
mInfo.setStateDescription(stateDescription);
} else if (Build.VERSION.SDK_INT >= 19) {
mInfo.getExtras().putCharSequence(STATE_DESCRIPTION_KEY, stateDescription);
}
} | void function(@Nullable CharSequence stateDescription) { if (BuildCompat.isAtLeastR()) { mInfo.setStateDescription(stateDescription); } else if (Build.VERSION.SDK_INT >= 19) { mInfo.getExtras().putCharSequence(STATE_DESCRIPTION_KEY, stateDescription); } } | /**
* Sets the state description of this node.
* <p>
* <strong>Note:</strong> Cannot be called from an
* {@link android.accessibilityservice.AccessibilityService}.
* This class is made immutable before being delivered to an AccessibilityService.
* </p>
*
* @param stateDescription the state description of this node.
* @throws IllegalStateException If called from an AccessibilityService.
*/ | Sets the state description of this node. Note: Cannot be called from an <code>android.accessibilityservice.AccessibilityService</code>. This class is made immutable before being delivered to an AccessibilityService. | setStateDescription | {
"repo_name": "AndroidX/androidx",
"path": "core/core/src/main/java/androidx/core/view/accessibility/AccessibilityNodeInfoCompat.java",
"license": "apache-2.0",
"size": 160272
} | [
"android.os.Build",
"androidx.annotation.Nullable",
"androidx.core.os.BuildCompat"
] | import android.os.Build; import androidx.annotation.Nullable; import androidx.core.os.BuildCompat; | import android.os.*; import androidx.annotation.*; import androidx.core.os.*; | [
"android.os",
"androidx.annotation",
"androidx.core"
] | android.os; androidx.annotation; androidx.core; | 10,946 |
// -------------------------------------------------------------------------
@Test(expectedExceptions = IllegalArgumentException.class)
public void testGetSingleNullId1() {
new RemoteConventionSource(_baseUri).getSingle((ExternalId) null);
} | @Test(expectedExceptions = IllegalArgumentException.class) void function() { new RemoteConventionSource(_baseUri).getSingle((ExternalId) null); } | /**
* Tests that the external id cannot be null.
*/ | Tests that the external id cannot be null | testGetSingleNullId1 | {
"repo_name": "McLeodMoores/starling",
"path": "projects/core-rest-client/src/test/java/com/opengamma/core/convention/impl/RemoteConventionSourceTest.java",
"license": "apache-2.0",
"size": 21252
} | [
"com.opengamma.id.ExternalId",
"org.testng.annotations.Test"
] | import com.opengamma.id.ExternalId; import org.testng.annotations.Test; | import com.opengamma.id.*; import org.testng.annotations.*; | [
"com.opengamma.id",
"org.testng.annotations"
] | com.opengamma.id; org.testng.annotations; | 2,149,952 |
public Object createConnectionFactory() throws ResourceException
{
throw new ResourceException("This resource adapter doesn't support non-managed environments");
} | Object function() throws ResourceException { throw new ResourceException(STR); } | /**
* Creates a Connection Factory instance.
*
* @return EIS-specific Connection Factory instance or javax.resource.cci.ConnectionFactory instance
* @throws ResourceException Generic exception
*/ | Creates a Connection Factory instance | createConnectionFactory | {
"repo_name": "ironjacamar/ironjacamar",
"path": "deployers/tests/src/test/java/org/jboss/jca/deployers/test/rars/inout/SimpleManagedConnectionFactory1.java",
"license": "lgpl-2.1",
"size": 7734
} | [
"javax.resource.ResourceException"
] | import javax.resource.ResourceException; | import javax.resource.*; | [
"javax.resource"
] | javax.resource; | 66,982 |
public void dump(OutputStream os); | void function(OutputStream os); | /**
* Dumps a formatted JSON string to the supplied out stream
* <p>
* This is mostly useful for debugging
*
* @param os The output stream the JSON should be dumped too.
*/ | Dumps a formatted JSON string to the supplied out stream This is mostly useful for debugging | dump | {
"repo_name": "OpenLiberty/open-liberty",
"path": "dev/com.ibm.ws.repository/src/com/ibm/ws/repository/resources/AttachmentResource.java",
"license": "epl-1.0",
"size": 4276
} | [
"java.io.OutputStream"
] | import java.io.OutputStream; | import java.io.*; | [
"java.io"
] | java.io; | 401,695 |
return new WebSocketCall(client, request);
}
private final Call call;
private final Random random;
private final String key;
WebSocketCall(OkHttpClient client, Request request) {
this(client, request, new SecureRandom());
}
WebSocketCall(OkHttpClient client, Request request, Random random) {
if (!"GET".equals(request.method())) {
throw new IllegalArgumentException("Request must be GET: " + request.method());
}
this.random = random;
byte[] nonce = new byte[16];
random.nextBytes(nonce);
key = ByteString.of(nonce).base64();
client = client.newBuilder()
.protocols(Collections.singletonList(Protocol.HTTP_1_1))
.build();
request = request.newBuilder()
.header("Upgrade", "websocket")
.header("Connection", "Upgrade")
.header("Sec-WebSocket-Key", key)
.header("Sec-WebSocket-Version", "13")
.build();
call = client.newCall(request);
} | return new WebSocketCall(client, request); } private final Call call; private final Random random; private final String key; WebSocketCall(OkHttpClient client, Request request) { this(client, request, new SecureRandom()); } WebSocketCall(OkHttpClient client, Request request, Random random) { if (!"GET".equals(request.method())) { throw new IllegalArgumentException(STR + request.method()); } this.random = random; byte[] nonce = new byte[16]; random.nextBytes(nonce); key = ByteString.of(nonce).base64(); client = client.newBuilder() .protocols(Collections.singletonList(Protocol.HTTP_1_1)) .build(); request = request.newBuilder() .header(STR, STR) .header(STR, STR) .header(STR, key) .header(STR, "13") .build(); call = client.newCall(request); } | /**
* Prepares the {@code request} to create a web socket at some point in the future.
*/ | Prepares the request to create a web socket at some point in the future | create | {
"repo_name": "xph906/NewOKHttp",
"path": "okhttp-ws/src/main/java/okhttp3/ws/WebSocketCall.java",
"license": "apache-2.0",
"size": 6774
} | [
"java.security.SecureRandom",
"java.util.Collections",
"java.util.Random"
] | import java.security.SecureRandom; import java.util.Collections; import java.util.Random; | import java.security.*; import java.util.*; | [
"java.security",
"java.util"
] | java.security; java.util; | 95,533 |
public boolean doOptimization(MainWindow.WorkerMonitor monitor) {
// int noUserConstraints = constraintSet.getConstraints().size();
int dim = getDimension();
MatrixStore<BigDecimal> a = BigDenseStore.FACTORY.makeZero(dim, dim);
MatrixStore<BigDecimal> r = BigDenseStore.FACTORY.makeZero(1, dim);
for (int i=0;i<dim;i++) {
((BigDenseStore) r).set(0, i, avgVector.getEntry(i));
for (int j=0;j<dim;j++)
((BigDenseStore) a).set(i, j, covMatrix.getEntry(i, j));
}
BasicMatrix cm = BigMatrix.FACTORY.copy(a);
BasicMatrix er = BigMatrix.FACTORY.copy(r);
portfolioVolatility = new ArrayRealVector(expectedReturns.getDimension());
portfolioLossProb = new ArrayRealVector(expectedReturns.getDimension());
quoteAmounts = new int[expectedReturns.getDimension()][];
logger.debug(String.format("optimization setup complete: %d", expectedReturns.getDimension()));
ArrayList<Integer> shorted = new ArrayList<>();
for (int i=0;i<expectedReturns.getDimension();i++) {
final MarkowitzModel mm = new MarkowitzModel(cm, er);
mm.setTargetReturn(new BigDecimal(expectedReturns.getEntry(i)));
mm.setShortingAllowed(false);
if (constraints != null)
constraints.stream().forEach((cons) -> {
mm.addConstraint(cons.getLower(), cons.getUpper(), cons.getAssets());
});
BasicMatrix assetWeights = mm.getAssetWeights();
portfolioVolatility.setEntry(i, mm.getVolatility());
portfolioLossProb.setEntry(i, mm.getLossProbability());
// Convert weights to discrete amounts based on last available prices.
quoteAmounts[i] = new int[dim];
for (int j=0;j<dim;j++) {
Double curval = assetWeights.get(j, 0).doubleValue() * initialWealth / lastPrice.getEntry(j);
quoteAmounts[i][j] = curval.intValue();
if (curval.intValue() < 0 && !shorted.contains(i)) shorted.add(i);
}
logger.debug(String.format("er=%f\tpv=%f\tel=%f", expectedReturns.getEntry(i), portfolioVolatility.getEntry(i), portfolioLossProb.getEntry(i)));
try {
monitor.setValue((i+1)*100/expectedReturns.getDimension());
} catch (Exception ex) {
logger.error(ex);
}
}
int noel = expectedReturns.getDimension()-shorted.size();
expectedReturns = new ArrayRealVector(expectedReturns.getSubVector(0, noel));
portfolioVolatility = new ArrayRealVector(portfolioVolatility.getSubVector(0, noel));
portfolioLossProb = new ArrayRealVector(portfolioLossProb.getSubVector(0, noel));
int[][] amts = new int[noel][];
for (int i=0;i<noel;i++) {
amts[i] = new int[avgVector.getDimension()];
System.arraycopy(quoteAmounts[i], 0, amts[i], 0, avgVector.getDimension());
}
quoteAmounts = amts;
return true;
}
| boolean function(MainWindow.WorkerMonitor monitor) { int dim = getDimension(); MatrixStore<BigDecimal> a = BigDenseStore.FACTORY.makeZero(dim, dim); MatrixStore<BigDecimal> r = BigDenseStore.FACTORY.makeZero(1, dim); for (int i=0;i<dim;i++) { ((BigDenseStore) r).set(0, i, avgVector.getEntry(i)); for (int j=0;j<dim;j++) ((BigDenseStore) a).set(i, j, covMatrix.getEntry(i, j)); } BasicMatrix cm = BigMatrix.FACTORY.copy(a); BasicMatrix er = BigMatrix.FACTORY.copy(r); portfolioVolatility = new ArrayRealVector(expectedReturns.getDimension()); portfolioLossProb = new ArrayRealVector(expectedReturns.getDimension()); quoteAmounts = new int[expectedReturns.getDimension()][]; logger.debug(String.format(STR, expectedReturns.getDimension())); ArrayList<Integer> shorted = new ArrayList<>(); for (int i=0;i<expectedReturns.getDimension();i++) { final MarkowitzModel mm = new MarkowitzModel(cm, er); mm.setTargetReturn(new BigDecimal(expectedReturns.getEntry(i))); mm.setShortingAllowed(false); if (constraints != null) constraints.stream().forEach((cons) -> { mm.addConstraint(cons.getLower(), cons.getUpper(), cons.getAssets()); }); BasicMatrix assetWeights = mm.getAssetWeights(); portfolioVolatility.setEntry(i, mm.getVolatility()); portfolioLossProb.setEntry(i, mm.getLossProbability()); quoteAmounts[i] = new int[dim]; for (int j=0;j<dim;j++) { Double curval = assetWeights.get(j, 0).doubleValue() * initialWealth / lastPrice.getEntry(j); quoteAmounts[i][j] = curval.intValue(); if (curval.intValue() < 0 && !shorted.contains(i)) shorted.add(i); } logger.debug(String.format(STR, expectedReturns.getEntry(i), portfolioVolatility.getEntry(i), portfolioLossProb.getEntry(i))); try { monitor.setValue((i+1)*100/expectedReturns.getDimension()); } catch (Exception ex) { logger.error(ex); } } int noel = expectedReturns.getDimension()-shorted.size(); expectedReturns = new ArrayRealVector(expectedReturns.getSubVector(0, noel)); portfolioVolatility = new ArrayRealVector(portfolioVolatility.getSubVector(0, noel)); portfolioLossProb = new ArrayRealVector(portfolioLossProb.getSubVector(0, noel)); int[][] amts = new int[noel][]; for (int i=0;i<noel;i++) { amts[i] = new int[avgVector.getDimension()]; System.arraycopy(quoteAmounts[i], 0, amts[i], 0, avgVector.getDimension()); } quoteAmounts = amts; return true; } | /**
* Run the optimization.
* @param monitor Worker manager for gui update.
* @return True on success.
*/ | Run the optimization | doOptimization | {
"repo_name": "r-k-/MarketAnalysis",
"path": "src/marketanalysis/portfolio/PortfolioOptimization.java",
"license": "gpl-3.0",
"size": 26586
} | [
"java.math.BigDecimal",
"java.util.ArrayList",
"org.apache.commons.math.linear.ArrayRealVector",
"org.ojalgo.finance.portfolio.MarkowitzModel",
"org.ojalgo.matrix.BasicMatrix",
"org.ojalgo.matrix.BigMatrix",
"org.ojalgo.matrix.store.BigDenseStore",
"org.ojalgo.matrix.store.MatrixStore"
] | import java.math.BigDecimal; import java.util.ArrayList; import org.apache.commons.math.linear.ArrayRealVector; import org.ojalgo.finance.portfolio.MarkowitzModel; import org.ojalgo.matrix.BasicMatrix; import org.ojalgo.matrix.BigMatrix; import org.ojalgo.matrix.store.BigDenseStore; import org.ojalgo.matrix.store.MatrixStore; | import java.math.*; import java.util.*; import org.apache.commons.math.linear.*; import org.ojalgo.finance.portfolio.*; import org.ojalgo.matrix.*; import org.ojalgo.matrix.store.*; | [
"java.math",
"java.util",
"org.apache.commons",
"org.ojalgo.finance",
"org.ojalgo.matrix"
] | java.math; java.util; org.apache.commons; org.ojalgo.finance; org.ojalgo.matrix; | 2,256,597 |
private static SSLContext getTrustedSslContext(final File trustStoreFile, final String trustStorePassword,
final String trustStoreType) {
try {
if (!trustStoreFile.exists() || !trustStoreFile.canRead()) {
throw new FileNotFoundException("Truststore file cannot be located at " + trustStoreFile.getCanonicalPath());
}
final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType);
final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray();
try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) {
casTrustStore.load(casStream, trustStorePasswordCharArray);
}
final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray);
final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null);
final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore);
final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null);
final KeyManager[] keyManagers = {
new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager))
};
final TrustManager[] trustManagers = {
new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager))
};
final SSLContext context = SSLContexts.custom().useSSL().build();
context.init(keyManagers, trustManagers, null);
return context;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
throw new RuntimeException(e);
}
} | static SSLContext function(final File trustStoreFile, final String trustStorePassword, final String trustStoreType) { try { if (!trustStoreFile.exists() !trustStoreFile.canRead()) { throw new FileNotFoundException(STR + trustStoreFile.getCanonicalPath()); } final KeyStore casTrustStore = KeyStore.getInstance(trustStoreType); final char[] trustStorePasswordCharArray = trustStorePassword.toCharArray(); try (final FileInputStream casStream = new FileInputStream(trustStoreFile)) { casTrustStore.load(casStream, trustStorePasswordCharArray); } final String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm(); final X509KeyManager customKeyManager = getKeyManager("PKIX", casTrustStore, trustStorePasswordCharArray); final X509KeyManager jvmKeyManager = getKeyManager(defaultAlgorithm, null, null); final X509TrustManager customTrustManager = getTrustManager("PKIX", casTrustStore); final X509TrustManager jvmTrustManager = getTrustManager(defaultAlgorithm, null); final KeyManager[] keyManagers = { new CompositeX509KeyManager(Arrays.asList(jvmKeyManager, customKeyManager)) }; final TrustManager[] trustManagers = { new CompositeX509TrustManager(Arrays.asList(jvmTrustManager, customTrustManager)) }; final SSLContext context = SSLContexts.custom().useSSL().build(); context.init(keyManagers, trustManagers, null); return context; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); throw new RuntimeException(e); } } | /**
* Gets the trusted ssl context.
*
* @param trustStoreFile the trust store file
* @param trustStorePassword the trust store password
* @param trustStoreType the trust store type
* @return the trusted ssl context
*/ | Gets the trusted ssl context | getTrustedSslContext | {
"repo_name": "jasonchw/cas",
"path": "cas-server-core/src/main/java/org/jasig/cas/authentication/FileTrustStoreSslSocketFactory.java",
"license": "apache-2.0",
"size": 12140
} | [
"java.io.File",
"java.io.FileInputStream",
"java.io.FileNotFoundException",
"java.security.KeyStore",
"java.util.Arrays",
"javax.net.ssl.KeyManager",
"javax.net.ssl.KeyManagerFactory",
"javax.net.ssl.SSLContext",
"javax.net.ssl.TrustManager",
"javax.net.ssl.X509KeyManager",
"javax.net.ssl.X509TrustManager",
"org.apache.http.conn.ssl.SSLContexts"
] | import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.security.KeyStore; import java.util.Arrays; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.ssl.SSLContexts; | import java.io.*; import java.security.*; import java.util.*; import javax.net.ssl.*; import org.apache.http.conn.ssl.*; | [
"java.io",
"java.security",
"java.util",
"javax.net",
"org.apache.http"
] | java.io; java.security; java.util; javax.net; org.apache.http; | 957,563 |
@Override
public void drawGlyphVector(GlyphVector g, float x, float y) {
fill(g.getOutline(x, y));
} | void function(GlyphVector g, float x, float y) { fill(g.getOutline(x, y)); } | /**
* Draws the specified glyph vector at the location {@code (x, y)}.
*
* @param g the glyph vector ({@code null} not permitted).
* @param x the x-coordinate.
* @param y the y-coordinate.
*/ | Draws the specified glyph vector at the location (x, y) | drawGlyphVector | {
"repo_name": "informatik-mannheim/Moduro-Toolbox",
"path": "src/main/java/de/hs/mannheim/modUro/controller/diagram/fx/FXGraphics2D.java",
"license": "apache-2.0",
"size": 60103
} | [
"java.awt.font.GlyphVector"
] | import java.awt.font.GlyphVector; | import java.awt.font.*; | [
"java.awt"
] | java.awt; | 1,997,065 |
public static boolean hasGroup(Matcher matcher) {
return matcher.groupCount() > 0;
} | static boolean function(Matcher matcher) { return matcher.groupCount() > 0; } | /**
* Check whether a Matcher contains a group or not.
*
* @param matcher a Matcher
* @return boolean <code>true</code> if matcher contains at least one group.
* @since 1.0
*/ | Check whether a Matcher contains a group or not | hasGroup | {
"repo_name": "bsideup/incubator-groovy",
"path": "src/main/org/codehaus/groovy/runtime/StringGroovyMethods.java",
"license": "apache-2.0",
"size": 141076
} | [
"java.util.regex.Matcher"
] | import java.util.regex.Matcher; | import java.util.regex.*; | [
"java.util"
] | java.util; | 2,264,728 |
public Drawable getSelector() {
return mSelector;
} | Drawable function() { return mSelector; } | /**
* Returns the selector {@link android.graphics.drawable.Drawable} that is used to draw the
* selection in the list.
*
* @return the drawable used to display the selector
*/ | Returns the selector <code>android.graphics.drawable.Drawable</code> that is used to draw the selection in the list | getSelector | {
"repo_name": "stockcode/vicky-learn",
"path": "src/main/java/com/origamilabs/library/views/StaggeredGridView.java",
"license": "gpl-3.0",
"size": 91079
} | [
"android.graphics.drawable.Drawable"
] | import android.graphics.drawable.Drawable; | import android.graphics.drawable.*; | [
"android.graphics"
] | android.graphics; | 1,458,168 |
public String toString() {
try {
Iterator keys = this.keys();
StringBuffer sb = new StringBuffer("{");
while (keys.hasNext()) {
if (sb.length() > 1) {
sb.append(',');
}
Object o = keys.next();
sb.append(quote(o.toString()));
sb.append(':');
sb.append(valueToString(this.map.get(o)));
}
sb.append('}');
return sb.toString();
} catch (Exception e) {
return null;
}
} | String function() { try { Iterator keys = this.keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.map.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } | /**
* Make a JSON text of this JSONObject. For compactness, no whitespace
* is added. If this would not result in a syntactically correct JSON text,
* then null will be returned instead.
* <p>
* Warning: This method assumes that the data structure is acyclical.
*
* @return a printable, displayable, portable, transmittable
* representation of the object, beginning
* with <code>{</code> <small>(left brace)</small> and ending
* with <code>}</code> <small>(right brace)</small>.
*/ | Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a syntactically correct JSON text, then null will be returned instead. Warning: This method assumes that the data structure is acyclical | toString | {
"repo_name": "zenwalk/atlasmapper",
"path": "src/main/java/org/json/JSONObject.java",
"license": "gpl-3.0",
"size": 55770
} | [
"java.util.Iterator"
] | import java.util.Iterator; | import java.util.*; | [
"java.util"
] | java.util; | 59,832 |
public String[] findReloadedContextMemoryLeaks() {
System.gc();
List<String> result = new ArrayList<>();
for (Map.Entry<ClassLoader, String> entry :
childClassLoaders.entrySet()) {
ClassLoader cl = entry.getKey();
if (cl instanceof WebappClassLoader) {
if (!((WebappClassLoader) cl).isStarted()) {
result.add(entry.getValue());
}
}
}
return result.toArray(new String[result.size()]);
} | String[] function() { System.gc(); List<String> result = new ArrayList<>(); for (Map.Entry<ClassLoader, String> entry : childClassLoaders.entrySet()) { ClassLoader cl = entry.getKey(); if (cl instanceof WebappClassLoader) { if (!((WebappClassLoader) cl).isStarted()) { result.add(entry.getValue()); } } } return result.toArray(new String[result.size()]); } | /**
* Attempt to identify the contexts that have a class loader memory leak.
* This is usually triggered on context reload. Note: This method attempts
* to force a full garbage collection. This should be used with extreme
* caution on a production system.
*/ | Attempt to identify the contexts that have a class loader memory leak. This is usually triggered on context reload. Note: This method attempts to force a full garbage collection. This should be used with extreme caution on a production system | findReloadedContextMemoryLeaks | {
"repo_name": "plumer/codana",
"path": "tomcat_files/8.0.0/StandardHost.java",
"license": "mit",
"size": 23241
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.Map",
"org.apache.catalina.loader.WebappClassLoader"
] | import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.catalina.loader.WebappClassLoader; | import java.util.*; import org.apache.catalina.loader.*; | [
"java.util",
"org.apache.catalina"
] | java.util; org.apache.catalina; | 651,296 |
public DcmElement putSL(int tag, int[] values) {
return put(values != null ? ValueElement.createSL(tag, values)
: ValueElement.createSL(tag));
} | DcmElement function(int tag, int[] values) { return put(values != null ? ValueElement.createSL(tag, values) : ValueElement.createSL(tag)); } | /**
* Description of the Method
*
* @param tag
* Description of the Parameter
* @param values
* Description of the Parameter
* @return Description of the Return Value
*/ | Description of the Method | putSL | {
"repo_name": "medicayun/medicayundicom",
"path": "dcm4che14/branches/DCM4CHE_2_14_22_BRANCHA/src/java/org/dcm4cheri/data/DcmObjectImpl.java",
"license": "apache-2.0",
"size": 86392
} | [
"org.dcm4che.data.DcmElement"
] | import org.dcm4che.data.DcmElement; | import org.dcm4che.data.*; | [
"org.dcm4che.data"
] | org.dcm4che.data; | 2,695,335 |
protected void setAdditionalParameters(final ISearchParameters iSearchParameters) {
for(Map.Entry<String,String> entry : getSearchConfiguration().getSearchParameterMap().entrySet()){
iSearchParameters.setParameter(new SearchParameter(entry.getKey(), entry.getValue()));
}
}
// Private ------------------------------------------------------- | void function(final ISearchParameters iSearchParameters) { for(Map.Entry<String,String> entry : getSearchConfiguration().getSearchParameterMap().entrySet()){ iSearchParameters.setParameter(new SearchParameter(entry.getKey(), entry.getValue())); } } | /** Add additional fast search parameters.
* iSearchParameters.setParameter(new SearchParameter(...));
*
* @param iSearchParameters live list of parameters being built and eventually used in the fast query.
*/ | Add additional fast search parameters. iSearchParameters.setParameter(new SearchParameter(...)) | setAdditionalParameters | {
"repo_name": "michaelsembwever/Sesat",
"path": "generic.sesam/search-command-control/fast/src/main/java/no/sesat/search/mode/command/AbstractFast4SearchCommand.java",
"license": "lgpl-3.0",
"size": 33044
} | [
"java.util.Map",
"no.fast.ds.search.ISearchParameters",
"no.fast.ds.search.SearchParameter"
] | import java.util.Map; import no.fast.ds.search.ISearchParameters; import no.fast.ds.search.SearchParameter; | import java.util.*; import no.fast.ds.search.*; | [
"java.util",
"no.fast.ds"
] | java.util; no.fast.ds; | 177,176 |
public boolean isBackCellSet() {
if (backCellRow == -1) {
if (backCellColumn != -1) {
throw new CoreIncorrectCalculationException("Both row and column must be -1 if back-cell was not set");
}
return false;
}
if (backCellColumn == -1) {
throw new CoreIncorrectCalculationException("Both row and column must not be -1 if back-cell was set");
}
return true;
} | boolean function() { if (backCellRow == -1) { if (backCellColumn != -1) { throw new CoreIncorrectCalculationException(STR); } return false; } if (backCellColumn == -1) { throw new CoreIncorrectCalculationException(STR); } return true; } | /**
* Check whether back-cell was set
*
* @return true if back-cell was set
*/ | Check whether back-cell was set | isBackCellSet | {
"repo_name": "nazaryan/ShipIt",
"path": "src/main/java/com/nkwebapps/shipit/placer/BackLinkedCell.java",
"license": "mit",
"size": 2476
} | [
"com.nkwebapps.shipit.exception.CoreIncorrectCalculationException"
] | import com.nkwebapps.shipit.exception.CoreIncorrectCalculationException; | import com.nkwebapps.shipit.exception.*; | [
"com.nkwebapps.shipit"
] | com.nkwebapps.shipit; | 2,230,216 |
private Object addElement(XmlElement e, Method method, Object[] args) {
Class<?> rt = method.getReturnType();
// the last precedence: default name
String nsUri = "##default";
String localName = method.getName();
if(e!=null) {
// then the annotation on this method
if(e.value().length()!=0)
localName = e.value();
nsUri = e.ns();
}
if(nsUri.equals("##default")) {
// look for the annotation on the declaring class
Class<?> c = method.getDeclaringClass();
XmlElement ce = c.getAnnotation(XmlElement.class);
if(ce!=null) {
nsUri = ce.ns();
}
if(nsUri.equals("##default"))
// then default to the XmlNamespace
nsUri = getNamespace(c.getPackage());
}
if(rt==Void.TYPE) {
// leaf element with just a value
boolean isCDATA = method.getAnnotation(XmlCDATA.class)!=null;
StartTag st = new StartTag(document,nsUri,localName);
addChild(st);
for( Object arg : args ) {
Text text;
if(isCDATA) text = new Cdata(document,st,arg);
else text = new Pcdata(document,st,arg);
addChild(text);
}
addChild(new EndTag());
return null;
}
if(TypedXmlWriter.class.isAssignableFrom(rt)) {
// sub writer
return _element(nsUri,localName,(Class)rt);
}
throw new IllegalSignatureException("Illegal return type: "+rt);
} | Object function(XmlElement e, Method method, Object[] args) { Class<?> rt = method.getReturnType(); String nsUri = STR; String localName = method.getName(); if(e!=null) { if(e.value().length()!=0) localName = e.value(); nsUri = e.ns(); } if(nsUri.equals(STR)) { Class<?> c = method.getDeclaringClass(); XmlElement ce = c.getAnnotation(XmlElement.class); if(ce!=null) { nsUri = ce.ns(); } if(nsUri.equals(STR)) nsUri = getNamespace(c.getPackage()); } if(rt==Void.TYPE) { boolean isCDATA = method.getAnnotation(XmlCDATA.class)!=null; StartTag st = new StartTag(document,nsUri,localName); addChild(st); for( Object arg : args ) { Text text; if(isCDATA) text = new Cdata(document,st,arg); else text = new Pcdata(document,st,arg); addChild(text); } addChild(new EndTag()); return null; } if(TypedXmlWriter.class.isAssignableFrom(rt)) { return _element(nsUri,localName,(Class)rt); } throw new IllegalSignatureException(STR+rt); } | /**
* Writes a new element.
*/ | Writes a new element | addElement | {
"repo_name": "GeeQuery/cxf-plus",
"path": "src/main/java/com/github/cxfplus/com/sun/xml/txw2/ContainerElement.java",
"license": "apache-2.0",
"size": 11276
} | [
"com.github.cxfplus.com.sun.xml.txw2.annotation.XmlCDATA",
"com.github.cxfplus.com.sun.xml.txw2.annotation.XmlElement",
"java.lang.reflect.Method"
] | import com.github.cxfplus.com.sun.xml.txw2.annotation.XmlCDATA; import com.github.cxfplus.com.sun.xml.txw2.annotation.XmlElement; import java.lang.reflect.Method; | import com.github.cxfplus.com.sun.xml.txw2.annotation.*; import java.lang.reflect.*; | [
"com.github.cxfplus",
"java.lang"
] | com.github.cxfplus; java.lang; | 2,665,148 |
private String AdditionResolver(String Num1, String Num2){
return new BigDecimal(Num1).add(new BigDecimal(Num2)).toString();
} | String function(String Num1, String Num2){ return new BigDecimal(Num1).add(new BigDecimal(Num2)).toString(); } | /**
* Resolve addition and deduction
* @param Num1 Base number
* @param Num2 Second number
* @return result
*/ | Resolve addition and deduction | AdditionResolver | {
"repo_name": "ICEFIR/CalcExperimental",
"path": "app/src/main/java/com/example/mjmj1996/appfun/ExpressionResolver.java",
"license": "lgpl-3.0",
"size": 8595
} | [
"java.math.BigDecimal"
] | import java.math.BigDecimal; | import java.math.*; | [
"java.math"
] | java.math; | 1,890,169 |
@Override
public Path getWorkingDirectory() {
if (workingDir == null) {
workingDir = getHomeDirectory();
}
return workingDir;
} | Path function() { if (workingDir == null) { workingDir = getHomeDirectory(); } return workingDir; } | /**
* Get the current working directory for the given file system
*
* @return the directory pathname
*/ | Get the current working directory for the given file system | getWorkingDirectory | {
"repo_name": "mapr/hadoop-common",
"path": "hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/fs/http/client/HttpFSFileSystem.java",
"license": "apache-2.0",
"size": 68980
} | [
"org.apache.hadoop.fs.Path"
] | import org.apache.hadoop.fs.Path; | import org.apache.hadoop.fs.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 1,437,803 |
public void setUbefAttr(final H2FeatureService ubefAttr) {
this.ubefAttr = ubefAttr;
} | void function(final H2FeatureService ubefAttr) { this.ubefAttr = ubefAttr; } | /**
* DOCUMENT ME!
*
* @param ubefAttr the ubefAttr to set
*/ | DOCUMENT ME | setUbefAttr | {
"repo_name": "cismet/watergis-client",
"path": "src/main/java/de/cismet/watergis/gui/actions/checks/AusbauCheckAction.java",
"license": "lgpl-3.0",
"size": 64923
} | [
"de.cismet.cismap.commons.featureservice.H2FeatureService"
] | import de.cismet.cismap.commons.featureservice.H2FeatureService; | import de.cismet.cismap.commons.featureservice.*; | [
"de.cismet.cismap"
] | de.cismet.cismap; | 949,003 |
public String getName(String key) throws Exception {
IEntityGroup g = GroupService.findGroup(key);
return g.getName();
} | String function(String key) throws Exception { IEntityGroup g = GroupService.findGroup(key); return g.getName(); } | /**
* Given the key, returns the entity's name.
*
* @param key java.lang.String
*/ | Given the key, returns the entity's name | getName | {
"repo_name": "jhelmer-unicon/uPortal",
"path": "uportal-war/src/main/java/org/apereo/portal/groups/EntityGroupNameFinder.java",
"license": "apache-2.0",
"size": 2154
} | [
"org.apereo.portal.services.GroupService"
] | import org.apereo.portal.services.GroupService; | import org.apereo.portal.services.*; | [
"org.apereo.portal"
] | org.apereo.portal; | 305,245 |
public static Intent getPlayerActivityIntent(Context context, Playable media) {
MediaType mt = media.getMediaType();
return ClientConfig.playbackServiceCallbacks.getPlayerActivityIntent(context, mt);
} | static Intent function(Context context, Playable media) { MediaType mt = media.getMediaType(); return ClientConfig.playbackServiceCallbacks.getPlayerActivityIntent(context, mt); } | /**
* Same as getPlayerActivityIntent(context), but here the type of activity
* depends on the FeedMedia that is provided as an argument.
*/ | Same as getPlayerActivityIntent(context), but here the type of activity depends on the FeedMedia that is provided as an argument | getPlayerActivityIntent | {
"repo_name": "volhol/AntennaPod",
"path": "core/src/main/java/de/danoeh/antennapod/core/service/playback/PlaybackService.java",
"license": "mit",
"size": 53237
} | [
"android.content.Context",
"android.content.Intent",
"de.danoeh.antennapod.core.ClientConfig",
"de.danoeh.antennapod.core.feed.MediaType",
"de.danoeh.antennapod.core.util.playback.Playable"
] | import android.content.Context; import android.content.Intent; import de.danoeh.antennapod.core.ClientConfig; import de.danoeh.antennapod.core.feed.MediaType; import de.danoeh.antennapod.core.util.playback.Playable; | import android.content.*; import de.danoeh.antennapod.core.*; import de.danoeh.antennapod.core.feed.*; import de.danoeh.antennapod.core.util.playback.*; | [
"android.content",
"de.danoeh.antennapod"
] | android.content; de.danoeh.antennapod; | 436,712 |
@SuppressWarnings("boxing")
public static double[][] solutionToCoefficients(DoubleSolution solution) {
int numberOfVariables = solution.getNumberOfVariables();
int numberOfCoefficients = numberOfVariables / 2;
double[][] coefficients = new double[2][numberOfCoefficients];
for (int i = 0; i < numberOfVariables; i++) {
if (i < numberOfCoefficients) {
coefficients[0][i] = solution.getVariableValue(i);
}
else {
coefficients[1][i - numberOfCoefficients] = solution.getVariableValue(i);
}
}
return coefficients;
}
private class MyNSGAIIRunner extends AbstractAlgorithmRunner {
final Algorithm<List<DoubleSolution>> algorithm;
MyNSGAIIRunner(Instances data, double minEffectiveness) {
final Problem<DoubleSolution> problem = new MODEPProblem(data, minEffectiveness);
double crossoverProbability = 0.6;
double crossoverDistributionIndex = 20.0;
final CrossoverOperator<DoubleSolution> crossover =
new SBXCrossover(crossoverProbability, crossoverDistributionIndex);
double mutationProbability = 0.05;
double mutationPerturbation = 0.0;
final MutationOperator<DoubleSolution> mutation =
new UniformMutation(mutationProbability, mutationPerturbation);
final SelectionOperator<List<DoubleSolution>, DoubleSolution> selection =
new BinaryTournamentSelection<>(new RankingAndCrowdingDistanceComparator<DoubleSolution>());
this.algorithm = new NSGAIIBuilder<>(problem, crossover, mutation)
.setSelectionOperator(selection).setMaxIterations(400).setPopulationSize(100)
.build();
}
| @SuppressWarnings(STR) static double[][] function(DoubleSolution solution) { int numberOfVariables = solution.getNumberOfVariables(); int numberOfCoefficients = numberOfVariables / 2; double[][] coefficients = new double[2][numberOfCoefficients]; for (int i = 0; i < numberOfVariables; i++) { if (i < numberOfCoefficients) { coefficients[0][i] = solution.getVariableValue(i); } else { coefficients[1][i - numberOfCoefficients] = solution.getVariableValue(i); } } return coefficients; } private class MyNSGAIIRunner extends AbstractAlgorithmRunner { final Algorithm<List<DoubleSolution>> algorithm; MyNSGAIIRunner(Instances data, double minEffectiveness) { final Problem<DoubleSolution> problem = new MODEPProblem(data, minEffectiveness); double crossoverProbability = 0.6; double crossoverDistributionIndex = 20.0; final CrossoverOperator<DoubleSolution> crossover = new SBXCrossover(crossoverProbability, crossoverDistributionIndex); double mutationProbability = 0.05; double mutationPerturbation = 0.0; final MutationOperator<DoubleSolution> mutation = new UniformMutation(mutationProbability, mutationPerturbation); final SelectionOperator<List<DoubleSolution>, DoubleSolution> selection = new BinaryTournamentSelection<>(new RankingAndCrowdingDistanceComparator<DoubleSolution>()); this.algorithm = new NSGAIIBuilder<>(problem, crossover, mutation) .setSelectionOperator(selection).setMaxIterations(400).setPopulationSize(100) .build(); } | /**
* <p>
* Converts a {@link DoubleSolution} into a coefficient matrix
* </p>
*
* @param solution
* solution the is converted
* @return coefficient matrix
*/ | Converts a <code>DoubleSolution</code> into a coefficient matrix | solutionToCoefficients | {
"repo_name": "sherbold/CrossPare",
"path": "CrossPare/src/main/java/de/ugoe/cs/cpdp/wekaclassifier/MODEPClassifier.java",
"license": "apache-2.0",
"size": 14859
} | [
"java.util.List",
"org.uma.jmetal.algorithm.Algorithm",
"org.uma.jmetal.algorithm.multiobjective.nsgaii.NSGAIIBuilder",
"org.uma.jmetal.operator.CrossoverOperator",
"org.uma.jmetal.operator.MutationOperator",
"org.uma.jmetal.operator.SelectionOperator",
"org.uma.jmetal.operator.impl.crossover.SBXCrossover",
"org.uma.jmetal.operator.impl.mutation.UniformMutation",
"org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection",
"org.uma.jmetal.problem.Problem",
"org.uma.jmetal.runner.AbstractAlgorithmRunner",
"org.uma.jmetal.solution.DoubleSolution",
"org.uma.jmetal.util.comparator.RankingAndCrowdingDistanceComparator"
] | import java.util.List; import org.uma.jmetal.algorithm.Algorithm; import org.uma.jmetal.algorithm.multiobjective.nsgaii.NSGAIIBuilder; import org.uma.jmetal.operator.CrossoverOperator; import org.uma.jmetal.operator.MutationOperator; import org.uma.jmetal.operator.SelectionOperator; import org.uma.jmetal.operator.impl.crossover.SBXCrossover; import org.uma.jmetal.operator.impl.mutation.UniformMutation; import org.uma.jmetal.operator.impl.selection.BinaryTournamentSelection; import org.uma.jmetal.problem.Problem; import org.uma.jmetal.runner.AbstractAlgorithmRunner; import org.uma.jmetal.solution.DoubleSolution; import org.uma.jmetal.util.comparator.RankingAndCrowdingDistanceComparator; | import java.util.*; import org.uma.jmetal.algorithm.*; import org.uma.jmetal.algorithm.multiobjective.nsgaii.*; import org.uma.jmetal.operator.*; import org.uma.jmetal.operator.impl.crossover.*; import org.uma.jmetal.operator.impl.mutation.*; import org.uma.jmetal.operator.impl.selection.*; import org.uma.jmetal.problem.*; import org.uma.jmetal.runner.*; import org.uma.jmetal.solution.*; import org.uma.jmetal.util.comparator.*; | [
"java.util",
"org.uma.jmetal"
] | java.util; org.uma.jmetal; | 1,647,840 |
private boolean examineGetDeclaredTypeNested() {
TypeElement stringDecl = _elementUtils.getTypeElement(String.class.getName());
TypeElement numberDecl = _elementUtils.getTypeElement(Number.class.getName());
TypeElement elementOuter = _elementUtils.getTypeElement("targets.model.pd.Outer");
TypeElement elementInner = _elementUtils.getTypeElement("targets.model.pd.Outer.Inner");
DeclaredType stringType = _typeUtils.getDeclaredType(stringDecl);
DeclaredType numberType = _typeUtils.getDeclaredType(numberDecl);
ArrayType numberArrayType = _typeUtils.getArrayType(numberType);
// Outer<T1, T2> ---> Outer<String, Number[]>
DeclaredType outerType = _typeUtils.getDeclaredType(elementOuter, stringType, numberArrayType);
// Outer<T1, T2>.Inner<T2> ---> Outer<String, Number[]>.Inner<Number[]>
DeclaredType decl = _typeUtils.getDeclaredType(outerType, elementInner, new TypeMirror[] { numberArrayType });
List<? extends TypeMirror> args = decl.getTypeArguments();
if (args.size() != 1) {
reportError("Outer<String, Number[]>.Inner<Number[]> should have one argument but decl.getTypeArguments() returned " + args.size());
return false;
}
if (!_typeUtils.isSameType(numberArrayType, args.get(0))) {
reportError("First arg of Outer<String, Number[]>.Inner<Number[]> was expected to be Number[], but was: " + args.get(0));
return false;
}
return true;
} | boolean function() { TypeElement stringDecl = _elementUtils.getTypeElement(String.class.getName()); TypeElement numberDecl = _elementUtils.getTypeElement(Number.class.getName()); TypeElement elementOuter = _elementUtils.getTypeElement(STR); TypeElement elementInner = _elementUtils.getTypeElement(STR); DeclaredType stringType = _typeUtils.getDeclaredType(stringDecl); DeclaredType numberType = _typeUtils.getDeclaredType(numberDecl); ArrayType numberArrayType = _typeUtils.getArrayType(numberType); DeclaredType outerType = _typeUtils.getDeclaredType(elementOuter, stringType, numberArrayType); DeclaredType decl = _typeUtils.getDeclaredType(outerType, elementInner, new TypeMirror[] { numberArrayType }); List<? extends TypeMirror> args = decl.getTypeArguments(); if (args.size() != 1) { reportError(STR + args.size()); return false; } if (!_typeUtils.isSameType(numberArrayType, args.get(0))) { reportError(STR + args.get(0)); return false; } return true; } | /**
* Test getDeclaredType() for nested parameterized types (Outer<Foo>.Inner<Bar>).
* @return true if tests passed
*/ | Test getDeclaredType() for nested parameterized types (Outer<Foo>.Inner<Bar>) | examineGetDeclaredTypeNested | {
"repo_name": "maxeler/eclipse",
"path": "eclipse.jdt.core/org.eclipse.jdt.compiler.apt.tests/processors/org/eclipse/jdt/compiler/apt/tests/processors/typeutils/TypeUtilsProc.java",
"license": "epl-1.0",
"size": 11803
} | [
"java.util.List",
"javax.lang.model.element.TypeElement",
"javax.lang.model.type.ArrayType",
"javax.lang.model.type.DeclaredType",
"javax.lang.model.type.TypeMirror"
] | import java.util.List; import javax.lang.model.element.TypeElement; import javax.lang.model.type.ArrayType; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; | import java.util.*; import javax.lang.model.element.*; import javax.lang.model.type.*; | [
"java.util",
"javax.lang"
] | java.util; javax.lang; | 1,953,987 |
@SuppressWarnings("checkstyle:magicnumber")
public static long idFromString(String str) {
if (str == null || !ID_PATTERN.matcher(str).matches()) {
return -1;
}
str = str.replaceAll("-", "");
return Long.parseUnsignedLong(str, 16);
}
/**
* Takes the pathname of a classpath resource and returns a {@link Path} | @SuppressWarnings(STR) static long function(String str) { if (str == null !ID_PATTERN.matcher(str).matches()) { return -1; } str = str.replaceAll("-", ""); return Long.parseUnsignedLong(str, 16); } /** * Takes the pathname of a classpath resource and returns a {@link Path} | /**
* Parses the jobId formatted with {@link Util#idToString(long)}.
* <p>
* The method is lenient: if the string doesn't match the structure of the
* ID generated by {@code idToString} or if the string is null, it will
* return -1.
*
* @return the parsed ID or -1 if parsing failed.
*/ | Parses the jobId formatted with <code>Util#idToString(long)</code>. The method is lenient: if the string doesn't match the structure of the ID generated by idToString or if the string is null, it will return -1 | idFromString | {
"repo_name": "jerrinot/hazelcast",
"path": "hazelcast/src/main/java/com/hazelcast/jet/Util.java",
"license": "apache-2.0",
"size": 7142
} | [
"java.nio.file.Path"
] | import java.nio.file.Path; | import java.nio.file.*; | [
"java.nio"
] | java.nio; | 880,258 |
protected BitSet decodeGenomeToBinary(){
return this.genome;
}
| BitSet function(){ return this.genome; } | /**
* Decodes genome to traditional binary coding.
* SimpleBinaryRepresentation does not do anything with binary representation.
* Suitable for (i.e. gray) ancestors to override.
* @return genome written in binary coding.
*/ | Decodes genome to traditional binary coding. SimpleBinaryRepresentation does not do anything with binary representation. Suitable for (i.e. gray) ancestors to override | decodeGenomeToBinary | {
"repo_name": "dhonza/JCOOL",
"path": "jcool/benchmark/src/main/java/cz/cvut/felk/cig/jcool/benchmark/method/evolutionary/representations/genotype/BitSetBinaryRepresentation.java",
"license": "lgpl-3.0",
"size": 9979
} | [
"java.util.BitSet"
] | import java.util.BitSet; | import java.util.*; | [
"java.util"
] | java.util; | 2,464,239 |
@Test
public void testHexToLong() {
String src = "CDF1F0C10F12345678";
assertEquals(0x0000000000000000L, Conversion.hexToLong(src, 0, 0L, 0, 0));
assertEquals(0x000000000000000CL, Conversion.hexToLong(src, 0, 0L, 0, 1));
assertEquals(0x000000001C0F1FDCL, Conversion.hexToLong(src, 0, 0L, 0, 8));
assertEquals(0x0000000001C0F1FDL, Conversion.hexToLong(src, 1, 0L, 0, 8));
assertEquals(
0x123456798ABCDEF0L, Conversion.hexToLong(src, 0, 0x123456798ABCDEF0L, 0, 0));
assertEquals(
0x1234567876BCDEF0L, Conversion.hexToLong(src, 15, 0x123456798ABCDEF0L, 24, 3));
} | void function() { String src = STR; assertEquals(0x0000000000000000L, Conversion.hexToLong(src, 0, 0L, 0, 0)); assertEquals(0x000000000000000CL, Conversion.hexToLong(src, 0, 0L, 0, 1)); assertEquals(0x000000001C0F1FDCL, Conversion.hexToLong(src, 0, 0L, 0, 8)); assertEquals(0x0000000001C0F1FDL, Conversion.hexToLong(src, 1, 0L, 0, 8)); assertEquals( 0x123456798ABCDEF0L, Conversion.hexToLong(src, 0, 0x123456798ABCDEF0L, 0, 0)); assertEquals( 0x1234567876BCDEF0L, Conversion.hexToLong(src, 15, 0x123456798ABCDEF0L, 24, 3)); } | /**
* Tests {@link Conversion#hexToLong(String, int, long, int, int)}.
*/ | Tests <code>Conversion#hexToLong(String, int, long, int, int)</code> | testHexToLong | {
"repo_name": "martingwhite/astor",
"path": "examples/lang_7/src/test/java/org/apache/commons/lang3/ConversionTest.java",
"license": "gpl-2.0",
"size": 100416
} | [
"org.junit.Assert"
] | import org.junit.Assert; | import org.junit.*; | [
"org.junit"
] | org.junit; | 2,267,080 |
public void testInvalidEnum () {
String example = "noRmaL";
try {
CarModeStatus temp = CarModeStatus.valueForString(example);
assertNull("Result of valueForString should be null.", temp);
}
catch (IllegalArgumentException exception) {
fail("Invalid enum throws IllegalArgumentException.");
}
} | void function () { String example = STR; try { CarModeStatus temp = CarModeStatus.valueForString(example); assertNull(STR, temp); } catch (IllegalArgumentException exception) { fail(STR); } } | /**
* Verifies that an invalid assignment is null.
*/ | Verifies that an invalid assignment is null | testInvalidEnum | {
"repo_name": "914802951/sdl_android",
"path": "sdl_android/src/androidTest/java/com/smartdevicelink/test/rpc/enums/CarModeStatusTests.java",
"license": "bsd-3-clause",
"size": 2470
} | [
"com.smartdevicelink.proxy.rpc.enums.CarModeStatus"
] | import com.smartdevicelink.proxy.rpc.enums.CarModeStatus; | import com.smartdevicelink.proxy.rpc.enums.*; | [
"com.smartdevicelink.proxy"
] | com.smartdevicelink.proxy; | 1,237,019 |
private void deleteInboundAuthRequestConfiguration(int applicationID, Connection connection)
throws SQLException {
if (log.isDebugEnabled()) {
log.debug("Deleting Clients of the Application " + applicationID);
}
int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId();
PreparedStatement deleteClientPrepStmt = null;
try {
deleteClientPrepStmt = connection
.prepareStatement(ApplicationMgtDBQueries.REMOVE_CLIENT_FROM_APPMGT_CLIENT);
// APP_ID = ? AND TENANT_ID = ?
deleteClientPrepStmt.setInt(1, applicationID);
deleteClientPrepStmt.setInt(2, tenantID);
deleteClientPrepStmt.execute();
} finally {
IdentityApplicationManagementUtil.closeStatement(deleteClientPrepStmt);
}
} | void function(int applicationID, Connection connection) throws SQLException { if (log.isDebugEnabled()) { log.debug(STR + applicationID); } int tenantID = CarbonContext.getThreadLocalCarbonContext().getTenantId(); PreparedStatement deleteClientPrepStmt = null; try { deleteClientPrepStmt = connection .prepareStatement(ApplicationMgtDBQueries.REMOVE_CLIENT_FROM_APPMGT_CLIENT); deleteClientPrepStmt.setInt(1, applicationID); deleteClientPrepStmt.setInt(2, tenantID); deleteClientPrepStmt.execute(); } finally { IdentityApplicationManagementUtil.closeStatement(deleteClientPrepStmt); } } | /**
* Deleting Clients of the Application
*
* @param applicationID
* @param connection
* @throws IdentityApplicationManagementException
*/ | Deleting Clients of the Application | deleteInboundAuthRequestConfiguration | {
"repo_name": "Niranjan-K/carbon-identity",
"path": "components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java",
"license": "apache-2.0",
"size": 128101
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.SQLException",
"org.wso2.carbon.context.CarbonContext",
"org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil",
"org.wso2.carbon.identity.application.mgt.ApplicationMgtDBQueries"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.application.mgt.ApplicationMgtDBQueries; | import java.sql.*; import org.wso2.carbon.context.*; import org.wso2.carbon.identity.application.common.util.*; import org.wso2.carbon.identity.application.mgt.*; | [
"java.sql",
"org.wso2.carbon"
] | java.sql; org.wso2.carbon; | 2,235,056 |
void exitPrimaryNoNewArray_lfno_arrayAccess(@NotNull Java8Parser.PrimaryNoNewArray_lfno_arrayAccessContext ctx); | void exitPrimaryNoNewArray_lfno_arrayAccess(@NotNull Java8Parser.PrimaryNoNewArray_lfno_arrayAccessContext ctx); | /**
* Exit a parse tree produced by {@link Java8Parser#primaryNoNewArray_lfno_arrayAccess}.
*
* @param ctx the parse tree
*/ | Exit a parse tree produced by <code>Java8Parser#primaryNoNewArray_lfno_arrayAccess</code> | exitPrimaryNoNewArray_lfno_arrayAccess | {
"repo_name": "BigDaddy-Germany/WHOAMI",
"path": "WHOAMI/src/de/aima13/whoami/modules/syntaxcheck/languages/antlrgen/Java8Listener.java",
"license": "mit",
"size": 97945
} | [
"org.antlr.v4.runtime.misc.NotNull"
] | import org.antlr.v4.runtime.misc.NotNull; | import org.antlr.v4.runtime.misc.*; | [
"org.antlr.v4"
] | org.antlr.v4; | 100,365 |
private void setupValue(Object target, Keyframe kf) {
//if (mProperty != null) {
// kf.setValue(mProperty.get(target));
//}
try {
if (mGetter == null) {
Class targetClass = target.getClass();
setupGetter(targetClass);
}
kf.setValue(mGetter.invoke(target));
} catch (InvocationTargetException e) {
Log.e("PropertyValuesHolder", e.toString());
} catch (IllegalAccessException e) {
Log.e("PropertyValuesHolder", e.toString());
}
} | void function(Object target, Keyframe kf) { try { if (mGetter == null) { Class targetClass = target.getClass(); setupGetter(targetClass); } kf.setValue(mGetter.invoke(target)); } catch (InvocationTargetException e) { Log.e(STR, e.toString()); } catch (IllegalAccessException e) { Log.e(STR, e.toString()); } } | /**
* Utility function to set the value stored in a particular Keyframe. The value used is
* whatever the value is for the property name specified in the keyframe on the target object.
*
* @param target The target object from which the current value should be extracted.
* @param kf The keyframe which holds the property name and value.
*/ | Utility function to set the value stored in a particular Keyframe. The value used is whatever the value is for the property name specified in the keyframe on the target object | setupValue | {
"repo_name": "Myanmar-Hub/collabra-devcon",
"path": "Sherlock/src/com/actionbarsherlock/internal/nineoldandroids/animation/PropertyValuesHolder.java",
"license": "apache-2.0",
"size": 45358
} | [
"android.util.Log",
"java.lang.reflect.InvocationTargetException"
] | import android.util.Log; import java.lang.reflect.InvocationTargetException; | import android.util.*; import java.lang.reflect.*; | [
"android.util",
"java.lang"
] | android.util; java.lang; | 476,396 |
private void writePageAndReport(CmsXmlPage page, boolean report) throws CmsException {
CmsFile file = page.getFile();
byte[] content = page.marshal();
file.setContents(content);
// check lock
CmsLock lock = getCms().getLock(file);
if (lock.isNullLock() || lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) {
// lock the page
checkLock(getCms().getSitePath(file));
// write the file with the new content
getCms().writeFile(file);
// unlock the page
getCms().unlockResource(getCms().getSitePath(file));
if (report) {
m_report.println(
Messages.get().container(Messages.RPT_ELEM_RENAME_2, getParamOldElement(), getParamNewElement()),
I_CmsReport.FORMAT_OK);
}
}
} | void function(CmsXmlPage page, boolean report) throws CmsException { CmsFile file = page.getFile(); byte[] content = page.marshal(); file.setContents(content); CmsLock lock = getCms().getLock(file); if (lock.isNullLock() lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) { checkLock(getCms().getSitePath(file)); getCms().writeFile(file); getCms().unlockResource(getCms().getSitePath(file)); if (report) { m_report.println( Messages.get().container(Messages.RPT_ELEM_RENAME_2, getParamOldElement(), getParamNewElement()), I_CmsReport.FORMAT_OK); } } } | /**
* Writes the given xml page by reporting the result.<p>
*
* @param page the xml page
* @param report if true then some output will be written to the report
* @throws CmsException if operation failed
*/ | Writes the given xml page by reporting the result | writePageAndReport | {
"repo_name": "ggiudetti/opencms-core",
"path": "src-modules/org/opencms/workplace/tools/content/CmsElementRename.java",
"license": "lgpl-2.1",
"size": 35235
} | [
"org.opencms.file.CmsFile",
"org.opencms.lock.CmsLock",
"org.opencms.main.CmsException",
"org.opencms.workplace.CmsReport",
"org.opencms.xml.page.CmsXmlPage"
] | import org.opencms.file.CmsFile; import org.opencms.lock.CmsLock; import org.opencms.main.CmsException; import org.opencms.workplace.CmsReport; import org.opencms.xml.page.CmsXmlPage; | import org.opencms.file.*; import org.opencms.lock.*; import org.opencms.main.*; import org.opencms.workplace.*; import org.opencms.xml.page.*; | [
"org.opencms.file",
"org.opencms.lock",
"org.opencms.main",
"org.opencms.workplace",
"org.opencms.xml"
] | org.opencms.file; org.opencms.lock; org.opencms.main; org.opencms.workplace; org.opencms.xml; | 100,855 |
public void deleteIndex(Index index, String reason) throws IOException {
removeIndex(index, reason, true);
}
/**
* Deletes an index that is not assigned to this node. This method cleans up all disk folders relating to the index
* but does not deal with in-memory structures. For those call {@link #deleteIndex(Index, String)} | void function(Index index, String reason) throws IOException { removeIndex(index, reason, true); } /** * Deletes an index that is not assigned to this node. This method cleans up all disk folders relating to the index * but does not deal with in-memory structures. For those call {@link #deleteIndex(Index, String)} | /**
* Deletes the given index. Persistent parts of the index
* like the shards files, state and transaction logs are removed once all resources are released.
*
* Equivalent to {@link #removeIndex(Index, String)} but fires
* different lifecycle events to ensure pending resources of this index are immediately removed.
* @param index the index to delete
* @param reason the high level reason causing this delete
*/ | Deletes the given index. Persistent parts of the index like the shards files, state and transaction logs are removed once all resources are released. Equivalent to <code>#removeIndex(Index, String)</code> but fires different lifecycle events to ensure pending resources of this index are immediately removed | deleteIndex | {
"repo_name": "myelin/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/indices/IndicesService.java",
"license": "apache-2.0",
"size": 55725
} | [
"java.io.IOException",
"org.elasticsearch.index.Index"
] | import java.io.IOException; import org.elasticsearch.index.Index; | import java.io.*; import org.elasticsearch.index.*; | [
"java.io",
"org.elasticsearch.index"
] | java.io; org.elasticsearch.index; | 2,374,533 |
protected final Coverage doOperation(
final String operationName,
final Coverage source,
final String argumentName1,
final Object argumentValue1)
throws OperationNotFoundException, InvalidParameterNameException,
CoverageProcessingException {
final Operation operation = processor.getOperation(operationName);
final ParameterValueGroup parameters = operation.getParameters();
addSources(operationName, parameters, source);
setParameterValue(parameters, argumentName1, argumentValue1);
return processor.doOperation(parameters);
} | final Coverage function( final String operationName, final Coverage source, final String argumentName1, final Object argumentValue1) throws OperationNotFoundException, InvalidParameterNameException, CoverageProcessingException { final Operation operation = processor.getOperation(operationName); final ParameterValueGroup parameters = operation.getParameters(); addSources(operationName, parameters, source); setParameterValue(parameters, argumentName1, argumentValue1); return processor.doOperation(parameters); } | /**
* Applies a process operation with one parameter. This is a helper method for implementation of
* various convenience methods in this class.
*
* @param operationName Name of the operation to be applied to the coverage.
* @param source The source coverage.
* @param argumentName1 The name of the first parameter to setParameterValue.
* @param argumentValue1 The value for the first parameter.
* @return The result as a coverage.
* @throws OperationNotFoundException if there is no operation named {@code operationName}.
* @throws InvalidParameterNameException if there is no parameter with the specified name.
* @throws CoverageProcessingException if the operation can't be applied.
*/ | Applies a process operation with one parameter. This is a helper method for implementation of various convenience methods in this class | doOperation | {
"repo_name": "geotools/geotools",
"path": "modules/library/coverage/src/main/java/org/geotools/coverage/processing/Operations.java",
"license": "lgpl-2.1",
"size": 44693
} | [
"org.opengis.coverage.Coverage",
"org.opengis.coverage.processing.Operation",
"org.opengis.coverage.processing.OperationNotFoundException",
"org.opengis.parameter.InvalidParameterNameException",
"org.opengis.parameter.ParameterValueGroup"
] | import org.opengis.coverage.Coverage; import org.opengis.coverage.processing.Operation; import org.opengis.coverage.processing.OperationNotFoundException; import org.opengis.parameter.InvalidParameterNameException; import org.opengis.parameter.ParameterValueGroup; | import org.opengis.coverage.*; import org.opengis.coverage.processing.*; import org.opengis.parameter.*; | [
"org.opengis.coverage",
"org.opengis.parameter"
] | org.opengis.coverage; org.opengis.parameter; | 1,668,531 |
public int read( byte[] b, int off, int len ) throws IOException {
return readDirect(b, off, len);
} | int function( byte[] b, int off, int len ) throws IOException { return readDirect(b, off, len); } | /**
* Reads up to len bytes of data from this input stream into an array of bytes.
*
* @throws IOException if a network error occurs
*/ | Reads up to len bytes of data from this input stream into an array of bytes | read | {
"repo_name": "felixion/flxsmb",
"path": "src/jcifs/smb/SmbFileInputStream.java",
"license": "lgpl-2.1",
"size": 8630
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 759,138 |
@Override
public void doSave(IProgressMonitor progressMonitor) {
// Save only resources that have actually changed.
//
final Map<Object, Object> saveOptions = new HashMap<Object, Object>();
saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER);
saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED);
| void function(IProgressMonitor progressMonitor) { final Map<Object, Object> saveOptions = new HashMap<Object, Object>(); saveOptions.put(Resource.OPTION_SAVE_ONLY_IF_CHANGED, Resource.OPTION_SAVE_ONLY_IF_CHANGED_MEMORY_BUFFER); saveOptions.put(Resource.OPTION_LINE_DELIMITER, Resource.OPTION_LINE_DELIMITER_UNSPECIFIED); | /**
* This is for implementing {@link IEditorPart} and simply saves the model file.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This is for implementing <code>IEditorPart</code> and simply saves the model file. | doSave | {
"repo_name": "FTSRG/mondo-collab-framework",
"path": "archive/workspaceTracker/VA/ikerlanEMF.editor/src/eu/mondo/collaboration/operationtracemodel/example/WTSpec/presentation/WTSpecEditor.java",
"license": "epl-1.0",
"size": 55795
} | [
"java.util.HashMap",
"java.util.Map",
"org.eclipse.core.runtime.IProgressMonitor",
"org.eclipse.emf.ecore.resource.Resource"
] | import java.util.HashMap; import java.util.Map; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.emf.ecore.resource.Resource; | import java.util.*; import org.eclipse.core.runtime.*; import org.eclipse.emf.ecore.resource.*; | [
"java.util",
"org.eclipse.core",
"org.eclipse.emf"
] | java.util; org.eclipse.core; org.eclipse.emf; | 1,048,268 |
public void visit(SmcFSM fsm)
{
String rawSource = fsm.getSource();
String packageName = fsm.getPackage();
String context = fsm.getContext();
String fsmClassName = fsm.getFsmClassName();
String startState = fsm.getStartState();
List<SmcMap> maps = fsm.getMaps();
List<SmcTransition> transitions;
List<SmcParameter> params;
Iterator<SmcParameter> pit;
String transName;
String vbState;
String separator;
int index;
String indent2;
// Dump out the raw source code, if any.
if (rawSource != null && rawSource.length () > 0)
{
_source.println(rawSource);
_source.println();
}
// If reflection is on, then import the .Net collections
// package.
if (_reflectFlag == true)
{
if (_genericFlag == false)
{
_source.println("Imports System.Collections");
}
else
{
_source.println("Imports System.Collections.Generic");
}
}
// Do user-specified imports now.
for (String imp: fsm.getImports())
{
_source.print("Imports ");
_source.println(imp);
}
// If serialization is on, then import the .Net
// serialization package.
if (_serialFlag == true)
{
_source.println(
"Imports System.Runtime.Serialization");
}
_source.println();
// If a package has been specified, generate the package
// statement now and set the indent.
if (packageName != null && packageName.length() > 0)
{
_source.print("Namespace ");
_source.println(packageName);
_source.println();
_indent = " ";
}
// If -serial was specified, then prepend the serialize
// attribute to the class declaration.
if (_serialFlag == true)
{
_source.print(_indent);
_source.print("<Serializable()> ");
}
// Now declare the context class.
_source.print(_indent);
_source.print("Public NotInheritable Class ");
_source.print(fsmClassName);
_source.println("");
_source.print(_indent);
_source.println(" Inherits statemap.FSMContext");
// If -serial was specified, then we also implement the
// ISerializable interface.
if (_serialFlag == true)
{
_source.print(_indent);
_source.println(" Implements ISerializable");
}
// Declare the associated application class as a data
// member.
_source.println();
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Member data");
_source.print(_indent);
_source.println(" '");
_source.print(_indent);
_source.println();
_source.print(_indent);
_source.println(
" ' The associated application class instance.");
_source.print(_indent);
_source.print(" Private _owner As ");
_source.println(context);
_source.println();
// If serialization is on, then the shared state array
// must be generated.
if (_serialFlag == true || _reflectFlag == true)
{
String mapName;
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Shared data");
_source.print(_indent);
_source.println(" '");
_source.println();
_source.print(_indent);
_source.print(" ' State instance array. ");
_source.println("Used to deserialize.");
_source.print(_indent);
_source.print(
" Private Shared ReadOnly _States() As ");
_source.print(context);
_source.println("State = _");
_source.print(_indent);
_source.print(" {");
// For each map, ...
separator = " _";
for (SmcMap map: maps)
{
mapName = map.getName();
// and for each map state, ...
for (SmcState state: map.getStates())
{
// Add its singleton instance to the array.
_source.println(separator);
_source.print(_indent);
_source.print(" ");
_source.print(mapName);
_source.print('.');
_source.print(state.getClassName());
separator = ", _";
}
}
_source.println(" _");
_source.print(_indent);
_source.println(" }");
_source.println();
}
// Now declare the current state and owner properties.
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Properties");
_source.print(_indent);
_source.println(" '");
_source.println();
_source.print(_indent);
_source.print(" Public Property State() As ");
_source.print(context);
_source.println("State");
_source.print(_indent);
_source.println(" Get");
_source.print(_indent);
_source.println(" If state_ Is Nothing _");
_source.print(_indent);
_source.println(" Then");
_source.print(_indent);
_source.print(" Throw ");
_source.println(
"New statemap.StateUndefinedException()");
_source.print(_indent);
_source.println(" End If");
_source.println();
_source.print(_indent);
_source.println(" Return state_");
_source.print(_indent);
_source.println(" End Get");
_source.println();
_source.print(_indent);
_source.print(" Set(ByVal state As ");
_source.print(context);
_source.println("State)");
_source.println();
_source.print(_indent);
_source.println(" state_ = state");
_source.print(_indent);
_source.println(" End Set");
_source.print(_indent);
_source.println(" End Property");
_source.println();
// The Owner property.
_source.print(_indent);
_source.print(
" Public Property Owner() As ");
_source.println(context);
_source.print(_indent);
_source.println(" Get");
_source.print(_indent);
_source.println(" Return _owner");
_source.print(_indent);
_source.println(" End Get");
_source.print(_indent);
_source.print(" Set(ByVal owner As ");
_source.print(context);
_source.println(")");
_source.println();
_source.print(_indent);
_source.println(" If owner Is Nothing _");
_source.print(_indent);
_source.println(" Then");
_source.print(_indent);
_source.println(
" Throw New NullReferenceException");
_source.print(_indent);
_source.println(" End If");
_source.println();
_source.print(_indent);
_source.println(" _owner = owner");
_source.print(_indent);
_source.println(" End Set");
_source.print(_indent);
_source.println(" End Property");
_source.println();
// The states property.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.print(
" Public ReadOnly Property States() As ");
_source.print(context);
_source.println("State()");
_source.print(_indent);
_source.println(" Get");
_source.print(_indent);
_source.println(" Return _States");
_source.print(_indent);
_source.println(" End Get");
_source.print(_indent);
_source.println(" End Property");
_source.println();
}
// The state name "map::state" must be changed to
// "map.state".
if ((index = startState.indexOf("::")) >= 0)
{
vbState = startState.substring(0, index) +
"." +
startState.substring(index + 2);
}
else
{
vbState = startState;
}
// Generate the class member methods, starting with the
// constructor.
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Member methods");
_source.print(_indent);
_source.println(" '");
_source.println();
_source.print(_indent);
_source.print(" Public Sub New(ByRef owner As ");
_source.print(context);
_source.println(")");
_source.println();
_source.print(_indent);
_source.print(" MyBase.New(");
_source.print(vbState);
_source.println(")");
_source.print(_indent);
_source.println(" _owner = owner");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
// Execute the start state's entry actions.
_source.print(_indent);
_source.println(" Public Overrides Sub EnterStartState()");
_source.println();
_source.print(_indent);
_source.println(" State.Entry(Me)");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
// Generate the transition methods. These methods are all
// formatted: set transition name, call the current
// state's transition method, clear the transition name.
transitions = fsm.getTransitions();
for (SmcTransition trans: transitions)
{
// Ignore the default transition.
if (trans.getName().equals("Default") == false)
{
_source.print(_indent);
_source.print(" Public Sub ");
_source.print(trans.getName());
_source.print("(");
// Now output the transition's parameters.
params = trans.getParameters();
for (pit = params.iterator(), separator = "";
pit.hasNext() == true;
separator = ", ")
{
_source.print(separator);
(pit.next()).accept(this);
}
_source.println(")");
_source.println();
// If the -sync flag was specified, then output
// "SyncLock Me" to prevent multiple threads from
// access this state machine simultaneously.
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" SyncLock Me");
indent2 = _indent + " ";
}
else
{
indent2 = _indent + " ";
}
// Save away the transition name in case it is
// need in an UndefinedTransitionException.
_source.print(indent2);
_source.print("transition_ = \"");
_source.print(trans.getName());
_source.println("\"");
_source.print(indent2);
_source.print("State.");
_source.print(trans.getName());
_source.print("(Me");
for (SmcParameter param: params)
{
_source.print(", ");
_source.print(param.getName());
}
_source.println(")");
_source.print(indent2);
_source.println("transition_ = \"\"");
// If the -sync flag was specified, then output
// the "End SyncLock".
if (_syncFlag == true)
{
_source.print(_indent);
_source.println(" End SyncLock");
}
_source.print(_indent);
_source.println(" End Sub");
_source.println();
}
}
// If serialization is one, then output the GetObjectData
// and deserialize constructor.
if (_serialFlag == true)
{
// Output the ValueOf method.
_source.print(_indent);
_source.print(" Public Function ValueOf(");
_source.print("ByVal stateId As Integer) As ");
_source.print(context);
_source.println("State");
_source.println();
_source.print(_indent);
_source.println(
" Return _States(stateId)");
_source.print(_indent);
_source.println(" End Function");
_source.println();
_source.print(_indent);
_source.print(" Private Sub GetObjectData(");
_source.println(
"ByVal info As SerializationInfo, _");
_source.print(_indent);
_source.print(" ");
_source.println(
"ByVal context As StreamingContext) _");
_source.print(_indent);
_source.print(" ");
_source.println(
"Implements ISerializable.GetObjectData");
_source.println();
_source.print(_indent);
_source.println(
" Dim stackSize As Integer = 0");
_source.print(_indent);
_source.println(" Dim index As Integer");
_source.print(_indent);
_source.println(" Dim it As IEnumerator");
_source.println();
_source.print(_indent);
_source.println(
" If Not IsNothing(stateStack_) _");
_source.print(_indent);
_source.println(" Then");
_source.print(_indent);
_source.println(
" stackSize = stateStack_.Count");
_source.print(_indent);
_source.println(
" it = stateStack_.GetEnumerator()");
_source.print(_indent);
_source.println(" End If");
_source.println();
_source.print(_indent);
_source.print(" ");
_source.println(
"info.AddValue(\"stackSize\", stackSize)");
_source.println();
_source.print(_indent);
_source.println(" index = 0");
_source.print(_indent);
_source.println(" While index < stackSize");
_source.print(_indent);
_source.println(" it.MoveNext()");
_source.print(_indent);
_source.println(" info.AddValue( _");
_source.print(_indent);
_source.print(" ");
_source.println(
"String.Concat(\"stackItem\", index), _");
_source.print(_indent);
_source.println(
" it.Current.Id)");
_source.print(_indent);
_source.println(" index += 1");
_source.print(_indent);
_source.println(" End While");
_source.println();
_source.print(_indent);
_source.println(
" info.AddValue(\"state\", state_.Id)");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
_source.print(_indent);
_source.print(" Private Sub New(");
_source.println(
"ByVal info As SerializationInfo, _");
_source.print(_indent);
_source.print(" ");
_source.println(
"ByVal context As StreamingContext)");
_source.println();
_source.print(_indent);
_source.println(" MyBase.New(Nothing)");
_source.println();
_source.print(_indent);
_source.println(" Dim stackSize As Integer");
_source.print(_indent);
_source.println(" Dim stateId As Integer");
_source.println();
_source.print(_indent);
_source.print(" stackSize = ");
_source.println("info.GetInt32(\"stackSize\")");
_source.print(_indent);
_source.println(" If stackSize > 0 _");
_source.print(_indent);
_source.println(" Then");
_source.print(_indent);
_source.println(" Dim index As Integer");
_source.println();
_source.print(_indent);
_source.println(
" stateStack_ = New Stack()");
_source.print(_indent);
_source.println(
" index = stackSize - 1");
_source.print(_indent);
_source.println(
" While index >= 0");
_source.print(_indent);
_source.println(
" stateId = _");
_source.print(_indent);
_source.println(
" info.GetInt32( _");
_source.print(_indent);
_source.print(" ");
_source.println(
"String.Concat(\"stackItem\", index))");
_source.print(_indent);
_source.print(" ");
_source.println(
"stateStack_.Push(_States(stateId))");
_source.print(_indent);
_source.println(
" index -= 1");
_source.print(_indent);
_source.println(
" End While");
_source.print(_indent);
_source.println(" End If");
_source.println();
_source.print(_indent);
_source.println(
" stateId = info.GetInt32(\"state\")");
_source.print(_indent);
_source.println(" state_ = _States(stateId)");
_source.println();
_source.print(_indent);
_source.println(" End Sub");
_source.println();
}
// The context class declaration is complete.
_source.print(_indent);
_source.println("End Class");
_source.println();
// Declare the root application state class.
_source.print(_indent);
_source.print("Public MustInherit Class ");
_source.print(context);
_source.println("State");
_source.print(_indent);
_source.println(" Inherits statemap.State");
_source.println();
// If reflection is on, then generate the abstract
// Transitions property.
if (_reflectFlag == true)
{
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Properties");
_source.print(_indent);
_source.println(" '");
_source.println();
_source.print(_indent);
_source.print(" Public MustOverride ReadOnly ");
_source.print(
"Property Transitions() As IDictionary");
if (_genericFlag == true)
{
_source.print("(Of String, Integer)");
}
_source.println();
_source.println();
}
_source.print(_indent);
_source.println(
" '------------------------------------------------------------");
_source.print(_indent);
_source.println(" ' Member methods");
_source.print(_indent);
_source.println(" '");
_source.println();
_source.print(_indent);
_source.print(" Protected Sub New(");
_source.println(
"ByVal name As String, ByVal id As Integer)");
_source.println();
_source.print(_indent);
_source.println(" MyBase.New(name, id)");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
_source.print(_indent);
_source.print(" Public Overridable Sub Entry(");
_source.print("ByRef context As ");
_source.print(fsmClassName);
_source.println(")");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
_source.print(_indent);
_source.print(" Public Overridable Sub Exit_(");
_source.print("ByRef context As ");
_source.print(fsmClassName);
_source.println(")");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
// Generate the default transition definitions.
for (SmcTransition trans: transitions)
{
// Don't generate the Default transition here.
if (trans.getName().equals("Default") == false)
{
_source.print(_indent);
_source.print(" Public Overridable Sub ");
_source.print(trans.getName());
_source.print("(ByRef context As ");
_source.print(fsmClassName);
_source.print("");
for (SmcParameter param: trans.getParameters())
{
_source.print(", ");
param.accept(this);
}
_source.println(")");
_source.println();
// If this method is reached, that means that
// this transition was passed to a state which
// does not define the transition. Call the
// state's default transition method.
// Note: "Default" is a VB keyword, so use
// "Default_" instead.
_source.print(_indent);
_source.println(" Default_(context)");
_source.print(_indent);
_source.println(" End Sub");
_source.println();
}
}
// Generate the overall Default transition for all maps.
// Note: "Default" is a VB keyword, so use "Default_"
// instead.
_source.print(_indent);
_source.print(" Public Overridable Sub Default_(");
_source.print("ByRef context As ");
_source.print(fsmClassName);
_source.println(")");
_source.println();
if (_debugLevel >= DEBUG_LEVEL_0)
{
_source.println("#If TRACE Then");
_source.print(_indent);
_source.print(" Trace.WriteLine(");
_source.println("\"TRANSITION : Default\")");
_source.println("#End If");
_source.println();
}
_source.print(_indent);
_source.print(" Throw ");
_source.println(
"New statemap.TransitionUndefinedException( _");
_source.print(_indent);
_source.println(
" String.Concat(\"State: \", _");
_source.print(_indent);
_source.println(" context.State.Name, _");
_source.print(_indent);
_source.println(" \", Transition: \", _");
_source.print(_indent);
_source.println(
" context.GetTransition()))");
_source.print(_indent);
_source.println(" End Sub");
// End of the application class' state class.
_source.print(_indent);
_source.println("End Class");
// Have each map print out its source code now.
for (SmcMap map: maps)
{
map.accept(this);
}
// If a package has been specified, then generate
// the End tag now.
if (packageName != null && packageName.length() > 0)
{
_source.println();
_source.println("End Namespace");
}
return;
} // end of visit(SmcFSM) | void function(SmcFSM fsm) { String rawSource = fsm.getSource(); String packageName = fsm.getPackage(); String context = fsm.getContext(); String fsmClassName = fsm.getFsmClassName(); String startState = fsm.getStartState(); List<SmcMap> maps = fsm.getMaps(); List<SmcTransition> transitions; List<SmcParameter> params; Iterator<SmcParameter> pit; String transName; String vbState; String separator; int index; String indent2; if (rawSource != null && rawSource.length () > 0) { _source.println(rawSource); _source.println(); } if (_reflectFlag == true) { if (_genericFlag == false) { _source.println(STR); } else { _source.println(STR); } } for (String imp: fsm.getImports()) { _source.print(STR); _source.println(imp); } if (_serialFlag == true) { _source.println( STR); } _source.println(); if (packageName != null && packageName.length() > 0) { _source.print(STR); _source.println(packageName); _source.println(); _indent = " "; } if (_serialFlag == true) { _source.print(_indent); _source.print(STR); } _source.print(_indent); _source.print(STR); _source.print(fsmClassName); _source.println(STR Inherits statemap.FSMContextSTR Implements ISerializableSTR '------------------------------------------------------------STR ' Member dataSTR 'STR ' The associated application class instance.STR Private _owner As STR '------------------------------------------------------------STR ' Shared dataSTR 'STR ' State instance array. STRUsed to deserialize.STR Private Shared ReadOnly _States() As STRState = _STR {STR _STR STR, _STR _STR }STR '------------------------------------------------------------STR ' PropertiesSTR 'STR Public Property State() As STRStateSTR GetSTR If state_ Is Nothing _STR ThenSTR Throw STRNew statemap.StateUndefinedException()STR End IfSTR Return state_STR End GetSTR Set(ByVal state As STRState)STR state_ = stateSTR End SetSTR End PropertySTR Public Property Owner() As STR GetSTR Return _ownerSTR End GetSTR Set(ByVal owner As STR)STR If owner Is Nothing _STR ThenSTR Throw New NullReferenceExceptionSTR End IfSTR _owner = ownerSTR End SetSTR End PropertySTR Public ReadOnly Property States() As STRState()STR GetSTR Return _StatesSTR End GetSTR End PropertySTR::STR.STR '------------------------------------------------------------STR ' Member methodsSTR 'STR Public Sub New(ByRef owner As STR)STR MyBase.New(STR)STR _owner = ownerSTR End SubSTR Public Overrides Sub EnterStartState()STR State.Entry(Me)STR End SubSTRDefaultSTR Public Sub STR(STRSTR, STR)STR SyncLock MeSTR STR STRtransition_ = \STR\STRState.STR(MeSTR, STR)STRtransition_ = \"\"STR End SyncLockSTR End SubSTR Public Function ValueOf(STRByVal stateId As Integer) As STRStateSTR Return _States(stateId)STR End FunctionSTR Private Sub GetObjectData(STRByVal info As SerializationInfo, _STR STRByVal context As StreamingContext) _STR STRImplements ISerializable.GetObjectDataSTR Dim stackSize As Integer = 0STR Dim index As IntegerSTR Dim it As IEnumeratorSTR If Not IsNothing(stateStack_) _STR ThenSTR stackSize = stateStack_.CountSTR it = stateStack_.GetEnumerator()STR End IfSTR STRinfo.AddValue(\STR, stackSize)STR index = 0STR While index < stackSizeSTR it.MoveNext()STR info.AddValue( _STR STRString.Concat(\STR, index), _STR it.Current.Id)STR index += 1STR End WhileSTR info.AddValue(\STR, state_.Id)STR End SubSTR Private Sub New(STRByVal info As SerializationInfo, _STR STRByVal context As StreamingContext)STR MyBase.New(Nothing)STR Dim stackSize As IntegerSTR Dim stateId As IntegerSTR stackSize = STRinfo.GetInt32(\STR)STR If stackSize > 0 _STR ThenSTR Dim index As IntegerSTR stateStack_ = New Stack()STR index = stackSize - 1STR While index >= 0STR stateId = _STR info.GetInt32( _STR STRString.Concat(\STR, index))STR STRstateStack_.Push(_States(stateId))STR index -= 1STR End WhileSTR End IfSTR stateId = info.GetInt32(\STR)STR state_ = _States(stateId)STR End SubSTREnd ClassSTRPublic MustInherit Class STRStateSTR Inherits statemap.StateSTR '------------------------------------------------------------STR ' PropertiesSTR 'STR Public MustOverride ReadOnly STRProperty Transitions() As IDictionarySTR(Of String, Integer)STR '------------------------------------------------------------STR ' Member methodsSTR 'STR Protected Sub New(STRByVal name As String, ByVal id As Integer)STR MyBase.New(name, id)STR End SubSTR Public Overridable Sub Entry(STRByRef context As STR)STR End SubSTR Public Overridable Sub Exit_(STRByRef context As STR)STR End SubSTRDefaultSTR Public Overridable Sub STR(ByRef context As STRSTR, STR)STR Default_(context)STR End SubSTR Public Overridable Sub Default_(STRByRef context As STR)STR#If TRACE ThenSTR Trace.WriteLine(STR\STR)STR#End IfSTR Throw STRNew statemap.TransitionUndefinedException( _STR String.Concat(\STR, _STR context.State.Name, _STR \STR, _STR context.GetTransition()))STR End SubSTREnd ClassSTREnd Namespace"); } return; } | /**
* Emits VB code for the finite state machine.
* @param fsm emit VB code for this finite state machine.
*/ | Emits VB code for the finite state machine | visit | {
"repo_name": "Praveen-1987/devstack-Quantumleap",
"path": "smc/net/sf/smc/generator/SmcVBGenerator.java",
"license": "apache-2.0",
"size": 70855
} | [
"java.util.Iterator",
"java.util.List",
"net.sf.smc.model.SmcFSM",
"net.sf.smc.model.SmcMap",
"net.sf.smc.model.SmcParameter",
"net.sf.smc.model.SmcTransition"
] | import java.util.Iterator; import java.util.List; import net.sf.smc.model.SmcFSM; import net.sf.smc.model.SmcMap; import net.sf.smc.model.SmcParameter; import net.sf.smc.model.SmcTransition; | import java.util.*; import net.sf.smc.model.*; | [
"java.util",
"net.sf.smc"
] | java.util; net.sf.smc; | 1,501,097 |
public void destroyRegion(EventID eventId, Object callbackArg) {
DestroyRegionOp.execute(pool, regionName, eventId, callbackArg);
} | void function(EventID eventId, Object callbackArg) { DestroyRegionOp.execute(pool, regionName, eventId, callbackArg); } | /**
* Does a region destroy on the server
*
* @param eventId the event id for this destroy
* @param callbackArg an optional callback arg to pass to any cache callbacks
*/ | Does a region destroy on the server | destroyRegion | {
"repo_name": "PurelyApplied/geode",
"path": "geode-core/src/main/java/org/apache/geode/cache/client/internal/ServerRegionProxy.java",
"license": "apache-2.0",
"size": 33053
} | [
"org.apache.geode.internal.cache.EventID"
] | import org.apache.geode.internal.cache.EventID; | import org.apache.geode.internal.cache.*; | [
"org.apache.geode"
] | org.apache.geode; | 1,253,077 |
public static <E extends Enum<E>> List<E> parseListEnums(final String s, final Class<E> enumClass) {
final List<E> enums = new ArrayList<>();
final String[] substrings = s.trim().split(",");
for (final String substring : substrings) {
final E value = parseEnum(substring, enumClass);
if (value == null) {
throw new IllegalArgumentException(
"Unable to parse list element, expected enum constant name but actual was [" + substring + "]");
}
enums.add(value);
}
return enums;
} | static <E extends Enum<E>> List<E> function(final String s, final Class<E> enumClass) { final List<E> enums = new ArrayList<>(); final String[] substrings = s.trim().split(","); for (final String substring : substrings) { final E value = parseEnum(substring, enumClass); if (value == null) { throw new IllegalArgumentException( STR + substring + "]"); } enums.add(value); } return enums; } | /**
* Parses a comma separated list of enum names
* @param s The string to scan
* @param enumClass The class of enum constants
* @return List of found enum constants
*/ | Parses a comma separated list of enum names | parseListEnums | {
"repo_name": "clicktravel-chris/Cheddar",
"path": "commons/commons-lang/src/main/java/com/clicktravel/common/functional/StringUtils.java",
"license": "apache-2.0",
"size": 3609
} | [
"java.util.ArrayList",
"java.util.List"
] | import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,498,026 |
public void setBlockCommentStartDelimiter(String blockCommentStartDelimiter) {
Assert.hasText(blockCommentStartDelimiter, "'blockCommentStartDelimiter' must not be null or empty");
this.blockCommentStartDelimiter = blockCommentStartDelimiter;
} | void function(String blockCommentStartDelimiter) { Assert.hasText(blockCommentStartDelimiter, STR); this.blockCommentStartDelimiter = blockCommentStartDelimiter; } | /**
* Set the start delimiter that identifies block comments within the SQL
* scripts.
* <p>Defaults to {@code "/*"}.
* @param blockCommentStartDelimiter the start delimiter for block comments
* (never {@code null} or empty)
* @see #setBlockCommentEndDelimiter
*/ | Set the start delimiter that identifies block comments within the SQL scripts. Defaults to "/*" | setBlockCommentStartDelimiter | {
"repo_name": "spring-projects/spring-framework",
"path": "spring-r2dbc/src/main/java/org/springframework/r2dbc/connection/init/ResourceDatabasePopulator.java",
"license": "apache-2.0",
"size": 10185
} | [
"org.springframework.util.Assert"
] | import org.springframework.util.Assert; | import org.springframework.util.*; | [
"org.springframework.util"
] | org.springframework.util; | 683,402 |
public HddsProtos.ReplicationType getType() {
// TODO : Fix me and make Ratis default before release.
// TODO: Remove this as replication factor and type are pipeline properties
if(isUseRatis()) {
return HddsProtos.ReplicationType.RATIS;
}
return HddsProtos.ReplicationType.STAND_ALONE;
} | HddsProtos.ReplicationType function() { if(isUseRatis()) { return HddsProtos.ReplicationType.RATIS; } return HddsProtos.ReplicationType.STAND_ALONE; } | /**
* Returns the default replication type.
* @return Ratis or Standalone
*/ | Returns the default replication type | getType | {
"repo_name": "littlezhou/hadoop",
"path": "hadoop-hdds/client/src/main/java/org/apache/hadoop/hdds/scm/XceiverClientManager.java",
"license": "apache-2.0",
"size": 7528
} | [
"org.apache.hadoop.hdds.protocol.proto.HddsProtos"
] | import org.apache.hadoop.hdds.protocol.proto.HddsProtos; | import org.apache.hadoop.hdds.protocol.proto.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 841,456 |
@Test(expected = IOException.class)
public void testBadOpenImport() throws IOException {
doTestBadOpen(NaiveFileFailoverManager.IMPORTDIR);
} | @Test(expected = IOException.class) void function() throws IOException { doTestBadOpen(NaiveFileFailoverManager.IMPORTDIR); } | /**
* Tests import to make sure we handle errors with dir problems
*/ | Tests import to make sure we handle errors with dir problems | testBadOpenImport | {
"repo_name": "anuragphadke/Flume-Hive",
"path": "src/javatest/com/cloudera/flume/agent/diskfailover/TestDiskFailoverManager.java",
"license": "apache-2.0",
"size": 8484
} | [
"java.io.IOException",
"org.junit.Test"
] | import java.io.IOException; import org.junit.Test; | import java.io.*; import org.junit.*; | [
"java.io",
"org.junit"
] | java.io; org.junit; | 2,570,871 |
public XMLString toLowerCase(Locale locale)
{
return new XString(str().toLowerCase(locale));
} | XMLString function(Locale locale) { return new XString(str().toLowerCase(locale)); } | /**
* Converts all of the characters in this <code>String</code> to lower
* case using the rules of the given <code>Locale</code>.
*
* @param locale use the case transformation rules for this locale
* @return the String, converted to lowercase.
* @see java.lang.Character#toLowerCase(char)
* @see java.lang.String#toUpperCase(Locale)
*/ | Converts all of the characters in this <code>String</code> to lower case using the rules of the given <code>Locale</code> | toLowerCase | {
"repo_name": "shun634501730/java_source_cn",
"path": "src_en/com/sun/org/apache/xpath/internal/objects/XString.java",
"license": "apache-2.0",
"size": 37914
} | [
"com.sun.org.apache.xml.internal.utils.XMLString",
"java.util.Locale"
] | import com.sun.org.apache.xml.internal.utils.XMLString; import java.util.Locale; | import com.sun.org.apache.xml.internal.utils.*; import java.util.*; | [
"com.sun.org",
"java.util"
] | com.sun.org; java.util; | 794,777 |
@Nullable
public List<String> getUserinfoEncryptionEncodingValuesSupported() {
return get(USERINFO_ENCRYPTION_ENC_VALUES_SUPPORTED);
} | List<String> function() { return get(USERINFO_ENCRYPTION_ENC_VALUES_SUPPORTED); } | /**
* The JWE encryption encodings (enc values) supported by the UserInfo Endpoint
* for encoding ID token claims.
*
* @see <a href="https://tools.ietf.org/html/rfc7519">"JSON Web Token (JWT)"</a>
*/ | The JWE encryption encodings (enc values) supported by the UserInfo Endpoint for encoding ID token claims | getUserinfoEncryptionEncodingValuesSupported | {
"repo_name": "StudienprojektUniTrier/Client",
"path": "library/java/net/openid/appauth/AuthorizationServiceDiscovery.java",
"license": "apache-2.0",
"size": 21556
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 1,091,591 |
Subsets and Splits