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
|
---|---|---|---|---|---|---|---|---|---|---|---|
@Override
public Adapter adapt(Notifier notifier, Object type)
{
return super.adapt(notifier, this);
} | Adapter function(Notifier notifier, Object type) { return super.adapt(notifier, this); } | /**
* This implementation substitutes the factory itself as the key for the adapter.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This implementation substitutes the factory itself as the key for the adapter. | adapt | {
"repo_name": "peterkir/org.eclipse.oomph",
"path": "plugins/org.eclipse.oomph.setup.edit/src/org/eclipse/oomph/setup/provider/SetupItemProviderAdapterFactory.java",
"license": "epl-1.0",
"size": 39182
} | [
"org.eclipse.emf.common.notify.Adapter",
"org.eclipse.emf.common.notify.Notifier"
]
| import org.eclipse.emf.common.notify.Adapter; import org.eclipse.emf.common.notify.Notifier; | import org.eclipse.emf.common.notify.*; | [
"org.eclipse.emf"
]
| org.eclipse.emf; | 266,092 |
public void setRequest(ServletRequest request) {
super.setRequest(request);
// Initialize the attributes for this request
synchronized (attributes) {
attributes.clear();
Enumeration names = request.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
Object value = request.getAttribute(name);
attributes.put(name, value);
}
}
}
// ------------------------------------------------------ Protected Methods | void function(ServletRequest request) { super.setRequest(request); synchronized (attributes) { attributes.clear(); Enumeration names = request.getAttributeNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); Object value = request.getAttribute(name); attributes.put(name, value); } } } | /**
* Set the request that we are wrapping.
*
* @param request The new wrapped request
*/ | Set the request that we are wrapping | setRequest | {
"repo_name": "whitingjr/JbossWeb_7_2_0",
"path": "src/main/java/org/apache/catalina/core/ApplicationRequest.java",
"license": "apache-2.0",
"size": 6056
} | [
"java.util.Enumeration",
"javax.servlet.ServletRequest"
]
| import java.util.Enumeration; import javax.servlet.ServletRequest; | import java.util.*; import javax.servlet.*; | [
"java.util",
"javax.servlet"
]
| java.util; javax.servlet; | 2,472,055 |
@Override
public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) {
int pc = codeStream.position;
boolean annotatedCast = (this.type.bits & ASTNode.HasTypeAnnotations) != 0;
boolean needRuntimeCheckcast = (this.bits & ASTNode.GenerateCheckcast) != 0;
if (this.constant != Constant.NotAConstant) {
if (valueRequired || needRuntimeCheckcast || annotatedCast) { // Added for: 1F1W9IG: IVJCOM:WINNT - Compiler omits casting check
codeStream.generateConstant(this.constant, this.implicitConversion);
if (needRuntimeCheckcast || annotatedCast) {
codeStream.checkcast(this.type, this.resolvedType, pc);
}
if (!valueRequired) {
// the resolveType cannot be double or long
codeStream.pop();
}
}
codeStream.recordPositionsFrom(pc, this.sourceStart);
return;
}
this.expression.generateCode(currentScope, codeStream, annotatedCast || valueRequired || needRuntimeCheckcast);
if (annotatedCast || (needRuntimeCheckcast && TypeBinding.notEquals(this.expression.postConversionType(currentScope), this.resolvedType.erasure()))) { // no need to issue a checkcast if already done as genericCast
codeStream.checkcast(this.type, this.resolvedType, pc);
}
if (valueRequired) {
codeStream.generateImplicitConversion(this.implicitConversion);
} else if (annotatedCast || needRuntimeCheckcast) {
switch (this.resolvedType.id) {
case T_long :
case T_double :
codeStream.pop2();
break;
default :
codeStream.pop();
break;
}
}
codeStream.recordPositionsFrom(pc, this.sourceStart);
} | void function(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; boolean annotatedCast = (this.type.bits & ASTNode.HasTypeAnnotations) != 0; boolean needRuntimeCheckcast = (this.bits & ASTNode.GenerateCheckcast) != 0; if (this.constant != Constant.NotAConstant) { if (valueRequired needRuntimeCheckcast annotatedCast) { codeStream.generateConstant(this.constant, this.implicitConversion); if (needRuntimeCheckcast annotatedCast) { codeStream.checkcast(this.type, this.resolvedType, pc); } if (!valueRequired) { codeStream.pop(); } } codeStream.recordPositionsFrom(pc, this.sourceStart); return; } this.expression.generateCode(currentScope, codeStream, annotatedCast valueRequired needRuntimeCheckcast); if (annotatedCast (needRuntimeCheckcast && TypeBinding.notEquals(this.expression.postConversionType(currentScope), this.resolvedType.erasure()))) { codeStream.checkcast(this.type, this.resolvedType, pc); } if (valueRequired) { codeStream.generateImplicitConversion(this.implicitConversion); } else if (annotatedCast needRuntimeCheckcast) { switch (this.resolvedType.id) { case T_long : case T_double : codeStream.pop2(); break; default : codeStream.pop(); break; } } codeStream.recordPositionsFrom(pc, this.sourceStart); } | /**
* Cast expression code generation
*
* @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope
* @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream
* @param valueRequired boolean
*/ | Cast expression code generation | generateCode | {
"repo_name": "Niky4000/UsefulUtils",
"path": "projects/others/eclipse-platform-parent/eclipse.jdt.core-master/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/CastExpression.java",
"license": "gpl-3.0",
"size": 31707
} | [
"org.eclipse.jdt.internal.compiler.codegen.CodeStream",
"org.eclipse.jdt.internal.compiler.impl.Constant",
"org.eclipse.jdt.internal.compiler.lookup.BlockScope",
"org.eclipse.jdt.internal.compiler.lookup.TypeBinding"
]
| import org.eclipse.jdt.internal.compiler.codegen.CodeStream; import org.eclipse.jdt.internal.compiler.impl.Constant; import org.eclipse.jdt.internal.compiler.lookup.BlockScope; import org.eclipse.jdt.internal.compiler.lookup.TypeBinding; | import org.eclipse.jdt.internal.compiler.codegen.*; import org.eclipse.jdt.internal.compiler.impl.*; import org.eclipse.jdt.internal.compiler.lookup.*; | [
"org.eclipse.jdt"
]
| org.eclipse.jdt; | 2,797,818 |
public static boolean updateUser(Connection conn,
int userid,
String username,
String firstname,
String lastname,
String email,
String password)
throws SQLException
{
User user=findUser(conn, userid);
if (user!=null) {
if (username.length()>0) {
user.setUsername(username);
}
if (firstname.length()>0) {
user.setFirstname(firstname);
}
if (lastname.length()>0) {
user.setLastname(lastname);
}
if (email.length()>0) {
user.setEmail(email);
}
if (password.length()>0) {
user.setPasswordHash(PasswordUtil.hashPassword(password));
}
// update all the fields other than id and username
updateUserById(conn, user);
return true;
}
// couldn't find
throw new SQLException("Unable to find user record with id "+userid);
} | static boolean function(Connection conn, int userid, String username, String firstname, String lastname, String email, String password) throws SQLException { User user=findUser(conn, userid); if (user!=null) { if (username.length()>0) { user.setUsername(username); } if (firstname.length()>0) { user.setFirstname(firstname); } if (lastname.length()>0) { user.setLastname(lastname); } if (email.length()>0) { user.setEmail(email); } if (password.length()>0) { user.setPasswordHash(PasswordUtil.hashPassword(password)); } updateUserById(conn, user); return true; } throw new SQLException(STR+userid); } | /**
* Update the text fields of the given record. Any
* parameters left blank will remain unchanged. For example,
* if the password parameter is an empty string, this method
* will not change the password currently stored in the database.
*
* @param conn
* @param userid
* @param username
* @param firstname
* @param lastname
* @param email
* @param password
* @return The userid of the record that was changed.
* @throws SQLException
*/ | Update the text fields of the given record. Any parameters left blank will remain unchanged. For example, if the password parameter is an empty string, this method will not change the password currently stored in the database | updateUser | {
"repo_name": "jspacco/CloudCoder2",
"path": "CloudCoderModelClassesPersistence/src/org/cloudcoder/app/server/persist/util/ConfigurationUtil.java",
"license": "agpl-3.0",
"size": 19404
} | [
"java.sql.Connection",
"java.sql.SQLException",
"org.cloudcoder.app.server.persist.PasswordUtil",
"org.cloudcoder.app.shared.model.User"
]
| import java.sql.Connection; import java.sql.SQLException; import org.cloudcoder.app.server.persist.PasswordUtil; import org.cloudcoder.app.shared.model.User; | import java.sql.*; import org.cloudcoder.app.server.persist.*; import org.cloudcoder.app.shared.model.*; | [
"java.sql",
"org.cloudcoder.app"
]
| java.sql; org.cloudcoder.app; | 1,892,265 |
public void setExcludeProperties(String commaDelim) {
Set<String> excludePatterns = JSONUtil.asSet(commaDelim);
if (excludePatterns != null) {
this.excludeProperties = new ArrayList<Pattern>(excludePatterns.size());
for (String pattern : excludePatterns) {
this.excludeProperties.add(Pattern.compile(pattern));
}
}
} | void function(String commaDelim) { Set<String> excludePatterns = JSONUtil.asSet(commaDelim); if (excludePatterns != null) { this.excludeProperties = new ArrayList<Pattern>(excludePatterns.size()); for (String pattern : excludePatterns) { this.excludeProperties.add(Pattern.compile(pattern)); } } } | /**
* Sets a comma-delimited list of regular expressions to match properties
* that should be excluded from the JSON output.
*
* @param commaDelim A comma-delimited list of regular expressions
*/ | Sets a comma-delimited list of regular expressions to match properties that should be excluded from the JSON output | setExcludeProperties | {
"repo_name": "makersoft/makereap",
"path": "modules/mvc/src/main/java/org/makersoft/mvc/json/JSONResult.java",
"license": "apache-2.0",
"size": 13699
} | [
"java.util.ArrayList",
"java.util.Set",
"java.util.regex.Pattern"
]
| import java.util.ArrayList; import java.util.Set; import java.util.regex.Pattern; | import java.util.*; import java.util.regex.*; | [
"java.util"
]
| java.util; | 2,437,230 |
public Map<String, String> tags() {
return this.tags;
} | Map<String, String> function() { return this.tags; } | /**
* Get the tags value.
*
* @return the tags value
*/ | Get the tags value | tags | {
"repo_name": "martinsawicki/azure-sdk-for-java",
"path": "azure-mgmt-cognitiveservices/src/main/java/com/microsoft/azure/management/cognitiveservices/implementation/CognitiveServicesAccountCreateParametersInner.java",
"license": "mit",
"size": 4612
} | [
"java.util.Map"
]
| import java.util.Map; | import java.util.*; | [
"java.util"
]
| java.util; | 1,515,083 |
@Test()
public void testWithCustomWrappedConnector()
throws Exception
{
final TestReferralConnector testReferralConnector =
new TestReferralConnector();
testReferralConnector.setExceptionToThrow(new LDAPException(
ResultCode.CONNECT_ERROR, "I feel like failing."));
final RetainConnectExceptionReferralConnector referralConnector =
new RetainConnectExceptionReferralConnector(testReferralConnector);
try (LDAPConnection conn = ds1.getConnection())
{
// Create a search request that should trigger a referral, and configure
// it to use a custom referral handler.
final SearchRequest searchRequest = new SearchRequest(
"ou=Test,dc=example,dc=com", SearchScope.BASE,
Filter.createPresenceFilter("objectClass"));
searchRequest.setFollowReferrals(true);
searchRequest.setReferralConnector(referralConnector);
SearchResult searchResult;
try
{
searchResult = conn.search(searchRequest);
}
catch (final LDAPSearchException e)
{
searchResult = e.getSearchResult();
}
assertResultCodeEquals(searchResult, ResultCode.REFERRAL);
assertNotNull(referralConnector.getExceptionFromLastConnectAttempt());
assertEquals(
referralConnector.getExceptionFromLastConnectAttempt().
getResultCode(),
ResultCode.CONNECT_ERROR);
assertEquals(
referralConnector.getExceptionFromLastConnectAttempt().getMessage(),
"I feel like failing.");
}
} | @Test() void function() throws Exception { final TestReferralConnector testReferralConnector = new TestReferralConnector(); testReferralConnector.setExceptionToThrow(new LDAPException( ResultCode.CONNECT_ERROR, STR)); final RetainConnectExceptionReferralConnector referralConnector = new RetainConnectExceptionReferralConnector(testReferralConnector); try (LDAPConnection conn = ds1.getConnection()) { final SearchRequest searchRequest = new SearchRequest( STR, SearchScope.BASE, Filter.createPresenceFilter(STR)); searchRequest.setFollowReferrals(true); searchRequest.setReferralConnector(referralConnector); SearchResult searchResult; try { searchResult = conn.search(searchRequest); } catch (final LDAPSearchException e) { searchResult = e.getSearchResult(); } assertResultCodeEquals(searchResult, ResultCode.REFERRAL); assertNotNull(referralConnector.getExceptionFromLastConnectAttempt()); assertEquals( referralConnector.getExceptionFromLastConnectAttempt(). getResultCode(), ResultCode.CONNECT_ERROR); assertEquals( referralConnector.getExceptionFromLastConnectAttempt().getMessage(), STR); } } | /**
* Tests the behavior when the referral connector wraps a provided connector.
*
* @throws Exception If an unexpected problem occurs.
*/ | Tests the behavior when the referral connector wraps a provided connector | testWithCustomWrappedConnector | {
"repo_name": "UnboundID/ldapsdk",
"path": "tests/unit/src/com/unboundid/ldap/sdk/RetainConnectExceptionReferralConnectorTestCase.java",
"license": "gpl-2.0",
"size": 10469
} | [
"org.testng.annotations.Test"
]
| import org.testng.annotations.Test; | import org.testng.annotations.*; | [
"org.testng.annotations"
]
| org.testng.annotations; | 885,512 |
public void setForegroundState(RemoteValueState foregroundState) {
this.foregroundState = foregroundState;
} | void function(RemoteValueState foregroundState) { this.foregroundState = foregroundState; } | /**
* Sets the foregroundState.
*
* @param foregroundState
* the foregroundState to set.
*/ | Sets the foregroundState | setForegroundState | {
"repo_name": "maximehamm/jspresso-ce",
"path": "remote/components/src/main/java/org/jspresso/framework/gui/remote/RComponent.java",
"license": "lgpl-3.0",
"size": 9005
} | [
"org.jspresso.framework.state.remote.RemoteValueState"
]
| import org.jspresso.framework.state.remote.RemoteValueState; | import org.jspresso.framework.state.remote.*; | [
"org.jspresso.framework"
]
| org.jspresso.framework; | 1,313,578 |
public List<GVRSceneObject> getSceneObjects() {
return Collections.unmodifiableList(mSceneObjects);
} | List<GVRSceneObject> function() { return Collections.unmodifiableList(mSceneObjects); } | /**
* The top-level scene objects.
*
* @return A read-only list containing all the 'root' scene objects (those
* that were added directly to the scene).
*
* @since 2.0.0
*/ | The top-level scene objects | getSceneObjects | {
"repo_name": "Maginador/GearVRf",
"path": "GVRf/Framework/src/org/gearvrf/GVRScene.java",
"license": "apache-2.0",
"size": 8400
} | [
"java.util.Collections",
"java.util.List"
]
| import java.util.Collections; import java.util.List; | import java.util.*; | [
"java.util"
]
| java.util; | 2,882,545 |
Class<Score_> getScoreClass(); | Class<Score_> getScoreClass(); | /**
* Returns the {@link Class} of the actual {@link Score} implementation.
* For example: returns {@link HardSoftScore HardSoftScore.class} on {@link HardSoftScoreDefinition}.
*
* @return never null
*/ | Returns the <code>Class</code> of the actual <code>Score</code> implementation. For example: returns <code>HardSoftScore HardSoftScore.class</code> on <code>HardSoftScoreDefinition</code> | getScoreClass | {
"repo_name": "droolsjbpm/optaplanner",
"path": "optaplanner-core/src/main/java/org/optaplanner/core/impl/score/definition/ScoreDefinition.java",
"license": "apache-2.0",
"size": 7107
} | [
"org.optaplanner.core.api.score.Score"
]
| import org.optaplanner.core.api.score.Score; | import org.optaplanner.core.api.score.*; | [
"org.optaplanner.core"
]
| org.optaplanner.core; | 676,255 |
public LockService getLockService()
{
return lockService;
} | LockService function() { return lockService; } | /**
* Sets the lock service.
*/ | Sets the lock service | getLockService | {
"repo_name": "daniel-he/community-edition",
"path": "projects/repository/source/java/org/alfresco/opencmis/CMISConnector.java",
"license": "lgpl-3.0",
"size": 151182
} | [
"org.alfresco.service.cmr.lock.LockService"
]
| import org.alfresco.service.cmr.lock.LockService; | import org.alfresco.service.cmr.lock.*; | [
"org.alfresco.service"
]
| org.alfresco.service; | 1,514,122 |
public void getAttachment(Attachment attachment, BodyType bodyType,
Iterable<PropertyDefinitionBase> additionalProperties)
throws Exception {
List<Attachment> attachmentArray = new ArrayList<Attachment>();
attachmentArray.add(attachment);
this.internalGetAttachments(attachmentArray, bodyType, additionalProperties,
ServiceErrorHandling.ThrowOnError);
} | void function(Attachment attachment, BodyType bodyType, Iterable<PropertyDefinitionBase> additionalProperties) throws Exception { List<Attachment> attachmentArray = new ArrayList<Attachment>(); attachmentArray.add(attachment); this.internalGetAttachments(attachmentArray, bodyType, additionalProperties, ServiceErrorHandling.ThrowOnError); } | /**
* Gets the attachment.
*
* @param attachment the attachment
* @param bodyType the body type
* @param additionalProperties the additional property
* @throws Exception the exception
*/ | Gets the attachment | getAttachment | {
"repo_name": "xvronny/ews-java-api",
"path": "src/main/java/microsoft/exchange/webservices/data/core/ExchangeService.java",
"license": "mit",
"size": 161280
} | [
"java.util.ArrayList",
"java.util.List"
]
| import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
]
| java.util; | 1,478,678 |
public FlexLayout align(ContentAlignment eAlignment)
{
if (eAlignment == ContentAlignment.SPACE_EVENLY)
{
throw new IllegalArgumentException(
"SPACE_EVENLY alignment is not supported for the secondary layout axis");
}
return _with(() -> eAlignContent = eAlignment);
} | FlexLayout function(ContentAlignment eAlignment) { if (eAlignment == ContentAlignment.SPACE_EVENLY) { throw new IllegalArgumentException( STR); } return _with(() -> eAlignContent = eAlignment); } | /***************************************
* Sets the alignment of the layout content along the secondary layout axis
* (#see method {@link #direction(Orientation, boolean)}). This property
* will only have an effect if the layout has multiple lines because when
* wrapping occurs. Almost all content alignment values with the exception
* of {@link ContentAlignment#SPACE_EVENLY SPACE_EVENLY} are supported.
*
* @param eAlignment The horizontal content alignment
*
* @return This instance for fluent invocation
*
* @throws IllegalArgumentException If an unsupported aligment is provided
*/ | Sets the alignment of the layout content along the secondary layout axis (#see method <code>#direction(Orientation, boolean)</code>). This property will only have an effect if the layout has multiple lines because when wrapping occurs. Almost all content alignment values with the exception of <code>ContentAlignment#SPACE_EVENLY SPACE_EVENLY</code> are supported | align | {
"repo_name": "esoco/gewt",
"path": "src/main/java/de/esoco/ewt/layout/FlexLayout.java",
"license": "apache-2.0",
"size": 9635
} | [
"de.esoco.lib.property.ContentAlignment"
]
| import de.esoco.lib.property.ContentAlignment; | import de.esoco.lib.property.*; | [
"de.esoco.lib"
]
| de.esoco.lib; | 2,555,484 |
@Override
public int replace(String regex, String replaceBy, boolean caseSensitive) throws Exception {
int totalReplaced = 0;
for (JMeterProperty jMeterProperty : getArguments()) {
HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue();
String value = arg.getValue();
if(!StringUtils.isEmpty(value)) {
Object[] result = JOrphanUtils.replaceAllWithRegex(value, regex, replaceBy, caseSensitive);
// check if there is anything to replace
int nbReplaced = ((Integer)result[1]).intValue();
if (nbReplaced>0) {
String replacedText = (String) result[0];
arg.setValue(replacedText);
totalReplaced += nbReplaced;
}
}
}
String value = getPath();
if(!StringUtils.isEmpty(value)) {
Object[] result = JOrphanUtils.replaceAllWithRegex(value, regex, replaceBy, caseSensitive);
// check if there is anything to replace
int nbReplaced = ((Integer)result[1]).intValue();
if (nbReplaced>0) {
String replacedText = (String) result[0];
setPath(replacedText);
totalReplaced += nbReplaced;
}
}
if(!StringUtils.isEmpty(getDomain())) {
Object[] result = JOrphanUtils.replaceAllWithRegex(getDomain(), regex, replaceBy, caseSensitive);
// check if there is anything to replace
int nbReplaced = ((Integer)result[1]).intValue();
if (nbReplaced>0) {
String replacedText = (String) result[0];
setDomain(replacedText);
totalReplaced += nbReplaced;
}
}
return totalReplaced;
} | int function(String regex, String replaceBy, boolean caseSensitive) throws Exception { int totalReplaced = 0; for (JMeterProperty jMeterProperty : getArguments()) { HTTPArgument arg = (HTTPArgument) jMeterProperty.getObjectValue(); String value = arg.getValue(); if(!StringUtils.isEmpty(value)) { Object[] result = JOrphanUtils.replaceAllWithRegex(value, regex, replaceBy, caseSensitive); int nbReplaced = ((Integer)result[1]).intValue(); if (nbReplaced>0) { String replacedText = (String) result[0]; arg.setValue(replacedText); totalReplaced += nbReplaced; } } } String value = getPath(); if(!StringUtils.isEmpty(value)) { Object[] result = JOrphanUtils.replaceAllWithRegex(value, regex, replaceBy, caseSensitive); int nbReplaced = ((Integer)result[1]).intValue(); if (nbReplaced>0) { String replacedText = (String) result[0]; setPath(replacedText); totalReplaced += nbReplaced; } } if(!StringUtils.isEmpty(getDomain())) { Object[] result = JOrphanUtils.replaceAllWithRegex(getDomain(), regex, replaceBy, caseSensitive); int nbReplaced = ((Integer)result[1]).intValue(); if (nbReplaced>0) { String replacedText = (String) result[0]; setDomain(replacedText); totalReplaced += nbReplaced; } } return totalReplaced; } | /**
* Replace by replaceBy in path and body (arguments) properties
*/ | Replace by replaceBy in path and body (arguments) properties | replace | {
"repo_name": "vherilier/jmeter",
"path": "src/protocol/http/org/apache/jmeter/protocol/http/sampler/HTTPSamplerBase.java",
"license": "apache-2.0",
"size": 84530
} | [
"org.apache.commons.lang3.StringUtils",
"org.apache.jmeter.protocol.http.util.HTTPArgument",
"org.apache.jmeter.testelement.property.JMeterProperty",
"org.apache.jorphan.util.JOrphanUtils"
]
| import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.protocol.http.util.HTTPArgument; import org.apache.jmeter.testelement.property.JMeterProperty; import org.apache.jorphan.util.JOrphanUtils; | import org.apache.commons.lang3.*; import org.apache.jmeter.protocol.http.util.*; import org.apache.jmeter.testelement.property.*; import org.apache.jorphan.util.*; | [
"org.apache.commons",
"org.apache.jmeter",
"org.apache.jorphan"
]
| org.apache.commons; org.apache.jmeter; org.apache.jorphan; | 2,215,304 |
List<TimesheetActivityType> activityTypes = TimesheetDao.getTimesheetActivityTypeAsList();
List<TimesheetActivityTypeListView> activityTypesListView = new ArrayList<TimesheetActivityTypeListView>();
for (TimesheetActivityType activityType : activityTypes) {
activityTypesListView.add(new TimesheetActivityTypeListView(activityType));
}
Table<TimesheetActivityTypeListView> activityTypesFilledTable = this.getTableProvider().get().timesheetActivityType.templateTable
.fill(activityTypesListView);
List<TimesheetActivity> activities = TimesheetDao.getTimesheetActivityAsList();
List<TimesheetActivityListView> activitiesListView = new ArrayList<TimesheetActivityListView>();
for (TimesheetActivity activity : activities) {
activitiesListView.add(new TimesheetActivityListView(activity));
}
Table<TimesheetActivityListView> activitiesFilledTable = this.getTableProvider().get().timesheetActivity.templateTable.fill(activitiesListView);
return ok(views.html.admin.config.datareference.timesheetactivity.timesheet_activities.render(activityTypesFilledTable, activitiesFilledTable));
} | List<TimesheetActivityType> activityTypes = TimesheetDao.getTimesheetActivityTypeAsList(); List<TimesheetActivityTypeListView> activityTypesListView = new ArrayList<TimesheetActivityTypeListView>(); for (TimesheetActivityType activityType : activityTypes) { activityTypesListView.add(new TimesheetActivityTypeListView(activityType)); } Table<TimesheetActivityTypeListView> activityTypesFilledTable = this.getTableProvider().get().timesheetActivityType.templateTable .fill(activityTypesListView); List<TimesheetActivity> activities = TimesheetDao.getTimesheetActivityAsList(); List<TimesheetActivityListView> activitiesListView = new ArrayList<TimesheetActivityListView>(); for (TimesheetActivity activity : activities) { activitiesListView.add(new TimesheetActivityListView(activity)); } Table<TimesheetActivityListView> activitiesFilledTable = this.getTableProvider().get().timesheetActivity.templateTable.fill(activitiesListView); return ok(views.html.admin.config.datareference.timesheetactivity.timesheet_activities.render(activityTypesFilledTable, activitiesFilledTable)); } | /**
* Reference data: timesheet activities.
*/ | Reference data: timesheet activities | list | {
"repo_name": "theAgileFactory/maf-desktop-app",
"path": "app/controllers/admin/ConfigurationTimesheetActivityController.java",
"license": "gpl-2.0",
"size": 10409
} | [
"java.util.ArrayList",
"java.util.List"
]
| import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
]
| java.util; | 962,367 |
@Test
public void testCU_To_NewCU_1Tomato()
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
final I_C_BPartner bpartner = data.helper.createBPartner("testVendor");
final I_C_BPartner_Location bPartnerLocation = data.helper.createBPartnerLocation(bpartner);
final I_M_Warehouse warehouse = data.helper.createWarehouse("testWarehouse");
final I_M_Locator locator = data.helper.createLocator("testLocator", warehouse);
final I_M_HU sourceTU;
final I_M_HU cuToSplit;
{
final LUTUProducerDestination lutuProducer = new LUTUProducerDestination();
lutuProducer.setNoLU();
lutuProducer.setTUPI(data.piTU_IFCO);
lutuProducer.setC_BPartner(bpartner);
lutuProducer.setM_Locator(locator);
lutuProducer.setC_BPartner_Location_ID(bPartnerLocation.getC_BPartner_Location_ID());
data.helper.load(lutuProducer, data.helper.pTomato, new BigDecimal("2"), data.helper.uomKg);
final List<I_M_HU> createdTUs = lutuProducer.getCreatedHUs();
assertThat(createdTUs.size(), is(1));
sourceTU = createdTUs.get(0);
// guard: verify that we have on IFCO with a two-tomato-CU in it
final Node sourceTUBeforeSplitXML = HUXmlConverter.toXml(sourceTU);
assertThat(sourceTUBeforeSplitXML, hasXPath("count(HU-TU_IFCO[@HUStatus='P'])", is("1")));
assertThat(sourceTUBeforeSplitXML, hasXPath("string(HU-TU_IFCO/Storage[@M_Product_Value='Tomato' and @C_UOM_Name='Kg']/@Qty)", is("2.000")));
assertThat(sourceTUBeforeSplitXML, hasXPath("string(HU-TU_IFCO/Item[@ItemType='MI']/HU-VirtualPI/Storage[@M_Product_Value='Tomato' and @C_UOM_Name='Kg']/@Qty)", is("2.000")));
final List<I_M_HU> createdCUs = handlingUnitsDAO.retrieveIncludedHUs(createdTUs.get(0));
assertThat(createdCUs.size(), is(1));
cuToSplit = createdCUs.get(0);
}
// invoke the method under test
final List<I_M_HU> newCUs = HUTransferService.get(data.helper.getHUContext())
.cuToNewCU(cuToSplit, BigDecimal.ONE);
assertThat(newCUs.size(), is(1));
final Node sourceTUXML = HUXmlConverter.toXml(sourceTU);
assertThat(sourceTUXML, hasXPath("count(HU-TU_IFCO[@HUStatus='P'])", is("1")));
assertThat(sourceTUXML, hasXPath("count(HU-TU_IFCO/Storage[@M_Product_Value='Tomato' and @Qty='1.000' and @C_UOM_Name='Kg'])", is("1")));
final Node cuToSplitXML = HUXmlConverter.toXml(cuToSplit);
assertThat(cuToSplitXML, hasXPath("count(HU-VirtualPI[@HUStatus='P'])", is("1")));
assertThat(cuToSplitXML, hasXPath("count(HU-VirtualPI/Storage[@M_Product_Value='Tomato' and @Qty='1.000' and @C_UOM_Name='Kg'])", is("1")));
final Node newCUXML = HUXmlConverter.toXml(newCUs.get(0));
assertThat(newCUXML, not(hasXPath("HU-VirtualPI/M_HU_Item_Parent_ID"))); // verify that there is no parent HU
assertThat(newCUXML, hasXPath("count(HU-VirtualPI[@HUStatus='P'])", is("1")));
assertThat(newCUXML, hasXPath("count(HU-VirtualPI/Storage[@M_Product_Value='Tomato' and @Qty='1.000' and @C_UOM_Name='Kg'])", is("1")));
assertThat(newCUXML, hasXPath("string(HU-VirtualPI/@C_BPartner_ID)", is(Integer.toString(bpartner.getC_BPartner_ID())))); // verify that the bpartner is propagated
assertThat(newCUXML, hasXPath("string(HU-VirtualPI/@C_BPartner_Location_ID)", is(Integer.toString(bPartnerLocation.getC_BPartner_Location_ID())))); // verify that the bpartner location is propagated
assertThat(newCUXML, hasXPath("string(HU-VirtualPI/@M_Locator_ID)", is(Integer.toString(locator.getM_Locator_ID())))); // verify that the locator is propagated
} | void function() { final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class); final I_C_BPartner bpartner = data.helper.createBPartner(STR); final I_C_BPartner_Location bPartnerLocation = data.helper.createBPartnerLocation(bpartner); final I_M_Warehouse warehouse = data.helper.createWarehouse(STR); final I_M_Locator locator = data.helper.createLocator(STR, warehouse); final I_M_HU sourceTU; final I_M_HU cuToSplit; { final LUTUProducerDestination lutuProducer = new LUTUProducerDestination(); lutuProducer.setNoLU(); lutuProducer.setTUPI(data.piTU_IFCO); lutuProducer.setC_BPartner(bpartner); lutuProducer.setM_Locator(locator); lutuProducer.setC_BPartner_Location_ID(bPartnerLocation.getC_BPartner_Location_ID()); data.helper.load(lutuProducer, data.helper.pTomato, new BigDecimal("2"), data.helper.uomKg); final List<I_M_HU> createdTUs = lutuProducer.getCreatedHUs(); assertThat(createdTUs.size(), is(1)); sourceTU = createdTUs.get(0); final Node sourceTUBeforeSplitXML = HUXmlConverter.toXml(sourceTU); assertThat(sourceTUBeforeSplitXML, hasXPath(STR, is("1"))); assertThat(sourceTUBeforeSplitXML, hasXPath(STR, is("2.000"))); assertThat(sourceTUBeforeSplitXML, hasXPath(STR, is("2.000"))); final List<I_M_HU> createdCUs = handlingUnitsDAO.retrieveIncludedHUs(createdTUs.get(0)); assertThat(createdCUs.size(), is(1)); cuToSplit = createdCUs.get(0); } final List<I_M_HU> newCUs = HUTransferService.get(data.helper.getHUContext()) .cuToNewCU(cuToSplit, BigDecimal.ONE); assertThat(newCUs.size(), is(1)); final Node sourceTUXML = HUXmlConverter.toXml(sourceTU); assertThat(sourceTUXML, hasXPath(STR, is("1"))); assertThat(sourceTUXML, hasXPath(STR, is("1"))); final Node cuToSplitXML = HUXmlConverter.toXml(cuToSplit); assertThat(cuToSplitXML, hasXPath(STR, is("1"))); assertThat(cuToSplitXML, hasXPath(STR, is("1"))); final Node newCUXML = HUXmlConverter.toXml(newCUs.get(0)); assertThat(newCUXML, not(hasXPath(STR))); assertThat(newCUXML, hasXPath(STR, is("1"))); assertThat(newCUXML, hasXPath(STR, is("1"))); assertThat(newCUXML, hasXPath(STR, is(Integer.toString(bpartner.getC_BPartner_ID())))); assertThat(newCUXML, hasXPath(STR, is(Integer.toString(bPartnerLocation.getC_BPartner_Location_ID())))); assertThat(newCUXML, hasXPath(STR, is(Integer.toString(locator.getM_Locator_ID())))); } | /**
* Tests {@link HUTransferService#cuToNewCU(I_M_HU, org.compiere.model.I_M_Product, org.compiere.model.I_C_UOM, BigDecimal)} by splitting one tomato onto a new CU.
* Also verifies that the new CU has the same C_BPartner, M_Locator etc as the old CU.
*/ | Tests <code>HUTransferService#cuToNewCU(I_M_HU, org.compiere.model.I_M_Product, org.compiere.model.I_C_UOM, BigDecimal)</code> by splitting one tomato onto a new CU. Also verifies that the new CU has the same C_BPartner, M_Locator etc as the old CU | testCU_To_NewCU_1Tomato | {
"repo_name": "klst-com/metasfresh",
"path": "de.metas.handlingunits.base/src/test/java/de/metas/handlingunits/allocation/transfer/HUTransferServiceTests.java",
"license": "gpl-2.0",
"size": 50793
} | [
"de.metas.handlingunits.HUXmlConverter",
"de.metas.handlingunits.IHandlingUnitsDAO",
"de.metas.handlingunits.allocation.transfer.impl.LUTUProducerDestination",
"java.math.BigDecimal",
"java.util.List",
"org.adempiere.util.Services",
"org.hamcrest.Matchers",
"org.junit.Assert",
"org.w3c.dom.Node"
]
| import de.metas.handlingunits.HUXmlConverter; import de.metas.handlingunits.IHandlingUnitsDAO; import de.metas.handlingunits.allocation.transfer.impl.LUTUProducerDestination; import java.math.BigDecimal; import java.util.List; import org.adempiere.util.Services; import org.hamcrest.Matchers; import org.junit.Assert; import org.w3c.dom.Node; | import de.metas.handlingunits.*; import de.metas.handlingunits.allocation.transfer.impl.*; import java.math.*; import java.util.*; import org.adempiere.util.*; import org.hamcrest.*; import org.junit.*; import org.w3c.dom.*; | [
"de.metas.handlingunits",
"java.math",
"java.util",
"org.adempiere.util",
"org.hamcrest",
"org.junit",
"org.w3c.dom"
]
| de.metas.handlingunits; java.math; java.util; org.adempiere.util; org.hamcrest; org.junit; org.w3c.dom; | 2,380,700 |
public static List<PlantType> getPlantTypesProducing(final Resource resource) {
final List<PlantType> plantTypesProducingResource = new ArrayList<>();
for (final PlantType plantType : PlantType.ALL_PLANT_TYPES_LIST) {
for (final Amount plantTypeAmount : plantType.production) {
if (resource.equals(plantTypeAmount.getResource())) {
plantTypesProducingResource.add(plantType);
}
}
}
return plantTypesProducingResource;
}
| static List<PlantType> function(final Resource resource) { final List<PlantType> plantTypesProducingResource = new ArrayList<>(); for (final PlantType plantType : PlantType.ALL_PLANT_TYPES_LIST) { for (final Amount plantTypeAmount : plantType.production) { if (resource.equals(plantTypeAmount.getResource())) { plantTypesProducingResource.add(plantType); } } } return plantTypesProducingResource; } | /**
* Gets the plant types that produce a given resource.
*
* @param resource
* A resource.
* @return A list of plant types that produce a given resource.
*/ | Gets the plant types that produce a given resource | getPlantTypesProducing | {
"repo_name": "JavierCenteno/Industry",
"path": "src/type/PlantType.java",
"license": "gpl-3.0",
"size": 9682
} | [
"java.util.ArrayList",
"java.util.List"
]
| import java.util.ArrayList; import java.util.List; | import java.util.*; | [
"java.util"
]
| java.util; | 19,050 |
CipherData getCipherData(boolean generateIfNeeded) {
if (mData == null && generateIfNeeded) {
// Ideally, this task should have been started way before this.
triggerKeyGeneration();
// Grab the data from the task.
CipherData data;
try {
data = mDataGenerator.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
// Only the first thread is allowed to save the data.
synchronized (mDataLock) {
if (mData == null) mData = data;
}
}
return mData;
} | CipherData getCipherData(boolean generateIfNeeded) { if (mData == null && generateIfNeeded) { triggerKeyGeneration(); CipherData data; try { data = mDataGenerator.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (ExecutionException e) { throw new RuntimeException(e); } synchronized (mDataLock) { if (mData == null) mData = data; } } return mData; } | /**
* Returns data required for generating the Cipher.
* @param generateIfNeeded Generates data on the background thread, blocking until it is done.
* @return Data to use for the Cipher, null if it couldn't be generated.
*/ | Returns data required for generating the Cipher | getCipherData | {
"repo_name": "7kbird/chrome",
"path": "content/public/android/java/src/org/chromium/content/browser/crypto/CipherFactory.java",
"license": "bsd-3-clause",
"size": 10908
} | [
"java.util.concurrent.ExecutionException"
]
| import java.util.concurrent.ExecutionException; | import java.util.concurrent.*; | [
"java.util"
]
| java.util; | 2,063,453 |
protected void doUnlock(WebdavRequest request, WebdavResponse response,
DavResource resource) throws DavException {
// get lock token from header
String lockToken = request.getLockToken();
TransactionInfo tInfo = request.getTransactionInfo();
if (tInfo != null) {
((TransactionResource) resource).unlock(lockToken, tInfo);
} else {
resource.unlock(lockToken);
}
response.setStatus(DavServletResponse.SC_NO_CONTENT);
} | void function(WebdavRequest request, WebdavResponse response, DavResource resource) throws DavException { String lockToken = request.getLockToken(); TransactionInfo tInfo = request.getTransactionInfo(); if (tInfo != null) { ((TransactionResource) resource).unlock(lockToken, tInfo); } else { resource.unlock(lockToken); } response.setStatus(DavServletResponse.SC_NO_CONTENT); } | /**
* The UNLOCK method
*
* @param request
* @param response
* @param resource
* @throws DavException
*/ | The UNLOCK method | doUnlock | {
"repo_name": "SylvesterAbreu/jackrabbit",
"path": "jackrabbit-webdav/src/main/java/org/apache/jackrabbit/webdav/server/AbstractWebdavServlet.java",
"license": "apache-2.0",
"size": 51686
} | [
"org.apache.jackrabbit.webdav.DavException",
"org.apache.jackrabbit.webdav.DavResource",
"org.apache.jackrabbit.webdav.DavServletResponse",
"org.apache.jackrabbit.webdav.WebdavRequest",
"org.apache.jackrabbit.webdav.WebdavResponse",
"org.apache.jackrabbit.webdav.transaction.TransactionInfo",
"org.apache.jackrabbit.webdav.transaction.TransactionResource"
]
| import org.apache.jackrabbit.webdav.DavException; import org.apache.jackrabbit.webdav.DavResource; import org.apache.jackrabbit.webdav.DavServletResponse; import org.apache.jackrabbit.webdav.WebdavRequest; import org.apache.jackrabbit.webdav.WebdavResponse; import org.apache.jackrabbit.webdav.transaction.TransactionInfo; import org.apache.jackrabbit.webdav.transaction.TransactionResource; | import org.apache.jackrabbit.webdav.*; import org.apache.jackrabbit.webdav.transaction.*; | [
"org.apache.jackrabbit"
]
| org.apache.jackrabbit; | 2,785,924 |
private void createEntryTypesCombobox() {
Iterator<EntryType> iterator = EntryTypes
.getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()).iterator();
Vector<BibtexEntryTypeWrapper> list = new Vector<>();
list.add(new BibtexEntryTypeWrapper(null));
while (iterator.hasNext()) {
list.add(new BibtexEntryTypeWrapper(iterator.next()));
}
comboBoxEntryTypeSelection = new JComboBox<>(list);
}
private static class BibtexEntryTypeWrapper {
private final EntryType entryType;
BibtexEntryTypeWrapper(EntryType bibtexType) {
this.entryType = bibtexType;
} | void function() { Iterator<EntryType> iterator = EntryTypes .getAllValues(frame.getCurrentBasePanel().getBibDatabaseContext().getMode()).iterator(); Vector<BibtexEntryTypeWrapper> list = new Vector<>(); list.add(new BibtexEntryTypeWrapper(null)); while (iterator.hasNext()) { list.add(new BibtexEntryTypeWrapper(iterator.next())); } comboBoxEntryTypeSelection = new JComboBox<>(list); } private static class BibtexEntryTypeWrapper { private final EntryType entryType; BibtexEntryTypeWrapper(EntryType bibtexType) { this.entryType = bibtexType; } | /**
* Creates the ComboBox-View for the Listbox that holds the Bibtex entry
* types.
*/ | Creates the ComboBox-View for the Listbox that holds the Bibtex entry types | createEntryTypesCombobox | {
"repo_name": "motokito/jabref",
"path": "src/main/java/net/sf/jabref/gui/FindUnlinkedFilesDialog.java",
"license": "mit",
"size": 47869
} | [
"java.util.Iterator",
"java.util.Vector",
"javax.swing.JComboBox",
"net.sf.jabref.model.EntryTypes",
"net.sf.jabref.model.entry.EntryType"
]
| import java.util.Iterator; import java.util.Vector; import javax.swing.JComboBox; import net.sf.jabref.model.EntryTypes; import net.sf.jabref.model.entry.EntryType; | import java.util.*; import javax.swing.*; import net.sf.jabref.model.*; import net.sf.jabref.model.entry.*; | [
"java.util",
"javax.swing",
"net.sf.jabref"
]
| java.util; javax.swing; net.sf.jabref; | 925,385 |
public boolean hasModificationOverlap(IonType ion) {
if (!hasMods() || !ion.hasMods())
return false;
IonModification[] a = mod.getAdducts();
IonModification[] b = ion.mod.getAdducts();
if (a == b)
return true;
for (final IonModification aa : a)
if (Arrays.stream(b).anyMatch(ab -> aa.equals(ab)))
return true;
return false;
} | boolean function(IonType ion) { if (!hasMods() !ion.hasMods()) return false; IonModification[] a = mod.getAdducts(); IonModification[] b = ion.mod.getAdducts(); if (a == b) return true; for (final IonModification aa : a) if (Arrays.stream(b).anyMatch(ab -> aa.equals(ab))) return true; return false; } | /**
* checks if at least one modification is shared
*
* @param a
* @return
*/ | checks if at least one modification is shared | hasModificationOverlap | {
"repo_name": "tomas-pluskal/mzmine3",
"path": "src/main/java/io/github/mzmine/datamodel/identities/iontype/IonType.java",
"license": "gpl-2.0",
"size": 11222
} | [
"java.util.Arrays"
]
| import java.util.Arrays; | import java.util.*; | [
"java.util"
]
| java.util; | 1,767,095 |
public static final class IceProcessingListener
implements PropertyChangeListener
{
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
Object iceProcessingState = evt.getNewValue();
System.out.println(
"Agent entered the " + iceProcessingState + " state.");
if(iceProcessingState == IceProcessingState.COMPLETED)
{
System.out.println(
"Total ICE processing time: "
+ (processingEndTime - startTime) + "ms");
Agent agent = (Agent)evt.getSource();
List<IceMediaStream> streams = agent.getStreams();
for(IceMediaStream stream : streams)
{
String streamName = stream.getName();
System.out.println(
"Pairs selected for stream: " + streamName);
List<Component> components = stream.getComponents();
for(Component cmp : components)
{
String cmpName = cmp.getName();
System.out.println(cmpName + ": "
+ cmp.getSelectedPair());
}
}
System.out.println("Printing the completed check lists:");
for(IceMediaStream stream : streams)
{
String streamName = stream.getName();
System.out.println("Check list for stream: " + streamName);
//uncomment for a more verbose output
System.out.println(stream.getCheckList());
}
}
else if(iceProcessingState == IceProcessingState.TERMINATED
|| iceProcessingState == IceProcessingState.FAILED)
{
((Agent) evt.getSource()).free();
System.exit(0);
}
}
} | static final class IceProcessingListener implements PropertyChangeListener { public void function(PropertyChangeEvent evt) { long processingEndTime = System.currentTimeMillis(); Object iceProcessingState = evt.getNewValue(); System.out.println( STR + iceProcessingState + STR); if(iceProcessingState == IceProcessingState.COMPLETED) { System.out.println( STR + (processingEndTime - startTime) + "ms"); Agent agent = (Agent)evt.getSource(); List<IceMediaStream> streams = agent.getStreams(); for(IceMediaStream stream : streams) { String streamName = stream.getName(); System.out.println( STR + streamName); List<Component> components = stream.getComponents(); for(Component cmp : components) { String cmpName = cmp.getName(); System.out.println(cmpName + STR + cmp.getSelectedPair()); } } System.out.println(STR); for(IceMediaStream stream : streams) { String streamName = stream.getName(); System.out.println(STR + streamName); System.out.println(stream.getCheckList()); } } else if(iceProcessingState == IceProcessingState.TERMINATED iceProcessingState == IceProcessingState.FAILED) { ((Agent) evt.getSource()).free(); System.exit(0); } } } | /**
* System.exit()s as soon as ICE processing enters a final state.
*
* @param evt the {@link PropertyChangeEvent} containing the old and new
* states of ICE processing.
*/ | System.exit()s as soon as ICE processing enters a final state | propertyChange | {
"repo_name": "ChipsetSV/MultiPaint",
"path": "src/com/chipsetsv/multipaint/Ice.java",
"license": "apache-2.0",
"size": 12784
} | [
"java.beans.PropertyChangeEvent",
"java.beans.PropertyChangeListener",
"java.util.List",
"org.ice4j.ice.Agent",
"org.ice4j.ice.Component",
"org.ice4j.ice.IceMediaStream",
"org.ice4j.ice.IceProcessingState"
]
| import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import org.ice4j.ice.Agent; import org.ice4j.ice.Component; import org.ice4j.ice.IceMediaStream; import org.ice4j.ice.IceProcessingState; | import java.beans.*; import java.util.*; import org.ice4j.ice.*; | [
"java.beans",
"java.util",
"org.ice4j.ice"
]
| java.beans; java.util; org.ice4j.ice; | 2,729,639 |
@Test
public void testCompositeBindingUpdate() throws Exception {
final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(getSubsystemXml()).build();
// updates binding 'a' through composite op
// binding-type used is lookup, op should succeed even if lookup value is set by a followup step
final ModelNode addr = Operations.createAddress(ModelDescriptionConstants.SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME, NamingSubsystemModel.BINDING, "java:global/a");
final ModelNode compositeOp = Operations.CompositeOperationBuilder.create()
.addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.BINDING_TYPE, NamingSubsystemModel.LOOKUP))
.addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.LOOKUP, "java:global/b"))
.build().getOperation();
ModelTestUtils.checkOutcome(services.executeOperation(compositeOp));
} | void function() throws Exception { final KernelServices services = createKernelServicesBuilder(createAdditionalInitialization()).setSubsystemXml(getSubsystemXml()).build(); final ModelNode addr = Operations.createAddress(ModelDescriptionConstants.SUBSYSTEM, NamingExtension.SUBSYSTEM_NAME, NamingSubsystemModel.BINDING, STR); final ModelNode compositeOp = Operations.CompositeOperationBuilder.create() .addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.BINDING_TYPE, NamingSubsystemModel.LOOKUP)) .addStep(Operations.createWriteAttributeOperation(addr, NamingSubsystemModel.LOOKUP, STR)) .build().getOperation(); ModelTestUtils.checkOutcome(services.executeOperation(compositeOp)); } | /**
* Asserts that bindings may be updated through composite ops.
*
* @throws Exception
*/ | Asserts that bindings may be updated through composite ops | testCompositeBindingUpdate | {
"repo_name": "jstourac/wildfly",
"path": "naming/src/test/java/org/jboss/as/naming/subsystem/NamingSubsystemTestCase.java",
"license": "lgpl-2.1",
"size": 6229
} | [
"org.jboss.as.controller.client.helpers.Operations",
"org.jboss.as.controller.descriptions.ModelDescriptionConstants",
"org.jboss.as.model.test.ModelTestUtils",
"org.jboss.as.subsystem.test.KernelServices",
"org.jboss.dmr.ModelNode"
]
| import org.jboss.as.controller.client.helpers.Operations; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.model.test.ModelTestUtils; import org.jboss.as.subsystem.test.KernelServices; import org.jboss.dmr.ModelNode; | import org.jboss.as.controller.client.helpers.*; import org.jboss.as.controller.descriptions.*; import org.jboss.as.model.test.*; import org.jboss.as.subsystem.test.*; import org.jboss.dmr.*; | [
"org.jboss.as",
"org.jboss.dmr"
]
| org.jboss.as; org.jboss.dmr; | 519,826 |
public Observable<ServiceResponse<WorkflowTriggerCallbackUrlInner>> listCallbackUrlWithServiceResponseAsync(String resourceGroupName, String workflowName, String triggerName) {
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 (workflowName == null) {
throw new IllegalArgumentException("Parameter workflowName is required and cannot be null.");
}
if (triggerName == null) {
throw new IllegalArgumentException("Parameter triggerName 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<WorkflowTriggerCallbackUrlInner>> function(String resourceGroupName, String workflowName, String triggerName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException(STR); } if (resourceGroupName == null) { throw new IllegalArgumentException(STR); } if (workflowName == null) { throw new IllegalArgumentException(STR); } if (triggerName == null) { throw new IllegalArgumentException(STR); } if (this.client.apiVersion() == null) { throw new IllegalArgumentException(STR); } | /**
* Get the callback URL for a workflow trigger.
*
* @param resourceGroupName The resource group name.
* @param workflowName The workflow name.
* @param triggerName The workflow trigger name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the WorkflowTriggerCallbackUrlInner object
*/ | Get the callback URL for a workflow trigger | listCallbackUrlWithServiceResponseAsync | {
"repo_name": "navalev/azure-sdk-for-java",
"path": "sdk/logic/mgmt-v2018_07_01_preview/src/main/java/com/microsoft/azure/management/logic/v2018_07_01_preview/implementation/WorkflowTriggersInner.java",
"license": "mit",
"size": 57964
} | [
"com.microsoft.rest.ServiceResponse"
]
| import com.microsoft.rest.ServiceResponse; | import com.microsoft.rest.*; | [
"com.microsoft.rest"
]
| com.microsoft.rest; | 1,745,182 |
@Override
public int read(char[] buffer) throws IOException
{
return read(buffer, 0, buffer.length);
} | int function(char[] buffer) throws IOException { return read(buffer, 0, buffer.length); } | /**
* Reads the next characters from the message into an array and
* returns the number of characters read. Returns -1 if the end of the
* message has been reached.
* @param buffer The character array in which to store the characters.
* @return The number of characters read. Returns -1 if the
* end of the message has been reached.
* @exception IOException If an error occurs in reading the underlying
* stream.
*/ | Reads the next characters from the message into an array and returns the number of characters read. Returns -1 if the end of the message has been reached | read | {
"repo_name": "chenxiwen/CommonShellUtils",
"path": "src/main/java/org/apache/commons/net/io/DotTerminatedMessageReader.java",
"license": "apache-2.0",
"size": 9299
} | [
"java.io.IOException"
]
| import java.io.IOException; | import java.io.*; | [
"java.io"
]
| java.io; | 2,642,302 |
public MultiChangeBuilder<PS, SEG, S> replaceAbsolutely(int start, int end, StyledDocument<PS, SEG, S> replacement) {
return absoluteReplace(start, end, ReadOnlyStyledDocument.from(replacement));
} | MultiChangeBuilder<PS, SEG, S> function(int start, int end, StyledDocument<PS, SEG, S> replacement) { return absoluteReplace(start, end, ReadOnlyStyledDocument.from(replacement)); } | /**
* Replaces a range of characters with the given rich-text document.
*/ | Replaces a range of characters with the given rich-text document | replaceAbsolutely | {
"repo_name": "JFormDesigner/RichTextFX",
"path": "richtextfx/src/main/java/org/fxmisc/richtext/MultiChangeBuilder.java",
"license": "bsd-2-clause",
"size": 16745
} | [
"org.fxmisc.richtext.model.ReadOnlyStyledDocument",
"org.fxmisc.richtext.model.StyledDocument"
]
| import org.fxmisc.richtext.model.ReadOnlyStyledDocument; import org.fxmisc.richtext.model.StyledDocument; | import org.fxmisc.richtext.model.*; | [
"org.fxmisc.richtext"
]
| org.fxmisc.richtext; | 1,446,394 |
SystemData systemData(); | SystemData systemData(); | /**
* Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information.
*
* @return the systemData value.
*/ | Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information | systemData | {
"repo_name": "Azure/azure-sdk-for-java",
"path": "sdk/securityinsights/azure-resourcemanager-securityinsights/src/main/java/com/azure/resourcemanager/securityinsights/models/MetadataModel.java",
"license": "mit",
"size": 23019
} | [
"com.azure.core.management.SystemData"
]
| import com.azure.core.management.SystemData; | import com.azure.core.management.*; | [
"com.azure.core"
]
| com.azure.core; | 739,988 |
private static String highlightField(Query query, String fieldName, String text)
throws IOException, InvalidTokenOffsetsException {
TokenStream tokenStream = new StandardAnalyzer(Version.LUCENE_CURRENT).tokenStream(fieldName, new StringReader(text));
// Assuming "<B>", "</B>" used to highlight
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter();
QueryScorer scorer = new QueryScorer(query, fieldName, FIELD_NAME);
Highlighter highlighter = new Highlighter(formatter, scorer);
highlighter.setTextFragmenter(new SimpleFragmenter(Integer.MAX_VALUE));
String rv = highlighter.getBestFragments(tokenStream, text, 1, "(FIELD TEXT TRUNCATED)");
return rv.length() == 0 ? text : rv;
} | static String function(Query query, String fieldName, String text) throws IOException, InvalidTokenOffsetsException { TokenStream tokenStream = new StandardAnalyzer(Version.LUCENE_CURRENT).tokenStream(fieldName, new StringReader(text)); SimpleHTMLFormatter formatter = new SimpleHTMLFormatter(); QueryScorer scorer = new QueryScorer(query, fieldName, FIELD_NAME); Highlighter highlighter = new Highlighter(formatter, scorer); highlighter.setTextFragmenter(new SimpleFragmenter(Integer.MAX_VALUE)); String rv = highlighter.getBestFragments(tokenStream, text, 1, STR); return rv.length() == 0 ? text : rv; } | /**
* This method intended for use with <tt>testHighlightingWithDefaultField()</tt>
* @throws InvalidTokenOffsetsException
*/ | This method intended for use with testHighlightingWithDefaultField() | highlightField | {
"repo_name": "Overruler/retired-apache-sources",
"path": "lucene-2.9.4/contrib/highlighter/src/test/org/apache/lucene/search/highlight/HighlighterTest.java",
"license": "apache-2.0",
"size": 73712
} | [
"java.io.IOException",
"java.io.StringReader",
"org.apache.lucene.analysis.TokenStream",
"org.apache.lucene.analysis.standard.StandardAnalyzer",
"org.apache.lucene.search.Query",
"org.apache.lucene.util.Version"
]
| import java.io.IOException; import java.io.StringReader; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.search.Query; import org.apache.lucene.util.Version; | import java.io.*; import org.apache.lucene.analysis.*; import org.apache.lucene.analysis.standard.*; import org.apache.lucene.search.*; import org.apache.lucene.util.*; | [
"java.io",
"org.apache.lucene"
]
| java.io; org.apache.lucene; | 2,407,935 |
public void addPropertyChangeListener(PropertyChangeListener listener)
{
// Tests seem to indicate that this method also sets up the other two
// handlers.
if (accessibleContainerHandler == null)
{
accessibleContainerHandler = new AccessibleContainerHandler();
addContainerListener(accessibleContainerHandler);
}
if (accessibleFocusHandler == null)
{
accessibleFocusHandler = new AccessibleFocusHandler();
addFocusListener(accessibleFocusHandler);
}
super.addPropertyChangeListener(listener);
} | void function(PropertyChangeListener listener) { if (accessibleContainerHandler == null) { accessibleContainerHandler = new AccessibleContainerHandler(); addContainerListener(accessibleContainerHandler); } if (accessibleFocusHandler == null) { accessibleFocusHandler = new AccessibleFocusHandler(); addFocusListener(accessibleFocusHandler); } super.addPropertyChangeListener(listener); } | /**
* Adds a property change listener to the list of registered listeners.
*
* This sets up the {@link #accessibleContainerHandler} and
* {@link #accessibleFocusHandler} fields and calls
* <code>super.addPropertyChangeListener(listener)</code>.
*
* @param listener the listener to add
*/ | Adds a property change listener to the list of registered listeners. This sets up the <code>#accessibleContainerHandler</code> and <code>#accessibleFocusHandler</code> fields and calls <code>super.addPropertyChangeListener(listener)</code> | addPropertyChangeListener | {
"repo_name": "rhuitl/uClinux",
"path": "lib/classpath/javax/swing/JComponent.java",
"license": "gpl-2.0",
"size": 117352
} | [
"java.beans.PropertyChangeListener"
]
| import java.beans.PropertyChangeListener; | import java.beans.*; | [
"java.beans"
]
| java.beans; | 2,705,133 |
public void route(Route route) {
String streamID = route.getStreamID();
if (streamID == null) {
// No stream ID was included so return a bad_request error
Element extraError = DocumentHelper.createElement(QName.get(
"id-required", "http://jabber.org/protocol/connectionmanager#errors"));
sendErrorPacket(route, PacketError.Condition.bad_request, extraError);
}
LocalClientSession session = multiplexerManager.getClientSession(connectionManagerDomain, streamID);
if (session == null) {
// Specified Client Session does not exist
sendErrorPacket(route, PacketError.Condition.item_not_found, null);
return;
}
SessionPacketRouter router = new SessionPacketRouter(session);
// Connection Manager already validate JIDs so just skip this expensive operation
router.setSkipJIDValidation(true);
try {
router.route(route.getChildElement());
}
catch (UnknownStanzaException use) {
Element extraError = DocumentHelper.createElement(QName.get(
"unknown-stanza",
"http://jabber.org/protocol/connectionmanager#errors"));
sendErrorPacket(route, PacketError.Condition.bad_request, extraError);
}
catch (Exception e) {
Log.error("Error processing wrapped packet: " + route.getChildElement().asXML(), e);
sendErrorPacket(route, PacketError.Condition.internal_server_error, null);
}
} | void function(Route route) { String streamID = route.getStreamID(); if (streamID == null) { Element extraError = DocumentHelper.createElement(QName.get( STR, STRunknown-stanzaSTRhttp: sendErrorPacket(route, PacketError.Condition.bad_request, extraError); } catch (Exception e) { Log.error(STR + route.getChildElement().asXML(), e); sendErrorPacket(route, PacketError.Condition.internal_server_error, null); } } | /**
* Processes a route packet that is wrapping a stanza sent by a client that is connected
* to the connection manager.
*
* @param route the route packet.
*/ | Processes a route packet that is wrapping a stanza sent by a client that is connected to the connection manager | route | {
"repo_name": "wudingli/openfire",
"path": "src/java/org/jivesoftware/openfire/multiplex/MultiplexerPacketHandler.java",
"license": "apache-2.0",
"size": 11883
} | [
"org.dom4j.DocumentHelper",
"org.dom4j.Element",
"org.dom4j.QName",
"org.xmpp.packet.PacketError"
]
| import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.QName; import org.xmpp.packet.PacketError; | import org.dom4j.*; import org.xmpp.packet.*; | [
"org.dom4j",
"org.xmpp.packet"
]
| org.dom4j; org.xmpp.packet; | 2,394,074 |
@NonNull
public static ComplicationText plainText(@NonNull CharSequence text) {
return new ComplicationText(text, null);
}
public static final class TimeDifferenceBuilder {
private static final long NO_PERIOD_START = 0;
private static final long NO_PERIOD_END = Long.MAX_VALUE;
private long mReferencePeriodStartMillis = NO_PERIOD_START;
private long mReferencePeriodEndMillis = NO_PERIOD_END;
@TimeDifferenceStyle
private int mStyle = ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT;
private CharSequence mSurroundingText;
private Boolean mShowNowText;
private TimeUnit mMinimumUnit;
public TimeDifferenceBuilder() {
}
public TimeDifferenceBuilder(
long referencePeriodStartMillis,
long referencePeriodEndMillis
) {
mReferencePeriodStartMillis = referencePeriodStartMillis;
mReferencePeriodEndMillis = referencePeriodEndMillis;
} | static ComplicationText function(@NonNull CharSequence text) { return new ComplicationText(text, null); } public static final class TimeDifferenceBuilder { private static final long NO_PERIOD_START = 0; private static final long NO_PERIOD_END = Long.MAX_VALUE; private long mReferencePeriodStartMillis = NO_PERIOD_START; private long mReferencePeriodEndMillis = NO_PERIOD_END; private int mStyle = ComplicationText.DIFFERENCE_STYLE_SHORT_DUAL_UNIT; private CharSequence mSurroundingText; private Boolean mShowNowText; private TimeUnit mMinimumUnit; public TimeDifferenceBuilder() { } public TimeDifferenceBuilder( long referencePeriodStartMillis, long referencePeriodEndMillis ) { mReferencePeriodStartMillis = referencePeriodStartMillis; mReferencePeriodEndMillis = referencePeriodEndMillis; } | /**
* Returns a ComplicationText object that will display the given {@code text} for any input
* time.
*
* <p>If the text contains spans, some of them may not be rendered by
* {@link androidx.wear.watchface.complications.rendering.ComplicationDrawable}. Supported spans
* are {@link ForegroundColorSpan}, {@link LocaleSpan}, {@link SubscriptSpan}, {@link
* SuperscriptSpan}, {@link StyleSpan}, {@link StrikethroughSpan}, {@link TypefaceSpan} and
* {@link UnderlineSpan}.
*
* @param text the text to be displayed
*/ | Returns a ComplicationText object that will display the given text for any input time. If the text contains spans, some of them may not be rendered by <code>androidx.wear.watchface.complications.rendering.ComplicationDrawable</code>. Supported spans are <code>ForegroundColorSpan</code>, <code>LocaleSpan</code>, <code>SubscriptSpan</code>, <code>SuperscriptSpan</code>, <code>StyleSpan</code>, <code>StrikethroughSpan</code>, <code>TypefaceSpan</code> and <code>UnderlineSpan</code> | plainText | {
"repo_name": "AndroidX/androidx",
"path": "wear/watchface/watchface-complications-data/src/main/java/android/support/wearable/complications/ComplicationText.java",
"license": "apache-2.0",
"size": 33364
} | [
"androidx.annotation.NonNull",
"java.util.concurrent.TimeUnit"
]
| import androidx.annotation.NonNull; import java.util.concurrent.TimeUnit; | import androidx.annotation.*; import java.util.concurrent.*; | [
"androidx.annotation",
"java.util"
]
| androidx.annotation; java.util; | 1,700,279 |
@Test
public void whenNeedTransformCollectionToArrayThenDoIt() {
ReverseArray reverseArray = new ReverseArray();
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7);
int[][] array = reverseArray.toArray(list, 3);
int[][] arraySecond = {{1, 2, 3}, {4, 5, 6}, {7, 0, 0}};
boolean fact = true;
boolean expect = true;
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i][j] != arraySecond[i][j]) {
fact = false;
break;
}
}
}
assertThat(fact, is(expect));
} | void function() { ReverseArray reverseArray = new ReverseArray(); List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7); int[][] array = reverseArray.toArray(list, 3); int[][] arraySecond = {{1, 2, 3}, {4, 5, 6}, {7, 0, 0}}; boolean fact = true; boolean expect = true; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array.length; j++) { if (array[i][j] != arraySecond[i][j]) { fact = false; break; } } } assertThat(fact, is(expect)); } | /**.
* Test transform collection to array
*/ | . Test transform collection to array | whenNeedTransformCollectionToArrayThenDoIt | {
"repo_name": "AntonVasilyuk/Aduma",
"path": "chapter_003/reverseArray/src/test/java/ru/job4j/ReverseArrayTest.java",
"license": "apache-2.0",
"size": 2381
} | [
"java.util.List",
"org.hamcrest.Matchers",
"org.junit.Assert"
]
| import java.util.List; import org.hamcrest.Matchers; import org.junit.Assert; | import java.util.*; import org.hamcrest.*; import org.junit.*; | [
"java.util",
"org.hamcrest",
"org.junit"
]
| java.util; org.hamcrest; org.junit; | 181,673 |
public void delete(String path) {
List<AttachmentState> states = findAttachmentStates(String.format("^%s$", path), false);
states.addAll(findAttachmentStates(String.format("^%s/", path), false));
states.forEach(this::delete);
} | void function(String path) { List<AttachmentState> states = findAttachmentStates(String.format("^%s$", path), false); states.addAll(findAttachmentStates(String.format("^%s/", path), false)); states.forEach(this::delete); } | /**
* Delete all unpublished {@link AttachmentState}s corresponding to the given path.
*
* @param path
*/ | Delete all unpublished <code>AttachmentState</code>s corresponding to the given path | delete | {
"repo_name": "obiba/mica2",
"path": "mica-core/src/main/java/org/obiba/mica/file/service/FileSystemService.java",
"license": "gpl-3.0",
"size": 34162
} | [
"java.util.List",
"org.obiba.mica.file.AttachmentState"
]
| import java.util.List; import org.obiba.mica.file.AttachmentState; | import java.util.*; import org.obiba.mica.file.*; | [
"java.util",
"org.obiba.mica"
]
| java.util; org.obiba.mica; | 1,843,336 |
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
} | void function(Collection<Object> newChildDescriptors, Object object) { super.collectNewChildDescriptors(newChildDescriptors, object); } | /**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/ | This adds <code>org.eclipse.emf.edit.command.CommandParameter</code>s describing the children that can be created under this object. | collectNewChildDescriptors | {
"repo_name": "KAMP-Research/KAMP",
"path": "bundles/Toometa/de.uka.ipd.sdq.namedelement.edit/src/namedelement/provider/NamedElementItemProvider.java",
"license": "apache-2.0",
"size": 4569
} | [
"java.util.Collection"
]
| import java.util.Collection; | import java.util.*; | [
"java.util"
]
| java.util; | 2,002,321 |
public void close(boolean cleanupOnError) throws StandardException
{
if ( isOpen )
{
leftResultSet.close(cleanupOnError);
if (isRightOpen)
{
closeRight();
}
super.close(cleanupOnError);
}
else
if (SanityManager.DEBUG)
SanityManager.DEBUG("CloseRepeatInfo","Close of JoinResultSet repeated");
clearScanState();
} | void function(boolean cleanupOnError) throws StandardException { if ( isOpen ) { leftResultSet.close(cleanupOnError); if (isRightOpen) { closeRight(); } super.close(cleanupOnError); } else if (SanityManager.DEBUG) SanityManager.DEBUG(STR,STR); clearScanState(); } | /**
* If the result set has been opened,
* close the open scan.
* <n>
* <B>WARNING</B> does not track close
* time, since it is expected to be called
* directly by its subclasses, and we don't
* want to skew the times
*
* @exception StandardException thrown on error
*/ | If the result set has been opened, close the open scan. WARNING does not track close time, since it is expected to be called directly by its subclasses, and we don't want to skew the times | close | {
"repo_name": "papicella/snappy-store",
"path": "gemfirexd/core/src/main/java/com/pivotal/gemfirexd/internal/impl/sql/execute/JoinResultSet.java",
"license": "apache-2.0",
"size": 13600
} | [
"com.pivotal.gemfirexd.internal.iapi.error.StandardException",
"com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager"
]
| import com.pivotal.gemfirexd.internal.iapi.error.StandardException; import com.pivotal.gemfirexd.internal.iapi.services.sanity.SanityManager; | import com.pivotal.gemfirexd.internal.iapi.error.*; import com.pivotal.gemfirexd.internal.iapi.services.sanity.*; | [
"com.pivotal.gemfirexd"
]
| com.pivotal.gemfirexd; | 2,659,118 |
Iterator<Entry> iterator(); | Iterator<Entry> iterator(); | /**
* Generic dense iterator.
* It iterates in increasing order of the vector index.
*
* @return a dense iterator
*/ | Generic dense iterator. It iterates in increasing order of the vector index | iterator | {
"repo_name": "SpoonLabs/astor",
"path": "examples/math_50v2/src/main/java/org/apache/commons/math/linear/RealVector.java",
"license": "gpl-2.0",
"size": 21636
} | [
"java.util.Iterator"
]
| import java.util.Iterator; | import java.util.*; | [
"java.util"
]
| java.util; | 1,961,934 |
protected void text(Element elem) throws BadLocationException, IOException {
int start = Math.max(getStartOffset(), elem.getStartOffset());
int end = Math.min(getEndOffset(), elem.getEndOffset());
if (start < end) {
if (segment == null) {
segment = new Segment();
}
getDocument().getText(start, end - start, segment);
newlineOutputed = false;
if (segment.count > 0) {
if (segment.array[segment.offset + segment.count - 1] == '\n') {
newlineOutputed = true;
}
if (inPre && end == preEndOffset) {
if (segment.count > 1) {
segment.count--;
}
else {
return;
}
}
replaceEntities = true;
setCanWrapLines(!inPre);
write(segment.array, segment.offset, segment.count);
setCanWrapLines(false);
replaceEntities = false;
}
}
} | void function(Element elem) throws BadLocationException, IOException { int start = Math.max(getStartOffset(), elem.getStartOffset()); int end = Math.min(getEndOffset(), elem.getEndOffset()); if (start < end) { if (segment == null) { segment = new Segment(); } getDocument().getText(start, end - start, segment); newlineOutputed = false; if (segment.count > 0) { if (segment.array[segment.offset + segment.count - 1] == '\n') { newlineOutputed = true; } if (inPre && end == preEndOffset) { if (segment.count > 1) { segment.count--; } else { return; } } replaceEntities = true; setCanWrapLines(!inPre); write(segment.array, segment.offset, segment.count); setCanWrapLines(false); replaceEntities = false; } } } | /**
* Writes out text. If a range is specified when the constructor
* is invoked, then only the appropriate range of text is written
* out.
*
* @param elem an Element
* @exception IOException on any I/O error
* @exception BadLocationException if pos represents an invalid
* location within the document.
*/ | Writes out text. If a range is specified when the constructor is invoked, then only the appropriate range of text is written out | text | {
"repo_name": "jzalden/SER316-Karlsruhe",
"path": "src/net/sf/memoranda/ui/htmleditor/AltHTMLWriter.java",
"license": "gpl-2.0",
"size": 64897
} | [
"java.io.IOException",
"javax.swing.text.BadLocationException",
"javax.swing.text.Element",
"javax.swing.text.Segment"
]
| import java.io.IOException; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.Segment; | import java.io.*; import javax.swing.text.*; | [
"java.io",
"javax.swing"
]
| java.io; javax.swing; | 552,568 |
public static int checkExists(ZooKeeperWatcher zkw, String znode)
throws KeeperException {
try {
Stat s = zkw.getRecoverableZooKeeper().exists(znode, null);
return s != null ? s.getVersion() : -1;
} catch (KeeperException e) {
LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
zkw.keeperException(e);
return -1;
} catch (InterruptedException e) {
LOG.warn(zkw.prefix("Unable to set watcher on znode (" + znode + ")"), e);
zkw.interruptedException(e);
return -1;
}
}
//
// Znode listings
// | static int function(ZooKeeperWatcher zkw, String znode) throws KeeperException { try { Stat s = zkw.getRecoverableZooKeeper().exists(znode, null); return s != null ? s.getVersion() : -1; } catch (KeeperException e) { LOG.warn(zkw.prefix(STR + znode + ")"), e); zkw.keeperException(e); return -1; } catch (InterruptedException e) { LOG.warn(zkw.prefix(STR + znode + ")"), e); zkw.interruptedException(e); return -1; } } // | /**
* Check if the specified node exists. Sets no watches.
*
* Returns true if node exists, false if not. Returns an exception if there
* is an unexpected zookeeper exception.
*
* @param zkw zk reference
* @param znode path of node to watch
* @return version of the node if it exists, -1 if does not exist
* @throws KeeperException if unexpected zookeeper exception
*/ | Check if the specified node exists. Sets no watches. Returns true if node exists, false if not. Returns an exception if there is an unexpected zookeeper exception | checkExists | {
"repo_name": "ay65535/hbase-0.94.0",
"path": "src/main/java/org/apache/hadoop/hbase/zookeeper/ZKUtil.java",
"license": "apache-2.0",
"size": 41402
} | [
"org.apache.zookeeper.KeeperException",
"org.apache.zookeeper.data.Stat"
]
| import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.data.Stat; | import org.apache.zookeeper.*; import org.apache.zookeeper.data.*; | [
"org.apache.zookeeper"
]
| org.apache.zookeeper; | 498,972 |
@Nonnull
public final SubstringBounds getLabelBounds(int index) {
return this.labels[index];
} | final SubstringBounds function(int index) { return this.labels[index]; } | /**
* Gets the bounds of a label on this logical line.
*
* @param index
* the index of the label
* @return the bounds of the label
*/ | Gets the bounds of a label on this logical line | getLabelBounds | {
"repo_name": "reasm/reasm-commons",
"path": "src/main/java/org/reasm/commons/source/LogicalLine.java",
"license": "mit",
"size": 4975
} | [
"org.reasm.SubstringBounds"
]
| import org.reasm.SubstringBounds; | import org.reasm.*; | [
"org.reasm"
]
| org.reasm; | 1,186,240 |
public SteeringComponents avoidObstacles(Iterable<Obstacle> obstacles, float detectionPeriod, float elapsedTime)
{
Obstacle nearestObstacle = potentialCollisionDetector
.findNearestPotentialCollision(vehicle, obstacles, detectionPeriod);
if (nearestObstacle != null)
{
// Find the steering direction
Vector2 obstacleOffset = vehicle.getPosition().cpy().sub(nearestObstacle.getPosition());
Vector2 parallel = vehicle.getDirection().cpy().scl(obstacleOffset.dot(vehicle.getDirection()));
Vector2 perpendicular = obstacleOffset.sub(parallel);
// Offset to be past the obstacle's edge
perpendicular.nor();
Vector2 seekTo = nearestObstacle.getPosition().cpy().add(perpendicular.scl(nearestObstacle.getRadius() + (vehicle.getRadius() * avoidanceFactor)));
return getComponents("Avoid obstacle", seekTo, elapsedTime);
}
return SteeringComponents.NO_STEERING;
}
// /// <summary>
// /// Steers to stay aligned and cohesive to the flock.
// /// </summary>
// /// <param name="flock">The flock of vehicles to stay with.</param>
// /// <param name="elapsedTime">The elapsed time.</param>
// /// <returns>The steering force.</returns>
// public SteeringComponents flock(Iterable<Vehicle> flock, float elapsedTime)
// {
// var closeBoids = FindCloseBoids(flock);
//
// if (!closeBoids.Any())
// {
// // Found no other boids!
// return SteeringComponents.NoSteering;
// }
//
// if (closeBoids.First().DistanceSquared < MinimumBoidDistance)
// {
// // Steer to separate
// return SeparationImpl(closeBoids, elapsedTime);
// }
// else if (closeBoids.First().DistanceSquared > BoidCohesionDistance)
// {
// // Steer for cohension
// return CohesionImpl(closeBoids, elapsedTime);
// }
// else
// {
// // Steer for alignment
// return AlignmentImpl(closeBoids, elapsedTime);
// }
// }
//
// /// <summary>
// /// Steers to separate from neighbours.
// /// </summary>
// /// <param name="neighbours">The vehicles to separate from.</param>
// /// <param name="elapsedTime">The elapsed time.</param>
// /// <returns>The steering force.</returns>
// public SteeringComponents separate(Iterable<Vehicle> neighbours, float elapsedTime)
// {
// var closeBoids = FindCloseBoids(neighbours);
//
// if (closeBoids.Any() && closeBoids.First().DistanceSquared < MinimumBoidDistance)
// {
// // Steer to separate
// return SeparationImpl(closeBoids, elapsedTime);
// }
//
// return SteeringComponents.NO_STEERING;
// }
//
// /// <summary>
// /// Separates from nearby neighbours.
// /// </summary>
// /// <param name="closeBoids">The close boids.</param>
// /// <param name="elapsedTime">The elapsed time.</param>
// /// <returns>The steering force.</returns>
// protected SteeringComponents separationImpl(Iterable<BoidDistance> closeBoids, float elapsedTime)
// {
// Vector2 direction = closeBoids.Aggregate(Vector2.Zero, (p, b) => p + b.Boid.Position);
// direction /= closeBoids.Count();
// direction.Normalize();
//
// return getComponents("Flocking: separation", direction, elapsedTime);
// }
//
// /// <summary>
// /// Steers for cohesion.
// /// </summary>
// /// <param name="closeBoids">The close boids.</param>
// /// <param name="elapsedTime">The elapsed time.</param>
// /// <returns>The steering force.</returns>
// protected SteeringComponents cohesionImpl(Iterable<BoidDistance> closeBoids, float elapsedTime)
// {
// Vector2 direction = closeBoids.Aggregate(Vector2.Zero, (p, b) => p + b.Boid.Position);
//
// direction /= closeBoids.Count();
// direction -= vehicle.Position;
// direction.Normalize();
//
// return getComponents("Flocking: cohesion", direction, elapsedTime);
// }
//
// /// <summary>
// /// Steers for alignment.
// /// </summary>
// /// <param name="closeBoids">The close boids.</param>
// /// <param name="elapsedTime">The elapsed time.</param>
// /// <returns>The steering force.</returns>
// protected SteeringComponents alignmentImpl(Iterable<BoidDistance> closeBoids, float elapsedTime)
// {
// Vector2 direction = closeBoids.Aggregate(Vector2.Zero, (p, b) => p + b.Boid.Direction);
//
// direction /= closeBoids.Count();
// direction -= vehicle.Direction;
// direction.Normalize();
//
// return getComponents("Flocking: alignment", direction, elapsedTime);
// }
//
// /// <summary>
// /// Finds close boids for flocking. Any boids further than "MaximumBoidDistance" will be filtered.
// /// </summary>
// /// <param name="flock">The flock to find close boids in.</param>
// /// <returns>The close boids ordered by closest boid first.</returns>
// public IEnumerable<BoidDistance> findCloseBoids(IEnumerable<IVehicle> flock)
// {
// // Filter out any boids that are too distance
// var maxBoidDistanceSquared = MaximumBoidDistance * MaximumBoidDistance;
//
// var closeBoids = flock
// .Where(b => !vehicle.Equals(b))
// .Select(b => new BoidDistance
// {
// Boid = b,
// DistanceSquared = (b.Position - vehicle.Position).LengthSquared()
// });
//
// closeBoids = closeBoids
// .OrderBy(bd => bd.DistanceSquared);
//
// closeBoids = closeBoids
// .Where(bd => bd.DistanceSquared < MaximumBoidDistance);
//
// closeBoids = closeBoids
// .Take(5);
//
// return closeBoids;
// } | SteeringComponents function(Iterable<Obstacle> obstacles, float detectionPeriod, float elapsedTime) { Obstacle nearestObstacle = potentialCollisionDetector .findNearestPotentialCollision(vehicle, obstacles, detectionPeriod); if (nearestObstacle != null) { Vector2 obstacleOffset = vehicle.getPosition().cpy().sub(nearestObstacle.getPosition()); Vector2 parallel = vehicle.getDirection().cpy().scl(obstacleOffset.dot(vehicle.getDirection())); Vector2 perpendicular = obstacleOffset.sub(parallel); perpendicular.nor(); Vector2 seekTo = nearestObstacle.getPosition().cpy().add(perpendicular.scl(nearestObstacle.getRadius() + (vehicle.getRadius() * avoidanceFactor))); return getComponents(STR, seekTo, elapsedTime); } return SteeringComponents.NO_STEERING; } | /**
* Steers to avoid the given obstacles.
*
* @param obstacles the obstacles to avoid.
* @param detectionPeriod The time window to perform detection in (in milliseconds). E.g. 500ms from current position.
* @param elapsedTime the elapsed time.
* @return the steering components.
*/ | Steers to avoid the given obstacles | avoidObstacles | {
"repo_name": "tmyroadctfig/jsteer2d",
"path": "src/main/java/com/github/tmyroadctfig/jsteer2d/Steering.java",
"license": "mit",
"size": 13482
} | [
"com.badlogic.gdx.math.Vector2"
]
| import com.badlogic.gdx.math.Vector2; | import com.badlogic.gdx.math.*; | [
"com.badlogic.gdx"
]
| com.badlogic.gdx; | 1,100,123 |
protected List<Option> getItemOptions( Grid grid )
{
List<Option> options = new ArrayList<>();
for ( int i = 0; i < grid.getHeaders().size(); ++i )
{
GridHeader gridHeader = grid.getHeaders().get( i );
if ( gridHeader.hasOptionSet() )
{
final int columnIndex = i;
options.addAll( gridHeader
.getOptionSetObject()
.getOptions()
.stream()
.filter( opt -> opt != null && grid.getRows().stream().anyMatch( r -> {
Object o = r.get( columnIndex );
if ( o instanceof String )
{
return ((String) o).equalsIgnoreCase( opt.getCode() );
}
return false;
} ) ).collect( Collectors.toList() ) );
}
}
return options.stream().distinct().collect( Collectors.toList() );
} | List<Option> function( Grid grid ) { List<Option> options = new ArrayList<>(); for ( int i = 0; i < grid.getHeaders().size(); ++i ) { GridHeader gridHeader = grid.getHeaders().get( i ); if ( gridHeader.hasOptionSet() ) { final int columnIndex = i; options.addAll( gridHeader .getOptionSetObject() .getOptions() .stream() .filter( opt -> opt != null && grid.getRows().stream().anyMatch( r -> { Object o = r.get( columnIndex ); if ( o instanceof String ) { return ((String) o).equalsIgnoreCase( opt.getCode() ); } return false; } ) ).collect( Collectors.toList() ) ); } } return options.stream().distinct().collect( Collectors.toList() ); } | /**
* Returns a map of metadata item options and {@link Option}.
*
* @param grid the Grid instance.
* @return a list of options.
*/ | Returns a map of metadata item options and <code>Option</code> | getItemOptions | {
"repo_name": "dhis2/dhis2-core",
"path": "dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/event/data/AbstractAnalyticsService.java",
"license": "bsd-3-clause",
"size": 21883
} | [
"java.util.ArrayList",
"java.util.List",
"java.util.stream.Collectors",
"org.hisp.dhis.common.Grid",
"org.hisp.dhis.common.GridHeader",
"org.hisp.dhis.option.Option"
]
| import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.hisp.dhis.common.Grid; import org.hisp.dhis.common.GridHeader; import org.hisp.dhis.option.Option; | import java.util.*; import java.util.stream.*; import org.hisp.dhis.common.*; import org.hisp.dhis.option.*; | [
"java.util",
"org.hisp.dhis"
]
| java.util; org.hisp.dhis; | 1,265,249 |
@Deprecated
List<ConnectorDefinition> getConnectorsList() throws PulsarAdminException; | List<ConnectorDefinition> getConnectorsList() throws PulsarAdminException; | /**
* Deprecated in favor of getting sources and sinks for their own APIs
*
* Fetches a list of supported Pulsar IO connectors currently running in cluster mode
*
* @throws PulsarAdminException
* Unexpected error
*
*/ | Deprecated in favor of getting sources and sinks for their own APIs Fetches a list of supported Pulsar IO connectors currently running in cluster mode | getConnectorsList | {
"repo_name": "merlimat/pulsar",
"path": "pulsar-client-admin/src/main/java/org/apache/pulsar/client/admin/Functions.java",
"license": "apache-2.0",
"size": 16585
} | [
"java.util.List",
"org.apache.pulsar.common.io.ConnectorDefinition"
]
| import java.util.List; import org.apache.pulsar.common.io.ConnectorDefinition; | import java.util.*; import org.apache.pulsar.common.io.*; | [
"java.util",
"org.apache.pulsar"
]
| java.util; org.apache.pulsar; | 2,257,189 |
public void setSamplingLocationCollection(Set<gov.nih.nci.calims2.domain.administration.Location> samplingLocationCollection) {
this.samplingLocationCollection = samplingLocationCollection;
}
private gov.nih.nci.calims2.domain.inventory.Specimen parentSpecimen;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SPECIMEN_FK")
@org.hibernate.annotations.ForeignKey(name = "CHILDSSPECIM_FK") | void function(Set<gov.nih.nci.calims2.domain.administration.Location> samplingLocationCollection) { this.samplingLocationCollection = samplingLocationCollection; } private gov.nih.nci.calims2.domain.inventory.Specimen parentSpecimen; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = STR) @org.hibernate.annotations.ForeignKey(name = STR) | /**
* Sets the value of samplingLocationCollection attribute.
* @param samplingLocationCollection .
**/ | Sets the value of samplingLocationCollection attribute | setSamplingLocationCollection | {
"repo_name": "NCIP/calims",
"path": "calims2-model/src/java/gov/nih/nci/calims2/domain/inventory/Specimen.java",
"license": "bsd-3-clause",
"size": 13463
} | [
"java.util.Set",
"javax.persistence.FetchType",
"javax.persistence.JoinColumn",
"javax.persistence.ManyToOne",
"org.hibernate.annotations.ForeignKey"
]
| import java.util.Set; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import org.hibernate.annotations.ForeignKey; | import java.util.*; import javax.persistence.*; import org.hibernate.annotations.*; | [
"java.util",
"javax.persistence",
"org.hibernate.annotations"
]
| java.util; javax.persistence; org.hibernate.annotations; | 1,366,309 |
public java.util.List<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI> getInput_cyclicEnumerations_CyclicEnumerationHLAPI(){
java.util.List<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI> retour = new ArrayList<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI>();
for (Sort elemnt : getInput()) {
if(elemnt.getClass().equals(fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.impl.CyclicEnumerationImpl.class)){
retour.add(new fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI(
(fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.CyclicEnumeration)elemnt
));
}
}
return retour;
}
| java.util.List<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI> function(){ java.util.List<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI> retour = new ArrayList<fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI>(); for (Sort elemnt : getInput()) { if(elemnt.getClass().equals(fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.impl.CyclicEnumerationImpl.class)){ retour.add(new fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.hlapi.CyclicEnumerationHLAPI( (fr.lip6.move.pnml.symmetricnet.cyclicEnumerations.CyclicEnumeration)elemnt )); } } return retour; } | /**
* This accessor return a list of encapsulated subelement, only of CyclicEnumerationHLAPI kind.
* WARNING : this method can creates a lot of new object in memory.
*/ | This accessor return a list of encapsulated subelement, only of CyclicEnumerationHLAPI kind. WARNING : this method can creates a lot of new object in memory | getInput_cyclicEnumerations_CyclicEnumerationHLAPI | {
"repo_name": "lhillah/pnmlframework",
"path": "pnmlFw-SNNet/src/fr/lip6/move/pnml/symmetricnet/integers/hlapi/NumberConstantHLAPI.java",
"license": "epl-1.0",
"size": 94704
} | [
"fr.lip6.move.pnml.symmetricnet.terms.Sort",
"java.util.ArrayList",
"java.util.List"
]
| import fr.lip6.move.pnml.symmetricnet.terms.Sort; import java.util.ArrayList; import java.util.List; | import fr.lip6.move.pnml.symmetricnet.terms.*; import java.util.*; | [
"fr.lip6.move",
"java.util"
]
| fr.lip6.move; java.util; | 1,041,959 |
private void serializeMessages(ObjectOutputStream out)
throws IOException {
// Step 1.
final int len = messages.size();
out.writeInt(len);
// Step 2.
for (int i = 0; i < len; i++) {
SerializablePair<Localizable, Object[]> pair = messages.get(i);
// Step 3.
out.writeObject(pair.getKey());
final Object[] args = pair.getValue();
final int aLen = args.length;
// Step 4.
out.writeInt(aLen);
for (int j = 0; j < aLen; j++) {
if (args[j] instanceof Serializable) {
// Step 5a.
out.writeObject(args[j]);
} else {
// Step 5b.
out.writeObject(nonSerializableReplacement(args[j]));
}
}
}
} | void function(ObjectOutputStream out) throws IOException { final int len = messages.size(); out.writeInt(len); for (int i = 0; i < len; i++) { SerializablePair<Localizable, Object[]> pair = messages.get(i); out.writeObject(pair.getKey()); final Object[] args = pair.getValue(); final int aLen = args.length; out.writeInt(aLen); for (int j = 0; j < aLen; j++) { if (args[j] instanceof Serializable) { out.writeObject(args[j]); } else { out.writeObject(nonSerializableReplacement(args[j])); } } } } | /**
* Serialize {@link #messages}.
*
* @param out Stream.
* @throws IOException This should never happen.
*/ | Serialize <code>#messages</code> | serializeMessages | {
"repo_name": "martingwhite/astor",
"path": "examples/math_57/src/main/java/org/apache/commons/math/exception/MathRuntimeException.java",
"license": "gpl-2.0",
"size": 9437
} | [
"java.io.IOException",
"java.io.ObjectOutputStream",
"java.io.Serializable",
"org.apache.commons.math.exception.util.Localizable",
"org.apache.commons.math.util.SerializablePair"
]
| import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import org.apache.commons.math.exception.util.Localizable; import org.apache.commons.math.util.SerializablePair; | import java.io.*; import org.apache.commons.math.exception.util.*; import org.apache.commons.math.util.*; | [
"java.io",
"org.apache.commons"
]
| java.io; org.apache.commons; | 200,444 |
@Test
@Category(NeedsRunner.class)
public void testSpecializedButIgnoredGenericInPipeline() throws Exception {
Pipeline pipeline = TestPipeline.create();
pipeline
.apply(Create.of("hello", "goodbye"))
.apply(new PTransformOutputingMySerializableGeneric());
pipeline.run();
}
private static class GenericOutputMySerializedGeneric<T extends Serializable>
extends PTransform<
PCollection<String>,
PCollection<KV<String, MySerializableGeneric<T>>>> {
private class OutputDoFn extends DoFn<String, KV<String, MySerializableGeneric<T>>> {
@ProcessElement
public void processElement(ProcessContext c) { } | @Category(NeedsRunner.class) void function() throws Exception { Pipeline pipeline = TestPipeline.create(); pipeline .apply(Create.of("hello", STR)) .apply(new PTransformOutputingMySerializableGeneric()); pipeline.run(); } private static class GenericOutputMySerializedGeneric<T extends Serializable> extends PTransform< PCollection<String>, PCollection<KV<String, MySerializableGeneric<T>>>> { private class OutputDoFn extends DoFn<String, KV<String, MySerializableGeneric<T>>> { public void processElement(ProcessContext c) { } | /**
* In-context test that assures the functionality tested in
* {@link #testDefaultCoderAnnotationGeneric} is invoked in the right ways.
*/ | In-context test that assures the functionality tested in <code>#testDefaultCoderAnnotationGeneric</code> is invoked in the right ways | testSpecializedButIgnoredGenericInPipeline | {
"repo_name": "yafengguo/Apache-beam",
"path": "sdks/java/core/src/test/java/org/apache/beam/sdk/coders/CoderRegistryTest.java",
"license": "apache-2.0",
"size": 18687
} | [
"java.io.Serializable",
"org.apache.beam.sdk.Pipeline",
"org.apache.beam.sdk.testing.NeedsRunner",
"org.apache.beam.sdk.testing.TestPipeline",
"org.apache.beam.sdk.transforms.Create",
"org.apache.beam.sdk.transforms.DoFn",
"org.apache.beam.sdk.transforms.PTransform",
"org.apache.beam.sdk.values.PCollection",
"org.junit.experimental.categories.Category"
]
| import java.io.Serializable; import org.apache.beam.sdk.Pipeline; import org.apache.beam.sdk.testing.NeedsRunner; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.transforms.Create; import org.apache.beam.sdk.transforms.DoFn; import org.apache.beam.sdk.transforms.PTransform; import org.apache.beam.sdk.values.PCollection; import org.junit.experimental.categories.Category; | import java.io.*; import org.apache.beam.sdk.*; import org.apache.beam.sdk.testing.*; import org.apache.beam.sdk.transforms.*; import org.apache.beam.sdk.values.*; import org.junit.experimental.categories.*; | [
"java.io",
"org.apache.beam",
"org.junit.experimental"
]
| java.io; org.apache.beam; org.junit.experimental; | 2,509,314 |
boolean isOptAttribute(PerunSession sess, AttributeDefinition attribute); | boolean isOptAttribute(PerunSession sess, AttributeDefinition attribute); | /**
* Determine if attribute is optional (opt) attribute.
*
* @param sess
* @param attribute
* @return true if attribute is optional attribute
* false otherwise
*/ | Determine if attribute is optional (opt) attribute | isOptAttribute | {
"repo_name": "Simcsa/perun",
"path": "perun-core/src/main/java/cz/metacentrum/perun/core/implApi/AttributesManagerImplApi.java",
"license": "bsd-2-clause",
"size": 98325
} | [
"cz.metacentrum.perun.core.api.AttributeDefinition",
"cz.metacentrum.perun.core.api.PerunSession"
]
| import cz.metacentrum.perun.core.api.AttributeDefinition; import cz.metacentrum.perun.core.api.PerunSession; | import cz.metacentrum.perun.core.api.*; | [
"cz.metacentrum.perun"
]
| cz.metacentrum.perun; | 2,424,716 |
timerTime = ms;
time = Task.time() + ms;
active = true;
}
| timerTime = ms; time = Task.time() + ms; active = true; } | /**
* Set the time to measure.
* @param ms the time in milliseconds
*/ | Set the time to measure | set | {
"repo_name": "deepjava/runtime-library",
"path": "src/org/deepjava/runtime/mpc555/Timer.java",
"license": "apache-2.0",
"size": 1721
} | [
"org.deepjava.runtime.ppc32.Task"
]
| import org.deepjava.runtime.ppc32.Task; | import org.deepjava.runtime.ppc32.*; | [
"org.deepjava.runtime"
]
| org.deepjava.runtime; | 1,250,810 |
public Location getLastLocation() {
return LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
} | Location function() { return LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient); } | /**
* Get last known location
*
* @return Location
*/ | Get last known location | getLastLocation | {
"repo_name": "0359xiaodong/DebugDrawer",
"path": "debugdrawer-location/src/main/java/io/palaima/debugdrawer/location/LocationController.java",
"license": "apache-2.0",
"size": 3532
} | [
"android.location.Location",
"com.google.android.gms.location.LocationServices"
]
| import android.location.Location; import com.google.android.gms.location.LocationServices; | import android.location.*; import com.google.android.gms.location.*; | [
"android.location",
"com.google.android"
]
| android.location; com.google.android; | 131,916 |
public Date getFechaEvento() {
return fechaEvento;
} | Date function() { return fechaEvento; } | /**
* Atributo fechaEvento
*
* @return el valor del atributo fechaEvento
*/ | Atributo fechaEvento | getFechaEvento | {
"repo_name": "REDDSOFT/saap",
"path": "fuentes/saap.root/saap-jpa/src/org/ec/jap/entiti/saap/Actividad.java",
"license": "apache-2.0",
"size": 7121
} | [
"java.util.Date"
]
| import java.util.Date; | import java.util.*; | [
"java.util"
]
| java.util; | 1,664,114 |
public void registerSqlTypeToClassMappings(Map<Integer, Class<?>> mappings) {
mappings.put(Integer.valueOf(Types.VARCHAR), String.class);
mappings.put(Integer.valueOf(Types.CHAR), String.class);
mappings.put(Integer.valueOf(Types.LONGVARCHAR), String.class);
mappings.put(Integer.valueOf(Types.NVARCHAR), String.class);
mappings.put(Integer.valueOf(Types.NCHAR), String.class);
mappings.put(Integer.valueOf(Types.BIT), Boolean.class);
mappings.put(Integer.valueOf(Types.BOOLEAN), Boolean.class);
mappings.put(Integer.valueOf(Types.TINYINT), Short.class);
mappings.put(Integer.valueOf(Types.SMALLINT), Short.class);
mappings.put(Integer.valueOf(Types.INTEGER), Integer.class);
mappings.put(Integer.valueOf(Types.BIGINT), Long.class);
mappings.put(Integer.valueOf(Types.REAL), Float.class);
mappings.put(Integer.valueOf(Types.FLOAT), Double.class);
mappings.put(Integer.valueOf(Types.DOUBLE), Double.class);
mappings.put(Integer.valueOf(Types.DECIMAL), BigDecimal.class);
mappings.put(Integer.valueOf(Types.NUMERIC), BigDecimal.class);
mappings.put(Integer.valueOf(Types.DATE), Date.class);
mappings.put(Integer.valueOf(Types.TIME), Time.class);
mappings.put(Integer.valueOf(Types.TIMESTAMP), Timestamp.class);
mappings.put(Integer.valueOf(Types.BLOB), byte[].class);
mappings.put(Integer.valueOf(Types.BINARY), byte[].class);
mappings.put(Integer.valueOf(Types.CLOB), String.class);
mappings.put(Integer.valueOf(Types.VARBINARY), byte[].class);
// subclasses should extend to provide additional
} | void function(Map<Integer, Class<?>> mappings) { mappings.put(Integer.valueOf(Types.VARCHAR), String.class); mappings.put(Integer.valueOf(Types.CHAR), String.class); mappings.put(Integer.valueOf(Types.LONGVARCHAR), String.class); mappings.put(Integer.valueOf(Types.NVARCHAR), String.class); mappings.put(Integer.valueOf(Types.NCHAR), String.class); mappings.put(Integer.valueOf(Types.BIT), Boolean.class); mappings.put(Integer.valueOf(Types.BOOLEAN), Boolean.class); mappings.put(Integer.valueOf(Types.TINYINT), Short.class); mappings.put(Integer.valueOf(Types.SMALLINT), Short.class); mappings.put(Integer.valueOf(Types.INTEGER), Integer.class); mappings.put(Integer.valueOf(Types.BIGINT), Long.class); mappings.put(Integer.valueOf(Types.REAL), Float.class); mappings.put(Integer.valueOf(Types.FLOAT), Double.class); mappings.put(Integer.valueOf(Types.DOUBLE), Double.class); mappings.put(Integer.valueOf(Types.DECIMAL), BigDecimal.class); mappings.put(Integer.valueOf(Types.NUMERIC), BigDecimal.class); mappings.put(Integer.valueOf(Types.DATE), Date.class); mappings.put(Integer.valueOf(Types.TIME), Time.class); mappings.put(Integer.valueOf(Types.TIMESTAMP), Timestamp.class); mappings.put(Integer.valueOf(Types.BLOB), byte[].class); mappings.put(Integer.valueOf(Types.BINARY), byte[].class); mappings.put(Integer.valueOf(Types.CLOB), String.class); mappings.put(Integer.valueOf(Types.VARBINARY), byte[].class); } | /**
* Registers the sql type to java type mappings that the dialect uses when reading and writing
* objects to and from the database.
*
* <p>Subclasses should extend (not override) this method to provide additional mappings, or to
* override mappings provided by this implementation. This implementation provides the following
* mappings:
*/ | Registers the sql type to java type mappings that the dialect uses when reading and writing objects to and from the database. Subclasses should extend (not override) this method to provide additional mappings, or to override mappings provided by this implementation. This implementation provides the following mappings: | registerSqlTypeToClassMappings | {
"repo_name": "geotools/geotools",
"path": "modules/library/jdbc/src/main/java/org/geotools/jdbc/SQLDialect.java",
"license": "lgpl-2.1",
"size": 55267
} | [
"java.math.BigDecimal",
"java.sql.Date",
"java.sql.Time",
"java.sql.Timestamp",
"java.sql.Types",
"java.util.Map"
]
| import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Map; | import java.math.*; import java.sql.*; import java.util.*; | [
"java.math",
"java.sql",
"java.util"
]
| java.math; java.sql; java.util; | 236,874 |
response.setContentType("application/json; charset=utf-8");
boolean allParameters = false;
String param = request.getParameter("param");
String url = request.getRequestURI();
String fileName = ManagementInterfaceUtils.getFileName(url);
if (param == null) {
allParameters = true;
} else if (param.equals("")) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().println("{\"success\":\"false\","
+ "\"error\":\"Parse error, empty parameter (param_name). Check it for errors.\"}");
LOGGER.error("Parse error, empty parameter (param_name). Check it for errors.");
return;
} // if else
String pathToFile;
if (v1) {
pathToFile = url.substring(32);
} else {
pathToFile = url.substring(29);
} // if else
if (!(pathToFile.endsWith("/usr/cygnus/conf/" + fileName))) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().println("{\"success\":\"false\","
+ "\"result\":\"Invalid path for a instance configuration file\"}");
return;
} // if
File file = new File(pathToFile);
try {
FileInputStream fileInputStream = new FileInputStream(file);
Properties properties = new Properties();
properties.load(fileInputStream);
JSONObject jsonObject = new JSONObject();
if (allParameters) {
jsonObject.put("instance", properties);
} else {
String property = properties.getProperty(param);
if (property != null) {
jsonObject.put(param, properties.getProperty(param));
} else {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
response.getWriter().println("{\"success\":\"false\","
+ "\"result\":\"Param '" + param + "' not found in the instance\"}");
return;
} // if else
} // if else
response.getWriter().println("{\"success\":\"true\",\"result\":\"" + jsonObject + "\"}");
LOGGER.debug(jsonObject);
response.setStatus(HttpServletResponse.SC_OK);
} catch (Exception e) {
response.getWriter().println("{\"success\":\"false\",\"result\":\"File not found in the path received\"}");
LOGGER.debug("File not found in the path received. Details: " + e.getMessage());
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
} // if else
} // get | response.setContentType(STR); boolean allParameters = false; String param = request.getParameter("param"); String url = request.getRequestURI(); String fileName = ManagementInterfaceUtils.getFileName(url); if (param == null) { allParameters = true; } else if (param.equals(STR{\STR:\STR,STR\STR:\STR}STRParse error, empty parameter (param_name). Check it for errors.STR/usr/cygnus/conf/STR{\STR:\STR,STR\STR:\STR}STRinstanceSTR{\STR:\STR,STR\STR:\STR + param + STR}STR{\STR:\"true\",\STR:\STR\"}"); LOGGER.debug(jsonObject); response.setStatus(HttpServletResponse.SC_OK); } catch (Exception e) { response.getWriter().println("{\STR:\STR,\STR:\"File not found in the path received\"}"); LOGGER.debug(STR + e.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } | /**
* Handles GET /admin/configuration/instance.
* @param request
* @param response
* @param v1
* @throws IOException
*/ | Handles GET /admin/configuration/instance | get | {
"repo_name": "telefonicaid/fiware-cygnus",
"path": "cygnus-common/src/main/java/com/telefonica/iot/cygnus/management/ConfigurationInstanceHandlers.java",
"license": "agpl-3.0",
"size": 15226
} | [
"java.io.File",
"javax.servlet.http.HttpServletResponse"
]
| import java.io.File; import javax.servlet.http.HttpServletResponse; | import java.io.*; import javax.servlet.http.*; | [
"java.io",
"javax.servlet"
]
| java.io; javax.servlet; | 1,670,785 |
public void modifyAclEntries(Path path, List<AclEntry> aclSpec)
throws IOException {
throw new UnsupportedOperationException(getClass().getSimpleName()
+ " doesn't support modifyAclEntries");
} | void function(Path path, List<AclEntry> aclSpec) throws IOException { throw new UnsupportedOperationException(getClass().getSimpleName() + STR); } | /**
* Modifies ACL entries of files and directories. This method can add new ACL
* entries or modify the permissions on existing ACL entries. All existing
* ACL entries that are not specified in this call are retained without
* changes. (Modifications are merged into the current ACL.)
*
* @param path Path to modify
* @param aclSpec List<AclEntry> describing modifications
* @throws IOException if an ACL could not be modified
*/ | Modifies ACL entries of files and directories. This method can add new ACL entries or modify the permissions on existing ACL entries. All existing ACL entries that are not specified in this call are retained without changes. (Modifications are merged into the current ACL.) | modifyAclEntries | {
"repo_name": "songweijia/fffs",
"path": "sources/hadoop-2.4.1-src/hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/fs/FileSystem.java",
"license": "apache-2.0",
"size": 102912
} | [
"java.io.IOException",
"java.util.List",
"org.apache.hadoop.fs.permission.AclEntry"
]
| import java.io.IOException; import java.util.List; import org.apache.hadoop.fs.permission.AclEntry; | import java.io.*; import java.util.*; import org.apache.hadoop.fs.permission.*; | [
"java.io",
"java.util",
"org.apache.hadoop"
]
| java.io; java.util; org.apache.hadoop; | 1,514,753 |
@SuppressWarnings("deprecation")
public boolean equalsIgnoreBase(IdDt theId) {
if (theId == null) {
return false;
}
if (theId.isEmpty()) {
return isEmpty();
}
return ObjectUtils.equals(getResourceType(), theId.getResourceType()) && ObjectUtils.equals(getIdPart(), theId.getIdPart()) && ObjectUtils.equals(getVersionIdPart(), theId.getVersionIdPart());
} | @SuppressWarnings(STR) boolean function(IdDt theId) { if (theId == null) { return false; } if (theId.isEmpty()) { return isEmpty(); } return ObjectUtils.equals(getResourceType(), theId.getResourceType()) && ObjectUtils.equals(getIdPart(), theId.getIdPart()) && ObjectUtils.equals(getVersionIdPart(), theId.getVersionIdPart()); } | /**
* Returns true if this IdDt matches the given IdDt in terms of resource type and ID, but ignores the URL base
*/ | Returns true if this IdDt matches the given IdDt in terms of resource type and ID, but ignores the URL base | equalsIgnoreBase | {
"repo_name": "SingingTree/hapi-fhir",
"path": "hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java",
"license": "apache-2.0",
"size": 20336
} | [
"org.apache.commons.lang3.ObjectUtils"
]
| import org.apache.commons.lang3.ObjectUtils; | import org.apache.commons.lang3.*; | [
"org.apache.commons"
]
| org.apache.commons; | 2,208,569 |
@Override
public Runnable poll(long timeout, TimeUnit unit)
throws InterruptedException {
logger.debug("In poll(t,u) timeout={} units={}", timeout, unit);
Runnable runnable;
do {
runnable = super.poll(timeout, unit);
} while (runnable != null && isObsolete(runnable));
if (runnable != null) {
logger.debug("poll(t,u) in AvlQueue returned {}",
((AvlClient) runnable).getAvlReport());
}
return runnable;
}
| Runnable function(long timeout, TimeUnit unit) throws InterruptedException { logger.debug(STR, timeout, unit); Runnable runnable; do { runnable = super.poll(timeout, unit); } while (runnable != null && isObsolete(runnable)); if (runnable != null) { logger.debug(STR, ((AvlClient) runnable).getAvlReport()); } return runnable; } | /**
* Calls superclass poll(timeout, unit) method until it gets AVL data that
* is not obsolete. Used by ThreadPoolExecutor.
*/ | Calls superclass poll(timeout, unit) method until it gets AVL data that is not obsolete. Used by ThreadPoolExecutor | poll | {
"repo_name": "walkeriniraq/transittime-core",
"path": "transitime/src/main/java/org/transitime/avl/AvlQueue.java",
"license": "gpl-3.0",
"size": 7129
} | [
"java.util.concurrent.TimeUnit"
]
| import java.util.concurrent.TimeUnit; | import java.util.concurrent.*; | [
"java.util"
]
| java.util; | 406,606 |
@Email("http://www.nabble.com/Master-slave-refactor-td21361880.html")
public void testComputerConfigureLink() throws Exception {
HtmlPage page = new WebClient().goTo("computer/(master)/configure");
submit(page.getFormByName("config"));
} | @Email(STRcomputer/(master)/configureSTRconfig")); } | /**
* Configure link from "/computer/(master)/" should work.
*/ | Configure link from "/computer/(master)/" should work | testComputerConfigureLink | {
"repo_name": "fujibee/hudson",
"path": "test/src/test/java/hudson/model/HudsonTest.java",
"license": "mit",
"size": 6728
} | [
"org.jvnet.hudson.test.Email"
]
| import org.jvnet.hudson.test.Email; | import org.jvnet.hudson.test.*; | [
"org.jvnet.hudson"
]
| org.jvnet.hudson; | 1,719,311 |
@Override
public void visitBlockTransferPre(BasicBlock block, State state) {
block_transfers++;
} | void function(BasicBlock block, State state) { block_transfers++; } | /**
* Counts block transfers.
*/ | Counts block transfers | visitBlockTransferPre | {
"repo_name": "cs-au-dk/TAJS",
"path": "src/dk/brics/tajs/monitoring/AnalysisMonitor.java",
"license": "apache-2.0",
"size": 66064
} | [
"dk.brics.tajs.flowgraph.BasicBlock",
"dk.brics.tajs.lattice.State"
]
| import dk.brics.tajs.flowgraph.BasicBlock; import dk.brics.tajs.lattice.State; | import dk.brics.tajs.flowgraph.*; import dk.brics.tajs.lattice.*; | [
"dk.brics.tajs"
]
| dk.brics.tajs; | 2,700,130 |
@Test void testDateType2() throws SQLException {
Properties info = new Properties();
info.put("model", FileAdapterTests.jsonPath("bug"));
try (Connection connection =
DriverManager.getConnection("jdbc:calcite:", info)) {
Statement statement = connection.createStatement();
final String sql = "select * from \"DATE\"\n"
+ "where EMPNO >= 140 and EMPNO < 200";
ResultSet resultSet = statement.executeQuery(sql);
int n = 0;
while (resultSet.next()) {
++n;
final int empId = resultSet.getInt(1);
final String date = resultSet.getString(2);
final String time = resultSet.getString(3);
final String timestamp = resultSet.getString(4);
assertThat(date, is("2015-12-31"));
switch (empId) {
case 140:
assertThat(time, is("07:15:56"));
assertThat(timestamp, is("2015-12-31 07:15:56"));
break;
case 150:
assertThat(time, is("13:31:21"));
assertThat(timestamp, is("2015-12-31 13:31:21"));
break;
default:
throw new AssertionError();
}
}
assertThat(n, is(2));
resultSet.close();
statement.close();
}
} | @Test void testDateType2() throws SQLException { Properties info = new Properties(); info.put("model", FileAdapterTests.jsonPath("bug")); try (Connection connection = DriverManager.getConnection(STR, info)) { Statement statement = connection.createStatement(); final String sql = STRDATE\"\n" + STR; ResultSet resultSet = statement.executeQuery(sql); int n = 0; while (resultSet.next()) { ++n; final int empId = resultSet.getInt(1); final String date = resultSet.getString(2); final String time = resultSet.getString(3); final String timestamp = resultSet.getString(4); assertThat(date, is(STR)); switch (empId) { case 140: assertThat(time, is(STR)); assertThat(timestamp, is(STR)); break; case 150: assertThat(time, is(STR)); assertThat(timestamp, is(STR)); break; default: throw new AssertionError(); } } assertThat(n, is(2)); resultSet.close(); statement.close(); } } | /** Test case for
* <a href="https://issues.apache.org/jira/browse/CALCITE-1072">[CALCITE-1072]
* CSV adapter incorrectly parses TIMESTAMP values after noon</a>. */ | Test case for [CALCITE-1072] | testDateType2 | {
"repo_name": "vlsi/calcite",
"path": "file/src/test/java/org/apache/calcite/adapter/file/FileAdapterTest.java",
"license": "apache-2.0",
"size": 35249
} | [
"java.sql.Connection",
"java.sql.DriverManager",
"java.sql.ResultSet",
"java.sql.SQLException",
"java.sql.Statement",
"java.util.Properties",
"org.hamcrest.CoreMatchers",
"org.hamcrest.MatcherAssert",
"org.junit.jupiter.api.Test"
]
| import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import org.hamcrest.CoreMatchers; import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; | import java.sql.*; import java.util.*; import org.hamcrest.*; import org.junit.jupiter.api.*; | [
"java.sql",
"java.util",
"org.hamcrest",
"org.junit.jupiter"
]
| java.sql; java.util; org.hamcrest; org.junit.jupiter; | 258,310 |
@Override
public void mutateData(Tank t1) {
Random noGen = new Random();
int chosenData = noGen.nextInt(3);
switch (chosenData) {
case 0:
int newData = (int) (t1.getAttackPower() * 0.2);
t1.decreaseAttackPower(newData);
break;
case 1:
int newData1 = (int) (t1.getSensorRange() * 0.2);
t1.decreaseSensorRange(newData1);
break;
case 2:
int newData2 = (int) (t1.getAmmoSupply() * 0.2);
t1.decreaseAmmoSupply(newData2);
break;
case 3:
int newData3 = (int) (t1.getArmour() * 0.2);
t1.decreaseArmour(newData3);
break;
}
}
| void function(Tank t1) { Random noGen = new Random(); int chosenData = noGen.nextInt(3); switch (chosenData) { case 0: int newData = (int) (t1.getAttackPower() * 0.2); t1.decreaseAttackPower(newData); break; case 1: int newData1 = (int) (t1.getSensorRange() * 0.2); t1.decreaseSensorRange(newData1); break; case 2: int newData2 = (int) (t1.getAmmoSupply() * 0.2); t1.decreaseAmmoSupply(newData2); break; case 3: int newData3 = (int) (t1.getArmour() * 0.2); t1.decreaseArmour(newData3); break; } } | /**
* This method will randomly mutate one piece of data from the tank.
* @param t1 this tanks data is what will be mutated in the method.*/ | This method will randomly mutate one piece of data from the tank | mutateData | {
"repo_name": "jonster100/TankEA",
"path": "TankEA/tankea/ea/mutagen/core/RandomDataMutagen.java",
"license": "gpl-2.0",
"size": 897
} | [
"java.util.Random"
]
| import java.util.Random; | import java.util.*; | [
"java.util"
]
| java.util; | 1,542,552 |
private IntermediateSortTempRow getSortedRecordFromFile() throws CarbonDataWriterException {
IntermediateSortTempRow row = null;
// poll the top object from heap
// heap maintains binary tree which is based on heap condition that will
// be based on comparator we are passing the heap
// when will call poll it will always delete root of the tree and then
// it does trickel down operation complexity is log(n)
SortTempChunkHolder poll = this.recordHolderHeapLocal.poll();
// get the row from chunk
row = poll.getRow();
// check if there no entry present
if (!poll.hasNext()) {
// if chunk is empty then close the stream
poll.close();
// change the file counter
--this.fileCounter;
// reaturn row
return row;
}
// read new row
try {
poll.readRow();
} catch (Exception e) {
throw new CarbonDataWriterException(e.getMessage(), e);
}
// add to heap
this.recordHolderHeapLocal.add(poll);
// return row
return row;
} | IntermediateSortTempRow function() throws CarbonDataWriterException { IntermediateSortTempRow row = null; SortTempChunkHolder poll = this.recordHolderHeapLocal.poll(); row = poll.getRow(); if (!poll.hasNext()) { poll.close(); --this.fileCounter; return row; } try { poll.readRow(); } catch (Exception e) { throw new CarbonDataWriterException(e.getMessage(), e); } this.recordHolderHeapLocal.add(poll); return row; } | /**
* This method will be used to get the sorted record from file
*
* @return sorted record sorted record
*/ | This method will be used to get the sorted record from file | getSortedRecordFromFile | {
"repo_name": "manishgupta88/carbondata",
"path": "processing/src/main/java/org/apache/carbondata/processing/loading/sort/unsafe/merger/UnsafeSingleThreadFinalSortFilesMerger.java",
"license": "apache-2.0",
"size": 9017
} | [
"org.apache.carbondata.core.datastore.exception.CarbonDataWriterException",
"org.apache.carbondata.processing.loading.row.IntermediateSortTempRow",
"org.apache.carbondata.processing.loading.sort.unsafe.holder.SortTempChunkHolder"
]
| import org.apache.carbondata.core.datastore.exception.CarbonDataWriterException; import org.apache.carbondata.processing.loading.row.IntermediateSortTempRow; import org.apache.carbondata.processing.loading.sort.unsafe.holder.SortTempChunkHolder; | import org.apache.carbondata.core.datastore.exception.*; import org.apache.carbondata.processing.loading.row.*; import org.apache.carbondata.processing.loading.sort.unsafe.holder.*; | [
"org.apache.carbondata"
]
| org.apache.carbondata; | 2,139,750 |
public void addDescriptionType(DescriptionTypeRefSetMember type); | void function(DescriptionTypeRefSetMember type); | /**
* Adds the description types.
*
* @param type the type
*/ | Adds the description types | addDescriptionType | {
"repo_name": "WestCoastInformatics/ihtsdo-refset-tool",
"path": "model/src/main/java/org/ihtsdo/otf/refset/Translation.java",
"license": "apache-2.0",
"size": 3352
} | [
"org.ihtsdo.otf.refset.rf2.DescriptionTypeRefSetMember"
]
| import org.ihtsdo.otf.refset.rf2.DescriptionTypeRefSetMember; | import org.ihtsdo.otf.refset.rf2.*; | [
"org.ihtsdo.otf"
]
| org.ihtsdo.otf; | 2,069,260 |
IObject createObject(SecurityContext ctx, IObject object)
throws DSOutOfServiceException, DSAccessException
{
try {
isSessionAlive(ctx);
return saveAndReturnObject(ctx, object, null);
} catch (Throwable t) {
handleException(t, "Cannot update the object.");
}
return null;
} | IObject createObject(SecurityContext ctx, IObject object) throws DSOutOfServiceException, DSAccessException { try { isSessionAlive(ctx); return saveAndReturnObject(ctx, object, null); } catch (Throwable t) { handleException(t, STR); } return null; } | /**
* Creates the specified object.
*
* @param ctx The security context.
* @param object The object to create.
* @param options Options to create the data.
* @return See above.
* @throws DSOutOfServiceException If the connection is broken, or logged in
* @throws DSAccessException If an error occurred while trying to
* retrieve data from OMERO service.
* @see IPojos#createDataObject(IObject, Map)
*/ | Creates the specified object | createObject | {
"repo_name": "rleigh-dundee/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/env/data/OMEROGateway.java",
"license": "gpl-2.0",
"size": 268360
} | [
"org.openmicroscopy.shoola.env.data.util.SecurityContext"
]
| import org.openmicroscopy.shoola.env.data.util.SecurityContext; | import org.openmicroscopy.shoola.env.data.util.*; | [
"org.openmicroscopy.shoola"
]
| org.openmicroscopy.shoola; | 2,068,712 |
public float getCurrVelocity() {
float squaredNorm = mScrollerX.mCurrVelocity * mScrollerX.mCurrVelocity;
squaredNorm += mScrollerY.mCurrVelocity * mScrollerY.mCurrVelocity;
return FloatMath.sqrt(squaredNorm);
} | float function() { float squaredNorm = mScrollerX.mCurrVelocity * mScrollerX.mCurrVelocity; squaredNorm += mScrollerY.mCurrVelocity * mScrollerY.mCurrVelocity; return FloatMath.sqrt(squaredNorm); } | /**
* Returns the absolute value of the current velocity.
*
* @return The original velocity less the deceleration, norm of the X and Y velocity vector.
*/ | Returns the absolute value of the current velocity | getCurrVelocity | {
"repo_name": "mateor/pdroid",
"path": "android-4.0.3_r1/trunk/frameworks/base/core/java/android/widget/OverScroller.java",
"license": "gpl-3.0",
"size": 36967
} | [
"android.util.FloatMath"
]
| import android.util.FloatMath; | import android.util.*; | [
"android.util"
]
| android.util; | 1,089,176 |
public static final Store newQuadStore() {
return new QuadStore(randomString());
} | static final Store function() { return new QuadStore(randomString()); } | /**
* Returns a new instance of a quad store with default values.
*
* @return a new instance of a quad store with default values.
*/ | Returns a new instance of a quad store with default values | newQuadStore | {
"repo_name": "agazzarini/cumulusrdf",
"path": "cumulusrdf-core/src/test/java/edu/kit/aifb/cumulus/TestUtils.java",
"license": "apache-2.0",
"size": 9066
} | [
"edu.kit.aifb.cumulus.store.QuadStore",
"edu.kit.aifb.cumulus.store.Store"
]
| import edu.kit.aifb.cumulus.store.QuadStore; import edu.kit.aifb.cumulus.store.Store; | import edu.kit.aifb.cumulus.store.*; | [
"edu.kit.aifb"
]
| edu.kit.aifb; | 472,641 |
@Idempotent
ErasureCodingPolicy getErasureCodingPolicy(String src) throws IOException; | ErasureCodingPolicy getErasureCodingPolicy(String src) throws IOException; | /**
* Get the information about the EC policy for the path.
*
* @param src path to get the info for
* @throws IOException
*/ | Get the information about the EC policy for the path | getErasureCodingPolicy | {
"repo_name": "legend-hua/hadoop",
"path": "hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/ClientProtocol.java",
"license": "apache-2.0",
"size": 61815
} | [
"java.io.IOException"
]
| import java.io.IOException; | import java.io.*; | [
"java.io"
]
| java.io; | 2,345,766 |
public Cookie[] getCookieObjects() {
Cookie[] result = request.getCookies();
return result != null ? result : new Cookie[0];
}
| Cookie[] function() { Cookie[] result = request.getCookies(); return result != null ? result : new Cookie[0]; } | /**
* Get all cookie objects.
*/ | Get all cookie objects | getCookieObjects | {
"repo_name": "handong106324/sqLogWeb",
"path": "src/com/jfinal/core/Controller.java",
"license": "lgpl-2.1",
"size": 29613
} | [
"javax.servlet.http.Cookie"
]
| import javax.servlet.http.Cookie; | import javax.servlet.http.*; | [
"javax.servlet"
]
| javax.servlet; | 419,009 |
private void putSupplementItemAttachmentStateIntoContext(SessionState state, Context context, String attachmentsKind)
{
List refs = new ArrayList();
String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR);
if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind))
{
ToolSession session = SessionManager.getCurrentToolSession();
if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null &&
session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null)
{
refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
// set the correct state variable
state.setAttribute(attachmentsKind, refs);
}
session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS);
session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL);
state.removeAttribute(ATTACHMENTS_FOR);
}
// show attachments content
if (state.getAttribute(attachmentsKind) != null)
{
context.put(attachmentsKind, state.getAttribute(attachmentsKind));
}
// this is to keep the proper node div open
context.put("attachments_for", attachmentsKind);
}
| void function(SessionState state, Context context, String attachmentsKind) { List refs = new ArrayList(); String attachmentsFor = (String) state.getAttribute(ATTACHMENTS_FOR); if (attachmentsFor != null && attachmentsFor.equals(attachmentsKind)) { ToolSession session = SessionManager.getCurrentToolSession(); if (session.getAttribute(FilePickerHelper.FILE_PICKER_CANCEL) == null && session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS) != null) { refs = (List)session.getAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); state.setAttribute(attachmentsKind, refs); } session.removeAttribute(FilePickerHelper.FILE_PICKER_ATTACHMENTS); session.removeAttribute(FilePickerHelper.FILE_PICKER_CANCEL); state.removeAttribute(ATTACHMENTS_FOR); } if (state.getAttribute(attachmentsKind) != null) { context.put(attachmentsKind, state.getAttribute(attachmentsKind)); } context.put(STR, attachmentsKind); } | /**
* put supplement item attachment state attribute value into context
* @param state
* @param context
* @param attachmentsKind
*/ | put supplement item attachment state attribute value into context | putSupplementItemAttachmentStateIntoContext | {
"repo_name": "rodriguezdevera/sakai",
"path": "assignment/assignment-tool/tool/src/java/org/sakaiproject/assignment/tool/AssignmentAction.java",
"license": "apache-2.0",
"size": 685575
} | [
"java.util.ArrayList",
"java.util.List",
"org.sakaiproject.cheftool.Context",
"org.sakaiproject.content.api.FilePickerHelper",
"org.sakaiproject.event.api.SessionState",
"org.sakaiproject.tool.api.ToolSession",
"org.sakaiproject.tool.cover.SessionManager"
]
| import java.util.ArrayList; import java.util.List; import org.sakaiproject.cheftool.Context; import org.sakaiproject.content.api.FilePickerHelper; import org.sakaiproject.event.api.SessionState; import org.sakaiproject.tool.api.ToolSession; import org.sakaiproject.tool.cover.SessionManager; | import java.util.*; import org.sakaiproject.cheftool.*; import org.sakaiproject.content.api.*; import org.sakaiproject.event.api.*; import org.sakaiproject.tool.api.*; import org.sakaiproject.tool.cover.*; | [
"java.util",
"org.sakaiproject.cheftool",
"org.sakaiproject.content",
"org.sakaiproject.event",
"org.sakaiproject.tool"
]
| java.util; org.sakaiproject.cheftool; org.sakaiproject.content; org.sakaiproject.event; org.sakaiproject.tool; | 1,051,869 |
public IDataset getSet_voltage();
| IDataset function(); | /**
* voltage set on supply.
* <p>
* <b>Type:</b> NX_FLOAT
* <b>Units:</b> NX_VOLTAGE
* </p>
*
* @return the value.
*/ | voltage set on supply. Type: NX_FLOAT Units: NX_VOLTAGE | getSet_voltage | {
"repo_name": "jamesmudd/dawnsci",
"path": "org.eclipse.dawnsci.nexus/autogen/org/eclipse/dawnsci/nexus/NXmagnetic_kicker.java",
"license": "epl-1.0",
"size": 5999
} | [
"org.eclipse.january.dataset.IDataset"
]
| import org.eclipse.january.dataset.IDataset; | import org.eclipse.january.dataset.*; | [
"org.eclipse.january"
]
| org.eclipse.january; | 175,475 |
protected void saveResponseData(HierarchicalStreamWriter writer, MarshallingContext context, SampleResult res,
SampleSaveConfiguration save) {
if (save.saveResponseData(res)) {
writer.startNode(TAG_RESPONSE_DATA);
writer.addAttribute(ATT_CLASS, JAVA_LANG_STRING);
try {
if (SampleResult.TEXT.equals(res.getDataType())){
writer.setValue(new String(res.getResponseData(), res.getDataEncodingWithDefault()));
} else {
writer.setValue("Non-TEXT response data, cannot record: (" + res.getDataType() + ")");
}
// Otherwise don't save anything - no point
} catch (UnsupportedEncodingException e) {
writer.setValue("Unsupported encoding in response data, cannot record: " + e);
}
writer.endNode();
}
if (save.saveFileName()){
writer.startNode(TAG_RESPONSE_FILE);
writer.addAttribute(ATT_CLASS, JAVA_LANG_STRING);
writer.setValue(res.getResultFileName());
writer.endNode();
}
} | void function(HierarchicalStreamWriter writer, MarshallingContext context, SampleResult res, SampleSaveConfiguration save) { if (save.saveResponseData(res)) { writer.startNode(TAG_RESPONSE_DATA); writer.addAttribute(ATT_CLASS, JAVA_LANG_STRING); try { if (SampleResult.TEXT.equals(res.getDataType())){ writer.setValue(new String(res.getResponseData(), res.getDataEncodingWithDefault())); } else { writer.setValue(STR + res.getDataType() + ")"); } } catch (UnsupportedEncodingException e) { writer.setValue(STR + e); } writer.endNode(); } if (save.saveFileName()){ writer.startNode(TAG_RESPONSE_FILE); writer.addAttribute(ATT_CLASS, JAVA_LANG_STRING); writer.setValue(res.getResultFileName()); writer.endNode(); } } | /**
* Save the response from the sample result into the stream
*
* @param writer
* stream to save objects into
* @param context
* context for xstream to allow nested objects
* @param res
* sample to be saved
* @param save
* configuration telling us what to save
*/ | Save the response from the sample result into the stream | saveResponseData | {
"repo_name": "ra0077/jmeter",
"path": "src/core/org/apache/jmeter/save/converters/SampleResultConverter.java",
"license": "apache-2.0",
"size": 20924
} | [
"com.thoughtworks.xstream.converters.MarshallingContext",
"com.thoughtworks.xstream.io.HierarchicalStreamWriter",
"java.io.UnsupportedEncodingException",
"org.apache.jmeter.samplers.SampleResult",
"org.apache.jmeter.samplers.SampleSaveConfiguration"
]
| import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import java.io.UnsupportedEncodingException; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.samplers.SampleSaveConfiguration; | import com.thoughtworks.xstream.converters.*; import com.thoughtworks.xstream.io.*; import java.io.*; import org.apache.jmeter.samplers.*; | [
"com.thoughtworks.xstream",
"java.io",
"org.apache.jmeter"
]
| com.thoughtworks.xstream; java.io; org.apache.jmeter; | 554,410 |
public void setExportDifferenceToReferenceSignals(boolean exportDifferenceToReferenceSignals)
throws RemoteException;
| void function(boolean exportDifferenceToReferenceSignals) throws RemoteException; | /**
* Change if the difference to the {@link Channel reference signals} are exported to the report.
*
* @param exportDifferenceToReferenceSignals
* the new attribute value
*
* @throws RemoteException
* remote communication problem
*/ | Change if the difference to the <code>Channel reference signals</code> are exported to the report | setExportDifferenceToReferenceSignals | {
"repo_name": "jenkinsci/piketec-tpt-plugin",
"path": "src/main/java/com/piketec/tpt/api/Back2BackSettings.java",
"license": "mit",
"size": 14114
} | [
"java.rmi.RemoteException"
]
| import java.rmi.RemoteException; | import java.rmi.*; | [
"java.rmi"
]
| java.rmi; | 1,848,623 |
public CallHandle renderOverLays(SecurityContext ctx, long pixelsID,
PlaneDef pd, long tableID, Map<Long, Integer> overlays,
AgentEventListener observer)
{
BatchCallTree cmd = new OverlaysRenderer(ctx, pixelsID, pd, tableID,
overlays);
return cmd.exec(observer);
} | CallHandle function(SecurityContext ctx, long pixelsID, PlaneDef pd, long tableID, Map<Long, Integer> overlays, AgentEventListener observer) { BatchCallTree cmd = new OverlaysRenderer(ctx, pixelsID, pd, tableID, overlays); return cmd.exec(observer); } | /**
* Implemented as specified by the view interface.
* @see ImageDataView#renderOverLays(long, PlaneDef, long, Map,
* AgentEventListener)
*/ | Implemented as specified by the view interface | renderOverLays | {
"repo_name": "simleo/openmicroscopy",
"path": "components/insight/SRC/org/openmicroscopy/shoola/env/data/views/ImageDataViewImpl.java",
"license": "gpl-2.0",
"size": 17832
} | [
"java.util.Map",
"org.openmicroscopy.shoola.env.data.views.calls.OverlaysRenderer",
"org.openmicroscopy.shoola.env.event.AgentEventListener"
]
| import java.util.Map; import org.openmicroscopy.shoola.env.data.views.calls.OverlaysRenderer; import org.openmicroscopy.shoola.env.event.AgentEventListener; | import java.util.*; import org.openmicroscopy.shoola.env.data.views.calls.*; import org.openmicroscopy.shoola.env.event.*; | [
"java.util",
"org.openmicroscopy.shoola"
]
| java.util; org.openmicroscopy.shoola; | 1,766,093 |
Format getFormat(DataHandle<Location> source) throws FormatException; | Format getFormat(DataHandle<Location> source) throws FormatException; | /**
* As {@link #getFormat(Location)} but takes an initialized
* {@link DataHandle}.
*
* @param source the source
* @return A {@link Format} compatible with the provided source
* @throws FormatException if no compatible format was found, or if something
* goes wrong checking the source
*/ | As <code>#getFormat(Location)</code> but takes an initialized <code>DataHandle</code> | getFormat | {
"repo_name": "scifio/scifio",
"path": "src/main/java/io/scif/services/FormatService.java",
"license": "bsd-2-clause",
"size": 10996
} | [
"io.scif.Format",
"io.scif.FormatException",
"org.scijava.io.handle.DataHandle",
"org.scijava.io.location.Location"
]
| import io.scif.Format; import io.scif.FormatException; import org.scijava.io.handle.DataHandle; import org.scijava.io.location.Location; | import io.scif.*; import org.scijava.io.handle.*; import org.scijava.io.location.*; | [
"io.scif",
"org.scijava.io"
]
| io.scif; org.scijava.io; | 1,652,935 |
public JToolBar getProjectBar() {
return projectBar;
} | JToolBar function() { return projectBar; } | /**
* Returns the top tool bar in the frame.
*/ | Returns the top tool bar in the frame | getProjectBar | {
"repo_name": "SQLPower/power-architect",
"path": "src/main/java/ca/sqlpower/architect/swingui/ArchitectFrame.java",
"license": "gpl-3.0",
"size": 75470
} | [
"javax.swing.JToolBar"
]
| import javax.swing.JToolBar; | import javax.swing.*; | [
"javax.swing"
]
| javax.swing; | 1,465,272 |
public void setSettlementDate(ZonedDateTimeBean settlementDate) {
this._settlementDate = settlementDate;
} | void function(ZonedDateTimeBean settlementDate) { this._settlementDate = settlementDate; } | /**
* Sets the settlementDate.
* @param settlementDate the new value of the property
*/ | Sets the settlementDate | setSettlementDate | {
"repo_name": "McLeodMoores/starling",
"path": "projects/master-db/src/main/java/com/opengamma/masterdb/security/hibernate/option/SwaptionSecurityBean.java",
"license": "apache-2.0",
"size": 18205
} | [
"com.opengamma.masterdb.security.hibernate.ZonedDateTimeBean"
]
| import com.opengamma.masterdb.security.hibernate.ZonedDateTimeBean; | import com.opengamma.masterdb.security.hibernate.*; | [
"com.opengamma.masterdb"
]
| com.opengamma.masterdb; | 2,325,551 |
@Override
public String toString() {
float occupiedSlotsAsPercent =
getCapacity() != 0 ?
((float) numSlotsOccupied * 100 / getCapacity()) : 0;
StringBuffer sb = new StringBuffer();
sb.append("Capacity: " + capacity + " slots\n");
if(getMaxCapacity() >= 0) {
sb.append("Maximum capacity: " + getMaxCapacity() +" slots\n");
}
sb.append(String.format("Used capacity: %d (%.1f%% of Capacity)\n",
Integer.valueOf(numSlotsOccupied), Float
.valueOf(occupiedSlotsAsPercent)));
sb.append(String.format("Running tasks: %d\n", Integer
.valueOf(numRunningTasks)));
// include info on active users
if (numSlotsOccupied != 0) {
sb.append("Active users:\n");
for (Map.Entry<String, Integer> entry : numSlotsOccupiedByUser
.entrySet()) {
if ((entry.getValue() == null) || (entry.getValue().intValue() <= 0)) {
// user has no tasks running
continue;
}
sb.append("User '" + entry.getKey() + "': ");
int numSlotsOccupiedByThisUser = entry.getValue().intValue();
float p =
(float) numSlotsOccupiedByThisUser * 100 / numSlotsOccupied;
sb.append(String.format("%d (%.1f%% of used capacity)\n", Long
.valueOf(numSlotsOccupiedByThisUser), Float.valueOf(p)));
}
}
return sb.toString();
} | String function() { float occupiedSlotsAsPercent = getCapacity() != 0 ? ((float) numSlotsOccupied * 100 / getCapacity()) : 0; StringBuffer sb = new StringBuffer(); sb.append(STR + capacity + STR); if(getMaxCapacity() >= 0) { sb.append(STR + getMaxCapacity() +STR); } sb.append(String.format(STR, Integer.valueOf(numSlotsOccupied), Float .valueOf(occupiedSlotsAsPercent))); sb.append(String.format(STR, Integer .valueOf(numRunningTasks))); if (numSlotsOccupied != 0) { sb.append(STR); for (Map.Entry<String, Integer> entry : numSlotsOccupiedByUser .entrySet()) { if ((entry.getValue() == null) (entry.getValue().intValue() <= 0)) { continue; } sb.append(STR + entry.getKey() + STR); int numSlotsOccupiedByThisUser = entry.getValue().intValue(); float p = (float) numSlotsOccupiedByThisUser * 100 / numSlotsOccupied; sb.append(String.format(STR, Long .valueOf(numSlotsOccupiedByThisUser), Float.valueOf(p))); } } return sb.toString(); } | /**
* return information about the tasks
*/ | return information about the tasks | toString | {
"repo_name": "ZhangXFeng/hadoop",
"path": "src/hadoop-mapreduce1-project/src/contrib/capacity-scheduler/src/java/org/apache/hadoop/mapred/CapacitySchedulerQueue.java",
"license": "apache-2.0",
"size": 45344
} | [
"java.util.Map"
]
| import java.util.Map; | import java.util.*; | [
"java.util"
]
| java.util; | 1,382,858 |
public void migratePreferences(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
int currentVersion = preferences.getInt(MIGRATION_PREF_KEY, 0);
if (currentVersion == MIGRATION_CURRENT_VERSION) return;
if (currentVersion > MIGRATION_CURRENT_VERSION) {
Log.e(LOG_TAG, "Saved preferences version is newer than supported. Attempting to "
+ "run an older version of Chrome without clearing data is unsupported and "
+ "the results may be unpredictable.");
}
if (currentVersion < 1) {
nativeMigrateJavascriptPreference();
}
if (currentVersion < 2) {
addDefaultSearchEnginePermission(context);
}
if (currentVersion < 3) {
nativeMigrateLocationPreference();
nativeMigrateProtectedMediaPreference();
}
preferences.edit().putInt(MIGRATION_PREF_KEY, MIGRATION_CURRENT_VERSION).commit();
} | void function(Context context) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); int currentVersion = preferences.getInt(MIGRATION_PREF_KEY, 0); if (currentVersion == MIGRATION_CURRENT_VERSION) return; if (currentVersion > MIGRATION_CURRENT_VERSION) { Log.e(LOG_TAG, STR + STR + STR); } if (currentVersion < 1) { nativeMigrateJavascriptPreference(); } if (currentVersion < 2) { addDefaultSearchEnginePermission(context); } if (currentVersion < 3) { nativeMigrateLocationPreference(); nativeMigrateProtectedMediaPreference(); } preferences.edit().putInt(MIGRATION_PREF_KEY, MIGRATION_CURRENT_VERSION).commit(); } | /**
* Migrates (synchronously) the preferences to the most recent version.
*/ | Migrates (synchronously) the preferences to the most recent version | migratePreferences | {
"repo_name": "ltilve/chromium",
"path": "chrome/android/java/src/org/chromium/chrome/browser/preferences/PrefServiceBridge.java",
"license": "bsd-3-clause",
"size": 35046
} | [
"android.content.Context",
"android.content.SharedPreferences",
"android.preference.PreferenceManager",
"android.util.Log"
]
| import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; | import android.content.*; import android.preference.*; import android.util.*; | [
"android.content",
"android.preference",
"android.util"
]
| android.content; android.preference; android.util; | 569,942 |
private Number translateToNumber(final int opcode) {
switch (opcode) {
case Opcodes.ICONST_M1:
return Integer.valueOf(-1);
case Opcodes.ICONST_0:
return Integer.valueOf(0);
case Opcodes.ICONST_1:
return Integer.valueOf(1);
case Opcodes.ICONST_2:
return Integer.valueOf(2);
case Opcodes.ICONST_3:
return Integer.valueOf(3);
case Opcodes.ICONST_4:
return Integer.valueOf(4);
case Opcodes.ICONST_5:
return Integer.valueOf(5);
case Opcodes.LCONST_0:
return Long.valueOf(0L);
case Opcodes.LCONST_1:
return Long.valueOf(1L);
case Opcodes.FCONST_0:
return Float.valueOf(0F);
case Opcodes.FCONST_1:
return Float.valueOf(1F);
case Opcodes.FCONST_2:
return Float.valueOf(2F);
case Opcodes.DCONST_0:
return Double.valueOf(0D);
case Opcodes.DCONST_1:
return Double.valueOf(1D);
default:
return null;
}
}
| Number function(final int opcode) { switch (opcode) { case Opcodes.ICONST_M1: return Integer.valueOf(-1); case Opcodes.ICONST_0: return Integer.valueOf(0); case Opcodes.ICONST_1: return Integer.valueOf(1); case Opcodes.ICONST_2: return Integer.valueOf(2); case Opcodes.ICONST_3: return Integer.valueOf(3); case Opcodes.ICONST_4: return Integer.valueOf(4); case Opcodes.ICONST_5: return Integer.valueOf(5); case Opcodes.LCONST_0: return Long.valueOf(0L); case Opcodes.LCONST_1: return Long.valueOf(1L); case Opcodes.FCONST_0: return Float.valueOf(0F); case Opcodes.FCONST_1: return Float.valueOf(1F); case Opcodes.FCONST_2: return Float.valueOf(2F); case Opcodes.DCONST_0: return Double.valueOf(0D); case Opcodes.DCONST_1: return Double.valueOf(1D); default: return null; } } | /**
* Translates the opcode to a number (inline constant) if possible or
* returns <code>null</code> if the opcode cannot be translated.
*
* @param opcode
* that might represent an inline constant.
* @return the value of the inline constant represented by opcode or
* <code>null</code> if the opcode does not represent a
* number/constant.
*/ | Translates the opcode to a number (inline constant) if possible or returns <code>null</code> if the opcode cannot be translated | translateToNumber | {
"repo_name": "roberth/pitest",
"path": "pitest/src/main/java/org/pitest/mutationtest/engine/gregor/mutators/InlineConstantMutator.java",
"license": "apache-2.0",
"size": 8951
} | [
"org.objectweb.asm.Opcodes"
]
| import org.objectweb.asm.Opcodes; | import org.objectweb.asm.*; | [
"org.objectweb.asm"
]
| org.objectweb.asm; | 1,657,214 |
protected void updateOrInsert(final Serializable id,
final Object[] fields,
final Object[] oldFields,
final Object rowId,
final boolean[] includeProperty,
final int j,
final Object oldVersion,
final Object object,
final String sql,
final SessionImplementor session)
throws HibernateException {
if ( !isInverseTable( j ) ) {
final boolean isRowToUpdate;
if ( isNullableTable( j ) && oldFields != null && isAllNull( oldFields, j ) ) {
//don't bother trying to update, we know there is no row there yet
isRowToUpdate = false;
}
else if ( isNullableTable( j ) && isAllNull( fields, j ) ) {
//if all fields are null, we might need to delete existing row
isRowToUpdate = true;
delete( id, oldVersion, j, object, getSQLDeleteStrings()[j], session );
}
else {
//there is probably a row there, so try to update
//if no rows were updated, we will find out
isRowToUpdate = update( id, fields, oldFields, rowId, includeProperty, j, oldVersion, object, sql, session );
}
if ( !isRowToUpdate && !isAllNull( fields, j ) ) {
// assume that the row was not there since it previously had only null
// values, so do an INSERT instead
//TODO: does not respect dynamic-insert
insert( id, fields, getPropertyInsertability(), j, getSQLInsertStrings()[j], object, session );
}
}
} | void function(final Serializable id, final Object[] fields, final Object[] oldFields, final Object rowId, final boolean[] includeProperty, final int j, final Object oldVersion, final Object object, final String sql, final SessionImplementor session) throws HibernateException { if ( !isInverseTable( j ) ) { final boolean isRowToUpdate; if ( isNullableTable( j ) && oldFields != null && isAllNull( oldFields, j ) ) { isRowToUpdate = false; } else if ( isNullableTable( j ) && isAllNull( fields, j ) ) { isRowToUpdate = true; delete( id, oldVersion, j, object, getSQLDeleteStrings()[j], session ); } else { isRowToUpdate = update( id, fields, oldFields, rowId, includeProperty, j, oldVersion, object, sql, session ); } if ( !isRowToUpdate && !isAllNull( fields, j ) ) { insert( id, fields, getPropertyInsertability(), j, getSQLInsertStrings()[j], object, session ); } } } | /**
* Perform an SQL UPDATE or SQL INSERT
*/ | Perform an SQL UPDATE or SQL INSERT | updateOrInsert | {
"repo_name": "raedle/univis",
"path": "lib/hibernate-3.1.3/src/org/hibernate/persister/entity/AbstractEntityPersister.java",
"license": "lgpl-2.1",
"size": 116750
} | [
"java.io.Serializable",
"org.hibernate.HibernateException",
"org.hibernate.engine.SessionImplementor"
]
| import java.io.Serializable; import org.hibernate.HibernateException; import org.hibernate.engine.SessionImplementor; | import java.io.*; import org.hibernate.*; import org.hibernate.engine.*; | [
"java.io",
"org.hibernate",
"org.hibernate.engine"
]
| java.io; org.hibernate; org.hibernate.engine; | 1,542,803 |
public OpenCLGrid3D computeWeightedTVGradient2(OpenCLGrid3D imgCL)//do TV in each Z slide
{
//TVOpenCLGridOperators.getInstance().compute_wTV_Gradient(imgCL, WmatrixCL, TVgradientCL);
tvOperators.computeWeightedTVGradient2(imgCL, weightMatrixCL, tvGradientCL);
return this.tvGradientCL;
}
| OpenCLGrid3D function(OpenCLGrid3D imgCL) { tvOperators.computeWeightedTVGradient2(imgCL, weightMatrixCL, tvGradientCL); return this.tvGradientCL; } | /**
* compute wTV gradient, only in XY plane
* @param imgCL
* @return
*/ | compute wTV gradient, only in XY plane | computeWeightedTVGradient2 | {
"repo_name": "YixingHuang/CONRAD-1",
"path": "src/edu/stanford/rsl/tutorial/weightedtv/TVGradient3D.java",
"license": "gpl-3.0",
"size": 15950
} | [
"edu.stanford.rsl.conrad.data.numeric.opencl.OpenCLGrid3D"
]
| import edu.stanford.rsl.conrad.data.numeric.opencl.OpenCLGrid3D; | import edu.stanford.rsl.conrad.data.numeric.opencl.*; | [
"edu.stanford.rsl"
]
| edu.stanford.rsl; | 508,646 |
public final void testGetRadish() {
String comment_content = "This is a ContentTest15";
String comment_title = "This is a TitleTest15";
Bitmap picture = HelperFunctions.generateBitmap(50,50);
model = new RootCommentModel(comment_content, comment_title, picture, getInstrumentation().getContext());
model.setFreshness(0);
assertNotNull(model.getRadish());
} | final void function() { String comment_content = STR; String comment_title = STR; Bitmap picture = HelperFunctions.generateBitmap(50,50); model = new RootCommentModel(comment_content, comment_title, picture, getInstrumentation().getContext()); model.setFreshness(0); assertNotNull(model.getRadish()); } | /**
* Test the radish getter
*/ | Test the radish getter | testGetRadish | {
"repo_name": "CMPUT301W14T01/localpost",
"path": "LocalpostTestingTest/src/ca/cs/ualberta/localpost/test/CommentModelTest.java",
"license": "mit",
"size": 11673
} | [
"android.graphics.Bitmap",
"ca.cs.ualberta.localpost.model.RootCommentModel"
]
| import android.graphics.Bitmap; import ca.cs.ualberta.localpost.model.RootCommentModel; | import android.graphics.*; import ca.cs.ualberta.localpost.model.*; | [
"android.graphics",
"ca.cs.ualberta"
]
| android.graphics; ca.cs.ualberta; | 2,862,237 |
public Object getAdapter(Class adapter) {
if (adapter == IWorkbenchAdapter.class) {
return this;
}
return null;
}
| Object function(Class adapter) { if (adapter == IWorkbenchAdapter.class) { return this; } return null; } | /**
* Method declared on IAdaptable
*
* @param adapter
*
* @return
*/ | Method declared on IAdaptable | getAdapter | {
"repo_name": "ben8p/smallEditor",
"path": "src/smalleditor/editors/common/outline/ACommonOutlineElement.java",
"license": "gpl-2.0",
"size": 3974
} | [
"org.eclipse.ui.model.IWorkbenchAdapter"
]
| import org.eclipse.ui.model.IWorkbenchAdapter; | import org.eclipse.ui.model.*; | [
"org.eclipse.ui"
]
| org.eclipse.ui; | 993,911 |
CryptoAddress getNewAssetVaultCryptoAddress(BlockchainNetworkType blockchainNetworkType) throws GetNewCryptoAddressException; | CryptoAddress getNewAssetVaultCryptoAddress(BlockchainNetworkType blockchainNetworkType) throws GetNewCryptoAddressException; | /**
* Will generate a CryptoAddress in the current network originated at the vault.
* @return
*/ | Will generate a CryptoAddress in the current network originated at the vault | getNewAssetVaultCryptoAddress | {
"repo_name": "fvasquezjatar/fermat-unused",
"path": "BCH/library/api/fermat-bch-api/src/main/java/com/bitdubai/fermat_bch_api/layer/crypto_vault/asset_vault/interfaces/AssetVaultManager.java",
"license": "mit",
"size": 1114
} | [
"com.bitdubai.fermat_api.layer.all_definition.enums.BlockchainNetworkType",
"com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress",
"com.bitdubai.fermat_bch_api.layer.crypto_vault.asset_vault.interfaces.exceptions.GetNewCryptoAddressException"
]
| import com.bitdubai.fermat_api.layer.all_definition.enums.BlockchainNetworkType; import com.bitdubai.fermat_api.layer.all_definition.money.CryptoAddress; import com.bitdubai.fermat_bch_api.layer.crypto_vault.asset_vault.interfaces.exceptions.GetNewCryptoAddressException; | import com.bitdubai.fermat_api.layer.all_definition.enums.*; import com.bitdubai.fermat_api.layer.all_definition.money.*; import com.bitdubai.fermat_bch_api.layer.crypto_vault.asset_vault.interfaces.exceptions.*; | [
"com.bitdubai.fermat_api",
"com.bitdubai.fermat_bch_api"
]
| com.bitdubai.fermat_api; com.bitdubai.fermat_bch_api; | 2,759,385 |
public String processSelection(final Selection selection, final HttpServletRequest request) {
if (isSelectionValidated(request)) {
String userSelection = request.getParameter(USER_SELECTION_PARAMETER);
String[] selectedUsers = null;
if (isDefined(userSelection)) {
selectedUsers = userSelection.split(",");
}
String groupSelection = request.getParameter(GROUP_SELECTION_PARAMETER);
String[] selectedGroups = null;
if (isDefined(groupSelection)) {
selectedGroups = groupSelection.split(",");
}
selection.setSelectedElements(selectedUsers);
selection.setSelectedSets(selectedGroups);
// a workaround to clients that use the user panel within a window popup without taking avantage
// of the hot settings
if (!selection.isHotSetting() && selection.isPopupMode()) {
request.setAttribute("RedirectionURL", selection.getGoBackURL());
return "/selection/jsp/redirect.jsp";
}
// a workaround to clients that use the user panel within a window popup without taking avantage
// of the hot settings
} else if (!selection.isHotSetting() && selection.isPopupMode()) {
request.setAttribute("RedirectionURL", selection.getCancelURL());
return "/selection/jsp/redirect.jsp";
}
return null;
} | String function(final Selection selection, final HttpServletRequest request) { if (isSelectionValidated(request)) { String userSelection = request.getParameter(USER_SELECTION_PARAMETER); String[] selectedUsers = null; if (isDefined(userSelection)) { selectedUsers = userSelection.split(","); } String groupSelection = request.getParameter(GROUP_SELECTION_PARAMETER); String[] selectedGroups = null; if (isDefined(groupSelection)) { selectedGroups = groupSelection.split(","); } selection.setSelectedElements(selectedUsers); selection.setSelectedSets(selectedGroups); if (!selection.isHotSetting() && selection.isPopupMode()) { request.setAttribute(STR, selection.getGoBackURL()); return STR; } } else if (!selection.isHotSetting() && selection.isPopupMode()) { request.setAttribute(STR, selection.getCancelURL()); return STR; } return null; } | /**
* Processes the specified selection object from the parameters set into the incoming HTTP
* request.
*
* @param selection the object representing the selection done by the user.
* @param request the HTTP request with the actually selected users and groups.
* @return the next destination that is the view or the service that has to use the selection.
*/ | Processes the specified selection object from the parameters set into the incoming HTTP request | processSelection | {
"repo_name": "SilverDav/Silverpeas-Core",
"path": "core-web/src/main/java/org/silverpeas/core/web/mvc/processor/UserAndGroupSelectionProcessor.java",
"license": "agpl-3.0",
"size": 6169
} | [
"javax.servlet.http.HttpServletRequest",
"org.silverpeas.core.web.selection.Selection"
]
| import javax.servlet.http.HttpServletRequest; import org.silverpeas.core.web.selection.Selection; | import javax.servlet.http.*; import org.silverpeas.core.web.selection.*; | [
"javax.servlet",
"org.silverpeas.core"
]
| javax.servlet; org.silverpeas.core; | 1,297,349 |
void addRefreshableView(View view, ViewDelegate viewDelegate) {
if (isDestroyed()) return;
// Check to see if view is null
if (view == null) {
Log.i(LOG_TAG, "Refreshable View is null.");
return;
}
// ViewDelegate
if (viewDelegate == null) {
viewDelegate = InstanceCreationUtils.getBuiltInViewDelegate(view);
}
// View to detect refreshes for
mRefreshableViews.put(view, viewDelegate);
} | void addRefreshableView(View view, ViewDelegate viewDelegate) { if (isDestroyed()) return; if (view == null) { Log.i(LOG_TAG, STR); return; } if (viewDelegate == null) { viewDelegate = InstanceCreationUtils.getBuiltInViewDelegate(view); } mRefreshableViews.put(view, viewDelegate); } | /**
* Add a view which will be used to initiate refresh requests.
*
* @param view View which will be used to initiate refresh requests.
*/ | Add a view which will be used to initiate refresh requests | addRefreshableView | {
"repo_name": "thunderace/mpd-control",
"path": "src/org/thunder/actionbarpulltorefresh/PullToRefreshAttacher.java",
"license": "apache-2.0",
"size": 21422
} | [
"android.util.Log",
"android.view.View",
"org.thunder.actionbarpulltorefresh.viewdelegates.ViewDelegate"
]
| import android.util.Log; import android.view.View; import org.thunder.actionbarpulltorefresh.viewdelegates.ViewDelegate; | import android.util.*; import android.view.*; import org.thunder.actionbarpulltorefresh.viewdelegates.*; | [
"android.util",
"android.view",
"org.thunder.actionbarpulltorefresh"
]
| android.util; android.view; org.thunder.actionbarpulltorefresh; | 2,198,885 |
RemoteSession remoteController = null;
try {
remoteController = RemoteSession.create("openHAB", "openHAB", ip, port);
Key key = Key.valueOf(cmd);
logger.debug("Try to send command: {}", cmd);
remoteController.sendKey(key);
} catch (Exception e) {
logger.error("Could not send command to device on {}: {}", ip + ":" + port, e);
}
remoteController = null;
} | RemoteSession remoteController = null; try { remoteController = RemoteSession.create(STR, STR, ip, port); Key key = Key.valueOf(cmd); logger.debug(STR, cmd); remoteController.sendKey(key); } catch (Exception e) { logger.error(STR, ip + ":" + port, e); } remoteController = null; } | /**
* Sends a command to Samsung device.
*
* @param cmd
* Command to send
*/ | Sends a command to Samsung device | send | {
"repo_name": "computergeek1507/openhab",
"path": "bundles/binding/org.openhab.binding.samsungtv/src/main/java/org/openhab/binding/samsungtv/internal/SamsungTvConnection.java",
"license": "epl-1.0",
"size": 1626
} | [
"de.quist.samy.remocon.Key",
"de.quist.samy.remocon.RemoteSession"
]
| import de.quist.samy.remocon.Key; import de.quist.samy.remocon.RemoteSession; | import de.quist.samy.remocon.*; | [
"de.quist.samy"
]
| de.quist.samy; | 750,223 |
T visitExpressionLogicNot(@NotNull BigDataScriptParser.ExpressionLogicNotContext ctx); | T visitExpressionLogicNot(@NotNull BigDataScriptParser.ExpressionLogicNotContext ctx); | /**
* Visit a parse tree produced by {@link BigDataScriptParser#expressionLogicNot}.
* @param ctx the parse tree
* @return the visitor result
*/ | Visit a parse tree produced by <code>BigDataScriptParser#expressionLogicNot</code> | visitExpressionLogicNot | {
"repo_name": "leepc12/BigDataScript",
"path": "src/org/bds/antlr/BigDataScriptVisitor.java",
"license": "apache-2.0",
"size": 22181
} | [
"org.antlr.v4.runtime.misc.NotNull"
]
| import org.antlr.v4.runtime.misc.NotNull; | import org.antlr.v4.runtime.misc.*; | [
"org.antlr.v4"
]
| org.antlr.v4; | 1,315,918 |
private void cancelFutures() {
sharedCtx.mvcc().onStop();
Exception err = new IgniteCheckedException("Operation has been cancelled (node is stopping).");
for (IgniteInternalFuture fut : pendingFuts.values())
((GridFutureAdapter)fut).onDone(err);
for (IgniteInternalFuture fut : pendingTemplateFuts.values())
((GridFutureAdapter)fut).onDone(err);
for (EnableStatisticsFuture fut : manageStatisticsFuts.values())
fut.onDone(err);
for (TxTimeoutOnPartitionMapExchangeChangeFuture fut : txTimeoutOnPartitionMapExchangeFuts.values())
fut.onDone(err);
} | void function() { sharedCtx.mvcc().onStop(); Exception err = new IgniteCheckedException(STR); for (IgniteInternalFuture fut : pendingFuts.values()) ((GridFutureAdapter)fut).onDone(err); for (IgniteInternalFuture fut : pendingTemplateFuts.values()) ((GridFutureAdapter)fut).onDone(err); for (EnableStatisticsFuture fut : manageStatisticsFuts.values()) fut.onDone(err); for (TxTimeoutOnPartitionMapExchangeChangeFuture fut : txTimeoutOnPartitionMapExchangeFuts.values()) fut.onDone(err); } | /**
* Cancel all user operations.
*/ | Cancel all user operations | cancelFutures | {
"repo_name": "ilantukh/ignite",
"path": "modules/core/src/main/java/org/apache/ignite/internal/processors/cache/GridCacheProcessor.java",
"license": "apache-2.0",
"size": 237840
} | [
"org.apache.ignite.IgniteCheckedException",
"org.apache.ignite.internal.IgniteInternalFuture",
"org.apache.ignite.internal.util.future.GridFutureAdapter"
]
| import org.apache.ignite.IgniteCheckedException; import org.apache.ignite.internal.IgniteInternalFuture; import org.apache.ignite.internal.util.future.GridFutureAdapter; | import org.apache.ignite.*; import org.apache.ignite.internal.*; import org.apache.ignite.internal.util.future.*; | [
"org.apache.ignite"
]
| org.apache.ignite; | 1,257,747 |
public static ByteKey copyFrom(byte[] bytes) {
return of(ByteString.copyFrom(bytes));
} | static ByteKey function(byte[] bytes) { return of(ByteString.copyFrom(bytes)); } | /**
* Creates a new {@link ByteKey} backed by a copy of the specified {@code byte[]}.
*
* <p>Makes a copy of the underlying array.
*/ | Creates a new <code>ByteKey</code> backed by a copy of the specified byte[]. Makes a copy of the underlying array | copyFrom | {
"repo_name": "shakamunyi/beam",
"path": "sdks/java/core/src/main/java/com/google/cloud/dataflow/sdk/io/range/ByteKey.java",
"license": "apache-2.0",
"size": 5713
} | [
"com.google.protobuf.ByteString"
]
| import com.google.protobuf.ByteString; | import com.google.protobuf.*; | [
"com.google.protobuf"
]
| com.google.protobuf; | 1,124,249 |
private void initReader() throws IOException {
long syncPos = trackerFile.length() - 256L;
if (syncPos < 0) syncPos = 0L;
reader.sync(syncPos);
while (reader.hasNext()) {
reader.next(metaCache);
}
} | void function() throws IOException { long syncPos = trackerFile.length() - 256L; if (syncPos < 0) syncPos = 0L; reader.sync(syncPos); while (reader.hasNext()) { reader.next(metaCache); } } | /**
* Read the last record in the file.
*/ | Read the last record in the file | initReader | {
"repo_name": "wangcy6/storm_app",
"path": "frame/apache-flume-1.7.0-src/flume-ng-core/src/main/java/org/apache/flume/serialization/DurablePositionTracker.java",
"license": "apache-2.0",
"size": 6263
} | [
"java.io.IOException"
]
| import java.io.IOException; | import java.io.*; | [
"java.io"
]
| java.io; | 2,676,523 |
private void parseVariableChunk() throws InvalidConfigurationException {
current = current + 1;
if (current >= value.length() || value.charAt(current) != '{') {
abort("expected '{'");
}
current = current + 1;
if (current >= value.length() || value.charAt(current) == '}') {
abort("expected variable name");
}
int end = value.indexOf('}', current);
final String name = value.substring(current, end);
usedVariables.add(name);
chunks.add(new VariableChunk(name));
current = end + 1;
} | void function() throws InvalidConfigurationException { current = current + 1; if (current >= value.length() value.charAt(current) != '{') { abort(STR); } current = current + 1; if (current >= value.length() value.charAt(current) == '}') { abort(STR); } int end = value.indexOf('}', current); final String name = value.substring(current, end); usedVariables.add(name); chunks.add(new VariableChunk(name)); current = end + 1; } | /**
* Parses a variable to be expanded.
*
* @throws InvalidConfigurationException if there is a parsing error.
*/ | Parses a variable to be expanded | parseVariableChunk | {
"repo_name": "hermione521/bazel",
"path": "src/main/java/com/google/devtools/build/lib/rules/cpp/CcToolchainFeatures.java",
"license": "apache-2.0",
"size": 83364
} | [
"com.google.devtools.build.lib.analysis.config.InvalidConfigurationException"
]
| import com.google.devtools.build.lib.analysis.config.InvalidConfigurationException; | import com.google.devtools.build.lib.analysis.config.*; | [
"com.google.devtools"
]
| com.google.devtools; | 1,681,002 |
InputStream getInputStream() throws WebDavException; | InputStream getInputStream() throws WebDavException; | /**
* Reads data from the resource.
*
* @throws WebDavException if reading fails, e.g. due to network problems
*/ | Reads data from the resource | getInputStream | {
"repo_name": "Prasad1337/GANTTing",
"path": "ganttproject/src/net/sourceforge/ganttproject/document/webdav/WebDavResource.java",
"license": "gpl-2.0",
"size": 5970
} | [
"java.io.InputStream"
]
| import java.io.InputStream; | import java.io.*; | [
"java.io"
]
| java.io; | 2,547,780 |
@Nullable
public Date getDateCreated()
{
return getDate(TAG_DATE_CREATED, TAG_TIME_CREATED);
} | Date function() { return getDate(TAG_DATE_CREATED, TAG_TIME_CREATED); } | /**
* Parses the Date Created tag and the Time Created tag to obtain a single Date object representing the
* date and time when this image was captured.
* @return A Date object representing when this image was captured, if possible, otherwise null
*/ | Parses the Date Created tag and the Time Created tag to obtain a single Date object representing the date and time when this image was captured | getDateCreated | {
"repo_name": "PaytonGarland/metadata-extractor",
"path": "Source/com/drew/metadata/iptc/IptcDirectory.java",
"license": "apache-2.0",
"size": 16213
} | [
"java.util.Date"
]
| import java.util.Date; | import java.util.*; | [
"java.util"
]
| java.util; | 519,364 |
CompletableFuture<Void> disableControllerServices(List<ControllerServiceNode> services); | CompletableFuture<Void> disableControllerServices(List<ControllerServiceNode> services); | /**
* Disables all of the given Controller Services in the order provided by the List
* @param services the controller services to disable
*/ | Disables all of the given Controller Services in the order provided by the List | disableControllerServices | {
"repo_name": "YolandaMDavis/nifi",
"path": "nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-framework-core-api/src/main/java/org/apache/nifi/controller/ProcessScheduler.java",
"license": "apache-2.0",
"size": 8673
} | [
"java.util.List",
"java.util.concurrent.CompletableFuture",
"org.apache.nifi.controller.service.ControllerServiceNode"
]
| import java.util.List; import java.util.concurrent.CompletableFuture; import org.apache.nifi.controller.service.ControllerServiceNode; | import java.util.*; import java.util.concurrent.*; import org.apache.nifi.controller.service.*; | [
"java.util",
"org.apache.nifi"
]
| java.util; org.apache.nifi; | 1,346,042 |
public static <T extends Node> Element wrap(boolean copy, String prefix, String name, String namespace, T... n) {
Element ret = new Element(prefix + ":" + name, namespace);
if (copy) {
Node x = null;
for (Node node : n) {
x = node.copy();
x.detach();
ret.appendChild(node);
}
} else {
for (Node node : n) {
node.detach();
ret.appendChild(node);
}
}
return ret;
} | static <T extends Node> Element function(boolean copy, String prefix, String name, String namespace, T... n) { Element ret = new Element(prefix + ":" + name, namespace); if (copy) { Node x = null; for (Node node : n) { x = node.copy(); x.detach(); ret.appendChild(node); } } else { for (Node node : n) { node.detach(); ret.appendChild(node); } } return ret; } | /**
* Wrap the given list of nodes in a root element
*
* @param n nodes to wrap
* @param copy whether to append copies of the nodes. If false then the given nodes are detached!
* @param prefix root element prefix
* @param name root element name
* @param namespace root element namespace
* @return the root element
*/ | Wrap the given list of nodes in a root element | wrap | {
"repo_name": "diogo-andrade/DataHubSystem",
"path": "petascope/src/main/java/petascope/util/XMLUtil.java",
"license": "agpl-3.0",
"size": 35634
} | [
"nu.xom.Element",
"nu.xom.Node"
]
| import nu.xom.Element; import nu.xom.Node; | import nu.xom.*; | [
"nu.xom"
]
| nu.xom; | 1,576,055 |
public static DataTableW<String> textToTable(LinkedList<String> linesOfText, String[] singleLineFields, String[] multipleLineFields)
{ // unique field names are listed in the 'fieldList', except for geometry field names: pt, lc, lm, ln.
CountingTree fieldList = new CountingTree();
// This is a unique list of the comments in the geometry sub-records, key is comment, value is count for that comment
CountingTree geometryCommentMap = new CountingTree();
// one 'record' per parcel, each 'record' contains a list of 'DataRecordW' objects containing the fields and geometry of each parcel
Parcel<String> record = null;
// the 'table' contains all of the parcels in the data file
LinkedList<Parcel<String>> table = new LinkedList<Parcel<String>>();
int commentCntMax = 0, locLengthMin = 100, locLengthMax = 0;
int recordCount = 0;
String rcrdCntStr = (new Integer(0)).toString();
String allFieldsCnt = "", cmntCntStr = "", fieldCntStr = "", edgePtCntStr = "";
int commentCnt, fieldCnt, edgePtCnt;
int firstSemi, secondSemi;
String current;
String comment, commentLabel = "", before = "", after, id="";
String direction, distance, ddComment;
String[] locParam;
String[] temp;
int pos;
boolean multiCustom = false;
int customFieldType = 0;
try
{ while(!linesOfText.isEmpty()) // begin loop that reads the data file into a 'table',
{ recordCount++; // parcel count
rcrdCntStr = (new Integer(recordCount)).toString();
commentCnt = 0;
fieldCnt = 0;
edgePtCnt = 0;
locParam = null;
temp = null;
id = "";
current = linesOfText.poll();
record = new Parcel<String>(); // TODO change all uses of 'record' if order changes
//field order for 'record' {fieldName,rcrdCntStr,allFieldsCnt,cmntCntStr,fieldCntStr,edgePtCntStr,comment or additional fields: for geometry:direction,distance,ddComment,id; for 'loc': it is split on the " " character}
// fieldName may be 'commentLabel', 'before' or 'loc_tay'
while (!current.startsWith("end") && !linesOfText.isEmpty()) // begin parcel loop --> prepares a 'record' to add to the 'table'
{ firstSemi = 0;
secondSemi = 0;
direction = "";
distance = "";
ddComment = "";
multiCustom = false;
customFieldType = checkCustomFieldType(current, singleLineFields, multipleLineFields);
if(customFieldType == SINGLE_LINE_FIELD) // convert single line custom fields to fields. <-- exit comment logic
current = current.substring(1).trim(); // remove the '!' and concatenate (desirable??)
if(customFieldType == MULTIPLE_LINE_FIELD) // flag multiline custom fields. <-- remain in comment logic
{ multiCustom = true;
commentLabel = getFieldMatch(current, multipleLineFields);
}
if (current.startsWith("!")) // comment logic, concatenates comment into single list entry
{ if(!multiCustom)
{ commentCnt++;
commentLabel = "z_cmnt" + commentCnt;
}
cmntCntStr = (new Integer(commentCnt)).toString();
allFieldsCnt = (new Integer(commentCnt + fieldCnt + edgePtCnt)).toString();
comment = "";
while (current.startsWith("!"))
{ current = current.replace("\t", " "); // TODO may want to do this to all lines, not just comments.
comment += current.substring(1); // remove the '!' and concatenate (desirable??)
if (!linesOfText.isEmpty())
{ current = linesOfText.poll(); // get next line, preview its contents, converting single line to fields
customFieldType = checkCustomFieldType(current, singleLineFields, multipleLineFields);
if(customFieldType == SINGLE_LINE_FIELD) // convert single line custom fields to fields
{ current = current.substring(1).trim(); // remove the '!' and concatenate (desirable??)
}
else if(customFieldType == MULTIPLE_LINE_FIELD) // convert multiple line custom fields to fields
{ // add the current record
if(!comment.trim().equals(""))
{ record.add(new DataRecordW<String>(new String[]{commentLabel,rcrdCntStr,allFieldsCnt,cmntCntStr,"0","0",comment},1,MBL_FIELDNAME),false);
fieldList.add(commentLabel);
}
else commentCnt--; // discard comments that contain nothing but white space
// start a new record
commentLabel = getFieldMatch(current, multipleLineFields);
}
}
}// end multiline comment/field loop
if(!comment.trim().equals(""))
{ record.add(new DataRecordW<String>(new String[]{commentLabel,rcrdCntStr,allFieldsCnt,cmntCntStr,"0","0",comment},1,MBL_FIELDNAME),false);
fieldList.add(commentLabel);
}
else commentCnt--; // discard comments that contain nothing but white space
}// end comment logic
if (current.startsWith("end")) // start next parcel
{ if(!linesOfText.isEmpty())
current = linesOfText.poll();
}
else // field logic
{ if(current.contains(" ") && current.length() > current.indexOf(" ") + 1) // if 'after' exists
{ before = current.substring(0, current.indexOf(" ")); // the field name (before the first space)
after = current.substring(current.indexOf(" ") + 1); // the field content, which may be further subdivided
if (before.equals("id"))
{ id = after; // capture the id so it can be added to the geometry sub-records
record.setComparator(id); // the parcels will be compared using 'id' for .equals(), .contains(), etc.
}
if (!isMBLgeoField(before))
{// handle field names for non geometry fields
fieldList.add(before); // add all field names to fieldList
}// end handle field names for non geometry fields
if (isMBLgeoField(before))
{// add geometry sub-record
edgePtCnt++;
if (after.contains(";")) // format of geometry is: 'before';'direction';'distance';'ddComment'
{ firstSemi = after.indexOf(";");
direction = after.substring(0, firstSemi); // 'direction' assigned
if (after.substring(firstSemi+1).contains(";"))
{ secondSemi = (after.substring(firstSemi+1)).indexOf(";") + firstSemi + 1;
distance = after.substring(firstSemi + 1, secondSemi); // 'distance' assigned
if (after.length() > secondSemi + 1)
ddComment = after.substring(secondSemi + 1); // 'ddComment' assigned
}
else ddComment = after.substring(firstSemi+1); // in case there is no distance, 'ddComment' assigned
}
else ddComment = after; // mostly used for 'pt' start points of tract description, 'ddComment' assigned
edgePtCntStr = (new Integer(edgePtCnt)).toString();
allFieldsCnt = (new Integer(commentCnt + fieldCnt + edgePtCnt)).toString();
record.add(new DataRecordW<String>(new String[]{before,rcrdCntStr,allFieldsCnt,"0","0",edgePtCntStr,direction,distance,ddComment,(id+" ["+edgePtCnt+"]")},1,MBL_FIELDNAME),true);
geometryCommentMap.add(ddComment);
}// end add geometry sub-record
else if (before.equals("loc")) // add 'loc' field. TODO change this if 'loc' handling changes
{ fieldCnt++;
fieldCntStr = (new Integer(fieldCnt)).toString();
allFieldsCnt = (new Integer(commentCnt + fieldCnt + edgePtCnt)).toString();
// standard method for handling a field
record.add(new DataRecordW<String>(new String[]{before,rcrdCntStr,allFieldsCnt,"0",fieldCntStr,"0",after},1,MBL_FIELDNAME),false);
if (after.length() > 0) // non-standard method: splits the 'after' for 'loc' on ' ' and attaches the split on the end of the 'record'
{ fieldCntStr = (new Integer(++fieldCnt)).toString();
allFieldsCnt = (new Integer(commentCnt + fieldCnt + edgePtCnt)).toString();
locParam = after.split(" "); // splits 'after' portion of 'loc' using ' ' as the delimeter
temp = new String[locParam.length + 6]; // creates a new array and puts the 6 basic fields up front in that array
temp[MBL_FIELDNAME] = "loc_tay";
temp[MBL_RECORDCOUNT] = rcrdCntStr;
temp[MBL_ALLFIELDSCOUNT] = allFieldsCnt;
temp[MBL_COMMENTCOUNT] = "0";
temp[MBL_FIELDCOUNT] = fieldCntStr;
temp[MBL_EDGEPOINTCOUNT] = "0";
pos = 5;
for (String cur:locParam) // then copy in the split out portions from 'loc'
temp[++pos] = cur;
record.add(new DataRecordW<String>(temp,1,MBL_FIELDNAME),false); // add the non-standard 'loc'
if(pos + 1 > locLengthMax)
locLengthMax = pos + 1;
if(pos + 1 < locLengthMin)
locLengthMin = pos + 1;
} // end non-standard method for handling 'loc'
}// end add 'loc' field
else // add record for non geometry and non loc fields
{ fieldCnt++;
fieldCntStr = (new Integer(fieldCnt)).toString();
allFieldsCnt = (new Integer(commentCnt + fieldCnt + edgePtCnt)).toString();
record.add(new DataRecordW<String>(new String[]{before,rcrdCntStr,allFieldsCnt,"0",fieldCntStr,"0",after},1,MBL_FIELDNAME),false);
}// end add record for non geometry and non loc fields
}// end "if 'after' exists"
if(!linesOfText.isEmpty())
current = linesOfText.poll();
else current = "end";
}// end field logic
}// end parcel loop
table.add(record);
if (commentCnt > commentCntMax)
commentCntMax = commentCnt;
}// end data file loop
}catch(Exception e)
{ popupErrorDialog("An error occured while reading the mbl file.","MBL File Error", e);
}
return new DataTableW<String>(table,fieldList, geometryCommentMap);
}// end of textToTable()
| static DataTableW<String> function(LinkedList<String> linesOfText, String[] singleLineFields, String[] multipleLineFields) { CountingTree fieldList = new CountingTree(); CountingTree geometryCommentMap = new CountingTree(); Parcel<String> record = null; LinkedList<Parcel<String>> table = new LinkedList<Parcel<String>>(); int commentCntMax = 0, locLengthMin = 100, locLengthMax = 0; int recordCount = 0; String rcrdCntStr = (new Integer(0)).toString(); String allFieldsCnt = STRSTRSTRSTRSTRSTRSTRSTRendSTRSTRSTRSTR!STRz_cmntSTRSTR!STR\tSTR STRSTR0","0STRSTR0","0STRendSTR STR STR STR STRidSTR;STR;STR;STR;STR0","0STR [STR]STRlocSTR0STR0STR STRloc_taySTR0STR0STR0STR0STRendSTRAn error occured while reading the mbl file.","MBL File Error", e); } return new DataTableW<String>(table,fieldList, geometryCommentMap); } | /**
* The main logic for parsing the "read in" Deed Mapper ".mbl" data file.
* @param linesOfText The "read in" data file (created using the Witness.readInLines method)
* @return The formatted table containing a LinkedList of records and a CountingTree of field names
*/ | The main logic for parsing the "read in" Deed Mapper ".mbl" data file | textToTable | {
"repo_name": "thayeray/witness_tree",
"path": "src/Witness.java",
"license": "lgpl-2.1",
"size": 50119
} | [
"java.io.File",
"java.util.LinkedList"
]
| import java.io.File; import java.util.LinkedList; | import java.io.*; import java.util.*; | [
"java.io",
"java.util"
]
| java.io; java.util; | 2,596,269 |
public Date getCreationDate () {
return creationDate;
} | Date function () { return creationDate; } | /**
* Returns the date when this notification was created.
*
* @return
* the value of {@code creationDate}.
*/ | Returns the date when this notification was created | getCreationDate | {
"repo_name": "Foo-Manroot/CAL",
"path": "src/control/Notification.java",
"license": "gpl-3.0",
"size": 9951
} | [
"java.util.Date"
]
| import java.util.Date; | import java.util.*; | [
"java.util"
]
| java.util; | 1,191,237 |
private boolean isError(IProblem problem, Type type) {
return true;
} | boolean function(IProblem problem, Type type) { return true; } | /**
* Decides if a problem matters.
* @param problem the problem
* @param type the current type
* @return return if a problem matters.
*/ | Decides if a problem matters | isError | {
"repo_name": "dhuebner/che",
"path": "plugins/plugin-java/che-plugin-java-ext-jdt/org-eclipse-jdt-ui/src/main/java/org/eclipse/jdt/internal/corext/refactoring/TypeContextChecker.java",
"license": "epl-1.0",
"size": 34199
} | [
"org.eclipse.jdt.core.compiler.IProblem",
"org.eclipse.jdt.core.dom.Type"
]
| import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.core.dom.Type; | import org.eclipse.jdt.core.compiler.*; import org.eclipse.jdt.core.dom.*; | [
"org.eclipse.jdt"
]
| org.eclipse.jdt; | 925,256 |
public JobSchedulingError withDetails(List<NameValuePair> details) {
this.details = details;
return this;
} | JobSchedulingError function(List<NameValuePair> details) { this.details = details; return this; } | /**
* Set the details value.
*
* @param details the details value to set
* @return the JobSchedulingError object itself.
*/ | Set the details value | withDetails | {
"repo_name": "navalev/azure-sdk-for-java",
"path": "sdk/batch/microsoft-azure-batch/src/main/java/com/microsoft/azure/batch/protocol/models/JobSchedulingError.java",
"license": "mit",
"size": 3049
} | [
"java.util.List"
]
| import java.util.List; | import java.util.*; | [
"java.util"
]
| java.util; | 1,859,010 |
public String convert(Literal lit) {
return convert(NodeFactory.createLiteral(
lit.getLexicalForm(),
lit.getLanguage(),
lit.getDatatype()).getLiteral());
} | String function(Literal lit) { return convert(NodeFactory.createLiteral( lit.getLexicalForm(), lit.getLanguage(), lit.getDatatype()).getLiteral()); } | /**
* Convert the literal into natural language.
* @param lit the literal
* @return the natural language expression
*/ | Convert the literal into natural language | convert | {
"repo_name": "AKSW/SemWeb2NL",
"path": "Triple2NL/src/main/java/org/aksw/triple2nl/converter/LiteralConverter.java",
"license": "gpl-3.0",
"size": 7554
} | [
"com.hp.hpl.jena.graph.NodeFactory",
"com.hp.hpl.jena.rdf.model.Literal"
]
| import com.hp.hpl.jena.graph.NodeFactory; import com.hp.hpl.jena.rdf.model.Literal; | import com.hp.hpl.jena.graph.*; import com.hp.hpl.jena.rdf.model.*; | [
"com.hp.hpl"
]
| com.hp.hpl; | 1,839,929 |
public static void requestPermission(AppCompatActivity activity, int requestId,
String permission, boolean finishActivity) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
// Display a dialog with rationale.
PermissionUtils.RationaleDialog.newInstance(requestId, finishActivity)
.show(activity.getSupportFragmentManager(), "dialog");
} else {
// Location permission has not been granted yet, request it.
ActivityCompat.requestPermissions(activity, new String[]{permission}, requestId);
}
} | static void function(AppCompatActivity activity, int requestId, String permission, boolean finishActivity) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { PermissionUtils.RationaleDialog.newInstance(requestId, finishActivity) .show(activity.getSupportFragmentManager(), STR); } else { ActivityCompat.requestPermissions(activity, new String[]{permission}, requestId); } } | /**
* Requests the fine location permission. If a rationale with an additional explanation should
* be shown to the user, displays a dialog that triggers the request.
*/ | Requests the fine location permission. If a rationale with an additional explanation should be shown to the user, displays a dialog that triggers the request | requestPermission | {
"repo_name": "miroc/Whitebikes",
"path": "app/src/main/java/sk/miroc/whitebikes/utils/PermissionUtils.java",
"license": "gpl-3.0",
"size": 7526
} | [
"android.support.v4.app.ActivityCompat",
"android.support.v7.app.AppCompatActivity"
]
| import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; | import android.support.v4.app.*; import android.support.v7.app.*; | [
"android.support"
]
| android.support; | 2,368,807 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.