method
stringlengths
13
441k
clean_method
stringlengths
7
313k
doc
stringlengths
17
17.3k
comment
stringlengths
3
1.42k
method_name
stringlengths
1
273
extra
dict
imports
list
imports_info
stringlengths
19
34.8k
cluster_imports_info
stringlengths
15
3.66k
libraries
list
libraries_info
stringlengths
6
661
id
int64
0
2.92M
private void ackSecurity() { assert log != null; U.quietAndInfo(log, "Security status [authentication=" + onOff(ctx.security().enabled()) + ", tls/ssl=" + onOff(ctx.config().getSslContextFactory() != null) + ']'); }
void function() { assert log != null; U.quietAndInfo(log, STR + onOff(ctx.security().enabled()) + STR + onOff(ctx.config().getSslContextFactory() != null) + ']'); }
/** * Prints security status. */
Prints security status
ackSecurity
{ "repo_name": "VladimirErshov/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/IgniteKernal.java", "license": "apache-2.0", "size": 111511 }
[ "org.apache.ignite.internal.util.typedef.internal.U" ]
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.internal.util.typedef.internal.*;
[ "org.apache.ignite" ]
org.apache.ignite;
155,521
public Integer getOneCentCount() { return (financialDocumentOneCentAmount == null) ? new Integer(0) : new Integer(financialDocumentOneCentAmount.divide(KFSConstants.CoinTypeAmounts.ONE_CENT_AMOUNT).intValue()); }
Integer function() { return (financialDocumentOneCentAmount == null) ? new Integer(0) : new Integer(financialDocumentOneCentAmount.divide(KFSConstants.CoinTypeAmounts.ONE_CENT_AMOUNT).intValue()); }
/** * Returns the number of pennies in the drawer * * @return the count of pennies in the drawer */
Returns the number of pennies in the drawer
getOneCentCount
{ "repo_name": "ua-eas/kfs-devops-automation-fork", "path": "kfs-core/src/main/java/org/kuali/kfs/fp/businessobject/CoinDetail.java", "license": "agpl-3.0", "size": 28331 }
[ "org.kuali.kfs.sys.KFSConstants" ]
import org.kuali.kfs.sys.KFSConstants;
import org.kuali.kfs.sys.*;
[ "org.kuali.kfs" ]
org.kuali.kfs;
2,174,973
@Override protected void processResourceCharacteristicsRequest(SimEvent ev) { setDatacenterCharacteristicsList(new HashMap<>()); Log.printLine(CloudSim.clock() + ": " + getName() + ": Cloud Resource List received with " + getDatacenterIdsList().size() + " resource(s)"); for (Integer datacenterId : getDatacenterIdsList()) { sendNow(datacenterId, CloudSimTags.RESOURCE_CHARACTERISTICS, getId()); } }
void function(SimEvent ev) { setDatacenterCharacteristicsList(new HashMap<>()); Log.printLine(CloudSim.clock() + STR + getName() + STR + getDatacenterIdsList().size() + STR); for (Integer datacenterId : getDatacenterIdsList()) { sendNow(datacenterId, CloudSimTags.RESOURCE_CHARACTERISTICS, getId()); } }
/** * Process a request for the characteristics of a PowerDatacenter. * * @param ev a SimEvent object * @pre ev != $null * @post $none */
Process a request for the characteristics of a PowerDatacenter
processResourceCharacteristicsRequest
{ "repo_name": "WorkflowSim/WorkflowSim-1.0", "path": "sources/org/workflowsim/WorkflowScheduler.java", "license": "lgpl-3.0", "size": 12847 }
[ "java.util.HashMap", "org.cloudbus.cloudsim.Log", "org.cloudbus.cloudsim.core.CloudSim", "org.cloudbus.cloudsim.core.CloudSimTags", "org.cloudbus.cloudsim.core.SimEvent" ]
import java.util.HashMap; import org.cloudbus.cloudsim.Log; import org.cloudbus.cloudsim.core.CloudSim; import org.cloudbus.cloudsim.core.CloudSimTags; import org.cloudbus.cloudsim.core.SimEvent;
import java.util.*; import org.cloudbus.cloudsim.*; import org.cloudbus.cloudsim.core.*;
[ "java.util", "org.cloudbus.cloudsim" ]
java.util; org.cloudbus.cloudsim;
1,653,495
public Collection<File> getCreatedFiles() { return createdFiles; }
Collection<File> function() { return createdFiles; }
/** * Return the set of created files. * * @return Files which have been created */
Return the set of created files
getCreatedFiles
{ "repo_name": "pimtegelaar/commons-io-test3", "path": "src/test/java/org/apache/commons/io/monitor/CollectionFileListener.java", "license": "apache-2.0", "size": 5168 }
[ "java.io.File", "java.util.Collection" ]
import java.io.File; import java.util.Collection;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
195,727
public Class<?> getOutputValueClass() { return getClass(JobContext.OUTPUT_VALUE_CLASS, Text.class, Object.class); }
Class<?> function() { return getClass(JobContext.OUTPUT_VALUE_CLASS, Text.class, Object.class); }
/** * Get the value class for job outputs. * * @return the value class for job outputs. */
Get the value class for job outputs
getOutputValueClass
{ "repo_name": "JingchengDu/hadoop", "path": "hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java", "license": "apache-2.0", "size": 77430 }
[ "org.apache.hadoop.io.Text" ]
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.*;
[ "org.apache.hadoop" ]
org.apache.hadoop;
2,367,964
@Override public SimulationPackage.GUIScreenplayArguments clone() { try { { // CC-XJC Version 2.0.1 Build 2012-03-02T12:09:12+0000 final SimulationPackage.GUIScreenplayArguments clone = ((SimulationPackage.GUIScreenplayArguments) super.clone()); return clone; } } catch (CloneNotSupportedException e) { // Please report this at https://apps.sourceforge.net/mantisbt/ccxjc/ throw new AssertionError(e); } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "priceCurveDuration", "chosenPriceCurve" }) public static class StaticScreenplayArguments implements Cloneable { @XmlElement(name = "PriceCurveDuration") protected long priceCurveDuration; @XmlElement(name = "ChosenPriceCurve") protected int chosenPriceCurve; public StaticScreenplayArguments() { // CC-XJC Version 2.0.1 Build 2012-03-02T12:09:12+0000 super(); } public StaticScreenplayArguments(final SimulationPackage.StaticScreenplayArguments o) { // CC-XJC Version 2.0.1 Build 2012-03-02T12:09:12+0000 super(); if (o == null) { throw new NullPointerException("Cannot create a copy of 'StaticScreenplayArguments' from 'null'."); } // CBuiltinLeafInfo: java.lang.Long this.priceCurveDuration = o.getPriceCurveDuration(); // CBuiltinLeafInfo: java.lang.Integer this.chosenPriceCurve = o.getChosenPriceCurve(); }
SimulationPackage.GUIScreenplayArguments function() { try { { final SimulationPackage.GUIScreenplayArguments clone = ((SimulationPackage.GUIScreenplayArguments) super.clone()); return clone; } } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = STRpriceCurveDurationSTRchosenPriceCurveSTRPriceCurveDurationSTRChosenPriceCurveSTRCannot create a copy of 'StaticScreenplayArguments' from 'null'."); } this.priceCurveDuration = o.getPriceCurveDuration(); this.chosenPriceCurve = o.getChosenPriceCurve(); }
/** * Creates and returns a deep copy of this object. * * * @return * A deep copy of this object. */
Creates and returns a deep copy of this object
clone
{ "repo_name": "organicsmarthome/OSHv4", "path": "source/osh_sim_builder/src/constructsimulation/SimulationPackage.java", "license": "gpl-3.0", "size": 36354 }
[ "javax.xml.bind.annotation.XmlAccessType", "javax.xml.bind.annotation.XmlAccessorType", "javax.xml.bind.annotation.XmlType" ]
import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.*;
[ "javax.xml" ]
javax.xml;
2,629,140
@VisibleForTesting public CompletableFuture<Collection<TaskManagerLocation>> calculatePreferredLocations(LocationPreferenceConstraint locationPreferenceConstraint) { final Collection<CompletableFuture<TaskManagerLocation>> preferredLocationFutures = getVertex().getPreferredLocations(); final CompletableFuture<Collection<TaskManagerLocation>> preferredLocationsFuture; switch(locationPreferenceConstraint) { case ALL: preferredLocationsFuture = FutureUtils.combineAll(preferredLocationFutures); break; case ANY: final ArrayList<TaskManagerLocation> completedTaskManagerLocations = new ArrayList<>(preferredLocationFutures.size()); for (CompletableFuture<TaskManagerLocation> preferredLocationFuture : preferredLocationFutures) { if (preferredLocationFuture.isDone() && !preferredLocationFuture.isCompletedExceptionally()) { final TaskManagerLocation taskManagerLocation = preferredLocationFuture.getNow(null); if (taskManagerLocation == null) { throw new FlinkRuntimeException("TaskManagerLocationFuture was completed with null. This indicates a programming bug."); } completedTaskManagerLocations.add(taskManagerLocation); } } preferredLocationsFuture = CompletableFuture.completedFuture(completedTaskManagerLocations); break; default: throw new RuntimeException("Unknown LocationPreferenceConstraint " + locationPreferenceConstraint + '.'); } return preferredLocationsFuture; }
CompletableFuture<Collection<TaskManagerLocation>> function(LocationPreferenceConstraint locationPreferenceConstraint) { final Collection<CompletableFuture<TaskManagerLocation>> preferredLocationFutures = getVertex().getPreferredLocations(); final CompletableFuture<Collection<TaskManagerLocation>> preferredLocationsFuture; switch(locationPreferenceConstraint) { case ALL: preferredLocationsFuture = FutureUtils.combineAll(preferredLocationFutures); break; case ANY: final ArrayList<TaskManagerLocation> completedTaskManagerLocations = new ArrayList<>(preferredLocationFutures.size()); for (CompletableFuture<TaskManagerLocation> preferredLocationFuture : preferredLocationFutures) { if (preferredLocationFuture.isDone() && !preferredLocationFuture.isCompletedExceptionally()) { final TaskManagerLocation taskManagerLocation = preferredLocationFuture.getNow(null); if (taskManagerLocation == null) { throw new FlinkRuntimeException(STR); } completedTaskManagerLocations.add(taskManagerLocation); } } preferredLocationsFuture = CompletableFuture.completedFuture(completedTaskManagerLocations); break; default: throw new RuntimeException(STR + locationPreferenceConstraint + '.'); } return preferredLocationsFuture; }
/** * Calculates the preferred locations based on the location preference constraint. * * @param locationPreferenceConstraint constraint for the location preference * @return Future containing the collection of preferred locations. This might not be completed if not all inputs * have been a resource assigned. */
Calculates the preferred locations based on the location preference constraint
calculatePreferredLocations
{ "repo_name": "fhueske/flink", "path": "flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/Execution.java", "license": "apache-2.0", "size": 60613 }
[ "java.util.ArrayList", "java.util.Collection", "java.util.concurrent.CompletableFuture", "org.apache.flink.runtime.concurrent.FutureUtils", "org.apache.flink.runtime.jobmanager.scheduler.LocationPreferenceConstraint", "org.apache.flink.runtime.taskmanager.TaskManagerLocation", "org.apache.flink.util.FlinkRuntimeException" ]
import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.CompletableFuture; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.jobmanager.scheduler.LocationPreferenceConstraint; import org.apache.flink.runtime.taskmanager.TaskManagerLocation; import org.apache.flink.util.FlinkRuntimeException;
import java.util.*; import java.util.concurrent.*; import org.apache.flink.runtime.concurrent.*; import org.apache.flink.runtime.jobmanager.scheduler.*; import org.apache.flink.runtime.taskmanager.*; import org.apache.flink.util.*;
[ "java.util", "org.apache.flink" ]
java.util; org.apache.flink;
1,016,658
public int evalBoolean(QueryContext context) throws SQLException { _subselect.evaluate(context); return TRUE; }
int function(QueryContext context) throws SQLException { _subselect.evaluate(context); return TRUE; }
/** * Evaluates the expression as a boolean. * * @param rows the current database tuple * * @return the string value */
Evaluates the expression as a boolean
evalBoolean
{ "repo_name": "dlitz/resin", "path": "modules/resin/src/com/caucho/db/sql/ExistsEvalExpr.java", "license": "gpl-2.0", "size": 2326 }
[ "java.sql.SQLException" ]
import java.sql.SQLException;
import java.sql.*;
[ "java.sql" ]
java.sql;
1,626,786
public ToolBar getControl() { return toolBar; }
ToolBar function() { return toolBar; }
/** * Returns the tool bar control for this manager. * * @return the tool bar control, or <code>null</code> if none (before * creating or after disposal) */
Returns the tool bar control for this manager
getControl
{ "repo_name": "neelance/jface4ruby", "path": "jface4ruby/src/org/eclipse/jface/action/ToolBarManager.java", "license": "epl-1.0", "size": 13694 }
[ "org.eclipse.swt.widgets.ToolBar" ]
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.*;
[ "org.eclipse.swt" ]
org.eclipse.swt;
1,444,900
static URL getAzureAsyncOperationUrl(HttpHeaders headers, ClientLogger logger) { return getUrl("Azure-AsyncOperation", headers, logger, false); }
static URL getAzureAsyncOperationUrl(HttpHeaders headers, ClientLogger logger) { return getUrl(STR, headers, logger, false); }
/** * Gets value of Azure-AsyncOperation header from the given Http headers. * * @param headers the Http headers * @param logger the logger * @return the Azure-AsyncOperation header value if exists, null otherwise */
Gets value of Azure-AsyncOperation header from the given Http headers
getAzureAsyncOperationUrl
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/core/azure-core-management/src/main/java/com/azure/core/management/implementation/polling/Util.java", "license": "mit", "size": 3629 }
[ "com.azure.core.http.HttpHeaders", "com.azure.core.util.logging.ClientLogger" ]
import com.azure.core.http.HttpHeaders; import com.azure.core.util.logging.ClientLogger;
import com.azure.core.http.*; import com.azure.core.util.logging.*;
[ "com.azure.core" ]
com.azure.core;
1,926,448
public List<List<String>> getTailoring() { return tailoring == null ? DEFAULT_TAILORING : tailoring; }
List<List<String>> function() { return tailoring == null ? DEFAULT_TAILORING : tailoring; }
/** * Defines the tailoring as multiple service combinations. * * @return A list of service combinations. For each combination, sessions will be created * automatically. Default is {@code [[ all ]]}. */
Defines the tailoring as multiple service combinations
getTailoring
{ "repo_name": "ContinuITy-Project/ContinuITy", "path": "continuity.lib.api/src/main/java/org/continuity/api/entities/config/cobra/CobraConfiguration.java", "license": "apache-2.0", "size": 4927 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
439,969
@Test() public void testErrorConditions() throws Exception { // Create a directory instance with an initial set of data that doesn't have // any unique attribute conflicts. final InMemoryDirectoryServerConfig cfg = new InMemoryDirectoryServerConfig("dc=example,dc=com"); final InMemoryDirectoryServer ds = new InMemoryDirectoryServer(cfg); ds.startListening(); final LDAPConnection conn = ds.getConnection(); conn.add( "dn: dc=example,dc=com", "objectClass: top", "objectClass: domain", "dc: example"); conn.close(); // Shut down the server and try to use the tool when it can't establish a // connection. ds.shutDown(true); IdentifyUniqueAttributeConflicts tool = new IdentifyUniqueAttributeConflicts(null, null); ResultCode resultCode = tool.runTool( "--port", String.valueOf(ds.getListenPort()), "--baseDN", "dc=example,dc=com", "--attribute", "member"); assertFalse(resultCode == ResultCode.SUCCESS); // Start the server and try to use the tool with invalid bind credentials. ds.startListening(); tool = new IdentifyUniqueAttributeConflicts(null, null); resultCode = tool.runTool( "--port", String.valueOf(ds.getListenPort()), "--bindDN", "cn=invalid", "--bindPassword", "invalid", "--baseDN", "dc=missing,dc=com", "--attribute", "member"); assertFalse(resultCode == ResultCode.SUCCESS); // Try to use the tool with a base DN that doesn't exist. ds.startListening(); tool = new IdentifyUniqueAttributeConflicts(null, null); resultCode = tool.runTool( "--port", String.valueOf(ds.getListenPort()), "--baseDN", "dc=missing,dc=com", "--attribute", "member"); assertFalse(resultCode == ResultCode.SUCCESS); ds.shutDown(true); }
@Test() void function() throws Exception { final InMemoryDirectoryServerConfig cfg = new InMemoryDirectoryServerConfig(STR); final InMemoryDirectoryServer ds = new InMemoryDirectoryServer(cfg); ds.startListening(); final LDAPConnection conn = ds.getConnection(); conn.add( STR, STR, STR, STR); conn.close(); ds.shutDown(true); IdentifyUniqueAttributeConflicts tool = new IdentifyUniqueAttributeConflicts(null, null); ResultCode resultCode = tool.runTool( STR, String.valueOf(ds.getListenPort()), STR, STR, STR, STR); assertFalse(resultCode == ResultCode.SUCCESS); ds.startListening(); tool = new IdentifyUniqueAttributeConflicts(null, null); resultCode = tool.runTool( STR, String.valueOf(ds.getListenPort()), STR, STR, STR, STR, STR, STR, STR, STR); assertFalse(resultCode == ResultCode.SUCCESS); ds.startListening(); tool = new IdentifyUniqueAttributeConflicts(null, null); resultCode = tool.runTool( STR, String.valueOf(ds.getListenPort()), STR, STR, STR, STR); assertFalse(resultCode == ResultCode.SUCCESS); ds.shutDown(true); }
/** * Tests for a number of error conditions. * * @throws Exception If an unexpected problem occurs. */
Tests for a number of error conditions
testErrorConditions
{ "repo_name": "UnboundID/ldapsdk", "path": "tests/unit/src/com/unboundid/ldap/sdk/examples/IdentifyUniqueAttributeConflictsTestCase.java", "license": "gpl-2.0", "size": 23007 }
[ "com.unboundid.ldap.listener.InMemoryDirectoryServer", "com.unboundid.ldap.listener.InMemoryDirectoryServerConfig", "com.unboundid.ldap.sdk.LDAPConnection", "com.unboundid.ldap.sdk.ResultCode", "org.testng.annotations.Test" ]
import com.unboundid.ldap.listener.InMemoryDirectoryServer; import com.unboundid.ldap.listener.InMemoryDirectoryServerConfig; import com.unboundid.ldap.sdk.LDAPConnection; import com.unboundid.ldap.sdk.ResultCode; import org.testng.annotations.Test;
import com.unboundid.ldap.listener.*; import com.unboundid.ldap.sdk.*; import org.testng.annotations.*;
[ "com.unboundid.ldap", "org.testng.annotations" ]
com.unboundid.ldap; org.testng.annotations;
623,741
URL fileURL = clazz.getProtectionDomain().getCodeSource().getLocation(); return new FileResource(fileURL.getFile()); }
URL fileURL = clazz.getProtectionDomain().getCodeSource().getLocation(); return new FileResource(fileURL.getFile()); }
/** * Gets the jar file that a class is stored in. * * @param clazz The class whose associated jar file is descried. * @return The Resource (jar file) for the class */
Gets the jar file that a class is stored in
getJar
{ "repo_name": "dbracewell/mango", "path": "src/main/java/com/davidbracewell/io/JarUtils.java", "license": "apache-2.0", "size": 4434 }
[ "com.davidbracewell.io.resource.FileResource" ]
import com.davidbracewell.io.resource.FileResource;
import com.davidbracewell.io.resource.*;
[ "com.davidbracewell.io" ]
com.davidbracewell.io;
1,774,665
@Test public void testGreaterThanFilterOnDateType() throws SQLException { Properties info = new Properties(); info.put("model", jsonPath("bug")); try (Connection connection = DriverManager.getConnection("jdbc:calcite:", info)) { final Statement statement = connection.createStatement(); // date final String sql1 = "select JOINEDAT from \"DATE\"\n" + "where JOINEDAT > {d '1990-01-01'}"; final ResultSet joinedAt = statement.executeQuery(sql1); assertThat(joinedAt.next(), is(true)); assertThat(joinedAt.getDate(1).getClass(), equalTo(java.sql.Date.class)); assertThat(joinedAt.getDate(1), is(java.sql.Date.valueOf("1996-08-03"))); // time final String sql2 = "select JOINTIME from \"DATE\"\n" + "where JOINTIME > {t '00:00:00'}"; final ResultSet joinTime = statement.executeQuery(sql2); assertThat(joinTime.next(), is(true)); assertThat(joinTime.getTime(1).getClass(), equalTo(java.sql.Time.class)); assertThat(joinTime.getTime(1), is(java.sql.Time.valueOf("00:01:02"))); // timestamp final String sql3 = "select JOINTIMES from \"DATE\"\n" + "where JOINTIMES > {ts '1990-01-01 00:00:00'}"; final ResultSet joinTimes = statement.executeQuery(sql3); assertThat(joinTimes.next(), is(true)); assertThat(joinTimes.getTimestamp(1).getClass(), equalTo(java.sql.Timestamp.class)); assertThat(joinTimes.getTimestamp(1), is(java.sql.Timestamp.valueOf("1996-08-03 00:01:02"))); } }
@Test void function() throws SQLException { Properties info = new Properties(); info.put("model", jsonPath("bug")); try (Connection connection = DriverManager.getConnection(STR, info)) { final Statement statement = connection.createStatement(); final String sql1 = STRDATE\"\n" + STR; final ResultSet joinedAt = statement.executeQuery(sql1); assertThat(joinedAt.next(), is(true)); assertThat(joinedAt.getDate(1).getClass(), equalTo(java.sql.Date.class)); assertThat(joinedAt.getDate(1), is(java.sql.Date.valueOf(STR))); final String sql2 = STRDATE\"\n" + STR; final ResultSet joinTime = statement.executeQuery(sql2); assertThat(joinTime.next(), is(true)); assertThat(joinTime.getTime(1).getClass(), equalTo(java.sql.Time.class)); assertThat(joinTime.getTime(1), is(java.sql.Time.valueOf(STR))); final String sql3 = STRDATE\"\n" + STR; final ResultSet joinTimes = statement.executeQuery(sql3); assertThat(joinTimes.next(), is(true)); assertThat(joinTimes.getTimestamp(1).getClass(), equalTo(java.sql.Timestamp.class)); assertThat(joinTimes.getTimestamp(1), is(java.sql.Timestamp.valueOf(STR))); } }
/** Test case for * <a href="https://issues.apache.org/jira/browse/CALCITE-1427">[CALCITE-1427] * Code generation incorrect (does not compile) for DATE, TIME and TIMESTAMP * fields</a>. */
Test case for [CALCITE-1427] Code generation incorrect (does not compile) for DATE, TIME and TIMESTAMP
testGreaterThanFilterOnDateType
{ "repo_name": "arina-ielchiieva/calcite", "path": "example/csv/src/test/java/org/apache/calcite/test/CsvTest.java", "license": "apache-2.0", "size": 37426 }
[ "java.sql.Connection", "java.sql.DriverManager", "java.sql.ResultSet", "java.sql.SQLException", "java.sql.Statement", "java.sql.Timestamp", "java.util.Properties", "org.hamcrest.CoreMatchers", "org.junit.Assert", "org.junit.Test" ]
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.util.Properties; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test;
import java.sql.*; import java.util.*; import org.hamcrest.*; import org.junit.*;
[ "java.sql", "java.util", "org.hamcrest", "org.junit" ]
java.sql; java.util; org.hamcrest; org.junit;
2,002,102
void assertDefinitionNode(Node n, Token type) { checkState(sourceName != null); checkState(n.getToken() == type, n); }
void assertDefinitionNode(Node n, Token type) { checkState(sourceName != null); checkState(n.getToken() == type, n); }
/** * Asserts that it's OK to define this node's name. * The node should have a source name and be of the specified type. */
Asserts that it's OK to define this node's name. The node should have a source name and be of the specified type
assertDefinitionNode
{ "repo_name": "tdelmas/closure-compiler", "path": "src/com/google/javascript/jscomp/TypedScopeCreator.java", "license": "apache-2.0", "size": 87731 }
[ "com.google.common.base.Preconditions", "com.google.javascript.rhino.Node", "com.google.javascript.rhino.Token" ]
import com.google.common.base.Preconditions; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token;
import com.google.common.base.*; import com.google.javascript.rhino.*;
[ "com.google.common", "com.google.javascript" ]
com.google.common; com.google.javascript;
305,023
@Override public String toString(){ return JSON.serialize( this ); }
String function(){ return JSON.serialize( this ); }
/** * Returns a JSON serialization of this object * @return JSON serialization */
Returns a JSON serialization of this object
toString
{ "repo_name": "davydotcom/mongo-java-driver", "path": "src/main/org/bson/LazyDBList.java", "license": "apache-2.0", "size": 1100 }
[ "com.mongodb.util.JSON" ]
import com.mongodb.util.JSON;
import com.mongodb.util.*;
[ "com.mongodb.util" ]
com.mongodb.util;
1,372,567
public void setRunningJobs(Vector<JobState> runningJobs) { this.runningJobs = runningJobs; }
void function(Vector<JobState> runningJobs) { this.runningJobs = runningJobs; }
/** * To set the runningJobs * * @param runningJobs the runningJobs to set */
To set the runningJobs
setRunningJobs
{ "repo_name": "lpellegr/scheduling", "path": "scheduler/scheduler-client/src/main/java/org/ow2/proactive/scheduler/core/SchedulerStateImpl.java", "license": "agpl-3.0", "size": 10522 }
[ "java.util.Vector", "org.ow2.proactive.scheduler.common.job.JobState" ]
import java.util.Vector; import org.ow2.proactive.scheduler.common.job.JobState;
import java.util.*; import org.ow2.proactive.scheduler.common.job.*;
[ "java.util", "org.ow2.proactive" ]
java.util; org.ow2.proactive;
705,343
public String getComments( ) { return getStringProperty( IDesignElementModel.COMMENTS_PROP ); }
String function( ) { return getStringProperty( IDesignElementModel.COMMENTS_PROP ); }
/** * Gets the comments of the report element. * * @return the comments of the report element */
Gets the comments of the report element
getComments
{ "repo_name": "sguan-actuate/birt", "path": "model/org.eclipse.birt.report.model/src/org/eclipse/birt/report/model/api/ReportElementHandle.java", "license": "epl-1.0", "size": 11517 }
[ "org.eclipse.birt.report.model.elements.interfaces.IDesignElementModel" ]
import org.eclipse.birt.report.model.elements.interfaces.IDesignElementModel;
import org.eclipse.birt.report.model.elements.interfaces.*;
[ "org.eclipse.birt" ]
org.eclipse.birt;
289,679
EClass getGModel();
EClass getGModel();
/** * Returns the meta object for class '{@link de.tesis.dynaware.grapheditor.model.GModel <em>GModel</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for class '<em>GModel</em>'. * @see de.tesis.dynaware.grapheditor.model.GModel * @generated */
Returns the meta object for class '<code>de.tesis.dynaware.grapheditor.model.GModel GModel</code>'.
getGModel
{ "repo_name": "eckig/graph-editor", "path": "model/src/main/java/de/tesis/dynaware/grapheditor/model/GraphPackage.java", "license": "epl-1.0", "size": 33067 }
[ "org.eclipse.emf.ecore.EClass" ]
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,817,545
public int quantityDropped(Random par1Random) { return 0; }
int function(Random par1Random) { return 0; }
/** * Returns the quantity of items to drop on block destruction. */
Returns the quantity of items to drop on block destruction
quantityDropped
{ "repo_name": "sethten/MoDesserts", "path": "mcp50/src/minecraft_server/net/minecraft/src/BlockFire.java", "license": "gpl-3.0", "size": 12330 }
[ "java.util.Random" ]
import java.util.Random;
import java.util.*;
[ "java.util" ]
java.util;
1,176,465
protected int checkPipeline() { IOutputAdapter tmpOutputAdapter; IPlugIn tmpPlugIn; ListIterator<IPlugIn> pluginIterator; ListIterator<ThreadGroup> threadGroupIterator; int RecordsInPipe = 0; pluginIterator = plugInList.listIterator(); threadGroupIterator = thGrpsPlugIn.listIterator(); while (pluginIterator.hasNext() && threadGroupIterator.hasNext()) { tmpPlugIn = pluginIterator.next(); RecordsInPipe += tmpPlugIn.getOutboundRecordCount(); } for (int i = 0; i < batchOutputAdapterList.size(); ++i) { tmpOutputAdapter = batchOutputAdapterList.get(i); // anything that needs to be done 1x per batch cycle. RecordsInPipe += tmpOutputAdapter.getOutboundRecordCount(); } // check if there have been any errors in the threads, and if there // have, pass the exception up if (pipeExceptionHandler.hasError()) { // Failure occurred, propogate the error System.err.println("Exception thrown in pipeline <" + getSymbolicName() + ">, see Error Log."); OpenRate.getOpenRateFrameworkLog().error("Exception thrown in pipeline <" + getSymbolicName() + ">, see Error Log."); // report the exceptions to the ErrorLog Iterator<Exception> excList = pipeExceptionHandler.getExceptionList().iterator(); // for each of the exceptions we have collected while (excList.hasNext()) { Exception tmpException = excList.next(); OpenRate.getOpenRateErrorLog().error("Processing Exception caught.", tmpException); getPipeLog().error(tmpException.getMessage()); } // Clear down the list pipeExceptionHandler.clearExceptions(); // See if we should shutdown if (haltOnException) { // stop the pipe System.err.println("Exception thrown in pipeline <" + getSymbolicName() + ">, see Error Log."); OpenRate.getOpenRateFrameworkLog().error("Pipeline <" + getSymbolicName() + "> configured to shut down on exception. Shutting down."); aborted = true; } } return RecordsInPipe; }
int function() { IOutputAdapter tmpOutputAdapter; IPlugIn tmpPlugIn; ListIterator<IPlugIn> pluginIterator; ListIterator<ThreadGroup> threadGroupIterator; int RecordsInPipe = 0; pluginIterator = plugInList.listIterator(); threadGroupIterator = thGrpsPlugIn.listIterator(); while (pluginIterator.hasNext() && threadGroupIterator.hasNext()) { tmpPlugIn = pluginIterator.next(); RecordsInPipe += tmpPlugIn.getOutboundRecordCount(); } for (int i = 0; i < batchOutputAdapterList.size(); ++i) { tmpOutputAdapter = batchOutputAdapterList.get(i); RecordsInPipe += tmpOutputAdapter.getOutboundRecordCount(); } if (pipeExceptionHandler.hasError()) { System.err.println(STR + getSymbolicName() + STR); OpenRate.getOpenRateFrameworkLog().error(STR + getSymbolicName() + STR); Iterator<Exception> excList = pipeExceptionHandler.getExceptionList().iterator(); while (excList.hasNext()) { Exception tmpException = excList.next(); OpenRate.getOpenRateErrorLog().error(STR, tmpException); getPipeLog().error(tmpException.getMessage()); } pipeExceptionHandler.clearExceptions(); if (haltOnException) { System.err.println(STR + getSymbolicName() + STR); OpenRate.getOpenRateFrameworkLog().error(STR + getSymbolicName() + STR); aborted = true; } } return RecordsInPipe; }
/** * Perform regular maintenance on the pipeline elements. Also checks the pipe * for exceptions, and in the case one is found, report it and shut down the * pipe * * @return The approximate number of records still in the pipe */
Perform regular maintenance on the pipeline elements. Also checks the pipe for exceptions, and in the case one is found, report it and shut down the pipe
checkPipeline
{ "repo_name": "isparkes/OpenRate", "path": "src/main/java/OpenRate/Pipeline.java", "license": "apache-2.0", "size": 58344 }
[ "java.util.Iterator", "java.util.ListIterator" ]
import java.util.Iterator; import java.util.ListIterator;
import java.util.*;
[ "java.util" ]
java.util;
664,114
private static char[] transcodeRemaining(final char prev, final char curr, final char next, final char aNext) { // 1. EV -> AF if (curr == 'E' && next == 'V') { return CHARS_AF; } // A, E, I, O, U -> A if (isVowel(curr)) { return CHARS_A; } // 2. Q -> G, Z -> S, M -> N if (curr == 'Q') { return CHARS_G; } else if (curr == 'Z') { return CHARS_S; } else if (curr == 'M') { return CHARS_N; } // 3. KN -> NN else K -> C if (curr == 'K') { if (next == 'N') { return CHARS_NN; } else { return CHARS_C; } } // 4. SCH -> SSS if (curr == 'S' && next == 'C' && aNext == 'H') { return CHARS_SSS; } // PH -> FF if (curr == 'P' && next == 'H') { return CHARS_FF; } // 5. H -> If previous or next is a non vowel, previous. if (curr == 'H' && (!isVowel(prev) || !isVowel(next))) { return new char[] { prev }; } // 6. W -> If previous is vowel, previous. if (curr == 'W' && isVowel(prev)) { return new char[] { prev }; } return new char[] { curr }; } private final boolean strict; public Nysiis() { this(true); } public Nysiis(final boolean strict) { this.strict = strict; } /** * Encodes an Object using the NYSIIS algorithm. This method is provided in order to satisfy the requirements of the * Encoder interface, and will throw an {@link EncoderException} if the supplied object is not of type * {@link String}. * * @param obj * Object to encode * @return An object (or a {@link String}) containing the NYSIIS code which corresponds to the given String. * @throws EncoderException * if the parameter supplied is not of a {@link String}
static char[] function(final char prev, final char curr, final char next, final char aNext) { if (curr == 'E' && next == 'V') { return CHARS_AF; } if (isVowel(curr)) { return CHARS_A; } if (curr == 'Q') { return CHARS_G; } else if (curr == 'Z') { return CHARS_S; } else if (curr == 'M') { return CHARS_N; } if (curr == 'K') { if (next == 'N') { return CHARS_NN; } else { return CHARS_C; } } if (curr == 'S' && next == 'C' && aNext == 'H') { return CHARS_SSS; } if (curr == 'P' && next == 'H') { return CHARS_FF; } if (curr == 'H' && (!isVowel(prev) !isVowel(next))) { return new char[] { prev }; } if (curr == 'W' && isVowel(prev)) { return new char[] { prev }; } return new char[] { curr }; } private final boolean strict; public Nysiis() { this(true); } public Nysiis(final boolean strict) { this.strict = strict; } /** * Encodes an Object using the NYSIIS algorithm. This method is provided in order to satisfy the requirements of the * Encoder interface, and will throw an {@link EncoderException} if the supplied object is not of type * {@link String}. * * @param obj * Object to encode * @return An object (or a {@link String}) containing the NYSIIS code which corresponds to the given String. * @throws EncoderException * if the parameter supplied is not of a {@link String}
/** * Transcodes the remaining parts of the String. The method operates on a sliding window, looking at 4 characters at * a time: [i-1, i, i+1, i+2]. * * @param prev * the previous character * @param curr * the current character * @param next * the next character * @param aNext * the after next character * @return a transcoded array of characters, starting from the current position */
Transcodes the remaining parts of the String. The method operates on a sliding window, looking at 4 characters at a time: [i-1, i, i+1, i+2]
transcodeRemaining
{ "repo_name": "CURocketry/Ground_Station_GUI", "path": "src/org/apache/commons/codec/language/Nysiis.java", "license": "gpl-3.0", "size": 11315 }
[ "org.apache.commons.codec.EncoderException" ]
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.*;
[ "org.apache.commons" ]
org.apache.commons;
1,680,732
public static String calculateMD5(InputStream in) throws NoSuchAlgorithmException, IOException { byte[] md5Bytes = calculateMD5Digest(in); // Convert the byte to hex format. StringBuilder sb = new StringBuilder(); for (byte md5Byte : md5Bytes) sb.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1)); return sb.toString(); }
static String function(InputStream in) throws NoSuchAlgorithmException, IOException { byte[] md5Bytes = calculateMD5Digest(in); StringBuilder sb = new StringBuilder(); for (byte md5Byte : md5Bytes) sb.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1)); return sb.toString(); }
/** * Calculate MD5 string. * * @param in Input stream. * @return Calculated MD5 string for given input stream. * @throws NoSuchAlgorithmException If MD5 algorithm was not found. * @throws IOException If an I/O exception occurs. */
Calculate MD5 string
calculateMD5
{ "repo_name": "NSAmelchev/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java", "license": "apache-2.0", "size": 388551 }
[ "java.io.IOException", "java.io.InputStream", "java.security.NoSuchAlgorithmException" ]
import java.io.IOException; import java.io.InputStream; import java.security.NoSuchAlgorithmException;
import java.io.*; import java.security.*;
[ "java.io", "java.security" ]
java.io; java.security;
1,549,815
Object encrypt(String parameterName, Object value, ValueEncryptionContext context);
Object encrypt(String parameterName, Object value, ValueEncryptionContext context);
/** * Encrypt value. * @param parameterName Parameter name * @param value Unencrypted value * @param context Context * @return Encrypted value. * @throws UnsupportedOperationException when the plugin is not enabled. */
Encrypt value
encrypt
{ "repo_name": "wcm-io-devops/conga", "path": "generator/src/main/java/io/wcm/devops/conga/generator/spi/ValueEncryptionPlugin.java", "license": "apache-2.0", "size": 1491 }
[ "io.wcm.devops.conga.generator.spi.context.ValueEncryptionContext" ]
import io.wcm.devops.conga.generator.spi.context.ValueEncryptionContext;
import io.wcm.devops.conga.generator.spi.context.*;
[ "io.wcm.devops" ]
io.wcm.devops;
916,120
public HandlerRegistration addClickHandler(ClickHandler handler) { return widget.addDomHandler(handler, ClickEvent.getType()); }
HandlerRegistration function(ClickHandler handler) { return widget.addDomHandler(handler, ClickEvent.getType()); }
/** * Add ClickHandler to the whole Panel widget * * @param handler handler to add * @return handler registration */
Add ClickHandler to the whole Panel widget
addClickHandler
{ "repo_name": "zlamalp/perun-wui", "path": "perun-wui-consolidator/src/main/java/cz/metacentrum/perun/wui/consolidator/widgets/WayfGroupButton.java", "license": "bsd-2-clause", "size": 2187 }
[ "com.google.gwt.event.dom.client.ClickEvent", "com.google.gwt.event.dom.client.ClickHandler", "com.google.gwt.event.shared.HandlerRegistration" ]
import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.dom.client.*; import com.google.gwt.event.shared.*;
[ "com.google.gwt" ]
com.google.gwt;
743,778
public static void replaceNodeInStatement(final Statement container, final ReplacementTupla replacementTupla) { container.walk(node -> { if (node.equals(replacementTupla.toReplace)) { node.getParentNode() .ifPresent(parentNode -> parentNode.replace(replacementTupla.toReplace, replacementTupla.replacement)); } }); }
static void function(final Statement container, final ReplacementTupla replacementTupla) { container.walk(node -> { if (node.equals(replacementTupla.toReplace)) { node.getParentNode() .ifPresent(parentNode -> parentNode.replace(replacementTupla.toReplace, replacementTupla.replacement)); } }); }
/** * Replace <code>Node</code> in the given <code>Statement</code> * @param container * @param replacementTupla */
Replace <code>Node</code> in the given <code>Statement</code>
replaceNodeInStatement
{ "repo_name": "manstis/drools", "path": "kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-commons/src/main/java/org/kie/pmml/compiler/commons/utils/CommonCodegenUtils.java", "license": "apache-2.0", "size": 46882 }
[ "com.github.javaparser.ast.stmt.Statement" ]
import com.github.javaparser.ast.stmt.Statement;
import com.github.javaparser.ast.stmt.*;
[ "com.github.javaparser" ]
com.github.javaparser;
2,199,292
public Date getPlannedEndDate() { return plannedEndDate; }
Date function() { return plannedEndDate; }
/** * The scheduled ending date of this milestone * * @return a Date */
The scheduled ending date of this milestone
getPlannedEndDate
{ "repo_name": "thescouser89/pnc", "path": "model/src/main/java/org/jboss/pnc/model/ProductMilestone.java", "license": "apache-2.0", "size": 14048 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
1,904,317
@NonNull private SharedPreferences getDefaultSharedPreferences() { return PreferenceManager.getDefaultSharedPreferences(context); }
SharedPreferences function() { return PreferenceManager.getDefaultSharedPreferences(context); }
/** * Returns default shared preferences. * * @return {@link SharedPreferences} instance */
Returns default shared preferences
getDefaultSharedPreferences
{ "repo_name": "arunkumar9t2/chameleon-live-wallpaper", "path": "app/src/main/java/arun/com/chameleonskinforkwlp/preferences/Preferences.java", "license": "apache-2.0", "size": 2092 }
[ "android.content.SharedPreferences", "android.preference.PreferenceManager" ]
import android.content.SharedPreferences; import android.preference.PreferenceManager;
import android.content.*; import android.preference.*;
[ "android.content", "android.preference" ]
android.content; android.preference;
615,659
@Test public void processRangeWithOneInterval() throws IOException, ParserException { YangNode node = manager.getDataModel("src/test/resources/RangeWithOneInterval.yang"); assertThat((node instanceof YangModule), is(true)); assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE)); YangModule yangNode = (YangModule) node; assertThat(yangNode.getName(), is("Test")); ListIterator<YangLeafList> leafListIterator = yangNode.getListOfLeafList().listIterator(); YangLeafList leafListInfo = leafListIterator.next(); assertThat(leafListInfo.getName(), is("invalid-interval")); assertThat(leafListInfo.getDataType().getDataTypeName(), is("int32")); assertThat(leafListInfo.getDataType().getDataType(), is(YangDataTypes.INT32)); YangRangeRestriction rangeRestriction = (YangRangeRestriction) leafListInfo .getDataType().getDataTypeExtendedInfo(); ListIterator<YangRangeInterval> rangeListIterator = rangeRestriction.getAscendingRangeIntervals() .listIterator(); YangRangeInterval rangeInterval = rangeListIterator.next(); assertThat(((YangInt32) rangeInterval.getStartValue()).getValue(), is(1)); assertThat(((YangInt32) rangeInterval.getEndValue()).getValue(), is(1)); }
void function() throws IOException, ParserException { YangNode node = manager.getDataModel(STR); assertThat((node instanceof YangModule), is(true)); assertThat(node.getNodeType(), is(YangNodeType.MODULE_NODE)); YangModule yangNode = (YangModule) node; assertThat(yangNode.getName(), is("Test")); ListIterator<YangLeafList> leafListIterator = yangNode.getListOfLeafList().listIterator(); YangLeafList leafListInfo = leafListIterator.next(); assertThat(leafListInfo.getName(), is(STR)); assertThat(leafListInfo.getDataType().getDataTypeName(), is("int32")); assertThat(leafListInfo.getDataType().getDataType(), is(YangDataTypes.INT32)); YangRangeRestriction rangeRestriction = (YangRangeRestriction) leafListInfo .getDataType().getDataTypeExtendedInfo(); ListIterator<YangRangeInterval> rangeListIterator = rangeRestriction.getAscendingRangeIntervals() .listIterator(); YangRangeInterval rangeInterval = rangeListIterator.next(); assertThat(((YangInt32) rangeInterval.getStartValue()).getValue(), is(1)); assertThat(((YangInt32) rangeInterval.getEndValue()).getValue(), is(1)); }
/** * Checks valid range statement with one interval. */
Checks valid range statement with one interval
processRangeWithOneInterval
{ "repo_name": "VinodKumarS-Huawei/ietf96yang", "path": "utils/yangutils/plugin/src/test/java/org/onosproject/yangutils/parser/impl/listeners/RangeRestrictionListenerTest.java", "license": "apache-2.0", "size": 10960 }
[ "java.io.IOException", "java.util.ListIterator", "org.hamcrest.MatcherAssert", "org.hamcrest.core.Is", "org.junit.Test", "org.onosproject.yangutils.datamodel.YangLeafList", "org.onosproject.yangutils.datamodel.YangModule", "org.onosproject.yangutils.datamodel.YangNode", "org.onosproject.yangutils.datamodel.YangNodeType", "org.onosproject.yangutils.datamodel.YangRangeInterval", "org.onosproject.yangutils.datamodel.YangRangeRestriction", "org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes", "org.onosproject.yangutils.datamodel.utils.builtindatatype.YangInt32", "org.onosproject.yangutils.parser.exceptions.ParserException" ]
import java.io.IOException; import java.util.ListIterator; import org.hamcrest.MatcherAssert; import org.hamcrest.core.Is; import org.junit.Test; import org.onosproject.yangutils.datamodel.YangLeafList; import org.onosproject.yangutils.datamodel.YangModule; import org.onosproject.yangutils.datamodel.YangNode; import org.onosproject.yangutils.datamodel.YangNodeType; import org.onosproject.yangutils.datamodel.YangRangeInterval; import org.onosproject.yangutils.datamodel.YangRangeRestriction; import org.onosproject.yangutils.datamodel.utils.builtindatatype.YangDataTypes; import org.onosproject.yangutils.datamodel.utils.builtindatatype.YangInt32; import org.onosproject.yangutils.parser.exceptions.ParserException;
import java.io.*; import java.util.*; import org.hamcrest.*; import org.hamcrest.core.*; import org.junit.*; import org.onosproject.yangutils.datamodel.*; import org.onosproject.yangutils.datamodel.utils.builtindatatype.*; import org.onosproject.yangutils.parser.exceptions.*;
[ "java.io", "java.util", "org.hamcrest", "org.hamcrest.core", "org.junit", "org.onosproject.yangutils" ]
java.io; java.util; org.hamcrest; org.hamcrest.core; org.junit; org.onosproject.yangutils;
2,793,420
Assert.areNotNull(original, targetClassLoader); return !isSameInClassLoader(original.getClass(), targetClassLoader); }
Assert.areNotNull(original, targetClassLoader); return !isSameInClassLoader(original.getClass(), targetClassLoader); }
/** * Decides that the given object should be shallow copied if its <code>Class</code> would be different when loaded * through the given <code>ClassLoader</code>. * * @param original the candidate for cloning * @param targetClassLoader the <code>ClassLoader</code> it may be cloned with * @return <code>true</code> if <code>original</code>'s <code>Class</code> would be different when loaded * through <code>targetClassLoader</code> */
Decides that the given object should be shallow copied if its <code>Class</code> would be different when loaded through the given <code>ClassLoader</code>
shouldCloneObjectItself
{ "repo_name": "csm/java-sandbox", "path": "src/main/java/net/datenwerke/transloader/clone/reflect/decide/MinimalCloningDecisionStrategy.java", "license": "lgpl-2.1", "size": 3839 }
[ "net.datenwerke.transloader.except.Assert" ]
import net.datenwerke.transloader.except.Assert;
import net.datenwerke.transloader.except.*;
[ "net.datenwerke.transloader" ]
net.datenwerke.transloader;
1,647,756
private String buildOutOfMemoryErrorMessage() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); final long max = memoryMXBean.getHeapMemoryUsage().getMax() / MEGABYTE; final long used = memoryMXBean.getHeapMemoryUsage().getUsed() / MEGABYTE; final String msg = Status.outOfMemoryError .getMessage("There is not enough memory. Maximum = " + max + "Mb, Used = " + used + " Mb."); LOG.error(msg); return msg; }
String function() { MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean(); final long max = memoryMXBean.getHeapMemoryUsage().getMax() / MEGABYTE; final long used = memoryMXBean.getHeapMemoryUsage().getUsed() / MEGABYTE; final String msg = Status.outOfMemoryError .getMessage(STR + max + STR + used + STR); LOG.error(msg); return msg; }
/** * Builds the out of memory Error * * @return out of memory error message */
Builds the out of memory Error
buildOutOfMemoryErrorMessage
{ "repo_name": "debard/georchestra-ird", "path": "mapfishapp/src/main/java/org/georchestra/mapfishapp/ws/UpLoadGeoFileController.java", "license": "gpl-3.0", "size": 28113 }
[ "java.lang.management.ManagementFactory", "java.lang.management.MemoryMXBean" ]
import java.lang.management.ManagementFactory; import java.lang.management.MemoryMXBean;
import java.lang.management.*;
[ "java.lang" ]
java.lang;
2,141,689
@Test public void testGetSections() { System.out.println("GetSections"); String name = "test_multi_pages.docx"; String storage = ""; String folder = ""; try { SectionLinkCollectionResponse result = wordsApi.GetSections(name, storage, folder); } catch (ApiException apiException) { System.out.println("exp:" + apiException.getMessage()); assertNull(apiException); } }
void function() { System.out.println(STR); String name = STR; String storage = STRSTRexp:" + apiException.getMessage()); assertNull(apiException); } }
/** * Test of GetSections method, of class WordsApi. */
Test of GetSections method, of class WordsApi
testGetSections
{ "repo_name": "farooqsheikhpk/Aspose_Words_Cloud", "path": "SDKs/Aspose.Words-Cloud-SDK-for-Android/aspose-cloud-words-android/src/test/java/com/aspose/words/WordsApiTest.java", "license": "mit", "size": 42545 }
[ "org.junit.Assert" ]
import org.junit.Assert;
import org.junit.*;
[ "org.junit" ]
org.junit;
415,863
public static String asString(InputStream pStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(); }
static String function(InputStream pStream) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); copy(pStream, baos, true); return baos.toString(); }
/** * This convenience method allows to read a * {@link org.apache.commons.fileupload.FileItemStream}'s * content into a string. The platform's default character encoding * is used for converting bytes into characters. * @param pStream The input stream to read. * @see #asString(InputStream, String) * @return The streams contents, as a string. * @throws IOException An I/O error occurred. */
This convenience method allows to read a <code>org.apache.commons.fileupload.FileItemStream</code>'s content into a string. The platform's default character encoding is used for converting bytes into characters
asString
{ "repo_name": "bbossgroups/bbossgroups-3.5", "path": "bboss-mvc/src/org/frameworkset/web/multipart/commons/CommonsFileUploadSupport.java", "license": "apache-2.0", "size": 32456 }
[ "java.io.ByteArrayOutputStream", "java.io.IOException", "java.io.InputStream" ]
import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream;
import java.io.*;
[ "java.io" ]
java.io;
389,681
protected void status(final String[] args) throws Exception { workingDir = (File) getStopOptions(args).get(DIR); System.out.println(getStatus()); ExitCode.NORMAL.doSystemExit(); }
void function(final String[] args) throws Exception { workingDir = (File) getStopOptions(args).get(DIR); System.out.println(getStatus()); ExitCode.NORMAL.doSystemExit(); }
/** * Prints the status of the cache server running the configured working directory. */
Prints the status of the cache server running the configured working directory
status
{ "repo_name": "pivotal-amurmann/geode", "path": "geode-core/src/main/java/org/apache/geode/internal/cache/CacheServerLauncher.java", "license": "apache-2.0", "size": 50008 }
[ "java.io.File", "org.apache.geode.internal.ExitCode" ]
import java.io.File; import org.apache.geode.internal.ExitCode;
import java.io.*; import org.apache.geode.internal.*;
[ "java.io", "org.apache.geode" ]
java.io; org.apache.geode;
725,932
@Deprecated public Object[] listBaseChannels(User loggedInUser, Integer sid) throws FaultException { return listSubscribableBaseChannels(loggedInUser, sid); }
Object[] function(User loggedInUser, Integer sid) throws FaultException { return listSubscribableBaseChannels(loggedInUser, sid); }
/** * Gets a list of base channels subscribable by the logged in user for the server with * the given id. * @param loggedInUser The current user * @param sid The id of the server in question * @return Returns an array of maps representing the base channels the logged in user * can subscribe this system to. * @throws FaultException A FaultException is thrown if the server corresponding to * sid cannot be found. * @deprecated being replaced by listSubscribableBaseChannels(string sessionKey, * int serverId) * * @xmlrpc.doc Returns a list of subscribable base channels. * @xmlrpc.param #param("string", "sessionKey") * @xmlrpc.param #param("int", "serverId") * * @xmlrpc.returntype * #array() * #struct("channel") * #prop_desc("int" "id" "Base Channel ID.") * #prop_desc("string" "name" "Name of channel.") * #prop_desc("string" "label" "Label of Channel") * #prop_desc("int", "current_base", "1 indicates it is the current base * channel") * #struct_end() * #array_end() * */
Gets a list of base channels subscribable by the logged in user for the server with the given id
listBaseChannels
{ "repo_name": "jhutar/spacewalk", "path": "java/code/src/com/redhat/rhn/frontend/xmlrpc/system/SystemHandler.java", "license": "gpl-2.0", "size": 241022 }
[ "com.redhat.rhn.FaultException", "com.redhat.rhn.domain.user.User" ]
import com.redhat.rhn.FaultException; import com.redhat.rhn.domain.user.User;
import com.redhat.rhn.*; import com.redhat.rhn.domain.user.*;
[ "com.redhat.rhn" ]
com.redhat.rhn;
182,444
public Map<Integer, Integer> getBornByYears() { return new Reader().getBornByYears(); }
Map<Integer, Integer> function() { return new Reader().getBornByYears(); }
/** * Getting number of readers born in each year * * @return {Map<Integer, Integer>} botn by years */
Getting number of readers born in each year
getBornByYears
{ "repo_name": "biblelamp/JavaExercises", "path": "TestTasks/merck.com/jdbc/src/main/java/tools/Service.java", "license": "gpl-2.0", "size": 3594 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
2,761,988
public void xtestAbstractSuperclassMarshal() throws Exception { boolean exception = false; String msg = null; String tmpdir = System.getenv("T_WORK"); String src = "/output.xml"; MyTestSubType testObj = new MyTestSubType(); testObj.subTypeInt = 66; try { Class[] jClasses = new Class[] { MyAbstractTestType.class, MyTestSubType.class }; JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(jClasses, null); Marshaller marshaller = jCtx.createMarshaller(); FileWriter fw = new FileWriter(tmpdir + src); marshaller.marshal(testObj, fw); } catch (Exception ex) { exception = true; ex.printStackTrace(); msg = ex.toString(); } assertFalse("Marshal operation failed unexpectedly: " + msg, exception); }
void function() throws Exception { boolean exception = false; String msg = null; String tmpdir = System.getenv(STR); String src = STR; MyTestSubType testObj = new MyTestSubType(); testObj.subTypeInt = 66; try { Class[] jClasses = new Class[] { MyAbstractTestType.class, MyTestSubType.class }; JAXBContext jCtx = (JAXBContext) JAXBContextFactory.createContext(jClasses, null); Marshaller marshaller = jCtx.createMarshaller(); FileWriter fw = new FileWriter(tmpdir + src); marshaller.marshal(testObj, fw); } catch (Exception ex) { exception = true; ex.printStackTrace(); msg = ex.toString(); } assertFalse(STR + msg, exception); }
/** * This test will validate the descriptor's configuration wrt inheritance for * an abstract superclass via marshal operation. */
This test will validate the descriptor's configuration wrt inheritance for an abstract superclass via marshal operation
xtestAbstractSuperclassMarshal
{ "repo_name": "gameduell/eclipselink.runtime", "path": "moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/schemagen/employee/SchemaGenEmployeeTestCases.java", "license": "epl-1.0", "size": 12848 }
[ "java.io.FileWriter", "javax.xml.bind.Marshaller", "org.eclipse.persistence.jaxb.JAXBContext", "org.eclipse.persistence.jaxb.JAXBContextFactory" ]
import java.io.FileWriter; import javax.xml.bind.Marshaller; import org.eclipse.persistence.jaxb.JAXBContext; import org.eclipse.persistence.jaxb.JAXBContextFactory;
import java.io.*; import javax.xml.bind.*; import org.eclipse.persistence.jaxb.*;
[ "java.io", "javax.xml", "org.eclipse.persistence" ]
java.io; javax.xml; org.eclipse.persistence;
2,496,134
public static void deleteQuietly(TemporaryQueue q) { if (q == null) return; try { q.delete(); } catch (Exception e) { } }
static void function(TemporaryQueue q) { if (q == null) return; try { q.delete(); } catch (Exception e) { } }
/** * Delete a {@link TemporaryQueue} without logging any errors. * * @param q the queue. */
Delete a <code>TemporaryQueue</code> without logging any errors
deleteQuietly
{ "repo_name": "mcwarman/interlok", "path": "adapter/src/main/java/com/adaptris/core/jms/JmsUtils.java", "license": "apache-2.0", "size": 4424 }
[ "javax.jms.TemporaryQueue" ]
import javax.jms.TemporaryQueue;
import javax.jms.*;
[ "javax.jms" ]
javax.jms;
435,393
public List<ProviderInner> providers() { return this.providers; }
List<ProviderInner> function() { return this.providers; }
/** * Get the providers property: The list of resource providers needed for the deployment. * * @return the providers value. */
Get the providers property: The list of resource providers needed for the deployment
providers
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-resources/src/main/java/com/azure/resourcemanager/resources/models/DeploymentPropertiesExtended.java", "license": "mit", "size": 8667 }
[ "com.azure.resourcemanager.resources.fluent.models.ProviderInner", "java.util.List" ]
import com.azure.resourcemanager.resources.fluent.models.ProviderInner; import java.util.List;
import com.azure.resourcemanager.resources.fluent.models.*; import java.util.*;
[ "com.azure.resourcemanager", "java.util" ]
com.azure.resourcemanager; java.util;
104,133
public StreamItem setAbs_url(byte[] abs_url) { setAbs_url(abs_url == null ? (ByteBuffer)null : ByteBuffer.wrap(abs_url)); return this; }
StreamItem function(byte[] abs_url) { setAbs_url(abs_url == null ? (ByteBuffer)null : ByteBuffer.wrap(abs_url)); return this; }
/** * normalized form of the original_url, should be a valid URL */
normalized form of the original_url, should be a valid URL
setAbs_url
{ "repo_name": "shriphani/kba-2013-clj", "path": "gen-java/streamcorpus/StreamItem.java", "license": "epl-1.0", "size": 66082 }
[ "java.nio.ByteBuffer" ]
import java.nio.ByteBuffer;
import java.nio.*;
[ "java.nio" ]
java.nio;
126,077
public void setSafe(int index, UInt2Holder holder) { handleSafe(index); set(index, holder); }
void function(int index, UInt2Holder holder) { handleSafe(index); set(index, holder); }
/** * Same as {@link #set(int, UInt2Holder)} except that it handles the * case when index is greater than or equal to existing * value capacity {@link #getValueCapacity()}. * * @param index position of element * @param holder data holder for value of element */
Same as <code>#set(int, UInt2Holder)</code> except that it handles the case when index is greater than or equal to existing value capacity <code>#getValueCapacity()</code>
setSafe
{ "repo_name": "cpcloud/arrow", "path": "java/vector/src/main/java/org/apache/arrow/vector/UInt2Vector.java", "license": "apache-2.0", "size": 10324 }
[ "org.apache.arrow.vector.holders.UInt2Holder" ]
import org.apache.arrow.vector.holders.UInt2Holder;
import org.apache.arrow.vector.holders.*;
[ "org.apache.arrow" ]
org.apache.arrow;
685,968
private static void cleanFile(String path) throws IOException { List<String> list = FileUtil.readAllLines(path); Collections.sort(list); Set<String> set = new TreeSet<String>(); set.addAll(list); writeSetToFile(path, set); }
static void function(String path) throws IOException { List<String> list = FileUtil.readAllLines(path); Collections.sort(list); Set<String> set = new TreeSet<String>(); set.addAll(list); writeSetToFile(path, set); }
/** * Clean file at path. * * Will rewrite contents in file, sorted alphabetically and ensuring no * duplicates. * * @param path path to file * @throws IOException */
Clean file at path. Will rewrite contents in file, sorted alphabetically and ensuring no duplicates
cleanFile
{ "repo_name": "budi-github/SrtFixer", "path": "src/main/data/cleaner/DataCleaner.java", "license": "mit", "size": 2271 }
[ "java.io.IOException", "java.util.Collections", "java.util.List", "java.util.Set", "java.util.TreeSet" ]
import java.io.IOException; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
18,600
public final PointF getCenter() { int mX = getWidth() / 2; int mY = getHeight() / 2; return viewToSourceCoord(mX, mY); }
final PointF function() { int mX = getWidth() / 2; int mY = getHeight() / 2; return viewToSourceCoord(mX, mY); }
/** * Returns the source point at the center of the view. */
Returns the source point at the center of the view
getCenter
{ "repo_name": "Deadleg/Slide", "path": "app/src/main/java/me/ccrama/redditslide/Views/SubsamplingScaleImageView.java", "license": "gpl-3.0", "size": 122096 }
[ "android.graphics.PointF" ]
import android.graphics.PointF;
import android.graphics.*;
[ "android.graphics" ]
android.graphics;
163,654
private void createView(TCreateOrAlterViewParams params, TDdlExecResponse response) throws ImpalaException { TableName tableName = TableName.fromThrift(params.getView_name()); Preconditions.checkState(tableName != null && tableName.isFullyQualified()); Preconditions.checkState(params.getColumns() != null && params.getColumns().size() > 0, "Null or empty column list given as argument to DdlExecutor.createView"); if (params.if_not_exists && catalog_.containsTable(tableName.getDb(), tableName.getTbl())) { LOG.debug(String.format("Skipping view creation because %s already exists and " + "ifNotExists is true.", tableName)); } // Create new view. org.apache.hadoop.hive.metastore.api.Table view = new org.apache.hadoop.hive.metastore.api.Table(); setViewAttributes(params, view); LOG.debug(String.format("Creating view %s", tableName)); createTable(view, params.if_not_exists, null, response); }
void function(TCreateOrAlterViewParams params, TDdlExecResponse response) throws ImpalaException { TableName tableName = TableName.fromThrift(params.getView_name()); Preconditions.checkState(tableName != null && tableName.isFullyQualified()); Preconditions.checkState(params.getColumns() != null && params.getColumns().size() > 0, STR); if (params.if_not_exists && catalog_.containsTable(tableName.getDb(), tableName.getTbl())) { LOG.debug(String.format(STR + STR, tableName)); } org.apache.hadoop.hive.metastore.api.Table view = new org.apache.hadoop.hive.metastore.api.Table(); setViewAttributes(params, view); LOG.debug(String.format(STR, tableName)); createTable(view, params.if_not_exists, null, response); }
/** * Creates a new view in the metastore and adds an entry to the metadata cache to * lazily load the new metadata on the next access. Re-throws any Metastore * exceptions encountered during the create. */
Creates a new view in the metastore and adds an entry to the metadata cache to lazily load the new metadata on the next access. Re-throws any Metastore exceptions encountered during the create
createView
{ "repo_name": "placrosse/ImpalaToGo", "path": "fe/src/main/java/com/cloudera/impala/service/CatalogOpExecutor.java", "license": "apache-2.0", "size": 115741 }
[ "com.cloudera.impala.analysis.TableName", "com.cloudera.impala.catalog.Table", "com.cloudera.impala.common.ImpalaException", "com.cloudera.impala.thrift.TCreateOrAlterViewParams", "com.cloudera.impala.thrift.TDdlExecResponse", "com.google.common.base.Preconditions" ]
import com.cloudera.impala.analysis.TableName; import com.cloudera.impala.catalog.Table; import com.cloudera.impala.common.ImpalaException; import com.cloudera.impala.thrift.TCreateOrAlterViewParams; import com.cloudera.impala.thrift.TDdlExecResponse; import com.google.common.base.Preconditions;
import com.cloudera.impala.analysis.*; import com.cloudera.impala.catalog.*; import com.cloudera.impala.common.*; import com.cloudera.impala.thrift.*; import com.google.common.base.*;
[ "com.cloudera.impala", "com.google.common" ]
com.cloudera.impala; com.google.common;
625,078
@Override public void publishResource(final RestResourceFactory factory) { ArgumentChecker.notNull(factory, "factory"); getRootResourceFactories().add(factory); }
void function(final RestResourceFactory factory) { ArgumentChecker.notNull(factory, STR); getRootResourceFactories().add(factory); }
/** * Adds a JAX-RS root resource to the known set. * <p> * This is used for JAX-RS unmanaged resources. * These classes are not managed by {@code DataComponentsResource}. * * @param factory the factory for creating the resource per request, not null */
Adds a JAX-RS root resource to the known set. This is used for JAX-RS unmanaged resources. These classes are not managed by DataComponentsResource
publishResource
{ "repo_name": "McLeodMoores/starling", "path": "projects/component-rest/src/main/java/com/opengamma/component/rest/RestComponentsImpl.java", "license": "apache-2.0", "size": 23575 }
[ "com.opengamma.util.ArgumentChecker" ]
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.*;
[ "com.opengamma.util" ]
com.opengamma.util;
197,630
private InMemoryDirectoryInfo getDirectory(Path path) throws IOException { InMemoryContentInfo dirInfo = pathWalk(path, false); if (!dirInfo.isDirectory()) { throw Error.ENOTDIR.exception(path); } else { return (InMemoryDirectoryInfo) dirInfo; } }
InMemoryDirectoryInfo function(Path path) throws IOException { InMemoryContentInfo dirInfo = pathWalk(path, false); if (!dirInfo.isDirectory()) { throw Error.ENOTDIR.exception(path); } else { return (InMemoryDirectoryInfo) dirInfo; } }
/** * Given 'path', returns the existing directory inode it designates, * following symbolic links. * * <p>May fail with ENOTDIR, or any exception from pathWalk. */
Given 'path', returns the existing directory inode it designates, following symbolic links. May fail with ENOTDIR, or any exception from pathWalk
getDirectory
{ "repo_name": "damienmg/bazel", "path": "src/main/java/com/google/devtools/build/lib/vfs/inmemoryfs/InMemoryFileSystem.java", "license": "apache-2.0", "size": 27765 }
[ "com.google.devtools.build.lib.vfs.Path", "java.io.IOException" ]
import com.google.devtools.build.lib.vfs.Path; import java.io.IOException;
import com.google.devtools.build.lib.vfs.*; import java.io.*;
[ "com.google.devtools", "java.io" ]
com.google.devtools; java.io;
2,201,957
DeviceId ownerId();
DeviceId ownerId();
/** * Returns the controller identifier owning this abstracted topology. * * @return the controller id */
Returns the controller identifier owning this abstracted topology
ownerId
{ "repo_name": "sdnwiselab/onos", "path": "apps/tetopology/api/src/main/java/org/onosproject/tetopology/management/api/Network.java", "license": "apache-2.0", "size": 2941 }
[ "org.onosproject.net.DeviceId" ]
import org.onosproject.net.DeviceId;
import org.onosproject.net.*;
[ "org.onosproject.net" ]
org.onosproject.net;
2,330,539
public static String getRelativePath(String targetPath, String basePath, String pathSeparator) { if (targetPath.toLowerCase().startsWith("file:/")) { targetPath = targetPath.substring(6); while(targetPath.startsWith("/")) targetPath = targetPath.substring(1); } if (basePath.toLowerCase().startsWith("file:/")) { basePath = basePath.substring(6); while(basePath.startsWith("/")) basePath = basePath.substring(1); } String tempS = basePath; while(true) { File baseF = new File(tempS); if ((baseF.exists())&&(baseF.isFile())) { basePath = baseF.getAbsolutePath(); break; } if (!pathSeparator.equals("/")) break; if (tempS.startsWith("/")) break; tempS = "/" + tempS; } tempS = targetPath; while(true) { File targetF = new File(tempS); if ((targetF.exists())&&(targetF.isFile())) { targetPath = targetF.getAbsolutePath(); break; } if (!pathSeparator.equals("/")) break; if (tempS.startsWith("/")) break; tempS = "/" + tempS; } // Normalize the paths //System.out.println("ResourceUtils.getRelativePath()..target("+pathSeparator+"):"+targetPath); //System.out.println("ResourceUtils.getRelativePath()..base("+pathSeparator+"):"+basePath); String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); // Undo the changes to the separators made by normalization if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'"); } //System.out.println("ResourceUtils.getRelativePath()..normalizedTarget("+pathSeparator+"):"+normalizedTargetPath); //System.out.println("ResourceUtils.getRelativePath()..normalizedBase("+pathSeparator+"):"+normalizedBasePath); String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); // First get all the common elements. Store them as a string, // and also count how many of them there are. StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].trim().equals(base[commonIndex].trim())) { common.append(target[commonIndex].trim() + pathSeparator); commonIndex++; } if (commonIndex == 0) { // No single common path element. This most // likely indicates differing drive letters, like C: and D:. // These paths cannot be relativized. File ff = new File(targetPath); if ((ff.exists())&&(ff.isFile())) return ff.getAbsolutePath(); else throw new IllegalArgumentException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'"); } // The number of directories we have to backtrack depends on whether the base is a file or a dir // For example, the relative path from // // /foo/bar/baz/gg/ff to /foo/bar/baz // // ".." if ff is a file // "../.." if ff is a directory // // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because // the resource referred to by this path may not actually exist, but it's the best I can do boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); //System.out.println("ResourceUtils.getRelativePath()..relativeTarget:"+relative.toString()); return relative.toString(); }
static String function(String targetPath, String basePath, String pathSeparator) { if (targetPath.toLowerCase().startsWith(STR)) { targetPath = targetPath.substring(6); while(targetPath.startsWith("/")) targetPath = targetPath.substring(1); } if (basePath.toLowerCase().startsWith(STR)) { basePath = basePath.substring(6); while(basePath.startsWith("/")) basePath = basePath.substring(1); } String tempS = basePath; while(true) { File baseF = new File(tempS); if ((baseF.exists())&&(baseF.isFile())) { basePath = baseF.getAbsolutePath(); break; } if (!pathSeparator.equals("/")) break; if (tempS.startsWith("/")) break; tempS = "/" + tempS; } tempS = targetPath; while(true) { File targetF = new File(tempS); if ((targetF.exists())&&(targetF.isFile())) { targetPath = targetF.getAbsolutePath(); break; } if (!pathSeparator.equals("/")) break; if (tempS.startsWith("/")) break; tempS = "/" + tempS; } String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { throw new IllegalArgumentException(STR + pathSeparator + "'"); } String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].trim().equals(base[commonIndex].trim())) { common.append(target[commonIndex].trim() + pathSeparator); commonIndex++; } if (commonIndex == 0) { File ff = new File(targetPath); if ((ff.exists())&&(ff.isFile())) return ff.getAbsolutePath(); else throw new IllegalArgumentException(STR + normalizedTargetPath + STR + normalizedBasePath + "'"); } boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
/** * Get the relative path from one file to another, specifying the directory separator. * If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or * '\'. * * @param targetPath is calculated to this file * @param basePath is calculated from this file * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example) * @return target relative path from the base */
Get the relative path from one file to another, specifying the directory separator. If one of the provided resources does not exist, it is assumed to be a file unless it ends with '/' or '\'
getRelativePath
{ "repo_name": "NCIP/caadapter", "path": "software/cmts/src/java/gov/nih/nci/cbiit/cmts/util/ResourceUtils.java", "license": "bsd-3-clause", "size": 5797 }
[ "java.io.File", "java.util.regex.Pattern", "org.apache.commons.io.FilenameUtils" ]
import java.io.File; import java.util.regex.Pattern; import org.apache.commons.io.FilenameUtils;
import java.io.*; import java.util.regex.*; import org.apache.commons.io.*;
[ "java.io", "java.util", "org.apache.commons" ]
java.io; java.util; org.apache.commons;
1,363,929
public static Properties extractPrefixedProperties(Properties properties, String prefix) { Properties ret = new Properties(); Set<Object> sourceKeys = properties.keySet(); for (Object key : sourceKeys) { String keyStr = (String) key; if (keyStr.startsWith(prefix)) { String newStr = keyStr.substring(prefix.length()); ret.setProperty(newStr, properties.getProperty(keyStr)); } } return ret; }
static Properties function(Properties properties, String prefix) { Properties ret = new Properties(); Set<Object> sourceKeys = properties.keySet(); for (Object key : sourceKeys) { String keyStr = (String) key; if (keyStr.startsWith(prefix)) { String newStr = keyStr.substring(prefix.length()); ret.setProperty(newStr, properties.getProperty(keyStr)); } } return ret; }
/** * Build a {@code Properties} object containing key-value pairs from * the given data where the keys are prefixed with the given * {@code prefix}. The keys in the returned object will be stripped * of their common prefix. * * @param properties Key-value data from which to extract pairs * @param prefix Key-value pairs where the key has this prefix will * be retained in the returned {@code Properties} object * @return A Properties object containing those key-value pairs from * {@code properties} where the key was prefixed by * {@code prefix}. This prefix is removed from all keys in * the returned structure. */
Build a Properties object containing key-value pairs from the given data where the keys are prefixed with the given prefix. The keys in the returned object will be stripped of their common prefix
extractPrefixedProperties
{ "repo_name": "sanjithuom/Stanford-corenlp", "path": "src/edu/stanford/nlp/util/PropertiesUtils.java", "license": "gpl-2.0", "size": 10400 }
[ "java.util.Properties", "java.util.Set" ]
import java.util.Properties; import java.util.Set;
import java.util.*;
[ "java.util" ]
java.util;
12,871
public OperationStatus[] batchMutate( Mutation[] mutations, long nonceGroup, long nonce) throws IOException { // As it stands, this is used for 3 things // * batchMutate with single mutation - put/delete, separate or from checkAndMutate. // * coprocessor calls (see ex. BulkDeleteEndpoint). // So nonces are not really ever used by HBase. They could be by coprocs, and checkAnd... return batchMutate(new MutationBatch(mutations, nonceGroup, nonce)); }
OperationStatus[] function( Mutation[] mutations, long nonceGroup, long nonce) throws IOException { return batchMutate(new MutationBatch(mutations, nonceGroup, nonce)); }
/** * Perform a batch of mutations. * It supports only Put and Delete mutations and will ignore other types passed. * @param mutations the list of mutations * @return an array of OperationStatus which internally contains the * OperationStatusCode and the exceptionMessage if any. * @throws IOException */
Perform a batch of mutations. It supports only Put and Delete mutations and will ignore other types passed
batchMutate
{ "repo_name": "throughsky/lywebank", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/HRegion.java", "license": "apache-2.0", "size": 235118 }
[ "java.io.IOException", "org.apache.hadoop.hbase.client.Mutation" ]
import java.io.IOException; import org.apache.hadoop.hbase.client.Mutation;
import java.io.*; import org.apache.hadoop.hbase.client.*;
[ "java.io", "org.apache.hadoop" ]
java.io; org.apache.hadoop;
1,972,049
@Test public void testMixedFormatAllowsFutureVersions() throws Exception { storage.graalInfo.put(CommonConstants.CAP_GRAALVM_VERSION, "1.0.0"); setupCatalogFormat1("catalogFormatMix.properties"); List<ComponentInfo> infos; Version gv = getLocalRegistry().getGraalVersion(); Version.Match selector = gv.match(Version.Match.Type.INSTALLABLE); // check that versions 1.0.0-rcX are ignored for version 1.0.0 infos = new ArrayList<>(registry.loadComponents("ruby", selector, verbose)); assertNotNull(infos); assertEquals(3, infos.size()); Collections.sort(infos, ComponentInfo.versionComparator()); ComponentInfo one = infos.get(0); ComponentInfo two = infos.get(1); ComponentInfo three = infos.get(2); assertEquals("1.0.0", one.getVersionString()); assertEquals("1.0.1.0", two.getVersionString()); assertEquals("1.0.2.0-1", three.getVersionString()); }
void function() throws Exception { storage.graalInfo.put(CommonConstants.CAP_GRAALVM_VERSION, "1.0.0"); setupCatalogFormat1(STR); List<ComponentInfo> infos; Version gv = getLocalRegistry().getGraalVersion(); Version.Match selector = gv.match(Version.Match.Type.INSTALLABLE); infos = new ArrayList<>(registry.loadComponents("ruby", selector, verbose)); assertNotNull(infos); assertEquals(3, infos.size()); Collections.sort(infos, ComponentInfo.versionComparator()); ComponentInfo one = infos.get(0); ComponentInfo two = infos.get(1); ComponentInfo three = infos.get(2); assertEquals("1.0.0", one.getVersionString()); assertEquals(STR, two.getVersionString()); assertEquals(STR, three.getVersionString()); }
/** * Checks that if a catalog mixes in new-format entries, they're read and processed for new * versions, too. * * @throws Exception */
Checks that if a catalog mixes in new-format entries, they're read and processed for new versions, too
testMixedFormatAllowsFutureVersions
{ "repo_name": "smarr/Truffle", "path": "vm/src/org.graalvm.component.installer.test/src/org/graalvm/component/installer/remote/CatalogCompatTest.java", "license": "gpl-2.0", "size": 10492 }
[ "java.util.ArrayList", "java.util.Collections", "java.util.List", "org.graalvm.component.installer.CommonConstants", "org.graalvm.component.installer.Version", "org.graalvm.component.installer.model.ComponentInfo", "org.junit.Assert" ]
import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.graalvm.component.installer.CommonConstants; import org.graalvm.component.installer.Version; import org.graalvm.component.installer.model.ComponentInfo; import org.junit.Assert;
import java.util.*; import org.graalvm.component.installer.*; import org.graalvm.component.installer.model.*; import org.junit.*;
[ "java.util", "org.graalvm.component", "org.junit" ]
java.util; org.graalvm.component; org.junit;
2,184,893
public void marshallToOutputStreamNoNamespacePrefixes(Object container, OutputStream stream, Boolean includeXmlns) throws DhxException;
void function(Object container, OutputStream stream, Boolean includeXmlns) throws DhxException;
/** * Marshalls object to outputStream, removes all namespace prefixes from XML. * * @param container - object to marshall * @param stream - containing marshalled object * @param includeXmlns if true, then xmlns will be added * @throws DhxException - thrown if error occurs while marshalling object */
Marshalls object to outputStream, removes all namespace prefixes from XML
marshallToOutputStreamNoNamespacePrefixes
{ "repo_name": "e-gov/DHX-adapter", "path": "dhx-adapter-ws/src/main/java/ee/ria/dhx/ws/service/DhxMarshallerService.java", "license": "mit", "size": 6880 }
[ "ee.ria.dhx.exception.DhxException", "java.io.OutputStream" ]
import ee.ria.dhx.exception.DhxException; import java.io.OutputStream;
import ee.ria.dhx.exception.*; import java.io.*;
[ "ee.ria.dhx", "java.io" ]
ee.ria.dhx; java.io;
2,516,111
public void setEndDate(Date end) { this.endDate = end; }
void function(Date end) { this.endDate = end; }
/** * Sets the end date of the picker. Only applicable for types {@link Display#PICKER_TYPE_DATE_AND_TIME} and {@link Display#PICKER_TYPE_DATE}. * Also, only applicable to lightweight picker (i.e. {@link #isUseLightweightPopup() } == {@literal true}. * * <p>This does not affect the time. Only the date. You can set the hour range using {@link #setHourRange(int, int) }.</p> * @param end The end date. * @since 6.0 * @see #setStartDate(java.util.Date) * @see #getEndDate() */
Sets the end date of the picker. Only applicable for types <code>Display#PICKER_TYPE_DATE_AND_TIME</code> and <code>Display#PICKER_TYPE_DATE</code>. Also, only applicable to lightweight picker (i.e. <code>#isUseLightweightPopup() </code> == true. This does not affect the time. Only the date. You can set the hour range using <code>#setHourRange(int, int) </code>
setEndDate
{ "repo_name": "codenameone/CodenameOne", "path": "CodenameOne/src/com/codename1/ui/spinner/Picker.java", "license": "gpl-2.0", "size": 61541 }
[ "java.util.Date" ]
import java.util.Date;
import java.util.*;
[ "java.util" ]
java.util;
2,404,330
interface WithLocation { WithResourceGroup withRegion(Region location);
interface WithLocation { WithResourceGroup withRegion(Region location);
/** * Specifies the region for the resource. * * @param location The geo-location where the resource lives. * @return the next definition stage. */
Specifies the region for the resource
withRegion
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/purview/azure-resourcemanager-purview/src/main/java/com/azure/resourcemanager/purview/models/Account.java", "license": "mit", "size": 13986 }
[ "com.azure.core.management.Region" ]
import com.azure.core.management.Region;
import com.azure.core.management.*;
[ "com.azure.core" ]
com.azure.core;
2,595,720
public DiagramComponent getDiagramComponent(final Object object) { return (DiagramComponent) this.componentMap.get(object); }
DiagramComponent function(final Object object) { return (DiagramComponent) this.componentMap.get(object); }
/** * Looks up the diagram component in this diagram that is related to the * specified database object. If there is no component related to that * object, then null is returned, otherwise the component is returned. * * @param object * the database object to look up the component for. * @return the diagram component that represents that database object in * this diagram, or null if that model object is not in this diagram * at all. */
Looks up the diagram component in this diagram that is related to the specified database object. If there is no component related to that object, then null is returned, otherwise the component is returned
getDiagramComponent
{ "repo_name": "pubmed2ensembl/MartScript", "path": "src/org/biomart/builder/view/gui/diagrams/Diagram.java", "license": "lgpl-2.1", "size": 33876 }
[ "org.biomart.builder.view.gui.diagrams.components.DiagramComponent" ]
import org.biomart.builder.view.gui.diagrams.components.DiagramComponent;
import org.biomart.builder.view.gui.diagrams.components.*;
[ "org.biomart.builder" ]
org.biomart.builder;
94,764
private final int findStripeIndexByEndRow(byte[] endRow) { assert !isInvalid(endRow); if (isOpen(endRow)) return state.stripeEndRows.length; return Arrays.binarySearch(state.stripeEndRows, endRow, Bytes.BYTES_COMPARATOR); }
final int function(byte[] endRow) { assert !isInvalid(endRow); if (isOpen(endRow)) return state.stripeEndRows.length; return Arrays.binarySearch(state.stripeEndRows, endRow, Bytes.BYTES_COMPARATOR); }
/** * Finds the stripe index by end row. */
Finds the stripe index by end row
findStripeIndexByEndRow
{ "repo_name": "Jackygq1982/hbase_src", "path": "hbase-server/src/main/java/org/apache/hadoop/hbase/regionserver/StripeStoreFileManager.java", "license": "apache-2.0", "size": 40486 }
[ "java.util.Arrays", "org.apache.hadoop.hbase.util.Bytes" ]
import java.util.Arrays; import org.apache.hadoop.hbase.util.Bytes;
import java.util.*; import org.apache.hadoop.hbase.util.*;
[ "java.util", "org.apache.hadoop" ]
java.util; org.apache.hadoop;
136,296
ClassDescription getDescriptionClass();
ClassDescription getDescriptionClass();
/** * Returns the original description class. * @return the description class */
Returns the original description class
getDescriptionClass
{ "repo_name": "asakusafw/asakusafw-compiler", "path": "compiler-project/model/src/main/java/com/asakusafw/lang/compiler/model/info/DescriptionInfo.java", "license": "apache-2.0", "size": 998 }
[ "com.asakusafw.lang.compiler.model.description.ClassDescription" ]
import com.asakusafw.lang.compiler.model.description.ClassDescription;
import com.asakusafw.lang.compiler.model.description.*;
[ "com.asakusafw.lang" ]
com.asakusafw.lang;
2,118,745
public static long getFileLength(final String filePath) { boolean isURL = filePath.matches("[a-zA-z]+://[^\\s]*"); if (isURL) { try { HttpURLConnection conn = (HttpURLConnection) new URL(filePath).openConnection(); conn.setRequestProperty("Accept-Encoding", "identity"); conn.connect(); if (conn.getResponseCode() == 200) { return conn.getContentLength(); } return -1; } catch (IOException e) { e.printStackTrace(); } } return getFileLength(getFileByPath(filePath)); }
static long function(final String filePath) { boolean isURL = filePath.matches(STRAccept-EncodingSTRidentity"); conn.connect(); if (conn.getResponseCode() == 200) { return conn.getContentLength(); } return -1; } catch (IOException e) { e.printStackTrace(); } } return getFileLength(getFileByPath(filePath)); }
/** * Return the length of file. * * @param filePath The path of file. * @return the length of file */
Return the length of file
getFileLength
{ "repo_name": "treason258/TreLibrary", "path": "LovelyReaderAS/app/src/main/java/com/haoyang/lovelyreader/tre/util/FileUtils.java", "license": "apache-2.0", "size": 41121 }
[ "java.io.IOException" ]
import java.io.IOException;
import java.io.*;
[ "java.io" ]
java.io;
852,613
public Descriptor<AbstractRestriction> getDescriptor() { return (Descriptor<AbstractRestriction>) checkNotNull(Jenkins.getInstance()) .getDescriptor(getClass()); }
Descriptor<AbstractRestriction> function() { return (Descriptor<AbstractRestriction>) checkNotNull(Jenkins.getInstance()) .getDescriptor(getClass()); }
/** * Boilerplate, see: * https://wiki.jenkins-ci.org/display/JENKINS/Defining+a+new+extension+point */
Boilerplate, see: HREF
getDescriptor
{ "repo_name": "jenkinsci/yaml-project-plugin", "path": "src/main/java/com/google/jenkins/plugins/dsl/restrict/AbstractRestriction.java", "license": "apache-2.0", "size": 3576 }
[ "com.google.common.base.Preconditions", "hudson.model.Descriptor" ]
import com.google.common.base.Preconditions; import hudson.model.Descriptor;
import com.google.common.base.*; import hudson.model.*;
[ "com.google.common", "hudson.model" ]
com.google.common; hudson.model;
1,302,272
@FXML private void handleNameClick(final MouseEvent event) { String name = mListNames.getSelectionModel().getSelectedItem(); if (event.getButton() == MouseButton.SECONDARY) { createContextMenu(name).show(getRoot(), event.getScreenX(), event.getScreenY()); } else { if (name != null && !name.equals(mPreviousName)) { showPicturesForName(name); } PreferenceUtil.setPreference(KEY_LAST_NAME, name); } }
void function(final MouseEvent event) { String name = mListNames.getSelectionModel().getSelectedItem(); if (event.getButton() == MouseButton.SECONDARY) { createContextMenu(name).show(getRoot(), event.getScreenX(), event.getScreenY()); } else { if (name != null && !name.equals(mPreviousName)) { showPicturesForName(name); } PreferenceUtil.setPreference(KEY_LAST_NAME, name); } }
/** * Handler for Click on name on list. Displays the eye photo pairs for that name. * * @param event * The action event. */
Handler for Click on name on list. Displays the eye photo pairs for that name
handleNameClick
{ "repo_name": "jeisfeld/Augendiagnose", "path": "AugendiagnoseFX/src/de/eisfeldj/augendiagnosefx/controller/DisplayPhotosController.java", "license": "gpl-2.0", "size": 11388 }
[ "de.eisfeldj.augendiagnosefx.util.PreferenceUtil" ]
import de.eisfeldj.augendiagnosefx.util.PreferenceUtil;
import de.eisfeldj.augendiagnosefx.util.*;
[ "de.eisfeldj.augendiagnosefx" ]
de.eisfeldj.augendiagnosefx;
2,256,468
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(int expSize) { return new LinkedHashMap<>(capacity(expSize)); }
static <K, V> LinkedHashMap<K, V> function(int expSize) { return new LinkedHashMap<>(capacity(expSize)); }
/** * Creates new {@link LinkedHashMap} with expected size. * * @param expSize Expected size of created map. * @param <K> Type of map keys. * @param <V> Type of map values. * @return New map. */
Creates new <code>LinkedHashMap</code> with expected size
newLinkedHashMap
{ "repo_name": "apache/ignite", "path": "modules/core/src/main/java/org/apache/ignite/internal/util/IgniteUtils.java", "license": "apache-2.0", "size": 387878 }
[ "java.util.LinkedHashMap" ]
import java.util.LinkedHashMap;
import java.util.*;
[ "java.util" ]
java.util;
1,234,888
public ACData[] selectQCfromQCQ(ACData qcq_[]) { String select = "select 's', 1, 'qc', qc.qc_idseq as id, qc.version, qc.qc_id, qc.long_name, qc.conte_idseq as cid, " + "qc.date_modified, qc.date_created, qc.modified_by, qc.created_by, qc.change_note, c.name, qc2.qc_idseq " + "from sbrext.quest_contents_view_ext qc, sbrext.quest_contents_view_ext qc2, sbr.contexts_view c " + "where qc2.qc_idseq in (?) and qc2.qtl_name in ('QUESTION', 'QUESTION_INSTR') and qc2.p_mod_idseq is null and " + "qc.qc_idseq = qc2.dn_crf_idseq and c.conte_idseq = qc.conte_idseq " + "order by id asc, cid asc"; return selectAC(select, qcq_); }
ACData[] function(ACData qcq_[]) { String select = STR + STR + STR + STR + STR + STR; return selectAC(select, qcq_); }
/** * Select the Forms/Templates affected by the Value Domains provided. * * @param qcq_ * The data element list. * @return The array of related forms/templates. */
Select the Forms/Templates affected by the Value Domains provided
selectQCfromQCQ
{ "repo_name": "NCIP/cadsr-sentinel", "path": "software/src/java/gov/nih/nci/cadsr/sentinel/database/DBAlertOracle.java", "license": "bsd-3-clause", "size": 324316 }
[ "gov.nih.nci.cadsr.sentinel.tool.ACData" ]
import gov.nih.nci.cadsr.sentinel.tool.ACData;
import gov.nih.nci.cadsr.sentinel.tool.*;
[ "gov.nih.nci" ]
gov.nih.nci;
777,593
@Override public void processOrderProperties(Object... properties) { this.setOrderProperty(JmsOrderProperties.RETRIEVE_AE_TITLE, this.retrieveAET); this.setOrderProperty(JmsOrderProperties.DESTINATION_AE_TITLE, this.moveDestination); this.setOrderProperty(JmsOrderProperties.PATIENT_ID, this.patientId); this.setOrderMultiProperty(JmsOrderProperties.STUDY_INSTANCE_UID, this.studyIuids); this.setOrderMultiProperty(JmsOrderProperties.SERIES_INSTANCE_UID, this.seriesIuids); }
void function(Object... properties) { this.setOrderProperty(JmsOrderProperties.RETRIEVE_AE_TITLE, this.retrieveAET); this.setOrderProperty(JmsOrderProperties.DESTINATION_AE_TITLE, this.moveDestination); this.setOrderProperty(JmsOrderProperties.PATIENT_ID, this.patientId); this.setOrderMultiProperty(JmsOrderProperties.STUDY_INSTANCE_UID, this.studyIuids); this.setOrderMultiProperty(JmsOrderProperties.SERIES_INSTANCE_UID, this.seriesIuids); }
/** * Processes order attributes based on the values set in the {@code ctor}. * @see BaseJmsOrder#processOrderProperties(Object...) */
Processes order attributes based on the values set in the ctor
processOrderProperties
{ "repo_name": "medicayun/medicayundicom", "path": "dcm4jboss-all/trunk/dcm4jboss-sar/src/java/org/dcm4chex/archive/dcm/movescu/MoveOrder.java", "license": "apache-2.0", "size": 6904 }
[ "org.dcm4chex.archive.common.JmsOrderProperties" ]
import org.dcm4chex.archive.common.JmsOrderProperties;
import org.dcm4chex.archive.common.*;
[ "org.dcm4chex.archive" ]
org.dcm4chex.archive;
730,712
SpaceTemplate getSpaceTemplateByName(String name);
SpaceTemplate getSpaceTemplateByName(String name);
/** * Gets a space template by name * * @param name * @return The space template. * */
Gets a space template by name
getSpaceTemplateByName
{ "repo_name": "exodev/social", "path": "component/core/src/main/java/org/exoplatform/social/core/space/spi/SpaceTemplateService.java", "license": "lgpl-3.0", "size": 3835 }
[ "org.exoplatform.social.core.space.SpaceTemplate" ]
import org.exoplatform.social.core.space.SpaceTemplate;
import org.exoplatform.social.core.space.*;
[ "org.exoplatform.social" ]
org.exoplatform.social;
1,440,879
CalendarBuilder cb = new CalendarBuilder(); FileInputStream fis = new FileInputStream(baseDir + "limit_recurr_test.ics"); Calendar calendar = cb.build(fis); Assert.assertEquals(5, calendar.getComponents().getComponents("VEVENT").size()); VTimeZone vtz = (VTimeZone) calendar.getComponents().getComponent("VTIMEZONE"); TimeZone tz = new TimeZone(vtz); OutputFilter filter = new OutputFilter("test"); DateTime start = new DateTime("20060104T010000", tz); DateTime end = new DateTime("20060106T010000", tz); start.setUtc(true); end.setUtc(true); Period period = new Period(start, end); filter.setLimit(period); filter.setAllSubComponents(); filter.setAllProperties(); StringBuilder buffer = new StringBuilder(); filter.filter(calendar, buffer); StringReader sr = new StringReader(buffer.toString()); Calendar filterCal = cb.build(sr); ComponentList<CalendarComponent> comps = filterCal.getComponents(); Assert.assertEquals(3, comps.getComponents("VEVENT").size()); Assert.assertEquals(1, comps.getComponents("VTIMEZONE").size()); // Make sure 3rd and 4th override are dropped ComponentList<CalendarComponent> events = comps.getComponents("VEVENT"); for(CalendarComponent c : events) { Assert.assertNotSame("event 6 changed 3",((Summary) c.getProperties().getProperty("SUMMARY")).getValue()); Assert.assertNotSame("event 6 changed 4",((Summary) c.getProperties().getProperty("SUMMARY")).getValue()); } }
CalendarBuilder cb = new CalendarBuilder(); FileInputStream fis = new FileInputStream(baseDir + STR); Calendar calendar = cb.build(fis); Assert.assertEquals(5, calendar.getComponents().getComponents(STR).size()); VTimeZone vtz = (VTimeZone) calendar.getComponents().getComponent(STR); TimeZone tz = new TimeZone(vtz); OutputFilter filter = new OutputFilter("test"); DateTime start = new DateTime(STR, tz); DateTime end = new DateTime(STR, tz); start.setUtc(true); end.setUtc(true); Period period = new Period(start, end); filter.setLimit(period); filter.setAllSubComponents(); filter.setAllProperties(); StringBuilder buffer = new StringBuilder(); filter.filter(calendar, buffer); StringReader sr = new StringReader(buffer.toString()); Calendar filterCal = cb.build(sr); ComponentList<CalendarComponent> comps = filterCal.getComponents(); Assert.assertEquals(3, comps.getComponents(STR).size()); Assert.assertEquals(1, comps.getComponents(STR).size()); ComponentList<CalendarComponent> events = comps.getComponents(STR); for(CalendarComponent c : events) { Assert.assertNotSame(STR,((Summary) c.getProperties().getProperty(STR)).getValue()); Assert.assertNotSame(STR,((Summary) c.getProperties().getProperty(STR)).getValue()); } }
/** * Tests limit recurrence set. * @throws Exception - if something is wrong this exception is thrown. */
Tests limit recurrence set
testLimitRecurrenceSet
{ "repo_name": "1and1/cosmo", "path": "cosmo-core/src/test/unit/java/org/unitedinternet/cosmo/calendar/data/LimitRecurrenceSetTest.java", "license": "apache-2.0", "size": 6707 }
[ "java.io.FileInputStream", "java.io.StringReader", "net.fortuna.ical4j.data.CalendarBuilder", "net.fortuna.ical4j.model.Calendar", "net.fortuna.ical4j.model.ComponentList", "net.fortuna.ical4j.model.DateTime", "net.fortuna.ical4j.model.Period", "net.fortuna.ical4j.model.TimeZone", "net.fortuna.ical4j.model.component.CalendarComponent", "net.fortuna.ical4j.model.component.VTimeZone", "net.fortuna.ical4j.model.property.Summary", "org.junit.Assert" ]
import java.io.FileInputStream; import java.io.StringReader; import net.fortuna.ical4j.data.CalendarBuilder; import net.fortuna.ical4j.model.Calendar; import net.fortuna.ical4j.model.ComponentList; import net.fortuna.ical4j.model.DateTime; import net.fortuna.ical4j.model.Period; import net.fortuna.ical4j.model.TimeZone; import net.fortuna.ical4j.model.component.CalendarComponent; import net.fortuna.ical4j.model.component.VTimeZone; import net.fortuna.ical4j.model.property.Summary; import org.junit.Assert;
import java.io.*; import net.fortuna.ical4j.data.*; import net.fortuna.ical4j.model.*; import net.fortuna.ical4j.model.component.*; import net.fortuna.ical4j.model.property.*; import org.junit.*;
[ "java.io", "net.fortuna.ical4j", "org.junit" ]
java.io; net.fortuna.ical4j; org.junit;
2,471,241
public static void write(byte[] data, Writer output) throws IOException { write(data, output, Charset.defaultCharset()); }
static void function(byte[] data, Writer output) throws IOException { write(data, output, Charset.defaultCharset()); }
/** * Writes bytes from a <code>byte[]</code> to chars on a <code>Writer</code> * using the default character encoding of the platform. * <p> * This method uses {@link String#String(byte[])}. * * @param data the byte array to write, do not modify during output, * null ignored * @param output the <code>Writer</code> to write to * @throws NullPointerException if output is null * @throws IOException if an I/O error occurs * @since 1.1 */
Writes bytes from a <code>byte[]</code> to chars on a <code>Writer</code> using the default character encoding of the platform. This method uses <code>String#String(byte[])</code>
write
{ "repo_name": "wspeirs/sop4j-base", "path": "src/main/java/com/sop4j/base/apache/io/IOUtils.java", "license": "apache-2.0", "size": 97933 }
[ "java.io.IOException", "java.io.Writer", "java.nio.charset.Charset" ]
import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset;
import java.io.*; import java.nio.charset.*;
[ "java.io", "java.nio" ]
java.io; java.nio;
186,617
@Override public ZipkinDependencies rename(String name) { return new ZipkinDependencies(DSL.name(name), null); }
ZipkinDependencies function(String name) { return new ZipkinDependencies(DSL.name(name), null); }
/** * Rename this table */
Rename this table
rename
{ "repo_name": "twitter/zipkin", "path": "zipkin-storage/mysql-v1/src/main/java/zipkin2/storage/mysql/v1/internal/generated/tables/ZipkinDependencies.java", "license": "apache-2.0", "size": 4213 }
[ "org.jooq.impl.DSL" ]
import org.jooq.impl.DSL;
import org.jooq.impl.*;
[ "org.jooq.impl" ]
org.jooq.impl;
1,563,099
public static void removeConsecutiveSeparators(JMenu menu) { removeConsecutiveSeparators(menu.getPopupMenu()); }
static void function(JMenu menu) { removeConsecutiveSeparators(menu.getPopupMenu()); }
/** * Convenience method that calls the method {@code removeConsecutiveSeparators(JPopupMenu)} with * the {@code JPopupMenu} of the given {@code menu} as parameter. * * @param menu the menu whose consecutive separators will be removed * @see #removeConsecutiveSeparators(JPopupMenu) * @see JMenu#getPopupMenu() * @see javax.swing.JPopupMenu.Separator */
Convenience method that calls the method removeConsecutiveSeparators(JPopupMenu) with the JPopupMenu of the given menu as parameter
removeConsecutiveSeparators
{ "repo_name": "psiinon/zaproxy", "path": "zap/src/main/java/org/zaproxy/zap/view/popup/PopupMenuUtils.java", "license": "apache-2.0", "size": 20633 }
[ "javax.swing.JMenu" ]
import javax.swing.JMenu;
import javax.swing.*;
[ "javax.swing" ]
javax.swing;
726,196
public Collection<LGraph> getComponents(final Set<PortSide> connections) { return components.get(connections); }
Collection<LGraph> function(final Set<PortSide> connections) { return components.get(connections); }
/** * Returns the components in this component group connected to external ports on the given set * of port sides. * * @param connections external port sides the returned components are to be connected to. * @return the collection of components. If there are no components, an empty collection is * returned. */
Returns the components in this component group connected to external ports on the given set of port sides
getComponents
{ "repo_name": "eNBeWe/elk", "path": "plugins/org.eclipse.elk.alg.layered/src/org/eclipse/elk/alg/layered/components/ComponentGroup.java", "license": "epl-1.0", "size": 11478 }
[ "java.util.Collection", "java.util.Set", "org.eclipse.elk.alg.layered.graph.LGraph", "org.eclipse.elk.core.options.PortSide" ]
import java.util.Collection; import java.util.Set; import org.eclipse.elk.alg.layered.graph.LGraph; import org.eclipse.elk.core.options.PortSide;
import java.util.*; import org.eclipse.elk.alg.layered.graph.*; import org.eclipse.elk.core.options.*;
[ "java.util", "org.eclipse.elk" ]
java.util; org.eclipse.elk;
2,159,860
private JPanel getContentPanel() { if (contentPanel == null) { GridBagConstraints gridBagConstraints4 = new GridBagConstraints(); contentPanel = new JPanel(); contentPanel.setLayout(new GridBagLayout()); contentPanel .setBorder(javax.swing.BorderFactory .createTitledBorder( null, "Trusted IdPs", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, LookAndFeel.getPanelLabelColor())); gridBagConstraints4.weightx = 1.0; gridBagConstraints4.gridy = 0; gridBagConstraints4.gridx = 0; gridBagConstraints4.weighty = 1.0; gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH; contentPanel.add(getJScrollPane(), gridBagConstraints4); } return contentPanel; }
JPanel function() { if (contentPanel == null) { GridBagConstraints gridBagConstraints4 = new GridBagConstraints(); contentPanel = new JPanel(); contentPanel.setLayout(new GridBagLayout()); contentPanel .setBorder(javax.swing.BorderFactory .createTitledBorder( null, STR, javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, null, LookAndFeel.getPanelLabelColor())); gridBagConstraints4.weightx = 1.0; gridBagConstraints4.gridy = 0; gridBagConstraints4.gridx = 0; gridBagConstraints4.weighty = 1.0; gridBagConstraints4.fill = java.awt.GridBagConstraints.BOTH; contentPanel.add(getJScrollPane(), gridBagConstraints4); } return contentPanel; }
/** * This method initializes jPanel * * @return javax.swing.JPanel */
This method initializes jPanel
getContentPanel
{ "repo_name": "NCIP/cagrid-core", "path": "caGrid/projects/gaards-ui/src/org/cagrid/gaards/ui/dorian/federation/TrustedIdPsWindow.java", "license": "bsd-3-clause", "size": 13532 }
[ "java.awt.GridBagConstraints", "java.awt.GridBagLayout", "javax.swing.JPanel", "org.cagrid.grape.LookAndFeel" ]
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JPanel; import org.cagrid.grape.LookAndFeel;
import java.awt.*; import javax.swing.*; import org.cagrid.grape.*;
[ "java.awt", "javax.swing", "org.cagrid.grape" ]
java.awt; javax.swing; org.cagrid.grape;
2,369,910
public Map<String, Serializable> getValues() { return model.getValues(); }
Map<String, Serializable> function() { return model.getValues(); }
/** * Getter for the Values. * * @return the Map<String, Serializable>. */
Getter for the Values
getValues
{ "repo_name": "NABUCCO/org.nabucco.framework.support.scripting", "path": "org.nabucco.framework.support.scripting.ui.rcp/src/main/gen/org/nabucco/framework/support/scripting/ui/rcp/list/script/view/ScriptListView.java", "license": "epl-1.0", "size": 2844 }
[ "java.io.Serializable", "java.util.Map" ]
import java.io.Serializable; import java.util.Map;
import java.io.*; import java.util.*;
[ "java.io", "java.util" ]
java.io; java.util;
1,138,791
protected void testWarning(List<SourceFile> inputs, DiagnosticType warning, String description) { assertNotNull(warning); test(srcs(inputs), warning(warning, description)); }
void function(List<SourceFile> inputs, DiagnosticType warning, String description) { assertNotNull(warning); test(srcs(inputs), warning(warning, description)); }
/** * Verifies that the compiler generates the given warning for the given input. */
Verifies that the compiler generates the given warning for the given input
testWarning
{ "repo_name": "MatrixFrog/closure-compiler", "path": "test/com/google/javascript/jscomp/CompilerTestCase.java", "license": "apache-2.0", "size": 77821 }
[ "java.util.List" ]
import java.util.List;
import java.util.*;
[ "java.util" ]
java.util;
727,357
if (isValid()) { Pixels pixels = source.getLatestPixels(); if (pixels != null) { try { EmbeddedScene escene = (EmbeddedScene) scene; // Pixels are always stored in an IntBuffer for uploading escene.uploadPixels(pixels); } finally { source.doneWithPixels(pixels); } } } else { source.skipLatestPixels(); } }
if (isValid()) { Pixels pixels = source.getLatestPixels(); if (pixels != null) { try { EmbeddedScene escene = (EmbeddedScene) scene; escene.uploadPixels(pixels); } finally { source.doneWithPixels(pixels); } } } else { source.skipLatestPixels(); } }
/** * Put the pixels on the screen. * * @param source - the source for the Pixels object to be uploaded */
Put the pixels on the screen
uploadPixels
{ "repo_name": "teamfx/openjfx-9-dev-rt", "path": "modules/javafx.graphics/src/main/java/com/sun/javafx/tk/quantum/EmbeddedState.java", "license": "gpl-2.0", "size": 3480 }
[ "com.sun.glass.ui.Pixels" ]
import com.sun.glass.ui.Pixels;
import com.sun.glass.ui.*;
[ "com.sun.glass" ]
com.sun.glass;
1,755,925
protected WebResponse click(final WebRequest request) throws IOException { WebResponse response = this.service(request); try { Assert.assertNotNull("No response for:" + request.getURL(), response); } catch (final MalformedURLException e) { Assert.fail("Invalid URL in request"); } int code = response.getResponseCode(); this.addHistory(request.getMethod() + " " + code + " " + response.getURL()); if (HttpServletResponse.SC_MOVED_TEMPORARILY == code || HttpServletResponse.SC_SEE_OTHER == code) { final String location = response.getHeaderField("location"); response = this.get(location, Collections.EMPTY_MAP); code = response.getResponseCode(); } if (HttpServletResponse.SC_OK == code || HttpServletResponse.SC_ACCEPTED == code || HttpServletResponse.SC_BAD_REQUEST == code || HttpServletResponse.SC_INTERNAL_SERVER_ERROR == code) { return response; } if (HttpServletResponse.SC_FORBIDDEN == code) { this.onForbidden(request, response); return null; } this.printHistory(); Assert.fail("not OK getting: " + response.getURL() + " " + response.getResponseMessage()); return null; // not actually executed, fail does not return }
WebResponse function(final WebRequest request) throws IOException { WebResponse response = this.service(request); try { Assert.assertNotNull(STR + request.getURL(), response); } catch (final MalformedURLException e) { Assert.fail(STR); } int code = response.getResponseCode(); this.addHistory(request.getMethod() + " " + code + " " + response.getURL()); if (HttpServletResponse.SC_MOVED_TEMPORARILY == code HttpServletResponse.SC_SEE_OTHER == code) { final String location = response.getHeaderField(STR); response = this.get(location, Collections.EMPTY_MAP); code = response.getResponseCode(); } if (HttpServletResponse.SC_OK == code HttpServletResponse.SC_ACCEPTED == code HttpServletResponse.SC_BAD_REQUEST == code HttpServletResponse.SC_INTERNAL_SERVER_ERROR == code) { return response; } if (HttpServletResponse.SC_FORBIDDEN == code) { this.onForbidden(request, response); return null; } this.printHistory(); Assert.fail(STR + response.getURL() + " " + response.getResponseMessage()); return null; }
/** * Perform a request * * @param request the link to follow * @return the response * @throws IOException */
Perform a request
click
{ "repo_name": "homiak/pims-lims", "path": "TestSource/org/pimslims/servlet/remote/RemoteTest.java", "license": "bsd-2-clause", "size": 22329 }
[ "com.meterware.httpunit.WebRequest", "com.meterware.httpunit.WebResponse", "java.io.IOException", "java.net.MalformedURLException", "java.util.Collections", "javax.servlet.http.HttpServletResponse", "junit.framework.Assert" ]
import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; import java.io.IOException; import java.net.MalformedURLException; import java.util.Collections; import javax.servlet.http.HttpServletResponse; import junit.framework.Assert;
import com.meterware.httpunit.*; import java.io.*; import java.net.*; import java.util.*; import javax.servlet.http.*; import junit.framework.*;
[ "com.meterware.httpunit", "java.io", "java.net", "java.util", "javax.servlet", "junit.framework" ]
com.meterware.httpunit; java.io; java.net; java.util; javax.servlet; junit.framework;
1,316,631
public Grid2D backprojectPixelDrivenCL(Grid2D sino) { this.initSinogramParams(sino); boolean debug = true; // create context CLContext context = OpenCLUtil.createContext(); if (debug) System.out.println("Context: " + context); //show OpenCL devices in System CLDevice[] devices = context.getDevices(); if (debug){ for (CLDevice dev: devices) System.out.println(dev); } // select device CLDevice device = context.getMaxFlopsDevice(); if (debug) System.out.println("Device: " + device); int sinoSize = maxBetaIndex*maxTIndex; // Length of arrays to process int localWorkSize = Math.min(device.getMaxWorkGroupSize(), 16); // Local work size dimensions int globalWorkSizeX = OpenCLUtil.roundUp(localWorkSize, imgSizeX); // rounded up to the nearest multiple of localWorkSize int globalWorkSizeY = OpenCLUtil.roundUp(localWorkSize, imgSizeY); // rounded up to the nearest multiple of localWorkSize // load sources, create and build program CLProgram program = null; try { program = context.createProgram(this.getClass().getResourceAsStream("FanBeamBackProjectorPixel.cl")) .build(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(-1); } // create image from input grid CLImageFormat format = new CLImageFormat(ChannelOrder.INTENSITY, ChannelType.FLOAT); CLBuffer<FloatBuffer> sinoBuffer = context.createFloatBuffer(sinoSize, Mem.READ_ONLY); for (int i=0;i<sinoSize;++i){ sinoBuffer.getBuffer().put(((Grid2D)sino).getBuffer()[i]); } sinoBuffer.getBuffer().rewind(); /// CP CLImage2d<FloatBuffer> sinoGrid = context.createImage2d( sinoBuffer.getBuffer(), sino.getSize()[0], sino.getSize()[1], format); sinoBuffer.release(); // create memory for output image CLBuffer<FloatBuffer> imgBuffer = context.createFloatBuffer(imgSizeX*imgSizeY, Mem.WRITE_ONLY); // copy params CLKernel kernel = program.createCLKernel("backprojectPixelDriven2DCL"); kernel.putArg(sinoGrid).putArg(imgBuffer) .putArg(imgSizeX).putArg(imgSizeY) .putArg((float)maxT).putArg((float)deltaT) .putArg((float)maxBeta).putArg((float)deltaBeta) .putArg((float)focalLength).putArg(maxTIndex).putArg(maxBetaIndex); // TODO: Spacing :) // createCommandQueue CLCommandQueue queue = device.createCommandQueue(); queue .putWriteImage(sinoGrid, true) .finish() .put2DRangeKernel(kernel, 0, 0, globalWorkSizeX, globalWorkSizeY, localWorkSize, localWorkSize) .finish() .putReadBuffer(imgBuffer, true) .finish(); // write grid back to grid2D Grid2D img = new Grid2D(this.imgSizeX, this.imgSizeY); //img.setSpacing(pxSzXMM, pxSzYMM); imgBuffer.getBuffer().rewind(); for (int i = 0; i < imgSizeX*imgSizeY; ++i) { ((Grid2D)img).getBuffer()[i] = imgBuffer.getBuffer().get(); } queue.release(); imgBuffer.release(); sinoGrid.release(); kernel.release(); program.release(); context.release(); return img; }
Grid2D function(Grid2D sino) { this.initSinogramParams(sino); boolean debug = true; CLContext context = OpenCLUtil.createContext(); if (debug) System.out.println(STR + context); CLDevice[] devices = context.getDevices(); if (debug){ for (CLDevice dev: devices) System.out.println(dev); } CLDevice device = context.getMaxFlopsDevice(); if (debug) System.out.println(STR + device); int sinoSize = maxBetaIndex*maxTIndex; int localWorkSize = Math.min(device.getMaxWorkGroupSize(), 16); int globalWorkSizeX = OpenCLUtil.roundUp(localWorkSize, imgSizeX); int globalWorkSizeY = OpenCLUtil.roundUp(localWorkSize, imgSizeY); CLProgram program = null; try { program = context.createProgram(this.getClass().getResourceAsStream(STR)) .build(); } catch (IOException e) { e.printStackTrace(); System.exit(-1); } CLImageFormat format = new CLImageFormat(ChannelOrder.INTENSITY, ChannelType.FLOAT); CLBuffer<FloatBuffer> sinoBuffer = context.createFloatBuffer(sinoSize, Mem.READ_ONLY); for (int i=0;i<sinoSize;++i){ sinoBuffer.getBuffer().put(((Grid2D)sino).getBuffer()[i]); } sinoBuffer.getBuffer().rewind(); CLImage2d<FloatBuffer> sinoGrid = context.createImage2d( sinoBuffer.getBuffer(), sino.getSize()[0], sino.getSize()[1], format); sinoBuffer.release(); CLBuffer<FloatBuffer> imgBuffer = context.createFloatBuffer(imgSizeX*imgSizeY, Mem.WRITE_ONLY); CLKernel kernel = program.createCLKernel(STR); kernel.putArg(sinoGrid).putArg(imgBuffer) .putArg(imgSizeX).putArg(imgSizeY) .putArg((float)maxT).putArg((float)deltaT) .putArg((float)maxBeta).putArg((float)deltaBeta) .putArg((float)focalLength).putArg(maxTIndex).putArg(maxBetaIndex); CLCommandQueue queue = device.createCommandQueue(); queue .putWriteImage(sinoGrid, true) .finish() .put2DRangeKernel(kernel, 0, 0, globalWorkSizeX, globalWorkSizeY, localWorkSize, localWorkSize) .finish() .putReadBuffer(imgBuffer, true) .finish(); Grid2D img = new Grid2D(this.imgSizeX, this.imgSizeY); imgBuffer.getBuffer().rewind(); for (int i = 0; i < imgSizeX*imgSizeY; ++i) { ((Grid2D)img).getBuffer()[i] = imgBuffer.getBuffer().get(); } queue.release(); imgBuffer.release(); sinoGrid.release(); kernel.release(); program.release(); context.release(); return img; }
/** * The pixel driven solution for back-projection in a given range and with a given resolution. * * @param sino * the sinogram * @return the image */
The pixel driven solution for back-projection in a given range and with a given resolution
backprojectPixelDrivenCL
{ "repo_name": "YixingHuang/CONRAD", "path": "src/TVreconstruction/FanBeamBackprojector2D.java", "license": "gpl-3.0", "size": 23098 }
[ "com.jogamp.opencl.CLBuffer", "com.jogamp.opencl.CLCommandQueue", "com.jogamp.opencl.CLContext", "com.jogamp.opencl.CLDevice", "com.jogamp.opencl.CLImage2d", "com.jogamp.opencl.CLImageFormat", "com.jogamp.opencl.CLKernel", "com.jogamp.opencl.CLMemory", "com.jogamp.opencl.CLProgram", "edu.stanford.rsl.conrad.data.numeric.Grid2D", "edu.stanford.rsl.conrad.opencl.OpenCLUtil", "java.io.IOException", "java.nio.FloatBuffer" ]
import com.jogamp.opencl.CLBuffer; import com.jogamp.opencl.CLCommandQueue; import com.jogamp.opencl.CLContext; import com.jogamp.opencl.CLDevice; import com.jogamp.opencl.CLImage2d; import com.jogamp.opencl.CLImageFormat; import com.jogamp.opencl.CLKernel; import com.jogamp.opencl.CLMemory; import com.jogamp.opencl.CLProgram; import edu.stanford.rsl.conrad.data.numeric.Grid2D; import edu.stanford.rsl.conrad.opencl.OpenCLUtil; import java.io.IOException; import java.nio.FloatBuffer;
import com.jogamp.opencl.*; import edu.stanford.rsl.conrad.data.numeric.*; import edu.stanford.rsl.conrad.opencl.*; import java.io.*; import java.nio.*;
[ "com.jogamp.opencl", "edu.stanford.rsl", "java.io", "java.nio" ]
com.jogamp.opencl; edu.stanford.rsl; java.io; java.nio;
776,288
EReference getMessage_Interaction();
EReference getMessage_Interaction();
/** * Returns the meta object for the container reference '{@link ca.mcgill.cs.sel.ram.Message#getInteraction <em>Interaction</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the container reference '<em>Interaction</em>'. * @see ca.mcgill.cs.sel.ram.Message#getInteraction() * @see #getMessage() * @generated */
Returns the meta object for the container reference '<code>ca.mcgill.cs.sel.ram.Message#getInteraction Interaction</code>'.
getMessage_Interaction
{ "repo_name": "mjorod/textram", "path": "tool/ca.mcgill.sel.ram/src/ca/mcgill/cs/sel/ram/RamPackage.java", "license": "mit", "size": 271132 }
[ "org.eclipse.emf.ecore.EReference" ]
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
1,065,331
public CreateIndexResponse createIndex(String indexName, int shards) throws DotStateException, IOException{ return createIndex(indexName, null, shards); }
CreateIndexResponse function(String indexName, int shards) throws DotStateException, IOException{ return createIndex(indexName, null, shards); }
/** * Creates an index with default settings. If shards<1 then shards will be default * @param indexName * @param shards * @return * @throws DotStateException * @throws IOException */
Creates an index with default settings. If shards<1 then shards will be default
createIndex
{ "repo_name": "dotCMS/core-2.x", "path": "src/com/dotcms/content/elasticsearch/business/ESIndexAPI.java", "license": "gpl-3.0", "size": 22169 }
[ "com.dotmarketing.business.DotStateException", "java.io.IOException", "org.elasticsearch.action.admin.indices.create.CreateIndexResponse" ]
import com.dotmarketing.business.DotStateException; import java.io.IOException; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import com.dotmarketing.business.*; import java.io.*; import org.elasticsearch.action.admin.indices.create.*;
[ "com.dotmarketing.business", "java.io", "org.elasticsearch.action" ]
com.dotmarketing.business; java.io; org.elasticsearch.action;
1,574,700
public FeatureResultSet queryFeaturesForChunk(boolean distinct, String[] columns, BoundingBox boundingBox, Projection projection, String orderBy, int limit) { BoundingBox featureBoundingBox = projectBoundingBox(boundingBox, projection); return queryFeaturesForChunk(distinct, columns, featureBoundingBox, orderBy, limit); }
FeatureResultSet function(boolean distinct, String[] columns, BoundingBox boundingBox, Projection projection, String orderBy, int limit) { BoundingBox featureBoundingBox = projectBoundingBox(boundingBox, projection); return queryFeaturesForChunk(distinct, columns, featureBoundingBox, orderBy, limit); }
/** * Query for features within the bounding box in the provided projection, * starting at the offset and returning no more than the limit * * @param distinct * distinct rows * @param columns * columns * @param boundingBox * bounding box * @param projection * projection * @param orderBy * order by * @param limit * chunk limit * @return feature results * @since 6.2.0 */
Query for features within the bounding box in the provided projection, starting at the offset and returning no more than the limit
queryFeaturesForChunk
{ "repo_name": "ngageoint/geopackage-java", "path": "src/main/java/mil/nga/geopackage/extension/rtree/RTreeIndexTableDao.java", "license": "mit", "size": 349361 }
[ "mil.nga.geopackage.BoundingBox", "mil.nga.geopackage.features.user.FeatureResultSet", "mil.nga.proj.Projection" ]
import mil.nga.geopackage.BoundingBox; import mil.nga.geopackage.features.user.FeatureResultSet; import mil.nga.proj.Projection;
import mil.nga.geopackage.*; import mil.nga.geopackage.features.user.*; import mil.nga.proj.*;
[ "mil.nga.geopackage", "mil.nga.proj" ]
mil.nga.geopackage; mil.nga.proj;
1,962,582
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight){ RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight); draw(rect); }
void function(int x, int y, int width, int height, int arcWidth, int arcHeight){ RoundRectangle2D rect = new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight); draw(rect); }
/** * Draws an outlined round-cornered rectangle using this graphics * context's current color. The left and right edges of the rectangle * are at <code>x</code> and <code>x&nbsp;+&nbsp;width</code>, * respectively. The top and bottom edges of the rectangle are at * <code>y</code> and <code>y&nbsp;+&nbsp;height</code>. * @param x the <i>x</i> coordinate of the rectangle to be drawn. * @param y the <i>y</i> coordinate of the rectangle to be drawn. * @param width the width of the rectangle to be drawn. * @param height the height of the rectangle to be drawn. * @param arcWidth the horizontal diameter of the arc * at the four corners. * @param arcHeight the vertical diameter of the arc * at the four corners. * @see java.awt.Graphics#fillRoundRect */
Draws an outlined round-cornered rectangle using this graphics context's current color. The left and right edges of the rectangle are at <code>x</code> and <code>x&nbsp;+&nbsp;width</code>, respectively. The top and bottom edges of the rectangle are at <code>y</code> and <code>y&nbsp;+&nbsp;height</code>
drawRoundRect
{ "repo_name": "apache/batik", "path": "batik-awt-util/src/main/java/org/apache/batik/ext/awt/g2d/AbstractGraphics2D.java", "license": "apache-2.0", "size": 60679 }
[ "java.awt.geom.RoundRectangle2D" ]
import java.awt.geom.RoundRectangle2D;
import java.awt.geom.*;
[ "java.awt" ]
java.awt;
1,116,548
public void generateReactionGraph() { DefaultMutableTreeNode o=getSelectedNode(); if(o!=null){ BiochamModel m = getModelInstanceFromSelectedNode(o); if(m!=null){ m.setWhoPopup(null); m.sendToBiocham("draw_reactions.\n","reactionGraph"); } m=null; } o=null; }
void function() { DefaultMutableTreeNode o=getSelectedNode(); if(o!=null){ BiochamModel m = getModelInstanceFromSelectedNode(o); if(m!=null){ m.setWhoPopup(null); m.sendToBiocham(STR,STR); } m=null; } o=null; }
/** * Generates reaction graph of the current model */
Generates reaction graph of the current model
generateReactionGraph
{ "repo_name": "Thomashuet/Biocham", "path": "gui/BiochamDynamicTreeActionListener.java", "license": "gpl-2.0", "size": 59681 }
[ "javax.swing.tree.DefaultMutableTreeNode" ]
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.*;
[ "javax.swing" ]
javax.swing;
1,032,498
public static <T> Collection<T> tail(Iterable<T> self) { if (!self.iterator().hasNext()) { throw new NoSuchElementException("Cannot access tail() for an empty iterable"); } Collection<T> result = createSimilarCollection(self); addAll(result, tail(self.iterator())); return result; }
static <T> Collection<T> function(Iterable<T> self) { if (!self.iterator().hasNext()) { throw new NoSuchElementException(STR); } Collection<T> result = createSimilarCollection(self); addAll(result, tail(self.iterator())); return result; }
/** * Returns the items from the Iterable excluding the first item. * <pre class="groovyTestCase"> * def list = [3, 4, 2] * assert list.tail() == [4, 2] * assert list == [3, 4, 2] * </pre> * * @param self an Iterable * @return a collection without its first element * @throws NoSuchElementException if the iterable is empty and you try to access the tail() * @since 2.4.0 */
Returns the items from the Iterable excluding the first item. def list = [3, 4, 2] assert list.tail() == [4, 2] assert list == [3, 4, 2] </code>
tail
{ "repo_name": "apache/incubator-groovy", "path": "src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java", "license": "apache-2.0", "size": 703151 }
[ "java.util.Collection", "java.util.NoSuchElementException" ]
import java.util.Collection; import java.util.NoSuchElementException;
import java.util.*;
[ "java.util" ]
java.util;
2,620,676
public static void assertEquals(Class<?> clazz, String resourceName, List<BibEntry> asIsEntries) throws IOException { Assert.assertNotNull(clazz); Assert.assertNotNull(resourceName); Assert.assertNotNull(asIsEntries); try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) { BibEntryAssert.assertEquals(shouldBeIs, asIsEntries); } }
static void function(Class<?> clazz, String resourceName, List<BibEntry> asIsEntries) throws IOException { Assert.assertNotNull(clazz); Assert.assertNotNull(resourceName); Assert.assertNotNull(asIsEntries); try (InputStream shouldBeIs = clazz.getResourceAsStream(resourceName)) { BibEntryAssert.assertEquals(shouldBeIs, asIsEntries); } }
/** * Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to * contain a single entry * * @param clazz the class where to call `getResourceAsStream` * @param resourceName the resource to read * @param asIsEntries a list containing a single entry to compare with */
Reads a single entry from the resource using `getResourceAsStream` from the given class. The resource has to contain a single entry
assertEquals
{ "repo_name": "motokito/jabref", "path": "src/test/java/net/sf/jabref/logic/bibtex/BibEntryAssert.java", "license": "mit", "size": 6153 }
[ "java.io.IOException", "java.io.InputStream", "java.util.List", "net.sf.jabref.model.entry.BibEntry", "org.junit.Assert" ]
import java.io.IOException; import java.io.InputStream; import java.util.List; import net.sf.jabref.model.entry.BibEntry; import org.junit.Assert;
import java.io.*; import java.util.*; import net.sf.jabref.model.entry.*; import org.junit.*;
[ "java.io", "java.util", "net.sf.jabref", "org.junit" ]
java.io; java.util; net.sf.jabref; org.junit;
1,766,779
@SuppressWarnings("deprecation") public void addDocumentFile(SpdxDocument spdxDocument, SpdxFile spdxFile) throws SpdxCompareException { checkInProgress(); inProgress = true; Iterator<Entry<SpdxDocument, SpdxItem>> iter = this.documentItem.entrySet().iterator(); Entry<SpdxDocument, SpdxItem> entry; SpdxFile filesB = null; while (iter.hasNext() && filesB == null) { entry = iter.next(); if (entry.getValue() instanceof SpdxFile) { filesB = (SpdxFile)entry.getValue(); } } if (filesB != null) { // Artifact Of compareNewArtifactOf(spdxDocument, spdxFile.getArtifactOf()); // Checksums compareNewFileChecksums(spdxDocument, spdxFile.getChecksums()); // Type if (!SpdxComparer.arraysEqual(spdxFile.getFileTypes(), filesB.getFileTypes())) { this.typesEquals = false; this.differenceFound = true; } // contributors if (!SpdxComparer.stringArraysEqual(spdxFile.getFileContributors(), filesB.getFileContributors())) { this.contributorsEquals = false; this.differenceFound = true; } // notice text if (!SpdxComparer.stringsEqual(spdxFile.getNoticeText(), filesB.getNoticeText())) { this.noticeTextEquals = false; this.differenceFound = true; } // file dependencies if (!fileNamesEquals(spdxFile.getFileDependencies(), filesB.getFileDependencies())) { this.fileDependenciesEquals = false; this.differenceFound = true; } } super.addDocumentItem(spdxDocument, spdxFile); inProgress = false; }
@SuppressWarnings(STR) void function(SpdxDocument spdxDocument, SpdxFile spdxFile) throws SpdxCompareException { checkInProgress(); inProgress = true; Iterator<Entry<SpdxDocument, SpdxItem>> iter = this.documentItem.entrySet().iterator(); Entry<SpdxDocument, SpdxItem> entry; SpdxFile filesB = null; while (iter.hasNext() && filesB == null) { entry = iter.next(); if (entry.getValue() instanceof SpdxFile) { filesB = (SpdxFile)entry.getValue(); } } if (filesB != null) { compareNewArtifactOf(spdxDocument, spdxFile.getArtifactOf()); compareNewFileChecksums(spdxDocument, spdxFile.getChecksums()); if (!SpdxComparer.arraysEqual(spdxFile.getFileTypes(), filesB.getFileTypes())) { this.typesEquals = false; this.differenceFound = true; } if (!SpdxComparer.stringArraysEqual(spdxFile.getFileContributors(), filesB.getFileContributors())) { this.contributorsEquals = false; this.differenceFound = true; } if (!SpdxComparer.stringsEqual(spdxFile.getNoticeText(), filesB.getNoticeText())) { this.noticeTextEquals = false; this.differenceFound = true; } if (!fileNamesEquals(spdxFile.getFileDependencies(), filesB.getFileDependencies())) { this.fileDependenciesEquals = false; this.differenceFound = true; } } super.addDocumentItem(spdxDocument, spdxFile); inProgress = false; }
/** * Add a file to the comparer and compare to the existing files * @param spdxDocument document containing the file * @param spdxFile * @throws SpdxCompareException */
Add a file to the comparer and compare to the existing files
addDocumentFile
{ "repo_name": "romeara/spdx-tools", "path": "src/org/spdx/compare/SpdxFileComparer.java", "license": "apache-2.0", "size": 16190 }
[ "java.util.Iterator", "java.util.Map", "org.spdx.rdfparser.model.SpdxDocument", "org.spdx.rdfparser.model.SpdxFile", "org.spdx.rdfparser.model.SpdxItem" ]
import java.util.Iterator; import java.util.Map; import org.spdx.rdfparser.model.SpdxDocument; import org.spdx.rdfparser.model.SpdxFile; import org.spdx.rdfparser.model.SpdxItem;
import java.util.*; import org.spdx.rdfparser.model.*;
[ "java.util", "org.spdx.rdfparser" ]
java.util; org.spdx.rdfparser;
1,811,371
@Override @Deprecated public Map<String, String> getMdc() { return event.getMDCPropertyMap(); }
Map<String, String> function() { return event.getMDCPropertyMap(); }
/** * A synonym for {@link #getMDCPropertyMap}. * @deprecated Use {@link #getMDCPropertyMap()}. */
A synonym for <code>#getMDCPropertyMap</code>
getMdc
{ "repo_name": "jmostella/armeria", "path": "logback/src/main/java/com/linecorp/armeria/common/logback/RequestContextExportingAppender.java", "license": "apache-2.0", "size": 13630 }
[ "java.util.Map" ]
import java.util.Map;
import java.util.*;
[ "java.util" ]
java.util;
1,577,383
protected void doFlush(boolean realFlush) throws IOException { if (suspended) return; doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } doFlush = false; if (realFlush) { coyoteResponse.action(ActionCode.ACTION_CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } } // ------------------------------------------------- Bytes Handling Methods
void function(boolean realFlush) throws IOException { if (suspended) return; doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (bb.getLength() > 0) { bb.flushBuffer(); } doFlush = false; if (realFlush) { coyoteResponse.action(ActionCode.ACTION_CLIENT_FLUSH, coyoteResponse); if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } }
/** * Flush bytes or chars contained in the buffer. * * @throws IOException An underlying IOException occurred */
Flush bytes or chars contained in the buffer
doFlush
{ "repo_name": "plumer/codana", "path": "tomcat_files/6.0.0/OutputBuffer.java", "license": "mit", "size": 12609 }
[ "java.io.IOException", "org.apache.coyote.ActionCode" ]
import java.io.IOException; import org.apache.coyote.ActionCode;
import java.io.*; import org.apache.coyote.*;
[ "java.io", "org.apache.coyote" ]
java.io; org.apache.coyote;
2,117,398
//----------------------------------------------------------------------- public ImmutableList<CurveUnitParameterSensitivity> getSensitivities() { return sensitivities; }
ImmutableList<CurveUnitParameterSensitivity> function() { return sensitivities; }
/** * Gets the parameter sensitivities. * <p> * Each entry includes details of the curve it relates to. * @return the value of the property, not null */
Gets the parameter sensitivities. Each entry includes details of the curve it relates to
getSensitivities
{ "repo_name": "nssales/Strata", "path": "modules/market/src/main/java/com/opengamma/strata/market/sensitivity/CurveUnitParameterSensitivities.java", "license": "apache-2.0", "size": 18938 }
[ "com.google.common.collect.ImmutableList" ]
import com.google.common.collect.ImmutableList;
import com.google.common.collect.*;
[ "com.google.common" ]
com.google.common;
769,009
public Observable<ServiceResponse<Page<StreamingEndpointInner>>> listSinglePageAsync(final String resourceGroupName, final String accountName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (accountName == null) { throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); }
Observable<ServiceResponse<Page<StreamingEndpointInner>>> function(final String resourceGroupName, final String accountName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (accountName == null) { throw new IllegalArgumentException(STR); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException(STR); }
/** * List StreamingEndpoints. * Lists the StreamingEndpoints in the account. * ServiceResponse<PageImpl<StreamingEndpointInner>> * @param resourceGroupName The name of the resource group within the Azure subscription. ServiceResponse<PageImpl<StreamingEndpointInner>> * @param accountName The Media Services account name. * @throws IllegalArgumentException thrown if parameters fail the validation * @return the PagedList&lt;StreamingEndpointInner&gt; object wrapped in {@link ServiceResponse} if successful. */
List StreamingEndpoints. Lists the StreamingEndpoints in the account
listSinglePageAsync
{ "repo_name": "selvasingh/azure-sdk-for-java", "path": "sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/StreamingEndpointsInner.java", "license": "mit", "size": 117827 }
[ "com.microsoft.azure.Page", "com.microsoft.rest.ServiceResponse" ]
import com.microsoft.azure.Page; import com.microsoft.rest.ServiceResponse;
import com.microsoft.azure.*; import com.microsoft.rest.*;
[ "com.microsoft.azure", "com.microsoft.rest" ]
com.microsoft.azure; com.microsoft.rest;
2,706,682
public void seekToLast() throws DBException { try { iter.seekToLast(); } catch (DBException e) { throw e; } catch (RuntimeException e) { throw new DBException(e.getMessage(), e); } }
void function() throws DBException { try { iter.seekToLast(); } catch (DBException e) { throw e; } catch (RuntimeException e) { throw new DBException(e.getMessage(), e); } }
/** * Repositions the iterator so it is at the end of of the Database. */
Repositions the iterator so it is at the end of of the Database
seekToLast
{ "repo_name": "Julyme/utils", "path": "myutils/src/main/java/com/myutils/levelDB/LeveldbIterator.java", "license": "apache-2.0", "size": 5384 }
[ "org.iq80.leveldb.DBException" ]
import org.iq80.leveldb.DBException;
import org.iq80.leveldb.*;
[ "org.iq80.leveldb" ]
org.iq80.leveldb;
903,857
Set<PortletCategory> getAllChildCategories(PortletCategory parent);
Set<PortletCategory> getAllChildCategories(PortletCategory parent);
/** * Gets all child portlet categories for a parent category. * * @return portletCategories the children categories */
Gets all child portlet categories for a parent category
getAllChildCategories
{ "repo_name": "jl1955/uPortal5", "path": "uPortal-content/uPortal-content-portlet/src/main/java/org/apereo/portal/portlet/registry/IPortletCategoryRegistry.java", "license": "apache-2.0", "size": 3040 }
[ "java.util.Set", "org.apereo.portal.portlet.om.PortletCategory" ]
import java.util.Set; import org.apereo.portal.portlet.om.PortletCategory;
import java.util.*; import org.apereo.portal.portlet.om.*;
[ "java.util", "org.apereo.portal" ]
java.util; org.apereo.portal;
1,535,184
private String handleException(final GraphStep step, Exception e, String cause) throws GraphException { // First, immediately rollback the current savepoint. step.rollback(this); String msg = String.format("Could not process softly %s: %s due to %s", step.pathMsg, step.id, cause); // If this entry is "SOFT" then there's nothing // special we need to do. if (step.entry.isSoft()) { log.debug(msg); return "Skipping processing of " + step.table + ":" + step.id + "\n"; } // Otherwise calculate if there is any "SOFT" setting about this // location in the graph, and clean up all of the related entries. // As we check down the stack, we can safely call rollback since // the only other option is to rollback the entire transaction. for (int i = step.stack.size() - 1; i >= 0; i--) { GraphStep parent = step.stack.get(i); parent.rollback(this); if (parent.entry.isSoft()) { disableRelatedEntries(parent); log.debug(String.format("%s. Handled by %s: %s", msg, parent.pathMsg, parent.id)); return cause; } } log.info(String.format("Failed to process %s: %s due to %s", step.pathMsg, step.id, cause)); if (e instanceof ConstraintViolationException) { throw (ConstraintViolationException) e; } else if (e instanceof GraphException) { throw (GraphException) e; } else { RuntimeException rt = new RuntimeException(); rt.initCause(e); throw rt; } }
String function(final GraphStep step, Exception e, String cause) throws GraphException { step.rollback(this); String msg = String.format(STR, step.pathMsg, step.id, cause); if (step.entry.isSoft()) { log.debug(msg); return STR + step.table + ":" + step.id + "\n"; } for (int i = step.stack.size() - 1; i >= 0; i--) { GraphStep parent = step.stack.get(i); parent.rollback(this); if (parent.entry.isSoft()) { disableRelatedEntries(parent); log.debug(String.format(STR, msg, parent.pathMsg, parent.id)); return cause; } } log.info(String.format(STR, step.pathMsg, step.id, cause)); if (e instanceof ConstraintViolationException) { throw (ConstraintViolationException) e; } else if (e instanceof GraphException) { throw (GraphException) e; } else { RuntimeException rt = new RuntimeException(); rt.initCause(e); throw rt; } }
/** * Method called when an exception is be thrown, * i.e. during {@link #execute(int)}. * * @param session * @param opts * @param type * @param rv * @param cve */
Method called when an exception is be thrown, i.e. during <code>#execute(int)</code>
handleException
{ "repo_name": "hflynn/openmicroscopy", "path": "components/server/src/ome/services/graphs/GraphState.java", "license": "gpl-2.0", "size": 18863 }
[ "org.hibernate.exception.ConstraintViolationException" ]
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.exception.*;
[ "org.hibernate.exception" ]
org.hibernate.exception;
1,204,446
private void testClientReuse(int maxConnections, boolean concurrent) throws IOException, InterruptedException { Map<String, String> configMap = new HashMap<>(); configMap.put("spark.shuffle.io.numConnectionsPerPeer", Integer.toString(maxConnections)); TransportConf conf = new TransportConf("shuffle", new MapConfigProvider(configMap)); RpcHandler rpcHandler = new NoOpRpcHandler(); try (TransportContext context = new TransportContext(conf, rpcHandler)) { TransportClientFactory factory = context.createClientFactory(); Set<TransportClient> clients = Collections.synchronizedSet( new HashSet<>()); AtomicInteger failed = new AtomicInteger(); Thread[] attempts = new Thread[maxConnections * 10]; // Launch a bunch of threads to create new clients. for (int i = 0; i < attempts.length; i++) { attempts[i] = new Thread(() -> { try { TransportClient client = factory.createClient(TestUtils.getLocalHost(), server1.getPort()); assertTrue(client.isActive()); clients.add(client); } catch (IOException e) { failed.incrementAndGet(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); if (concurrent) { attempts[i].start(); } else { attempts[i].run(); } } // Wait until all the threads complete. for (Thread attempt : attempts) { attempt.join(); } Assert.assertEquals(0, failed.get()); Assert.assertTrue(clients.size() <= maxConnections); for (TransportClient client : clients) { client.close(); } factory.close(); } }
void function(int maxConnections, boolean concurrent) throws IOException, InterruptedException { Map<String, String> configMap = new HashMap<>(); configMap.put(STR, Integer.toString(maxConnections)); TransportConf conf = new TransportConf(STR, new MapConfigProvider(configMap)); RpcHandler rpcHandler = new NoOpRpcHandler(); try (TransportContext context = new TransportContext(conf, rpcHandler)) { TransportClientFactory factory = context.createClientFactory(); Set<TransportClient> clients = Collections.synchronizedSet( new HashSet<>()); AtomicInteger failed = new AtomicInteger(); Thread[] attempts = new Thread[maxConnections * 10]; for (int i = 0; i < attempts.length; i++) { attempts[i] = new Thread(() -> { try { TransportClient client = factory.createClient(TestUtils.getLocalHost(), server1.getPort()); assertTrue(client.isActive()); clients.add(client); } catch (IOException e) { failed.incrementAndGet(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); if (concurrent) { attempts[i].start(); } else { attempts[i].run(); } } for (Thread attempt : attempts) { attempt.join(); } Assert.assertEquals(0, failed.get()); Assert.assertTrue(clients.size() <= maxConnections); for (TransportClient client : clients) { client.close(); } factory.close(); } }
/** * Request a bunch of clients to a single server to test * we create up to maxConnections of clients. * * If concurrent is true, create multiple threads to create clients in parallel. */
Request a bunch of clients to a single server to test we create up to maxConnections of clients. If concurrent is true, create multiple threads to create clients in parallel
testClientReuse
{ "repo_name": "maropu/spark", "path": "common/network-common/src/test/java/org/apache/spark/network/client/TransportClientFactorySuite.java", "license": "apache-2.0", "size": 8525 }
[ "java.io.IOException", "java.util.Collections", "java.util.HashMap", "java.util.HashSet", "java.util.Map", "java.util.Set", "java.util.concurrent.atomic.AtomicInteger", "org.apache.spark.network.TestUtils", "org.apache.spark.network.TransportContext", "org.apache.spark.network.server.NoOpRpcHandler", "org.apache.spark.network.server.RpcHandler", "org.apache.spark.network.util.MapConfigProvider", "org.apache.spark.network.util.TransportConf", "org.junit.Assert" ]
import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.apache.spark.network.TestUtils; import org.apache.spark.network.TransportContext; import org.apache.spark.network.server.NoOpRpcHandler; import org.apache.spark.network.server.RpcHandler; import org.apache.spark.network.util.MapConfigProvider; import org.apache.spark.network.util.TransportConf; import org.junit.Assert;
import java.io.*; import java.util.*; import java.util.concurrent.atomic.*; import org.apache.spark.network.*; import org.apache.spark.network.server.*; import org.apache.spark.network.util.*; import org.junit.*;
[ "java.io", "java.util", "org.apache.spark", "org.junit" ]
java.io; java.util; org.apache.spark; org.junit;
1,932,714
@Override public String getText(Object object) { String label = ((Contribution) object).getName(); return label == null || label.length() == 0 ? getString("_UI_Contribution_type") : getString("_UI_Contribution_type") + " " + label; }
String function(Object object) { String label = ((Contribution) object).getName(); return label == null label.length() == 0 ? getString(STR) : getString(STR) + " " + label; }
/** * This returns the label text for the adapted class. <!-- begin-user-doc --> * <!-- end-user-doc --> * * @generated */
This returns the label text for the adapted class.
getText
{ "repo_name": "enterpriseDomain/ClassMaker", "path": "bundles/org.enterprisedomain.classmaker.edit/src/org/enterprisedomain/classmaker/provider/ContributionItemProvider.java", "license": "apache-2.0", "size": 5255 }
[ "org.enterprisedomain.classmaker.Contribution" ]
import org.enterprisedomain.classmaker.Contribution;
import org.enterprisedomain.classmaker.*;
[ "org.enterprisedomain.classmaker" ]
org.enterprisedomain.classmaker;
287,385
public static TransitiveInfoCollection mallocForTarget(RuleContext ruleContext) { if (ruleContext.getFragment(CppConfiguration.class).customMalloc() != null) { return ruleContext.getPrerequisite(":default_malloc", Mode.TARGET); } else { return ruleContext.getPrerequisite("malloc", Mode.TARGET); } }
static TransitiveInfoCollection function(RuleContext ruleContext) { if (ruleContext.getFragment(CppConfiguration.class).customMalloc() != null) { return ruleContext.getPrerequisite(STR, Mode.TARGET); } else { return ruleContext.getPrerequisite(STR, Mode.TARGET); } }
/** * Returns the malloc implementation for the given target. */
Returns the malloc implementation for the given target
mallocForTarget
{ "repo_name": "juhalindfors/bazel-patches", "path": "src/main/java/com/google/devtools/build/lib/rules/cpp/CppHelper.java", "license": "apache-2.0", "size": 29659 }
[ "com.google.devtools.build.lib.analysis.RuleConfiguredTarget", "com.google.devtools.build.lib.analysis.RuleContext", "com.google.devtools.build.lib.analysis.TransitiveInfoCollection" ]
import com.google.devtools.build.lib.analysis.RuleConfiguredTarget; import com.google.devtools.build.lib.analysis.RuleContext; import com.google.devtools.build.lib.analysis.TransitiveInfoCollection;
import com.google.devtools.build.lib.analysis.*;
[ "com.google.devtools" ]
com.google.devtools;
722,937
public void setAttributes(Map<AttributeKey, Object> attributes) { this.attributes = attributes; }
void function(Map<AttributeKey, Object> attributes) { this.attributes = attributes; }
/** * Sets the attributes. * * @param attributes The CreationTool applies these attributes to the * prototype after having applied the default attributes from the DrawingEditor. */
Sets the attributes
setAttributes
{ "repo_name": "dominikl/openmicroscopy", "path": "components/insight/SRC/org/openmicroscopy/shoola/util/ui/drawingtools/creationtools/DrawingBezierTool.java", "license": "gpl-2.0", "size": 3360 }
[ "java.util.Map", "org.jhotdraw.draw.AttributeKey" ]
import java.util.Map; import org.jhotdraw.draw.AttributeKey;
import java.util.*; import org.jhotdraw.draw.*;
[ "java.util", "org.jhotdraw.draw" ]
java.util; org.jhotdraw.draw;
1,802,435
private void instantiateServer() { if(webServer == null) { try { DeploymentInfo servletBuilder = deployment() .setClassLoader(OlatJerseyTestCase.class.getClassLoader()) .setContextPath("/" + CONTEXT_PATH) .setDeploymentName("rest.war") .addServlets( servlet("REST Servlet", com.sun.jersey.spi.container.servlet.ServletContainer.class) .addInitParam("javax.ws.rs.Application", OlatRestApplication.class.getName()) .addMapping("/*")) .addFilters(filter("REST security filter", RestApiLoginFilter.class)) .addFilterUrlMapping("REST security filter", "/*", DispatcherType.REQUEST); DeploymentManager manager = defaultContainer().addDeployment(servletBuilder); manager.deploy(); webServer = Undertow.builder() .addListener(PORT, HOST) .setHandler(manager.start()) .build(); webServer.start(); webServerStarted = true; } catch (ServletException e) { log.error("", e); } } }
void function() { if(webServer == null) { try { DeploymentInfo servletBuilder = deployment() .setClassLoader(OlatJerseyTestCase.class.getClassLoader()) .setContextPath("/" + CONTEXT_PATH) .setDeploymentName(STR) .addServlets( servlet(STR, com.sun.jersey.spi.container.servlet.ServletContainer.class) .addInitParam(STR, OlatRestApplication.class.getName()) .addMapping("/*")) .addFilters(filter(STR, RestApiLoginFilter.class)) .addFilterUrlMapping(STR, "/*", DispatcherType.REQUEST); DeploymentManager manager = defaultContainer().addDeployment(servletBuilder); manager.deploy(); webServer = Undertow.builder() .addListener(PORT, HOST) .setHandler(manager.start()) .build(); webServer.start(); webServerStarted = true; } catch (ServletException e) { log.error("", e); } } }
/** * Instantiates the server */
Instantiates the server
instantiateServer
{ "repo_name": "stevenhva/InfoLearn_OpenOLAT", "path": "src/test/java/org/olat/test/OlatJerseyTestCase.java", "license": "apache-2.0", "size": 5452 }
[ "io.undertow.Undertow", "io.undertow.servlet.Servlets", "io.undertow.servlet.api.DeploymentInfo", "io.undertow.servlet.api.DeploymentManager", "javax.servlet.DispatcherType", "javax.servlet.ServletException", "org.olat.restapi.security.RestApiLoginFilter", "org.olat.restapi.support.OlatRestApplication" ]
import io.undertow.Undertow; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import javax.servlet.DispatcherType; import javax.servlet.ServletException; import org.olat.restapi.security.RestApiLoginFilter; import org.olat.restapi.support.OlatRestApplication;
import io.undertow.*; import io.undertow.servlet.*; import io.undertow.servlet.api.*; import javax.servlet.*; import org.olat.restapi.security.*; import org.olat.restapi.support.*;
[ "io.undertow", "io.undertow.servlet", "javax.servlet", "org.olat.restapi" ]
io.undertow; io.undertow.servlet; javax.servlet; org.olat.restapi;
1,404,925
void setSubtitle(@NonNull CharSequence title);
void setSubtitle(@NonNull CharSequence title);
/** * Set the subtitle. */
Set the subtitle
setSubtitle
{ "repo_name": "aosp-mirror/platform_frameworks_support", "path": "slices/builders/src/main/java/androidx/slice/builders/impl/ListBuilder.java", "license": "apache-2.0", "size": 11740 }
[ "androidx.annotation.NonNull" ]
import androidx.annotation.NonNull;
import androidx.annotation.*;
[ "androidx.annotation" ]
androidx.annotation;
1,027,628
EAttribute getExternal_Allowance_Starting_year();
EAttribute getExternal_Allowance_Starting_year();
/** * Returns the meta object for the attribute '{@link TaxationWithRoot.External_Allowance#getStarting_year <em>Starting year</em>}'. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the meta object for the attribute '<em>Starting year</em>'. * @see TaxationWithRoot.External_Allowance#getStarting_year() * @see #getExternal_Allowance() * @generated */
Returns the meta object for the attribute '<code>TaxationWithRoot.External_Allowance#getStarting_year Starting year</code>'.
getExternal_Allowance_Starting_year
{ "repo_name": "viatra/VIATRA-Generator", "path": "Tests/MODELS2020-CaseStudies/case.study.pledge.model/src/TaxationWithRoot/TaxationPackage.java", "license": "epl-1.0", "size": 295635 }
[ "org.eclipse.emf.ecore.EAttribute" ]
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.*;
[ "org.eclipse.emf" ]
org.eclipse.emf;
2,233,059
@Test public void testNackQueueMessageAcknowledgerThrowError() throws JMSException { MessageListener msgListener = mock(MessageListener.class); SQSMessage sqsMessage = mock(SQSMessage.class); when(sqsMessage.getReceiptHandle()) .thenReturn("r2"); when(sqsMessage.getSQSMessageId()) .thenReturn("messageId2"); when(sqsMessage.getQueueUrl()) .thenReturn(QUEUE_URL_2); SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); when(msgManager.getMessage()) .thenReturn(sqsMessage); when(msgManager.getPrefetchManager()) .thenReturn(mock(PrefetchManager.class)); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(msgListener, msgManager); when(callbackQueue.isEmpty()) .thenReturn(false) .thenReturn(true); when(callbackQueue.pollFirst()) .thenReturn(entry1); doThrow(new Error("error")) .when(negativeAcknowledger).bulkAction(anyList(), anyInt()); try { sqsSessionRunnable.nackQueuedMessages(); fail(); } catch(Error e) { // expected error } }
void function() throws JMSException { MessageListener msgListener = mock(MessageListener.class); SQSMessage sqsMessage = mock(SQSMessage.class); when(sqsMessage.getReceiptHandle()) .thenReturn("r2"); when(sqsMessage.getSQSMessageId()) .thenReturn(STR); when(sqsMessage.getQueueUrl()) .thenReturn(QUEUE_URL_2); SQSMessageConsumerPrefetch.MessageManager msgManager = mock(SQSMessageConsumerPrefetch.MessageManager.class); when(msgManager.getMessage()) .thenReturn(sqsMessage); when(msgManager.getPrefetchManager()) .thenReturn(mock(PrefetchManager.class)); SQSSession.CallbackEntry entry1 = new SQSSession.CallbackEntry(msgListener, msgManager); when(callbackQueue.isEmpty()) .thenReturn(false) .thenReturn(true); when(callbackQueue.pollFirst()) .thenReturn(entry1); doThrow(new Error("error")) .when(negativeAcknowledger).bulkAction(anyList(), anyInt()); try { sqsSessionRunnable.nackQueuedMessages(); fail(); } catch(Error e) { } }
/** * Test nack queue messages does propagate Errors */
Test nack queue messages does propagate Errors
testNackQueueMessageAcknowledgerThrowError
{ "repo_name": "lkb2k/amazon-sqs-java-messaging-lib", "path": "src/test/java/com/amazon/sqs/javamessaging/SQSSessionCallbackSchedulerTest.java", "license": "apache-2.0", "size": 21786 }
[ "com.amazon.sqs.javamessaging.PrefetchManager", "com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch", "com.amazon.sqs.javamessaging.SQSSession", "com.amazon.sqs.javamessaging.message.SQSMessage", "javax.jms.JMSException", "javax.jms.MessageListener", "junit.framework.Assert", "org.mockito.Matchers", "org.mockito.Mockito" ]
import com.amazon.sqs.javamessaging.PrefetchManager; import com.amazon.sqs.javamessaging.SQSMessageConsumerPrefetch; import com.amazon.sqs.javamessaging.SQSSession; import com.amazon.sqs.javamessaging.message.SQSMessage; import javax.jms.JMSException; import javax.jms.MessageListener; import junit.framework.Assert; import org.mockito.Matchers; import org.mockito.Mockito;
import com.amazon.sqs.javamessaging.*; import com.amazon.sqs.javamessaging.message.*; import javax.jms.*; import junit.framework.*; import org.mockito.*;
[ "com.amazon.sqs", "javax.jms", "junit.framework", "org.mockito" ]
com.amazon.sqs; javax.jms; junit.framework; org.mockito;
613,687
public StreamError getStreamError() { return streamError; } }
StreamError function() { return streamError; } }
/** * Returns the StreamError associated with this exception. The underlying TCP connection is * closed by the server after sending the stream error to the client. * * @return the StreamError associated with this exception. */
Returns the StreamError associated with this exception. The underlying TCP connection is closed by the server after sending the stream error to the client
getStreamError
{ "repo_name": "Soo000/SooChat", "path": "src/org/jivesoftware/smack/XMPPException.java", "license": "apache-2.0", "size": 6004 }
[ "org.jivesoftware.smack.packet.StreamError" ]
import org.jivesoftware.smack.packet.StreamError;
import org.jivesoftware.smack.packet.*;
[ "org.jivesoftware.smack" ]
org.jivesoftware.smack;
1,069,177
@ServiceMethod(returns = ReturnType.SINGLE) public SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> beginCreateOrUpdate( String resourceGroupName, String serverName, String privateEndpointConnectionName, PrivateEndpointConnectionInner parameters, Context context) { return beginCreateOrUpdateAsync( resourceGroupName, serverName, privateEndpointConnectionName, parameters, context) .getSyncPoller(); }
@ServiceMethod(returns = ReturnType.SINGLE) SyncPoller<PollResult<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner> function( String resourceGroupName, String serverName, String privateEndpointConnectionName, PrivateEndpointConnectionInner parameters, Context context) { return beginCreateOrUpdateAsync( resourceGroupName, serverName, privateEndpointConnectionName, parameters, context) .getSyncPoller(); }
/** * Approve or reject a private endpoint connection with a given name. * * @param resourceGroupName The name of the resource group that contains the resource. You can obtain this value * from the Azure Resource Manager API or the portal. * @param serverName The name of the server. * @param privateEndpointConnectionName The privateEndpointConnectionName parameter. * @param parameters A private endpoint connection. * @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 a private endpoint connection. */
Approve or reject a private endpoint connection with a given name
beginCreateOrUpdate
{ "repo_name": "Azure/azure-sdk-for-java", "path": "sdk/resourcemanager/azure-resourcemanager-sql/src/main/java/com/azure/resourcemanager/sql/implementation/PrivateEndpointConnectionsClientImpl.java", "license": "mit", "size": 58978 }
[ "com.azure.core.annotation.ReturnType", "com.azure.core.annotation.ServiceMethod", "com.azure.core.management.polling.PollResult", "com.azure.core.util.Context", "com.azure.core.util.polling.SyncPoller", "com.azure.resourcemanager.sql.fluent.models.PrivateEndpointConnectionInner" ]
import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.sql.fluent.models.PrivateEndpointConnectionInner;
import com.azure.core.annotation.*; import com.azure.core.management.polling.*; import com.azure.core.util.*; import com.azure.core.util.polling.*; import com.azure.resourcemanager.sql.fluent.models.*;
[ "com.azure.core", "com.azure.resourcemanager" ]
com.azure.core; com.azure.resourcemanager;
2,073,276