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 list | imports_info stringlengths 19 34.8k | cluster_imports_info stringlengths 15 3.66k | libraries list | libraries_info stringlengths 6 661 | id int64 0 2.92M |
|---|---|---|---|---|---|---|---|---|---|---|---|
@Test
public void testWFSDownloadStatus() throws Exception {
final String serviceUrl = "http://example/url";
final String email = "unique@email";
final byte[] data = new byte[] {0,1,2,3,4,5,6,7,8,9};
final String contentType = "text/html";
final WFSStatusResponse mockResponse = context.mock(WFSStatusResponse.class);
final ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
final ByteBufferedServletOutputStream outputStream = new ByteBufferedServletOutputStream(data.length);
context.checking(new Expectations() {{
oneOf(mockDataService).checkWFSStatus(serviceUrl, email);will(returnValue(mockResponse));
oneOf(mockHttpResponse).setContentType(contentType);
oneOf(mockHttpResponse).getOutputStream();will(returnValue(outputStream));
allowing(mockResponse).getContentType();will(returnValue(contentType));
allowing(mockResponse).getResponse();will(returnValue(inputStream));
}});
this.nvclController.getNVCLWFSDownloadStatus(serviceUrl, email, mockHttpResponse);
Assert.assertArrayEquals(data, outputStream.toByteArray());
}
| void function() throws Exception { final String serviceUrl = STRunique@emailSTRtext/html"; final WFSStatusResponse mockResponse = context.mock(WFSStatusResponse.class); final ByteArrayInputStream inputStream = new ByteArrayInputStream(data); final ByteBufferedServletOutputStream outputStream = new ByteBufferedServletOutputStream(data.length); context.checking(new Expectations() {{ oneOf(mockDataService).checkWFSStatus(serviceUrl, email);will(returnValue(mockResponse)); oneOf(mockHttpResponse).setContentType(contentType); oneOf(mockHttpResponse).getOutputStream();will(returnValue(outputStream)); allowing(mockResponse).getContentType();will(returnValue(contentType)); allowing(mockResponse).getResponse();will(returnValue(inputStream)); }}); this.nvclController.getNVCLWFSDownloadStatus(serviceUrl, email, mockHttpResponse); Assert.assertArrayEquals(data, outputStream.toByteArray()); } | /**
* Tests a WFS download status calls the underlying service correctly
* @throws Exception
*/ | Tests a WFS download status calls the underlying service correctly | testWFSDownloadStatus | {
"repo_name": "AuScope/EOI-TCP",
"path": "src/test/java/org/auscope/portal/server/web/controllers/TestNVCLController.java",
"license": "gpl-3.0",
"size": 30174
} | [
"java.io.ByteArrayInputStream",
"org.auscope.portal.core.test.ByteBufferedServletOutputStream",
"org.auscope.portal.server.domain.nvcldataservice.WFSStatusResponse",
"org.jmock.Expectations",
"org.junit.Assert"
] | import java.io.ByteArrayInputStream; import org.auscope.portal.core.test.ByteBufferedServletOutputStream; import org.auscope.portal.server.domain.nvcldataservice.WFSStatusResponse; import org.jmock.Expectations; import org.junit.Assert; | import java.io.*; import org.auscope.portal.core.test.*; import org.auscope.portal.server.domain.nvcldataservice.*; import org.jmock.*; import org.junit.*; | [
"java.io",
"org.auscope.portal",
"org.jmock",
"org.junit"
] | java.io; org.auscope.portal; org.jmock; org.junit; | 1,916,134 |
public String getPrefix(String namespaceURI) {
Iterator<String> it = prefixMap.keySet().iterator();
while (it.hasNext()) {
String prefix = it.next();
Stack<String> stack = prefixMap.get(prefix);
if (namespaceURI.equals(stack.peek())) { return prefix; }
}
return null;
} | String function(String namespaceURI) { Iterator<String> it = prefixMap.keySet().iterator(); while (it.hasNext()) { String prefix = it.next(); Stack<String> stack = prefixMap.get(prefix); if (namespaceURI.equals(stack.peek())) { return prefix; } } return null; } | /**
* Provides reverse lookup; namespace uri -> prefix. The first prefix found
* will be returned. Multiple calls to this method may return different
* prefixes if more than one prefix is mapped to the given namespace uri.
*
* @param uri
* The uri to search for.
* @return The prefix to use for the uri or null if none exists.
*/ | Provides reverse lookup; namespace uri -> prefix. The first prefix found will be returned. Multiple calls to this method may return different prefixes if more than one prefix is mapped to the given namespace uri | getPrefix | {
"repo_name": "jvasileff/aos-commons",
"path": "src.java/org/anodyneos/commons/xml/NamespaceMapping.java",
"license": "mit",
"size": 5697
} | [
"java.util.Iterator",
"java.util.Stack"
] | import java.util.Iterator; import java.util.Stack; | import java.util.*; | [
"java.util"
] | java.util; | 800,134 |
@Test
public void readTest3() throws IOException {
for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) {
for (WriteType op : WriteType.values()) {
int fileId = TestUtils.createByteFile(mTfs, "/root/testFile_" + k + "_" + op, op, k);
TachyonFile file = mTfs.getFile(fileId);
InStream is =
(k < MEAN ? file.getInStream(ReadType.CACHE) : file.getInStream(ReadType.NO_CACHE));
Assert.assertTrue(is instanceof FileInStream);
byte[] ret = new byte[k / 2];
Assert.assertEquals(k / 2, is.read(ret, 0, k / 2));
Assert.assertTrue(TestUtils.equalIncreasingByteArray(k / 2, ret));
is.close();
is = (k < MEAN ? file.getInStream(ReadType.CACHE) : file.getInStream(ReadType.NO_CACHE));
Assert.assertTrue(is instanceof FileInStream);
ret = new byte[k];
Assert.assertEquals(k, is.read(ret, 0, k));
Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret));
is.close();
}
}
} | void function() throws IOException { for (int k = MIN_LEN; k <= MAX_LEN; k += DELTA) { for (WriteType op : WriteType.values()) { int fileId = TestUtils.createByteFile(mTfs, STR + k + "_" + op, op, k); TachyonFile file = mTfs.getFile(fileId); InStream is = (k < MEAN ? file.getInStream(ReadType.CACHE) : file.getInStream(ReadType.NO_CACHE)); Assert.assertTrue(is instanceof FileInStream); byte[] ret = new byte[k / 2]; Assert.assertEquals(k / 2, is.read(ret, 0, k / 2)); Assert.assertTrue(TestUtils.equalIncreasingByteArray(k / 2, ret)); is.close(); is = (k < MEAN ? file.getInStream(ReadType.CACHE) : file.getInStream(ReadType.NO_CACHE)); Assert.assertTrue(is instanceof FileInStream); ret = new byte[k]; Assert.assertEquals(k, is.read(ret, 0, k)); Assert.assertTrue(TestUtils.equalIncreasingByteArray(k, ret)); is.close(); } } } | /**
* Test <code>void read(byte[] b, int off, int len)</code>.
*/ | Test <code>void read(byte[] b, int off, int len)</code> | readTest3 | {
"repo_name": "solzy/tachyon",
"path": "core/src/test/java/tachyon/client/FileInStreamTest.java",
"license": "apache-2.0",
"size": 9230
} | [
"java.io.IOException",
"org.junit.Assert"
] | import java.io.IOException; import org.junit.Assert; | import java.io.*; import org.junit.*; | [
"java.io",
"org.junit"
] | java.io; org.junit; | 1,775,298 |
protected boolean isDamageTreeNode(ISimpleTerm tree, boolean isOriginalTree, int skippedChars) {
IToken current = findLeftMostLayoutToken(getLeftToken(tree));
IToken last = findRightMostLayoutToken(getRightToken(tree));
if (current != null && last != null) {
if (!isDamagedRange(
current.getStartOffset(), last.getEndOffset(), isOriginalTree, skippedChars))
return false;
Iterator<ISimpleTerm> iterator = tryGetListIterator(tree);
for (int i = 0, max = tree.getSubtermCount(); i < max; i++) {
ISimpleTerm child = iterator == null ? tree.getSubterm(i) : iterator.next();
IToken childLeft = findLeftMostLayoutToken(getLeftToken(child));
IToken childRight = findRightMostLayoutToken(getRightToken(child));
if (childLeft != null && childRight != null) {
if (childLeft.getIndex() > current.getIndex()
&& isDamagedRange(
current.getEndOffset() + 1, childLeft.getStartOffset() - 1,
isOriginalTree, skippedChars)) {
return true;
}
current = childRight;
}
}
return isDamagedRange(
current.getEndOffset() + 1, last.getEndOffset(), isOriginalTree, skippedChars);
} else {
return false;
}
}
| boolean function(ISimpleTerm tree, boolean isOriginalTree, int skippedChars) { IToken current = findLeftMostLayoutToken(getLeftToken(tree)); IToken last = findRightMostLayoutToken(getRightToken(tree)); if (current != null && last != null) { if (!isDamagedRange( current.getStartOffset(), last.getEndOffset(), isOriginalTree, skippedChars)) return false; Iterator<ISimpleTerm> iterator = tryGetListIterator(tree); for (int i = 0, max = tree.getSubtermCount(); i < max; i++) { ISimpleTerm child = iterator == null ? tree.getSubterm(i) : iterator.next(); IToken childLeft = findLeftMostLayoutToken(getLeftToken(child)); IToken childRight = findRightMostLayoutToken(getRightToken(child)); if (childLeft != null && childRight != null) { if (childLeft.getIndex() > current.getIndex() && isDamagedRange( current.getEndOffset() + 1, childLeft.getStartOffset() - 1, isOriginalTree, skippedChars)) { return true; } current = childRight; } } return isDamagedRange( current.getEndOffset() + 1, last.getEndOffset(), isOriginalTree, skippedChars); } else { return false; } } | /**
* Determines if the damage region affects a particular tree node,
* looking only at those tokens that actually belong to the node
* and not to its children.
*/ | Determines if the damage region affects a particular tree node, looking only at those tokens that actually belong to the node and not to its children | isDamageTreeNode | {
"repo_name": "metaborg/jsglr",
"path": "org.spoofax.jsglr/src/org/spoofax/jsglr/client/incremental/DamageRegionAnalyzer.java",
"license": "apache-2.0",
"size": 6782
} | [
"java.util.Iterator",
"org.spoofax.interpreter.terms.ISimpleTerm",
"org.spoofax.jsglr.client.imploder.AbstractTokenizer",
"org.spoofax.jsglr.client.imploder.IToken",
"org.spoofax.terms.SimpleTermVisitor"
] | import java.util.Iterator; import org.spoofax.interpreter.terms.ISimpleTerm; import org.spoofax.jsglr.client.imploder.AbstractTokenizer; import org.spoofax.jsglr.client.imploder.IToken; import org.spoofax.terms.SimpleTermVisitor; | import java.util.*; import org.spoofax.interpreter.terms.*; import org.spoofax.jsglr.client.imploder.*; import org.spoofax.terms.*; | [
"java.util",
"org.spoofax.interpreter",
"org.spoofax.jsglr",
"org.spoofax.terms"
] | java.util; org.spoofax.interpreter; org.spoofax.jsglr; org.spoofax.terms; | 2,335,833 |
documentDao.save(document);
AitLogger.debug(logger, "Documento guardado y metadata" + document);
return document;
}
| documentDao.save(document); AitLogger.debug(logger, STR + document); return document; } | /**
* Guarda un documento y retorna la informacion generada del mismo (metadata)
*
* @see IAitDocumentSrv.gov.fgn.susi.core.common.file.service.ICoreArchiveSrv#save(AitDocumentMetadataVO.gov.fgn.core.common.model.dto.CoreDocumentDto)
*
*/ | Guarda un documento y retorna la informacion generada del mismo (metadata) | save | {
"repo_name": "allianzit/ait-platform",
"path": "apps/common/common-utils/src/main/java/com/ait/platform/common/file/service/impl/AitDocumentSrv.java",
"license": "apache-2.0",
"size": 2886
} | [
"com.ait.platform.common.logger.AitLogger"
] | import com.ait.platform.common.logger.AitLogger; | import com.ait.platform.common.logger.*; | [
"com.ait.platform"
] | com.ait.platform; | 1,077,571 |
public static Text utf8Trim(Text src) {
return utf8Trim(src, src);
} | static Text function(Text src) { return utf8Trim(src, src); } | /**
* Trim leading / trailing whitespace from the passed text object which
* contains UTF8 byte stream
*
* @param text
* Object to trim
* @return text object, for call chaining
*/ | Trim leading / trailing whitespace from the passed text object which contains UTF8 byte stream | utf8Trim | {
"repo_name": "chriswhite199/hadoop-text-util",
"path": "src/main/java/csw/hadoop/text/TextUtils.java",
"license": "apache-2.0",
"size": 11967
} | [
"org.apache.hadoop.io.Text"
] | import org.apache.hadoop.io.Text; | import org.apache.hadoop.io.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 403,830 |
private boolean setNodePropertiesImpl(
Long nodeId,
Map<QName, Serializable> newProps,
boolean isAddOnly)
{
if (isAddOnly && newProps.size() == 0)
{
return false; // No point adding nothing
}
// Get the current node
Node node = getNodeNotNull(nodeId, false);
// Create an update node
NodeUpdateEntity nodeUpdate = new NodeUpdateEntity();
nodeUpdate.setId(nodeId);
// Copy inbound values
newProps = new HashMap<QName, Serializable>(newProps);
// Copy cm:auditable
if (!policyBehaviourFilter.isEnabled(node.getNodeRef(), ContentModel.ASPECT_AUDITABLE))
{
// Only bother if cm:auditable properties are present
if (AuditablePropertiesEntity.hasAuditableProperty(newProps.keySet()))
{
AuditablePropertiesEntity auditableProps = node.getAuditableProperties();
if (auditableProps == null)
{
auditableProps = new AuditablePropertiesEntity();
}
else
{
auditableProps = new AuditablePropertiesEntity(auditableProps); // Unlocked instance
}
boolean containedAuditProperties = auditableProps.setAuditValues(null, null, newProps);
if (!containedAuditProperties)
{
// Double-check (previous hasAuditableProperty should cover it)
// The behaviour is disabled, but no audit properties were passed in
auditableProps = null;
}
nodeUpdate.setAuditableProperties(auditableProps);
nodeUpdate.setUpdateAuditableProperties(true);
}
}
// Remove cm:auditable
newProps.keySet().removeAll(AuditablePropertiesEntity.getAuditablePropertyQNames());
// Check if the sys:localized property is being changed
Long oldNodeLocaleId = node.getLocaleId();
Locale newLocale = DefaultTypeConverter.INSTANCE.convert(
Locale.class,
newProps.get(ContentModel.PROP_LOCALE));
if (newLocale != null)
{
Long newNodeLocaleId = localeDAO.getOrCreateLocalePair(newLocale).getFirst();
if (!newNodeLocaleId.equals(oldNodeLocaleId))
{
nodeUpdate.setLocaleId(newNodeLocaleId);
nodeUpdate.setUpdateLocaleId(true);
}
}
// else: a 'null' new locale is completely ignored. This is the behaviour we choose.
// Remove sys:localized
LocalizedPropertiesEntity.removeLocalizedProperties(node, newProps);
// Remove sys:referenceable
ReferenceablePropertiesEntity.removeReferenceableProperties(node, newProps);
// Load the current properties.
// This means that we have to go to the DB during cold-write operations,
// but usually a write occurs after a node has been fetched of viewed in
// some way by the client code. Loading the existing properties has the
// advantage that the differencing code can eliminate unnecessary writes
// completely.
Map<QName, Serializable> oldPropsCached = getNodePropertiesCached(nodeId); // Keep pristine for caching
Map<QName, Serializable> oldProps = new HashMap<QName, Serializable>(oldPropsCached);
// If we're adding, remove current properties that are not of interest
if (isAddOnly)
{
oldProps.keySet().retainAll(newProps.keySet());
}
// We need to convert the new properties to our internally-used format,
// which is compatible with model i.e. people may have passed in data
// which needs to be converted to a model-compliant format. We do this
// before comparisons to avoid false negatives.
Map<NodePropertyKey, NodePropertyValue> newPropsRaw = nodePropertyHelper.convertToPersistentProperties(newProps);
newProps = nodePropertyHelper.convertToPublicProperties(newPropsRaw);
// Now find out what's changed
Map<QName, MapValueComparison> diff = EqualsHelper.getMapComparison(
oldProps,
newProps);
// Keep track of properties to delete and add
Set<QName> propsToDelete = new HashSet<QName>(oldProps.size()*2);
Map<QName, Serializable> propsToAdd = new HashMap<QName, Serializable>(newProps.size() * 2);
Set<QName> contentQNamesToDelete = new HashSet<QName>(5);
for (Map.Entry<QName, MapValueComparison> entry : diff.entrySet())
{
QName qname = entry.getKey();
PropertyDefinition removePropDef = dictionaryService.getProperty(qname);
boolean isContent = (removePropDef != null &&
removePropDef.getDataType().getName().equals(DataTypeDefinition.CONTENT));
switch (entry.getValue())
{
case EQUAL:
// Ignore
break;
case LEFT_ONLY:
// Not in the new properties
propsToDelete.add(qname);
if (isContent)
{
contentQNamesToDelete.add(qname);
}
break;
case NOT_EQUAL:
// Must remove from the LHS
propsToDelete.add(qname);
if (isContent)
{
contentQNamesToDelete.add(qname);
}
// Fall through to load up the RHS
case RIGHT_ONLY:
// We're adding this
Serializable value = newProps.get(qname);
if (isContent && value != null)
{
ContentData newContentData = (ContentData) value;
Long newContentDataId = contentDataDAO.createContentData(newContentData).getFirst();
value = new ContentDataWithId(newContentData, newContentDataId);
}
propsToAdd.put(qname, value);
break;
default:
throw new IllegalStateException("Unknown MapValueComparison: " + entry.getValue());
}
}
boolean modifyProps = propsToDelete.size() > 0 || propsToAdd.size() > 0;
boolean updated = modifyProps || nodeUpdate.isUpdateAnything();
// Bring the node into the current transaction
if (nodeUpdate.isUpdateAnything())
{
// We have to explicitly update the node (sys:locale or cm:auditable)
if (updateNodeImpl(node, nodeUpdate, null))
{
// Copy the caches across
NodeVersionKey nodeVersionKey = node.getNodeVersionKey();
NodeVersionKey newNodeVersionKey = getNodeNotNull(nodeId, false).getNodeVersionKey();
copyNodeAspectsCached(nodeVersionKey, newNodeVersionKey);
copyNodePropertiesCached(nodeVersionKey, newNodeVersionKey);
copyParentAssocsCached(node);
}
}
else if (modifyProps)
{
// Touch the node; all caches are fine
touchNode(nodeId, null, null, false, false, false);
}
// Touch to bring into current txn
if (modifyProps)
{
// Clean up content properties
try
{
if (contentQNamesToDelete.size() > 0)
{
Set<Long> contentQNameIdsToDelete = qnameDAO.convertQNamesToIds(contentQNamesToDelete, false);
contentDataDAO.deleteContentDataForNode(nodeId, contentQNameIdsToDelete);
}
}
catch (Throwable e)
{
throw new AlfrescoRuntimeException(
"Failed to delete content properties: \n" +
" Node: " + nodeId + "\n" +
" Delete Tried: " + contentQNamesToDelete,
e);
}
try
{
// Apply deletes
Set<Long> propQNameIdsToDelete = qnameDAO.convertQNamesToIds(propsToDelete, true);
deleteNodeProperties(nodeId, propQNameIdsToDelete);
// Now create the raw properties for adding
newPropsRaw = nodePropertyHelper.convertToPersistentProperties(propsToAdd);
insertNodeProperties(nodeId, newPropsRaw);
}
catch (Throwable e)
{
// Don't trust the caches for the node
invalidateNodeCaches(nodeId);
// Focused error
throw new AlfrescoRuntimeException(
"Failed to write property deltas: \n" +
" Node: " + nodeId + "\n" +
" Old: " + oldProps + "\n" +
" New: " + newProps + "\n" +
" Diff: " + diff + "\n" +
" Delete Tried: " + propsToDelete + "\n" +
" Add Tried: " + propsToAdd,
e);
}
// Build the properties to cache based on whether this is an append or replace
Map<QName, Serializable> propsToCache = null;
if (isAddOnly)
{
// Copy cache properties for additions
propsToCache = new HashMap<QName, Serializable>(oldPropsCached);
// Combine the old and new properties
propsToCache.putAll(propsToAdd);
}
else
{
// Replace old properties
propsToCache = newProps;
propsToCache.putAll(propsToAdd); // Ensure correct types
}
// Update cache
setNodePropertiesCached(nodeId, propsToCache);
}
// Done
if (isDebugEnabled && updated)
{
logger.debug(
"Modified node properties: " + nodeId + "\n" +
" Removed: " + propsToDelete + "\n" +
" Added: " + propsToAdd + "\n" +
" Node Update: " + nodeUpdate);
}
return updated;
}
| boolean function( Long nodeId, Map<QName, Serializable> newProps, boolean isAddOnly) { if (isAddOnly && newProps.size() == 0) { return false; } Node node = getNodeNotNull(nodeId, false); NodeUpdateEntity nodeUpdate = new NodeUpdateEntity(); nodeUpdate.setId(nodeId); newProps = new HashMap<QName, Serializable>(newProps); if (!policyBehaviourFilter.isEnabled(node.getNodeRef(), ContentModel.ASPECT_AUDITABLE)) { if (AuditablePropertiesEntity.hasAuditableProperty(newProps.keySet())) { AuditablePropertiesEntity auditableProps = node.getAuditableProperties(); if (auditableProps == null) { auditableProps = new AuditablePropertiesEntity(); } else { auditableProps = new AuditablePropertiesEntity(auditableProps); } boolean containedAuditProperties = auditableProps.setAuditValues(null, null, newProps); if (!containedAuditProperties) { auditableProps = null; } nodeUpdate.setAuditableProperties(auditableProps); nodeUpdate.setUpdateAuditableProperties(true); } } newProps.keySet().removeAll(AuditablePropertiesEntity.getAuditablePropertyQNames()); Long oldNodeLocaleId = node.getLocaleId(); Locale newLocale = DefaultTypeConverter.INSTANCE.convert( Locale.class, newProps.get(ContentModel.PROP_LOCALE)); if (newLocale != null) { Long newNodeLocaleId = localeDAO.getOrCreateLocalePair(newLocale).getFirst(); if (!newNodeLocaleId.equals(oldNodeLocaleId)) { nodeUpdate.setLocaleId(newNodeLocaleId); nodeUpdate.setUpdateLocaleId(true); } } LocalizedPropertiesEntity.removeLocalizedProperties(node, newProps); ReferenceablePropertiesEntity.removeReferenceableProperties(node, newProps); Map<QName, Serializable> oldPropsCached = getNodePropertiesCached(nodeId); Map<QName, Serializable> oldProps = new HashMap<QName, Serializable>(oldPropsCached); if (isAddOnly) { oldProps.keySet().retainAll(newProps.keySet()); } Map<NodePropertyKey, NodePropertyValue> newPropsRaw = nodePropertyHelper.convertToPersistentProperties(newProps); newProps = nodePropertyHelper.convertToPublicProperties(newPropsRaw); Map<QName, MapValueComparison> diff = EqualsHelper.getMapComparison( oldProps, newProps); Set<QName> propsToDelete = new HashSet<QName>(oldProps.size()*2); Map<QName, Serializable> propsToAdd = new HashMap<QName, Serializable>(newProps.size() * 2); Set<QName> contentQNamesToDelete = new HashSet<QName>(5); for (Map.Entry<QName, MapValueComparison> entry : diff.entrySet()) { QName qname = entry.getKey(); PropertyDefinition removePropDef = dictionaryService.getProperty(qname); boolean isContent = (removePropDef != null && removePropDef.getDataType().getName().equals(DataTypeDefinition.CONTENT)); switch (entry.getValue()) { case EQUAL: break; case LEFT_ONLY: propsToDelete.add(qname); if (isContent) { contentQNamesToDelete.add(qname); } break; case NOT_EQUAL: propsToDelete.add(qname); if (isContent) { contentQNamesToDelete.add(qname); } case RIGHT_ONLY: Serializable value = newProps.get(qname); if (isContent && value != null) { ContentData newContentData = (ContentData) value; Long newContentDataId = contentDataDAO.createContentData(newContentData).getFirst(); value = new ContentDataWithId(newContentData, newContentDataId); } propsToAdd.put(qname, value); break; default: throw new IllegalStateException(STR + entry.getValue()); } } boolean modifyProps = propsToDelete.size() > 0 propsToAdd.size() > 0; boolean updated = modifyProps nodeUpdate.isUpdateAnything(); if (nodeUpdate.isUpdateAnything()) { if (updateNodeImpl(node, nodeUpdate, null)) { NodeVersionKey nodeVersionKey = node.getNodeVersionKey(); NodeVersionKey newNodeVersionKey = getNodeNotNull(nodeId, false).getNodeVersionKey(); copyNodeAspectsCached(nodeVersionKey, newNodeVersionKey); copyNodePropertiesCached(nodeVersionKey, newNodeVersionKey); copyParentAssocsCached(node); } } else if (modifyProps) { touchNode(nodeId, null, null, false, false, false); } if (modifyProps) { try { if (contentQNamesToDelete.size() > 0) { Set<Long> contentQNameIdsToDelete = qnameDAO.convertQNamesToIds(contentQNamesToDelete, false); contentDataDAO.deleteContentDataForNode(nodeId, contentQNameIdsToDelete); } } catch (Throwable e) { throw new AlfrescoRuntimeException( STR + STR + nodeId + "\n" + STR + contentQNamesToDelete, e); } try { Set<Long> propQNameIdsToDelete = qnameDAO.convertQNamesToIds(propsToDelete, true); deleteNodeProperties(nodeId, propQNameIdsToDelete); newPropsRaw = nodePropertyHelper.convertToPersistentProperties(propsToAdd); insertNodeProperties(nodeId, newPropsRaw); } catch (Throwable e) { invalidateNodeCaches(nodeId); throw new AlfrescoRuntimeException( STR + STR + nodeId + "\n" + STR + oldProps + "\n" + STR + newProps + "\n" + STR + diff + "\n" + STR + propsToDelete + "\n" + STR + propsToAdd, e); } Map<QName, Serializable> propsToCache = null; if (isAddOnly) { propsToCache = new HashMap<QName, Serializable>(oldPropsCached); propsToCache.putAll(propsToAdd); } else { propsToCache = newProps; propsToCache.putAll(propsToAdd); } setNodePropertiesCached(nodeId, propsToCache); } if (isDebugEnabled && updated) { logger.debug( STR + nodeId + "\n" + STR + propsToDelete + "\n" + STR + propsToAdd + "\n" + STR + nodeUpdate); } return updated; } | /**
* Does differencing to add and/or remove properties. Internally, the existing properties
* will be retrieved and a difference performed to work out which properties need to be
* created, updated or deleted.
* <p/>
* Note: The cached properties are not updated
*
* @param nodeId the node ID
* @param newProps the properties to add or update
* @param isAddOnly <tt>true</tt> if the new properties are just an update or
* <tt>false</tt> if the properties are a complete set
* @return Returns <tt>true</tt> if any properties were changed
*/ | Does differencing to add and/or remove properties. Internally, the existing properties will be retrieved and a difference performed to work out which properties need to be created, updated or deleted. Note: The cached properties are not updated | setNodePropertiesImpl | {
"repo_name": "Kast0rTr0y/community-edition",
"path": "projects/repository/source/java/org/alfresco/repo/domain/node/AbstractNodeDAOImpl.java",
"license": "lgpl-3.0",
"size": 199381
} | [
"java.io.Serializable",
"java.util.HashMap",
"java.util.HashSet",
"java.util.Locale",
"java.util.Map",
"java.util.Set",
"org.alfresco.error.AlfrescoRuntimeException",
"org.alfresco.model.ContentModel",
"org.alfresco.service.cmr.dictionary.DataTypeDefinition",
"org.alfresco.service.cmr.dictionary.PropertyDefinition",
"org.alfresco.service.cmr.repository.ContentData",
"org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter",
"org.alfresco.service.namespace.QName",
"org.alfresco.util.EqualsHelper"
] | import java.io.Serializable; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Set; import org.alfresco.error.AlfrescoRuntimeException; import org.alfresco.model.ContentModel; import org.alfresco.service.cmr.dictionary.DataTypeDefinition; import org.alfresco.service.cmr.dictionary.PropertyDefinition; import org.alfresco.service.cmr.repository.ContentData; import org.alfresco.service.cmr.repository.datatype.DefaultTypeConverter; import org.alfresco.service.namespace.QName; import org.alfresco.util.EqualsHelper; | import java.io.*; import java.util.*; import org.alfresco.error.*; import org.alfresco.model.*; import org.alfresco.service.cmr.dictionary.*; import org.alfresco.service.cmr.repository.*; import org.alfresco.service.cmr.repository.datatype.*; import org.alfresco.service.namespace.*; import org.alfresco.util.*; | [
"java.io",
"java.util",
"org.alfresco.error",
"org.alfresco.model",
"org.alfresco.service",
"org.alfresco.util"
] | java.io; java.util; org.alfresco.error; org.alfresco.model; org.alfresco.service; org.alfresco.util; | 1,402,499 |
public void cancelLease(final String leaseName) throws LeaseException {
synchronized (leaseQueue) {
Lease lease = leases.remove(leaseName);
if (lease == null) {
throw new LeaseException("lease '" + leaseName + "' does not exist");
}
leaseQueue.remove(lease);
}
}
private static class Lease implements Delayed {
private final String leaseName;
private final LeaseListener listener;
private long expirationTime;
Lease(final String leaseName, LeaseListener listener, long expirationTime) {
this.leaseName = leaseName;
this.listener = listener;
this.expirationTime = expirationTime;
} | void function(final String leaseName) throws LeaseException { synchronized (leaseQueue) { Lease lease = leases.remove(leaseName); if (lease == null) { throw new LeaseException(STR + leaseName + STR); } leaseQueue.remove(lease); } } private static class Lease implements Delayed { private final String leaseName; private final LeaseListener listener; private long expirationTime; Lease(final String leaseName, LeaseListener listener, long expirationTime) { this.leaseName = leaseName; this.listener = listener; this.expirationTime = expirationTime; } | /**
* Client explicitly cancels a lease.
*
* @param leaseName name of lease
* @throws LeaseException
*/ | Client explicitly cancels a lease | cancelLease | {
"repo_name": "adragomir/hbaseindex",
"path": "src/java/org/apache/hadoop/hbase/Leases.java",
"license": "apache-2.0",
"size": 8252
} | [
"java.util.concurrent.Delayed"
] | import java.util.concurrent.Delayed; | import java.util.concurrent.*; | [
"java.util"
] | java.util; | 1,734,738 |
public RegistrationResponse registerUser(UserRegistrationRequest request) throws ApiException {
return registerUserWithHttpInfo(request).getData();
} | RegistrationResponse function(UserRegistrationRequest request) throws ApiException { return registerUserWithHttpInfo(request).getData(); } | /**
* Register a user
*
* @param request request (required)
* @return RegistrationResponse
* @throws ApiException if fails to make API call
*/ | Register a user | registerUser | {
"repo_name": "LogSentinel/logsentinel-java-client",
"path": "src/main/java/com/logsentinel/api/PartnersApi.java",
"license": "mit",
"size": 12210
} | [
"com.logsentinel.ApiException",
"com.logsentinel.model.RegistrationResponse",
"com.logsentinel.model.UserRegistrationRequest"
] | import com.logsentinel.ApiException; import com.logsentinel.model.RegistrationResponse; import com.logsentinel.model.UserRegistrationRequest; | import com.logsentinel.*; import com.logsentinel.model.*; | [
"com.logsentinel",
"com.logsentinel.model"
] | com.logsentinel; com.logsentinel.model; | 55,176 |
@Override
protected Hashtable<String,Object> backupState() {
Hashtable<String,Object> result;
result = super.backupState();
if (m_InputToken != null)
result.put(BACKUP_INPUT, m_InputToken);
return result;
} | Hashtable<String,Object> function() { Hashtable<String,Object> result; result = super.backupState(); if (m_InputToken != null) result.put(BACKUP_INPUT, m_InputToken); return result; } | /**
* Backs up the current state of the actor before update the variables.
*
* @return the backup
*/ | Backs up the current state of the actor before update the variables | backupState | {
"repo_name": "waikato-datamining/adams-base",
"path": "adams-core/src/main/java/adams/flow/sink/ExternalSink.java",
"license": "gpl-3.0",
"size": 5841
} | [
"java.util.Hashtable"
] | import java.util.Hashtable; | import java.util.*; | [
"java.util"
] | java.util; | 569,028 |
@SystemApi(client = MODULE_LIBRARIES)
public static byte[] decode(char[] encoded) throws IllegalArgumentException {
return decode(encoded, false);
} | @SystemApi(client = MODULE_LIBRARIES) static byte[] function(char[] encoded) throws IllegalArgumentException { return decode(encoded, false); } | /**
* Decodes the provided hexadecimal sequence. Odd-length inputs are not
* allowed.
*
* @param encoded char array of hexadecimal characters to decode. Letters
* can be either uppercase or lowercase.
* @return the decoded data
* @throws IllegalArgumentException if the input is malformed
*
* @hide
*/ | Decodes the provided hexadecimal sequence. Odd-length inputs are not allowed | decode | {
"repo_name": "google/desugar_jdk_libs",
"path": "jdk11/src/libcore/luni/src/main/java/libcore/util/HexEncoding.java",
"license": "gpl-2.0",
"size": 9009
} | [
"android.annotation.SystemApi"
] | import android.annotation.SystemApi; | import android.annotation.*; | [
"android.annotation"
] | android.annotation; | 2,118,966 |
public static void writeByteArray(DataOutput out, @Nullable byte[] arr, int maxLen) throws IOException {
if (arr == null)
out.writeInt(-1);
else {
int len = Math.min(arr.length, maxLen);
out.writeInt(len);
out.write(arr, 0, len);
}
} | static void function(DataOutput out, @Nullable byte[] arr, int maxLen) throws IOException { if (arr == null) out.writeInt(-1); else { int len = Math.min(arr.length, maxLen); out.writeInt(len); out.write(arr, 0, len); } } | /**
* Writes byte array to output stream accounting for <tt>null</tt> values.
*
* @param out Output stream to write to.
* @param arr Array to write, possibly <tt>null</tt>.
* @throws java.io.IOException If write failed.
*/ | Writes byte array to output stream accounting for null values | writeByteArray | {
"repo_name": "apache/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java",
"license": "apache-2.0",
"size": 387878
} | [
"java.io.DataOutput",
"java.io.IOException",
"org.jetbrains.annotations.Nullable"
] | import java.io.DataOutput; import java.io.IOException; import org.jetbrains.annotations.Nullable; | import java.io.*; import org.jetbrains.annotations.*; | [
"java.io",
"org.jetbrains.annotations"
] | java.io; org.jetbrains.annotations; | 1,234,696 |
@Override
public ExternalId getInstrument(final Number futureOptionNumber, final Double strike, final LocalDate surfaceDate) {
ArgumentChecker.notNull(futureOptionNumber, "futureOptionNumber");
ArgumentChecker.notNull(strike, "strike");
ArgumentChecker.notNull(surfaceDate, "surface date");
final StringBuffer ticker = new StringBuffer();
ticker.append(getFutureOptionPrefix());
ticker.append(BloombergFutureUtils.getExpiryCodeForBondFutureOptions(getFutureOptionPrefix(), futureOptionNumber.intValue(), surfaceDate));
ticker.append(strike > useCallAboveStrike() ? "C " : "P ");
ticker.append(FORMATTER.format(strike));
ticker.append(" ");
ticker.append(getPostfix());
return ExternalId.of(getScheme(), ticker.toString());
} | ExternalId function(final Number futureOptionNumber, final Double strike, final LocalDate surfaceDate) { ArgumentChecker.notNull(futureOptionNumber, STR); ArgumentChecker.notNull(strike, STR); ArgumentChecker.notNull(surfaceDate, STR); final StringBuffer ticker = new StringBuffer(); ticker.append(getFutureOptionPrefix()); ticker.append(BloombergFutureUtils.getExpiryCodeForBondFutureOptions(getFutureOptionPrefix(), futureOptionNumber.intValue(), surfaceDate)); ticker.append(strike > useCallAboveStrike() ? STR : STR); ticker.append(FORMATTER.format(strike)); ticker.append(" "); ticker.append(getPostfix()); return ExternalId.of(getScheme(), ticker.toString()); } | /**
* Provides ExternalID for Bloomberg ticker, e.g. RXZ3C 100 Comdty, given a reference date and an integer offset, the n'th subsequent option The format is
* futurePrefix + month + year + callPutFlag + strike + postfix
*
* @param futureOptionNumber
* n'th future following curve date, not null
* @param strike
* option's strike, expressed as price, e.g. 100, not null
* @param surfaceDate
* date of curve validity; valuation date, not null
* @return The external id for the Bloomberg ticker
*/ | Provides ExternalID for Bloomberg ticker, e.g. RXZ3C 100 Comdty, given a reference date and an integer offset, the n'th subsequent option The format is futurePrefix + month + year + callPutFlag + strike + postfix | getInstrument | {
"repo_name": "McLeodMoores/starling",
"path": "projects/financial/src/main/java/com/opengamma/financial/analytics/volatility/surface/BloombergBondFutureOptionVolatilitySurfaceInstrumentProvider.java",
"license": "apache-2.0",
"size": 4187
} | [
"com.opengamma.id.ExternalId",
"com.opengamma.util.ArgumentChecker",
"org.threeten.bp.LocalDate"
] | import com.opengamma.id.ExternalId; import com.opengamma.util.ArgumentChecker; import org.threeten.bp.LocalDate; | import com.opengamma.id.*; import com.opengamma.util.*; import org.threeten.bp.*; | [
"com.opengamma.id",
"com.opengamma.util",
"org.threeten.bp"
] | com.opengamma.id; com.opengamma.util; org.threeten.bp; | 2,717,804 |
@Test
public void testOnAction() {
final WhereAction pq = new WhereAction();
final RPAction action = new RPAction();
action.put(Actions.TYPE, "where");
action.put(Actions.TARGET, "bob");
final Player player = PlayerTestHelper.createPlayer("bob");
final StendhalRPZone zone = new StendhalRPZone("zone");
zone.add(player);
MockStendhalRPRuleProcessor.get().addPlayer(player);
pq.onAction(player, action);
assertThat(player.events().get(0).get("text"), equalTo("You are in zone at (0,0)"));
player.clearEvents();
// test that you can still /where yourself as a ghost
player.setGhost(true);
pq.onAction(player, action);
assertThat(player.events().get(0).get("text"), equalTo("You are in zone at (0,0)"));
player.clearEvents();
// test the player before he becomes ghostmode
final Player ghosted = PlayerTestHelper.createPlayer("ghosted");
zone.add(ghosted);
MockStendhalRPRuleProcessor.get().addPlayer(ghosted);
action.put(Actions.TARGET, ghosted.getName());
pq.onAction(player, action);
assertThat(player.events().get(0).get("text"), equalTo("ghosted is in zone at (0,0)"));
player.clearEvents();
// test the player after he becomes ghostmode
ghosted.setGhost(true);
pq.onAction(player, action);
assertThat(player.events().get(0).get("text"), equalTo("No player or pet named \"ghosted\" is currently logged in."));
} | void function() { final WhereAction pq = new WhereAction(); final RPAction action = new RPAction(); action.put(Actions.TYPE, "where"); action.put(Actions.TARGET, "bob"); final Player player = PlayerTestHelper.createPlayer("bob"); final StendhalRPZone zone = new StendhalRPZone("zone"); zone.add(player); MockStendhalRPRuleProcessor.get().addPlayer(player); pq.onAction(player, action); assertThat(player.events().get(0).get("text"), equalTo(STR)); player.clearEvents(); player.setGhost(true); pq.onAction(player, action); assertThat(player.events().get(0).get("text"), equalTo(STR)); player.clearEvents(); final Player ghosted = PlayerTestHelper.createPlayer(STR); zone.add(ghosted); MockStendhalRPRuleProcessor.get().addPlayer(ghosted); action.put(Actions.TARGET, ghosted.getName()); pq.onAction(player, action); assertThat(player.events().get(0).get("text"), equalTo(STR)); player.clearEvents(); ghosted.setGhost(true); pq.onAction(player, action); assertThat(player.events().get(0).get("text"), equalTo(STRghosted\STR)); } | /**
* Tests for onAction.
*/ | Tests for onAction | testOnAction | {
"repo_name": "acsid/stendhal",
"path": "tests/games/stendhal/server/actions/query/WhereActionTest.java",
"license": "gpl-2.0",
"size": 6199
} | [
"games.stendhal.common.constants.Actions",
"games.stendhal.server.actions.query.WhereAction",
"games.stendhal.server.core.engine.StendhalRPZone",
"games.stendhal.server.entity.player.Player",
"games.stendhal.server.maps.MockStendhalRPRuleProcessor",
"org.hamcrest.core.IsEqual",
"org.junit.Assert"
] | import games.stendhal.common.constants.Actions; import games.stendhal.server.actions.query.WhereAction; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.entity.player.Player; import games.stendhal.server.maps.MockStendhalRPRuleProcessor; import org.hamcrest.core.IsEqual; import org.junit.Assert; | import games.stendhal.common.constants.*; import games.stendhal.server.actions.query.*; import games.stendhal.server.core.engine.*; import games.stendhal.server.entity.player.*; import games.stendhal.server.maps.*; import org.hamcrest.core.*; import org.junit.*; | [
"games.stendhal.common",
"games.stendhal.server",
"org.hamcrest.core",
"org.junit"
] | games.stendhal.common; games.stendhal.server; org.hamcrest.core; org.junit; | 36,249 |
protected Query parseEscapedQuery(AqpExtendedSolrQueryParser up,
String escapedUserQuery, ExtendedDismaxConfiguration config) throws SyntaxError {
Query query = up.parse(escapedUserQuery);
if (query instanceof BooleanQuery) {
BooleanQuery t = new BooleanQuery();
SolrPluginUtils.flattenBooleanQuery(t, (BooleanQuery)query);
SolrPluginUtils.setMinShouldMatch(t, config.minShouldMatch);
query = t;
}
return query;
} | Query function(AqpExtendedSolrQueryParser up, String escapedUserQuery, ExtendedDismaxConfiguration config) throws SyntaxError { Query query = up.parse(escapedUserQuery); if (query instanceof BooleanQuery) { BooleanQuery t = new BooleanQuery(); SolrPluginUtils.flattenBooleanQuery(t, (BooleanQuery)query); SolrPluginUtils.setMinShouldMatch(t, config.minShouldMatch); query = t; } return query; } | /**
* Parses an escaped version of the user's query. This method is called
* in the event that the original query encounters exceptions during parsing.
*
* @param up parser used
* @param escapedUserQuery query that is parsed, should already be escaped so that no trivial parse errors are encountered
* @param config Configuration options for this parse request
* @return the resulting query (flattened if needed) with "min should match" rules applied as specified in the config.
* @see #parseOriginalQuery
* @see SolrPluginUtils#flattenBooleanQuery
*/ | Parses an escaped version of the user's query. This method is called in the event that the original query encounters exceptions during parsing | parseEscapedQuery | {
"repo_name": "aaccomazzi/montysolr",
"path": "contrib/adsabs/src/java/org/apache/solr/search/AqpExtendedDismaxQParserPlugin.java",
"license": "gpl-2.0",
"size": 58006
} | [
"org.apache.lucene.search.BooleanQuery",
"org.apache.lucene.search.Query",
"org.apache.solr.util.SolrPluginUtils"
] | import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.apache.solr.util.SolrPluginUtils; | import org.apache.lucene.search.*; import org.apache.solr.util.*; | [
"org.apache.lucene",
"org.apache.solr"
] | org.apache.lucene; org.apache.solr; | 1,831,758 |
EOperation getTSetter__GetMemberAsString(); | EOperation getTSetter__GetMemberAsString(); | /**
* Returns the meta object for the '{@link org.eclipse.n4js.ts.types.TSetter#getMemberAsString() <em>Get Member As String</em>}' operation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the '<em>Get Member As String</em>' operation.
* @see org.eclipse.n4js.ts.types.TSetter#getMemberAsString()
* @generated
*/ | Returns the meta object for the '<code>org.eclipse.n4js.ts.types.TSetter#getMemberAsString() Get Member As String</code>' operation. | getTSetter__GetMemberAsString | {
"repo_name": "lbeurerkellner/n4js",
"path": "plugins/org.eclipse.n4js.ts.model/emf-gen/org/eclipse/n4js/ts/types/TypesPackage.java",
"license": "epl-1.0",
"size": 538237
} | [
"org.eclipse.emf.ecore.EOperation"
] | import org.eclipse.emf.ecore.EOperation; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 1,864,431 |
public void startDragOrResize(final MouseEvent e, final Point origin, boolean allowResize) {
if (getSelected() == null) {
return;
}
if (!SwingUtilities.isLeftMouseButton(e)) {
return;
}
// manual resizing is NEVER permitted for operator annotations
if (getSelected() instanceof OperatorAnnotation) {
allowResize = false;
}
ResizeDirection direction = null;
if (allowResize) {
direction = AnnotationResizeHelper.getResizeDirectionOrNull(getSelected(), origin);
}
if (direction != null) {
resized = new AnnotationResizeHelper(selected, direction, origin);
} else {
dragged = new AnnotationDragHelper(selected, origin, model);
}
} | void function(final MouseEvent e, final Point origin, boolean allowResize) { if (getSelected() == null) { return; } if (!SwingUtilities.isLeftMouseButton(e)) { return; } if (getSelected() instanceof OperatorAnnotation) { allowResize = false; } ResizeDirection direction = null; if (allowResize) { direction = AnnotationResizeHelper.getResizeDirectionOrNull(getSelected(), origin); } if (direction != null) { resized = new AnnotationResizeHelper(selected, direction, origin); } else { dragged = new AnnotationDragHelper(selected, origin, model); } } | /**
* Starts a drag or resizing of the selected annotation, depending on whether the drag starts on
* the annotation or one of the resize "knobs". If no annotation is selected, does nothing. If
* the triggering action was not a left-click, does nothing.
*
* @param e
* the mouse event triggering the drag/resize
* @param origin
* the origin of the drag/resize event
* @param allowResize
* if {@code true}, resize is allowed. Otherwise only a drag can be started
*/ | Starts a drag or resizing of the selected annotation, depending on whether the drag starts on the annotation or one of the resize "knobs". If no annotation is selected, does nothing. If the triggering action was not a left-click, does nothing | startDragOrResize | {
"repo_name": "aborg0/rapidminer-studio",
"path": "src/main/java/com/rapidminer/gui/flow/processrendering/annotations/model/AnnotationsModel.java",
"license": "agpl-3.0",
"size": 21916
} | [
"com.rapidminer.gui.flow.processrendering.annotations.model.AnnotationResizeHelper",
"java.awt.Point",
"java.awt.event.MouseEvent",
"javax.swing.SwingUtilities"
] | import com.rapidminer.gui.flow.processrendering.annotations.model.AnnotationResizeHelper; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.SwingUtilities; | import com.rapidminer.gui.flow.processrendering.annotations.model.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; | [
"com.rapidminer.gui",
"java.awt",
"javax.swing"
] | com.rapidminer.gui; java.awt; javax.swing; | 1,483,660 |
@ServiceMethod(returns = ReturnType.COLLECTION)
public PagedIterable<AfdOriginGroupInner> listByProfile(String resourceGroupName, String profileName) {
return new PagedIterable<>(listByProfileAsync(resourceGroupName, profileName));
} | @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<AfdOriginGroupInner> function(String resourceGroupName, String profileName) { return new PagedIterable<>(listByProfileAsync(resourceGroupName, profileName)); } | /**
* Lists all of the existing origin groups within a profile.
*
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param profileName Name of the Azure Front Door Standard or Azure Front Door Premium profile which is unique
* within the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return result of the request to list origin groups as paginated response with {@link PagedIterable}.
*/ | Lists all of the existing origin groups within a profile | listByProfile | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/AfdOriginGroupsClientImpl.java",
"license": "mit",
"size": 96553
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.PagedIterable",
"com.azure.resourcemanager.cdn.fluent.models.AfdOriginGroupInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedIterable; import com.azure.resourcemanager.cdn.fluent.models.AfdOriginGroupInner; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.resourcemanager.cdn.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 1,601,350 |
public Observable<ServiceResponse<Page<Product>>> getMultiplePagesWithOffsetSinglePageAsync(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions) {
if (pagingGetMultiplePagesWithOffsetOptions == null) {
throw new IllegalArgumentException("Parameter pagingGetMultiplePagesWithOffsetOptions is required and cannot be null.");
} | Observable<ServiceResponse<Page<Product>>> function(final PagingGetMultiplePagesWithOffsetOptions pagingGetMultiplePagesWithOffsetOptions) { if (pagingGetMultiplePagesWithOffsetOptions == null) { throw new IllegalArgumentException(STR); } | /**
* A paging operation that includes a nextLink that has 10 pages.
*
* @param pagingGetMultiplePagesWithOffsetOptions Additional parameters for the operation
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<Product> object wrapped in {@link ServiceResponse} if successful.
*/ | A paging operation that includes a nextLink that has 10 pages | getMultiplePagesWithOffsetSinglePageAsync | {
"repo_name": "lmazuel/autorest",
"path": "src/generator/AutoRest.Java.Azure.Tests/src/main/java/fixtures/paging/implementation/PagingsImpl.java",
"license": "mit",
"size": 189316
} | [
"com.microsoft.azure.Page",
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.azure.Page; import com.microsoft.rest.ServiceResponse; | import com.microsoft.azure.*; import com.microsoft.rest.*; | [
"com.microsoft.azure",
"com.microsoft.rest"
] | com.microsoft.azure; com.microsoft.rest; | 2,450,246 |
public Owner getS3AccountOwner() throws AmazonClientException,
AmazonServiceException; | Owner function() throws AmazonClientException, AmazonServiceException; | /**
* <p>
* Gets the current owner of the AWS account
* that the authenticated sender of the request is using.
* </p>
* <p>
* The caller <i>must</i> authenticate with a valid AWS Access Key ID that is registered
* with AWS.
* </p>
*
* @return The account of the authenticated sender
*
* @throws AmazonClientException
* If any errors are encountered in the client while making the
* request or handling the response.
* @throws AmazonServiceException
* If any errors occurred in Amazon S3 while processing the
* request.
*
* @see AmazonS3#getS3AccountOwner(GetS3AccountOwnerRequest)
*/ | Gets the current owner of the AWS account that the authenticated sender of the request is using. The caller must authenticate with a valid AWS Access Key ID that is registered with AWS. | getS3AccountOwner | {
"repo_name": "mhurne/aws-sdk-java",
"path": "aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3.java",
"license": "apache-2.0",
"size": 211153
} | [
"com.amazonaws.AmazonClientException",
"com.amazonaws.AmazonServiceException",
"com.amazonaws.services.s3.model.Owner"
] | import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.model.Owner; | import com.amazonaws.*; import com.amazonaws.services.s3.model.*; | [
"com.amazonaws",
"com.amazonaws.services"
] | com.amazonaws; com.amazonaws.services; | 2,453,435 |
@Override
public void run() {
try {
this.inputStream = client.getInputStream();
this.reader = new InputStreamReader(this.inputStream, FTPFiletype.ASCII.getCharset());
while (!inter.isClosing()) {
try {
synchronized (this.queue) {
while (this.queue.size() == 0) {
this.queue.wait();
}
}
FTPFuture future = this.queue.remove(0);
inter.setFuture(future);
future.execute();
while (!inter.isClosing() && !future.completed()) {
int read = reader.read(buffer);
int newline;
while ((newline = findNewlineIndex(buffer, read)) > -1) {
String line = new String(buffer, 0, newline);
int shift = newline + 2;
int len = buffer.length;
int threshold = len - shift;
for(int i = 0; i < len; i++)
if (i < threshold) buffer[i] = buffer[i + shift];
else buffer[i] = 0;
System.out.println(" " + line);
Matcher matcher = CONTROL_RESPONSE_PATTERN.matcher(line);
if (matcher.find()) {
int code = Integer.parseInt(matcher.group(1));
String delim = matcher.group(2);
String content = matcher.group(3);
if (delim.equals(" ")) {
FTPResponse response = new FTPResponse(code, responseBuffer.append(content).toString());
responseBuffer.setLength(0);
if (future.pushResponse(response)) break;
} else responseBuffer.append(content).append("\n");
continue;
}
responseBuffer.append(line).append("\n");
}
}
} catch (IOException e) {
// TODO: Exceptions
}
}
} catch (InterruptedException e) {
// TODO: Exceptions
} catch (IOException e) {
// TODO: Exceptions
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO: Exceptions
}
}
}
}
| void function() { try { this.inputStream = client.getInputStream(); this.reader = new InputStreamReader(this.inputStream, FTPFiletype.ASCII.getCharset()); while (!inter.isClosing()) { try { synchronized (this.queue) { while (this.queue.size() == 0) { this.queue.wait(); } } FTPFuture future = this.queue.remove(0); inter.setFuture(future); future.execute(); while (!inter.isClosing() && !future.completed()) { int read = reader.read(buffer); int newline; while ((newline = findNewlineIndex(buffer, read)) > -1) { String line = new String(buffer, 0, newline); int shift = newline + 2; int len = buffer.length; int threshold = len - shift; for(int i = 0; i < len; i++) if (i < threshold) buffer[i] = buffer[i + shift]; else buffer[i] = 0; System.out.println(" " + line); Matcher matcher = CONTROL_RESPONSE_PATTERN.matcher(line); if (matcher.find()) { int code = Integer.parseInt(matcher.group(1)); String delim = matcher.group(2); String content = matcher.group(3); if (delim.equals(" ")) { FTPResponse response = new FTPResponse(code, responseBuffer.append(content).toString()); responseBuffer.setLength(0); if (future.pushResponse(response)) break; } else responseBuffer.append(content).append("\n"); continue; } responseBuffer.append(line).append("\n"); } } } catch (IOException e) { } } } catch (InterruptedException e) { } catch (IOException e) { } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } } | /**
* Method that handles the queue logic and executes commands in order.
*/ | Method that handles the queue logic and executes commands in order | run | {
"repo_name": "hsun324/FTPLite",
"path": "src/main/java/com/hsun324/ftp/ftplite/client/FTPClientThread.java",
"license": "gpl-3.0",
"size": 4107
} | [
"com.hsun324.ftp.ftplite.FTPFile",
"com.hsun324.ftp.ftplite.FTPFuture",
"com.hsun324.ftp.ftplite.FTPResponse",
"java.io.IOException",
"java.io.InputStreamReader",
"java.util.regex.Matcher"
] | import com.hsun324.ftp.ftplite.FTPFile; import com.hsun324.ftp.ftplite.FTPFuture; import com.hsun324.ftp.ftplite.FTPResponse; import java.io.IOException; import java.io.InputStreamReader; import java.util.regex.Matcher; | import com.hsun324.ftp.ftplite.*; import java.io.*; import java.util.regex.*; | [
"com.hsun324.ftp",
"java.io",
"java.util"
] | com.hsun324.ftp; java.io; java.util; | 1,677,477 |
public void convertMaterial(File materialFile, File outputFolder,
String uuid, File logFile) throws ZipException, IOException, ExecutionException {
exploreMaterialFile(materialFile, outputFolder);
logger.info("Material Type: " + materialType);
switch (materialType) {
case MP3:
if (materialFolder.isDirectory())
materialFile = FileExtractor.findFileWithSuffix(materialFolder, "mp3");
convertMP3(materialFile, outputFolder, uuid, logFile);
break;
case MP4_LQ:
case MP4_HQ:
case MP4_HD:
if (materialFolder.isDirectory())
materialFile = FileExtractor.findFileWithSuffix(materialFolder, "mp4");
convertMP4(materialFile, outputFolder, uuid, logFile);
break;
case LPD_VIDEO_LQ:
case LPD_VIDEO_HQ:
case LPD_AUDIO:
if (materialFolder.isDirectory())
materialFile = FileExtractor.findFileWithSuffix(materialFolder, "lpd");
convertLPD(materialFile, outputFolder, uuid, logFile);
break;
case CAM_VIDEO_LQ:
case CAM_VIDEO_HQ:
case CAM_AUDIO:
convertCAM(materialFolder,outputFolder, uuid, logFile);
break;
case PDF:
if (materialFolder.isDirectory())
materialFile = FileExtractor.findFileWithSuffix(materialFolder, "pdf");
convertPDF(materialFile,outputFolder, logFile);
break;
default:
FileUtils.copyFileToDirectory(materialFile, outputFolder);
break;
}
} | void function(File materialFile, File outputFolder, String uuid, File logFile) throws ZipException, IOException, ExecutionException { exploreMaterialFile(materialFile, outputFolder); logger.info(STR + materialType); switch (materialType) { case MP3: if (materialFolder.isDirectory()) materialFile = FileExtractor.findFileWithSuffix(materialFolder, "mp3"); convertMP3(materialFile, outputFolder, uuid, logFile); break; case MP4_LQ: case MP4_HQ: case MP4_HD: if (materialFolder.isDirectory()) materialFile = FileExtractor.findFileWithSuffix(materialFolder, "mp4"); convertMP4(materialFile, outputFolder, uuid, logFile); break; case LPD_VIDEO_LQ: case LPD_VIDEO_HQ: case LPD_AUDIO: if (materialFolder.isDirectory()) materialFile = FileExtractor.findFileWithSuffix(materialFolder, "lpd"); convertLPD(materialFile, outputFolder, uuid, logFile); break; case CAM_VIDEO_LQ: case CAM_VIDEO_HQ: case CAM_AUDIO: convertCAM(materialFolder,outputFolder, uuid, logFile); break; case PDF: if (materialFolder.isDirectory()) materialFile = FileExtractor.findFileWithSuffix(materialFolder, "pdf"); convertPDF(materialFile,outputFolder, logFile); break; default: FileUtils.copyFileToDirectory(materialFile, outputFolder); break; } } | /**
* converts material
*
* @param materialFile
* @param outputFolder
* @throws ZipException
* @throws ExecutionException
* @throws IOException
*/ | converts material | convertMaterial | {
"repo_name": "olw/converter",
"path": "src/java/de/tu_darmstadt/elc/olw/api/converter/OLWConverter.java",
"license": "apache-2.0",
"size": 10132
} | [
"de.tu_darmstadt.elc.olw.api.misc.execution.ExecutionException",
"de.tu_darmstadt.elc.olw.api.misc.io.FileExtractor",
"java.io.File",
"java.io.IOException",
"java.util.zip.ZipException",
"org.apache.commons.io.FileUtils"
] | import de.tu_darmstadt.elc.olw.api.misc.execution.ExecutionException; import de.tu_darmstadt.elc.olw.api.misc.io.FileExtractor; import java.io.File; import java.io.IOException; import java.util.zip.ZipException; import org.apache.commons.io.FileUtils; | import de.tu_darmstadt.elc.olw.api.misc.execution.*; import de.tu_darmstadt.elc.olw.api.misc.io.*; import java.io.*; import java.util.zip.*; import org.apache.commons.io.*; | [
"de.tu_darmstadt.elc",
"java.io",
"java.util",
"org.apache.commons"
] | de.tu_darmstadt.elc; java.io; java.util; org.apache.commons; | 1,051,996 |
protected void addCommentPropertyDescriptor(Object object)
{
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_NamedElement_comment_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_NamedElement_comment_feature", "_UI_NamedElement_type"),
RobotPackage.Literals.NAMED_ELEMENT__COMMENT,
true,
true,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
null,
null));
}
| void function(Object object) { itemPropertyDescriptors.add (createItemPropertyDescriptor (((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(), getResourceLocator(), getString(STR), getString(STR, STR, STR), RobotPackage.Literals.NAMED_ELEMENT__COMMENT, true, true, false, ItemPropertyDescriptor.GENERIC_VALUE_IMAGE, null, null)); } | /**
* This adds a property descriptor for the Comment feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/ | This adds a property descriptor for the Comment feature. | addCommentPropertyDescriptor | {
"repo_name": "roboidstudio/embedded",
"path": "org.roboid.robot.model.edit/src/org/roboid/robot/provider/NamedElementItemProvider.java",
"license": "lgpl-2.1",
"size": 8223
} | [
"org.eclipse.emf.edit.provider.ComposeableAdapterFactory",
"org.eclipse.emf.edit.provider.ItemPropertyDescriptor",
"org.roboid.robot.RobotPackage"
] | import org.eclipse.emf.edit.provider.ComposeableAdapterFactory; import org.eclipse.emf.edit.provider.ItemPropertyDescriptor; import org.roboid.robot.RobotPackage; | import org.eclipse.emf.edit.provider.*; import org.roboid.robot.*; | [
"org.eclipse.emf",
"org.roboid.robot"
] | org.eclipse.emf; org.roboid.robot; | 1,890,103 |
public int read2LE() throws OtpErlangDecodeException {
final byte[] b = new byte[2];
try {
super.read(b);
} catch (final IOException e) {
throw new OtpErlangDecodeException("Cannot read from input stream");
}
return (b[1] << 8 & 0xff00) + (b[0] & 0xff);
} | int function() throws OtpErlangDecodeException { final byte[] b = new byte[2]; try { super.read(b); } catch (final IOException e) { throw new OtpErlangDecodeException(STR); } return (b[1] << 8 & 0xff00) + (b[0] & 0xff); } | /**
* Read a two byte little endian integer from the stream.
*
* @return the bytes read, converted from little endian to an integer.
*
* @exception OtpErlangDecodeException
* if the next byte cannot be read.
*/ | Read a two byte little endian integer from the stream | read2LE | {
"repo_name": "paulcager/otp",
"path": "lib/jinterface/java_src/com/ericsson/otp/erlang/OtpInputStream.java",
"license": "apache-2.0",
"size": 38903
} | [
"java.io.IOException"
] | import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 1,317,548 |
void buildComponent()
{
// Retrieve the preferences.
ViewerPreferences pref = ImViewerFactory.getPreferences();
if (pref != null) {
//Action a = controller.getAction(ImViewerControl.RENDERER);
//rndButton.removeActionListener(a);
rndButton.setSelected(pref.isRenderer());
//rndButton.setAction(a);
}
int compression = ImViewerFactory.getCompressionLevel();
int value = (Integer)
ImViewerAgent.getRegistry().lookup(LookupNames.IMAGE_QUALITY_LEVEL);
int setUp = view.convertCompressionLevel(value);
if (compression != setUp) compression = setUp;
if (view.isLargePlane() && value > RenderingControl.UNCOMPRESSED) {
compression = ImViewer.LOW;
}
int index = view.convertCompressionLevel();
if (compression >= UNCOMPRESSED && compression <= LOW)
index = compression;
compressionBox.setSelectedIndex(index);
compressionBox.addActionListener(
controller.getAction(ImViewerControl.COMPRESSION));
| void buildComponent() { ViewerPreferences pref = ImViewerFactory.getPreferences(); if (pref != null) { rndButton.setSelected(pref.isRenderer()); } int compression = ImViewerFactory.getCompressionLevel(); int value = (Integer) ImViewerAgent.getRegistry().lookup(LookupNames.IMAGE_QUALITY_LEVEL); int setUp = view.convertCompressionLevel(value); if (compression != setUp) compression = setUp; if (view.isLargePlane() && value > RenderingControl.UNCOMPRESSED) { compression = ImViewer.LOW; } int index = view.convertCompressionLevel(); if (compression >= UNCOMPRESSED && compression <= LOW) index = compression; compressionBox.setSelectedIndex(index); compressionBox.addActionListener( controller.getAction(ImViewerControl.COMPRESSION)); | /**
* This method should be called straight after the metadata and the
* rendering settings are loaded.
*/ | This method should be called straight after the metadata and the rendering settings are loaded | buildComponent | {
"repo_name": "simleo/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/agents/imviewer/view/ToolBar.java",
"license": "gpl-2.0",
"size": 17143
} | [
"org.openmicroscopy.shoola.agents.imviewer.ImViewerAgent",
"org.openmicroscopy.shoola.env.LookupNames",
"org.openmicroscopy.shoola.env.rnd.RenderingControl"
] | import org.openmicroscopy.shoola.agents.imviewer.ImViewerAgent; import org.openmicroscopy.shoola.env.LookupNames; import org.openmicroscopy.shoola.env.rnd.RenderingControl; | import org.openmicroscopy.shoola.agents.imviewer.*; import org.openmicroscopy.shoola.env.*; import org.openmicroscopy.shoola.env.rnd.*; | [
"org.openmicroscopy.shoola"
] | org.openmicroscopy.shoola; | 1,164,286 |
public int addBodyEndHandler(Handler<Void> handler) {
int ret = this.delegate.addBodyEndHandler(handler);
return ret;
} | int function(Handler<Void> handler) { int ret = this.delegate.addBodyEndHandler(handler); return ret; } | /**
* Add a handler that will be called just before the response body has been completely written.
* This gives you a hook where you can write any extra data to the response before it has ended when it will be too late.
* @param handler the handler
* @return the id of the handler. This can be used if you later want to remove the handler.
*/ | Add a handler that will be called just before the response body has been completely written. This gives you a hook where you can write any extra data to the response before it has ended when it will be too late | addBodyEndHandler | {
"repo_name": "javazquez/vertx-web",
"path": "src/main/generated/io/vertx/rxjava/ext/web/RoutingContext.java",
"license": "apache-2.0",
"size": 15455
} | [
"io.vertx.core.Handler"
] | import io.vertx.core.Handler; | import io.vertx.core.*; | [
"io.vertx.core"
] | io.vertx.core; | 1,600,252 |
void indexes(String command) {
QueryService qs = this.cache.getQueryService();
Collection indexes = qs.getIndexes();
StringBuffer sb = new StringBuffer();
sb.append("There are ");
sb.append(indexes.size());
sb.append(" indexes in this cache\n");
for (Iterator iter = indexes.iterator(); iter.hasNext(); ) {
Index index = (Index) iter.next();
sb.append(" ");
sb.append(index.getType());
sb.append(" index \"");
sb.append(index.getName());
sb.append(" on region ");
sb.append(index.getRegion().getFullPath());
sb.append("\n");
String expr = index.getIndexedExpression();
if (expr != null) {
sb.append(" Indexed expression: ");
sb.append(expr);
sb.append("\n");
}
String from = index.getFromClause();
if (from != null) {
sb.append(" From: ");
sb.append(from);
sb.append("\n");
}
String projection = index.getProjectionAttributes();
if (projection != null) {
sb.append(" Projection: ");
sb.append(projection);
sb.append("\n");
}
sb.append(" Statistics\n");
IndexStatistics stats = index.getStatistics();
sb.append(" ");
sb.append(stats.getTotalUses());
sb.append(" uses\n");
sb.append(" ");
sb.append(stats.getNumberOfKeys());
sb.append(" keys, ");
sb.append(stats.getNumberOfValues());
sb.append(" values\n");
sb.append(" ");
sb.append(stats.getNumUpdates());
sb.append(" updates totaling ");
sb.append(stats.getTotalUpdateTime() / 1e6);
sb.append(" ms.\n");
}
System.out.println(sb.toString());
} | void indexes(String command) { QueryService qs = this.cache.getQueryService(); Collection indexes = qs.getIndexes(); StringBuffer sb = new StringBuffer(); sb.append(STR); sb.append(indexes.size()); sb.append(STR); for (Iterator iter = indexes.iterator(); iter.hasNext(); ) { Index index = (Index) iter.next(); sb.append(" "); sb.append(index.getType()); sb.append(STRSTR on region STR\nSTR Indexed expression: STR\nSTR From: STR\nSTR Projection: STR\nSTR Statistics\nSTR STR uses\nSTR STR keys, STR values\nSTR STR updates totaling STR ms.\n"); } System.out.println(sb.toString()); } | /**
* Prints out information about all of the indexes built in the
* cache.
*/ | Prints out information about all of the indexes built in the cache | indexes | {
"repo_name": "papicella/snappy-store",
"path": "gemfire-examples/src/dist/java/cacheRunner/CacheRunner.java",
"license": "apache-2.0",
"size": 58690
} | [
"com.gemstone.gemfire.cache.query.Index",
"com.gemstone.gemfire.cache.query.QueryService",
"java.util.Collection",
"java.util.Iterator"
] | import com.gemstone.gemfire.cache.query.Index; import com.gemstone.gemfire.cache.query.QueryService; import java.util.Collection; import java.util.Iterator; | import com.gemstone.gemfire.cache.query.*; import java.util.*; | [
"com.gemstone.gemfire",
"java.util"
] | com.gemstone.gemfire; java.util; | 1,936,479 |
private void doIndent ()
throws SAXException
{
if (depth > 0) {
char[] ch = indentStep.toCharArray();
for( int i=0; i<depth; i++ )
characters(ch, 0, ch.length);
}
}
////////////////////////////////////////////////////////////////////
// Constants.
////////////////////////////////////////////////////////////////////
private final static Object SEEN_NOTHING = new Object();
private final static Object SEEN_ELEMENT = new Object();
private final static Object SEEN_DATA = new Object();
////////////////////////////////////////////////////////////////////
// Internal state.
////////////////////////////////////////////////////////////////////
private Object state = SEEN_NOTHING;
private Stack<Object> stateStack = new Stack<Object>();
private String indentStep = "";
private int depth = 0;
} | void function () throws SAXException { if (depth > 0) { char[] ch = indentStep.toCharArray(); for( int i=0; i<depth; i++ ) characters(ch, 0, ch.length); } } private final static Object SEEN_NOTHING = new Object(); private final static Object SEEN_ELEMENT = new Object(); private final static Object SEEN_DATA = new Object(); private Object state = SEEN_NOTHING; private Stack<Object> stateStack = new Stack<Object>(); private String indentStep = ""; private int depth = 0; } | /**
* Print indentation for the current level.
*
* @exception org.xml.sax.SAXException If there is an error
* writing the indentation characters, or if a filter
* further down the chain raises an exception.
*/ | Print indentation for the current level | doIndent | {
"repo_name": "samskivert/ikvm-openjdk",
"path": "build/linux-amd64/impsrc/com/sun/xml/internal/bind/marshaller/DataWriter.java",
"license": "gpl-2.0",
"size": 12086
} | [
"java.util.Stack",
"org.xml.sax.SAXException"
] | import java.util.Stack; import org.xml.sax.SAXException; | import java.util.*; import org.xml.sax.*; | [
"java.util",
"org.xml.sax"
] | java.util; org.xml.sax; | 2,608,587 |
switch (Build.DEVICE) {
case DEVICE_RPI3:
case DEVICE_RPI3BP:
return "BCM21";
case DEVICE_IMX7D_PICO:
return "GPIO6_IO14";
default:
throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE);
}
} | switch (Build.DEVICE) { case DEVICE_RPI3: case DEVICE_RPI3BP: return "BCM21"; case DEVICE_IMX7D_PICO: return STR; default: throw new IllegalStateException(STR + Build.DEVICE); } } | /**
* Return the GPIO pin with a button that will trigger the Pairing command.
*/ | Return the GPIO pin with a button that will trigger the Pairing command | getGPIOForPairing | {
"repo_name": "androidthings/sample-bluetooth-audio",
"path": "audio-sink/src/main/java/com/example/androidthings/bluetooth/audio/BoardDefaults.java",
"license": "apache-2.0",
"size": 1899
} | [
"android.os.Build"
] | import android.os.Build; | import android.os.*; | [
"android.os"
] | android.os; | 1,113,801 |
private void moveNamedFunctions(Node functionBody) {
Preconditions.checkState(
functionBody.getParent().isFunction());
Node previous = null;
Node current = functionBody.getFirstChild();
// Skip any declarations at the beginning of the function body, they
// are already in the right place.
while (current != null && NodeUtil.isFunctionDeclaration(current)) {
previous = current;
current = current.getNext();
}
// Find any remaining declarations and move them.
Node insertAfter = previous;
while (current != null) {
// Save off the next node as the current node maybe removed.
Node next = current.getNext();
if (NodeUtil.isFunctionDeclaration(current)) {
// Remove the declaration from the body.
Preconditions.checkNotNull(previous);
functionBody.removeChildAfter(previous);
// Read the function at the top of the function body (after any
// previous declarations).
insertAfter = addToFront(functionBody, current, insertAfter);
reportCodeChange("Move function declaration not at top of function");
} else {
// Update the previous only if the current node hasn't been moved.
previous = current;
}
current = next;
}
} | void function(Node functionBody) { Preconditions.checkState( functionBody.getParent().isFunction()); Node previous = null; Node current = functionBody.getFirstChild(); while (current != null && NodeUtil.isFunctionDeclaration(current)) { previous = current; current = current.getNext(); } Node insertAfter = previous; while (current != null) { Node next = current.getNext(); if (NodeUtil.isFunctionDeclaration(current)) { Preconditions.checkNotNull(previous); functionBody.removeChildAfter(previous); insertAfter = addToFront(functionBody, current, insertAfter); reportCodeChange(STR); } else { previous = current; } current = next; } } | /**
* Move all the functions that are valid at the execution of the first
* statement of the function to the beginning of the function definition.
*/ | Move all the functions that are valid at the execution of the first statement of the function to the beginning of the function definition | moveNamedFunctions | {
"repo_name": "zombiezen/cardcpx",
"path": "third_party/closure-compiler/src/com/google/javascript/jscomp/Normalize.java",
"license": "apache-2.0",
"size": 29896
} | [
"com.google.common.base.Preconditions",
"com.google.javascript.rhino.Node"
] | import com.google.common.base.Preconditions; import com.google.javascript.rhino.Node; | import com.google.common.base.*; import com.google.javascript.rhino.*; | [
"com.google.common",
"com.google.javascript"
] | com.google.common; com.google.javascript; | 524,186 |
public UUID getUUIDForCluster(ZooKeeperWatcher zkw) throws KeeperException {
return UUID.fromString(ClusterId.readClusterIdZNode(zkw));
} | UUID function(ZooKeeperWatcher zkw) throws KeeperException { return UUID.fromString(ClusterId.readClusterIdZNode(zkw)); } | /**
* Get the UUID for the provided ZK watcher. Doesn't handle any ZK exceptions
* @param zkw watcher connected to an ensemble
* @return the UUID read from zookeeper
* @throws KeeperException
*/ | Get the UUID for the provided ZK watcher. Doesn't handle any ZK exceptions | getUUIDForCluster | {
"repo_name": "zqxjjj/NobidaBase",
"path": "target/hbase-0.94.9/hbase-0.94.9/src/main/java/org/apache/hadoop/hbase/replication/ReplicationZookeeper.java",
"license": "apache-2.0",
"size": 34191
} | [
"java.util.UUID",
"org.apache.hadoop.hbase.zookeeper.ClusterId",
"org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher",
"org.apache.zookeeper.KeeperException"
] | import java.util.UUID; import org.apache.hadoop.hbase.zookeeper.ClusterId; import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher; import org.apache.zookeeper.KeeperException; | import java.util.*; import org.apache.hadoop.hbase.zookeeper.*; import org.apache.zookeeper.*; | [
"java.util",
"org.apache.hadoop",
"org.apache.zookeeper"
] | java.util; org.apache.hadoop; org.apache.zookeeper; | 1,923,764 |
private static String getExtraKeyHash(TableDefinition table, Entity entity)
{
if (table.getExtraKeyHashColumns().size() == 0)
return null;
StringBuilder extraKeyValue = new StringBuilder();
for (ColumnDefinition column : table.getExtraKeyHashColumns())
{
extraKeyValue.append(column.getSqlName());
extraKeyValue.append("=");
extraKeyValue.append(serializeValue(entity, column));
extraKeyValue.append(";");
}
return Services.Strings.getStringHash(extraKeyValue.toString());
}
| static String function(TableDefinition table, Entity entity) { if (table.getExtraKeyHashColumns().size() == 0) return null; StringBuilder extraKeyValue = new StringBuilder(); for (ColumnDefinition column : table.getExtraKeyHashColumns()) { extraKeyValue.append(column.getSqlName()); extraKeyValue.append("="); extraKeyValue.append(serializeValue(entity, column)); extraKeyValue.append(";"); } return Services.Strings.getStringHash(extraKeyValue.toString()); } | /**
* Gets the hash value associated to a specific record, according the columns that
* the table defines as being part of the 'extra key hash' set.
*/ | Gets the hash value associated to a specific record, according the columns that the table defines as being part of the 'extra key hash' set | getExtraKeyHash | {
"repo_name": "pablanco/taskManager",
"path": "Android/FlexibleClient/src/com/artech/providers/EntityDatabaseHelper.java",
"license": "gpl-2.0",
"size": 20837
} | [
"com.artech.base.model.Entity",
"com.artech.base.services.Services",
"com.artech.base.utils.Strings"
] | import com.artech.base.model.Entity; import com.artech.base.services.Services; import com.artech.base.utils.Strings; | import com.artech.base.model.*; import com.artech.base.services.*; import com.artech.base.utils.*; | [
"com.artech.base"
] | com.artech.base; | 870,339 |
public static void commitLaunchMetrics(WebContents webContents) {
for (Pair<String, Integer> item : sActivityUrls) {
nativeRecordLaunch(true, item.first, item.second, webContents);
}
for (Pair<String, Integer> item : sTabUrls) {
nativeRecordLaunch(false, item.first, item.second, webContents);
}
sActivityUrls.clear();
sTabUrls.clear();
} | static void function(WebContents webContents) { for (Pair<String, Integer> item : sActivityUrls) { nativeRecordLaunch(true, item.first, item.second, webContents); } for (Pair<String, Integer> item : sTabUrls) { nativeRecordLaunch(false, item.first, item.second, webContents); } sActivityUrls.clear(); sTabUrls.clear(); } | /**
* Calls out to native code to record URLs that have been launched via the Home screen.
* This intermediate step is necessary because Activity.onCreate() may be called when
* the native library has not yet been loaded.
* @param webContents WebContents for the current Tab.
*/ | Calls out to native code to record URLs that have been launched via the Home screen. This intermediate step is necessary because Activity.onCreate() may be called when the native library has not yet been loaded | commitLaunchMetrics | {
"repo_name": "TheTypoMaster/chromium-crosswalk",
"path": "chrome/android/java/src/org/chromium/chrome/browser/metrics/LaunchMetrics.java",
"license": "bsd-3-clause",
"size": 2673
} | [
"android.util.Pair",
"org.chromium.content_public.browser.WebContents"
] | import android.util.Pair; import org.chromium.content_public.browser.WebContents; | import android.util.*; import org.chromium.content_public.browser.*; | [
"android.util",
"org.chromium.content_public"
] | android.util; org.chromium.content_public; | 1,046,092 |
private String getSparkMaster() {
if (!sparkMaster.isPresent()) {
String master = properties.getProperty(SPARK_MASTER_KEY);
if (master == null) {
master = properties.getProperty("master");
if (master == null) {
String masterEnv = System.getenv("SPARK_MASTER");
master = (masterEnv == null ? DEFAULT_MASTER : masterEnv);
}
properties.put(SPARK_MASTER_KEY, master);
}
sparkMaster = Optional.of(master);
}
return sparkMaster.get();
} | String function() { if (!sparkMaster.isPresent()) { String master = properties.getProperty(SPARK_MASTER_KEY); if (master == null) { master = properties.getProperty(STR); if (master == null) { String masterEnv = System.getenv(STR); master = (masterEnv == null ? DEFAULT_MASTER : masterEnv); } properties.put(SPARK_MASTER_KEY, master); } sparkMaster = Optional.of(master); } return sparkMaster.get(); } | /**
* Returns cached Spark Master value if it's present, or calculate it
*
* Order to look for spark master
* 1. master in interpreter setting
* 2. spark.master interpreter setting
* 3. use local[*]
* @return Spark Master string
*/ | Returns cached Spark Master value if it's present, or calculate it Order to look for spark master 1. master in interpreter setting 2. spark.master interpreter setting 3. use local[*] | getSparkMaster | {
"repo_name": "apache/incubator-zeppelin",
"path": "zeppelin-zengine/src/main/java/org/apache/zeppelin/interpreter/launcher/SparkInterpreterLauncher.java",
"license": "apache-2.0",
"size": 17812
} | [
"java.util.Optional"
] | import java.util.Optional; | import java.util.*; | [
"java.util"
] | java.util; | 2,486,193 |
public static int findIgnoreCase(Reader in, String... findMe) throws IOException {
int[] pos = new int[findMe.length];
for (int i = 0; i < findMe.length; i++)
findMe[i] = findMe[i].toUpperCase();
while (true) {
int c = in.read();
if (c == -1)
return (-1);
if (c == -2)
continue; // Let's be compliant with HTMLReader: Skip tags
c = Character.toUpperCase(c);
for (int i = 0; i < findMe.length; i++) {
if (c == findMe[i].charAt(pos[i]))
pos[i]++;
else
pos[i] = 0;
if (pos[i] == findMe[i].length())
return (i);
}
}
}
public static long maxChars = -1;
| static int function(Reader in, String... findMe) throws IOException { int[] pos = new int[findMe.length]; for (int i = 0; i < findMe.length; i++) findMe[i] = findMe[i].toUpperCase(); while (true) { int c = in.read(); if (c == -1) return (-1); if (c == -2) continue; c = Character.toUpperCase(c); for (int i = 0; i < findMe.length; i++) { if (c == findMe[i].charAt(pos[i])) pos[i]++; else pos[i] = 0; if (pos[i] == findMe[i].length()) return (i); } } } public static long maxChars = -1; | /**
* Reads until one of the strings is found, returns its index or -1.
*
* @throws IOException
*/ | Reads until one of the strings is found, returns its index or -1 | findIgnoreCase | {
"repo_name": "thomasrebele/casie",
"path": "src/main/java/javatools/filehandlers/FileLines.java",
"license": "mpl-2.0",
"size": 12099
} | [
"java.io.IOException",
"java.io.Reader"
] | import java.io.IOException; import java.io.Reader; | import java.io.*; | [
"java.io"
] | java.io; | 1,153,431 |
public final IDataNode getDataNode(String path) {
PreCon.notNullOrEmpty(path);
String key = path.toLowerCase();
IDataNode node = _customNodes.get(key);
if (node != null)
return node;
DataPath dataPath = new DataPath("modules." + getName()).getPath(path);
node = DataStorage.get(PVStarAPI.getPlugin(), dataPath);
node.load();
_customNodes.put(key, node);
return node;
} | final IDataNode function(String path) { PreCon.notNullOrEmpty(path); String key = path.toLowerCase(); IDataNode node = _customNodes.get(key); if (node != null) return node; DataPath dataPath = new DataPath(STR + getName()).getPath(path); node = DataStorage.get(PVStarAPI.getPlugin(), dataPath); node.load(); _customNodes.put(key, node); return node; } | /**
* Get a data storage node.
*
* @param path The relative data path of the node.
*/ | Get a data storage node | getDataNode | {
"repo_name": "JCThePants/PV-StarAPI",
"path": "src/com/jcwhatever/pvs/api/modules/PVStarModule.java",
"license": "mit",
"size": 8753
} | [
"com.jcwhatever.nucleus.providers.storage.DataStorage",
"com.jcwhatever.nucleus.storage.DataPath",
"com.jcwhatever.nucleus.storage.IDataNode",
"com.jcwhatever.nucleus.utils.PreCon",
"com.jcwhatever.pvs.api.PVStarAPI"
] | import com.jcwhatever.nucleus.providers.storage.DataStorage; import com.jcwhatever.nucleus.storage.DataPath; import com.jcwhatever.nucleus.storage.IDataNode; import com.jcwhatever.nucleus.utils.PreCon; import com.jcwhatever.pvs.api.PVStarAPI; | import com.jcwhatever.nucleus.providers.storage.*; import com.jcwhatever.nucleus.storage.*; import com.jcwhatever.nucleus.utils.*; import com.jcwhatever.pvs.api.*; | [
"com.jcwhatever.nucleus",
"com.jcwhatever.pvs"
] | com.jcwhatever.nucleus; com.jcwhatever.pvs; | 427,688 |
public void actionPerformed(ActionEvent event)
{
// We only can handle strings for now.
if (key instanceof String)
{
String name = UIManager.getString(key);
InputStream stream = getClass().getResourceAsStream(name);
try
{
Clip clip = AudioSystem.getClip();
AudioInputStream audioStream =
AudioSystem.getAudioInputStream(stream);
clip.open(audioStream);
}
catch (LineUnavailableException ex)
{
// Nothing we can do about it.
}
catch (IOException ex)
{
// Nothing we can do about it.
}
catch (UnsupportedAudioFileException e)
{
// Nothing we can do about it.
}
}
}
}
static final long serialVersionUID = -6096995660290287879L;
static final String DONT_CANCEL_POPUP = "noCancelPopup";
private transient PopupHelper popupHelper;
private ActionMap audioActionMap;
public BasicLookAndFeel()
{
// Nothing to do here.
} | void function(ActionEvent event) { if (key instanceof String) { String name = UIManager.getString(key); InputStream stream = getClass().getResourceAsStream(name); try { Clip clip = AudioSystem.getClip(); AudioInputStream audioStream = AudioSystem.getAudioInputStream(stream); clip.open(audioStream); } catch (LineUnavailableException ex) { } catch (IOException ex) { } catch (UnsupportedAudioFileException e) { } } } } static final long serialVersionUID = -6096995660290287879L; static final String DONT_CANCEL_POPUP = STR; private transient PopupHelper popupHelper; private ActionMap audioActionMap; public BasicLookAndFeel() { } | /**
* Plays the sound represented by this action.
*
* @param event the action event that triggers this audio action
*/ | Plays the sound represented by this action | actionPerformed | {
"repo_name": "SanDisk-Open-Source/SSD_Dashboard",
"path": "uefi/gcc/gcc-4.6.3/libjava/classpath/javax/swing/plaf/basic/BasicLookAndFeel.java",
"license": "gpl-2.0",
"size": 87825
} | [
"java.awt.event.ActionEvent",
"java.io.IOException",
"java.io.InputStream",
"javax.sound.sampled.AudioInputStream",
"javax.sound.sampled.AudioSystem",
"javax.sound.sampled.Clip",
"javax.sound.sampled.LineUnavailableException",
"javax.sound.sampled.UnsupportedAudioFileException",
"javax.swing.ActionMap",
"javax.swing.UIManager"
] | import java.awt.event.ActionEvent; import java.io.IOException; import java.io.InputStream; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.UnsupportedAudioFileException; import javax.swing.ActionMap; import javax.swing.UIManager; | import java.awt.event.*; import java.io.*; import javax.sound.sampled.*; import javax.swing.*; | [
"java.awt",
"java.io",
"javax.sound",
"javax.swing"
] | java.awt; java.io; javax.sound; javax.swing; | 1,884,932 |
private static final void writeIntoStream(final ByteBuffer bytebuf, final FileChannel fc, final byte[] contents)
throws IOException {
final int chopSize = 6 * 1024;
if (contents.length >= bytebuf.capacity()) {
List<byte[]> chops = PnmlExport.chopBytes(contents, chopSize);
for (byte[] buf : chops) {
bytebuf.put(buf);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
} else {
bytebuf.put(contents);
bytebuf.flip();
fc.write(bytebuf);
bytebuf.clear();
}
} | static final void function(final ByteBuffer bytebuf, final FileChannel fc, final byte[] contents) throws IOException { final int chopSize = 6 * 1024; if (contents.length >= bytebuf.capacity()) { List<byte[]> chops = PnmlExport.chopBytes(contents, chopSize); for (byte[] buf : chops) { bytebuf.put(buf); bytebuf.flip(); fc.write(bytebuf); bytebuf.clear(); } } else { bytebuf.put(contents); bytebuf.flip(); fc.write(bytebuf); bytebuf.clear(); } } | /**
* Writes buffer of a given max size into file channel.
*/ | Writes buffer of a given max size into file channel | writeIntoStream | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/finiteEnumerations/impl/FiniteEnumerationImpl.java",
"license": "epl-1.0",
"size": 12202
} | [
"fr.lip6.move.pnml.framework.general.PnmlExport",
"java.io.IOException",
"java.nio.ByteBuffer",
"java.nio.channels.FileChannel",
"java.util.List"
] | import fr.lip6.move.pnml.framework.general.PnmlExport; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.List; | import fr.lip6.move.pnml.framework.general.*; import java.io.*; import java.nio.*; import java.nio.channels.*; import java.util.*; | [
"fr.lip6.move",
"java.io",
"java.nio",
"java.util"
] | fr.lip6.move; java.io; java.nio; java.util; | 275,314 |
public Observable<ServiceResponse<RoleAssignmentInner>> deleteByIdWithServiceResponseAsync(String roleAssignmentId) {
if (roleAssignmentId == null) {
throw new IllegalArgumentException("Parameter roleAssignmentId is required and cannot be null.");
}
if (this.client.apiVersion() == null) {
throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
} | Observable<ServiceResponse<RoleAssignmentInner>> function(String roleAssignmentId) { if (roleAssignmentId == null) { throw new IllegalArgumentException(STR); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException(STR); } | /**
* Deletes a role assignment.
*
* @param roleAssignmentId The ID of the role assignment to delete.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the RoleAssignmentInner object
*/ | Deletes a role assignment | deleteByIdWithServiceResponseAsync | {
"repo_name": "martinsawicki/azure-sdk-for-java",
"path": "azure-mgmt-graph-rbac/src/main/java/com/microsoft/azure/management/graphrbac/implementation/RoleAssignmentsInner.java",
"license": "mit",
"size": 130097
} | [
"com.microsoft.rest.ServiceResponse"
] | import com.microsoft.rest.ServiceResponse; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
] | com.microsoft.rest; | 918,067 |
protected void sequence_Decks(ISerializationContext context, Decks semanticObject) {
genericSequencer.createSequence(context, semanticObject);
}
| void function(ISerializationContext context, Decks semanticObject) { genericSequencer.createSequence(context, semanticObject); } | /**
* Contexts:
* Decks returns Decks
*
* Constraint:
* decks+=Deck+
*/ | Contexts: Decks returns Decks Constraint: decks+=Deck+ | sequence_Decks | {
"repo_name": "rehne93/pokemon-tcgo-deck-generator",
"path": "de.baernreuther.dsls.pkmntcgo/src-gen/de/baernreuther/dsls/serializer/PkmntcgoSemanticSequencer.java",
"license": "unlicense",
"size": 5530
} | [
"de.baernreuther.dsls.pkmntcgo.Decks",
"org.eclipse.xtext.serializer.ISerializationContext"
] | import de.baernreuther.dsls.pkmntcgo.Decks; import org.eclipse.xtext.serializer.ISerializationContext; | import de.baernreuther.dsls.pkmntcgo.*; import org.eclipse.xtext.serializer.*; | [
"de.baernreuther.dsls",
"org.eclipse.xtext"
] | de.baernreuther.dsls; org.eclipse.xtext; | 2,487,579 |
public static <T> T lookupMandatoryBean(Exchange exchange, String name, Class<T> type) {
T value = lookupBean(exchange, name, type);
if (value == null) {
throw new NoSuchBeanException(name);
}
return value;
} | static <T> T function(Exchange exchange, String name, Class<T> type) { T value = lookupBean(exchange, name, type); if (value == null) { throw new NoSuchBeanException(name); } return value; } | /**
* Performs a lookup in the registry of the mandatory bean name and throws an exception if it could not be found
*
* @param exchange the exchange
* @param name the bean name
* @param type the expected bean type
* @return the bean
* @throws NoSuchBeanException if no bean could be found in the registry
*/ | Performs a lookup in the registry of the mandatory bean name and throws an exception if it could not be found | lookupMandatoryBean | {
"repo_name": "oscerd/camel",
"path": "camel-core/src/main/java/org/apache/camel/util/ExchangeHelper.java",
"license": "apache-2.0",
"size": 35401
} | [
"org.apache.camel.Exchange",
"org.apache.camel.NoSuchBeanException"
] | import org.apache.camel.Exchange; import org.apache.camel.NoSuchBeanException; | import org.apache.camel.*; | [
"org.apache.camel"
] | org.apache.camel; | 20,309 |
@Property(DISPLAY_NAME)
void setDisplayName(String displayName); | @Property(DISPLAY_NAME) void setDisplayName(String displayName); | /**
* Contains the bean's display name
*/ | Contains the bean's display name | setDisplayName | {
"repo_name": "OndraZizka/windup",
"path": "rules-java-ee/addon/src/main/java/org/jboss/windup/rules/apps/javaee/model/EjbBeanBaseModel.java",
"license": "epl-1.0",
"size": 3722
} | [
"com.tinkerpop.frames.Property"
] | import com.tinkerpop.frames.Property; | import com.tinkerpop.frames.*; | [
"com.tinkerpop.frames"
] | com.tinkerpop.frames; | 2,668,042 |
EReference getExecutionState_EntryAction(); | EReference getExecutionState_EntryAction(); | /**
* Returns the meta object for the containment reference '{@link org.yakindu.sct.model.sexec.ExecutionState#getEntryAction <em>Entry Action</em>}'.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the containment reference '<em>Entry Action</em>'.
* @see org.yakindu.sct.model.sexec.ExecutionState#getEntryAction()
* @see #getExecutionState()
* @generated
*/ | Returns the meta object for the containment reference '<code>org.yakindu.sct.model.sexec.ExecutionState#getEntryAction Entry Action</code>'. | getExecutionState_EntryAction | {
"repo_name": "Yakindu/statecharts",
"path": "plugins/org.yakindu.sct.model.sexec/src/org/yakindu/sct/model/sexec/SexecPackage.java",
"license": "epl-1.0",
"size": 168724
} | [
"org.eclipse.emf.ecore.EReference"
] | import org.eclipse.emf.ecore.EReference; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 456,146 |
public void testSetLayout() throws Exception {
mWindow = new MockWindow(mContext);
WindowManager.LayoutParams attrs = mWindow.getAttributes();
assertEquals(WindowManager.LayoutParams.MATCH_PARENT, attrs.width);
assertEquals(WindowManager.LayoutParams.MATCH_PARENT, attrs.height);
MockWindowCallback callback = new MockWindowCallback();
mWindow.setCallback(callback);
assertFalse(callback.isOnWindowAttributesChangedCalled());
mWindow.setLayout(WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT);
attrs = mWindow.getAttributes();
assertEquals(WindowManager.LayoutParams.WRAP_CONTENT, attrs.width);
assertEquals(WindowManager.LayoutParams.WRAP_CONTENT, attrs.height);
assertTrue(callback.isOnWindowAttributesChangedCalled());
} | void function() throws Exception { mWindow = new MockWindow(mContext); WindowManager.LayoutParams attrs = mWindow.getAttributes(); assertEquals(WindowManager.LayoutParams.MATCH_PARENT, attrs.width); assertEquals(WindowManager.LayoutParams.MATCH_PARENT, attrs.height); MockWindowCallback callback = new MockWindowCallback(); mWindow.setCallback(callback); assertFalse(callback.isOnWindowAttributesChangedCalled()); mWindow.setLayout(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); attrs = mWindow.getAttributes(); assertEquals(WindowManager.LayoutParams.WRAP_CONTENT, attrs.width); assertEquals(WindowManager.LayoutParams.WRAP_CONTENT, attrs.height); assertTrue(callback.isOnWindowAttributesChangedCalled()); } | /**
* Set the width and height layout parameters of the window.
* 1.The default for both of these is MATCH_PARENT;
* 2.You can change them to WRAP_CONTENT to make a window that is not full-screen.
*/ | Set the width and height layout parameters of the window. 1.The default for both of these is MATCH_PARENT; 2.You can change them to WRAP_CONTENT to make a window that is not full-screen | testSetLayout | {
"repo_name": "rex-xxx/mt6572_x201",
"path": "cts/tests/tests/view/src/android/view/cts/WindowTest.java",
"license": "gpl-2.0",
"size": 33766
} | [
"android.view.WindowManager"
] | import android.view.WindowManager; | import android.view.*; | [
"android.view"
] | android.view; | 897,562 |
private void extendParsers( Class<?> clss ) throws IOException{
Enumeration<URL> enm = clss.getClassLoader().getResources( IFactoryBuilder.S_DEFAULT_LOCATION );
while( enm.hasMoreElements()){
URL url = enm.nextElement();
parsers.add( new ContextServiceParser( url, clss ));
}
}
private class FactoryContainer{
private Jp2pServiceDescriptor descriptor;
private Collection<IPropertySourceFactory> factories;
public FactoryContainer( Jp2pServiceDescriptor descriptor ) {
super();
this.descriptor = descriptor;
factories = new ArrayList<IPropertySourceFactory>();
}
| void function( Class<?> clss ) throws IOException{ Enumeration<URL> enm = clss.getClassLoader().getResources( IFactoryBuilder.S_DEFAULT_LOCATION ); while( enm.hasMoreElements()){ URL url = enm.nextElement(); parsers.add( new ContextServiceParser( url, clss )); } } private class FactoryContainer{ private Jp2pServiceDescriptor descriptor; private Collection<IPropertySourceFactory> factories; public FactoryContainer( Jp2pServiceDescriptor descriptor ) { super(); this.descriptor = descriptor; factories = new ArrayList<IPropertySourceFactory>(); } | /**
* Allow additional builders to extend the primary builder, by looking at resources with the
* similar name and location, for instance provided by fragments
* @param clss
* @param containerBuilder
* @throws IOException
*/ | Allow additional builders to extend the primary builder, by looking at resources with the similar name and location, for instance provided by fragments | extendParsers | {
"repo_name": "chaupal/jp2p",
"path": "Workspace/net.jp2p.builder/src/net/jp2p/builder/context/Jp2pServiceManager.java",
"license": "apache-2.0",
"size": 9091
} | [
"java.io.IOException",
"java.util.ArrayList",
"java.util.Collection",
"java.util.Enumeration",
"net.jp2p.container.builder.IFactoryBuilder",
"net.jp2p.container.context.Jp2pServiceDescriptor",
"net.jp2p.container.factory.IPropertySourceFactory"
] | import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import net.jp2p.container.builder.IFactoryBuilder; import net.jp2p.container.context.Jp2pServiceDescriptor; import net.jp2p.container.factory.IPropertySourceFactory; | import java.io.*; import java.util.*; import net.jp2p.container.builder.*; import net.jp2p.container.context.*; import net.jp2p.container.factory.*; | [
"java.io",
"java.util",
"net.jp2p.container"
] | java.io; java.util; net.jp2p.container; | 1,288,956 |
@Generated
@Selector("range")
@ByValue
public native NSRange range(); | @Selector("range") native NSRange function(); | /**
* Range to read in blocks. Valid start index range is 0x00 to 0xFF. Length shall not be 0.
*/ | Range to read in blocks. Valid start index range is 0x00 to 0xFF. Length shall not be 0 | range | {
"repo_name": "multi-os-engine/moe-core",
"path": "moe.apple/moe.platform.ios/src/main/java/apple/corenfc/NFCISO15693ReadMultipleBlocksConfiguration.java",
"license": "apache-2.0",
"size": 6510
} | [
"org.moe.natj.objc.ann.Selector"
] | import org.moe.natj.objc.ann.Selector; | import org.moe.natj.objc.ann.*; | [
"org.moe.natj"
] | org.moe.natj; | 2,539,115 |
public void init(Vector<Object> values) {
grid.add(new JLabel(Translation.getInstance().getLabel("me_42")));
grid.add(new JLabel(values.get(0).toString()));
grid.add(new JLabel(Translation.getInstance().getLabel("me_83")));
SpinnerModel spmodel = new SpinnerNumberModel(0, 0, MemorySettings.MAX_MEMSIZE, 1);
address = new JSpinner(spmodel);
JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) address.getEditor();
editor.getTextField().addFocusListener(presenter);
address.addChangeListener(this);
grid.add(address);
grid.add(new JLabel(Translation.getInstance().getLabel("me_84")));
phyAddr = new JLabel(((MemoryPresenter) presenter).getAddTransPhysical(0));
grid.add(phyAddr);
Functions.getInstance().makeCompactGrid(grid, 3, 2, 10, 10, 10, 10);
pn.add(grid);
} | void function(Vector<Object> values) { grid.add(new JLabel(Translation.getInstance().getLabel("me_42"))); grid.add(new JLabel(values.get(0).toString())); grid.add(new JLabel(Translation.getInstance().getLabel("me_83"))); SpinnerModel spmodel = new SpinnerNumberModel(0, 0, MemorySettings.MAX_MEMSIZE, 1); address = new JSpinner(spmodel); JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) address.getEditor(); editor.getTextField().addFocusListener(presenter); address.addChangeListener(this); grid.add(address); grid.add(new JLabel(Translation.getInstance().getLabel("me_84"))); phyAddr = new JLabel(((MemoryPresenter) presenter).getAddTransPhysical(0)); grid.add(phyAddr); Functions.getInstance().makeCompactGrid(grid, 3, 2, 10, 10, 10, 10); pn.add(grid); } | /**
* Creates and initialize form fields
*/ | Creates and initialize form fields | init | {
"repo_name": "kromatum/OsSim",
"path": "edu/upc/fib/ossim/memory/view/FormAddress.java",
"license": "gpl-2.0",
"size": 2598
} | [
"edu.upc.fib.ossim.memory.MemoryPresenter",
"edu.upc.fib.ossim.utils.Functions",
"edu.upc.fib.ossim.utils.Translation",
"java.util.Vector",
"javax.swing.JLabel",
"javax.swing.JSpinner",
"javax.swing.SpinnerModel",
"javax.swing.SpinnerNumberModel"
] | import edu.upc.fib.ossim.memory.MemoryPresenter; import edu.upc.fib.ossim.utils.Functions; import edu.upc.fib.ossim.utils.Translation; import java.util.Vector; import javax.swing.JLabel; import javax.swing.JSpinner; import javax.swing.SpinnerModel; import javax.swing.SpinnerNumberModel; | import edu.upc.fib.ossim.memory.*; import edu.upc.fib.ossim.utils.*; import java.util.*; import javax.swing.*; | [
"edu.upc.fib",
"java.util",
"javax.swing"
] | edu.upc.fib; java.util; javax.swing; | 1,495,075 |
@ServiceMethod(returns = ReturnType.SINGLE)
void deleteAdministrativeUnits(String administrativeUnitId); | @ServiceMethod(returns = ReturnType.SINGLE) void deleteAdministrativeUnits(String administrativeUnitId); | /**
* Delete navigation property administrativeUnits for directory.
*
* @param administrativeUnitId key: id of administrativeUnit.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.resourcemanager.authorization.fluent.models.OdataErrorMainException thrown if the request is
* rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/ | Delete navigation property administrativeUnits for directory | deleteAdministrativeUnits | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanager/azure-resourcemanager-authorization/src/main/java/com/azure/resourcemanager/authorization/fluent/DirectoriesClient.java",
"license": "mit",
"size": 34524
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; | import com.azure.core.annotation.*; | [
"com.azure.core"
] | com.azure.core; | 2,637,810 |
@Test
public void testAdd() throws Exception {
// add load
List<ListenableFuture<Integer>> futures = put(folder);
//start
taskLatch.countDown();
callbackLatch.countDown();
assertFuture(futures, 0);
assertCacheStats(stagingCache, 0, 0, 1, 1);
} | void function() throws Exception { List<ListenableFuture<Integer>> futures = put(folder); taskLatch.countDown(); callbackLatch.countDown(); assertFuture(futures, 0); assertCacheStats(stagingCache, 0, 0, 1, 1); } | /**
* Stage file successful upload.
* @throws Exception
*/ | Stage file successful upload | testAdd | {
"repo_name": "meggermo/jackrabbit-oak",
"path": "oak-core/src/test/java/org/apache/jackrabbit/oak/plugins/blob/UploadStagingCacheTest.java",
"license": "apache-2.0",
"size": 23563
} | [
"com.google.common.util.concurrent.ListenableFuture",
"java.util.List"
] | import com.google.common.util.concurrent.ListenableFuture; import java.util.List; | import com.google.common.util.concurrent.*; import java.util.*; | [
"com.google.common",
"java.util"
] | com.google.common; java.util; | 1,942,884 |
void remove(Result<Boolean> result); | void remove(Result<Boolean> result); | /**
* Deletes this file.
*/ | Deletes this file | remove | {
"repo_name": "baratine/baratine",
"path": "core/src/main/java/io/baratine/files/BfsFile.java",
"license": "gpl-2.0",
"size": 2988
} | [
"io.baratine.service.Result"
] | import io.baratine.service.Result; | import io.baratine.service.*; | [
"io.baratine.service"
] | io.baratine.service; | 1,416,847 |
protected RANode getFixture() {
return fixture;
}
| RANode function() { return fixture; } | /**
* Returns the fixture for this RA Node test case.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | Returns the fixture for this RA Node test case. | getFixture | {
"repo_name": "korpling/pepperModules-RelANNISModules",
"path": "src/test/java/de/hu_berlin/german/korpling/saltnpepper/misc/relANNIS/tests/RANodeTest.java",
"license": "apache-2.0",
"size": 15474
} | [
"de.hu_berlin.german.korpling.saltnpepper.misc.relANNIS.RANode"
] | import de.hu_berlin.german.korpling.saltnpepper.misc.relANNIS.RANode; | import de.hu_berlin.german.korpling.saltnpepper.misc.*; | [
"de.hu_berlin.german"
] | de.hu_berlin.german; | 1,696,601 |
public String discoverMimeType(ImageInputStream data) throws IOException; | String function(ImageInputStream data) throws IOException; | /**
* Get the MIME type for specified data input. This method returns the
* ImageInputStream to the position it was in before calling the method.
*
* @param data the DataInput
* @return String representing the asset mime type
*/ | Get the MIME type for specified data input. This method returns the ImageInputStream to the position it was in before calling the method | discoverMimeType | {
"repo_name": "balhoff/svg-image-reader",
"path": "src/main/java/com/volantis/synergetics/mime/MimeDiscoverer.java",
"license": "gpl-3.0",
"size": 3884
} | [
"java.io.IOException",
"javax.imageio.stream.ImageInputStream"
] | import java.io.IOException; import javax.imageio.stream.ImageInputStream; | import java.io.*; import javax.imageio.stream.*; | [
"java.io",
"javax.imageio"
] | java.io; javax.imageio; | 2,506,160 |
public Context getContext () {
return context;
} | Context function () { return context; } | /**
* Get application context.
*/ | Get application context | getContext | {
"repo_name": "Xicnet/radioflow",
"path": "app/nacionalrock/plugins/de.appplant.cordova.plugin.local-notification/src/android/notification/Notification.java",
"license": "gpl-3.0",
"size": 9428
} | [
"android.content.Context"
] | import android.content.Context; | import android.content.*; | [
"android.content"
] | android.content; | 1,118,289 |
// ~ ======================================================================
public void setJavaMailSender(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
} | void function(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } | /**
* set mail sender.
*/ | set mail sender | setJavaMailSender | {
"repo_name": "izerui/lemon",
"path": "src/main/java/com/mossle/core/mail/MailService.java",
"license": "apache-2.0",
"size": 9074
} | [
"org.springframework.mail.javamail.JavaMailSender"
] | import org.springframework.mail.javamail.JavaMailSender; | import org.springframework.mail.javamail.*; | [
"org.springframework.mail"
] | org.springframework.mail; | 976,000 |
@Generated
@Selector("mediaSelectionCriteriaForMediaCharacteristic:")
public native AVPlayerMediaSelectionCriteria mediaSelectionCriteriaForMediaCharacteristic(
String mediaCharacteristic); | @Selector(STR) native AVPlayerMediaSelectionCriteria function( String mediaCharacteristic); | /**
* mediaSelectionCriteriaForMediaCharacteristic:
* <p>
* Returns the automatic selection criteria for media that has the specified media characteristic.
*
* @param mediaCharacteristic The media characteristic for which the selection criteria is to be returned. Supported values include AVMediaCharacteristicAudible, AVMediaCharacteristicLegible, and AVMediaCharacteristicVisual.
* <p>
* This method must be invoked on the main thread/queue.
*/ | mediaSelectionCriteriaForMediaCharacteristic: Returns the automatic selection criteria for media that has the specified media characteristic | mediaSelectionCriteriaForMediaCharacteristic | {
"repo_name": "multi-os-engine/moe-core",
"path": "moe.apple/moe.platform.ios/src/main/java/apple/avfoundation/AVPlayer.java",
"license": "apache-2.0",
"size": 61892
} | [
"org.moe.natj.objc.ann.Selector"
] | import org.moe.natj.objc.ann.Selector; | import org.moe.natj.objc.ann.*; | [
"org.moe.natj"
] | org.moe.natj; | 2,354,942 |
public void updateContext() throws CoreException, IOException {
if(TomcatLauncherPlugin.getDefault().getConfigMode().equals(TomcatLauncherPlugin.SERVERXML_MODE)) {
this.updateServerXML();
} else {
this.updateContextFile();
}
} | void function() throws CoreException, IOException { if(TomcatLauncherPlugin.getDefault().getConfigMode().equals(TomcatLauncherPlugin.SERVERXML_MODE)) { this.updateServerXML(); } else { this.updateContextFile(); } } | /**
* Add or update a Context definition
*/ | Add or update a Context definition | updateContext | {
"repo_name": "dcendents/sysdeotomcat",
"path": "src/com/sysdeo/eclipse/tomcat/TomcatProject.java",
"license": "mit",
"size": 37707
} | [
"java.io.IOException",
"org.eclipse.core.runtime.CoreException"
] | import java.io.IOException; import org.eclipse.core.runtime.CoreException; | import java.io.*; import org.eclipse.core.runtime.*; | [
"java.io",
"org.eclipse.core"
] | java.io; org.eclipse.core; | 1,585,103 |
try (InputStreamReader reader = IrCoreUtils.getInputReader(urlOrFilename, charSetName)) {
return readThings(reader, multiLines);
}
} | try (InputStreamReader reader = IrCoreUtils.getInputReader(urlOrFilename, charSetName)) { return readThings(reader, multiLines); } } | /**
* Reads Ts from the file/url in the first argument.
* @param urlOrFilename
* @param charSetName name of character set.
* @param multiLines if true, successive lines are considered to belong to the same object, unless separated by empty lines.
* @return List of Ts read from the first argument.
* @throws IOException
*/ | Reads Ts from the file/url in the first argument | readThings | {
"repo_name": "bengtmartensson/IrpTransmogrifier",
"path": "src/main/java/org/harctoolbox/ircore/ThingsLineParser.java",
"license": "gpl-3.0",
"size": 5287
} | [
"java.io.InputStreamReader"
] | import java.io.InputStreamReader; | import java.io.*; | [
"java.io"
] | java.io; | 409,754 |
public BlockMatrixKey getCacheKey(long blockIdRow, long blockIdCol) {
return new BlockMatrixKey(blockIdRow, blockIdCol, uuid, getAffinityKey(blockIdRow, blockIdCol));
} | BlockMatrixKey function(long blockIdRow, long blockIdCol) { return new BlockMatrixKey(blockIdRow, blockIdCol, uuid, getAffinityKey(blockIdRow, blockIdCol)); } | /**
* Build the cache key for the given blocks id.
*
* NB: NOT cell indices.
*/ | Build the cache key for the given blocks id | getCacheKey | {
"repo_name": "ntikhonov/ignite",
"path": "modules/ml/src/main/java/org/apache/ignite/ml/math/impls/storage/matrix/BlockMatrixStorage.java",
"license": "apache-2.0",
"size": 12683
} | [
"org.apache.ignite.ml.math.distributed.keys.impl.BlockMatrixKey"
] | import org.apache.ignite.ml.math.distributed.keys.impl.BlockMatrixKey; | import org.apache.ignite.ml.math.distributed.keys.impl.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 204,660 |
EOperation getPositionPoint__IsAppropriate_checkCsp_FWD__CSP(); | EOperation getPositionPoint__IsAppropriate_checkCsp_FWD__CSP(); | /**
* Returns the meta object for the '{@link rgse.ttc17.emoflon.tgg.task2.Rules.PositionPoint#isAppropriate_checkCsp_FWD(org.moflon.tgg.language.csp.CSP) <em>Is Appropriate check Csp FWD</em>}' operation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return the meta object for the '<em>Is Appropriate check Csp FWD</em>' operation.
* @see rgse.ttc17.emoflon.tgg.task2.Rules.PositionPoint#isAppropriate_checkCsp_FWD(org.moflon.tgg.language.csp.CSP)
* @generated
*/ | Returns the meta object for the '<code>rgse.ttc17.emoflon.tgg.task2.Rules.PositionPoint#isAppropriate_checkCsp_FWD(org.moflon.tgg.language.csp.CSP) Is Appropriate check Csp FWD</code>' operation. | getPositionPoint__IsAppropriate_checkCsp_FWD__CSP | {
"repo_name": "georghinkel/ttc2017smartGrids",
"path": "solutions/eMoflon/rgse.ttc17.emoflon.tgg.task2/gen/rgse/ttc17/emoflon/tgg/task2/Rules/RulesPackage.java",
"license": "mit",
"size": 437406
} | [
"org.eclipse.emf.ecore.EOperation"
] | import org.eclipse.emf.ecore.EOperation; | import org.eclipse.emf.ecore.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,727,589 |
protected String formatTranscriptString(BuildingComponents buildingComponents) {
StringBuilder allele = new StringBuilder();
allele.append(formatPrefix(buildingComponents)); // if use_prefix else ''
allele.append(COLON);
if (buildingComponents.getKind().equals(BuildingComponents.Kind.CODING)) {
allele.append(CODING_TRANSCRIPT_CHAR).append(formatCdnaCoords(buildingComponents)
+ formatDnaAllele(buildingComponents));
} else if (buildingComponents.getKind().equals(BuildingComponents.Kind.NON_CODING)) {
allele.append(NON_CODING_TRANSCRIPT_CHAR).append(formatCdnaCoords(buildingComponents)
+ formatDnaAllele(buildingComponents));
} else {
throw new NotImplementedException("HGVS calculation not implemented for variant "
+ buildingComponents.getChromosome() + ":"
+ buildingComponents.getStart() + ":" + buildingComponents.getReferenceStart() + ":"
+ buildingComponents.getAlternate() + "; kind: " + buildingComponents.getKind());
}
return allele.toString();
} | String function(BuildingComponents buildingComponents) { StringBuilder allele = new StringBuilder(); allele.append(formatPrefix(buildingComponents)); allele.append(COLON); if (buildingComponents.getKind().equals(BuildingComponents.Kind.CODING)) { allele.append(CODING_TRANSCRIPT_CHAR).append(formatCdnaCoords(buildingComponents) + formatDnaAllele(buildingComponents)); } else if (buildingComponents.getKind().equals(BuildingComponents.Kind.NON_CODING)) { allele.append(NON_CODING_TRANSCRIPT_CHAR).append(formatCdnaCoords(buildingComponents) + formatDnaAllele(buildingComponents)); } else { throw new NotImplementedException(STR + buildingComponents.getChromosome() + ":" + buildingComponents.getStart() + ":" + buildingComponents.getReferenceStart() + ":" + buildingComponents.getAlternate() + STR + buildingComponents.getKind()); } return allele.toString(); } | /**
* Generate a transcript HGVS string.
* @param buildingComponents BuildingComponents object containing all elements needed to build the hgvs string
* @return String containing an HGVS formatted variant representation
*/ | Generate a transcript HGVS string | formatTranscriptString | {
"repo_name": "opencb/cellbase",
"path": "cellbase-lib/src/main/java/org/opencb/cellbase/lib/variant/hgvs/HgvsCalculator.java",
"license": "apache-2.0",
"size": 35386
} | [
"org.apache.commons.lang.NotImplementedException"
] | import org.apache.commons.lang.NotImplementedException; | import org.apache.commons.lang.*; | [
"org.apache.commons"
] | org.apache.commons; | 2,257,207 |
void enterPatternFilterAnnotation(@NotNull EsperEPL2GrammarParser.PatternFilterAnnotationContext ctx);
void exitPatternFilterAnnotation(@NotNull EsperEPL2GrammarParser.PatternFilterAnnotationContext ctx); | void enterPatternFilterAnnotation(@NotNull EsperEPL2GrammarParser.PatternFilterAnnotationContext ctx); void exitPatternFilterAnnotation(@NotNull EsperEPL2GrammarParser.PatternFilterAnnotationContext ctx); | /**
* Exit a parse tree produced by {@link EsperEPL2GrammarParser#patternFilterAnnotation}.
* @param ctx the parse tree
*/ | Exit a parse tree produced by <code>EsperEPL2GrammarParser#patternFilterAnnotation</code> | exitPatternFilterAnnotation | {
"repo_name": "georgenicoll/esper",
"path": "esper/src/main/java/com/espertech/esper/epl/generated/EsperEPL2GrammarListener.java",
"license": "gpl-2.0",
"size": 114105
} | [
"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; | 2,636,960 |
@Test()
public void testSetCharacterNonEmpty()
throws Exception
{
ByteStringBuffer buffer = new ByteStringBuffer().append("foo");
assertFalse(buffer.isEmpty());
assertEquals(buffer.length(), 3);
assertEquals(buffer.toString(), "foo");
buffer.set('a');
assertFalse(buffer.isEmpty());
assertEquals(buffer.length(), 1);
assertEquals(buffer.toString(), "a");
buffer.hashCode();
} | @Test() void function() throws Exception { ByteStringBuffer buffer = new ByteStringBuffer().append("foo"); assertFalse(buffer.isEmpty()); assertEquals(buffer.length(), 3); assertEquals(buffer.toString(), "foo"); buffer.set('a'); assertFalse(buffer.isEmpty()); assertEquals(buffer.length(), 1); assertEquals(buffer.toString(), "a"); buffer.hashCode(); } | /**
* Provides test coverage for the {@code set} method variant that takes a
* single character with a non-empty buffer.
*
* @throws Exception If an unexpected problem occurs.
*/ | Provides test coverage for the set method variant that takes a single character with a non-empty buffer | testSetCharacterNonEmpty | {
"repo_name": "UnboundID/ldapsdk",
"path": "tests/unit/src/com/unboundid/util/ByteStringBufferTestCase.java",
"license": "gpl-2.0",
"size": 141047
} | [
"org.testng.annotations.Test"
] | import org.testng.annotations.Test; | import org.testng.annotations.*; | [
"org.testng.annotations"
] | org.testng.annotations; | 2,813,234 |
public static List<Material> doorTypes = new ArrayList<Material>(Arrays.asList(
Material.WOODEN_DOOR, Material.IRON_DOOR_BLOCK,
Material.ACACIA_DOOR, Material.BIRCH_DOOR,
Material.DARK_OAK_DOOR, Material.JUNGLE_DOOR,
Material.SPRUCE_DOOR, Material.WOOD_DOOR));
public static Block getRealBlock(Block block){
Block b = block;
switch (block.getType()){
case CHEST:
case TRAPPED_CHEST:
if (!rm.isReinforced(block))
b = getAttachedChest(block);
if (b == null)
b = block;
break;
case WOODEN_DOOR:
case IRON_DOOR_BLOCK:
case ACACIA_DOOR:
case BIRCH_DOOR:
case DARK_OAK_DOOR:
case JUNGLE_DOOR:
case SPRUCE_DOOR:
case WOOD_DOOR:
if (!doorTypes.contains(block.getRelative(BlockFace.UP).getType()))
b = block.getRelative(BlockFace.DOWN);
break;
case BED_BLOCK:
if (((Bed) block.getState().getData()).isHeadOfBed())
b = block.getRelative(((Bed) block.getState().getData()).getFacing().getOppositeFace());
break;
default:
return block;
}
return b;
} | static List<Material> doorTypes = new ArrayList<Material>(Arrays.asList( Material.WOODEN_DOOR, Material.IRON_DOOR_BLOCK, Material.ACACIA_DOOR, Material.BIRCH_DOOR, Material.DARK_OAK_DOOR, Material.JUNGLE_DOOR, Material.SPRUCE_DOOR, Material.WOOD_DOOR)); public static Block function(Block block){ Block b = block; switch (block.getType()){ case CHEST: case TRAPPED_CHEST: if (!rm.isReinforced(block)) b = getAttachedChest(block); if (b == null) b = block; break; case WOODEN_DOOR: case IRON_DOOR_BLOCK: case ACACIA_DOOR: case BIRCH_DOOR: case DARK_OAK_DOOR: case JUNGLE_DOOR: case SPRUCE_DOOR: case WOOD_DOOR: if (!doorTypes.contains(block.getRelative(BlockFace.UP).getType())) b = block.getRelative(BlockFace.DOWN); break; case BED_BLOCK: if (((Bed) block.getState().getData()).isHeadOfBed()) b = block.getRelative(((Bed) block.getState().getData()).getFacing().getOppositeFace()); break; default: return block; } return b; } | /**
* Returns the block the Citadel is looking at, example: for beds, doors we want the bottom half.
* @param block
* @return Returns the block we want.
*/ | Returns the block the Citadel is looking at, example: for beds, doors we want the bottom half | getRealBlock | {
"repo_name": "TreeDB/Citadel",
"path": "src/vg/civcraft/mc/citadel/Utility.java",
"license": "bsd-3-clause",
"size": 24427
} | [
"java.util.ArrayList",
"java.util.Arrays",
"java.util.List",
"org.bukkit.Material",
"org.bukkit.block.Block",
"org.bukkit.block.BlockFace",
"org.bukkit.material.Bed"
] | import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.material.Bed; | import java.util.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.material.*; | [
"java.util",
"org.bukkit",
"org.bukkit.block",
"org.bukkit.material"
] | java.util; org.bukkit; org.bukkit.block; org.bukkit.material; | 2,628,566 |
default boolean canChangeOwnNickname(User user) {
return hasAnyPermission(user,
PermissionType.ADMINISTRATOR,
PermissionType.CHANGE_NICKNAME,
PermissionType.MANAGE_NICKNAMES);
} | default boolean canChangeOwnNickname(User user) { return hasAnyPermission(user, PermissionType.ADMINISTRATOR, PermissionType.CHANGE_NICKNAME, PermissionType.MANAGE_NICKNAMES); } | /**
* Checks if the given user can change its own nickname in the server.
*
* @param user The user to check.
* @return Whether the given user can change its own nickname or not.
*/ | Checks if the given user can change its own nickname in the server | canChangeOwnNickname | {
"repo_name": "BtoBastian/Javacord",
"path": "javacord-api/src/main/java/org/javacord/api/entity/server/Server.java",
"license": "lgpl-3.0",
"size": 103692
} | [
"org.javacord.api.entity.permission.PermissionType",
"org.javacord.api.entity.user.User"
] | import org.javacord.api.entity.permission.PermissionType; import org.javacord.api.entity.user.User; | import org.javacord.api.entity.permission.*; import org.javacord.api.entity.user.*; | [
"org.javacord.api"
] | org.javacord.api; | 1,044,764 |
public static Expression parseSimpleOrFallbackToConstantExpression(String str, CamelContext camelContext) {
if (StringHelper.hasStartToken(str, "simple")) {
return camelContext.resolveLanguage("simple").createExpression(str);
}
return constantExpression(str);
} | static Expression function(String str, CamelContext camelContext) { if (StringHelper.hasStartToken(str, STR)) { return camelContext.resolveLanguage(STR).createExpression(str); } return constantExpression(str); } | /**
* Returns Simple expression or fallback to Constant expression if expression str is not Simple expression.
*/ | Returns Simple expression or fallback to Constant expression if expression str is not Simple expression | parseSimpleOrFallbackToConstantExpression | {
"repo_name": "objectiser/camel",
"path": "core/camel-support/src/main/java/org/apache/camel/support/builder/ExpressionBuilder.java",
"license": "apache-2.0",
"size": 52014
} | [
"org.apache.camel.CamelContext",
"org.apache.camel.Expression",
"org.apache.camel.util.StringHelper"
] | import org.apache.camel.CamelContext; import org.apache.camel.Expression; import org.apache.camel.util.StringHelper; | import org.apache.camel.*; import org.apache.camel.util.*; | [
"org.apache.camel"
] | org.apache.camel; | 1,931,694 |
private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg,
Channel inboundChannel, AuditLogEntry logEntry) throws Exception {
String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION);
String accessToken = null;
if (auth != null) {
int spIndex = auth.trim().indexOf(' ');
if (spIndex != -1) {
accessToken = auth.substring(spIndex + 1).trim();
}
}
logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress());
logEntry.setRequestLine(msg.getMethod(), msg.getUri(), msg.getProtocolVersion());
TokenState tokenState = tokenValidator.validate(accessToken);
if (!tokenState.isValid()) {
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode());
JsonObject jsonObject = new JsonObject();
if (tokenState == TokenState.MISSING) {
httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE,
String.format("Bearer realm=\"%s\"", realm));
LOG.debug("Authentication failed due to missing token");
} else {
httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE,
String.format("Bearer realm=\"%s\" error=\"invalid_token\"" +
" error_description=\"%s\"", realm, tokenState.getMsg()));
jsonObject.addProperty("error", "invalid_token");
jsonObject.addProperty("error_description", tokenState.getMsg());
LOG.debug("Authentication failed due to invalid token, reason={};", tokenState);
}
JsonArray externalAuthenticationURIs = new JsonArray();
// Waiting for service to get discovered
stopWatchWait(externalAuthenticationURIs);
jsonObject.add("auth_uri", externalAuthenticationURIs);
ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8));
httpResponse.setContent(content);
int contentLength = content.readableBytes();
httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
logEntry.setResponseContentLength(new Long(contentLength));
ChannelFuture writeFuture = Channels.future(inboundChannel);
Channels.write(ctx, writeFuture, httpResponse);
writeFuture.addListener(ChannelFutureListener.CLOSE);
return false;
} else {
AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair =
accessTokenTransformer.transform(accessToken);
logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
msg.setHeader(HttpHeaders.Names.AUTHORIZATION,
"CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr());
msg.setHeader(Constants.Security.Headers.USER_ID,
accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
msg.setHeader(Constants.Security.Headers.USER_IP,
((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress());
return true;
}
} | boolean function(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel, AuditLogEntry logEntry) throws Exception { String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION); String accessToken = null; if (auth != null) { int spIndex = auth.trim().indexOf(' '); if (spIndex != -1) { accessToken = auth.substring(spIndex + 1).trim(); } } logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress()); logEntry.setRequestLine(msg.getMethod(), msg.getUri(), msg.getProtocolVersion()); TokenState tokenState = tokenValidator.validate(accessToken); if (!tokenState.isValid()) { HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED); logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode()); JsonObject jsonObject = new JsonObject(); if (tokenState == TokenState.MISSING) { httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format(STR%s\STRAuthentication failed due to missing token"); } else { httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format(STR%s\" error=\STRSTR error_description=\"%s\"STRerrorSTRinvalid_tokenSTRerror_descriptionSTRAuthentication failed due to invalid token, reason={};STRauth_uriSTRapplication/json;charset=UTF-8STRCDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr()); msg.setHeader(Constants.Security.Headers.USER_ID, accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername()); msg.setHeader(Constants.Security.Headers.USER_IP, ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress()); return true; } } | /**
* Intercepts the HttpMessage for getting the access token in authorization header
*
* @param ctx channel handler context delegated from MessageReceived callback
* @param msg intercepted HTTP message
* @param inboundChannel
* @return {@code true} if the HTTP message has valid Access token
* @throws Exception
*/ | Intercepts the HttpMessage for getting the access token in authorization header | validateSecuredInterception | {
"repo_name": "caskdata/cdap",
"path": "cdap-gateway/src/main/java/co/cask/cdap/gateway/router/handlers/SecurityAuthenticationHttpHandler.java",
"license": "apache-2.0",
"size": 15299
} | [
"co.cask.cdap.common.conf.Constants",
"co.cask.cdap.common.logging.AuditLogEntry",
"co.cask.cdap.security.auth.TokenState",
"com.google.gson.JsonObject",
"java.net.InetSocketAddress",
"org.jboss.netty.channel.Channel",
"org.jboss.netty.channel.ChannelHandlerContext",
"org.jboss.netty.handler.codec.http.DefaultHttpResponse",
"org.jboss.netty.handler.codec.http.HttpHeaders",
"org.jboss.netty.handler.codec.http.HttpRequest",
"org.jboss.netty.handler.codec.http.HttpResponse",
"org.jboss.netty.handler.codec.http.HttpResponseStatus",
"org.jboss.netty.handler.codec.http.HttpVersion"
] | import co.cask.cdap.common.conf.Constants; import co.cask.cdap.common.logging.AuditLogEntry; import co.cask.cdap.security.auth.TokenState; import com.google.gson.JsonObject; import java.net.InetSocketAddress; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; | import co.cask.cdap.common.conf.*; import co.cask.cdap.common.logging.*; import co.cask.cdap.security.auth.*; import com.google.gson.*; import java.net.*; import org.jboss.netty.channel.*; import org.jboss.netty.handler.codec.http.*; | [
"co.cask.cdap",
"com.google.gson",
"java.net",
"org.jboss.netty"
] | co.cask.cdap; com.google.gson; java.net; org.jboss.netty; | 2,573,463 |
public void toSystem(Point3D point, CoordinateSystem3D targetCoordinateSystem) {
if (targetCoordinateSystem!=this) {
toPivot(point);
targetCoordinateSystem.fromPivot(point);
}
} | void function(Point3D point, CoordinateSystem3D targetCoordinateSystem) { if (targetCoordinateSystem!=this) { toPivot(point); targetCoordinateSystem.fromPivot(point); } } | /** Convert the specified point into from the current coordinate system
* to the specified coordinate system.
*
* @param point is the point to convert
* @param targetCoordinateSystem is the target coordinate system.
*/ | Convert the specified point into from the current coordinate system to the specified coordinate system | toSystem | {
"repo_name": "gallandarakhneorg/afc",
"path": "core/maths/mathgeom/tobeincluded/src/coordinatesystem/CoordinateSystem3D.java",
"license": "apache-2.0",
"size": 36244
} | [
"org.arakhne.afc.math.geometry.d3.Point3D"
] | import org.arakhne.afc.math.geometry.d3.Point3D; | import org.arakhne.afc.math.geometry.d3.*; | [
"org.arakhne.afc"
] | org.arakhne.afc; | 2,520,268 |
ResponseCodeHandler getHandler(int code);
| ResponseCodeHandler getHandler(int code); | /**
* Returns the handler that matches the given code.
*
* @param code HTTP numeric esponse code.
*
* @return The associated {@link ResponseCodeHandler} or {@code null} if none.
*/ | Returns the handler that matches the given code | getHandler | {
"repo_name": "jasondevj/hotpotato",
"path": "src/main/java/com/biasedbit/hotpotato/session/HttpSession.java",
"license": "apache-2.0",
"size": 9500
} | [
"com.biasedbit.hotpotato.session.handler.ResponseCodeHandler"
] | import com.biasedbit.hotpotato.session.handler.ResponseCodeHandler; | import com.biasedbit.hotpotato.session.handler.*; | [
"com.biasedbit.hotpotato"
] | com.biasedbit.hotpotato; | 2,203,437 |
@Input @Optional
public String getBottom() {
return bottom;
} | @Input String function() { return bottom; } | /**
* Returns the HTML text to appear in the bottom text for each page.
*/ | Returns the HTML text to appear in the bottom text for each page | getBottom | {
"repo_name": "HenryHarper/Acquire-Reboot",
"path": "gradle/src/scala/org/gradle/api/tasks/scala/ScalaDocOptions.java",
"license": "mit",
"size": 5538
} | [
"org.gradle.api.tasks.Input"
] | import org.gradle.api.tasks.Input; | import org.gradle.api.tasks.*; | [
"org.gradle.api"
] | org.gradle.api; | 50,758 |
public List<GenPolynomial<C>> coPrime(List<GenPolynomial<C>> A) {
if (A == null || A.isEmpty()) {
return A;
}
List<GenPolynomial<C>> B = new ArrayList<GenPolynomial<C>>(A.size());
// make a coprime to rest of list
GenPolynomial<C> a = A.get(0);
//System.out.println("a = " + a);
if (!a.isZERO() && !a.isConstant()) {
for (int i = 1; i < A.size(); i++) {
GenPolynomial<C> b = A.get(i);
GenPolynomial<C> g = gcd(a, b).abs();
if (!g.isONE()) {
a = PolyUtil.<C> basePseudoDivide(a, g);
b = PolyUtil.<C> basePseudoDivide(b, g);
GenPolynomial<C> gp = gcd(a, g).abs();
while (!gp.isONE()) {
a = PolyUtil.<C> basePseudoDivide(a, gp);
g = PolyUtil.<C> basePseudoDivide(g, gp);
B.add(g); // gcd(a,g) == 1
g = gp;
gp = gcd(a, gp).abs();
}
if (!g.isZERO() && !g.isConstant() ) {
B.add(g); // gcd(a,g) == 1
}
}
if (!b.isZERO() && !b.isConstant()) {
B.add(b); // gcd(a,b) == 1
}
}
} else {
B.addAll(A.subList(1, A.size()));
}
// make rest coprime
B = coPrime(B);
//System.out.println("B = " + B);
if (!a.isZERO() && !a.isConstant() ) {
a = a.abs();
B.add(a);
}
return B;
} | List<GenPolynomial<C>> function(List<GenPolynomial<C>> A) { if (A == null A.isEmpty()) { return A; } List<GenPolynomial<C>> B = new ArrayList<GenPolynomial<C>>(A.size()); GenPolynomial<C> a = A.get(0); if (!a.isZERO() && !a.isConstant()) { for (int i = 1; i < A.size(); i++) { GenPolynomial<C> b = A.get(i); GenPolynomial<C> g = gcd(a, b).abs(); if (!g.isONE()) { a = PolyUtil.<C> basePseudoDivide(a, g); b = PolyUtil.<C> basePseudoDivide(b, g); GenPolynomial<C> gp = gcd(a, g).abs(); while (!gp.isONE()) { a = PolyUtil.<C> basePseudoDivide(a, gp); g = PolyUtil.<C> basePseudoDivide(g, gp); B.add(g); g = gp; gp = gcd(a, gp).abs(); } if (!g.isZERO() && !g.isConstant() ) { B.add(g); } } if (!b.isZERO() && !b.isConstant()) { B.add(b); } } } else { B.addAll(A.subList(1, A.size())); } B = coPrime(B); if (!a.isZERO() && !a.isConstant() ) { a = a.abs(); B.add(a); } return B; } | /**
* GenPolynomial co-prime list.
* @param A list of GenPolynomials.
* @return B with gcd(b,c) = 1 for all b != c in B and for all non-constant
* a in A there exists b in B with b|a. B does not contain zero or
* constant polynomials.
*/ | GenPolynomial co-prime list | coPrime | {
"repo_name": "breandan/java-algebra-system",
"path": "src/edu/jas/ufd/GreatestCommonDivisorAbstract.java",
"license": "gpl-2.0",
"size": 36942
} | [
"edu.jas.poly.GenPolynomial",
"edu.jas.poly.PolyUtil",
"java.util.ArrayList",
"java.util.List"
] | import edu.jas.poly.GenPolynomial; import edu.jas.poly.PolyUtil; import java.util.ArrayList; import java.util.List; | import edu.jas.poly.*; import java.util.*; | [
"edu.jas.poly",
"java.util"
] | edu.jas.poly; java.util; | 347,829 |
@Override
public ResultSetMetaData getMetaData() throws SQLException {
throw new SQLException("not supported");
} | ResultSetMetaData function() throws SQLException { throw new SQLException(STR); } | /**
* Dynamic MetaData used to dynamically bind a function.
*
* Metadata
*/ | Dynamic MetaData used to dynamically bind a function. Metadata | getMetaData | {
"repo_name": "splicemachine/splice-community-sample-code",
"path": "tutorial-iot-stream-predict/splicemachine/src/main/java/com/splicemachine/tutorials/vti/ArrayListOfStringVTI.java",
"license": "apache-2.0",
"size": 6875
} | [
"java.sql.ResultSetMetaData",
"java.sql.SQLException"
] | import java.sql.ResultSetMetaData; import java.sql.SQLException; | import java.sql.*; | [
"java.sql"
] | java.sql; | 1,179,392 |
public static void ensureNoProhibitedStringInLogFiles(final String[] prohibited, final String[] whitelisted) {
File cwd = new File("target/" + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY));
Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to exist", cwd.exists());
Assert.assertTrue("Expecting directory " + cwd.getAbsolutePath() + " to be a directory", cwd.isDirectory()); | static void function(final String[] prohibited, final String[] whitelisted) { File cwd = new File(STR + YARN_CONFIGURATION.get(TEST_CLUSTER_NAME_KEY)); Assert.assertTrue(STR + cwd.getAbsolutePath() + STR, cwd.exists()); Assert.assertTrue(STR + cwd.getAbsolutePath() + STR, cwd.isDirectory()); | /**
* This method checks the written TaskManager and JobManager log files
* for exceptions.
*
* <p>WARN: Please make sure the tool doesn't find old logfiles from previous test runs.
* So always run "mvn clean" before running the tests here.
*
*/ | This method checks the written TaskManager and JobManager log files for exceptions. So always run "mvn clean" before running the tests here | ensureNoProhibitedStringInLogFiles | {
"repo_name": "WangTaoTheTonic/flink",
"path": "flink-yarn-tests/src/test/java/org/apache/flink/yarn/YarnTestBase.java",
"license": "apache-2.0",
"size": 27304
} | [
"java.io.File",
"org.junit.Assert"
] | import java.io.File; import org.junit.Assert; | import java.io.*; import org.junit.*; | [
"java.io",
"org.junit"
] | java.io; org.junit; | 966,078 |
protected void safelyDeleteAll( final ObjectId[] ids ) throws Exception {
Exception firstException = null;
List<String> frozenIds = new ArrayList<String>();
for ( ObjectId id : ids ) {
frozenIds.add( id.getId() );
}
List<String> remainingIds = new ArrayList<String>();
for ( ObjectId id : ids ) {
remainingIds.add( id.getId() );
}
try {
for ( int i = 0; i < frozenIds.size(); i++ ) {
repo.deleteFile( frozenIds.get( i ), true, null );
remainingIds.remove( frozenIds.get( i ) );
}
} catch ( Exception e ) {
e.printStackTrace();
}
if ( !remainingIds.isEmpty() ) {
List<String> frozenIds2 = remainingIds;
List<String> remainingIds2 = new ArrayList<String>();
for ( String id : frozenIds2 ) {
remainingIds2.add( id );
}
try {
for ( int i = 0; i < frozenIds2.size(); i++ ) {
repo.deleteFile( frozenIds2.get( i ), true, null );
remainingIds2.remove( frozenIds2.get( i ) );
}
} catch ( Exception e ) {
if ( firstException == null ) {
firstException = e;
}
}
if ( !remainingIds2.isEmpty() ) {
throw firstException;
}
}
} | void function( final ObjectId[] ids ) throws Exception { Exception firstException = null; List<String> frozenIds = new ArrayList<String>(); for ( ObjectId id : ids ) { frozenIds.add( id.getId() ); } List<String> remainingIds = new ArrayList<String>(); for ( ObjectId id : ids ) { remainingIds.add( id.getId() ); } try { for ( int i = 0; i < frozenIds.size(); i++ ) { repo.deleteFile( frozenIds.get( i ), true, null ); remainingIds.remove( frozenIds.get( i ) ); } } catch ( Exception e ) { e.printStackTrace(); } if ( !remainingIds.isEmpty() ) { List<String> frozenIds2 = remainingIds; List<String> remainingIds2 = new ArrayList<String>(); for ( String id : frozenIds2 ) { remainingIds2.add( id ); } try { for ( int i = 0; i < frozenIds2.size(); i++ ) { repo.deleteFile( frozenIds2.get( i ), true, null ); remainingIds2.remove( frozenIds2.get( i ) ); } } catch ( Exception e ) { if ( firstException == null ) { firstException = e; } } if ( !remainingIds2.isEmpty() ) { throw firstException; } } } | /**
* Tries twice to delete files. By not failing outright on the first pass, we hopefully eliminate files that are
* holding references to the files we cannot delete.
*/ | Tries twice to delete files. By not failing outright on the first pass, we hopefully eliminate files that are holding references to the files we cannot delete | safelyDeleteAll | {
"repo_name": "TatsianaKasiankova/pentaho-kettle",
"path": "plugins/pur/core/src/test/java/org/pentaho/di/ui/repository/pur/repositoryexplorer/model/UIEERepositoryDirectoryIT.java",
"license": "apache-2.0",
"size": 33027
} | [
"java.util.ArrayList",
"java.util.List",
"org.pentaho.di.repository.ObjectId"
] | import java.util.ArrayList; import java.util.List; import org.pentaho.di.repository.ObjectId; | import java.util.*; import org.pentaho.di.repository.*; | [
"java.util",
"org.pentaho.di"
] | java.util; org.pentaho.di; | 1,279,627 |
public View getView() {
return mContentView;
} | View function() { return mContentView; } | /**
* Returns the content view of the overflow.
*/ | Returns the content view of the overflow | getView | {
"repo_name": "OmniEvo/android_frameworks_base",
"path": "core/java/com/android/internal/widget/FloatingToolbar.java",
"license": "gpl-3.0",
"size": 65171
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 238,887 |
@SynchronizedRpcRequest
void destroySession(CmsUUID sessionId, AsyncCallback<Void> callback); | void destroySession(CmsUUID sessionId, AsyncCallback<Void> callback); | /**
* Destroys a session.<p>
*
* @param sessionId the id of the session to destroy
*
* @param callback if something goes wrong
*/ | Destroys a session | destroySession | {
"repo_name": "mediaworx/opencms-core",
"path": "src/org/opencms/ugc/shared/rpc/I_CmsUgcEditServiceAsync.java",
"license": "lgpl-2.1",
"size": 3993
} | [
"com.google.gwt.user.client.rpc.AsyncCallback",
"org.opencms.util.CmsUUID"
] | import com.google.gwt.user.client.rpc.AsyncCallback; import org.opencms.util.CmsUUID; | import com.google.gwt.user.client.rpc.*; import org.opencms.util.*; | [
"com.google.gwt",
"org.opencms.util"
] | com.google.gwt; org.opencms.util; | 570,397 |
void enterVars(@NotNull jazzikParser.VarsContext ctx);
void exitVars(@NotNull jazzikParser.VarsContext ctx); | void enterVars(@NotNull jazzikParser.VarsContext ctx); void exitVars(@NotNull jazzikParser.VarsContext ctx); | /**
* Exit a parse tree produced by {@link jazzikParser#Vars}.
* @param ctx the parse tree
*/ | Exit a parse tree produced by <code>jazzikParser#Vars</code> | exitVars | {
"repo_name": "petersch/jazzik",
"path": "src/parser/jazzikListener.java",
"license": "gpl-3.0",
"size": 16952
} | [
"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; | 872,379 |
@Aspect(advice = org.support.project.ormapping.transaction.Transaction.class)
public WebhooksEntity update(Integer user, WebhooksEntity entity) {
WebhooksEntity db = selectOnKey(entity.getWebhookId());
entity.setInsertUser(db.getInsertUser());
entity.setInsertDatetime(db.getInsertDatetime());
entity.setDeleteFlag(db.getDeleteFlag());
entity.setUpdateUser(user);
entity.setUpdateDatetime(new Timestamp(DateUtils.now().getTime()));
return physicalUpdate(entity);
} | @Aspect(advice = org.support.project.ormapping.transaction.Transaction.class) WebhooksEntity function(Integer user, WebhooksEntity entity) { WebhooksEntity db = selectOnKey(entity.getWebhookId()); entity.setInsertUser(db.getInsertUser()); entity.setInsertDatetime(db.getInsertDatetime()); entity.setDeleteFlag(db.getDeleteFlag()); entity.setUpdateUser(user); entity.setUpdateDatetime(new Timestamp(DateUtils.now().getTime())); return physicalUpdate(entity); } | /**
* Update.
* set saved user id.
* @param user saved userid
* @param entity entity
* @return saved entity
*/ | Update. set saved user id | update | {
"repo_name": "support-project/knowledge",
"path": "src/main/java/org/support/project/knowledge/dao/gen/GenWebhooksDao.java",
"license": "apache-2.0",
"size": 16205
} | [
"java.sql.Timestamp",
"org.support.project.aop.Aspect",
"org.support.project.common.util.DateUtils",
"org.support.project.knowledge.entity.WebhooksEntity"
] | import java.sql.Timestamp; import org.support.project.aop.Aspect; import org.support.project.common.util.DateUtils; import org.support.project.knowledge.entity.WebhooksEntity; | import java.sql.*; import org.support.project.aop.*; import org.support.project.common.util.*; import org.support.project.knowledge.entity.*; | [
"java.sql",
"org.support.project"
] | java.sql; org.support.project; | 2,476,454 |
@javax.annotation.Nullable
@ApiModelProperty(
value = "Reason is a brief machine readable explanation for the condition's last transition.")
public String getReason() {
return reason;
} | @javax.annotation.Nullable @ApiModelProperty( value = STR) String function() { return reason; } | /**
* Reason is a brief machine readable explanation for the condition's last transition.
*
* @return reason
*/ | Reason is a brief machine readable explanation for the condition's last transition | getReason | {
"repo_name": "kubernetes-client/java",
"path": "client-java-contrib/cert-manager/src/main/java/io/cert/manager/models/V1beta1CertificateRequestStatusConditions.java",
"license": "apache-2.0",
"size": 7979
} | [
"io.swagger.annotations.ApiModelProperty"
] | import io.swagger.annotations.ApiModelProperty; | import io.swagger.annotations.*; | [
"io.swagger.annotations"
] | io.swagger.annotations; | 127,004 |
protected static Schema validateAndConvert(Schema avroSchema, ResourceFieldSchema pigSchema) throws IOException {
AvroStorageLog.details("Validate pig field schema:" + pigSchema);
if (!isCompatible(avroSchema, pigSchema))
throw new IOException("Schemas are not compatible.\n Avro=" + avroSchema + "\n" + "Pig=" + pigSchema);
final byte pigType = pigSchema.getType();
if (avroSchema.getType().equals(Schema.Type.UNION)) {
AvroStorageLog.details("Validate Pig schema with Avro union:" + avroSchema);
List<Schema> unionSchemas = avroSchema.getTypes();
for (Schema schema : unionSchemas) {
try {
@SuppressWarnings("unused")
Schema s = validateAndConvert(schema, pigSchema);
return avroSchema;
} catch (IOException e) {
// ignore the unmatched one
}
}
throw new IOException("pig schema " + pigSchema + " is not compatible with avro " + avroSchema);
} else if (pigType == DataType.TUPLE) {
AvroStorageLog.details("Validate a pig tuple: " + pigSchema);
ResourceFieldSchema[] pigFields = pigSchema.getSchema().getFields();
Schema outSchema = validateAndConvertRecord(avroSchema, pigFields);
return outSchema;
} else if (pigType == DataType.BAG) {
AvroStorageLog.details("Validate a pig bag:" + pigSchema);
ResourceFieldSchema[] fs = pigSchema.getSchema().getFields();
if (fs == null || fs.length != 1 || fs[0].getType() != DataType.TUPLE)
throw new IOException("Expect one tuple field in a bag");
Schema inElemSchema = avroSchema.getElementType();
Schema outSchema = Schema.createArray(validateAndConvert(inElemSchema, fs[0]));
return outSchema;
} else if (pigType == DataType.MAP) {
AvroStorageLog.details("Cannot validate a pig map. Will use user defined Avro schema.");
return avroSchema;
} else if (pigType == DataType.UNKNOWN || pigType == DataType.CHARARRAY
|| pigType == DataType.BIGCHARARRAY
|| pigType == DataType.BOOLEAN
|| pigType == DataType.BYTE
|| pigType == DataType.BYTEARRAY
|| pigType == DataType.DOUBLE
|| pigType == DataType.FLOAT
|| pigType == DataType.INTEGER
|| pigType == DataType.LONG) {
AvroStorageLog.details("Validate a pig primitive type:" + pigSchema);
return avroSchema;
} else
throw new IOException("Unsupported pig type:" + DataType.findTypeName(pigType));
} | static Schema function(Schema avroSchema, ResourceFieldSchema pigSchema) throws IOException { AvroStorageLog.details(STR + pigSchema); if (!isCompatible(avroSchema, pigSchema)) throw new IOException(STR + avroSchema + "\n" + "Pig=" + pigSchema); final byte pigType = pigSchema.getType(); if (avroSchema.getType().equals(Schema.Type.UNION)) { AvroStorageLog.details(STR + avroSchema); List<Schema> unionSchemas = avroSchema.getTypes(); for (Schema schema : unionSchemas) { try { @SuppressWarnings(STR) Schema s = validateAndConvert(schema, pigSchema); return avroSchema; } catch (IOException e) { } } throw new IOException(STR + pigSchema + STR + avroSchema); } else if (pigType == DataType.TUPLE) { AvroStorageLog.details(STR + pigSchema); ResourceFieldSchema[] pigFields = pigSchema.getSchema().getFields(); Schema outSchema = validateAndConvertRecord(avroSchema, pigFields); return outSchema; } else if (pigType == DataType.BAG) { AvroStorageLog.details(STR + pigSchema); ResourceFieldSchema[] fs = pigSchema.getSchema().getFields(); if (fs == null fs.length != 1 fs[0].getType() != DataType.TUPLE) throw new IOException(STR); Schema inElemSchema = avroSchema.getElementType(); Schema outSchema = Schema.createArray(validateAndConvert(inElemSchema, fs[0])); return outSchema; } else if (pigType == DataType.MAP) { AvroStorageLog.details(STR); return avroSchema; } else if (pigType == DataType.UNKNOWN pigType == DataType.CHARARRAY pigType == DataType.BIGCHARARRAY pigType == DataType.BOOLEAN pigType == DataType.BYTE pigType == DataType.BYTEARRAY pigType == DataType.DOUBLE pigType == DataType.FLOAT pigType == DataType.INTEGER pigType == DataType.LONG) { AvroStorageLog.details(STR + pigSchema); return avroSchema; } else throw new IOException(STR + DataType.findTypeName(pigType)); } | /**
* Validate whether pigSchema is compatible with avroSchema and convert
* those Pig fields with to corresponding Avro schemas.
*/ | Validate whether pigSchema is compatible with avroSchema and convert those Pig fields with to corresponding Avro schemas | validateAndConvert | {
"repo_name": "aglne/Cubert",
"path": "src/main/java/com/linkedin/cubert/pig/piggybank/storage/avro/PigSchema2Avro.java",
"license": "apache-2.0",
"size": 17900
} | [
"java.io.IOException",
"java.util.List",
"org.apache.avro.Schema",
"org.apache.pig.ResourceSchema",
"org.apache.pig.data.DataType"
] | import java.io.IOException; import java.util.List; import org.apache.avro.Schema; import org.apache.pig.ResourceSchema; import org.apache.pig.data.DataType; | import java.io.*; import java.util.*; import org.apache.avro.*; import org.apache.pig.*; import org.apache.pig.data.*; | [
"java.io",
"java.util",
"org.apache.avro",
"org.apache.pig"
] | java.io; java.util; org.apache.avro; org.apache.pig; | 1,001,162 |
protected boolean isActiveWalPath(Path p) {
return !AbstractFSWALProvider.isArchivedLogFile(p);
} | boolean function(Path p) { return !AbstractFSWALProvider.isArchivedLogFile(p); } | /**
* Check if a given path is belongs to active WAL directory
* @param p path
* @return true, if yes
*/ | Check if a given path is belongs to active WAL directory | isActiveWalPath | {
"repo_name": "vincentpoon/hbase",
"path": "hbase-backup/src/main/java/org/apache/hadoop/hbase/backup/impl/IncrementalTableBackupClient.java",
"license": "apache-2.0",
"size": 16095
} | [
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.hbase.wal.AbstractFSWALProvider"
] | import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.wal.AbstractFSWALProvider; | import org.apache.hadoop.fs.*; import org.apache.hadoop.hbase.wal.*; | [
"org.apache.hadoop"
] | org.apache.hadoop; | 519,164 |
Objects.requireNonNull(credential, "'credential' cannot be null.");
Objects.requireNonNull(profile, "'profile' cannot be null.");
return configure().authenticate(credential, profile);
} | Objects.requireNonNull(credential, STR); Objects.requireNonNull(profile, STR); return configure().authenticate(credential, profile); } | /**
* Creates an instance of BatchAI service API entry point.
*
* @param credential the credential to use.
* @param profile the Azure profile for client.
* @return the BatchAI service API instance.
*/ | Creates an instance of BatchAI service API entry point | authenticate | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/batchai/azure-resourcemanager-batchai/src/main/java/com/azure/resourcemanager/batchai/BatchAIManager.java",
"license": "mit",
"size": 11406
} | [
"java.util.Objects"
] | import java.util.Objects; | import java.util.*; | [
"java.util"
] | java.util; | 1,868,033 |
public interface ITreeState extends Serializable
{
void addTreeStateListener(ITreeStateListener l); | interface ITreeState extends Serializable { void function(ITreeStateListener l); | /**
* Adds a tree state listener. On state change events on the listener are fired.
*
* @param l
* Listener to add
*/ | Adds a tree state listener. On state change events on the listener are fired | addTreeStateListener | {
"repo_name": "afiantara/apache-wicket-1.5.7",
"path": "src/wicket-core/src/main/java/org/apache/wicket/markup/html/tree/ITreeState.java",
"license": "apache-2.0",
"size": 3361
} | [
"java.io.Serializable"
] | import java.io.Serializable; | import java.io.*; | [
"java.io"
] | java.io; | 2,631,905 |
private void kick() {
try {
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("Begun kick() in " + group.getPeerGroupID());
}
// Use seed strategy. (it has its own throttling and resource limiting).
seed();
// refresh ourself to a peer in our view
PeerViewElement refreshee = refreshRecipientStrategy.next();
if ((refreshee != null) && (self != refreshee)) {
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("Refresh " + refreshee);
}
send(refreshee, self, false, false);
}
if (!rdvService.isRendezVous()) {
return;
}
// now share an adv from our local view to another peer from our
// local view.
PeerViewElement recipient = kickRecipientStrategy.next();
if (recipient == null) {
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("No recipient to send adv ");
}
return;
}
PeerViewElement rpve = kickAdvertisementStrategy.next();
if (rpve == null) {
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("No adv to send");
}
return;
}
if (rpve.equals(recipient) || self.equals(recipient)) {
// give up: no point in sending a peer its own adv
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("adv to send is same as recipient: Nothing to do.");
}
return;
}
if (LOG.isEnabledFor(Level.DEBUG)) {
LOG.debug("Sending adv " + rpve + " to " + recipient);
}
send(recipient, rpve, true, false);
} finally {
rescheduleKick(false);
}
} | void function() { try { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR + group.getPeerGroupID()); } seed(); PeerViewElement refreshee = refreshRecipientStrategy.next(); if ((refreshee != null) && (self != refreshee)) { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR + refreshee); } send(refreshee, self, false, false); } if (!rdvService.isRendezVous()) { return; } PeerViewElement recipient = kickRecipientStrategy.next(); if (recipient == null) { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR); } return; } PeerViewElement rpve = kickAdvertisementStrategy.next(); if (rpve == null) { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR); } return; } if (rpve.equals(recipient) self.equals(recipient)) { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR); } return; } if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug(STR + rpve + STR + recipient); } send(recipient, rpve, true, false); } finally { rescheduleKick(false); } } | /**
* Invoked by the Timer thread to cause each PeerView to initiate
* a Peer Advertisement exchange.
*/ | Invoked by the Timer thread to cause each PeerView to initiate a Peer Advertisement exchange | kick | {
"repo_name": "idega/net.jxta",
"path": "src/java/net/jxta/impl/rendezvous/rpv/PeerView.java",
"license": "gpl-3.0",
"size": 97289
} | [
"org.apache.log4j.Level"
] | import org.apache.log4j.Level; | import org.apache.log4j.*; | [
"org.apache.log4j"
] | org.apache.log4j; | 1,072,219 |
public static void advertiseHeaders(HttpServletResponse rsp) {
Jenkins j = Jenkins.getInstanceOrNull();
if (j!=null) {
rsp.setHeader("X-Hudson","1.395");
rsp.setHeader("X-Jenkins", Jenkins.VERSION);
rsp.setHeader("X-Jenkins-Session", Jenkins.SESSION_HASH);
TcpSlaveAgentListener tal = j.tcpSlaveAgentListener;
if (tal !=null) {
int p = tal.getAdvertisedPort();
rsp.setIntHeader("X-Hudson-CLI-Port", p);
rsp.setIntHeader("X-Jenkins-CLI-Port", p);
rsp.setIntHeader("X-Jenkins-CLI2-Port", p);
rsp.setHeader("X-Jenkins-CLI-Host", TcpSlaveAgentListener.CLI_HOST_NAME);
}
}
} | static void function(HttpServletResponse rsp) { Jenkins j = Jenkins.getInstanceOrNull(); if (j!=null) { rsp.setHeader(STR,"1.395"); rsp.setHeader(STR, Jenkins.VERSION); rsp.setHeader(STR, Jenkins.SESSION_HASH); TcpSlaveAgentListener tal = j.tcpSlaveAgentListener; if (tal !=null) { int p = tal.getAdvertisedPort(); rsp.setIntHeader(STR, p); rsp.setIntHeader(STR, p); rsp.setIntHeader(STR, p); rsp.setHeader(STR, TcpSlaveAgentListener.CLI_HOST_NAME); } } } | /**
* Advertises the minimum set of HTTP headers that assist programmatic
* discovery of Jenkins.
*/ | Advertises the minimum set of HTTP headers that assist programmatic discovery of Jenkins | advertiseHeaders | {
"repo_name": "ajshastri/jenkins",
"path": "core/src/main/java/hudson/Functions.java",
"license": "mit",
"size": 74762
} | [
"javax.servlet.http.HttpServletResponse"
] | import javax.servlet.http.HttpServletResponse; | import javax.servlet.http.*; | [
"javax.servlet"
] | javax.servlet; | 142,993 |
public void setTags(String[] tags)
{
this.services.getTaggingService().setTags(this.nodeRef, Arrays.asList(tags));
updateTagProperty();
} | void function(String[] tags) { this.services.getTaggingService().setTags(this.nodeRef, Arrays.asList(tags)); updateTagProperty(); } | /**
* Set the tags applied to this node. This overwirtes the list of tags currently applied to the
* node.
*
* @param tags array of tags
*/ | Set the tags applied to this node. This overwirtes the list of tags currently applied to the node | setTags | {
"repo_name": "nguyentienlong/community-edition",
"path": "projects/repository/source/java/org/alfresco/repo/jscript/ScriptNode.java",
"license": "lgpl-3.0",
"size": 153865
} | [
"java.util.Arrays"
] | import java.util.Arrays; | import java.util.*; | [
"java.util"
] | java.util; | 1,281,860 |
public RepositoryConnection getAndCheckRepositoryConnection() throws RepositoryResourceNoConnectionException {
if (_repoConnection == null) {
// In order to have an ID then we should have already been stored so we should have a connection but just in case...
throw new RepositoryResourceNoConnectionException("No connection has been specified for the resource when attemping to communicte with the repository", getId());
}
return _repoConnection;
} | RepositoryConnection function() throws RepositoryResourceNoConnectionException { if (_repoConnection == null) { throw new RepositoryResourceNoConnectionException(STR, getId()); } return _repoConnection; } | /**
* Gets the connection associated with the connection and throws a RepositoryResourceNoConnectionException
* if no connection has been specified
*
* @return The connection associated with this resource
* @throws RepositoryResourceNoConnectionException If no connection has been specified
*/ | Gets the connection associated with the connection and throws a RepositoryResourceNoConnectionException if no connection has been specified | getAndCheckRepositoryConnection | {
"repo_name": "OpenLiberty/open-liberty",
"path": "dev/com.ibm.ws.repository/src/com/ibm/ws/repository/resources/internal/RepositoryResourceImpl.java",
"license": "epl-1.0",
"size": 79962
} | [
"com.ibm.ws.repository.connections.RepositoryConnection",
"com.ibm.ws.repository.exceptions.RepositoryResourceNoConnectionException"
] | import com.ibm.ws.repository.connections.RepositoryConnection; import com.ibm.ws.repository.exceptions.RepositoryResourceNoConnectionException; | import com.ibm.ws.repository.connections.*; import com.ibm.ws.repository.exceptions.*; | [
"com.ibm.ws"
] | com.ibm.ws; | 335,110 |
@VisibleForTesting
static void unregister(SpanExporter spanExporter) {
spanExporter.unregisterHandler(REGISTER_NAME);
} | static void unregister(SpanExporter spanExporter) { spanExporter.unregisterHandler(REGISTER_NAME); } | /**
* Unregisters the {@code OcAgentTraceExporterHandler}.
*
* @param spanExporter the instance of the {@code SpanExporter} from where this service is
* unregistered.
*/ | Unregisters the OcAgentTraceExporterHandler | unregister | {
"repo_name": "bogdandrutu/opencensus-java",
"path": "exporters/trace/ocagent/src/main/java/io/opencensus/exporter/trace/ocagent/OcAgentTraceExporter.java",
"license": "apache-2.0",
"size": 3917
} | [
"io.opencensus.trace.export.SpanExporter"
] | import io.opencensus.trace.export.SpanExporter; | import io.opencensus.trace.export.*; | [
"io.opencensus.trace"
] | io.opencensus.trace; | 2,116,601 |
IObject createObject(SecurityContext ctx, IObject object)
throws DSOutOfServiceException, DSAccessException
{
return createObject(ctx, object, null);
} | IObject createObject(SecurityContext ctx, IObject object) throws DSOutOfServiceException, DSAccessException { return createObject(ctx, object, null); } | /**
* Creates the specified object.
*
* @param ctx The security context.
* @param object The object to create.
* @param options Options to create the data.
* @return See above.
* @throws DSOutOfServiceException If the connection is broken, or logged in
* @throws DSAccessException If an error occurred while trying to
* retrieve data from OMERO service.
* @see IPojos#createDataObject(IObject, Map)
*/ | Creates the specified object | createObject | {
"repo_name": "jballanc/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/env/data/OMEROGateway.java",
"license": "gpl-2.0",
"size": 286379
} | [
"org.openmicroscopy.shoola.env.data.util.SecurityContext"
] | import org.openmicroscopy.shoola.env.data.util.SecurityContext; | import org.openmicroscopy.shoola.env.data.util.*; | [
"org.openmicroscopy.shoola"
] | org.openmicroscopy.shoola; | 2,598,130 |
@Override
public Object visit(final QualifiedName node) {
final List ids = node.getIdentifiers();
final IdentifierToken t = (IdentifierToken) ids.get(0);
if (this.context.isDefinedVariable(t.image()) || fieldExists(ClassInfoCompiler.this.classInfo, t.image())) {
// The name starts with a reference to a local variable,
// the end of the name is a sequence of field access
Expression result = null;
if (this.context.isDefinedVariable(t.image())) {
if (ids.size() == 1) {
final ClassInfo c = (ClassInfo) this.context.get(t.image());
node.setProperty(NodeProperties.TYPE, c);
return null;
}
final List l = new LinkedList();
l.add(t);
result = new QualifiedName(l);
} else {
result = new StaticFieldAccess(new ReferenceType(ClassInfoCompiler.this.classInfo.getName()), t.image());
}
final Iterator it = ids.iterator();
it.next();
IdentifierToken t2;
while (it.hasNext()) {
result = new ObjectFieldAccess(result, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn());
}
result.acceptVisitor(this);
return result;
}
// The name must be, or starts with, a class name
final List l = (List) ((LinkedList) ids).clone();
boolean b = false;
while (l.size() > 0) {
final String s = TreeUtilities.listToName(l);
try {
ClassInfoCompiler.this.classFinder.lookupClass(s, ClassInfoCompiler.this.classInfo);
b = true;
break;
} catch (final ClassNotFoundException e) {
}
l.remove(l.size() - 1);
}
if (!b) {
// It is an error if no matching class or field was found
node.setProperty(NodeProperties.ERROR_STRINGS, new String[] { t.image() });
throw new ExecutionError("undefined.class", node);
}
// Creates a ReferenceType node
IdentifierToken t2 = (IdentifierToken) l.get(l.size() - 1);
final ReferenceType rt = new ReferenceType(l, node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn());
if (l.size() != ids.size()) {
// The end of the name is a sequence of field access
final ListIterator it = ids.listIterator(l.size());
Expression result = new StaticFieldAccess(rt, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn());
while (it.hasNext()) {
result = new ObjectFieldAccess(result, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn());
}
result.acceptVisitor(this);
return result;
} else {
rt.acceptVisitor(this);
return rt;
}
}
| Object function(final QualifiedName node) { final List ids = node.getIdentifiers(); final IdentifierToken t = (IdentifierToken) ids.get(0); if (this.context.isDefinedVariable(t.image()) fieldExists(ClassInfoCompiler.this.classInfo, t.image())) { Expression result = null; if (this.context.isDefinedVariable(t.image())) { if (ids.size() == 1) { final ClassInfo c = (ClassInfo) this.context.get(t.image()); node.setProperty(NodeProperties.TYPE, c); return null; } final List l = new LinkedList(); l.add(t); result = new QualifiedName(l); } else { result = new StaticFieldAccess(new ReferenceType(ClassInfoCompiler.this.classInfo.getName()), t.image()); } final Iterator it = ids.iterator(); it.next(); IdentifierToken t2; while (it.hasNext()) { result = new ObjectFieldAccess(result, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn()); } result.acceptVisitor(this); return result; } final List l = (List) ((LinkedList) ids).clone(); boolean b = false; while (l.size() > 0) { final String s = TreeUtilities.listToName(l); try { ClassInfoCompiler.this.classFinder.lookupClass(s, ClassInfoCompiler.this.classInfo); b = true; break; } catch (final ClassNotFoundException e) { } l.remove(l.size() - 1); } if (!b) { node.setProperty(NodeProperties.ERROR_STRINGS, new String[] { t.image() }); throw new ExecutionError(STR, node); } IdentifierToken t2 = (IdentifierToken) l.get(l.size() - 1); final ReferenceType rt = new ReferenceType(l, node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn()); if (l.size() != ids.size()) { final ListIterator it = ids.listIterator(l.size()); Expression result = new StaticFieldAccess(rt, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn()); while (it.hasNext()) { result = new ObjectFieldAccess(result, (t2 = (IdentifierToken) it.next()).image(), node.getFilename(), t.beginLine(), t.beginColumn(), t2.endLine(), t2.endColumn()); } result.acceptVisitor(this); return result; } else { rt.acceptVisitor(this); return rt; } } | /**
* Visits a QualifiedName
*
* @param node the node to visit
* @return a node that depends of the meaning of this name. It could be : a QualifiedName, a
* ReferenceType or a FieldAccess.
*/ | Visits a QualifiedName | visit | {
"repo_name": "mbshopM/openconcerto",
"path": "OpenConcerto/src/koala/dynamicjava/interpreter/ClassInfoCompiler.java",
"license": "gpl-3.0",
"size": 77727
} | [
"java.util.Iterator",
"java.util.LinkedList",
"java.util.List",
"java.util.ListIterator"
] | import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; | import java.util.*; | [
"java.util"
] | java.util; | 1,163,634 |
public DateTime getNow() {
return this.now;
} | DateTime function() { return this.now; } | /**
* Get the now value.
*
* @return the now value
*/ | Get the now value | getNow | {
"repo_name": "matt-gibbs/AutoRest",
"path": "AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/DatetimeWrapper.java",
"license": "mit",
"size": 1229
} | [
"org.joda.time.DateTime"
] | import org.joda.time.DateTime; | import org.joda.time.*; | [
"org.joda.time"
] | org.joda.time; | 1,343,508 |
@SuppressWarnings("resource")
public static CSVParser parse(final InputStream inputStream, final Charset charset, final CSVFormat format)
throws IOException {
Objects.requireNonNull(inputStream, "inputStream");
Objects.requireNonNull(format, "format");
return parse(new InputStreamReader(inputStream, charset), format);
} | @SuppressWarnings(STR) static CSVParser function(final InputStream inputStream, final Charset charset, final CSVFormat format) throws IOException { Objects.requireNonNull(inputStream, STR); Objects.requireNonNull(format, STR); return parse(new InputStreamReader(inputStream, charset), format); } | /**
* Creates a CSV parser using the given {@link CSVFormat}.
*
* <p>
* If you do not read all records from the given {@code reader}, you should call {@link #close()} on the parser,
* unless you close the {@code reader}.
* </p>
*
* @param inputStream
* an InputStream containing CSV-formatted input. Must not be null.
* @param charset
* The Charset to decode the given file.
* @param format
* the CSVFormat used for CSV parsing. Must not be null.
* @return a new CSVParser configured with the given reader and format.
* @throws IllegalArgumentException
* If the parameters of the format are inconsistent or if either reader or format are null.
* @throws IOException
* If there is a problem reading the header or skipping the first record
* @since 1.5
*/ | Creates a CSV parser using the given <code>CSVFormat</code>. If you do not read all records from the given reader, you should call <code>#close()</code> on the parser, unless you close the reader. | parse | {
"repo_name": "apache/commons-csv",
"path": "src/main/java/org/apache/commons/csv/CSVParser.java",
"license": "apache-2.0",
"size": 27146
} | [
"java.io.IOException",
"java.io.InputStream",
"java.io.InputStreamReader",
"java.nio.charset.Charset",
"java.util.Objects"
] | import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.Objects; | import java.io.*; import java.nio.charset.*; import java.util.*; | [
"java.io",
"java.nio",
"java.util"
] | java.io; java.nio; java.util; | 2,350,592 |
protected Map<String, String> getParams() throws AuthFailureError {
return null;
} | Map<String, String> function() throws AuthFailureError { return null; } | /**
* Returns a Map of parameters to be used for a POST or PUT request. Can throw
* {@link AuthFailureError} as authentication may be required to provide these values.
*
* <p>Note that you can directly override {@link #getBody()} for custom data.</p>
*
* @throws AuthFailureError in the event of auth failure
*/ | Returns a Map of parameters to be used for a POST or PUT request. Can throw <code>AuthFailureError</code> as authentication may be required to provide these values. Note that you can directly override <code>#getBody()</code> for custom data | getParams | {
"repo_name": "tooskagroup/test",
"path": "TMessagesProj/src/main/java/com/panahit/telegramma/volley/Request.java",
"license": "gpl-2.0",
"size": 19146
} | [
"java.util.Map"
] | import java.util.Map; | import java.util.*; | [
"java.util"
] | java.util; | 2,313,419 |
public static CSharp4PreProcessor tokenizeStream(CharStream stream) throws TransformationException {
if (stream == null) {
throw new IllegalArgumentException("Stream is null");
}
CSharp4PreProcessor lexer = new CSharp4PreProcessor(stream);
if (lexer.failed()) {
throw new TransformationException(
"Lexer has failed, stream could not be tokenized.");
}
return lexer;
}
| static CSharp4PreProcessor function(CharStream stream) throws TransformationException { if (stream == null) { throw new IllegalArgumentException(STR); } CSharp4PreProcessor lexer = new CSharp4PreProcessor(stream); if (lexer.failed()) { throw new TransformationException( STR); } return lexer; } | /**
* Instantiates {@link CSharp4PreProcessor} on provided stream - it will
* try to tokenize the input.
* @param stream string stream which should be tokenized
* @return lexer
* @throws TransformationException
*/ | Instantiates <code>CSharp4PreProcessor</code> on provided stream - it will try to tokenize the input | tokenizeStream | {
"repo_name": "formanek/CesTa",
"path": "src/org/cesta/util/antlr/csharp/ANTLRCSharpHelper.java",
"license": "bsd-3-clause",
"size": 4792
} | [
"org.antlr.runtime.CharStream",
"org.cesta.parsers.csharp.generated.CSharp4PreProcessor",
"org.cesta.trans.TransformationException"
] | import org.antlr.runtime.CharStream; import org.cesta.parsers.csharp.generated.CSharp4PreProcessor; import org.cesta.trans.TransformationException; | import org.antlr.runtime.*; import org.cesta.parsers.csharp.generated.*; import org.cesta.trans.*; | [
"org.antlr.runtime",
"org.cesta.parsers",
"org.cesta.trans"
] | org.antlr.runtime; org.cesta.parsers; org.cesta.trans; | 2,789,002 |
public static Map<String, Column> getMapId(Class classe) throws AnalyzeException {
Analyzer(classe);
Map<String, Column> resultMap = new HashMap();
String id = _entitys.get(classe.getName()).id;
resultMap.put(id, (Column) _entitys.get(classe.getName()).attributes.get(id));
return resultMap;
} | static Map<String, Column> function(Class classe) throws AnalyzeException { Analyzer(classe); Map<String, Column> resultMap = new HashMap(); String id = _entitys.get(classe.getName()).id; resultMap.put(id, (Column) _entitys.get(classe.getName()).attributes.get(id)); return resultMap; } | /**
* E feita a analize da classe e em seguida retornado um Map com os dados do
* atributo marcado com a annotation
*
* @Id
* @param classe classe a ser analizada
* @return Map com o nome do atributo e um column com os dados do mesmo.
* @throws AnalyzeException Caso ocorra algum erro.
*/ | E feita a analize da classe e em seguida retornado um Map com os dados do atributo marcado com a annotation | getMapId | {
"repo_name": "pxrg/SqlBuilder",
"path": "SQLBuilder/src/com/analyzer/AnalyzerClass.java",
"license": "gpl-3.0",
"size": 19137
} | [
"com.annotations.Column",
"com.exceptions.AnalyzeException",
"java.util.HashMap",
"java.util.Map"
] | import com.annotations.Column; import com.exceptions.AnalyzeException; import java.util.HashMap; import java.util.Map; | import com.annotations.*; import com.exceptions.*; import java.util.*; | [
"com.annotations",
"com.exceptions",
"java.util"
] | com.annotations; com.exceptions; java.util; | 2,125,218 |
public static boolean dateIsValid( org.hisp.dhis.calendar.Calendar calendar, String dateString )
{
Matcher matcher = DEFAULT_DATE_REGEX_PATTERN.matcher( dateString );
if ( !matcher.matches() )
{
return false;
}
DateTimeUnit dateTime = new DateTimeUnit(
Integer.valueOf( matcher.group( "year" ) ),
Integer.valueOf( matcher.group( "month" ) ),
Integer.valueOf( matcher.group( "day" ) )
);
return calendar.isValid( dateTime );
}
| static boolean function( org.hisp.dhis.calendar.Calendar calendar, String dateString ) { Matcher matcher = DEFAULT_DATE_REGEX_PATTERN.matcher( dateString ); if ( !matcher.matches() ) { return false; } DateTimeUnit dateTime = new DateTimeUnit( Integer.valueOf( matcher.group( "year" ) ), Integer.valueOf( matcher.group( "month" ) ), Integer.valueOf( matcher.group( "day" ) ) ); return calendar.isValid( dateTime ); } | /**
* This method checks whether the String inDate is a valid date following
* the format "yyyy-MM-dd".
*
* @param calendar Calendar to be used
* @param dateString the string to be checked.
* @return true/false depending on whether the string is a date according to the format "yyyy-MM-dd".
*/ | This method checks whether the String inDate is a valid date following the format "yyyy-MM-dd" | dateIsValid | {
"repo_name": "troyel/dhis2-core",
"path": "dhis-2/dhis-support/dhis-support-system/src/main/java/org/hisp/dhis/system/util/DateUtils.java",
"license": "bsd-3-clause",
"size": 24563
} | [
"java.util.Calendar",
"java.util.regex.Matcher",
"org.hisp.dhis.calendar.DateTimeUnit"
] | import java.util.Calendar; import java.util.regex.Matcher; import org.hisp.dhis.calendar.DateTimeUnit; | import java.util.*; import java.util.regex.*; import org.hisp.dhis.calendar.*; | [
"java.util",
"org.hisp.dhis"
] | java.util; org.hisp.dhis; | 1,371,245 |
static NeutronEndpointBuilder openstackNeutron(String path) {
class NeutronEndpointBuilderImpl extends AbstractEndpointBuilder implements NeutronEndpointBuilder, AdvancedNeutronEndpointBuilder {
public NeutronEndpointBuilderImpl(String path) {
super("openstack-neutron", path);
}
}
return new NeutronEndpointBuilderImpl(path);
} | static NeutronEndpointBuilder openstackNeutron(String path) { class NeutronEndpointBuilderImpl extends AbstractEndpointBuilder implements NeutronEndpointBuilder, AdvancedNeutronEndpointBuilder { public NeutronEndpointBuilderImpl(String path) { super(STR, path); } } return new NeutronEndpointBuilderImpl(path); } | /**
* OpenStack Neutron (camel-openstack)
* The openstack-neutron component allows messages to be sent to an
* OpenStack network services.
*
* Category: cloud,paas
* Since: 2.19
* Maven coordinates: org.apache.camel:camel-openstack
*
* Syntax: <code>openstack-neutron:host</code>
*
* Path parameter: host (required)
* OpenStack host url
*/ | OpenStack Neutron (camel-openstack) The openstack-neutron component allows messages to be sent to an OpenStack network services. Category: cloud,paas Since: 2.19 Maven coordinates: org.apache.camel:camel-openstack Syntax: <code>openstack-neutron:host</code> Path parameter: host (required) OpenStack host url | openstackNeutron | {
"repo_name": "ullgren/camel",
"path": "core/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/NeutronEndpointBuilderFactory.java",
"license": "apache-2.0",
"size": 10685
} | [
"org.apache.camel.builder.endpoint.AbstractEndpointBuilder"
] | import org.apache.camel.builder.endpoint.AbstractEndpointBuilder; | import org.apache.camel.builder.endpoint.*; | [
"org.apache.camel"
] | org.apache.camel; | 1,804,611 |
@SuppressWarnings("all")
public static void unhookMethod(final Member hookMethod, final XC_MethodHook callback) {
final AdditionalHookInfo additionalInfo = sHookedMethodInfos.get(hookMethod);
if (additionalInfo != null) {
additionalInfo.callbacks.remove(callback);
}
} | @SuppressWarnings("all") static void function(final Member hookMethod, final XC_MethodHook callback) { final AdditionalHookInfo additionalInfo = sHookedMethodInfos.get(hookMethod); if (additionalInfo != null) { additionalInfo.callbacks.remove(callback); } } | /**
* Removes the callback for a hooked method/constructor.
*
* @param hookMethod The method for which the callback should be removed.
* @param callback The reference to the callback as specified in {@link #hookMethod}.
*/ | Removes the callback for a hooked method/constructor | unhookMethod | {
"repo_name": "rrrfff/AndHook",
"path": "lib/src/main/java/andhook/lib/xposed/XposedBridge.java",
"license": "mit",
"size": 14426
} | [
"java.lang.reflect.Member"
] | import java.lang.reflect.Member; | import java.lang.reflect.*; | [
"java.lang"
] | java.lang; | 500,023 |
public RowSet findRowSet( String from, int fromcopy, String to, int tocopy ) {
// Start with the transformation.
for ( int i = 0; i < rowsets.size(); i++ ) {
RowSet rs = rowsets.get( i );
if ( rs.getOriginStepName().equalsIgnoreCase( from )
&& rs.getDestinationStepName().equalsIgnoreCase( to ) && rs.getOriginStepCopy() == fromcopy
&& rs.getDestinationStepCopy() == tocopy ) {
return rs;
}
}
return null;
} | RowSet function( String from, int fromcopy, String to, int tocopy ) { for ( int i = 0; i < rowsets.size(); i++ ) { RowSet rs = rowsets.get( i ); if ( rs.getOriginStepName().equalsIgnoreCase( from ) && rs.getDestinationStepName().equalsIgnoreCase( to ) && rs.getOriginStepCopy() == fromcopy && rs.getDestinationStepCopy() == tocopy ) { return rs; } } return null; } | /**
* Finds the RowSet between two steps (or copies of steps).
*
* @param from
* the name of the "from" step
* @param fromcopy
* the copy number of the "from" step
* @param to
* the name of the "to" step
* @param tocopy
* the copy number of the "to" step
* @return the row set, or null if none found
*/ | Finds the RowSet between two steps (or copies of steps) | findRowSet | {
"repo_name": "gretchiemoran/pentaho-kettle",
"path": "engine/src/org/pentaho/di/trans/Trans.java",
"license": "apache-2.0",
"size": 194677
} | [
"org.pentaho.di.core.RowSet"
] | import org.pentaho.di.core.RowSet; | import org.pentaho.di.core.*; | [
"org.pentaho.di"
] | org.pentaho.di; | 602,789 |
@ServiceMethod(returns = ReturnType.SINGLE)
LoadBalancingRuleInner get(String resourceGroupName, String loadBalancerName, String loadBalancingRuleName); | @ServiceMethod(returns = ReturnType.SINGLE) LoadBalancingRuleInner get(String resourceGroupName, String loadBalancerName, String loadBalancingRuleName); | /**
* Gets the specified load balancer load balancing rule.
*
* @param resourceGroupName The name of the resource group.
* @param loadBalancerName The name of the load balancer.
* @param loadBalancingRuleName The name of the load balancing rule.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the specified load balancer load balancing rule.
*/ | Gets the specified load balancer load balancing rule | get | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/resourcemanagerhybrid/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/LoadBalancerLoadBalancingRulesClient.java",
"license": "mit",
"size": 6440
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.resourcemanager.network.fluent.models.LoadBalancingRuleInner"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.resourcemanager.network.fluent.models.LoadBalancingRuleInner; | import com.azure.core.annotation.*; import com.azure.resourcemanager.network.fluent.models.*; | [
"com.azure.core",
"com.azure.resourcemanager"
] | com.azure.core; com.azure.resourcemanager; | 406,513 |
public List<Protocol> protocols() {
return this.protocols;
} | List<Protocol> function() { return this.protocols; } | /**
* Get describes on which protocols the operations in this API can be invoked.
*
* @return the protocols value
*/ | Get describes on which protocols the operations in this API can be invoked | protocols | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/apimanagement/mgmt-v2019_12_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_12_01/ApiTagResourceContractProperties.java",
"license": "mit",
"size": 4292
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 2,913,821 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.