method
stringlengths 13
441k
| clean_method
stringlengths 7
313k
| doc
stringlengths 17
17.3k
| comment
stringlengths 3
1.42k
| method_name
stringlengths 1
273
| extra
dict | imports
sequence | imports_info
stringlengths 19
34.8k
| cluster_imports_info
stringlengths 15
3.66k
| libraries
sequence | libraries_info
stringlengths 6
661
| id
int64 0
2.92M
|
---|---|---|---|---|---|---|---|---|---|---|---|
private void ackVmArguments(RuntimeMXBean rtBean) {
assert log != null;
// Ack IGNITE_HOME and VM arguments.
if (log.isInfoEnabled() && S.INCLUDE_SENSITIVE) {
log.info("IGNITE_HOME=" + cfg.getIgniteHome());
log.info("VM arguments: " + rtBean.getInputArguments());
}
} | void function(RuntimeMXBean rtBean) { assert log != null; if (log.isInfoEnabled() && S.INCLUDE_SENSITIVE) { log.info(STR + cfg.getIgniteHome()); log.info(STR + rtBean.getInputArguments()); } } | /**
* Prints out VM arguments and IGNITE_HOME in info mode.
*
* @param rtBean Java runtime bean.
*/ | Prints out VM arguments and IGNITE_HOME in info mode | ackVmArguments | {
"repo_name": "sk0x50/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java",
"license": "apache-2.0",
"size": 150674
} | [
"java.lang.management.RuntimeMXBean"
] | import java.lang.management.RuntimeMXBean; | import java.lang.management.*; | [
"java.lang"
] | java.lang; | 1,019,235 |
public void run() throws Exception {
logger.log(Level.INFO, "======================================");
for (int i = 0; i < cases.length; ++i) {
int testCase = cases[i];
logger.log(Level.INFO, "--> " + testCase);
// 1
String name = "someMethod";
Class[] types = new Class[] {int.class, Object.class};
InvocationConstraint ic = Delegation.YES;
InvocationConstraints constraints = new InvocationConstraints(
ic, null);
callConstructor(testCase, name, types, constraints);
// 2
if (testCase == case2arg) {
name = "*someMethod";
callConstructor(testCase, name, types, constraints);
name = "*5someMethod";
callConstructor(testCase, name, types, constraints);
}
// 3
if (testCase == case2arg) {
name = "someMethod*";
callConstructor(testCase, name, types, constraints);
}
// 4
if (testCase == case3arg) {
name = "someMethod";
Class[] storedTypes = new Class[types.length];
for (int j = 0; j < types.length; ++j) {
storedTypes[j] = types[j];
}
callConstructor(testCase, name, types, constraints);
if (storedTypes.length != types.length) {
throw new TestException(
"types array length was modified");
}
for (int j = 0; j < types.length; ++j) {
if (storedTypes[j] != types[j]) {
throw new TestException(
"types array was modified");
}
}
}
// 5
if (testCase == case3arg) {
name = "someMethod";
Class[] types2 = new Class[types.length];
for (int j = 0; j < types.length; ++j) {
types2[j] = types[j];
}
MethodDesc md1 =
callConstructor(testCase, name, types, constraints);
MethodDesc md2 =
callConstructor(testCase, name, types2, constraints);
if (!md1.equals(md2)) {
throw new TestException(
"MethodDesc objects should be equal");
}
types2[0] = long.class;
if (!md1.equals(md2)) {
throw new TestException(
"MethodDesc objects should be equal");
}
}
// 6
name = "someMethod";
InvocationConstraints emptyConstraints = new InvocationConstraints(
(InvocationConstraint) null, null);
MethodDesc md1 =
callConstructor(testCase, name, types, emptyConstraints);
MethodDesc md2 =
callConstructor(testCase, name, types, null);
if (!md1.equals(md2)) {
throw new TestException(
"MethodDesc objects should be equal");
}
// 7
if (testCase == case2arg || testCase == case3arg) {
try {
callConstructor(testCase, null, types, constraints);
throw new TestException(
"NullPointerException should be thrown");
} catch (NullPointerException ignore) {
}
}
// 8
if (testCase == case3arg) {
try {
callConstructor(testCase, name, null, constraints);
throw new TestException(
"NullPointerException should be thrown");
} catch (NullPointerException ignore) {
}
}
// 9
if (testCase == case3arg) {
Class[] brokenTypes = new Class[] {null, Object.class};
try {
callConstructor(testCase, name, brokenTypes, constraints);
throw new TestException(
"NullPointerException should be thrown");
} catch (NullPointerException ignore) {
}
brokenTypes = new Class[] {Object.class, null};
try {
callConstructor(testCase, name, brokenTypes, constraints);
throw new TestException(
"NullPointerException should be thrown");
} catch (NullPointerException ignore) {
}
}
// 10
if (testCase == case2arg || testCase == case3arg) {
String [] names = new String [] {
"#someMethod",
"2someMethod",
"*#someMethod",
"*someMethod*"
};
for (int j = 0; j < names.length; ++j) {
String brokenName = names[j];
try {
callConstructor(testCase, brokenName, types,
constraints);
throw new TestException(
"IllegalArgumentException should be thrown");
} catch (IllegalArgumentException ignore) {
}
}
}
}
} | void function() throws Exception { logger.log(Level.INFO, STR); for (int i = 0; i < cases.length; ++i) { int testCase = cases[i]; logger.log(Level.INFO, STR + testCase); String name = STR; Class[] types = new Class[] {int.class, Object.class}; InvocationConstraint ic = Delegation.YES; InvocationConstraints constraints = new InvocationConstraints( ic, null); callConstructor(testCase, name, types, constraints); if (testCase == case2arg) { name = STR; callConstructor(testCase, name, types, constraints); name = STR; callConstructor(testCase, name, types, constraints); } if (testCase == case2arg) { name = STR; callConstructor(testCase, name, types, constraints); } if (testCase == case3arg) { name = STR; Class[] storedTypes = new Class[types.length]; for (int j = 0; j < types.length; ++j) { storedTypes[j] = types[j]; } callConstructor(testCase, name, types, constraints); if (storedTypes.length != types.length) { throw new TestException( STR); } for (int j = 0; j < types.length; ++j) { if (storedTypes[j] != types[j]) { throw new TestException( STR); } } } if (testCase == case3arg) { name = STR; Class[] types2 = new Class[types.length]; for (int j = 0; j < types.length; ++j) { types2[j] = types[j]; } MethodDesc md1 = callConstructor(testCase, name, types, constraints); MethodDesc md2 = callConstructor(testCase, name, types2, constraints); if (!md1.equals(md2)) { throw new TestException( STR); } types2[0] = long.class; if (!md1.equals(md2)) { throw new TestException( STR); } } name = STR; InvocationConstraints emptyConstraints = new InvocationConstraints( (InvocationConstraint) null, null); MethodDesc md1 = callConstructor(testCase, name, types, emptyConstraints); MethodDesc md2 = callConstructor(testCase, name, types, null); if (!md1.equals(md2)) { throw new TestException( STR); } if (testCase == case2arg testCase == case3arg) { try { callConstructor(testCase, null, types, constraints); throw new TestException( STR); } catch (NullPointerException ignore) { } } if (testCase == case3arg) { try { callConstructor(testCase, name, null, constraints); throw new TestException( STR); } catch (NullPointerException ignore) { } } if (testCase == case3arg) { Class[] brokenTypes = new Class[] {null, Object.class}; try { callConstructor(testCase, name, brokenTypes, constraints); throw new TestException( STR); } catch (NullPointerException ignore) { } brokenTypes = new Class[] {Object.class, null}; try { callConstructor(testCase, name, brokenTypes, constraints); throw new TestException( STR); } catch (NullPointerException ignore) { } } if (testCase == case2arg testCase == case3arg) { String [] names = new String [] { STR, STR, STR, STR }; for (int j = 0; j < names.length; ++j) { String brokenName = names[j]; try { callConstructor(testCase, brokenName, types, constraints); throw new TestException( STR); } catch (IllegalArgumentException ignore) { } } } } } | /**
* This method performs all actions mentioned in class description.
*/ | This method performs all actions mentioned in class description | run | {
"repo_name": "cdegroot/river",
"path": "qa/src/com/sun/jini/test/spec/constraint/basicmethodconstraints/methoddesc/Constructor_Test.java",
"license": "apache-2.0",
"size": 15547
} | [
"com.sun.jini.qa.harness.TestException",
"java.util.logging.Level",
"net.jini.constraint.BasicMethodConstraints",
"net.jini.core.constraint.Delegation",
"net.jini.core.constraint.InvocationConstraint",
"net.jini.core.constraint.InvocationConstraints"
] | import com.sun.jini.qa.harness.TestException; import java.util.logging.Level; import net.jini.constraint.BasicMethodConstraints; import net.jini.core.constraint.Delegation; import net.jini.core.constraint.InvocationConstraint; import net.jini.core.constraint.InvocationConstraints; | import com.sun.jini.qa.harness.*; import java.util.logging.*; import net.jini.constraint.*; import net.jini.core.constraint.*; | [
"com.sun.jini",
"java.util",
"net.jini.constraint",
"net.jini.core"
] | com.sun.jini; java.util; net.jini.constraint; net.jini.core; | 2,789,257 |
// [TARGET testSubscriptionPermissionsAsync(String, List)]
// [VARIABLE "my_subscription_name"]
public List<Boolean> testSubscriptionPermissionsAsync(String subscriptionName)
throws ExecutionException, InterruptedException {
// [START testSubscriptionPermissionsAsync]
List<String> permissions = new LinkedList<>();
permissions.add("pubsub.subscriptions.get");
Future<List<Boolean>> future =
pubsub.testSubscriptionPermissionsAsync(subscriptionName, permissions);
// ...
List<Boolean> testedPermissions = future.get();
// [END testSubscriptionPermissionsAsync]
return testedPermissions;
} | List<Boolean> function(String subscriptionName) throws ExecutionException, InterruptedException { List<String> permissions = new LinkedList<>(); permissions.add(STR); Future<List<Boolean>> future = pubsub.testSubscriptionPermissionsAsync(subscriptionName, permissions); List<Boolean> testedPermissions = future.get(); return testedPermissions; } | /**
* Example of asynchronously testing whether the caller has the provided permissions on a
* subscription.
*/ | Example of asynchronously testing whether the caller has the provided permissions on a subscription | testSubscriptionPermissionsAsync | {
"repo_name": "tangiel/google-cloud-java",
"path": "google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PubSubSnippets.java",
"license": "apache-2.0",
"size": 35770
} | [
"java.util.LinkedList",
"java.util.List",
"java.util.concurrent.ExecutionException",
"java.util.concurrent.Future"
] | import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; | import java.util.*; import java.util.concurrent.*; | [
"java.util"
] | java.util; | 2,755,749 |
public void createModel() {
URI resourceURI = EditUIUtil.getURI(getEditorInput(), editingDomain.getResourceSet().getURIConverter());
Exception exception = null;
Resource resource = null;
try {
// Load the resource through the editing domain.
//
resource = editingDomain.getResourceSet().getResource(resourceURI, true);
}
catch (Exception e) {
exception = e;
resource = editingDomain.getResourceSet().getResource(resourceURI, false);
}
Diagnostic diagnostic = analyzeResourceProblems(resource, exception);
if (diagnostic.getSeverity() != Diagnostic.OK) {
resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception));
}
editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter);
}
| void function() { URI resourceURI = EditUIUtil.getURI(getEditorInput(), editingDomain.getResourceSet().getURIConverter()); Exception exception = null; Resource resource = null; try { resource = editingDomain.getResourceSet().getResource(resourceURI, true); } catch (Exception e) { exception = e; resource = editingDomain.getResourceSet().getResource(resourceURI, false); } Diagnostic diagnostic = analyzeResourceProblems(resource, exception); if (diagnostic.getSeverity() != Diagnostic.OK) { resourceToDiagnosticMap.put(resource, analyzeResourceProblems(resource, exception)); } editingDomain.getResourceSet().eAdapters().add(problemIndicationAdapter); } | /**
* This is the method called to load a resource into the editing domain's resource set based on the editor's input.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This is the method called to load a resource into the editing domain's resource set based on the editor's input. | createModel | {
"repo_name": "7xMatthx2/E4Training",
"path": "com.sii.airline.editor/src/com/sii/airline/airline/presentation/AirlineEditor.java",
"license": "epl-1.0",
"size": 55870
} | [
"org.eclipse.emf.common.util.Diagnostic",
"org.eclipse.emf.ecore.resource.Resource",
"org.eclipse.emf.edit.ui.util.EditUIUtil"
] | import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.edit.ui.util.EditUIUtil; | import org.eclipse.emf.common.util.*; import org.eclipse.emf.ecore.resource.*; import org.eclipse.emf.edit.ui.util.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 966,825 |
public void init(Object objectName,
Object statementType)
throws StandardException {
initAndCheck(null);
this.savepointName = (String)objectName;
this.statementType = (StatementType)statementType;
} | void function(Object objectName, Object statementType) throws StandardException { initAndCheck(null); this.savepointName = (String)objectName; this.statementType = (StatementType)statementType; } | /**
* Initializer for a SavepointNode
*
* @param objectName The name of the savepoint
* @param savepointStatementType Type of savepoint statement ie rollback, release or set savepoint
*
* @exception StandardException Thrown on error
*/ | Initializer for a SavepointNode | init | {
"repo_name": "youngor/openclouddb",
"path": "src/main/java/com/akiban/sql/parser/SavepointNode.java",
"license": "apache-2.0",
"size": 3719
} | [
"com.akiban.sql.StandardException"
] | import com.akiban.sql.StandardException; | import com.akiban.sql.*; | [
"com.akiban.sql"
] | com.akiban.sql; | 1,669,755 |
private void cleanupV2guiPreferences(final UpgradeManager upgradeManager, final UpgradeHistoryData uhd) {
if (!uhd.getBooleanDataValue(TASK_CLEAN_UP_OF_V2GUIPREFERENCES_DONE)) {
final String query = "delete from o_property where name = 'v2guipreferences' and textvalue like '%ajax-beta-on</string>%<boolean>false%'";
try {
Connection con = upgradeManager.getDataSource().getConnection();
final Statement deleteStmt = con.createStatement();
deleteStmt.execute(query);
con.close();
con = null;
} catch (final SQLException e) {
log.warn("Could not execute system upgrade sql query. Query:" + query, e);
throw new StartupException("Could not execute system upgrade sql query. Query:" + query, e);
}
uhd.setBooleanDataValue(TASK_CLEAN_UP_OF_V2GUIPREFERENCES_DONE, true);
log.info("Audit:+---------------------------------------------------------------------------------------+");
log.info("Audit:+... Deleted all v2guipreferences with textvalues containing 'ajax-beta-on' -> false ...+");
log.info("Audit:+................... (details of affected users are listed above) .....................+");
log.info("Audit:+---------------------------------------------------------------------------------------+");
upgradeManager.setUpgradesHistory(uhd, VERSION);
}
} | void function(final UpgradeManager upgradeManager, final UpgradeHistoryData uhd) { if (!uhd.getBooleanDataValue(TASK_CLEAN_UP_OF_V2GUIPREFERENCES_DONE)) { final String query = STR; try { Connection con = upgradeManager.getDataSource().getConnection(); final Statement deleteStmt = con.createStatement(); deleteStmt.execute(query); con.close(); con = null; } catch (final SQLException e) { log.warn(STR + query, e); throw new StartupException(STR + query, e); } uhd.setBooleanDataValue(TASK_CLEAN_UP_OF_V2GUIPREFERENCES_DONE, true); log.info(STR); log.info(STR); log.info(STR); log.info(STR); upgradeManager.setUpgradesHistory(uhd, VERSION); } } | /**
* Deletes all v2guipreference with textvalues containing '.*ajax-beta-on</string><boolean>false</boolean>'
*/ | Deletes all v2guipreference with textvalues containing '.*ajax-beta-onfalse' | cleanupV2guiPreferences | {
"repo_name": "huihoo/olat",
"path": "olat7.8/src/main/java/org/olat/lms/upgrade/upgrades/OLATUpgrade_5_2_0.java",
"license": "apache-2.0",
"size": 12374
} | [
"java.sql.Connection",
"java.sql.SQLException",
"java.sql.Statement",
"org.olat.lms.upgrade.UpgradeHistoryData",
"org.olat.lms.upgrade.UpgradeManager",
"org.olat.system.exception.StartupException"
] | import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import org.olat.lms.upgrade.UpgradeHistoryData; import org.olat.lms.upgrade.UpgradeManager; import org.olat.system.exception.StartupException; | import java.sql.*; import org.olat.lms.upgrade.*; import org.olat.system.exception.*; | [
"java.sql",
"org.olat.lms",
"org.olat.system"
] | java.sql; org.olat.lms; org.olat.system; | 1,439,635 |
protected void doUnlock(HttpServletRequest req, HttpServletResponse resp) {
String path = getRelativePath(req);
// Check if Webdav is read only
if (m_readOnly) {
resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0));
}
return;
}
// Check if resource is locked
if (isLocked(req)) {
resp.setStatus(CmsWebdavStatus.SC_LOCKED);
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path));
}
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug(Messages.get().getBundle().key(Messages.LOG_UNLOCK_ITEM_0));
}
m_session.unlock(path);
resp.setStatus(CmsWebdavStatus.SC_NO_CONTENT);
}
| void function(HttpServletRequest req, HttpServletResponse resp) { String path = getRelativePath(req); if (m_readOnly) { resp.setStatus(CmsWebdavStatus.SC_FORBIDDEN); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_WEBDAV_READ_ONLY_0)); } return; } if (isLocked(req)) { resp.setStatus(CmsWebdavStatus.SC_LOCKED); if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_ITEM_LOCKED_1, path)); } return; } if (LOG.isDebugEnabled()) { LOG.debug(Messages.get().getBundle().key(Messages.LOG_UNLOCK_ITEM_0)); } m_session.unlock(path); resp.setStatus(CmsWebdavStatus.SC_NO_CONTENT); } | /**
* Process a UNLOCK WebDAV request for the specified resource.<p>
*
* @param req the servlet request we are processing
* @param resp the servlet response we are creating
*/ | Process a UNLOCK WebDAV request for the specified resource | doUnlock | {
"repo_name": "comundus/opencms-comundus",
"path": "src/main/java/org/opencms/webdav/CmsWebdavServlet.java",
"license": "lgpl-2.1",
"size": 129079
} | [
"javax.servlet.http.HttpServletRequest",
"javax.servlet.http.HttpServletResponse"
] | import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; | import javax.servlet.http.*; | [
"javax.servlet"
] | javax.servlet; | 2,664,325 |
protected void drawEntryLabel(Canvas c, String label, float x, float y) {
c.drawText(label, x, y, mEntryLabelsPaint);
} | void function(Canvas c, String label, float x, float y) { c.drawText(label, x, y, mEntryLabelsPaint); } | /**
* Draws an entry label at the specified position.
*
* @param c
* @param label
* @param x
* @param y
*/ | Draws an entry label at the specified position | drawEntryLabel | {
"repo_name": "xyjincan/snore-test",
"path": "Snore/MPChartLib/src/main/java/com/github/mikephil/charting/renderer/PieChartRenderer.java",
"license": "apache-2.0",
"size": 39604
} | [
"android.graphics.Canvas"
] | import android.graphics.Canvas; | import android.graphics.*; | [
"android.graphics"
] | android.graphics; | 1,501,775 |
public boolean checkCollisionBottom(ArrayList<Block> blocks,int m) {
for(Block xx : this.blocks){
for(Block yy : blocks){
if(xx.getY()+1==yy.getY() && xx.getX() == yy.getX()) return true;
}
if(xx.getY() == m-1)return true;
}
return false;
}
| boolean function(ArrayList<Block> blocks,int m) { for(Block xx : this.blocks){ for(Block yy : blocks){ if(xx.getY()+1==yy.getY() && xx.getX() == yy.getX()) return true; } if(xx.getY() == m-1)return true; } return false; } | /**
* checks collision with bottom wall|objects
* @param blocks
* @param m
* @return
*/ | checks collision with bottom wall|objects | checkCollisionBottom | {
"repo_name": "ericcee/SimpleTetris",
"path": "src/TetrisClasses/Tetromino.java",
"license": "apache-2.0",
"size": 4019
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 960,676 |
private void testMultiMinAggregation()
{
String queryString = "Select min(p.salary), min(p.age) from PersonES p where p.age > 20";
Query query = em.createQuery(queryString);
List resultList = query.getResultList();
Assert.assertEquals(2, resultList.size());
Assert.assertEquals(300.0, resultList.get(0));
Assert.assertEquals(30.0, resultList.get(1));
} | void function() { String queryString = STR; Query query = em.createQuery(queryString); List resultList = query.getResultList(); Assert.assertEquals(2, resultList.size()); Assert.assertEquals(300.0, resultList.get(0)); Assert.assertEquals(30.0, resultList.get(1)); } | /**
* Test multi min aggregation.
*/ | Test multi min aggregation | testMultiMinAggregation | {
"repo_name": "impetus-opensource/Kundera",
"path": "src/kundera-elastic-search/src/test/java/com/impetus/client/es/ESAggregationTest.java",
"license": "apache-2.0",
"size": 20075
} | [
"java.util.List",
"javax.persistence.Query",
"junit.framework.Assert"
] | import java.util.List; import javax.persistence.Query; import junit.framework.Assert; | import java.util.*; import javax.persistence.*; import junit.framework.*; | [
"java.util",
"javax.persistence",
"junit.framework"
] | java.util; javax.persistence; junit.framework; | 2,334,888 |
public Builder demoServerQuery(Optional<String> newDemoServerQuery) {
this.demoServerQuery = newDemoServerQuery;
return this;
} | Builder function(Optional<String> newDemoServerQuery) { this.demoServerQuery = newDemoServerQuery; return this; } | /**
* Sets the query string that failing test cases use to make it easy to
* visualize the test run via the demo server.
*/ | Sets the query string that failing test cases use to make it easy to visualize the test run via the demo server | demoServerQuery | {
"repo_name": "mikesamuel/template-analysis",
"path": "src/main/java/com/google/template/autoesc/Language.java",
"license": "apache-2.0",
"size": 20519
} | [
"com.google.common.base.Optional"
] | import com.google.common.base.Optional; | import com.google.common.base.*; | [
"com.google.common"
] | com.google.common; | 1,727,754 |
FRAMETYPE frame(Vertex vertex); | FRAMETYPE frame(Vertex vertex); | /**
* Return the given {@link Vertex} as a {@link WindupVertexFrame} (if possible.)
* <p>
* <b>Note:</b> This method will always succeed! Even if the given {@link Vertex} is not actually the specified {@link WindupVertexFrame} type.
* Call {@link GraphTypeManager#hasType(Class, Vertex)} <b>before</b> using this!
*/ | Return the given <code>Vertex</code> as a <code>WindupVertexFrame</code> (if possible.) Note: This method will always succeed! Even if the given <code>Vertex</code> is not actually the specified <code>WindupVertexFrame</code> type. Call <code>GraphTypeManager#hasType(Class, Vertex)</code> before using this | frame | {
"repo_name": "jsight/windup",
"path": "graph/api/src/main/java/org/jboss/windup/graph/service/Service.java",
"license": "epl-1.0",
"size": 3777
} | [
"org.apache.tinkerpop.gremlin.structure.Vertex"
] | import org.apache.tinkerpop.gremlin.structure.Vertex; | import org.apache.tinkerpop.gremlin.structure.*; | [
"org.apache.tinkerpop"
] | org.apache.tinkerpop; | 2,882,396 |
@Override
public void writeTo(Writer writer, Syntax syntax) throws IOException, ModelRuntimeException {
RDFWriter rdfWriter = Rio.createWriter(getRDFFormat(syntax), writer);
this.writeTo(rdfWriter);
}
| void function(Writer writer, Syntax syntax) throws IOException, ModelRuntimeException { RDFWriter rdfWriter = Rio.createWriter(getRDFFormat(syntax), writer); this.writeTo(rdfWriter); } | /**
* Writes the whole ModelSet to the Writer. Depending on the Syntax the
* context URIs might or might not be serialized. TriX should be able to
* serialize contexts.
*/ | Writes the whole ModelSet to the Writer. Depending on the Syntax the context URIs might or might not be serialized. TriX should be able to serialize contexts | writeTo | {
"repo_name": "semweb4j/semweb4j",
"path": "org.semweb4j.rdf2go.impl.sesame/src/main/java/org/openrdf/rdf2go/RepositoryModelSet.java",
"license": "bsd-2-clause",
"size": 34889
} | [
"java.io.IOException",
"java.io.Writer",
"org.ontoware.rdf2go.exception.ModelRuntimeException",
"org.ontoware.rdf2go.model.Syntax",
"org.openrdf.rio.RDFWriter",
"org.openrdf.rio.Rio"
] | import java.io.IOException; import java.io.Writer; import org.ontoware.rdf2go.exception.ModelRuntimeException; import org.ontoware.rdf2go.model.Syntax; import org.openrdf.rio.RDFWriter; import org.openrdf.rio.Rio; | import java.io.*; import org.ontoware.rdf2go.exception.*; import org.ontoware.rdf2go.model.*; import org.openrdf.rio.*; | [
"java.io",
"org.ontoware.rdf2go",
"org.openrdf.rio"
] | java.io; org.ontoware.rdf2go; org.openrdf.rio; | 1,934,191 |
protected void send(ComposableBody body) throws BOSHException {
if (!connected) {
throw new IllegalStateException("Not connected to a server!");
}
if (body == null) {
throw new NullPointerException("Body mustn't be null!");
}
if (sessionID != null) {
body = body.rebuild().setAttribute(
BodyQName.create(BOSH_URI, "sid"), sessionID).build();
}
client.send(body);
} | void function(ComposableBody body) throws BOSHException { if (!connected) { throw new IllegalStateException(STR); } if (body == null) { throw new NullPointerException(STR); } if (sessionID != null) { body = body.rebuild().setAttribute( BodyQName.create(BOSH_URI, "sid"), sessionID).build(); } client.send(body); } | /**
* Send a HTTP request to the connection manager with the provided body element.
*
* @param body the body which will be sent.
*/ | Send a HTTP request to the connection manager with the provided body element | send | {
"repo_name": "u20024804/Smack",
"path": "smack-bosh/src/main/java/org/jivesoftware/smack/bosh/XMPPBOSHConnection.java",
"license": "apache-2.0",
"size": 20158
} | [
"org.igniterealtime.jbosh.BOSHException",
"org.igniterealtime.jbosh.BodyQName",
"org.igniterealtime.jbosh.ComposableBody"
] | import org.igniterealtime.jbosh.BOSHException; import org.igniterealtime.jbosh.BodyQName; import org.igniterealtime.jbosh.ComposableBody; | import org.igniterealtime.jbosh.*; | [
"org.igniterealtime.jbosh"
] | org.igniterealtime.jbosh; | 815,619 |
@NonNull
public Locker getLocker(@NonNull String name) {
return new Locker(this, name);
} | Locker function(@NonNull String name) { return new Locker(this, name); } | /**
* Get an empty locker to keep locks in.
* @param name A name for the process/user that will own this lock, so that he can be displayed.
*/ | Get an empty locker to keep locks in | getLocker | {
"repo_name": "fjalvingh/domui",
"path": "to.etc.domui/src/main/java/to/etc/domui/lockhandler/LockHandler.java",
"license": "lgpl-2.1",
"size": 4280
} | [
"org.eclipse.jdt.annotation.NonNull"
] | import org.eclipse.jdt.annotation.NonNull; | import org.eclipse.jdt.annotation.*; | [
"org.eclipse.jdt"
] | org.eclipse.jdt; | 2,268,547 |
@Operation(desc = "Disable message counters", impact = MBeanOperationInfo.ACTION)
void disableMessageCounters() throws Exception; | @Operation(desc = STR, impact = MBeanOperationInfo.ACTION) void disableMessageCounters() throws Exception; | /**
* Disables message counters for this server.
*/ | Disables message counters for this server | disableMessageCounters | {
"repo_name": "gaohoward/activemq-artemis",
"path": "artemis-core-client/src/main/java/org/apache/activemq/artemis/api/core/management/ActiveMQServerControl.java",
"license": "apache-2.0",
"size": 83324
} | [
"javax.management.MBeanOperationInfo"
] | import javax.management.MBeanOperationInfo; | import javax.management.*; | [
"javax.management"
] | javax.management; | 1,925,362 |
public static AccessibilityNodeInfoCompat obtain(View source) {
return AccessibilityNodeInfoCompat.wrapNonNullInstance(IMPL.obtain(source));
} | static AccessibilityNodeInfoCompat function(View source) { return AccessibilityNodeInfoCompat.wrapNonNullInstance(IMPL.obtain(source)); } | /**
* Returns a cached instance if such is available otherwise a new one and
* sets the source.
*
* @return An instance.
* @see #setSource(View)
*/ | Returns a cached instance if such is available otherwise a new one and sets the source | obtain | {
"repo_name": "kingargyle/adt-leanback-support",
"path": "support-v4/src/main/java/android/support/v4/view/accessibility/AccessibilityNodeInfoCompat.java",
"license": "apache-2.0",
"size": 82367
} | [
"android.view.View"
] | import android.view.View; | import android.view.*; | [
"android.view"
] | android.view; | 2,796,194 |
@Test
public void testGetSetRemoveCP() throws Exception {
HTableDescriptor desc = new HTableDescriptor("table");
// simple CP
String className = BaseRegionObserver.class.getName();
// add and check that it is present
desc.addCoprocessor(className);
assertTrue(desc.hasCoprocessor(className));
// remove it and check that it is gone
desc.removeCoprocessor(className);
assertFalse(desc.hasCoprocessor(className));
} | void function() throws Exception { HTableDescriptor desc = new HTableDescriptor("table"); String className = BaseRegionObserver.class.getName(); desc.addCoprocessor(className); assertTrue(desc.hasCoprocessor(className)); desc.removeCoprocessor(className); assertFalse(desc.hasCoprocessor(className)); } | /**
* Test cps in the table description
* @throws Exception
*/ | Test cps in the table description | testGetSetRemoveCP | {
"repo_name": "ddraj/hbase-mttr",
"path": "hbase-server/src/test/java/org/apache/hadoop/hbase/TestHTableDescriptor.java",
"license": "apache-2.0",
"size": 2768
} | [
"org.apache.hadoop.hbase.coprocessor.BaseRegionObserver",
"org.junit.Assert"
] | import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver; import org.junit.Assert; | import org.apache.hadoop.hbase.coprocessor.*; import org.junit.*; | [
"org.apache.hadoop",
"org.junit"
] | org.apache.hadoop; org.junit; | 2,284,032 |
@Id
@Column(name="hashid")
public String getHashid() {
return hashid;
} | @Column(name=STR) String function() { return hashid; } | /**
* Gets the hashid.
*
* @return the hashid
*/ | Gets the hashid | getHashid | {
"repo_name": "gleb619/hotel_shop",
"path": "src/main/java/org/test/shop/model/domain/entity/other/TimelineView.java",
"license": "apache-2.0",
"size": 9873
} | [
"javax.persistence.Column"
] | import javax.persistence.Column; | import javax.persistence.*; | [
"javax.persistence"
] | javax.persistence; | 2,376,470 |
public void addMetadataToQueue(final String queueName, List<AndesMessageMetadata> metadata)
throws AndesException; | void function(final String queueName, List<AndesMessageMetadata> metadata) throws AndesException; | /**
* store metadata list specifically under a queue
*
* @param queueName name of the queue to store metadata
* @param metadata metadata list to store
* @throws AndesException
*/ | store metadata list specifically under a queue | addMetadataToQueue | {
"repo_name": "pamod/andes",
"path": "modules/andes-core/broker/src/main/java/org/wso2/andes/kernel/MessageStore.java",
"license": "apache-2.0",
"size": 8121
} | [
"java.util.List"
] | import java.util.List; | import java.util.*; | [
"java.util"
] | java.util; | 403,674 |
@SuppressWarnings("rawtypes")
public Vector getSolution() {
return theSolution;
}
| @SuppressWarnings(STR) Vector function() { return theSolution; } | /**
* Gets the solution.
*
* @return the solution
*/ | Gets the solution | getSolution | {
"repo_name": "synergynet/synergynet2.5",
"path": "synergynet2.5/src/main/java/apps/twentyfourpoint/algorithm/Solution.java",
"license": "bsd-3-clause",
"size": 8798
} | [
"java.util.Vector"
] | import java.util.Vector; | import java.util.*; | [
"java.util"
] | java.util; | 1,543,597 |
private class SwitchPacketProcessor implements PacketProcessor {
@Override
public void process(PacketContext pc) {
log.info(pc.toString());
ConnectPoint cp = pc.inPacket().receivedFrom();
macTables.putIfAbsent(cp.deviceId(), Maps.newConcurrentMap());
// This method simply floods all ports with the packet.
actLikeHub(pc);
//actLikeSwitch(pc);
} | class SwitchPacketProcessor implements PacketProcessor { public void function(PacketContext pc) { log.info(pc.toString()); ConnectPoint cp = pc.inPacket().receivedFrom(); macTables.putIfAbsent(cp.deviceId(), Maps.newConcurrentMap()); actLikeHub(pc); } | /**
* Learns the source port associated with the packet's DeviceId if it has not already been learned.
* Calls actLikeSwitch to process and send the packet.
* @param pc PacketContext object containing packet info
*/ | Learns the source port associated with the packet's DeviceId if it has not already been learned. Calls actLikeSwitch to process and send the packet | process | {
"repo_name": "osinstom/onos",
"path": "apps/learning-switch/src/main/java/org/onosproject/learningswitch/LearningSwitchTutorial.java",
"license": "apache-2.0",
"size": 7862
} | [
"com.google.common.collect.Maps",
"org.onosproject.net.ConnectPoint",
"org.onosproject.net.packet.PacketContext",
"org.onosproject.net.packet.PacketProcessor"
] | import com.google.common.collect.Maps; import org.onosproject.net.ConnectPoint; import org.onosproject.net.packet.PacketContext; import org.onosproject.net.packet.PacketProcessor; | import com.google.common.collect.*; import org.onosproject.net.*; import org.onosproject.net.packet.*; | [
"com.google.common",
"org.onosproject.net"
] | com.google.common; org.onosproject.net; | 921,930 |
public Vertex details(Vertex source, Vertex vertex, Vertex vertex2) {
return details(source, vertex, vertex2, null, null, null);
}
| Vertex function(Vertex source, Vertex vertex, Vertex vertex2) { return details(source, vertex, vertex2, null, null, null); } | /**
* Self API
* Discover the meaning of the word including all details.
*/ | Self API Discover the meaning of the word including all details | details | {
"repo_name": "BOTlibre/BOTlibre",
"path": "micro-ai-engine/android/source/org/botlibre/sense/wikidata/Wikidata.java",
"license": "epl-1.0",
"size": 29781
} | [
"org.botlibre.api.knowledge.Vertex"
] | import org.botlibre.api.knowledge.Vertex; | import org.botlibre.api.knowledge.*; | [
"org.botlibre.api"
] | org.botlibre.api; | 2,207,539 |
public void runInBackground(ISchedulingRule rule, Object jobFamily) {
if (jobFamily == null) {
runInBackground(rule, (Object[]) null);
} else {
runInBackground(rule, new Object[] { jobFamily });
}
} | void function(ISchedulingRule rule, Object jobFamily) { if (jobFamily == null) { runInBackground(rule, (Object[]) null); } else { runInBackground(rule, new Object[] { jobFamily }); } } | /**
* Run the action in the background rather than with the progress dialog.
*
* @param rule
* The rule to apply to the background job or <code>null</code>
* if there isn't one.
* @param jobFamily
* a single family that the job should belong to or
* <code>null</code> if none.
*
* @since 3.1
*/ | Run the action in the background rather than with the progress dialog | runInBackground | {
"repo_name": "elucash/eclipse-oxygen",
"path": "org.eclipse.ui.ide/src/org/eclipse/ui/actions/WorkspaceAction.java",
"license": "epl-1.0",
"size": 16671
} | [
"org.eclipse.core.runtime.jobs.ISchedulingRule"
] | import org.eclipse.core.runtime.jobs.ISchedulingRule; | import org.eclipse.core.runtime.jobs.*; | [
"org.eclipse.core"
] | org.eclipse.core; | 851,933 |
public Statement createStatement();
| Statement function(); | /**
* Create a statement.
*
* @return the statement
*/ | Create a statement | createStatement | {
"repo_name": "kevin-chen-hw/LDAE",
"path": "com.huawei.soa.ldae/src/main/java/org/hibernate/engine/jdbc/spi/StatementPreparer.java",
"license": "lgpl-2.1",
"size": 3637
} | [
"java.sql.Statement"
] | import java.sql.Statement; | import java.sql.*; | [
"java.sql"
] | java.sql; | 2,847,282 |
ProgramExpression getProgramExpression( int id );
/**
* Get value of program expression
*
* @param programExpression {@link ProgramExpression}
* @param programStageInstance The {@link ProgramStageInstance} associate
* with this expression
* @param trackedEntityDataValueMap TrackedEntityDataValue<The id of {@link DataElement}
| ProgramExpression getProgramExpression( int id ); /** * Get value of program expression * * @param programExpression {@link ProgramExpression} * @param programStageInstance The {@link ProgramStageInstance} associate * with this expression * @param trackedEntityDataValueMap TrackedEntityDataValue<The id of {@link DataElement} | /**
* Returns a {@link ProgramExpression}.
*
* @param id the id of the ProgramExpression to return.
* @return the ProgramExpression with the given id
*/ | Returns a <code>ProgramExpression</code> | getProgramExpression | {
"repo_name": "kakada/dhis2",
"path": "dhis-api/src/main/java/org/hisp/dhis/program/ProgramExpressionService.java",
"license": "bsd-3-clause",
"size": 4679
} | [
"org.hisp.dhis.dataelement.DataElement",
"org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue"
] | import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue; | import org.hisp.dhis.dataelement.*; import org.hisp.dhis.trackedentitydatavalue.*; | [
"org.hisp.dhis"
] | org.hisp.dhis; | 1,493,778 |
public CloudToDeviceProperties withDefaultTtlAsIso8601(Period defaultTtlAsIso8601) {
this.defaultTtlAsIso8601 = defaultTtlAsIso8601;
return this;
} | CloudToDeviceProperties function(Period defaultTtlAsIso8601) { this.defaultTtlAsIso8601 = defaultTtlAsIso8601; return this; } | /**
* Set the default time to live for cloud-to-device messages in the device queue. See: https://docs.microsoft.com/azure/iot-hub/iot-hub-devguide-messaging#cloud-to-device-messages.
*
* @param defaultTtlAsIso8601 the defaultTtlAsIso8601 value to set
* @return the CloudToDeviceProperties object itself.
*/ | Set the default time to live for cloud-to-device messages in the device queue. See: HREF | withDefaultTtlAsIso8601 | {
"repo_name": "selvasingh/azure-sdk-for-java",
"path": "sdk/iothub/mgmt-v2019_03_22_preview/src/main/java/com/microsoft/azure/management/iothub/v2019_03_22_preview/CloudToDeviceProperties.java",
"license": "mit",
"size": 3354
} | [
"org.joda.time.Period"
] | import org.joda.time.Period; | import org.joda.time.*; | [
"org.joda.time"
] | org.joda.time; | 2,216,092 |
Flowable<Transaction> pendingTransactionFlowable(); | Flowable<Transaction> pendingTransactionFlowable(); | /**
* Create an {@link Flowable} instance to emit all pending transactions that have yet to be
* placed into a block on the blockchain.
*
* @return a {@link Flowable} instance to emit pending transactions
*/ | Create an <code>Flowable</code> instance to emit all pending transactions that have yet to be placed into a block on the blockchain | pendingTransactionFlowable | {
"repo_name": "web3j/web3j",
"path": "core/src/main/java/org/web3j/protocol/rx/Web3jRx.java",
"license": "apache-2.0",
"size": 9184
} | [
"io.reactivex.Flowable",
"org.web3j.protocol.core.methods.response.Transaction"
] | import io.reactivex.Flowable; import org.web3j.protocol.core.methods.response.Transaction; | import io.reactivex.*; import org.web3j.protocol.core.methods.response.*; | [
"io.reactivex",
"org.web3j.protocol"
] | io.reactivex; org.web3j.protocol; | 1,395,610 |
public void doShow_preview_assignment_assignment(RunData data)
{
SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid());
state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false));
} // doShow_preview_assignment_assignment | void function(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); state.setAttribute(PREVIEW_ASSIGNMENT_ASSIGNMENT_HIDE_FLAG, Boolean.valueOf(false)); } | /**
* Action is to show the preview assignment assignment info
*/ | Action is to show the preview assignment assignment info | doShow_preview_assignment_assignment | {
"repo_name": "frasese/sakai",
"path": "assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java",
"license": "apache-2.0",
"size": 686269
} | [
"org.sakaiproject.cheftool.JetspeedRunData",
"org.sakaiproject.cheftool.RunData",
"org.sakaiproject.event.api.SessionState"
] | import org.sakaiproject.cheftool.JetspeedRunData; import org.sakaiproject.cheftool.RunData; import org.sakaiproject.event.api.SessionState; | import org.sakaiproject.cheftool.*; import org.sakaiproject.event.api.*; | [
"org.sakaiproject.cheftool",
"org.sakaiproject.event"
] | org.sakaiproject.cheftool; org.sakaiproject.event; | 1,496,921 |
public void put(CoapHandler handler, String payload, int format) {
asynchronous(format(Request.newPut().setURI(uri).setPayload(payload), format), handler);
}
| void function(CoapHandler handler, String payload, int format) { asynchronous(format(Request.newPut().setURI(uri).setPayload(payload), format), handler); } | /**
* Sends a PUT request with the specified payload and the specified content
* format and invokes the specified handler when a response arrives.
*
* @param handler the Response handler
* @param payload the payload
* @param format the Content-Format
*/ | Sends a PUT request with the specified payload and the specified content format and invokes the specified handler when a response arrives | put | {
"repo_name": "tucanae47/CoAp-Android-MsgPack",
"path": "app/src/main/java/org/eclipse/californium/core/CoapClient.java",
"license": "mit",
"size": 34238
} | [
"org.eclipse.californium.core.coap.Request"
] | import org.eclipse.californium.core.coap.Request; | import org.eclipse.californium.core.coap.*; | [
"org.eclipse.californium"
] | org.eclipse.californium; | 1,001,924 |
public Vector<BigInteger> encrypt(byte[] message) {
return encrypt(message, message.length);
}
| Vector<BigInteger> function(byte[] message) { return encrypt(message, message.length); } | /**
* encrypt byte[] and returns vector of bigintegers.
*/ | encrypt byte[] and returns vector of bigintegers | encrypt | {
"repo_name": "thc202/zap-extensions",
"path": "addOns/tokengen/src/main/java/com/fasteasytrade/JRandTest/Algo/RSACrypt.java",
"license": "apache-2.0",
"size": 16780
} | [
"java.math.BigInteger",
"java.util.Vector"
] | import java.math.BigInteger; import java.util.Vector; | import java.math.*; import java.util.*; | [
"java.math",
"java.util"
] | java.math; java.util; | 517,701 |
@Override
@XmlElement(name = "measureDescription", namespace = LegacyNamespaces.GMD)
public InternationalString getMeasureDescription() {
return FilterByVersion.LEGACY_METADATA.accept() ? measureDescription : null;
} | @XmlElement(name = STR, namespace = LegacyNamespaces.GMD) InternationalString function() { return FilterByVersion.LEGACY_METADATA.accept() ? measureDescription : null; } | /**
* Returns the description of the measure being determined.
*
* @return description of the measure being determined, or {@code null}.
*
* @see <a href="https://issues.apache.org/jira/browse/SIS-394">Issue SIS-394</a>
*/ | Returns the description of the measure being determined | getMeasureDescription | {
"repo_name": "apache/sis",
"path": "core/sis-metadata/src/main/java/org/apache/sis/metadata/iso/quality/AbstractElement.java",
"license": "apache-2.0",
"size": 22505
} | [
"javax.xml.bind.annotation.XmlElement",
"org.apache.sis.internal.jaxb.FilterByVersion",
"org.apache.sis.internal.xml.LegacyNamespaces",
"org.opengis.util.InternationalString"
] | import javax.xml.bind.annotation.XmlElement; import org.apache.sis.internal.jaxb.FilterByVersion; import org.apache.sis.internal.xml.LegacyNamespaces; import org.opengis.util.InternationalString; | import javax.xml.bind.annotation.*; import org.apache.sis.internal.jaxb.*; import org.apache.sis.internal.xml.*; import org.opengis.util.*; | [
"javax.xml",
"org.apache.sis",
"org.opengis.util"
] | javax.xml; org.apache.sis; org.opengis.util; | 216,845 |
public void removeColumn(Attribute attribute, String tableName) throws SQLException {
Statement st = null;
try {
st = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
String query =
"ALTER TABLE " +
properties.getIdentifierQuoteOpen() + tableName + properties.getIdentifierQuoteClose() +
" DROP COLUMN " +
properties.getIdentifierQuoteOpen() + attribute.getName() + properties.getIdentifierQuoteClose();
st.execute(query);
} catch (SQLException e) {
throw e;
} finally {
if (st != null)
st.close();
}
}
| void function(Attribute attribute, String tableName) throws SQLException { Statement st = null; try { st = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); String query = STR + properties.getIdentifierQuoteOpen() + tableName + properties.getIdentifierQuoteClose() + STR + properties.getIdentifierQuoteOpen() + attribute.getName() + properties.getIdentifierQuoteClose(); st.execute(query); } catch (SQLException e) { throw e; } finally { if (st != null) st.close(); } } | /**
* Removes the column of the given attribute from the table with name
* tableName.
*/ | Removes the column of the given attribute from the table with name tableName | removeColumn | {
"repo_name": "ntj/ComplexRapidMiner",
"path": "src/com/rapidminer/tools/jdbc/DatabaseHandler.java",
"license": "gpl-2.0",
"size": 23802
} | [
"com.rapidminer.example.Attribute",
"java.sql.ResultSet",
"java.sql.SQLException",
"java.sql.Statement"
] | import com.rapidminer.example.Attribute; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; | import com.rapidminer.example.*; import java.sql.*; | [
"com.rapidminer.example",
"java.sql"
] | com.rapidminer.example; java.sql; | 1,736,291 |
private RectF getDisplayRect(Matrix matrix) {
ImageView imageView = getImageView();
if (null != imageView) {
Drawable d = imageView.getDrawable();
if (null != d) {
mDisplayRect.set(0, 0, d.getIntrinsicWidth(),
d.getIntrinsicHeight());
matrix.mapRect(mDisplayRect);
return mDisplayRect;
}
}
return null;
} | RectF function(Matrix matrix) { ImageView imageView = getImageView(); if (null != imageView) { Drawable d = imageView.getDrawable(); if (null != d) { mDisplayRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); matrix.mapRect(mDisplayRect); return mDisplayRect; } } return null; } | /**
* Helper method that maps the supplied Matrix to the current Drawable
*
* @param matrix - Matrix to map Drawable against
* @return RectF - Displayed Rectangle
*/ | Helper method that maps the supplied Matrix to the current Drawable | getDisplayRect | {
"repo_name": "hellcharmer/REMOVING",
"path": "app/src/main/java/com/example/charmer/moving/photoView/PhotoViewAttacher.java",
"license": "apache-2.0",
"size": 39867
} | [
"android.graphics.Matrix",
"android.graphics.RectF",
"android.graphics.drawable.Drawable",
"android.widget.ImageView"
] | import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.widget.ImageView; | import android.graphics.*; import android.graphics.drawable.*; import android.widget.*; | [
"android.graphics",
"android.widget"
] | android.graphics; android.widget; | 552,812 |
public HierarchicStyle getStyle() {
return m_type == null ? m_style : getLayout(m_type);
} | HierarchicStyle function() { return m_type == null ? m_style : getLayout(m_type); } | /**
* Returns the current hierarchic layouting style.
*
* @return The current hierarchic layouting style.
*/ | Returns the current hierarchic layouting style | getStyle | {
"repo_name": "AmesianX/binnavi",
"path": "src/main/java/com/google/security/zynamics/binnavi/ZyGraph/Settings/ZyGraphHierarchicalSettings.java",
"license": "apache-2.0",
"size": 8886
} | [
"com.google.security.zynamics.zylib.gui.zygraph.layouters.HierarchicStyle"
] | import com.google.security.zynamics.zylib.gui.zygraph.layouters.HierarchicStyle; | import com.google.security.zynamics.zylib.gui.zygraph.layouters.*; | [
"com.google.security"
] | com.google.security; | 2,471,933 |
Volume createVolume(CreateVolumeCmd cmd); | Volume createVolume(CreateVolumeCmd cmd); | /**
* Creates the volume based on the given criteria
*
* @param cmd
* the API command wrapping the criteria (account/domainId [admin only], zone, diskOffering, snapshot,
* name)
* @return the volume object
*/ | Creates the volume based on the given criteria | createVolume | {
"repo_name": "ikoula/cloudstack",
"path": "api/src/com/cloud/storage/VolumeApiService.java",
"license": "gpl-2.0",
"size": 4184
} | [
"org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd"
] | import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd; | import org.apache.cloudstack.api.command.user.volume.*; | [
"org.apache.cloudstack"
] | org.apache.cloudstack; | 1,332,169 |
static CharacterRunAutomaton buildRemoteWhitelist(List<String> whitelist) {
if (whitelist.isEmpty()) {
return new CharacterRunAutomaton(Automata.makeEmpty());
}
Automaton automaton = Regex.simpleMatchToAutomaton(whitelist.toArray(Strings.EMPTY_ARRAY));
automaton = MinimizationOperations.minimize(automaton, Operations.DEFAULT_MAX_DETERMINIZED_STATES);
if (Operations.isTotal(automaton)) {
throw new IllegalArgumentException("Refusing to start because whitelist " + whitelist + " accepts all addresses. "
+ "This would allow users to reindex-from-remote any URL they like effectively having Elasticsearch make HTTP GETs "
+ "for them.");
}
return new CharacterRunAutomaton(automaton);
} | static CharacterRunAutomaton buildRemoteWhitelist(List<String> whitelist) { if (whitelist.isEmpty()) { return new CharacterRunAutomaton(Automata.makeEmpty()); } Automaton automaton = Regex.simpleMatchToAutomaton(whitelist.toArray(Strings.EMPTY_ARRAY)); automaton = MinimizationOperations.minimize(automaton, Operations.DEFAULT_MAX_DETERMINIZED_STATES); if (Operations.isTotal(automaton)) { throw new IllegalArgumentException(STR + whitelist + STR + STR + STR); } return new CharacterRunAutomaton(automaton); } | /**
* Build the {@link CharacterRunAutomaton} that represents the reindex-from-remote whitelist and make sure that it doesn't whitelist
* the world.
*/ | Build the <code>CharacterRunAutomaton</code> that represents the reindex-from-remote whitelist and make sure that it doesn't whitelist the world | buildRemoteWhitelist | {
"repo_name": "strapdata/elassandra",
"path": "modules/reindex/src/main/java/org/elasticsearch/index/reindex/TransportReindexAction.java",
"license": "apache-2.0",
"size": 23431
} | [
"java.util.List",
"org.apache.lucene.util.automaton.Automata",
"org.apache.lucene.util.automaton.Automaton",
"org.apache.lucene.util.automaton.CharacterRunAutomaton",
"org.apache.lucene.util.automaton.MinimizationOperations",
"org.apache.lucene.util.automaton.Operations",
"org.elasticsearch.common.Strings",
"org.elasticsearch.common.regex.Regex"
] | import java.util.List; import org.apache.lucene.util.automaton.Automata; import org.apache.lucene.util.automaton.Automaton; import org.apache.lucene.util.automaton.CharacterRunAutomaton; import org.apache.lucene.util.automaton.MinimizationOperations; import org.apache.lucene.util.automaton.Operations; import org.elasticsearch.common.Strings; import org.elasticsearch.common.regex.Regex; | import java.util.*; import org.apache.lucene.util.automaton.*; import org.elasticsearch.common.*; import org.elasticsearch.common.regex.*; | [
"java.util",
"org.apache.lucene",
"org.elasticsearch.common"
] | java.util; org.apache.lucene; org.elasticsearch.common; | 1,568,410 |
public String getFullName() throws SQLException {
if (this.fullName == null) {
StringBuffer fullNameBuf = new StringBuffer(getTableName().length()
+ 1 + getName().length());
fullNameBuf.append(this.tableName);
// much faster to append a char than a String
fullNameBuf.append('.');
fullNameBuf.append(this.name);
this.fullName = fullNameBuf.toString();
fullNameBuf = null;
}
return this.fullName;
} | String function() throws SQLException { if (this.fullName == null) { StringBuffer fullNameBuf = new StringBuffer(getTableName().length() + 1 + getName().length()); fullNameBuf.append(this.tableName); fullNameBuf.append('.'); fullNameBuf.append(this.name); this.fullName = fullNameBuf.toString(); fullNameBuf = null; } return this.fullName; } | /**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/ | DOCUMENT ME | getFullName | {
"repo_name": "spullara/mysql-connector-java",
"path": "src/main/java/com/mysql/jdbc/Field.java",
"license": "gpl-2.0",
"size": 28240
} | [
"java.sql.SQLException"
] | import java.sql.SQLException; | import java.sql.*; | [
"java.sql"
] | java.sql; | 1,138,173 |
public HLMarking getContainerHLMarking(){
return item.getContainerHLMarking();
}
| HLMarking function(){ return item.getContainerHLMarking(); } | /**
* Return the encapsulate Low Level API object.
*/ | Return the encapsulate Low Level API object | getContainerHLMarking | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-HLPN/src/fr/lip6/move/pnml/hlpn/strings/hlapi/LessThanOrEqualHLAPI.java",
"license": "epl-1.0",
"size": 108661
} | [
"fr.lip6.move.pnml.hlpn.hlcorestructure.HLMarking"
] | import fr.lip6.move.pnml.hlpn.hlcorestructure.HLMarking; | import fr.lip6.move.pnml.hlpn.hlcorestructure.*; | [
"fr.lip6.move"
] | fr.lip6.move; | 2,815,359 |
public void setActivateOnItemClick(boolean activateOnItemClick) {
// When setting CHOICE_MODE_SINGLE, ListView will automatically
// give items the 'activated' state when touched.
getListView().setChoiceMode(
activateOnItemClick ? AbsListView.CHOICE_MODE_SINGLE
: AbsListView.CHOICE_MODE_NONE);
} | void function(boolean activateOnItemClick) { getListView().setChoiceMode( activateOnItemClick ? AbsListView.CHOICE_MODE_SINGLE : AbsListView.CHOICE_MODE_NONE); } | /**
* Turns on activate-on-click mode. When this mode is on, list items will be
* given the 'activated' state when touched.
*/ | Turns on activate-on-click mode. When this mode is on, list items will be given the 'activated' state when touched | setActivateOnItemClick | {
"repo_name": "usrusr/mapsforge",
"path": "mapsforge-samples-android/src/main/java/org/mapsforge/samples/android/ItemListFragment.java",
"license": "lgpl-3.0",
"size": 6170
} | [
"android.widget.AbsListView"
] | import android.widget.AbsListView; | import android.widget.*; | [
"android.widget"
] | android.widget; | 339,331 |
private byte[] toArray() throws IOException {
try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(byteStream)) {
outputStream.writeInt(this.version);
outputStream.writeByte((byte) (this.errorsOccurred ? 0x80 : 0));
outputStream.writeUTF(this.directory.toString());
outputStream.writeLong(this.createDate.getTime());
outputStream.writeLong(this.lastAccessDate.getTime());
outputStream.writeUTF(this.name);
outputStream.writeUTF(this.displayName);
outputStream.writeShort(this.deletedItemFlags);
outputStream.writeInt(this.minorVersion);
outputStream.flush();
byteStream.flush();
return byteStream.toByteArray();
}
}
public enum DeletedFlags {
TEXT_INDEX(1),
CASE_DB(2),
CASE_DIR(4),
DATA_SOURCES(8),
MANIFEST_FILE_NODES(16);
private final short value;
private DeletedFlags(int value) {
this.value = (short) value;
} | byte[] function() throws IOException { try (ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(byteStream)) { outputStream.writeInt(this.version); outputStream.writeByte((byte) (this.errorsOccurred ? 0x80 : 0)); outputStream.writeUTF(this.directory.toString()); outputStream.writeLong(this.createDate.getTime()); outputStream.writeLong(this.lastAccessDate.getTime()); outputStream.writeUTF(this.name); outputStream.writeUTF(this.displayName); outputStream.writeShort(this.deletedItemFlags); outputStream.writeInt(this.minorVersion); outputStream.flush(); byteStream.flush(); return byteStream.toByteArray(); } } public enum DeletedFlags { TEXT_INDEX(1), CASE_DB(2), CASE_DIR(4), DATA_SOURCES(8), MANIFEST_FILE_NODES(16); private final short value; private DeletedFlags(int value) { this.value = (short) value; } | /**
* Gets the node data as a byte array that can be sent to the coordination
* service.
*
* @return The node data as a byte array.
*
* @throws IOException If there is an error writing the node data to the
* array.
*/ | Gets the node data as a byte array that can be sent to the coordination service | toArray | {
"repo_name": "eugene7646/autopsy",
"path": "Core/src/org/sleuthkit/autopsy/casemodule/multiusercases/CaseNodeData.java",
"license": "apache-2.0",
"size": 18953
} | [
"java.io.ByteArrayOutputStream",
"java.io.DataOutputStream",
"java.io.IOException"
] | import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 2,091,767 |
protected void setReference(Reference reference) {
this.reference = reference;
} | void function(Reference reference) { this.reference = reference; } | /**
* Initializes reference for this context instance. Called by
* {@link RegistryContextFactory#getObjectInstance(Object, Name, Context, Hashtable)}.
*
* @param reference
* Reference for this context instance.
*/ | Initializes reference for this context instance. Called by <code>RegistryContextFactory#getObjectInstance(Object, Name, Context, Hashtable)</code> | setReference | {
"repo_name": "freeVM/freeVM",
"path": "enhanced/archive/classlib/java6/modules/jndi/src/main/java/org/apache/harmony/jndi/provider/rmi/registry/RegistryContext.java",
"license": "apache-2.0",
"size": 25830
} | [
"javax.naming.Reference"
] | import javax.naming.Reference; | import javax.naming.*; | [
"javax.naming"
] | javax.naming; | 2,680,113 |
public static <T> Optional<T> between(String text, String after, String before, Function<String, T> mapper) {
String result = between(text, after, before);
if (result == null) {
return Optional.empty();
} else {
return Optional.ofNullable(mapper.apply(result));
}
} | static <T> Optional<T> function(String text, String after, String before, Function<String, T> mapper) { String result = between(text, after, before); if (result == null) { return Optional.empty(); } else { return Optional.ofNullable(mapper.apply(result)); } } | /**
* Returns an object between the given token
*
* @param text the text
* @param after the before token
* @param before the after token
* @param mapper a mapping function to convert the string between the token to type T
* @return an Optional describing the result of applying a mapping function to the text between the token.
*/ | Returns an object between the given token | between | {
"repo_name": "isavin/camel",
"path": "camel-core/src/main/java/org/apache/camel/util/StringHelper.java",
"license": "apache-2.0",
"size": 22921
} | [
"java.util.Optional",
"java.util.function.Function"
] | import java.util.Optional; import java.util.function.Function; | import java.util.*; import java.util.function.*; | [
"java.util"
] | java.util; | 394,076 |
public void testNotification() {
CombinedDomainXYPlot plot = createPlot();
JFreeChart chart = new JFreeChart(plot);
chart.addChangeListener(this);
XYPlot subplot1 = (XYPlot) plot.getSubplots().get(0);
NumberAxis yAxis = (NumberAxis) subplot1.getRangeAxis();
yAxis.setAutoRangeIncludesZero(!yAxis.getAutoRangeIncludesZero());
assertEquals(1, this.events.size());
// a redraw should NOT trigger another change event
BufferedImage image = new BufferedImage(200, 100,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
this.events.clear();
chart.draw(g2, new Rectangle2D.Double(0.0, 0.0, 200.0, 100.0));
assertTrue(this.events.isEmpty());
} | void function() { CombinedDomainXYPlot plot = createPlot(); JFreeChart chart = new JFreeChart(plot); chart.addChangeListener(this); XYPlot subplot1 = (XYPlot) plot.getSubplots().get(0); NumberAxis yAxis = (NumberAxis) subplot1.getRangeAxis(); yAxis.setAutoRangeIncludesZero(!yAxis.getAutoRangeIncludesZero()); assertEquals(1, this.events.size()); BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = image.createGraphics(); this.events.clear(); chart.draw(g2, new Rectangle2D.Double(0.0, 0.0, 200.0, 100.0)); assertTrue(this.events.isEmpty()); } | /**
* Check that only one chart change event is generated by a change to a
* subplot.
*/ | Check that only one chart change event is generated by a change to a subplot | testNotification | {
"repo_name": "apetresc/JFreeChart",
"path": "src/test/java/org/jfree/chart/plot/junit/CombinedDomainXYPlotTests.java",
"license": "lgpl-2.1",
"size": 10382
} | [
"java.awt.Graphics2D",
"java.awt.geom.Rectangle2D",
"java.awt.image.BufferedImage",
"org.jfree.chart.JFreeChart",
"org.jfree.chart.axis.NumberAxis",
"org.jfree.chart.plot.CombinedDomainXYPlot",
"org.jfree.chart.plot.XYPlot"
] | import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.XYPlot; | import java.awt.*; import java.awt.geom.*; import java.awt.image.*; import org.jfree.chart.*; import org.jfree.chart.axis.*; import org.jfree.chart.plot.*; | [
"java.awt",
"org.jfree.chart"
] | java.awt; org.jfree.chart; | 2,525,531 |
public void testPathQueryCodeGenerationWithInvalidQuery() {
String queryXml = "<query name=\"\" model=\"genomic\" view=\"Gene.primaryIdentifier " +
"Gene.secondaryIdentifier Gene.symbol Gene.name Gene.organism.shortName\"></query>";
// Parse XML to PathQuery - PathQueryBinding
PathQuery pathQuery = PathQueryBinding.unmarshalPathQuery(new StringReader(queryXml),
PathQuery.USERPROFILE_VERSION);
WebserviceCodeGenInfo wsCodeGenInfo = getGenInfo(pathQuery);
// Mock up
pathQuery.clearView();
String expected = testProps.getProperty("invalid.query");
assertEquals(expected, cg.generate(wsCodeGenInfo));
} | void function() { String queryXml = STR\STRgenomic\STRGene.primaryIdentifier STRGene.secondaryIdentifier Gene.symbol Gene.name Gene.organism.shortName\STR; PathQuery pathQuery = PathQueryBinding.unmarshalPathQuery(new StringReader(queryXml), PathQuery.USERPROFILE_VERSION); WebserviceCodeGenInfo wsCodeGenInfo = getGenInfo(pathQuery); pathQuery.clearView(); String expected = testProps.getProperty(STR); assertEquals(expected, cg.generate(wsCodeGenInfo)); } | /**
* This method tests when a path query has no views.
*
* Test PathQuery:
* <query name="" model="genomic" view="Gene.primaryIdentifier Gene.secondaryIdentifier
* Gene.symbol Gene.name Gene.organism.shortName" sortOrder="Gene.primaryIdentifier asc">
* </query>
*
* Views will be removed from the PathQuery object.
*
*/ | This method tests when a path query has no views. Test PathQuery: Views will be removed from the PathQuery object | testPathQueryCodeGenerationWithInvalidQuery | {
"repo_name": "justincc/intermine",
"path": "intermine/api/test/src/org/intermine/api/query/codegen/WebserviceJavaCodeGeneratorTest.java",
"license": "lgpl-2.1",
"size": 43150
} | [
"java.io.StringReader",
"org.intermine.pathquery.PathQuery",
"org.intermine.pathquery.PathQueryBinding"
] | import java.io.StringReader; import org.intermine.pathquery.PathQuery; import org.intermine.pathquery.PathQueryBinding; | import java.io.*; import org.intermine.pathquery.*; | [
"java.io",
"org.intermine.pathquery"
] | java.io; org.intermine.pathquery; | 1,470,348 |
public static List<Entitlement> getServerEntitlements(Long sid) {
List<Entitlement> entitlements = new ArrayList<Entitlement>();
SelectMode m = ModeFactory.getMode("General_queries", "system_entitlements");
Map<String, Object> params = new HashMap<String, Object>();
params.put("sid", sid);
DataResult<Map<String, Object>> dr = makeDataResult(params, null, null, m);
if (dr.isEmpty()) {
return null;
}
Iterator<Map<String, Object>> iter = dr.iterator();
while (iter.hasNext()) {
Map<String, Object> map = iter.next();
String ent = (String) map.get("label");
entitlements.add(EntitlementManager.getByName(ent));
}
return entitlements;
} | static List<Entitlement> function(Long sid) { List<Entitlement> entitlements = new ArrayList<Entitlement>(); SelectMode m = ModeFactory.getMode(STR, STR); Map<String, Object> params = new HashMap<String, Object>(); params.put("sid", sid); DataResult<Map<String, Object>> dr = makeDataResult(params, null, null, m); if (dr.isEmpty()) { return null; } Iterator<Map<String, Object>> iter = dr.iterator(); while (iter.hasNext()) { Map<String, Object> map = iter.next(); String ent = (String) map.get("label"); entitlements.add(EntitlementManager.getByName(ent)); } return entitlements; } | /**
* Returns the entitlements for the given server id.
* @param sid Server id
* @return entitlements - ArrayList of entitlements
*/ | Returns the entitlements for the given server id | getServerEntitlements | {
"repo_name": "renner/spacewalk",
"path": "java/code/src/com/redhat/rhn/manager/system/SystemManager.java",
"license": "gpl-2.0",
"size": 132498
} | [
"com.redhat.rhn.common.db.datasource.DataResult",
"com.redhat.rhn.common.db.datasource.ModeFactory",
"com.redhat.rhn.common.db.datasource.SelectMode",
"com.redhat.rhn.domain.entitlement.Entitlement",
"com.redhat.rhn.manager.entitlement.EntitlementManager",
"java.util.ArrayList",
"java.util.HashMap",
"java.util.Iterator",
"java.util.List",
"java.util.Map"
] | import com.redhat.rhn.common.db.datasource.DataResult; import com.redhat.rhn.common.db.datasource.ModeFactory; import com.redhat.rhn.common.db.datasource.SelectMode; import com.redhat.rhn.domain.entitlement.Entitlement; import com.redhat.rhn.manager.entitlement.EntitlementManager; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; | import com.redhat.rhn.common.db.datasource.*; import com.redhat.rhn.domain.entitlement.*; import com.redhat.rhn.manager.entitlement.*; import java.util.*; | [
"com.redhat.rhn",
"java.util"
] | com.redhat.rhn; java.util; | 1,058,390 |
@Override
public Object endElement(
ParseContext context,
String namespaceURI,
String localName
)
{
return _value;
} | Object function( ParseContext context, String namespaceURI, String localName ) { return _value; } | /**
* Implementation of NodeParser.endElement()
*/ | Implementation of NodeParser.endElement() | endElement | {
"repo_name": "adamrduffy/trinidad-1.0.x",
"path": "trinidad-impl/src/main/java/org/apache/myfaces/trinidadinternal/style/xml/parse/ValueNodeParser.java",
"license": "apache-2.0",
"size": 2120
} | [
"org.apache.myfaces.trinidadinternal.share.xml.ParseContext"
] | import org.apache.myfaces.trinidadinternal.share.xml.ParseContext; | import org.apache.myfaces.trinidadinternal.share.xml.*; | [
"org.apache.myfaces"
] | org.apache.myfaces; | 2,863,425 |
@SuppressLint("SdCardPath")
public static boolean isExternalFileUrl(Context context, String mediaPath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
// Q doesn't allow external files
return false;
}
return mediaPath.startsWith("file://" + QUtil.getExternalStorageDir(context))
|| mediaPath.startsWith("file:///sdcard");
} | @SuppressLint(STR) static boolean function(Context context, String mediaPath) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return false; } return mediaPath.startsWith(STRfile: } | /**
* Tests whether the given path is a URL pointing to an external file.
*
* @param context the Android context to use for determining external paths
* @param mediaPath path to a media file
* @return true if the mediaPath is on external storage, otherwise false
*/ | Tests whether the given path is a URL pointing to an external file | isExternalFileUrl | {
"repo_name": "mit-cml/appinventor-sources",
"path": "appinventor/components/src/com/google/appinventor/components/runtime/util/MediaUtil.java",
"license": "apache-2.0",
"size": 30913
} | [
"android.annotation.SuppressLint",
"android.content.Context",
"android.os.Build"
] | import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; | import android.annotation.*; import android.content.*; import android.os.*; | [
"android.annotation",
"android.content",
"android.os"
] | android.annotation; android.content; android.os; | 1,133,886 |
public static NodeConfig loadNodeConfig(Path solrHome, Properties nodeProperties) {
SolrResourceLoader loader = new SolrResourceLoader(solrHome, null, nodeProperties);
if (!StringUtils.isEmpty(System.getProperty("solr.solrxml.location"))) {
log.warn("Solr property solr.solrxml.location is no longer supported. " +
"Will automatically load solr.xml from ZooKeeper if it exists");
}
String zkHost = System.getProperty("zkHost");
if (!StringUtils.isEmpty(zkHost)) {
try (SolrZkClient zkClient = new SolrZkClient(zkHost, 30000)) {
if (zkClient.exists("/solr.xml", true)) {
log.info("solr.xml found in ZooKeeper. Loading...");
byte[] data = zkClient.getData("/solr.xml", null, null, true);
return SolrXmlConfig.fromInputStream(loader, new ByteArrayInputStream(data));
}
} catch (Exception e) {
throw new SolrException(ErrorCode.SERVER_ERROR, "Error occurred while loading solr.xml from zookeeper", e);
}
log.info("Loading solr.xml from SolrHome (not found in ZooKeeper)");
}
return SolrXmlConfig.fromSolrHome(loader, loader.getInstancePath());
} | static NodeConfig function(Path solrHome, Properties nodeProperties) { SolrResourceLoader loader = new SolrResourceLoader(solrHome, null, nodeProperties); if (!StringUtils.isEmpty(System.getProperty(STR))) { log.warn(STR + STR); } String zkHost = System.getProperty(STR); if (!StringUtils.isEmpty(zkHost)) { try (SolrZkClient zkClient = new SolrZkClient(zkHost, 30000)) { if (zkClient.exists(STR, true)) { log.info(STR); byte[] data = zkClient.getData(STR, null, null, true); return SolrXmlConfig.fromInputStream(loader, new ByteArrayInputStream(data)); } } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, STR, e); } log.info(STR); } return SolrXmlConfig.fromSolrHome(loader, loader.getInstancePath()); } | /**
* Get the NodeConfig whether stored on disk, in ZooKeeper, etc.
* This may also be used by custom filters to load relevant configuration.
* @return the NodeConfig
*/ | Get the NodeConfig whether stored on disk, in ZooKeeper, etc. This may also be used by custom filters to load relevant configuration | loadNodeConfig | {
"repo_name": "PATRIC3/p3_solr",
"path": "solr/core/src/java/org/apache/solr/servlet/SolrDispatchFilter.java",
"license": "apache-2.0",
"size": 10952
} | [
"java.io.ByteArrayInputStream",
"java.nio.file.Path",
"java.util.Properties",
"org.apache.commons.lang.StringUtils",
"org.apache.solr.common.SolrException",
"org.apache.solr.common.cloud.SolrZkClient",
"org.apache.solr.core.NodeConfig",
"org.apache.solr.core.SolrResourceLoader",
"org.apache.solr.core.SolrXmlConfig"
] | import java.io.ByteArrayInputStream; import java.nio.file.Path; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.solr.common.SolrException; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.core.NodeConfig; import org.apache.solr.core.SolrResourceLoader; import org.apache.solr.core.SolrXmlConfig; | import java.io.*; import java.nio.file.*; import java.util.*; import org.apache.commons.lang.*; import org.apache.solr.common.*; import org.apache.solr.common.cloud.*; import org.apache.solr.core.*; | [
"java.io",
"java.nio",
"java.util",
"org.apache.commons",
"org.apache.solr"
] | java.io; java.nio; java.util; org.apache.commons; org.apache.solr; | 1,929,731 |
@Test
@SmallTest
@Feature({"AndroidWebView"})
public void testNullCallbackNullPath() throws Throwable {
mActivityTestRule.loadUrlSync(mTestContainerView.getAwContents(),
mContentsClient.getOnPageFinishedHelper(), TEST_PAGE);
saveWebArchiveAndWaitForUiPost(null, false , null );
} | @Feature({STR}) void function() throws Throwable { mActivityTestRule.loadUrlSync(mTestContainerView.getAwContents(), mContentsClient.getOnPageFinishedHelper(), TEST_PAGE); saveWebArchiveAndWaitForUiPost(null, false , null ); } | /**
* Ensure passing a null callback to saveWebArchive doesn't cause a crash.
*/ | Ensure passing a null callback to saveWebArchive doesn't cause a crash | testNullCallbackNullPath | {
"repo_name": "ric2b/Vivaldi-browser",
"path": "chromium/android_webview/javatests/src/org/chromium/android_webview/test/ArchiveTest.java",
"license": "bsd-3-clause",
"size": 7225
} | [
"org.chromium.base.test.util.Feature"
] | import org.chromium.base.test.util.Feature; | import org.chromium.base.test.util.*; | [
"org.chromium.base"
] | org.chromium.base; | 2,626,651 |
public final AttributeEditorInfo init(BindableDescriptor bindable,
AttributeDescriptor attribute, IAttributeEventProvider eventProvider, Map<String,Object> defaultValues)
{
this.descriptor = attribute;
this.bindable = bindable;
this.eventProvider = eventProvider;
this.attributeEditorInfo = init(defaultValues);
return attributeEditorInfo;
} | final AttributeEditorInfo function(BindableDescriptor bindable, AttributeDescriptor attribute, IAttributeEventProvider eventProvider, Map<String,Object> defaultValues) { this.descriptor = attribute; this.bindable = bindable; this.eventProvider = eventProvider; this.attributeEditorInfo = init(defaultValues); return attributeEditorInfo; } | /**
* Store attribute descriptor in {@link #descriptor}.
*/ | Store attribute descriptor in <code>#descriptor</code> | init | {
"repo_name": "arnaudsj/carrot2",
"path": "workbench/org.carrot2.workbench.core/src/org/carrot2/workbench/editors/AttributeEditorAdapter.java",
"license": "bsd-3-clause",
"size": 3678
} | [
"java.util.Map",
"org.carrot2.util.attribute.AttributeDescriptor",
"org.carrot2.util.attribute.BindableDescriptor"
] | import java.util.Map; import org.carrot2.util.attribute.AttributeDescriptor; import org.carrot2.util.attribute.BindableDescriptor; | import java.util.*; import org.carrot2.util.attribute.*; | [
"java.util",
"org.carrot2.util"
] | java.util; org.carrot2.util; | 2,791,616 |
@ParameterizedTest
@MethodSource("java.util.Locale#getAvailableLocales")
public void testToLocales(final Locale actualLocale) {
assertEquals(actualLocale, LocaleUtils.toLocale(actualLocale));
} | @MethodSource(STR) void function(final Locale actualLocale) { assertEquals(actualLocale, LocaleUtils.toLocale(actualLocale)); } | /**
* Test toLocale(Locale) method.
*/ | Test toLocale(Locale) method | testToLocales | {
"repo_name": "apache/commons-lang",
"path": "src/test/java/org/apache/commons/lang3/LocaleUtilsTest.java",
"license": "apache-2.0",
"size": 22071
} | [
"java.util.Locale",
"org.junit.jupiter.api.Assertions",
"org.junit.jupiter.params.provider.MethodSource"
] | import java.util.Locale; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.params.provider.MethodSource; | import java.util.*; import org.junit.jupiter.api.*; import org.junit.jupiter.params.provider.*; | [
"java.util",
"org.junit.jupiter"
] | java.util; org.junit.jupiter; | 884,620 |
public void setUserAssignmentPersistence(
UserAssignmentPersistence userAssignmentPersistence) {
this.userAssignmentPersistence = userAssignmentPersistence;
} | void function( UserAssignmentPersistence userAssignmentPersistence) { this.userAssignmentPersistence = userAssignmentPersistence; } | /**
* Sets the user assignment persistence.
*
* @param userAssignmentPersistence the user assignment persistence
*/ | Sets the user assignment persistence | setUserAssignmentPersistence | {
"repo_name": "openegovplatform/OEPv2",
"path": "oep-core-processmgt-portlet/docroot/WEB-INF/src/org/oep/core/processmgt/service/base/UserAssignmentServiceBaseImpl.java",
"license": "apache-2.0",
"size": 35783
} | [
"org.oep.core.processmgt.service.persistence.UserAssignmentPersistence"
] | import org.oep.core.processmgt.service.persistence.UserAssignmentPersistence; | import org.oep.core.processmgt.service.persistence.*; | [
"org.oep.core"
] | org.oep.core; | 168,896 |
static Class<?> primitiveClass(Class<?> parm) {
// it is marginally faster to get from the map than call isPrimitive...
//if (!parm.isPrimitive()) return parm;
Class<?> prim = PRIMITIVE_TYPES.get(parm);
return prim == null ? parm : prim;
}
private final Map<MethodKey, Method> methods = new HashMap<MethodKey, Method>();
private final MethodMap methodMap = new MethodMap(); | static Class<?> primitiveClass(Class<?> parm) { Class<?> prim = PRIMITIVE_TYPES.get(parm); return prim == null ? parm : prim; } private final Map<MethodKey, Method> methods = new HashMap<MethodKey, Method>(); private final MethodMap methodMap = new MethodMap(); | /** Converts a primitive type to its corresponding class.
* <p>
* If the argument type is primitive then we want to convert our
* primitive type signature to the corresponding Object type so
* introspection for methods with primitive types will work
* correctly.
* </p>
* @param parm a may-be primitive type class
* @return the equivalent object class
*/ | Converts a primitive type to its corresponding class. If the argument type is primitive then we want to convert our primitive type signature to the corresponding Object type so introspection for methods with primitive types will work correctly. | primitiveClass | {
"repo_name": "InsomniaxGaming/OWHInternals",
"path": "src/org/apache/commons/jexl2/internal/introspection/ClassMap.java",
"license": "gpl-2.0",
"size": 13949
} | [
"java.lang.reflect.Method",
"java.util.HashMap",
"java.util.Map"
] | import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; | import java.lang.reflect.*; import java.util.*; | [
"java.lang",
"java.util"
] | java.lang; java.util; | 157,129 |
void processUpdateQueueForTesting() {
while (!updates.isEmpty()) {
IUpdate update = updates.poll();
if (update != null)
update.dispatch();
}
} | void processUpdateQueueForTesting() { while (!updates.isEmpty()) { IUpdate update = updates.poll(); if (update != null) update.dispatch(); } } | /**
* FOR TESTING ONLY. Dispatch all updates in the update queue until queue is
* empty
*/ | FOR TESTING ONLY. Dispatch all updates in the update queue until queue is empty | processUpdateQueueForTesting | {
"repo_name": "opennetworkinglab/spring-open",
"path": "src/main/java/net/floodlightcontroller/core/internal/Controller.java",
"license": "apache-2.0",
"size": 79816
} | [
"net.floodlightcontroller.core.IUpdate"
] | import net.floodlightcontroller.core.IUpdate; | import net.floodlightcontroller.core.*; | [
"net.floodlightcontroller.core"
] | net.floodlightcontroller.core; | 200,085 |
public void updateSubscriptionPolicy(SubscriptionPolicy policy) throws APIManagementException {
Connection connection = null;
PreparedStatement updateStatement = null;
boolean hasCustomAttrib = false;
String updateQuery;
try {
if(policy.getCustomAttributes() != null){
hasCustomAttrib = true;
}
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_SQL;
if (hasCustomAttrib) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
}
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_BY_UUID_SQL;
if (hasCustomAttrib) {
updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
}
} else {
String errorMsg =
"Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id"
+ " should be provided. Name: " + policy.getPolicyName()
+ ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
log.error(errorMsg);
throw new APIManagementException(errorMsg);
}
connection = APIMgtDBUtil.getConnection();
connection.setAutoCommit(false);
updateStatement = connection.prepareStatement(updateQuery);
if(!StringUtils.isEmpty(policy.getDisplayName())) {
updateStatement.setString(1, policy.getDisplayName());
} else {
updateStatement.setString(1, policy.getPolicyName());
}
updateStatement.setString(2, policy.getDescription());
updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getRequestCount());
updateStatement.setString(5, null);
} else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
updateStatement.setLong(4, limit.getDataAmount());
updateStatement.setString(5, limit.getDataUnit());
}
updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
updateStatement.setInt(8, policy.getRateLimitCount());
updateStatement.setString(9, policy.getRateLimitTimeUnit());
updateStatement.setBoolean(10, policy.isStopOnQuotaReach());
updateStatement.setString(11, policy.getBillingPlan());
if (hasCustomAttrib) {
long lengthOfStream = policy.getCustomAttributes().length;
updateStatement.setBinaryStream(12, new ByteArrayInputStream(policy.getCustomAttributes()),
lengthOfStream);
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement.setString(13, policy.getPolicyName());
updateStatement.setInt(14, policy.getTenantId());
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement.setString(13, policy.getUUID());
}
} else {
if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
updateStatement.setString(12, policy.getPolicyName());
updateStatement.setInt(13, policy.getTenantId());
} else if (!StringUtils.isBlank(policy.getUUID())) {
updateStatement.setString(12, policy.getUUID());
}
}
updateStatement.executeUpdate();
connection.commit();
} catch (SQLException e) {
if (connection != null) {
try {
connection.rollback();
} catch (SQLException ex) {
// Rollback failed. Exception will be thrown later for upper exception
log.error("Failed to rollback the update Subscription Policy: " + policy.toString(), ex);
}
}
handleException(
"Failed to update subscription policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
} finally {
APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
}
} | void function(SubscriptionPolicy policy) throws APIManagementException { Connection connection = null; PreparedStatement updateStatement = null; boolean hasCustomAttrib = false; String updateQuery; try { if(policy.getCustomAttributes() != null){ hasCustomAttrib = true; } if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) { updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_SQL; if (hasCustomAttrib) { updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL; } } else if (!StringUtils.isBlank(policy.getUUID())) { updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_BY_UUID_SQL; if (hasCustomAttrib) { updateQuery = SQLConstants.UPDATE_SUBSCRIPTION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL; } } else { String errorMsg = STR + STR + policy.getPolicyName() + STR + policy.getTenantId() + STR + policy.getUUID(); log.error(errorMsg); throw new APIManagementException(errorMsg); } connection = APIMgtDBUtil.getConnection(); connection.setAutoCommit(false); updateStatement = connection.prepareStatement(updateQuery); if(!StringUtils.isEmpty(policy.getDisplayName())) { updateStatement.setString(1, policy.getDisplayName()); } else { updateStatement.setString(1, policy.getPolicyName()); } updateStatement.setString(2, policy.getDescription()); updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType()); if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) { RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit(); updateStatement.setLong(4, limit.getRequestCount()); updateStatement.setString(5, null); } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) { BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit(); updateStatement.setLong(4, limit.getDataAmount()); updateStatement.setString(5, limit.getDataUnit()); } updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime()); updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit()); updateStatement.setInt(8, policy.getRateLimitCount()); updateStatement.setString(9, policy.getRateLimitTimeUnit()); updateStatement.setBoolean(10, policy.isStopOnQuotaReach()); updateStatement.setString(11, policy.getBillingPlan()); if (hasCustomAttrib) { long lengthOfStream = policy.getCustomAttributes().length; updateStatement.setBinaryStream(12, new ByteArrayInputStream(policy.getCustomAttributes()), lengthOfStream); if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) { updateStatement.setString(13, policy.getPolicyName()); updateStatement.setInt(14, policy.getTenantId()); } else if (!StringUtils.isBlank(policy.getUUID())) { updateStatement.setString(13, policy.getUUID()); } } else { if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) { updateStatement.setString(12, policy.getPolicyName()); updateStatement.setInt(13, policy.getTenantId()); } else if (!StringUtils.isBlank(policy.getUUID())) { updateStatement.setString(12, policy.getUUID()); } } updateStatement.executeUpdate(); connection.commit(); } catch (SQLException e) { if (connection != null) { try { connection.rollback(); } catch (SQLException ex) { log.error(STR + policy.toString(), ex); } } handleException( STR + policy.getPolicyName() + '-' + policy.getTenantId(), e); } finally { APIMgtDBUtil.closeAllConnections(updateStatement, connection, null); } } | /**
* Updates Subscription level policy.
* <p>policy name and tenant id should be specified in <code>policy</code></p>
*
* @param policy updated policy object
* @throws APIManagementException
*/ | Updates Subscription level policy. policy name and tenant id should be specified in <code>policy</code> | updateSubscriptionPolicy | {
"repo_name": "knPerera/carbon-apimgt",
"path": "components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/dao/ApiMgtDAO.java",
"license": "apache-2.0",
"size": 493075
} | [
"java.io.ByteArrayInputStream",
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.SQLException",
"org.apache.commons.lang.StringUtils",
"org.wso2.carbon.apimgt.api.APIManagementException",
"org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit",
"org.wso2.carbon.apimgt.api.model.policy.PolicyConstants",
"org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit",
"org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy",
"org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants",
"org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil"
] | import java.io.ByteArrayInputStream; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.apache.commons.lang.StringUtils; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit; import org.wso2.carbon.apimgt.api.model.policy.PolicyConstants; import org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit; import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy; import org.wso2.carbon.apimgt.impl.dao.constants.SQLConstants; import org.wso2.carbon.apimgt.impl.utils.APIMgtDBUtil; | import java.io.*; import java.sql.*; import org.apache.commons.lang.*; import org.wso2.carbon.apimgt.api.*; import org.wso2.carbon.apimgt.api.model.policy.*; import org.wso2.carbon.apimgt.impl.dao.constants.*; import org.wso2.carbon.apimgt.impl.utils.*; | [
"java.io",
"java.sql",
"org.apache.commons",
"org.wso2.carbon"
] | java.io; java.sql; org.apache.commons; org.wso2.carbon; | 1,052,168 |
private static TextArea findTextAreaText(Container root, String text) {
int count = root.getComponentCount();
for(int iter = 0 ; iter < count ; iter++) {
Component c = root.getComponentAt(iter);
if(c instanceof TextArea) {
String n = ((TextArea)c).getText();
if(n != null && n.equals(text)) {
return (TextArea)c;
}
continue;
}
if(c instanceof Container) {
TextArea l = findTextAreaText((Container)c, text);
if(l != null) {
return l;
}
}
}
return null;
} | static TextArea function(Container root, String text) { int count = root.getComponentCount(); for(int iter = 0 ; iter < count ; iter++) { Component c = root.getComponentAt(iter); if(c instanceof TextArea) { String n = ((TextArea)c).getText(); if(n != null && n.equals(text)) { return (TextArea)c; } continue; } if(c instanceof Container) { TextArea l = findTextAreaText((Container)c, text); if(l != null) { return l; } } } return null; } | /**
* Finds a component with the given name, works even with UI's that weren't created with the GUI builder
* @param text the text of the label/button
* @return the component with the given label text within the tree
*/ | Finds a component with the given name, works even with UI's that weren't created with the GUI builder | findTextAreaText | {
"repo_name": "skyHALud/codenameone",
"path": "CodenameOne/src/com/codename1/testing/TestUtils.java",
"license": "gpl-2.0",
"size": 30397
} | [
"com.codename1.ui.Component",
"com.codename1.ui.Container",
"com.codename1.ui.TextArea"
] | import com.codename1.ui.Component; import com.codename1.ui.Container; import com.codename1.ui.TextArea; | import com.codename1.ui.*; | [
"com.codename1.ui"
] | com.codename1.ui; | 2,199,685 |
public static boolean isSchedulerHostReachable(String connectionUrl, int connectionTimeout) {
boolean isReachable = false;
ReadOnlyScheduler.Client auroraSchedulerClient = null;
try {
// connect to scheduler & run dummy command
auroraSchedulerClient = AuroraSchedulerClientFactory.createReadOnlySchedulerClient(connectionUrl, connectionTimeout);
auroraSchedulerClient.getTierConfigs();
// host is reachable
isReachable = true;
} catch(Exception ex) {
logger.error("Timed-out connecting to URL: " + connectionUrl);
}
return isReachable;
}
| static boolean function(String connectionUrl, int connectionTimeout) { boolean isReachable = false; ReadOnlyScheduler.Client auroraSchedulerClient = null; try { auroraSchedulerClient = AuroraSchedulerClientFactory.createReadOnlySchedulerClient(connectionUrl, connectionTimeout); auroraSchedulerClient.getTierConfigs(); isReachable = true; } catch(Exception ex) { logger.error(STR + connectionUrl); } return isReachable; } | /**
* Checks if is scheduler host reachable.
*
* @param connectionUrl the connection url
* @param connectionTimeout the connection timeout
* @return true, if is scheduler host reachable
*/ | Checks if is scheduler host reachable | isSchedulerHostReachable | {
"repo_name": "machristie/airavata",
"path": "modules/cloud/aurora-client/src/main/java/org/apache/airavata/cloud/aurora/util/AuroraThriftClientUtil.java",
"license": "apache-2.0",
"size": 13907
} | [
"org.apache.airavata.cloud.aurora.client.AuroraSchedulerClientFactory",
"org.apache.airavata.cloud.aurora.client.sdk.ReadOnlyScheduler"
] | import org.apache.airavata.cloud.aurora.client.AuroraSchedulerClientFactory; import org.apache.airavata.cloud.aurora.client.sdk.ReadOnlyScheduler; | import org.apache.airavata.cloud.aurora.client.*; import org.apache.airavata.cloud.aurora.client.sdk.*; | [
"org.apache.airavata"
] | org.apache.airavata; | 464,905 |
public void setColors (Color tint, int start, int end) {
final float color = tint.toFloatBits();
if (vertexData.length == 1) { // only one page...
float[] vertices = vertexData[0];
for (int i = start * 20 + 2, n = end * 20; i < n; i += 5)
vertices[i] = color;
} else {
int pageCount = vertexData.length;
// for each page...
for (int i = 0; i < pageCount; i++) {
float[] vertices = vertexData[i];
// we need to loop through the indices and determine whether the glyph is inside begin/end
for (int j = 0, n = glyphIndices[i].size; j < n; j++) {
int gInd = glyphIndices[i].items[j];
// break early if the glyph is outside our bounds
if (gInd >= end) break;
// if the glyph is inside start and end, then change it's colour
if (gInd >= start) { // && gInd < end
// modify color index
for (int off = 0; off < 20; off += 5)
vertices[off + (j * 20 + 2)] = color;
}
}
}
}
} | void function (Color tint, int start, int end) { final float color = tint.toFloatBits(); if (vertexData.length == 1) { float[] vertices = vertexData[0]; for (int i = start * 20 + 2, n = end * 20; i < n; i += 5) vertices[i] = color; } else { int pageCount = vertexData.length; for (int i = 0; i < pageCount; i++) { float[] vertices = vertexData[i]; for (int j = 0, n = glyphIndices[i].size; j < n; j++) { int gInd = glyphIndices[i].items[j]; if (gInd >= end) break; if (gInd >= start) { for (int off = 0; off < 20; off += 5) vertices[off + (j * 20 + 2)] = color; } } } } } | /** Sets the color of the specified characters. This may only be called after {@link #setText(CharSequence, float, float)} and
* is reset every time setText is called. */ | Sets the color of the specified characters. This may only be called after <code>#setText(CharSequence, float, float)</code> and | setColors | {
"repo_name": "basherone/libgdxcn",
"path": "gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java",
"license": "apache-2.0",
"size": 29914
} | [
"com.badlogic.gdx.graphics.Color"
] | import com.badlogic.gdx.graphics.Color; | import com.badlogic.gdx.graphics.*; | [
"com.badlogic.gdx"
] | com.badlogic.gdx; | 2,250,120 |
public void processIncrementalBlockReport(final DatanodeID nodeID,
final StorageReceivedDeletedBlocks srdb) throws IOException {
assert namesystem.hasWriteLock();
int received = 0;
int deleted = 0;
int receiving = 0;
final DatanodeDescriptor node = datanodeManager.getDatanode(nodeID);
if (node == null || !node.isAlive) {
blockLog
.warn("BLOCK* processIncrementalBlockReport"
+ " is received from dead or unregistered node "
+ nodeID);
throw new IOException(
"Got incremental block report from unregistered or dead node");
}
DatanodeStorageInfo storageInfo =
node.getStorageInfo(srdb.getStorage().getStorageID());
if (storageInfo == null) {
// The DataNode is reporting an unknown storage. Usually the NN learns
// about new storages from heartbeats but during NN restart we may
// receive a block report or incremental report before the heartbeat.
// We must handle this for protocol compatibility. This issue was
// uncovered by HDFS-6094.
storageInfo = node.updateStorage(srdb.getStorage());
}
for (ReceivedDeletedBlockInfo rdbi : srdb.getBlocks()) {
switch (rdbi.getStatus()) {
case DELETED_BLOCK:
removeStoredBlock(rdbi.getBlock(), node);
deleted++;
break;
case RECEIVED_BLOCK:
addBlock(storageInfo, rdbi.getBlock(), rdbi.getDelHints());
received++;
break;
case RECEIVING_BLOCK:
receiving++;
processAndHandleReportedBlock(storageInfo, rdbi.getBlock(),
ReplicaState.RBW, null);
break;
default:
String msg =
"Unknown block status code reported by " + nodeID +
": " + rdbi;
blockLog.warn(msg);
assert false : msg; // if assertions are enabled, throw.
break;
}
if (blockLog.isDebugEnabled()) {
blockLog.debug("BLOCK* block "
+ (rdbi.getStatus()) + ": " + rdbi.getBlock()
+ " is received from " + nodeID);
}
}
if (blockLog.isDebugEnabled()) {
blockLog.debug("*BLOCK* NameNode.processIncrementalBlockReport: " + "from "
+ nodeID + " receiving: " + receiving + ", " + " received: " + received
+ ", " + " deleted: " + deleted);
}
} | void function(final DatanodeID nodeID, final StorageReceivedDeletedBlocks srdb) throws IOException { assert namesystem.hasWriteLock(); int received = 0; int deleted = 0; int receiving = 0; final DatanodeDescriptor node = datanodeManager.getDatanode(nodeID); if (node == null !node.isAlive) { blockLog .warn(STR + STR + nodeID); throw new IOException( STR); } DatanodeStorageInfo storageInfo = node.getStorageInfo(srdb.getStorage().getStorageID()); if (storageInfo == null) { storageInfo = node.updateStorage(srdb.getStorage()); } for (ReceivedDeletedBlockInfo rdbi : srdb.getBlocks()) { switch (rdbi.getStatus()) { case DELETED_BLOCK: removeStoredBlock(rdbi.getBlock(), node); deleted++; break; case RECEIVED_BLOCK: addBlock(storageInfo, rdbi.getBlock(), rdbi.getDelHints()); received++; break; case RECEIVING_BLOCK: receiving++; processAndHandleReportedBlock(storageInfo, rdbi.getBlock(), ReplicaState.RBW, null); break; default: String msg = STR + nodeID + STR + rdbi; blockLog.warn(msg); assert false : msg; break; } if (blockLog.isDebugEnabled()) { blockLog.debug(STR + (rdbi.getStatus()) + STR + rdbi.getBlock() + STR + nodeID); } } if (blockLog.isDebugEnabled()) { blockLog.debug(STR + STR + nodeID + STR + receiving + STR + STR + received + STR + STR + deleted); } } | /**
* The given node is reporting incremental information about some blocks.
* This includes blocks that are starting to be received, completed being
* received, or deleted.
*
* This method must be called with FSNamesystem lock held.
*/ | The given node is reporting incremental information about some blocks. This includes blocks that are starting to be received, completed being received, or deleted. This method must be called with FSNamesystem lock held | processIncrementalBlockReport | {
"repo_name": "HazelChen/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManager.java",
"license": "apache-2.0",
"size": 142814
} | [
"java.io.IOException",
"org.apache.hadoop.hdfs.protocol.DatanodeID",
"org.apache.hadoop.hdfs.server.common.HdfsServerConstants",
"org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo",
"org.apache.hadoop.hdfs.server.protocol.StorageReceivedDeletedBlocks"
] | import java.io.IOException; import org.apache.hadoop.hdfs.protocol.DatanodeID; import org.apache.hadoop.hdfs.server.common.HdfsServerConstants; import org.apache.hadoop.hdfs.server.protocol.ReceivedDeletedBlockInfo; import org.apache.hadoop.hdfs.server.protocol.StorageReceivedDeletedBlocks; | import java.io.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.common.*; import org.apache.hadoop.hdfs.server.protocol.*; | [
"java.io",
"org.apache.hadoop"
] | java.io; org.apache.hadoop; | 2,893,895 |
public void saveModel(File file) throws IOException {
save(new java.util.zip.GZIPOutputStream(
new java.io.FileOutputStream(
file.getCanonicalPath(), false)));
// If we've got an up to date model trained, then save that too,
// in a file with the same name but with .NativePart appended.
// N.B. As models are always stored on the disk anyway, this
// really just involves copying a file to the location given
// by the user.
if (datasetChanged==false && modelTrained)
copyModelFromTempFile(file.getCanonicalPath()+".NativePart");
} | void function(File file) throws IOException { save(new java.util.zip.GZIPOutputStream( new java.io.FileOutputStream( file.getCanonicalPath(), false))); if (datasetChanged==false && modelTrained) copyModelFromTempFile(file.getCanonicalPath()+STR); } | /**
* Saves the state of the engine for reuse at a later time. optionsElement is
* not saved so as to make this code consistent with wekaWrapper. If an
* up-to-date trained model exists, it will be saved in
* <i>file</i>.NativePart.
*/ | Saves the state of the engine for reuse at a later time. optionsElement is not saved so as to make this code consistent with wekaWrapper. If an up-to-date trained model exists, it will be saved in file.NativePart | saveModel | {
"repo_name": "SONIAGroup/S.O.N.I.A.",
"path": "GATE_Developer_8.0/plugins/Machine_Learning/src/gate/creole/ml/svmlight/SVMLightWrapper.java",
"license": "gpl-2.0",
"size": 58593
} | [
"java.io.File",
"java.io.IOException"
] | import java.io.File; import java.io.IOException; | import java.io.*; | [
"java.io"
] | java.io; | 848,671 |
@DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING,
defaultValue = "")
@SimpleProperty
public void ExtraKey(String extraKey) {
this.extraKey = extraKey.trim();
} | @DesignerProperty(editorType = PropertyTypeConstants.PROPERTY_TYPE_STRING, defaultValue = "") void function(String extraKey) { this.extraKey = extraKey.trim(); } | /**
* Specifies the extra key that will be passed to the activity.
* Obsolete. Should use Extras instead
*/ | Specifies the extra key that will be passed to the activity. Obsolete. Should use Extras instead | ExtraKey | {
"repo_name": "youprofit/appinventor-sources",
"path": "appinventor/components/src/com/google/appinventor/components/runtime/ActivityStarter.java",
"license": "apache-2.0",
"size": 19022
} | [
"com.google.appinventor.components.annotations.DesignerProperty",
"com.google.appinventor.components.common.PropertyTypeConstants"
] | import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.common.PropertyTypeConstants; | import com.google.appinventor.components.annotations.*; import com.google.appinventor.components.common.*; | [
"com.google.appinventor"
] | com.google.appinventor; | 2,535,782 |
public void exportDataToFile(String filePath, FinancistoData data, boolean compress) throws IOException {
LOGGER.trace("Initializing data export to file \"{}\".", filePath);
File file = new File(filePath);
if (file.isDirectory())
throw new RuntimeException(String.format("The path \"%s\" corresponds to a directory.", filePath));
if (file.exists()) {
if (!file.delete())
throw new RuntimeException(String.format("The output file \"%s\" already exists an could not be deleted.", filePath));
// Just wait a little for the deletion
while (file.exists())
;
LOGGER.info("Export file \"{}\" already existed and was deleted.", filePath);
}
try (FileOutputStream outputStream = new FileOutputStream(file)) {
this.dataExporter.exportData(data, this.getCompressStream(outputStream, compress));
LOGGER.trace("Data successfully exported to file \"{}\".", filePath);
} catch (UnsupportedEncodingException e) {
LOGGER.error("Error exporting data to file", e);
}
} | void function(String filePath, FinancistoData data, boolean compress) throws IOException { LOGGER.trace(STR{}\".", filePath); File file = new File(filePath); if (file.isDirectory()) throw new RuntimeException(String.format(STR%s\STR, filePath)); if (file.exists()) { if (!file.delete()) throw new RuntimeException(String.format(STR%s\STR, filePath)); while (file.exists()) ; LOGGER.info(STR{}\STR, filePath); } try (FileOutputStream outputStream = new FileOutputStream(file)) { this.dataExporter.exportData(data, this.getCompressStream(outputStream, compress)); LOGGER.trace(STR{}\".", filePath); } catch (UnsupportedEncodingException e) { LOGGER.error(STR, e); } } | /**
* Export Financisto data to file.
*
* @param filePath
* The destiny file path.
* @param data
* The Financisto data to be exported.
* @param compress
* The indication if the file should be compressed.
* @throws IOException
* if an I/O error occurs.
*/ | Export Financisto data to file | exportDataToFile | {
"repo_name": "tdemarchi/financisto-converter",
"path": "financisto-data/src/main/java/br/tkd/financisto/io/exporter/FinancistoFileDataExporter.java",
"license": "gpl-3.0",
"size": 2990
} | [
"br.tkd.financisto.data.FinancistoData",
"java.io.File",
"java.io.FileOutputStream",
"java.io.IOException",
"java.io.UnsupportedEncodingException"
] | import br.tkd.financisto.data.FinancistoData; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; | import br.tkd.financisto.data.*; import java.io.*; | [
"br.tkd.financisto",
"java.io"
] | br.tkd.financisto; java.io; | 651,729 |
public Adapter createLabelStyleAdapter() {
return null;
} | Adapter function() { return null; } | /**
* Creates a new adapter for an object of class '
* {@link org.eclipse.sirius.viewpoint.LabelStyle <em>Label Style</em>}'.
* <!-- begin-user-doc --> This default implementation returns null so that
* we can easily ignore cases; it's useful to ignore a case when inheritance
* will catch all the cases anyway. <!-- end-user-doc -->
*
* @return the new adapter.
* @see org.eclipse.sirius.viewpoint.LabelStyle
* @generated
*/ | Creates a new adapter for an object of class ' <code>org.eclipse.sirius.viewpoint.LabelStyle Label Style</code>'. This default implementation returns null so that we can easily ignore cases; it's useful to ignore a case when inheritance will catch all the cases anyway. | createLabelStyleAdapter | {
"repo_name": "FTSRG/iq-sirius-integration",
"path": "host/org.eclipse.sirius.diagram/src-gen/org/eclipse/sirius/diagram/util/DiagramAdapterFactory.java",
"license": "epl-1.0",
"size": 47245
} | [
"org.eclipse.emf.common.notify.Adapter"
] | import org.eclipse.emf.common.notify.Adapter; | import org.eclipse.emf.common.notify.*; | [
"org.eclipse.emf"
] | org.eclipse.emf; | 2,726,517 |
public InetSocketAddress getDestinationAddress() {
return getLocalAddress(InetSocketAddress.class);
} | InetSocketAddress function() { return getLocalAddress(InetSocketAddress.class); } | /**
* Get the destination address of the Channel.
*
* @return the destination address of the Channel
*/ | Get the destination address of the Channel | getDestinationAddress | {
"repo_name": "rhatlapa/undertow",
"path": "core/src/main/java/io/undertow/server/protocol/framed/AbstractFramedChannel.java",
"license": "apache-2.0",
"size": 36074
} | [
"java.net.InetSocketAddress"
] | import java.net.InetSocketAddress; | import java.net.*; | [
"java.net"
] | java.net; | 2,881,696 |
private static Set<Long> getDeadlockedThreadIds(ThreadMXBean mxBean) {
final long[] deadlockedIds = mxBean.findDeadlockedThreads();
final Set<Long> deadlockedThreadsIds;
if (!F.isEmpty(deadlockedIds)) {
Set<Long> set = new HashSet<>();
for (long id : deadlockedIds)
set.add(id);
deadlockedThreadsIds = Collections.unmodifiableSet(set);
}
else
deadlockedThreadsIds = Collections.emptySet();
return deadlockedThreadsIds;
} | static Set<Long> function(ThreadMXBean mxBean) { final long[] deadlockedIds = mxBean.findDeadlockedThreads(); final Set<Long> deadlockedThreadsIds; if (!F.isEmpty(deadlockedIds)) { Set<Long> set = new HashSet<>(); for (long id : deadlockedIds) set.add(id); deadlockedThreadsIds = Collections.unmodifiableSet(set); } else deadlockedThreadsIds = Collections.emptySet(); return deadlockedThreadsIds; } | /**
* Get deadlocks from the thread bean.
* @param mxBean the bean
* @return the set of deadlocked threads (may be empty Set, but never null).
*/ | Get deadlocks from the thread bean | getDeadlockedThreadIds | {
"repo_name": "apache/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java",
"license": "apache-2.0",
"size": 387878
} | [
"java.lang.management.ThreadMXBean",
"java.util.Collections",
"java.util.HashSet",
"java.util.Set",
"org.apache.ignite.internal.util.typedef.F"
] | import java.lang.management.ThreadMXBean; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.ignite.internal.util.typedef.F; | import java.lang.management.*; import java.util.*; import org.apache.ignite.internal.util.typedef.*; | [
"java.lang",
"java.util",
"org.apache.ignite"
] | java.lang; java.util; org.apache.ignite; | 1,234,666 |
public Location getLocation() {
return location;
} | Location function() { return location; } | /**
* Gets the poi location
*
* @return the poi location
*/ | Gets the poi location | getLocation | {
"repo_name": "Guacamoles/ardroid",
"path": "ardroid/src/main/java/org/arengine/engine/Poi.java",
"license": "mit",
"size": 4751
} | [
"android.location.Location"
] | import android.location.Location; | import android.location.*; | [
"android.location"
] | android.location; | 2,317,981 |
@Test
public void testConcatWholeAndDecThenConvertBigInteger() {
// Given
Money moneyA = new Money.Builder()
.wholeUnit(10)
.decimalUnit(2634)
.build();
Money moneyB = new Money.Builder()
.wholeUnit(30)
.decimalUnit(12)
.build();
BigInteger[] expectedResult = new BigInteger[] {
new BigInteger("4"),
new BigInteger("102634"),
new BigInteger("301200")
};
// When
BigInteger[] result = ConversionTypeUtil
.concatWholeAndDecThenConvertBigInteger(moneyA, moneyB);
// Then
Assert.assertArrayEquals(expectedResult, result);
} | void function() { Money moneyA = new Money.Builder() .wholeUnit(10) .decimalUnit(2634) .build(); Money moneyB = new Money.Builder() .wholeUnit(30) .decimalUnit(12) .build(); BigInteger[] expectedResult = new BigInteger[] { new BigInteger("4"), new BigInteger(STR), new BigInteger(STR) }; BigInteger[] result = ConversionTypeUtil .concatWholeAndDecThenConvertBigInteger(moneyA, moneyB); Assert.assertArrayEquals(expectedResult, result); } | /**
* Test of concatWholeAndDecThenConvertBigInteger method, of class ConversionTypeUtil.
*/ | Test of concatWholeAndDecThenConvertBigInteger method, of class ConversionTypeUtil | testConcatWholeAndDecThenConvertBigInteger | {
"repo_name": "Daytron/daytron-money",
"path": "src/test/java/com/github/daytron/daytronmoney/utility/ConversionTypeUtilTest.java",
"license": "mit",
"size": 2714
} | [
"com.github.daytron.daytronmoney.currency.Money",
"java.math.BigInteger",
"org.junit.Assert"
] | import com.github.daytron.daytronmoney.currency.Money; import java.math.BigInteger; import org.junit.Assert; | import com.github.daytron.daytronmoney.currency.*; import java.math.*; import org.junit.*; | [
"com.github.daytron",
"java.math",
"org.junit"
] | com.github.daytron; java.math; org.junit; | 2,418,828 |
public GlobalProperty getGlobalPropertyByUuid(String uuid) throws APIException;
| GlobalProperty function(String uuid) throws APIException; | /**
* Get a global property by its uuid. There should be only one of these in the database (well,
* in the world actually). If multiple are found, an error is thrown.
*
* @return the global property matching the given uuid
* @should find object given valid uuid
* @should return null if no object found with given uuid
*/ | Get a global property by its uuid. There should be only one of these in the database (well, in the world actually). If multiple are found, an error is thrown | getGlobalPropertyByUuid | {
"repo_name": "kabariyamilind/openMRSDEV",
"path": "api/src/main/java/org/openmrs/api/AdministrationService.java",
"license": "mpl-2.0",
"size": 14586
} | [
"org.openmrs.GlobalProperty"
] | import org.openmrs.GlobalProperty; | import org.openmrs.*; | [
"org.openmrs"
] | org.openmrs; | 432,221 |
@Test
public void testSingleThreadedLocatedFileStatus() throws Throwable {
describe("LocatedFileStatusFetcher operations");
// use the same filter as FileInputFormat; single thread.
listConfig.setInt(LIST_STATUS_NUM_THREADS, 1);
LocatedFileStatusFetcher fetcher =
new LocatedFileStatusFetcher(
listConfig,
new Path[]{basePath},
true,
HIDDEN_FILE_FILTER,
true);
Iterable<FileStatus> stats = fetcher.getFileStatuses();
Assertions.assertThat(stats)
.describedAs("result of located scan")
.flatExtracting(FileStatus::getPath)
.containsExactlyInAnyOrder(
emptyFile,
subdirFile,
subdir2File1,
subdir2File2);
assertListCount(fetcher, EXPECTED_LIST_COUNT);
} | void function() throws Throwable { describe(STR); listConfig.setInt(LIST_STATUS_NUM_THREADS, 1); LocatedFileStatusFetcher fetcher = new LocatedFileStatusFetcher( listConfig, new Path[]{basePath}, true, HIDDEN_FILE_FILTER, true); Iterable<FileStatus> stats = fetcher.getFileStatuses(); Assertions.assertThat(stats) .describedAs(STR) .flatExtracting(FileStatus::getPath) .containsExactlyInAnyOrder( emptyFile, subdirFile, subdir2File1, subdir2File2); assertListCount(fetcher, EXPECTED_LIST_COUNT); } | /**
* Run a located file status fetcher against the directory tree.
*/ | Run a located file status fetcher against the directory tree | testSingleThreadedLocatedFileStatus | {
"repo_name": "JingchengDu/hadoop",
"path": "hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/ITestLocatedFileStatusFetcher.java",
"license": "apache-2.0",
"size": 8143
} | [
"org.apache.hadoop.fs.FileStatus",
"org.apache.hadoop.fs.Path",
"org.apache.hadoop.mapred.LocatedFileStatusFetcher",
"org.assertj.core.api.Assertions"
] | import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.LocatedFileStatusFetcher; import org.assertj.core.api.Assertions; | import org.apache.hadoop.fs.*; import org.apache.hadoop.mapred.*; import org.assertj.core.api.*; | [
"org.apache.hadoop",
"org.assertj.core"
] | org.apache.hadoop; org.assertj.core; | 2,418,530 |
private int[] getChar2Glyph() {
if (char2glyph == null) {
GlyphVector gv = getGlyphVector();
char2glyph = new int[info.length];
Arrays.fill(char2glyph, -1);
// Fill glyph indicies for first characters corresponding to each glyph
int charIndicies[] = gv.getGlyphCharIndices(0, gv.getNumGlyphs(), null);
for (int i=0; i<charIndicies.length; i++) {
char2glyph[charIndicies[i]] = i;
}
// If several characters corresponds to one glyph, create mapping for them
// Suppose that these characters are going all together
int currIndex = 0;
for (int i=0; i<char2glyph.length; i++) {
if (char2glyph[i] < 0) {
char2glyph[i] = currIndex;
} else {
currIndex = char2glyph[i];
}
}
}
return char2glyph;
}
| int[] function() { if (char2glyph == null) { GlyphVector gv = getGlyphVector(); char2glyph = new int[info.length]; Arrays.fill(char2glyph, -1); int charIndicies[] = gv.getGlyphCharIndices(0, gv.getNumGlyphs(), null); for (int i=0; i<charIndicies.length; i++) { char2glyph[charIndicies[i]] = i; } int currIndex = 0; for (int i=0; i<char2glyph.length; i++) { if (char2glyph[i] < 0) { char2glyph[i] = currIndex; } else { currIndex = char2glyph[i]; } } } return char2glyph; } | /**
* Attempts to create mapping of the characters to glyphs in the glyph vector.
* @return array where for each character index stored corresponding glyph index
*/ | Attempts to create mapping of the characters to glyphs in the glyph vector | getChar2Glyph | {
"repo_name": "windwardadmin/android-awt",
"path": "src/main/java/org/apache/harmony/awt/gl/font/TextRunSegmentImpl.java",
"license": "apache-2.0",
"size": 36598
} | [
"java.util.Arrays",
"net.windward.android.awt.font.GlyphVector"
] | import java.util.Arrays; import net.windward.android.awt.font.GlyphVector; | import java.util.*; import net.windward.android.awt.font.*; | [
"java.util",
"net.windward.android"
] | java.util; net.windward.android; | 2,697,301 |
public static <C> ArrayList<C> filterResults(Object r, Class<? super C> restrictionClass) {
return Metadata.hierarchyOf(r).iterDescendantsSelf()//
.<C> filter(restrictionClass).collect(new ArrayList<C>());
} | static <C> ArrayList<C> function(Object r, Class<? super C> restrictionClass) { return Metadata.hierarchyOf(r).iterDescendantsSelf() } | /**
* Return only results of the given restriction class
*
* @param r Starting position
* @param restrictionClass Class restriction
*
* @param <C> Class type
* @return filtered results list
*/ | Return only results of the given restriction class | filterResults | {
"repo_name": "elki-project/elki",
"path": "elki-core/src/main/java/elki/result/ResultUtil.java",
"license": "agpl-3.0",
"size": 4125
} | [
"java.util.ArrayList"
] | import java.util.ArrayList; | import java.util.*; | [
"java.util"
] | java.util; | 206,495 |
public static final void updateMetadata(Context context, String path, JSONObject body, ResponseListener listener, int requestCode) {
JsonRequest.makePutRequest(context, path, body, listener, requestCode);
} | static final void function(Context context, String path, JSONObject body, ResponseListener listener, int requestCode) { JsonRequest.makePutRequest(context, path, body, listener, requestCode); } | /**
* Update the custom metadata of the specified entity.
*
* @param body parameters for the request as JSON object
* @see <a href="https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata">https://m2x.att.com/developer/documentation/v2/device#Update-Device-Metadata</a>
* @see <a href="https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata">https://m2x.att.com/developer/documentation/v2/distribution#Update-Distribution-Metadata</a>
* @see <a href="https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata">https://m2x.att.com/developer/documentation/v2/collections#Update-Collection-Metadata</a>
*/ | Update the custom metadata of the specified entity | updateMetadata | {
"repo_name": "attm2x/m2x-android-test-app",
"path": "api/src/main/java/lateralview/net/attm2xapiv2/model/Metadata.java",
"license": "mit",
"size": 4002
} | [
"android.content.Context",
"org.json.JSONObject"
] | import android.content.Context; import org.json.JSONObject; | import android.content.*; import org.json.*; | [
"android.content",
"org.json"
] | android.content; org.json; | 142,889 |
public void setReplyTimeoutSec(OptionalInt replyTimeoutSec) {
this.replyTimeoutSec = replyTimeoutSec;
} | void function(OptionalInt replyTimeoutSec) { this.replyTimeoutSec = replyTimeoutSec; } | /**
* Allows the NETCONF SSH session replies timeout to be set.
*
* @param replyTimeoutSec value in seconds
*/ | Allows the NETCONF SSH session replies timeout to be set | setReplyTimeoutSec | {
"repo_name": "opennetworkinglab/onos",
"path": "protocols/netconf/api/src/main/java/org/onosproject/netconf/NetconfDeviceInfo.java",
"license": "apache-2.0",
"size": 11661
} | [
"java.util.OptionalInt"
] | import java.util.OptionalInt; | import java.util.*; | [
"java.util"
] | java.util; | 1,253,615 |
CompletableFuture<SchemaVersion> addSchema(SchemaData schema); | CompletableFuture<SchemaVersion> addSchema(SchemaData schema); | /**
* Add a schema to the topic. This will fail if the new schema is incompatible with the current
* schema.
*/ | Add a schema to the topic. This will fail if the new schema is incompatible with the current schema | addSchema | {
"repo_name": "ArvinDevel/incubator-pulsar",
"path": "pulsar-broker/src/main/java/org/apache/pulsar/broker/service/Topic.java",
"license": "apache-2.0",
"size": 5532
} | [
"java.util.concurrent.CompletableFuture",
"org.apache.pulsar.common.schema.SchemaData",
"org.apache.pulsar.common.schema.SchemaVersion"
] | import java.util.concurrent.CompletableFuture; import org.apache.pulsar.common.schema.SchemaData; import org.apache.pulsar.common.schema.SchemaVersion; | import java.util.concurrent.*; import org.apache.pulsar.common.schema.*; | [
"java.util",
"org.apache.pulsar"
] | java.util; org.apache.pulsar; | 2,583,511 |
private void assertNoHUsAssigned()
{
final List<I_M_HU> husAssignedActual = huAssignmentDAO.retrieveTopLevelHUsForModel(record);
final List<I_M_HU> husAssignedExpected = Collections.emptyList();
Assert.assertEquals("Assigned HUs does not match", husAssignedExpected, husAssignedActual);
} | void function() { final List<I_M_HU> husAssignedActual = huAssignmentDAO.retrieveTopLevelHUsForModel(record); final List<I_M_HU> husAssignedExpected = Collections.emptyList(); Assert.assertEquals(STR, husAssignedExpected, husAssignedActual); } | /**
* Assert there are no HUs assigned to {@link #record}.
*/ | Assert there are no HUs assigned to <code>#record</code> | assertNoHUsAssigned | {
"repo_name": "klst-com/metasfresh",
"path": "de.metas.handlingunits.base/src/test/java/de/metas/handlingunits/impl/HUAssignmentBLTest.java",
"license": "gpl-2.0",
"size": 4589
} | [
"java.util.Collections",
"java.util.List",
"org.junit.Assert"
] | import java.util.Collections; import java.util.List; import org.junit.Assert; | import java.util.*; import org.junit.*; | [
"java.util",
"org.junit"
] | java.util; org.junit; | 766,045 |
void balance(PersistentStore store, NodeAVL x, boolean isleft) {
while (true) {
int sign = isleft ? 1
: -1;
switch (x.getBalance(store) * sign) {
case 1 :
x = x.setBalance(store, 0);
return;
case 0 :
x = x.setBalance(store, -sign);
break;
case -1 :
NodeAVL l = x.child(store, isleft);
if (l.getBalance(store) == -sign) {
x.replace(store, this, l);
x = x.set(store, isleft, l.child(store, !isleft));
l = l.set(store, !isleft, x);
x = x.setBalance(store, 0);
l = l.setBalance(store, 0);
} else {
NodeAVL r = l.child(store, !isleft);
x.replace(store, this, r);
l = l.set(store, !isleft, r.child(store, isleft));
r = r.set(store, isleft, l);
x = x.set(store, isleft, r.child(store, !isleft));
r = r.set(store, !isleft, x);
int rb = r.getBalance(store);
x = x.setBalance(store, (rb == -sign) ? sign
: 0);
l = l.setBalance(store, (rb == sign) ? -sign
: 0);
r = r.setBalance(store, 0);
}
return;
}
if (x.isRoot(store)) {
return;
}
isleft = x.isFromLeft(store);
x = x.getParent(store);
}
} | void balance(PersistentStore store, NodeAVL x, boolean isleft) { while (true) { int sign = isleft ? 1 : -1; switch (x.getBalance(store) * sign) { case 1 : x = x.setBalance(store, 0); return; case 0 : x = x.setBalance(store, -sign); break; case -1 : NodeAVL l = x.child(store, isleft); if (l.getBalance(store) == -sign) { x.replace(store, this, l); x = x.set(store, isleft, l.child(store, !isleft)); l = l.set(store, !isleft, x); x = x.setBalance(store, 0); l = l.setBalance(store, 0); } else { NodeAVL r = l.child(store, !isleft); x.replace(store, this, r); l = l.set(store, !isleft, r.child(store, isleft)); r = r.set(store, isleft, l); x = x.set(store, isleft, r.child(store, !isleft)); r = r.set(store, !isleft, x); int rb = r.getBalance(store); x = x.setBalance(store, (rb == -sign) ? sign : 0); l = l.setBalance(store, (rb == sign) ? -sign : 0); r = r.setBalance(store, 0); } return; } if (x.isRoot(store)) { return; } isleft = x.isFromLeft(store); x = x.getParent(store); } } | /**
* Balances part of the tree after an alteration to the index.
*/ | Balances part of the tree after an alteration to the index | balance | {
"repo_name": "RabadanLab/Pegasus",
"path": "resources/hsqldb-2.2.7/hsqldb/src/org/hsqldb/index/IndexAVL.java",
"license": "mit",
"size": 52803
} | [
"org.hsqldb.persist.PersistentStore"
] | import org.hsqldb.persist.PersistentStore; | import org.hsqldb.persist.*; | [
"org.hsqldb.persist"
] | org.hsqldb.persist; | 693,473 |
@SuppressWarnings("unchecked")
protected T parse(String s, GrammarRuleKey rule, Kind descendantToReturn) throws Exception {
Tree node = getParser(rule).parse(s);
checkFullFidelity(node, s);
return (T) getFirstDescendant((EsqlTree) node, descendantToReturn);
}
| @SuppressWarnings(STR) T function(String s, GrammarRuleKey rule, Kind descendantToReturn) throws Exception { Tree node = getParser(rule).parse(s); checkFullFidelity(node, s); return (T) getFirstDescendant((EsqlTree) node, descendantToReturn); } | /**
* Parse the given string and return the first descendant of the given kind.
*
* @param s
* the string to parse
* @param rule
* the rule used to parse the string
* @param descendantToReturn
* the node kind to seek in the generated tree
* @return the node found for the given kind, null if not found.
*/ | Parse the given string and return the first descendant of the given kind | parse | {
"repo_name": "EXXETA/sonar-esql-plugin",
"path": "esql-frontend/src/test/java/com/exxeta/iss/sonar/esql/utils/EsqlTreeModelTest.java",
"license": "apache-2.0",
"size": 4952
} | [
"com.exxeta.iss.sonar.esql.api.tree.Tree",
"com.exxeta.iss.sonar.esql.tree.impl.EsqlTree",
"org.sonar.sslr.grammar.GrammarRuleKey"
] | import com.exxeta.iss.sonar.esql.api.tree.Tree; import com.exxeta.iss.sonar.esql.tree.impl.EsqlTree; import org.sonar.sslr.grammar.GrammarRuleKey; | import com.exxeta.iss.sonar.esql.api.tree.*; import com.exxeta.iss.sonar.esql.tree.impl.*; import org.sonar.sslr.grammar.*; | [
"com.exxeta.iss",
"org.sonar.sslr"
] | com.exxeta.iss; org.sonar.sslr; | 583,507 |
public Set<DirectedEdge> outEdges() {
return new EdgeSetWrapper(outEdges, false);
}
/**
* {@inheritDoc}
| Set<DirectedEdge> function() { return new EdgeSetWrapper(outEdges, false); } /** * {@inheritDoc} | /**
* Returns the set of {@link DirectedEdge} instances that originate from the
* root vertex. Changes to this set will be reflected in this {@link
* EdgeSet} and vice versa.
*/ | Returns the set of <code>DirectedEdge</code> instances that originate from the root vertex. Changes to this set will be reflected in this <code>EdgeSet</code> and vice versa | outEdges | {
"repo_name": "fozziethebeat/S-Space",
"path": "src/main/java/edu/ucla/sspace/graph/SparseDirectedEdgeSet.java",
"license": "gpl-2.0",
"size": 17981
} | [
"java.util.Set"
] | import java.util.Set; | import java.util.*; | [
"java.util"
] | java.util; | 1,983,134 |
public static CConnection get (String apps_host)
{
if (s_cc == null)
{
String attributes = Ini.getProperty (Ini.P_CONNECTION);
if (attributes == null || attributes.length () == 0)
{
//hengsin, zero setup for webstart client
CConnection cc = null;
if (apps_host != null && Adempiere.isWebStartClient() && !CConnection.isServerEmbedded())
{
cc = new CConnection(apps_host);
cc.setConnectionProfile(CConnection.PROFILE_LAN);
cc.setAppsPort(ASFactory.getApplicationServer().getDefaultNamingServicePort());
if (cc.testAppsServer() == null)
{
s_cc = cc;
Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong());
Ini.saveProperties(Ini.isClient());
}
}
if (s_cc == null)
{
if (cc == null) cc = new CConnection(apps_host);
CConnectionDialog ccd = new CConnectionDialog (cc);
s_cc = ccd.getConnection ();
if (!s_cc.isDatabaseOK() && !ccd.isCancel()) {
s_cc.testDatabase(true);
}
// set also in ALogin and Ctrl
Ini.setProperty (Ini.P_CONNECTION, s_cc.toStringLong ());
Ini.saveProperties (Ini.isClient ());
}
}
else
{
s_cc = new CConnection (null);
s_cc.setAttributes (attributes);
}
log.fine(s_cc.toString());
}
return s_cc;
} // get
| static CConnection function (String apps_host) { if (s_cc == null) { String attributes = Ini.getProperty (Ini.P_CONNECTION); if (attributes == null attributes.length () == 0) { CConnection cc = null; if (apps_host != null && Adempiere.isWebStartClient() && !CConnection.isServerEmbedded()) { cc = new CConnection(apps_host); cc.setConnectionProfile(CConnection.PROFILE_LAN); cc.setAppsPort(ASFactory.getApplicationServer().getDefaultNamingServicePort()); if (cc.testAppsServer() == null) { s_cc = cc; Ini.setProperty(Ini.P_CONNECTION, cc.toStringLong()); Ini.saveProperties(Ini.isClient()); } } if (s_cc == null) { if (cc == null) cc = new CConnection(apps_host); CConnectionDialog ccd = new CConnectionDialog (cc); s_cc = ccd.getConnection (); if (!s_cc.isDatabaseOK() && !ccd.isCancel()) { s_cc.testDatabase(true); } Ini.setProperty (Ini.P_CONNECTION, s_cc.toStringLong ()); Ini.saveProperties (Ini.isClient ()); } } else { s_cc = new CConnection (null); s_cc.setAttributes (attributes); } log.fine(s_cc.toString()); } return s_cc; } | /**
* Get/Set default client/server Connection
* @param apps_host optional apps host for new connections
* @return Connection Descriptor
*/ | Get/Set default client/server Connection | get | {
"repo_name": "geneos/adempiere",
"path": "base/src/org/compiere/db/CConnection.java",
"license": "gpl-2.0",
"size": 43587
} | [
"org.adempiere.as.ASFactory",
"org.compiere.Adempiere",
"org.compiere.util.Ini"
] | import org.adempiere.as.ASFactory; import org.compiere.Adempiere; import org.compiere.util.Ini; | import org.adempiere.as.*; import org.compiere.*; import org.compiere.util.*; | [
"org.adempiere.as",
"org.compiere",
"org.compiere.util"
] | org.adempiere.as; org.compiere; org.compiere.util; | 1,751,412 |
private void loadDates() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
HashMap<String, String> dates = new HashMap<>();
try {
String query = "select startdatum,releasedatum from spelprojekt where sid=" + sid;
dates = DB.fetchRow(query);
} catch (InfException e) {
e.getMessage();
}
Date sdate = null;
Date rdate = null;
try {
sdate = sdf.parse(dates.get("STARTDATUM"));
rdate = sdf.parse(dates.get("RELEASEDATUM"));
} catch (ParseException e) {
e.getMessage();
}
startDate = sdate;
releaseDate = rdate;
} | void function() { SimpleDateFormat sdf = new SimpleDateFormat(STR); HashMap<String, String> dates = new HashMap<>(); try { String query = STR + sid; dates = DB.fetchRow(query); } catch (InfException e) { e.getMessage(); } Date sdate = null; Date rdate = null; try { sdate = sdf.parse(dates.get(STR)); rdate = sdf.parse(dates.get(STR)); } catch (ParseException e) { e.getMessage(); } startDate = sdate; releaseDate = rdate; } | /**
* loads the dates from the DB to the view
*/ | loads the dates from the DB to the view | loadDates | {
"repo_name": "DegJ/miceschoolproject",
"path": "MICE/src/mice/spelprojekt/SpelprojektUpdateDate.java",
"license": "apache-2.0",
"size": 9684
} | [
"java.text.ParseException",
"java.text.SimpleDateFormat",
"java.util.Date",
"java.util.HashMap"
] | import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; | import java.text.*; import java.util.*; | [
"java.text",
"java.util"
] | java.text; java.util; | 615,763 |
super.init(objectParam);
int tileIndex = getConfInteger("tile");
int tileSetIndex = getConfInteger("tileSet");
int numberTileSet = getConfInteger("numberTileSet");
// Load picture for each object. Don't use cache cause some picture
// change between jill episod.
this.images
= new Optional[numberTileSet];
for (int index = 0; index < numberTileSet; index++) {
this.images[index]
= this.pictureCache.getImage(tileSetIndex, tileIndex
+ index);
}
// Remove me from list of object (= kill me)
this.killme = new ObjectListMessage(this, false);
this.backgroundObject = objectParam.getBackgroundObject();
if (getWidth() == 0 || getHeight() == 0) {
setWidth(this.images[0].get().getWidth());
setHeight(this.images[0].get().getHeight());
}
}
| super.init(objectParam); int tileIndex = getConfInteger("tile"); int tileSetIndex = getConfInteger(STR); int numberTileSet = getConfInteger(STR); this.images = new Optional[numberTileSet]; for (int index = 0; index < numberTileSet; index++) { this.images[index] = this.pictureCache.getImage(tileSetIndex, tileIndex + index); } this.killme = new ObjectListMessage(this, false); this.backgroundObject = objectParam.getBackgroundObject(); if (getWidth() == 0 getHeight() == 0) { setWidth(this.images[0].get().getWidth()); setHeight(this.images[0].get().getHeight()); } } | /**
* Default constructor.
*
* @param objectParam object parameter
*/ | Default constructor | init | {
"repo_name": "bubulemaster/openjill",
"path": "open-jill-object-background/src/main/java/org/jill/game/entities/obj/FirebirdWeaponManager.java",
"license": "mpl-2.0",
"size": 3798
} | [
"java.util.Optional",
"org.jill.openjill.core.api.message.object.ObjectListMessage"
] | import java.util.Optional; import org.jill.openjill.core.api.message.object.ObjectListMessage; | import java.util.*; import org.jill.openjill.core.api.message.object.*; | [
"java.util",
"org.jill.openjill"
] | java.util; org.jill.openjill; | 2,275,545 |
public TimeValue timeout() {
return timeout;
} | TimeValue function() { return timeout; } | /**
* Gets the timeout to control how long search is allowed to take.
*/ | Gets the timeout to control how long search is allowed to take | timeout | {
"repo_name": "jimczi/elasticsearch",
"path": "core/src/main/java/org/elasticsearch/search/builder/SearchSourceBuilder.java",
"license": "apache-2.0",
"size": 58393
} | [
"org.elasticsearch.common.unit.TimeValue"
] | import org.elasticsearch.common.unit.TimeValue; | import org.elasticsearch.common.unit.*; | [
"org.elasticsearch.common"
] | org.elasticsearch.common; | 2,654,850 |
void activateSynchronizer (long id)
throws InvokeSynchronizerException; | void activateSynchronizer (long id) throws InvokeSynchronizerException; | /**
* Sets a {@link Synchronizer} active and adds it in the executor.
* @param id {@link SynchronizerConf} identifier.
* @throws InvokeSynchronizerException Synchronizer invocation failure.
*/ | Sets a <code>Synchronizer</code> active and adds it in the executor | activateSynchronizer | {
"repo_name": "calogera/DataHubSystem",
"path": "core/src/main/java/fr/gael/dhus/service/ISynchronizerService.java",
"license": "agpl-3.0",
"size": 5742
} | [
"fr.gael.dhus.service.exception.InvokeSynchronizerException"
] | import fr.gael.dhus.service.exception.InvokeSynchronizerException; | import fr.gael.dhus.service.exception.*; | [
"fr.gael.dhus"
] | fr.gael.dhus; | 375,960 |
private int getPermissionId(String permission) throws SQLException {
PreparedStatement loadPermissionsPrepStmt = null;
ResultSet resultSet = null;
Connection connection = null;
int id = -1;
try {
connection = IdentityDatabaseUtil.getUserDBConnection();
loadPermissionsPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.LOAD_UM_PERMISSIONS_W);
loadPermissionsPrepStmt.setString(1, permission.toLowerCase());
resultSet = loadPermissionsPrepStmt.executeQuery();
if (resultSet.next()) {
id = resultSet.getInt(1);
}
} finally {
IdentityDatabaseUtil.closeResultSet(resultSet);
IdentityDatabaseUtil.closeStatement(loadPermissionsPrepStmt);
IdentityDatabaseUtil.closeConnection(connection);
}
return id;
} | int function(String permission) throws SQLException { PreparedStatement loadPermissionsPrepStmt = null; ResultSet resultSet = null; Connection connection = null; int id = -1; try { connection = IdentityDatabaseUtil.getUserDBConnection(); loadPermissionsPrepStmt = connection.prepareStatement(ApplicationMgtDBQueries.LOAD_UM_PERMISSIONS_W); loadPermissionsPrepStmt.setString(1, permission.toLowerCase()); resultSet = loadPermissionsPrepStmt.executeQuery(); if (resultSet.next()) { id = resultSet.getInt(1); } } finally { IdentityDatabaseUtil.closeResultSet(resultSet); IdentityDatabaseUtil.closeStatement(loadPermissionsPrepStmt); IdentityDatabaseUtil.closeConnection(connection); } return id; } | /**
* Get permission id for a given permission path
*
* @param permission Permission path
* @return Permission id
* @throws SQLException
*/ | Get permission id for a given permission path | getPermissionId | {
"repo_name": "nuwandi-is/identity-framework",
"path": "components/application-mgt/org.wso2.carbon.identity.application.mgt/src/main/java/org/wso2/carbon/identity/application/mgt/dao/impl/ApplicationDAOImpl.java",
"license": "apache-2.0",
"size": 141804
} | [
"java.sql.Connection",
"java.sql.PreparedStatement",
"java.sql.ResultSet",
"java.sql.SQLException",
"org.wso2.carbon.identity.application.mgt.ApplicationMgtDBQueries",
"org.wso2.carbon.identity.core.util.IdentityDatabaseUtil"
] | import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.wso2.carbon.identity.application.mgt.ApplicationMgtDBQueries; import org.wso2.carbon.identity.core.util.IdentityDatabaseUtil; | import java.sql.*; import org.wso2.carbon.identity.application.mgt.*; import org.wso2.carbon.identity.core.util.*; | [
"java.sql",
"org.wso2.carbon"
] | java.sql; org.wso2.carbon; | 2,617,925 |
@Test
public void testManualPublishToolNoDescriptorPaths() {
// Manual publish, should fail
ApiClient client = getWebClient(USER_1_USERNAME, testingPostgres);
ContainersApi toolsApi = new ContainersApi(client);
// Manual publish
try {
DockstoreTool tool = manualRegisterAndPublish(toolsApi, "dockstoretestuser", "quayandgithubalternate", "alternate",
"[email protected]:DockstoreTestUser/dockstore-whalesay-alternate.git", "", "", "/testDir/Dockerfile",
DockstoreTool.RegistryEnum.DOCKER_HUB, "master", "latest", true);
fail("Should not be able to publish");
} catch (ApiException e) {
assertTrue(e.getMessage().contains("Repository does not meet requirements to publish"));
}
testBrokenPath();
} | void function() { ApiClient client = getWebClient(USER_1_USERNAME, testingPostgres); ContainersApi toolsApi = new ContainersApi(client); try { DockstoreTool tool = manualRegisterAndPublish(toolsApi, STR, STR, STR, STR, STRSTR/testDir/DockerfileSTRmasterSTRlatestSTRShould not be able to publishSTRRepository does not meet requirements to publish")); } testBrokenPath(); } | /**
* This tests that a tool cannot be manually published if it has no default descriptor paths
* Also tests for entry not found when a broken path is used
*/ | This tests that a tool cannot be manually published if it has no default descriptor paths Also tests for entry not found when a broken path is used | testManualPublishToolNoDescriptorPaths | {
"repo_name": "CancerCollaboratory/dockstore",
"path": "dockstore-integration-testing/src/test/java/io/dockstore/client/cli/BasicIT.java",
"license": "gpl-2.0",
"size": 94045
} | [
"io.swagger.client.ApiClient",
"io.swagger.client.api.ContainersApi",
"io.swagger.client.model.DockstoreTool"
] | import io.swagger.client.ApiClient; import io.swagger.client.api.ContainersApi; import io.swagger.client.model.DockstoreTool; | import io.swagger.client.*; import io.swagger.client.api.*; import io.swagger.client.model.*; | [
"io.swagger.client"
] | io.swagger.client; | 900,206 |
private String saveTR(GluuSAMLTrustRelationship trustRelationship, String metadata, String certificate) {
String inum;
boolean update = false;
synchronized (svnSyncTimer) {
if (StringHelper.isEmpty(trustRelationship.getInum())) {
inum = trustService.generateInumForNewTrustRelationship();
trustRelationship.setInum(inum);
} else {
inum = trustRelationship.getInum();
if(trustRelationship.getSpMetaDataFN() == null )
update=true;
}
boolean updateShib3Configuration = appConfiguration.isConfigGeneration();
switch (trustRelationship.getSpMetaDataSourceType()) {
case GENERATE:
try {
if (StringHelper.isEmpty(certificate))
certificate = generateCertForGeneratedSP(trustRelationship);
GluuStatus status = StringHelper.isNotEmpty(certificate) ? GluuStatus.ACTIVE : GluuStatus.INACTIVE;
trustRelationship.setStatus(status);
if (generateSpMetaDataFile(trustRelationship, certificate)) {
setEntityId(trustRelationship);
} else {
logger.error("Failed to generate SP meta-data file");
return OxTrustConstants.RESULT_FAILURE;
}
} catch (IOException ex) {
logger.error("Failed to download SP certificate", ex);
return OxTrustConstants.RESULT_FAILURE;
}
break;
case FILE:
try {
if (saveSpMetaDataFileSourceTypeFile(trustRelationship, inum, metadata)) {
//update = true;
updateTRCertificate(trustRelationship, certificate);
// setEntityId();
if(!update){
trustRelationship.setStatus(GluuStatus.ACTIVE);
}
} else {
logger.error("Failed to save SP metadata file {}", metadata);
return OxTrustConstants.RESULT_FAILURE;
}
} catch (IOException ex) {
logger.error("Failed to download SP metadata", ex);
//facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to download SP metadata");
return OxTrustConstants.RESULT_FAILURE;
}
break;
case URI:
try {
//if (saveSpMetaDataFileSourceTypeURI()) {
// setEntityId();
boolean result = shibboleth3ConfService.existsResourceUri(trustRelationship.getSpMetaDataURL());
if(result){
saveSpMetaDataFileSourceTypeURI(trustRelationship);
}else{
logger.info("There is no resource found Uri : {}", trustRelationship.getSpMetaDataURL());
}
if(!update){
trustRelationship.setStatus(GluuStatus.ACTIVE);
}
} catch (Exception e) {
//facesMessages.add(FacesMessage.SEVERITY_ERROR, "Unable to download metadata");
return "unable_download_metadata";
}
break;
case FEDERATION:
if(!update){
trustRelationship.setStatus(GluuStatus.ACTIVE);
}
if (trustRelationship.getEntityId() == null) {
//facesMessages.add(FacesMessage.SEVERITY_ERROR, "EntityID must be set to a value");
return "invalid_entity_id";
}
break;
default:
break;
}
trustService.updateReleasedAttributes(trustRelationship);
// We call it from TR validation timer
if (trustRelationship.getSpMetaDataSourceType().equals(GluuMetadataSourceType.GENERATE)
|| (trustRelationship.getSpMetaDataSourceType().equals(GluuMetadataSourceType.FEDERATION))) {
boolean federation = shibboleth3ConfService.isFederation(trustRelationship);
trustRelationship.setFederation(federation);
}
trustContactsAction.saveContacts();
if (update) {
try {
saveTR(trustRelationship, update);
} catch (BaseMappingException ex) {
logger.error("Failed to update trust relationship {}", inum, ex);
return OxTrustConstants.RESULT_FAILURE;
}
} else {
String dn = trustService.getDnForTrustRelationShip(inum);
// Save trustRelationship
trustRelationship.setDn(dn);
try {
saveTR(trustRelationship, update);
} catch (BaseMappingException ex) {
logger.error("Failed to add new trust relationship {}", trustRelationship.getInum(), ex);
return OxTrustConstants.RESULT_FAILURE;
}
update = true;
}
if (updateShib3Configuration) {
List<GluuSAMLTrustRelationship> trustRelationships = trustService.getAllActiveTrustRelationships();
if (!shibboleth3ConfService.generateConfigurationFiles(trustRelationships)) {
logger.error("Failed to update Shibboleth v3 configuration");
return "Failed to update Shibboleth v3 configuration";
} else {
logger.info("Shibboleth v3 configuration updated successfully");
return "Shibboleth v3 configuration updated successfully";
}
}
}
return OxTrustConstants.RESULT_SUCCESS;
}
| String function(GluuSAMLTrustRelationship trustRelationship, String metadata, String certificate) { String inum; boolean update = false; synchronized (svnSyncTimer) { if (StringHelper.isEmpty(trustRelationship.getInum())) { inum = trustService.generateInumForNewTrustRelationship(); trustRelationship.setInum(inum); } else { inum = trustRelationship.getInum(); if(trustRelationship.getSpMetaDataFN() == null ) update=true; } boolean updateShib3Configuration = appConfiguration.isConfigGeneration(); switch (trustRelationship.getSpMetaDataSourceType()) { case GENERATE: try { if (StringHelper.isEmpty(certificate)) certificate = generateCertForGeneratedSP(trustRelationship); GluuStatus status = StringHelper.isNotEmpty(certificate) ? GluuStatus.ACTIVE : GluuStatus.INACTIVE; trustRelationship.setStatus(status); if (generateSpMetaDataFile(trustRelationship, certificate)) { setEntityId(trustRelationship); } else { logger.error(STR); return OxTrustConstants.RESULT_FAILURE; } } catch (IOException ex) { logger.error(STR, ex); return OxTrustConstants.RESULT_FAILURE; } break; case FILE: try { if (saveSpMetaDataFileSourceTypeFile(trustRelationship, inum, metadata)) { updateTRCertificate(trustRelationship, certificate); if(!update){ trustRelationship.setStatus(GluuStatus.ACTIVE); } } else { logger.error(STR, metadata); return OxTrustConstants.RESULT_FAILURE; } } catch (IOException ex) { logger.error(STR, ex); return OxTrustConstants.RESULT_FAILURE; } break; case URI: try { boolean result = shibboleth3ConfService.existsResourceUri(trustRelationship.getSpMetaDataURL()); if(result){ saveSpMetaDataFileSourceTypeURI(trustRelationship); }else{ logger.info(STR, trustRelationship.getSpMetaDataURL()); } if(!update){ trustRelationship.setStatus(GluuStatus.ACTIVE); } } catch (Exception e) { return STR; } break; case FEDERATION: if(!update){ trustRelationship.setStatus(GluuStatus.ACTIVE); } if (trustRelationship.getEntityId() == null) { return STR; } break; default: break; } trustService.updateReleasedAttributes(trustRelationship); if (trustRelationship.getSpMetaDataSourceType().equals(GluuMetadataSourceType.GENERATE) (trustRelationship.getSpMetaDataSourceType().equals(GluuMetadataSourceType.FEDERATION))) { boolean federation = shibboleth3ConfService.isFederation(trustRelationship); trustRelationship.setFederation(federation); } trustContactsAction.saveContacts(); if (update) { try { saveTR(trustRelationship, update); } catch (BaseMappingException ex) { logger.error(STR, inum, ex); return OxTrustConstants.RESULT_FAILURE; } } else { String dn = trustService.getDnForTrustRelationShip(inum); trustRelationship.setDn(dn); try { saveTR(trustRelationship, update); } catch (BaseMappingException ex) { logger.error(STR, trustRelationship.getInum(), ex); return OxTrustConstants.RESULT_FAILURE; } update = true; } if (updateShib3Configuration) { List<GluuSAMLTrustRelationship> trustRelationships = trustService.getAllActiveTrustRelationships(); if (!shibboleth3ConfService.generateConfigurationFiles(trustRelationships)) { logger.error(STR); return STR; } else { logger.info(STR); return STR; } } } return OxTrustConstants.RESULT_SUCCESS; } | /**
* Save SAML TrustRelationship.
*
* @param trustRelationship
* @param metadata - need for FILE type TR only
* @param certificate - need for FILE type TR, optional for GENERATE type TR
* @return
*/ | Save SAML TrustRelationship | saveTR | {
"repo_name": "madumlao/oxTrust",
"path": "server/src/main/java/org/gluu/oxtrust/api/saml/TrustRelationshipWebService.java",
"license": "mit",
"size": 42014
} | [
"java.io.IOException",
"java.util.List",
"org.gluu.oxtrust.model.GluuMetadataSourceType",
"org.gluu.oxtrust.model.GluuSAMLTrustRelationship",
"org.gluu.oxtrust.util.OxTrustConstants",
"org.gluu.persist.exception.mapping.BaseMappingException",
"org.gluu.persist.model.base.GluuStatus",
"org.xdi.util.StringHelper"
] | import java.io.IOException; import java.util.List; import org.gluu.oxtrust.model.GluuMetadataSourceType; import org.gluu.oxtrust.model.GluuSAMLTrustRelationship; import org.gluu.oxtrust.util.OxTrustConstants; import org.gluu.persist.exception.mapping.BaseMappingException; import org.gluu.persist.model.base.GluuStatus; import org.xdi.util.StringHelper; | import java.io.*; import java.util.*; import org.gluu.oxtrust.model.*; import org.gluu.oxtrust.util.*; import org.gluu.persist.exception.mapping.*; import org.gluu.persist.model.base.*; import org.xdi.util.*; | [
"java.io",
"java.util",
"org.gluu.oxtrust",
"org.gluu.persist",
"org.xdi.util"
] | java.io; java.util; org.gluu.oxtrust; org.gluu.persist; org.xdi.util; | 2,056,426 |
protected File getUnusedFile(int tries, String dirPath, String suffix) {
assertNotNull("null dirPath passed to getUnusedFile", dirPath);
assertTrue("negative 'tries' parameter passed to getUnusedFile", tries >= 0);
File dir = new File(dirPath);
assertTrue("dirPath does not exist on client", dir.exists());
assertTrue("dirPath is not a directory on client", dir.isDirectory());
File file = null;
for (int i = 0; i < 5; i++) {
String name = this.getRandomName(null);
assertNotNull(name);
file = new File(dirPath + (dirPath.endsWith("/") ? "" : "/") + name
+ (suffix == null ? "" : "." + suffix));
try {
if (file.createNewFile()) {
return file;
}
} catch (IOException e) {
fail("unexpected exception: " + e.getLocalizedMessage());
}
}
return file;
} | File function(int tries, String dirPath, String suffix) { assertNotNull(STR, dirPath); assertTrue(STR, tries >= 0); File dir = new File(dirPath); assertTrue(STR, dir.exists()); assertTrue(STR, dir.isDirectory()); File file = null; for (int i = 0; i < 5; i++) { String name = this.getRandomName(null); assertNotNull(name); file = new File(dirPath + (dirPath.endsWith("/") ? STR/") + name + (suffix == null ? STR.STRunexpected exception: " + e.getLocalizedMessage()); } } return file; } | /**
* Try "tries" times to get an unused (random) file in dirPath; returns null
* if we can't get one that doesn't already exist. The directory named by
* dirPath must already exist...
*/ | Try "tries" times to get an unused (random) file in dirPath; returns null if we can't get one that doesn't already exist. The directory named by dirPath must already exist.. | getUnusedFile | {
"repo_name": "groboclown/p4ic4idea",
"path": "p4java/src/test/java/com/perforce/p4java/tests/dev/unit/P4JavaTestCase.java",
"license": "apache-2.0",
"size": 107234
} | [
"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; | 2,113,665 |
public MissionItem getMissionItem() {
return mMissionItem;
}
| MissionItem function() { return mMissionItem; } | /**
* Provides access to the mission item instance.
*
* @return {@link com.o3dr.services.android.lib.drone.mission.item.MissionItem} object
*/ | Provides access to the mission item instance | getMissionItem | {
"repo_name": "sai-harish/Tower",
"path": "Android/src/org/droidplanner/android/proxy/mission/item/MissionItemProxy.java",
"license": "gpl-3.0",
"size": 4977
} | [
"com.o3dr.services.android.lib.drone.mission.item.MissionItem"
] | import com.o3dr.services.android.lib.drone.mission.item.MissionItem; | import com.o3dr.services.android.lib.drone.mission.item.*; | [
"com.o3dr.services"
] | com.o3dr.services; | 2,142,838 |
public void memberDeparted(InternalDistributedMember id, boolean crashed) {
if (!crashed)
return;
synchronized (this) {
int kind = id.getVmKind();
switch (kind) {
case DistributionManager.LOCATOR_DM_TYPE:
case DistributionManager.NORMAL_DM_TYPE:
this.crashedApplications++;
break;
default:
break;
}
} // synchronized
} | void function(InternalDistributedMember id, boolean crashed) { if (!crashed) return; synchronized (this) { int kind = id.getVmKind(); switch (kind) { case DistributionManager.LOCATOR_DM_TYPE: case DistributionManager.NORMAL_DM_TYPE: this.crashedApplications++; break; default: break; } } } | /**
* Keeps track of which members depart unexpectedly
*/ | Keeps track of which members depart unexpectedly | memberDeparted | {
"repo_name": "prasi-in/geode",
"path": "geode-core/src/main/java/org/apache/geode/admin/internal/DistributedSystemHealthEvaluator.java",
"license": "apache-2.0",
"size": 5439
} | [
"org.apache.geode.distributed.internal.DistributionManager",
"org.apache.geode.distributed.internal.membership.InternalDistributedMember"
] | import org.apache.geode.distributed.internal.DistributionManager; import org.apache.geode.distributed.internal.membership.InternalDistributedMember; | import org.apache.geode.distributed.internal.*; import org.apache.geode.distributed.internal.membership.*; | [
"org.apache.geode"
] | org.apache.geode; | 1,123,117 |
@After
public void tearDown() {
Ignition.stop(true);
ignite = null;
} | void function() { Ignition.stop(true); ignite = null; } | /**
* Stop the Ignite.
*/ | Stop the Ignite | tearDown | {
"repo_name": "andrey-kuznetsov/ignite",
"path": "modules/ml/src/test/java/org/apache/ignite/ml/genetic/GAGridInitializePopulationTest.java",
"license": "apache-2.0",
"size": 4823
} | [
"org.apache.ignite.Ignition"
] | import org.apache.ignite.Ignition; | import org.apache.ignite.*; | [
"org.apache.ignite"
] | org.apache.ignite; | 2,912,429 |
void store(Connection db) throws SQLException {
store(db, false);
} | void store(Connection db) throws SQLException { store(db, false); } | /**
* Updates the interface information in the configured database. If the
* interface does not exist the a new row in the table is created. If the
* element already exists then it's current row is updated as needed based
* upon the current changes to the node.
*
* @param db
* The database connection used to write the record.
*/ | Updates the interface information in the configured database. If the interface does not exist the a new row in the table is created. If the element already exists then it's current row is updated as needed based upon the current changes to the node | store | {
"repo_name": "vishwaAbhinav/OpenNMS",
"path": "opennms-services/src/main/java/org/opennms/netmgt/capsd/DbIfServiceEntry.java",
"license": "gpl-2.0",
"size": 31245
} | [
"java.sql.Connection",
"java.sql.SQLException"
] | import java.sql.Connection; import java.sql.SQLException; | import java.sql.*; | [
"java.sql"
] | java.sql; | 9,701 |
try {
return new String(bytes, UTF8_CHARSET.name());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Impossible failure: Charset.forName(\"utf-8\") returns invalid name.", e);
}
}
| try { return new String(bytes, UTF8_CHARSET.name()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(STRutf-8\STR, e); } } | /**
* Use this function instead of new String(byte[]) to avoid surprises from non-standard default encodings.
*/ | Use this function instead of new String(byte[]) to avoid surprises from non-standard default encodings | newStringFromBytes | {
"repo_name": "everttigchelaar/camel-svn",
"path": "camel-core/src/main/java/org/apache/camel/util/IOHelper.java",
"license": "apache-2.0",
"size": 5780
} | [
"java.io.UnsupportedEncodingException"
] | import java.io.UnsupportedEncodingException; | import java.io.*; | [
"java.io"
] | java.io; | 2,684,406 |
@ServiceMethod(returns = ReturnType.SINGLE)
private PollerFlux<PollResult<Void>, Void> beginDeleteAsync(
String resourceGroupName, String clusterName, String applicationTypeName, String version, Context context) {
context = this.client.mergeContext(context);
Mono<Response<Flux<ByteBuffer>>> mono =
deleteWithResponseAsync(resourceGroupName, clusterName, applicationTypeName, version, context);
return this
.client
.<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, context);
} | @ServiceMethod(returns = ReturnType.SINGLE) PollerFlux<PollResult<Void>, Void> function( String resourceGroupName, String clusterName, String applicationTypeName, String version, Context context) { context = this.client.mergeContext(context); Mono<Response<Flux<ByteBuffer>>> mono = deleteWithResponseAsync(resourceGroupName, clusterName, applicationTypeName, version, context); return this .client .<Void, Void>getLroResult(mono, this.client.getHttpPipeline(), Void.class, Void.class, context); } | /**
* Delete a Service Fabric application type version resource with the specified name.
*
* @param resourceGroupName The name of the resource group.
* @param clusterName The name of the cluster resource.
* @param applicationTypeName The name of the application type name resource.
* @param version The application type version.
* @param context The context to associate with this operation.
* @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 the completion.
*/ | Delete a Service Fabric application type version resource with the specified name | beginDeleteAsync | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/servicefabric/azure-resourcemanager-servicefabric/src/main/java/com/azure/resourcemanager/servicefabric/implementation/ApplicationTypeVersionsClientImpl.java",
"license": "mit",
"size": 58470
} | [
"com.azure.core.annotation.ReturnType",
"com.azure.core.annotation.ServiceMethod",
"com.azure.core.http.rest.Response",
"com.azure.core.management.polling.PollResult",
"com.azure.core.util.Context",
"com.azure.core.util.polling.PollerFlux",
"java.nio.ByteBuffer"
] | import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.Response; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.PollerFlux; import java.nio.ByteBuffer; | import com.azure.core.annotation.*; import com.azure.core.http.rest.*; import com.azure.core.management.polling.*; import com.azure.core.util.*; import com.azure.core.util.polling.*; import java.nio.*; | [
"com.azure.core",
"java.nio"
] | com.azure.core; java.nio; | 149,941 |
protected void updateTotal(final Parameter _parameter,
final Instance _instance)
throws EFapsException
{
Instance instance;
BigDecimal total = BigDecimal.ZERO;
if (_instance.getType().isKindOf(CISales.BulkPaymentAbstract2PaymentDocument)) {
final PrintQuery print = new PrintQuery(_instance);
final SelectBuilder selInst = SelectBuilder.get()
.linkto(CISales.BulkPaymentAbstract2PaymentDocument.FromAbstractLink).instance();
print.addSelect(selInst);
print.executeWithoutAccessCheck();
instance = print.getSelect(selInst);
} else {
instance = _instance;
}
final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.BulkPayment2PaymentDocument);
attrQueryBldr.addWhereAttrEqValue(CISales.BulkPayment2PaymentDocument.FromLink, instance);
final AttributeQuery attrQuery = attrQueryBldr
.getAttributeQuery(CISales.BulkPayment2PaymentDocument.ToLink);
final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment);
queryBldr.addWhereAttrInQuery(CISales.Payment.TargetDocument, attrQuery);
final MultiPrintQuery multi = queryBldr.getPrint();
multi.addAttribute(CISales.Payment.Amount);
multi.executeWithoutAccessCheck();
while (multi.next()) {
total = total.add(multi.<BigDecimal>getAttribute(CISales.Payment.Amount));
}
final Update update = new Update(instance);
update.add(CISales.BulkPayment.CrossTotal, total);
update.executeWithoutAccessCheck();
} | void function(final Parameter _parameter, final Instance _instance) throws EFapsException { Instance instance; BigDecimal total = BigDecimal.ZERO; if (_instance.getType().isKindOf(CISales.BulkPaymentAbstract2PaymentDocument)) { final PrintQuery print = new PrintQuery(_instance); final SelectBuilder selInst = SelectBuilder.get() .linkto(CISales.BulkPaymentAbstract2PaymentDocument.FromAbstractLink).instance(); print.addSelect(selInst); print.executeWithoutAccessCheck(); instance = print.getSelect(selInst); } else { instance = _instance; } final QueryBuilder attrQueryBldr = new QueryBuilder(CISales.BulkPayment2PaymentDocument); attrQueryBldr.addWhereAttrEqValue(CISales.BulkPayment2PaymentDocument.FromLink, instance); final AttributeQuery attrQuery = attrQueryBldr .getAttributeQuery(CISales.BulkPayment2PaymentDocument.ToLink); final QueryBuilder queryBldr = new QueryBuilder(CISales.Payment); queryBldr.addWhereAttrInQuery(CISales.Payment.TargetDocument, attrQuery); final MultiPrintQuery multi = queryBldr.getPrint(); multi.addAttribute(CISales.Payment.Amount); multi.executeWithoutAccessCheck(); while (multi.next()) { total = total.add(multi.<BigDecimal>getAttribute(CISales.Payment.Amount)); } final Update update = new Update(instance); update.add(CISales.BulkPayment.CrossTotal, total); update.executeWithoutAccessCheck(); } | /**
* Update total.
*
* @param _parameter Parameter as passed by the eFaps API
* @param _instance the instance
* @throws EFapsException on error
*/ | Update total | updateTotal | {
"repo_name": "eFaps/eFapsApp-Sales",
"path": "src/main/efaps/ESJP/org/efaps/esjp/sales/payment/BulkPayment_Base.java",
"license": "apache-2.0",
"size": 17738
} | [
"java.math.BigDecimal",
"org.efaps.admin.event.Parameter",
"org.efaps.db.AttributeQuery",
"org.efaps.db.Instance",
"org.efaps.db.MultiPrintQuery",
"org.efaps.db.PrintQuery",
"org.efaps.db.QueryBuilder",
"org.efaps.db.SelectBuilder",
"org.efaps.db.Update",
"org.efaps.esjp.ci.CISales",
"org.efaps.util.EFapsException"
] | import java.math.BigDecimal; import org.efaps.admin.event.Parameter; import org.efaps.db.AttributeQuery; import org.efaps.db.Instance; import org.efaps.db.MultiPrintQuery; import org.efaps.db.PrintQuery; import org.efaps.db.QueryBuilder; import org.efaps.db.SelectBuilder; import org.efaps.db.Update; import org.efaps.esjp.ci.CISales; import org.efaps.util.EFapsException; | import java.math.*; import org.efaps.admin.event.*; import org.efaps.db.*; import org.efaps.esjp.ci.*; import org.efaps.util.*; | [
"java.math",
"org.efaps.admin",
"org.efaps.db",
"org.efaps.esjp",
"org.efaps.util"
] | java.math; org.efaps.admin; org.efaps.db; org.efaps.esjp; org.efaps.util; | 549,644 |
protected SoapFault createFault(String errorCode, String errorMessage) throws JAXBException, PropertyException {
BankException exception = new BankException();
exception.setCode(errorCode);
exception.setMessage(errorMessage);
QName qName = SoapFault.FAULT_CODE_SERVER;
SoapFault fault = new SoapFault("message", qName);
Element detail = fault.getOrCreateDetail();
JAXBContext context = JAXBContext.newInstance(BankException.class);
DOMResult result = new DOMResult();
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.marshal(
new JAXBElement<BankException>(new QName("http://soap.spring.example.bpm.camunda.com/v1", "bankException"),
BankException.class, exception), result);
detail.appendChild(detail.getOwnerDocument().importNode(result.getNode().getFirstChild(), true));
return fault;
} | SoapFault function(String errorCode, String errorMessage) throws JAXBException, PropertyException { BankException exception = new BankException(); exception.setCode(errorCode); exception.setMessage(errorMessage); QName qName = SoapFault.FAULT_CODE_SERVER; SoapFault fault = new SoapFault(STR, qName); Element detail = fault.getOrCreateDetail(); JAXBContext context = JAXBContext.newInstance(BankException.class); DOMResult result = new DOMResult(); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); marshaller.marshal( new JAXBElement<BankException>(new QName("http: BankException.class, exception), result); detail.appendChild(detail.getOwnerDocument().importNode(result.getNode().getFirstChild(), true)); return fault; } | /**
* construct soap fault
*/ | construct soap fault | createFault | {
"repo_name": "camunda/camunda-bpm-examples",
"path": "servicetask/soap-cxf-service/src/test/java/com/camunda/bpm/example/spring/soap/BankCustomerProcessTest.java",
"license": "apache-2.0",
"size": 11103
} | [
"com.camunda.bpm.example.spring.soap.v1.BankException",
"javax.xml.bind.JAXBContext",
"javax.xml.bind.JAXBElement",
"javax.xml.bind.JAXBException",
"javax.xml.bind.Marshaller",
"javax.xml.bind.PropertyException",
"javax.xml.namespace.QName",
"javax.xml.transform.dom.DOMResult",
"org.apache.cxf.binding.soap.SoapFault",
"org.w3c.dom.Element"
] | import com.camunda.bpm.example.spring.soap.v1.BankException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMResult; import org.apache.cxf.binding.soap.SoapFault; import org.w3c.dom.Element; | import com.camunda.bpm.example.spring.soap.v1.*; import javax.xml.bind.*; import javax.xml.namespace.*; import javax.xml.transform.dom.*; import org.apache.cxf.binding.soap.*; import org.w3c.dom.*; | [
"com.camunda.bpm",
"javax.xml",
"org.apache.cxf",
"org.w3c.dom"
] | com.camunda.bpm; javax.xml; org.apache.cxf; org.w3c.dom; | 2,693,572 |
private synchronized void rotate ()
{
if (logFiles.size () > 0)
{
File f1 = null;
ListIterator lit = null;
// If we reach the file count, ditch the oldest file.
if (logFiles.size () == count)
{
f1 = new File ((String) logFiles.getLast ());
f1.delete ();
lit = logFiles.listIterator (logFiles.size () - 1);
}
// Otherwise, move the oldest to a new location.
else
{
String path = replaceFileNameEscapes (pattern, logFiles.size (),
0, count);
f1 = new File (path);
logFiles.addLast (path);
lit = logFiles.listIterator (logFiles.size () - 1);
}
// Now rotate the files.
while (lit.hasPrevious ())
{
String s = (String) lit.previous ();
File f2 = new File (s);
f2.renameTo (f1);
f1 = f2;
}
}
setOutputStream (createFileStream (pattern, limit, count, append,
0));
// Reset written count.
written = 0;
} | synchronized void function () { if (logFiles.size () > 0) { File f1 = null; ListIterator lit = null; if (logFiles.size () == count) { f1 = new File ((String) logFiles.getLast ()); f1.delete (); lit = logFiles.listIterator (logFiles.size () - 1); } else { String path = replaceFileNameEscapes (pattern, logFiles.size (), 0, count); f1 = new File (path); logFiles.addLast (path); lit = logFiles.listIterator (logFiles.size () - 1); } while (lit.hasPrevious ()) { String s = (String) lit.previous (); File f2 = new File (s); f2.renameTo (f1); f1 = f2; } } setOutputStream (createFileStream (pattern, limit, count, append, 0)); written = 0; } | /**
* Rotates the current log files, possibly removing one if we
* exceed the file count.
*/ | Rotates the current log files, possibly removing one if we exceed the file count | rotate | {
"repo_name": "SanDisk-Open-Source/SSD_Dashboard",
"path": "uefi/gcc/gcc-4.6.3/libjava/classpath/java/util/logging/FileHandler.java",
"license": "gpl-2.0",
"size": 23470
} | [
"java.io.File",
"java.util.ListIterator"
] | import java.io.File; import java.util.ListIterator; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
] | java.io; java.util; | 1,889,499 |
@Override // FsDatasetSpi
public void invalidate(String bpid, Block invalidBlks[]) throws IOException {
final List<String> errors = new ArrayList<String>();
for (int i = 0; i < invalidBlks.length; i++) {
final File f;
final FsVolumeImpl v;
synchronized (this) {
final ReplicaInfo info = volumeMap.get(bpid, invalidBlks[i]);
if (info == null) {
// It is okay if the block is not found -- it may be deleted earlier.
LOG.info("Failed to delete replica " + invalidBlks[i]
+ ": ReplicaInfo not found.");
continue;
}
if (info.getGenerationStamp() != invalidBlks[i].getGenerationStamp()) {
errors.add("Failed to delete replica " + invalidBlks[i]
+ ": GenerationStamp not matched, info=" + info);
continue;
}
f = info.getBlockFile();
v = (FsVolumeImpl)info.getVolume();
if (v == null) {
errors.add("Failed to delete replica " + invalidBlks[i]
+ ". No volume for this replica, file=" + f);
continue;
}
File parent = f.getParentFile();
if (parent == null) {
errors.add("Failed to delete replica " + invalidBlks[i]
+ ". Parent not found for file " + f);
continue;
}
ReplicaInfo removing = volumeMap.remove(bpid, invalidBlks[i]);
addDeletingBlock(bpid, removing.getBlockId());
if (LOG.isDebugEnabled()) {
LOG.debug("Block file " + removing.getBlockFile().getName()
+ " is to be deleted");
}
}
if (v.isTransientStorage()) {
RamDiskReplica replicaInfo =
ramDiskReplicaTracker.getReplica(bpid, invalidBlks[i].getBlockId());
if (replicaInfo != null) {
if (!replicaInfo.getIsPersisted()) {
datanode.getMetrics().incrRamDiskBlocksDeletedBeforeLazyPersisted();
}
ramDiskReplicaTracker.discardReplica(replicaInfo.getBlockPoolId(),
replicaInfo.getBlockId(), true);
}
}
// If a DFSClient has the replica in its cache of short-circuit file
// descriptors (and the client is using ShortCircuitShm), invalidate it.
datanode.getShortCircuitRegistry().processBlockInvalidation(
new ExtendedBlockId(invalidBlks[i].getBlockId(), bpid));
// If the block is cached, start uncaching it.
cacheManager.uncacheBlock(bpid, invalidBlks[i].getBlockId());
// Delete the block asynchronously to make sure we can do it fast enough.
// It's ok to unlink the block file before the uncache operation
// finishes.
try {
asyncDiskService.deleteAsync(v.obtainReference(), f,
FsDatasetUtil.getMetaFile(f, invalidBlks[i].getGenerationStamp()),
new ExtendedBlock(bpid, invalidBlks[i]),
dataStorage.getTrashDirectoryForBlockFile(bpid, f));
} catch (ClosedChannelException e) {
LOG.warn("Volume " + v + " is closed, ignore the deletion task for " +
"block " + invalidBlks[i]);
}
}
if (!errors.isEmpty()) {
StringBuilder b = new StringBuilder("Failed to delete ")
.append(errors.size()).append(" (out of ").append(invalidBlks.length)
.append(") replica(s):");
for(int i = 0; i < errors.size(); i++) {
b.append("\n").append(i).append(") ").append(errors.get(i));
}
throw new IOException(b.toString());
}
} | @Override void function(String bpid, Block invalidBlks[]) throws IOException { final List<String> errors = new ArrayList<String>(); for (int i = 0; i < invalidBlks.length; i++) { final File f; final FsVolumeImpl v; synchronized (this) { final ReplicaInfo info = volumeMap.get(bpid, invalidBlks[i]); if (info == null) { LOG.info(STR + invalidBlks[i] + STR); continue; } if (info.getGenerationStamp() != invalidBlks[i].getGenerationStamp()) { errors.add(STR + invalidBlks[i] + STR + info); continue; } f = info.getBlockFile(); v = (FsVolumeImpl)info.getVolume(); if (v == null) { errors.add(STR + invalidBlks[i] + STR + f); continue; } File parent = f.getParentFile(); if (parent == null) { errors.add(STR + invalidBlks[i] + STR + f); continue; } ReplicaInfo removing = volumeMap.remove(bpid, invalidBlks[i]); addDeletingBlock(bpid, removing.getBlockId()); if (LOG.isDebugEnabled()) { LOG.debug(STR + removing.getBlockFile().getName() + STR); } } if (v.isTransientStorage()) { RamDiskReplica replicaInfo = ramDiskReplicaTracker.getReplica(bpid, invalidBlks[i].getBlockId()); if (replicaInfo != null) { if (!replicaInfo.getIsPersisted()) { datanode.getMetrics().incrRamDiskBlocksDeletedBeforeLazyPersisted(); } ramDiskReplicaTracker.discardReplica(replicaInfo.getBlockPoolId(), replicaInfo.getBlockId(), true); } } datanode.getShortCircuitRegistry().processBlockInvalidation( new ExtendedBlockId(invalidBlks[i].getBlockId(), bpid)); cacheManager.uncacheBlock(bpid, invalidBlks[i].getBlockId()); try { asyncDiskService.deleteAsync(v.obtainReference(), f, FsDatasetUtil.getMetaFile(f, invalidBlks[i].getGenerationStamp()), new ExtendedBlock(bpid, invalidBlks[i]), dataStorage.getTrashDirectoryForBlockFile(bpid, f)); } catch (ClosedChannelException e) { LOG.warn(STR + v + STR + STR + invalidBlks[i]); } } if (!errors.isEmpty()) { StringBuilder b = new StringBuilder(STR) .append(errors.size()).append(STR).append(invalidBlks.length) .append(STR); for(int i = 0; i < errors.size(); i++) { b.append("\n").append(i).append(STR).append(errors.get(i)); } throw new IOException(b.toString()); } } | /**
* We're informed that a block is no longer valid. Delete it.
*/ | We're informed that a block is no longer valid. Delete it | invalidate | {
"repo_name": "MeiSheng/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsDatasetImpl.java",
"license": "apache-2.0",
"size": 112841
} | [
"java.io.File",
"java.io.IOException",
"java.nio.channels.ClosedChannelException",
"java.util.ArrayList",
"java.util.List",
"org.apache.hadoop.hdfs.ExtendedBlockId",
"org.apache.hadoop.hdfs.protocol.Block",
"org.apache.hadoop.hdfs.protocol.ExtendedBlock",
"org.apache.hadoop.hdfs.server.datanode.ReplicaInfo",
"org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.RamDiskReplicaTracker"
] | import java.io.File; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.util.ArrayList; import java.util.List; import org.apache.hadoop.hdfs.ExtendedBlockId; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.server.datanode.ReplicaInfo; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.RamDiskReplicaTracker; | import java.io.*; import java.nio.channels.*; import java.util.*; import org.apache.hadoop.hdfs.*; import org.apache.hadoop.hdfs.protocol.*; import org.apache.hadoop.hdfs.server.datanode.*; import org.apache.hadoop.hdfs.server.datanode.fsdataset.impl.*; | [
"java.io",
"java.nio",
"java.util",
"org.apache.hadoop"
] | java.io; java.nio; java.util; org.apache.hadoop; | 212,750 |
ValueProperties getPortfolioNodeProperties(); | ValueProperties getPortfolioNodeProperties(); | /**
* Returns the maximal property set on portfolio nodes.
*
* @return the property set, not null
*/ | Returns the maximal property set on portfolio nodes | getPortfolioNodeProperties | {
"repo_name": "DevStreet/FinanceAnalytics",
"path": "projects/OG-Engine/src/main/java/com/opengamma/engine/view/helper/AvailableOutput.java",
"license": "apache-2.0",
"size": 1825
} | [
"com.opengamma.engine.value.ValueProperties"
] | import com.opengamma.engine.value.ValueProperties; | import com.opengamma.engine.value.*; | [
"com.opengamma.engine"
] | com.opengamma.engine; | 2,360,615 |
public void set__2(Field<Object> field) {
setField(_2, field);
} | void function(Field<Object> field) { setField(_2, field); } | /**
* Set the <code>_2</code> parameter to the function to be used with a {@link org.jooq.Select} statement
*/ | Set the <code>_2</code> parameter to the function to be used with a <code>org.jooq.Select</code> statement | set__2 | {
"repo_name": "Remper/sociallink",
"path": "alignments/src/main/java/eu/fbk/fm/alignments/index/db/routines/DistanceTaxicab.java",
"license": "apache-2.0",
"size": 2321
} | [
"org.jooq.Field"
] | import org.jooq.Field; | import org.jooq.*; | [
"org.jooq"
] | org.jooq; | 1,711,436 |
Subsets and Splits