type
stringclasses 1
value | dataset
stringclasses 1
value | input
stringlengths 75
160k
| instruction
stringlengths 117
171
| output
stringlengths 88
168k
|
---|---|---|---|---|
Inversion-Mutation | megadiff | "public void openModeler() {
try{
ModelerHelper.getInstance().createModelerTabFromOutputStep();
SpoonPerspectiveManager.getInstance().activatePerspective(AgileBiPerspective.class);
} catch(Exception e){
e.printStackTrace();
SpoonFactory.getInstance().messageBox( "Could not create a modeler: "+e.getLocalizedMessage(), "Modeler Error", false, Const.ERROR);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "openModeler" | "public void openModeler() {
try{
<MASK>SpoonPerspectiveManager.getInstance().activatePerspective(AgileBiPerspective.class);</MASK>
ModelerHelper.getInstance().createModelerTabFromOutputStep();
} catch(Exception e){
e.printStackTrace();
SpoonFactory.getInstance().messageBox( "Could not create a modeler: "+e.getLocalizedMessage(), "Modeler Error", false, Const.ERROR);
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void onPause() {
super.onPause();
updateModel();
String action = getIntent().getAction();
if (origDay.equals(day) && !Intent.ACTION_INSERT.equals(action)) {
return;
}
try {
DayAccess.getInstance().insertOrUpdate(day);
DayAccess.getInstance().recalculate(this, day);
// Cursor cursor = day.getTimestamps();
// if (cursor.moveToFirst()) {
// RebuildDaysTask
// .rebuildDays(getContext(), new Timestamp(cursor));
// }
} catch (Exception e) {
Log.e(Logger.LOG_TAG, "Cannot save day", e);
Toast.makeText(this, "Error saving day.", Toast.LENGTH_LONG).show();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPause" | "@Override
protected void onPause() {
updateModel();
String action = getIntent().getAction();
if (origDay.equals(day) && !Intent.ACTION_INSERT.equals(action)) {
return;
}
try {
DayAccess.getInstance().insertOrUpdate(day);
DayAccess.getInstance().recalculate(this, day);
// Cursor cursor = day.getTimestamps();
// if (cursor.moveToFirst()) {
// RebuildDaysTask
// .rebuildDays(getContext(), new Timestamp(cursor));
// }
} catch (Exception e) {
Log.e(Logger.LOG_TAG, "Cannot save day", e);
Toast.makeText(this, "Error saving day.", Toast.LENGTH_LONG).show();
}
<MASK>super.onPause();</MASK>
}" |
Inversion-Mutation | megadiff | "@Override
public int available() throws IOException{
if(_i == _currentLine.length){
if(++_rid == _numrows){
_ab = null;
int abytes = super.available();
if(abytes <= 0) return abytes;
_numrows = _ary.rpc(_chkidx-1);
_rid = 0;
}
StringBuilder sb = new StringBuilder();
boolean f = true;
for(Column c:_ary._cols){
if(f) f = false; else sb.append(',');
if(!_ary.isNA(_ab, _rid, c)){
if(c.isEnum()) sb.append('"' + c._domain[(int)_ary.data(_ab, _rid, c)] + '"');
else if(!c.isFloat()) sb.append(_ary.data(_ab, _rid, c));
else sb.append(_ary.datad(_ab,_rid,c));
}
}
sb.append('\n');
_currentLine = sb.toString().getBytes();
_i = 0;
}
return _currentLine.length - _i;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "available" | "@Override
public int available() throws IOException{
if(_i == _currentLine.length){
if(++_rid == _numrows){
_ab = null;
int abytes = super.available();
if(abytes <= 0) return abytes;
_numrows = _ary.rpc(_chkidx-1);
_rid = 0;
}
StringBuilder sb = new StringBuilder();
boolean f = true;
for(Column c:_ary._cols){
if(f) f = false; else sb.append(',');
if(!_ary.isNA(_ab, _rid, c)){
if(c.isEnum()) sb.append('"' + c._domain[(int)_ary.data(_ab, _rid, c)] + '"');
else if(!c.isFloat()) sb.append(_ary.data(_ab, _rid, c));
else sb.append(_ary.datad(_ab,_rid,c));
}
}
sb.append('\n');
_currentLine = sb.toString().getBytes();
}
<MASK>_i = 0;</MASK>
return _currentLine.length - _i;
}" |
Inversion-Mutation | megadiff | "@Override
public void write(Cluster cluster) throws IOException {
StringBuilder line = new StringBuilder();
line.append(createNode(String.valueOf(cluster.getId())));
List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId());
if (points != null) {
for (WeightedVectorWritable point : points) {
Vector theVec = point.getVector();
String vecStr;
if (theVec instanceof NamedVector) {
vecStr = ((NamedVector) theVec).getName();
line.append(createNode(vecStr));
} else {
vecStr = theVec.asFormatString();
//do some basic manipulations for display
vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_");
line.append(createNode(vecStr));
}
line.append(createEdge(String.valueOf(cluster.getId()), vecStr));
}
}
getWriter().append(line).append("\n");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "write" | "@Override
public void write(Cluster cluster) throws IOException {
StringBuilder line = new StringBuilder();
line.append(createNode(String.valueOf(cluster.getId())));
List<WeightedVectorWritable> points = getClusterIdToPoints().get(cluster.getId());
if (points != null) {
for (WeightedVectorWritable point : points) {
Vector theVec = point.getVector();
String vecStr;
if (theVec instanceof NamedVector) {
vecStr = ((NamedVector) theVec).getName();
line.append(createNode(vecStr));
} else {
vecStr = theVec.asFormatString();
//do some basic manipulations for display
vecStr = VEC_PATTERN.matcher(vecStr).replaceAll("_");
line.append(createNode(vecStr));
}
line.append(createEdge(String.valueOf(cluster.getId()), vecStr));
}
<MASK>getWriter().append(line).append("\n");</MASK>
}
}" |
Inversion-Mutation | megadiff | "public void childAdded(final TaskChild child, final boolean userThread) throws InvalidTransactionStateException {
assert ! holdsLock(this);
int state;
synchronized (this) {
state = this.state;
if (stateIsIn(state, STATE_EXECUTE_WAIT, STATE_EXECUTE)) {
children.add(child);
unfinishedChildren++;
unterminatedChildren++;
unvalidatedChildren++;
if (userThread) state |= FLAG_USER_THREAD;
state = transition(state);
this.state = state & PERSISTENT_STATE;
} else {
if (userThread) {
throw new IllegalStateException("Dependent may not be added at this point");
} else {
// todo log and ignore...
return;
}
}
}
executeTasks(state);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "childAdded" | "public void childAdded(final TaskChild child, final boolean userThread) throws InvalidTransactionStateException {
assert ! holdsLock(this);
int state;
synchronized (this) {
<MASK>children.add(child);</MASK>
state = this.state;
if (stateIsIn(state, STATE_EXECUTE_WAIT, STATE_EXECUTE)) {
unfinishedChildren++;
unterminatedChildren++;
unvalidatedChildren++;
if (userThread) state |= FLAG_USER_THREAD;
state = transition(state);
this.state = state & PERSISTENT_STATE;
} else {
if (userThread) {
throw new IllegalStateException("Dependent may not be added at this point");
} else {
// todo log and ignore...
return;
}
}
}
executeTasks(state);
}" |
Inversion-Mutation | megadiff | "public void join(Player player) {
if (player.hasPermission("deathswap.join")) {
String name = player.getName();
if (!plugin.game.contains(name) && !plugin.lobby.contains(name)) {
plugin.utility.message("You joined the game!", player);
plugin.lobby.add(name);
plugin.utility.broadcastLobby(name + " joined the game!");
plugin.utility.teleport(player, 0);
plugin.utility.checkForStart();
} else {
plugin.utility.message("You are already in a game!", player);
}
} else {
player.sendMessage(ChatColor.RED + "You do not have permission to do that!");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "join" | "public void join(Player player) {
if (player.hasPermission("deathswap.join")) {
String name = player.getName();
if (!plugin.game.contains(name) && !plugin.lobby.contains(name)) {
plugin.utility.message("You joined the game!", player);
<MASK>plugin.utility.broadcastLobby(name + " joined the game!");</MASK>
plugin.lobby.add(name);
plugin.utility.teleport(player, 0);
plugin.utility.checkForStart();
} else {
plugin.utility.message("You are already in a game!", player);
}
} else {
player.sendMessage(ChatColor.RED + "You do not have permission to do that!");
}
}" |
Inversion-Mutation | megadiff | "public PactProgram(File jarFile, String className, String... args)
throws ProgramInvocationException {
this.jarFile = jarFile;
this.args = args;
this.assemblerClass = getPactAssemblerFromJar(jarFile, className);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PactProgram" | "public PactProgram(File jarFile, String className, String... args)
throws ProgramInvocationException {
<MASK>this.assemblerClass = getPactAssemblerFromJar(jarFile, className);</MASK>
this.jarFile = jarFile;
this.args = args;
}" |
Inversion-Mutation | megadiff | "public boolean performAction() {
NewSearchUI.activateSearchResultView();
NewSearchUI.runQueryInBackground(getSearchQuery());
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "performAction" | "public boolean performAction() {
<MASK>NewSearchUI.runQueryInBackground(getSearchQuery());</MASK>
NewSearchUI.activateSearchResultView();
return true;
}" |
Inversion-Mutation | megadiff | "FieldEnumerator(Field f) throws VisADException, RemoteException {
field = f;
if (field.getDomainSet() == null) {
throw new FieldException("FieldImplEnumerator: DomainSet undefined");
}
index = new int[1];
index[0] = 0;
dimension = field.getDomainSet().getDimension();
type = ((FunctionType) field.getType()).getDomain();
types = new RealType[dimension];
for (int j=0; j<dimension; j++) {
types[j] = (RealType) type.getComponent(j);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "FieldEnumerator" | "FieldEnumerator(Field f) throws VisADException, RemoteException {
if (field.getDomainSet() == null) {
throw new FieldException("FieldImplEnumerator: DomainSet undefined");
}
<MASK>field = f;</MASK>
index = new int[1];
index[0] = 0;
dimension = field.getDomainSet().getDimension();
type = ((FunctionType) field.getType()).getDomain();
types = new RealType[dimension];
for (int j=0; j<dimension; j++) {
types[j] = (RealType) type.getComponent(j);
}
}" |
Inversion-Mutation | megadiff | "@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(resultCode, requestCode, data);
if (resultCode == Activity.RESULT_FIRST_USER && requestCode == SETTINGS_ACTIVITY) {
if (data.getExtras().getBoolean("Exit", false)) {
exit();
} else {
FragmentsAvailable newFragment = (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay");
changeCurrentFragment(newFragment, null, true);
selectMenu(newFragment);
}
}
else if (requestCode == callActivity) {
boolean callTransfer = data == null ? false : data.getBooleanExtra("Transfer", false);
if (LinphoneManager.getLc().getCallsNb() > 0) {
initInCallMenuLayout(callTransfer);
} else {
resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onActivityResult" | "@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(resultCode, requestCode, data);
if (resultCode == Activity.RESULT_FIRST_USER && requestCode == SETTINGS_ACTIVITY) {
if (data.getExtras().getBoolean("Exit", false)) {
exit();
} else {
FragmentsAvailable newFragment = (FragmentsAvailable) data.getExtras().getSerializable("FragmentToDisplay");
<MASK>selectMenu(newFragment);</MASK>
changeCurrentFragment(newFragment, null, true);
}
}
else if (requestCode == callActivity) {
boolean callTransfer = data == null ? false : data.getBooleanExtra("Transfer", false);
if (LinphoneManager.getLc().getCallsNb() > 0) {
initInCallMenuLayout(callTransfer);
} else {
resetClassicMenuLayoutAndGoBackToCallIfStillRunning();
}
}
}" |
Inversion-Mutation | megadiff | "public void doCreateTables(TransactionContext c) throws SQLException, IOException {
Statement s = null;
try {
// Check to see if the table already exists. If it does, then don't
// log warnings during startup.
// Need to run the scripts anyways since they may contain ALTER
// statements that upgrade a previous version
// of the table
boolean alreadyExists = false;
ResultSet rs = null;
try {
rs = c.getConnection().getMetaData().getTables(null, null, this.statements.getFullMessageTableName(),
new String[] { "TABLE" });
alreadyExists = rs.next();
} catch (Throwable ignore) {
} finally {
close(rs);
}
s = c.getConnection().createStatement();
String[] createStatments = this.statements.getCreateSchemaStatements();
for (int i = 0; i < createStatments.length; i++) {
// This will fail usually since the tables will be
// created already.
try {
LOG.debug("Executing SQL: " + createStatments[i]);
s.execute(createStatments[i]);
} catch (SQLException e) {
if (alreadyExists) {
LOG.debug("Could not create JDBC tables; The message table already existed." + " Failure was: "
+ createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
+ " Vendor code: " + e.getErrorCode());
} else {
LOG.warn("Could not create JDBC tables; they could already exist." + " Failure was: "
+ createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
+ " Vendor code: " + e.getErrorCode());
JDBCPersistenceAdapter.log("Failure details: ", e);
}
}
}
c.getConnection().commit();
} finally {
try {
s.close();
} catch (Throwable e) {
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doCreateTables" | "public void doCreateTables(TransactionContext c) throws SQLException, IOException {
Statement s = null;
try {
// Check to see if the table already exists. If it does, then don't
// log warnings during startup.
// Need to run the scripts anyways since they may contain ALTER
// statements that upgrade a previous version
// of the table
boolean alreadyExists = false;
ResultSet rs = null;
try {
rs = c.getConnection().getMetaData().getTables(null, null, this.statements.getFullMessageTableName(),
new String[] { "TABLE" });
alreadyExists = rs.next();
} catch (Throwable ignore) {
} finally {
close(rs);
}
s = c.getConnection().createStatement();
String[] createStatments = this.statements.getCreateSchemaStatements();
for (int i = 0; i < createStatments.length; i++) {
// This will fail usually since the tables will be
// created already.
try {
LOG.debug("Executing SQL: " + createStatments[i]);
s.execute(createStatments[i]);
} catch (SQLException e) {
if (alreadyExists) {
LOG.debug("Could not create JDBC tables; The message table already existed." + " Failure was: "
+ createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
+ " Vendor code: " + e.getErrorCode());
} else {
LOG.warn("Could not create JDBC tables; they could already exist." + " Failure was: "
+ createStatments[i] + " Message: " + e.getMessage() + " SQLState: " + e.getSQLState()
+ " Vendor code: " + e.getErrorCode());
JDBCPersistenceAdapter.log("Failure details: ", e);
}
}
<MASK>c.getConnection().commit();</MASK>
}
} finally {
try {
s.close();
} catch (Throwable e) {
}
}
}" |
Inversion-Mutation | megadiff | "public void interruped(String name) {
if (players.size() <= 1) {
return;
}
Iterator<Player> iter = players.iterator();
Player thePlayer = null;
Integer lowestScore = null;
while (iter.hasNext()) {
Player player = iter.next();
if (player.getName().equals(name)) {
thePlayer = player;
} else {
if (lowestScore == null) {
lowestScore = new Integer(player.getPoints());
} else {
lowestScore = Math.min(lowestScore, player.getPoints());
}
}
}
if ((thePlayer == null) || (lowestScore == null)) {
// shouldn't happen if name is valid
return;
}
lowestScore -= 1;
thePlayer.setPoints(lowestScore, "interrupted");
this.stopAndDumpStats("interrupted", getSortedScores());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "interruped" | "public void interruped(String name) {
if (players.size() <= 1) {
return;
}
Iterator<Player> iter = players.iterator();
Player thePlayer = null;
Integer lowestScore = null;
while (iter.hasNext()) {
Player player = iter.next();
if (player.getName().equals(name)) {
thePlayer = player;
} else {
if (lowestScore == null) {
lowestScore = new Integer(player.getPoints());
} else {
<MASK>lowestScore -= 1;</MASK>
lowestScore = Math.min(lowestScore, player.getPoints());
}
}
}
if ((thePlayer == null) || (lowestScore == null)) {
// shouldn't happen if name is valid
return;
}
thePlayer.setPoints(lowestScore, "interrupted");
this.stopAndDumpStats("interrupted", getSortedScores());
}" |
Inversion-Mutation | megadiff | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
context.getSession().quit();
context.sendResponse("221 Bye");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute" | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
<MASK>context.sendResponse("221 Bye");</MASK>
context.getSession().quit();
}" |
Inversion-Mutation | megadiff | "public SwingController(final PluginInfo pluginInfo,
final IdentityManager identityManager,
final PluginManager pluginManager,
final ActionManager actionManager) {
super();
this.pluginInfo = pluginInfo;
this.identityManager = identityManager;
this.actionManager = actionManager;
this.pluginManager = pluginManager;
globalConfig = identityManager.getGlobalConfiguration();
globalIdentity = identityManager.getGlobalConfigIdentity();
addonIdentity = identityManager.getGlobalAddonIdentity();
apple = new Apple(getGlobalConfig());
iconManager = new IconManager(globalConfig);
prefsComponentFactory = new PrefsComponentFactory(this);
dialogManager = new DialogManager(this);
setAntiAlias();
windows = new ArrayList<java.awt.Window>();
registerCommand(new ServerSettings(), ServerSettings.INFO);
registerCommand(new ChannelSettings(), ChannelSettings.INFO);
registerCommand(new Input(windowFactory), Input.INFO);
registerCommand(new PopOutCommand(this), PopOutCommand.INFO);
registerCommand(new PopInCommand(this), PopInCommand.INFO);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "SwingController" | "public SwingController(final PluginInfo pluginInfo,
final IdentityManager identityManager,
final PluginManager pluginManager,
final ActionManager actionManager) {
super();
this.pluginInfo = pluginInfo;
this.identityManager = identityManager;
this.actionManager = actionManager;
this.pluginManager = pluginManager;
<MASK>apple = new Apple(getGlobalConfig());</MASK>
globalConfig = identityManager.getGlobalConfiguration();
globalIdentity = identityManager.getGlobalConfigIdentity();
addonIdentity = identityManager.getGlobalAddonIdentity();
iconManager = new IconManager(globalConfig);
prefsComponentFactory = new PrefsComponentFactory(this);
dialogManager = new DialogManager(this);
setAntiAlias();
windows = new ArrayList<java.awt.Window>();
registerCommand(new ServerSettings(), ServerSettings.INFO);
registerCommand(new ChannelSettings(), ChannelSettings.INFO);
registerCommand(new Input(windowFactory), Input.INFO);
registerCommand(new PopOutCommand(this), PopOutCommand.INFO);
registerCommand(new PopInCommand(this), PopInCommand.INFO);
}" |
Inversion-Mutation | megadiff | "@Override
public PlsSolution[] run(PlsSolution plsSol, long timeToFinish, Random rand) {
VrpPlsSolution solAndStuff = (VrpPlsSolution)plsSol;
long startTime = System.currentTimeMillis();
VrpSolution sol = solAndStuff.getSolution();
VrpProblem problem = sol.getProblem();
LnsRelaxer relaxer = new LnsRelaxer(solAndStuff.getRelaxationRandomness(), problem.getMaxDistance(), rand);
VrpSearcher solver = new VrpSearcher(problem);
//if we've been sent neighborhoods to check, check them first
if (helperData != null) {
LOG.info("Has helper neighborhoods!");
List<List<Integer>> neighborhoods = helperData.getNeighborhoods();
int numSuccessful = 0;
long helperStartTime = System.currentTimeMillis();
double beforeSolCost = sol.getToursCost();
for (List<Integer> neighborhood : neighborhoods) {
VrpCpStats stats = new VrpCpStats();
VrpSolution partialSol = new VrpSolution(relaxer.buildRoutesWithoutCusts(sol.getRoutes(), neighborhood), neighborhood, problem);
VrpSolution newSol = solver.solve(partialSol, sol.getToursCost(), solAndStuff.getMaxDiscrepancies(), stats, true);
if (newSol != null && Math.abs(newSol.getToursCost() - sol.getToursCost()) > .001) {
extraData.addNeighborhood(partialSol);
sol = newSol;
solAndStuff.setSolution(sol);
numSuccessful++;
}
}
long helperFinishTime = System.currentTimeMillis();
int helperTime = (int)(helperFinishTime - helperStartTime);
extraData.setHelperStats(numSuccessful, neighborhoods.size(), beforeSolCost - sol.getToursCost(), helperTime);
LOG.info("Helper neighborhoods: " + numSuccessful + " successful / " + neighborhoods.size() +
". Took " + helperTime + " ms");
}
int numTries = 0;
int numSuccesses = 0;
double beforeBestCost = sol.getToursCost();
long regStartTime = System.currentTimeMillis();
outer:
while (true) {
for (int n = solAndStuff.getCurEscalation(); n <= solAndStuff.getMaxEscalation(); n++) {
for (int i = solAndStuff.getCurIteration(); i < solAndStuff.getMaxIterations(); i++) {
if (System.currentTimeMillis() >= timeToFinish) {
break outer;
}
VrpCpStats stats = new VrpCpStats();
VrpSolution partialSol = relaxer.relaxShaw(sol, n, -1);
VrpSolution newSol = solver.solve(partialSol, sol.getToursCost(), solAndStuff.getMaxDiscrepancies(), stats, true);
if (newSol != null && Math.abs(newSol.getToursCost() - sol.getToursCost()) > .001) {
extraData.addNeighborhood(partialSol);
sol = newSol;
solAndStuff.setSolution(sol);
i = 0;
numSuccesses++;
}
solAndStuff.setCurEscalation(n);
solAndStuff.setCurIteration(i);
numTries++;
}
}
//LOG.info("Starting new search");
solAndStuff.setCurEscalation(1);
solAndStuff.setCurIteration(0);
}
long regEndTime = System.currentTimeMillis();
int regTime = (int)(regEndTime - regStartTime);
extraData.setRegularStats(numSuccesses, numTries, beforeBestCost - sol.getToursCost(), regTime);
long endTime = System.currentTimeMillis();
LOG.info("VrpLnsRunner took " + (endTime - startTime) + " ms");
return new PlsSolution[] {solAndStuff};
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "@Override
public PlsSolution[] run(PlsSolution plsSol, long timeToFinish, Random rand) {
VrpPlsSolution solAndStuff = (VrpPlsSolution)plsSol;
long startTime = System.currentTimeMillis();
VrpSolution sol = solAndStuff.getSolution();
VrpProblem problem = sol.getProblem();
LnsRelaxer relaxer = new LnsRelaxer(solAndStuff.getRelaxationRandomness(), problem.getMaxDistance(), rand);
VrpSearcher solver = new VrpSearcher(problem);
//if we've been sent neighborhoods to check, check them first
if (helperData != null) {
LOG.info("Has helper neighborhoods!");
List<List<Integer>> neighborhoods = helperData.getNeighborhoods();
int numSuccessful = 0;
long helperStartTime = System.currentTimeMillis();
double beforeSolCost = sol.getToursCost();
for (List<Integer> neighborhood : neighborhoods) {
VrpCpStats stats = new VrpCpStats();
VrpSolution partialSol = new VrpSolution(relaxer.buildRoutesWithoutCusts(sol.getRoutes(), neighborhood), neighborhood, problem);
VrpSolution newSol = solver.solve(partialSol, sol.getToursCost(), solAndStuff.getMaxDiscrepancies(), stats, true);
if (newSol != null && Math.abs(newSol.getToursCost() - sol.getToursCost()) > .001) {
extraData.addNeighborhood(partialSol);
sol = newSol;
solAndStuff.setSolution(sol);
numSuccessful++;
}
}
long helperFinishTime = System.currentTimeMillis();
int helperTime = (int)(helperFinishTime - helperStartTime);
extraData.setHelperStats(numSuccessful, neighborhoods.size(), beforeSolCost - sol.getToursCost(), helperTime);
LOG.info("Helper neighborhoods: " + numSuccessful + " successful / " + neighborhoods.size() +
". Took " + helperTime + " ms");
}
int numTries = 0;
int numSuccesses = 0;
double beforeBestCost = sol.getToursCost();
long regStartTime = System.currentTimeMillis();
outer:
while (true) {
for (int n = solAndStuff.getCurEscalation(); n <= solAndStuff.getMaxEscalation(); n++) {
for (int i = solAndStuff.getCurIteration(); i < solAndStuff.getMaxIterations(); i++) {
if (System.currentTimeMillis() >= timeToFinish) {
break outer;
}
VrpCpStats stats = new VrpCpStats();
VrpSolution partialSol = relaxer.relaxShaw(sol, n, -1);
VrpSolution newSol = solver.solve(partialSol, sol.getToursCost(), solAndStuff.getMaxDiscrepancies(), stats, true);
if (newSol != null && Math.abs(newSol.getToursCost() - sol.getToursCost()) > .001) {
extraData.addNeighborhood(partialSol);
sol = newSol;
solAndStuff.setSolution(sol);
i = 0;
numSuccesses++;
}
solAndStuff.setCurEscalation(n);
solAndStuff.setCurIteration(i);
}
}
//LOG.info("Starting new search");
solAndStuff.setCurEscalation(1);
solAndStuff.setCurIteration(0);
<MASK>numTries++;</MASK>
}
long regEndTime = System.currentTimeMillis();
int regTime = (int)(regEndTime - regStartTime);
extraData.setRegularStats(numSuccesses, numTries, beforeBestCost - sol.getToursCost(), regTime);
long endTime = System.currentTimeMillis();
LOG.info("VrpLnsRunner took " + (endTime - startTime) + " ms");
return new PlsSolution[] {solAndStuff};
}" |
Inversion-Mutation | megadiff | "public GenericJDBCDataModel(Properties props) throws TasteException {
super(AbstractJDBCComponent.lookupDataSource(props.getProperty(DATA_SOURCE_KEY)),
props.getProperty(GET_PREFERENCE_SQL_KEY),
props.getProperty(GET_PREFERENCE_TIME_SQL_KEY),
props.getProperty(GET_USER_SQL_KEY),
props.getProperty(GET_ALL_USERS_SQL_KEY),
props.getProperty(GET_NUM_ITEMS_SQL_KEY),
props.getProperty(GET_NUM_USERS_SQL_KEY),
props.getProperty(SET_PREFERENCE_SQL_KEY),
props.getProperty(REMOVE_PREFERENCE_SQL_KEY),
props.getProperty(GET_USERS_SQL_KEY),
props.getProperty(GET_ITEMS_SQL_KEY),
props.getProperty(GET_PREFS_FOR_ITEM_SQL_KEY),
props.getProperty(GET_NUM_PREFERENCE_FOR_ITEM_KEY),
props.getProperty(GET_NUM_PREFERENCE_FOR_ITEMS_KEY),
props.getProperty(GET_MAX_PREFERENCE_KEY),
props.getProperty(GET_MIN_PREFERENCE_KEY));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "GenericJDBCDataModel" | "public GenericJDBCDataModel(Properties props) throws TasteException {
super(AbstractJDBCComponent.lookupDataSource(props.getProperty(DATA_SOURCE_KEY)),
props.getProperty(GET_PREFERENCE_SQL_KEY),
props.getProperty(GET_PREFERENCE_TIME_SQL_KEY),
props.getProperty(GET_USER_SQL_KEY),
props.getProperty(GET_ALL_USERS_SQL_KEY),
<MASK>props.getProperty(GET_NUM_USERS_SQL_KEY),</MASK>
props.getProperty(GET_NUM_ITEMS_SQL_KEY),
props.getProperty(SET_PREFERENCE_SQL_KEY),
props.getProperty(REMOVE_PREFERENCE_SQL_KEY),
props.getProperty(GET_USERS_SQL_KEY),
props.getProperty(GET_ITEMS_SQL_KEY),
props.getProperty(GET_PREFS_FOR_ITEM_SQL_KEY),
props.getProperty(GET_NUM_PREFERENCE_FOR_ITEM_KEY),
props.getProperty(GET_NUM_PREFERENCE_FOR_ITEMS_KEY),
props.getProperty(GET_MAX_PREFERENCE_KEY),
props.getProperty(GET_MIN_PREFERENCE_KEY));
}" |
Inversion-Mutation | megadiff | "protected void displayErrorMessage( String message )
{
setMessage( null, DialogPage.NONE );
setErrorMessage( message );
setPageComplete( message == null );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "displayErrorMessage" | "protected void displayErrorMessage( String message )
{
<MASK>setErrorMessage( message );</MASK>
setMessage( null, DialogPage.NONE );
setPageComplete( message == null );
}" |
Inversion-Mutation | megadiff | "public boolean visit(QualifiedName node) {
if (!isActive()) {
return false;
}
if (hasErrors()) {
return true;
}
IBinding binding = node.resolveBinding();
switch (binding.getKind()) {
case IBinding.TYPE:
node.getName().accept(this);
break;
case IBinding.VARIABLE:
SimpleName fieldName= node.getName();
IVariableBinding fieldBinding= (IVariableBinding) fieldName.resolveBinding();
ITypeBinding declaringTypeBinding= fieldBinding.getDeclaringClass();
String fieldId = fieldName.getIdentifier();
if (Modifier.isStatic(fieldBinding.getModifiers())) {
push(new PushStaticFieldVariable(fieldId, getTypeName(declaringTypeBinding), fCounter));
} else {
if (declaringTypeBinding == null) {
push(new PushArrayLength(fCounter));
} else {
push(new PushFieldVariable(fieldId, getTypeSignature(declaringTypeBinding), fCounter));
}
node.getQualifier().accept(this);
}
storeInstruction();
break;
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visit" | "public boolean visit(QualifiedName node) {
if (!isActive()) {
return false;
}
if (hasErrors()) {
return true;
}
IBinding binding = node.resolveBinding();
switch (binding.getKind()) {
case IBinding.TYPE:
node.getName().accept(this);
break;
case IBinding.VARIABLE:
SimpleName fieldName= node.getName();
IVariableBinding fieldBinding= (IVariableBinding) fieldName.resolveBinding();
ITypeBinding declaringTypeBinding= fieldBinding.getDeclaringClass();
String fieldId = fieldName.getIdentifier();
if (Modifier.isStatic(fieldBinding.getModifiers())) {
push(new PushStaticFieldVariable(fieldId, getTypeName(declaringTypeBinding), fCounter));
<MASK>storeInstruction();</MASK>
} else {
if (declaringTypeBinding == null) {
push(new PushArrayLength(fCounter));
} else {
push(new PushFieldVariable(fieldId, getTypeSignature(declaringTypeBinding), fCounter));
}
node.getQualifier().accept(this);
}
break;
}
return false;
}" |
Inversion-Mutation | megadiff | "private void notifyDownloadCompleted(
State state, int finalStatus, String errorMsg, int numFailed) {
notifyThroughDatabase(state, finalStatus, errorMsg, numFailed);
if (Downloads.Impl.isStatusCompleted(finalStatus)) {
mInfo.sendIntentIfRequested();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "notifyDownloadCompleted" | "private void notifyDownloadCompleted(
State state, int finalStatus, String errorMsg, int numFailed) {
if (Downloads.Impl.isStatusCompleted(finalStatus)) {
mInfo.sendIntentIfRequested();
}
<MASK>notifyThroughDatabase(state, finalStatus, errorMsg, numFailed);</MASK>
}" |
Inversion-Mutation | megadiff | "@Override
protected void configure() {
DynamicMap.mapOf(binder(), PROJECT_KIND);
DynamicMap.mapOf(binder(), DASHBOARD_KIND);
get(PROJECT_KIND).to(GetProject.class);
get(PROJECT_KIND, "description").to(GetDescription.class);
put(PROJECT_KIND, "description").to(SetDescription.class);
delete(PROJECT_KIND, "description").to(SetDescription.class);
get(PROJECT_KIND, "parent").to(GetParent.class);
put(PROJECT_KIND, "parent").to(SetParent.class);
get(DASHBOARD_KIND).to(GetDashboard.class);
put(DASHBOARD_KIND).to(SetDashboard.class);
delete(DASHBOARD_KIND).to(DeleteDashboard.class);
child(PROJECT_KIND, "dashboards").to(DashboardsCollection.class);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configure" | "@Override
protected void configure() {
DynamicMap.mapOf(binder(), PROJECT_KIND);
DynamicMap.mapOf(binder(), DASHBOARD_KIND);
get(PROJECT_KIND).to(GetProject.class);
get(PROJECT_KIND, "description").to(GetDescription.class);
put(PROJECT_KIND, "description").to(SetDescription.class);
delete(PROJECT_KIND, "description").to(SetDescription.class);
get(PROJECT_KIND, "parent").to(GetParent.class);
put(PROJECT_KIND, "parent").to(SetParent.class);
<MASK>child(PROJECT_KIND, "dashboards").to(DashboardsCollection.class);</MASK>
get(DASHBOARD_KIND).to(GetDashboard.class);
put(DASHBOARD_KIND).to(SetDashboard.class);
delete(DASHBOARD_KIND).to(DeleteDashboard.class);
}" |
Inversion-Mutation | megadiff | "public void popupDismissed(boolean topPopupOnly) {
initializePopup();
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mModule.showPopup(mPopup);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "popupDismissed" | "public void popupDismissed(boolean topPopupOnly) {
// if the 2nd level popup gets dismissed
if (mPopupStatus == POPUP_SECOND_LEVEL) {
<MASK>initializePopup();</MASK>
mPopupStatus = POPUP_FIRST_LEVEL;
if (topPopupOnly) mModule.showPopup(mPopup);
}
}" |
Inversion-Mutation | megadiff | "public void build() throws Exception {
names = new Hashtable();
int access = superclass.getModifiers();
if ((access & Modifier.FINAL) != 0) {
throw new InstantiationException("can't subclass final class");
}
access = Modifier.PUBLIC | Modifier.SYNCHRONIZED;
classfile = new ClassFile(myClass, mapClass(superclass), access);
addProxy();
addConstructors(superclass);
classfile.addInterface("org/python/core/PyProxy");
Hashtable seenmethods = new Hashtable();
addMethods(superclass, seenmethods);
for (int i=0; i<interfaces.length; i++) {
if (interfaces[i].isAssignableFrom(superclass)) {
Py.writeWarning("compiler",
"discarding redundant interface: "+
interfaces[i].getName());
continue;
}
classfile.addInterface(mapClass(interfaces[i]));
addMethods(interfaces[i], seenmethods);
}
doConstants();
addClassDictInit();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "build" | "public void build() throws Exception {
names = new Hashtable();
int access = superclass.getModifiers();
if ((access & Modifier.FINAL) != 0) {
throw new InstantiationException("can't subclass final class");
}
access = Modifier.PUBLIC | Modifier.SYNCHRONIZED;
classfile = new ClassFile(myClass, mapClass(superclass), access);
addProxy();
addConstructors(superclass);
classfile.addInterface("org/python/core/PyProxy");
Hashtable seenmethods = new Hashtable();
for (int i=0; i<interfaces.length; i++) {
if (interfaces[i].isAssignableFrom(superclass)) {
Py.writeWarning("compiler",
"discarding redundant interface: "+
interfaces[i].getName());
continue;
}
classfile.addInterface(mapClass(interfaces[i]));
addMethods(interfaces[i], seenmethods);
}
<MASK>addMethods(superclass, seenmethods);</MASK>
doConstants();
addClassDictInit();
}" |
Inversion-Mutation | megadiff | "protected void parseLine(String nextLine) throws ReaderException {
Scanner scanner = new Scanner(nextLine.trim());
// allow any whitespace
String next = scanner.next();
if (next.isEmpty()) {
return;
}
if (next.equals("WorkflowBundle")) {
level = Level.WorkflowBundle;
String name = parseName(scanner);
wb.setName(name);
return;
}
if (next.equals("MainWorkflow")) {
mainWorkflow = parseName(scanner);
return;
}
if (next.equals("Workflow")) {
level = Level.Workflow;
workflow = new Workflow();
String workflowName = parseName(scanner);
workflow.setName(workflowName);
wb.getWorkflows().add(workflow);
if (workflowName.equals(mainWorkflow)) {
wb.setMainWorkflow(workflow);
}
return;
}
if (next.equals("In") || next.equals("Out")) {
boolean in = next.equals("In");
String portName = parseName(scanner);
switch (level) {
case Workflow:
if (in) {
new InputWorkflowPort(workflow, portName);
} else {
new OutputWorkflowPort(workflow, portName);
}
break;
case Processor:
if (in) {
new InputProcessorPort(processor, portName);
} else {
new OutputProcessorPort(processor, portName);
}
break;
case Activity:
if (in) {
new InputActivityPort(activity, portName);
} else {
new OutputActivityPort(activity, portName);
}
break;
default:
throw new ReaderException("Unexpected " + next + " at level "
+ level);
}
return;
}
if (next.equals("Processor")
&& (level == Level.Workflow || level == Level.Processor)) {
level = Level.Processor;
processor = new Processor();
String processorName = parseName(scanner);
processor.setName(processorName);
processor.setParent(workflow);
workflow.getProcessors().add(processor);
return;
}
if (next.equals("Links")) {
level = Level.Links;
processor = null;
return;
}
if (next.equals("Controls")) {
level = Level.Controls;
return;
}
if (next.equals("block")) {
Matcher blockMatcher = blockPattern.matcher(nextLine);
blockMatcher.find();
String block = blockMatcher.group(1);
String untilFinish = blockMatcher.group(2);
Processor blockProc = workflow.getProcessors().getByName(block);
Processor untilFinishedProc = workflow.getProcessors().getByName(
untilFinish);
new BlockingControlLink(blockProc, untilFinishedProc);
}
if (next.startsWith("'") && level.equals(Level.Links)) {
Matcher linkMatcher = linkPattern.matcher(nextLine);
linkMatcher.find();
String firstLink = linkMatcher.group(1);
String secondLink = linkMatcher.group(2);
SenderPort senderPort;
if (firstLink.contains(":")) {
String[] procPort = firstLink.split(":");
Processor proc = workflow.getProcessors()
.getByName(procPort[0]);
senderPort = proc.getOutputPorts().getByName(procPort[1]);
} else {
senderPort = workflow.getInputPorts().getByName(firstLink);
}
ReceiverPort receiverPort;
if (secondLink.contains(":")) {
String[] procPort = secondLink.split(":");
Processor proc = workflow.getProcessors()
.getByName(procPort[0]);
receiverPort = proc.getInputPorts().getByName(procPort[1]);
} else {
receiverPort = workflow.getOutputPorts().getByName(secondLink);
}
new DataLink(workflow, senderPort, receiverPort);
return;
}
if (next.equals("MainProfile")) {
mainProfile = parseName(scanner);
return;
}
if (next.equals("Profile")) {
level = Level.Profile;
profile = new Profile();
String profileName = parseName(scanner);
profile.setName(profileName);
wb.getProfiles().add(profile);
if (profileName.equals(mainProfile)) {
wb.setMainProfile(profile);
}
return;
}
if (next.equals("Activity")
&& (level == Level.Profile || level == Level.Activity)) {
level = Level.Activity;
activity = new Activity();
String activityName = parseName(scanner);
activity.setName(activityName);
profile.getActivities().add(activity);
return;
}
if (next.equals("Type")) {
URI uri = URI.create(nextLine.split("[<>]")[1]);
if (level == Level.Activity) {
activity.setConfigurableType(uri);
} else if (level == Level.Configuration) {
configuration.getPropertyResource().setTypeURI(uri);
}
return;
}
if (next.equals("ProcessorBinding")) {
level = Level.ProcessorBinding;
processorBinding = new ProcessorBinding();
String bindingName = parseName(scanner);
processorBinding.setName(bindingName);
profile.getProcessorBindings().add(processorBinding);
return;
}
if (next.equals("Activity") && level == Level.ProcessorBinding) {
String activityName = parseName(scanner);
Activity boundActivity = profile.getActivities().getByName(
activityName);
processorBinding.setBoundActivity(boundActivity);
return;
}
if (next.equals("Processor") && level == Level.ProcessorBinding) {
String[] wfProcName = parseName(scanner).split(":");
Workflow wf = wb.getWorkflows().getByName(wfProcName[0]);
Processor boundProcessor = wf.getProcessors().getByName(
wfProcName[1]);
processorBinding.setBoundProcessor(boundProcessor);
return;
}
if (next.equals("InputPortBindings")) {
level = Level.InputPortBindings;
return;
}
if (next.equals("OutputPortBindings")) {
level = Level.OutputPortBindings;
return;
}
if (next.startsWith("'")
&& (level == Level.InputPortBindings || level == Level.OutputPortBindings)) {
Matcher linkMatcher = linkPattern.matcher(nextLine);
linkMatcher.find();
String firstLink = linkMatcher.group(1);
String secondLink = linkMatcher.group(2);
if (level == Level.InputPortBindings) {
InputProcessorPort processorPort = processorBinding
.getBoundProcessor().getInputPorts()
.getByName(firstLink);
InputActivityPort activityPort = processorBinding
.getBoundActivity().getInputPorts()
.getByName(secondLink);
new ProcessorInputPortBinding(processorBinding, processorPort,
activityPort);
} else {
OutputActivityPort activityPort = processorBinding
.getBoundActivity().getOutputPorts()
.getByName(firstLink);
OutputProcessorPort processorPort = processorBinding
.getBoundProcessor().getOutputPorts()
.getByName(secondLink);
new ProcessorOutputPortBinding(processorBinding, activityPort,
processorPort);
}
return;
}
if (next.equals("Configuration")) {
level = Level.Configuration;
configuration = new Configuration();
String configName = parseName(scanner);
configuration.setName(configName);
profile.getConfigurations().add(configuration);
return;
}
if (next.equals("Configures")) {
String configures = parseName(scanner);
if (configures.startsWith(ACTIVITY_SLASH)) {
String activityName = configures.substring(
ACTIVITY_SLASH.length(), configures.length());
activity = profile.getActivities().getByName(activityName);
configuration.setConfigures(activity);
return;
} else {
throw new UnsupportedOperationException("Unknown Configures "
+ configures);
}
}
if (next.equals("Property")) {
propertyUri = URI.create(nextLine.split("[<>]")[1]);
level = Level.Property;
return;
}
if (level == Level.Property) {
boolean finished = false;
String[] split = nextLine.split("'''", 3);
if (split.length == 1) {
largeString.append(split[0]);
largeString.append('\n');
} else if (next.startsWith("'''")) {
largeString = new StringBuffer();
largeString.append(split[1]);
if (split.length == 3) {
// It was a one-liner
finished = true;
} else {
largeString.append('\n');
}
} else {
largeString.append(split[0]);
// Assuming length is 2
finished = true;
}
if (finished) {
configuration.getPropertyResource().addPropertyAsString(
propertyUri, largeString.toString());
largeString = null;
propertyUri = null;
level = Level.Configuration;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "parseLine" | "protected void parseLine(String nextLine) throws ReaderException {
Scanner scanner = new Scanner(nextLine.trim());
// allow any whitespace
String next = scanner.next();
if (next.isEmpty()) {
return;
}
if (next.equals("WorkflowBundle")) {
level = Level.WorkflowBundle;
String name = parseName(scanner);
wb.setName(name);
return;
}
if (next.equals("MainWorkflow")) {
mainWorkflow = parseName(scanner);
return;
}
if (next.equals("Workflow")) {
level = Level.Workflow;
workflow = new Workflow();
String workflowName = parseName(scanner);
workflow.setName(workflowName);
wb.getWorkflows().add(workflow);
if (workflowName.equals(mainWorkflow)) {
wb.setMainWorkflow(workflow);
}
return;
}
if (next.equals("In") || next.equals("Out")) {
boolean in = next.equals("In");
String portName = parseName(scanner);
switch (level) {
case Workflow:
if (in) {
new InputWorkflowPort(workflow, portName);
} else {
new OutputWorkflowPort(workflow, portName);
}
break;
case Processor:
if (in) {
new InputProcessorPort(processor, portName);
} else {
new OutputProcessorPort(processor, portName);
}
break;
case Activity:
if (in) {
new InputActivityPort(activity, portName);
} else {
new OutputActivityPort(activity, portName);
}
break;
default:
throw new ReaderException("Unexpected " + next + " at level "
+ level);
}
return;
}
if (next.equals("Processor")
&& (level == Level.Workflow || level == Level.Processor)) {
level = Level.Processor;
processor = new Processor();
String processorName = parseName(scanner);
processor.setName(processorName);
processor.setParent(workflow);
workflow.getProcessors().add(processor);
return;
}
if (next.equals("Links")) {
level = Level.Links;
processor = null;
return;
}
if (next.equals("Controls")) {
level = Level.Controls;
return;
}
if (next.equals("block")) {
Matcher blockMatcher = blockPattern.matcher(nextLine);
blockMatcher.find();
String block = blockMatcher.group(1);
String untilFinish = blockMatcher.group(2);
Processor blockProc = workflow.getProcessors().getByName(block);
Processor untilFinishedProc = workflow.getProcessors().getByName(
untilFinish);
new BlockingControlLink(blockProc, untilFinishedProc);
}
if (next.startsWith("'") && level.equals(Level.Links)) {
Matcher linkMatcher = linkPattern.matcher(nextLine);
linkMatcher.find();
String firstLink = linkMatcher.group(1);
String secondLink = linkMatcher.group(2);
SenderPort senderPort;
if (firstLink.contains(":")) {
String[] procPort = firstLink.split(":");
Processor proc = workflow.getProcessors()
.getByName(procPort[0]);
senderPort = proc.getOutputPorts().getByName(procPort[1]);
} else {
senderPort = workflow.getInputPorts().getByName(firstLink);
}
ReceiverPort receiverPort;
if (secondLink.contains(":")) {
String[] procPort = secondLink.split(":");
Processor proc = workflow.getProcessors()
.getByName(procPort[0]);
receiverPort = proc.getInputPorts().getByName(procPort[1]);
} else {
receiverPort = workflow.getOutputPorts().getByName(secondLink);
}
new DataLink(workflow, senderPort, receiverPort);
return;
}
if (next.equals("MainProfile")) {
mainProfile = parseName(scanner);
return;
}
if (next.equals("Profile")) {
level = Level.Profile;
profile = new Profile();
String profileName = parseName(scanner);
profile.setName(profileName);
wb.getProfiles().add(profile);
if (profileName.equals(mainProfile)) {
wb.setMainProfile(profile);
}
return;
}
if (next.equals("Activity")
&& (level == Level.Profile || level == Level.Activity)) {
level = Level.Activity;
activity = new Activity();
String activityName = parseName(scanner);
activity.setName(activityName);
profile.getActivities().add(activity);
return;
}
if (next.equals("Type")) {
URI uri = URI.create(nextLine.split("[<>]")[1]);
if (level == Level.Activity) {
activity.setConfigurableType(uri);
} else if (level == Level.Configuration) {
configuration.getPropertyResource().setTypeURI(uri);
}
return;
}
if (next.equals("ProcessorBinding")) {
level = Level.ProcessorBinding;
processorBinding = new ProcessorBinding();
String bindingName = parseName(scanner);
processorBinding.setName(bindingName);
profile.getProcessorBindings().add(processorBinding);
return;
}
if (next.equals("Activity") && level == Level.ProcessorBinding) {
String activityName = parseName(scanner);
Activity boundActivity = profile.getActivities().getByName(
activityName);
processorBinding.setBoundActivity(boundActivity);
return;
}
if (next.equals("Processor") && level == Level.ProcessorBinding) {
String[] wfProcName = parseName(scanner).split(":");
Workflow wf = wb.getWorkflows().getByName(wfProcName[0]);
Processor boundProcessor = wf.getProcessors().getByName(
wfProcName[1]);
processorBinding.setBoundProcessor(boundProcessor);
return;
}
if (next.equals("InputPortBindings")) {
level = Level.InputPortBindings;
return;
}
if (next.equals("OutputPortBindings")) {
level = Level.OutputPortBindings;
return;
}
if (next.startsWith("'")
&& (level == Level.InputPortBindings || level == Level.OutputPortBindings)) {
Matcher linkMatcher = linkPattern.matcher(nextLine);
linkMatcher.find();
String firstLink = linkMatcher.group(1);
String secondLink = linkMatcher.group(2);
if (level == Level.InputPortBindings) {
InputProcessorPort processorPort = processorBinding
.getBoundProcessor().getInputPorts()
.getByName(firstLink);
InputActivityPort activityPort = processorBinding
.getBoundActivity().getInputPorts()
.getByName(secondLink);
new ProcessorInputPortBinding(processorBinding, processorPort,
activityPort);
} else {
OutputActivityPort activityPort = processorBinding
.getBoundActivity().getOutputPorts()
.getByName(firstLink);
OutputProcessorPort processorPort = processorBinding
.getBoundProcessor().getOutputPorts()
.getByName(secondLink);
new ProcessorOutputPortBinding(processorBinding, activityPort,
processorPort);
}
return;
}
if (next.equals("Configuration")) {
level = Level.Configuration;
configuration = new Configuration();
<MASK>profile.getConfigurations().add(configuration);</MASK>
String configName = parseName(scanner);
configuration.setName(configName);
return;
}
if (next.equals("Configures")) {
String configures = parseName(scanner);
if (configures.startsWith(ACTIVITY_SLASH)) {
String activityName = configures.substring(
ACTIVITY_SLASH.length(), configures.length());
activity = profile.getActivities().getByName(activityName);
configuration.setConfigures(activity);
return;
} else {
throw new UnsupportedOperationException("Unknown Configures "
+ configures);
}
}
if (next.equals("Property")) {
propertyUri = URI.create(nextLine.split("[<>]")[1]);
level = Level.Property;
return;
}
if (level == Level.Property) {
boolean finished = false;
String[] split = nextLine.split("'''", 3);
if (split.length == 1) {
largeString.append(split[0]);
largeString.append('\n');
} else if (next.startsWith("'''")) {
largeString = new StringBuffer();
largeString.append(split[1]);
if (split.length == 3) {
// It was a one-liner
finished = true;
} else {
largeString.append('\n');
}
} else {
largeString.append(split[0]);
// Assuming length is 2
finished = true;
}
if (finished) {
configuration.getPropertyResource().addPropertyAsString(
propertyUri, largeString.toString());
largeString = null;
propertyUri = null;
level = Level.Configuration;
}
}
}" |
Inversion-Mutation | megadiff | "public static Drawable getAvatarFromAddress(ContentResolver cr, String address, int width, int height) {
String[] projection = {Imps.Contacts.AVATAR_DATA};
String[] args = {address};
String query = "username LIKE ?";
Cursor cursor = cr.query(Imps.Contacts.CONTENT_URI,projection,
query, args, Imps.Contacts.DEFAULT_SORT_ORDER);
if (cursor.moveToFirst())
{
String hexData = cursor.getString(0);
cursor.close();
if (hexData.equals("NULL")) {
return null;
}
byte[] data = Hex.decode(hexData.substring(2, hexData.length() - 1));
return decodeAvatar(data, width, height);
}
else
{
cursor.close();
return null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAvatarFromAddress" | "public static Drawable getAvatarFromAddress(ContentResolver cr, String address, int width, int height) {
String[] projection = {Imps.Contacts.AVATAR_DATA};
String[] args = {address};
String query = "username LIKE ?";
Cursor cursor = cr.query(Imps.Contacts.CONTENT_URI,projection,
query, args, Imps.Contacts.DEFAULT_SORT_ORDER);
if (cursor.moveToFirst())
{
String hexData = cursor.getString(0);
if (hexData.equals("NULL")) {
return null;
}
<MASK>cursor.close();</MASK>
byte[] data = Hex.decode(hexData.substring(2, hexData.length() - 1));
return decodeAvatar(data, width, height);
}
else
{
<MASK>cursor.close();</MASK>
return null;
}
}" |
Inversion-Mutation | megadiff | "public void handleMethod(String id, String method, Object[] parameters) {
ClientCommand.COMMAND cmd = Enum.valueOf(ClientCommand.COMMAND.class, method);
//System.out.println("ClientMethodHandler#handleMethod: " + cmd.name());
GUID zoneGUID;
Zone zone;
switch (cmd) {
case enforceZone:
zoneGUID = (GUID) parameters[0];
ZoneRenderer renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
if (renderer != null && renderer != MapTool.getFrame().getCurrentZoneRenderer() && (renderer.getZone().isVisible() || MapTool.getPlayer().isGM())) {
MapTool.getFrame().setCurrentZoneRenderer(renderer);
}
break;
case clearAllDrawings:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.getDrawnElements().clear();
MapTool.getFrame().refresh();
break;
case setZoneHasFoW:
zoneGUID = (GUID) parameters[0];
boolean hasFog = (Boolean) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.setHasFog(hasFog);
// In case we're looking at the zone
MapTool.getFrame().refresh();
break;
case exposeFoW:
zoneGUID = (GUID) parameters[0];
Area area = (Area) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.exposeArea(area);
MapTool.getFrame().getZoneRenderer(zoneGUID).updateFog();
break;
case hideFoW:
zoneGUID = (GUID) parameters[0];
area = (Area) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.hideArea(area);
MapTool.getFrame().getZoneRenderer(zoneGUID).updateFog();
break;
case setCampaign:
Campaign campaign = (Campaign) parameters[0];
MapTool.setCampaign(campaign);
break;
case putZone:
zone = (Zone) parameters[0];
MapTool.getCampaign().putZone(zone);
// TODO: combine this with MapTool.addZone()
renderer = ZoneRendererFactory.newRenderer(zone);
MapTool.getFrame().addZoneRenderer(renderer);
if (MapTool.getFrame().getCurrentZoneRenderer() == null && zone.isVisible()) {
MapTool.getFrame().setCurrentZoneRenderer(renderer);
}
AppListeners.fireZoneAdded(zone);
break;
case removeZone:
zoneGUID = (GUID)parameters[0];
MapTool.getCampaign().removeZone(zoneGUID);
MapTool.getFrame().removeZoneRenderer(MapTool.getFrame().getZoneRenderer(zoneGUID));
break;
case putAsset:
AssetManager.putAsset((Asset) parameters[0]);
MapTool.getFrame().refresh();
break;
case removeAsset:
break;
case putToken:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
Token token = (Token) parameters[1];
zone.putToken(token);
MapTool.getFrame().refresh();
break;
case putLabel:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
Label label = (Label) parameters[1];
zone.putLabel(label);
MapTool.getFrame().refresh();
break;
case removeToken:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
GUID tokenGUID = (GUID) parameters[1];
zone.removeToken(tokenGUID);
MapTool.getFrame().refresh();
break;
case removeLabel:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
GUID labelGUID = (GUID) parameters[1];
zone.removeLabel(labelGUID);
MapTool.getFrame().refresh();
break;
case enforceZoneView:
zoneGUID = (GUID) parameters[0];
int x = (Integer)parameters[1];
int y = (Integer)parameters[2];
int zoomIndex = (Integer)parameters[3];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
if (renderer == null) {
return;
}
renderer.setScaleIndex(zoomIndex);
renderer.centerOn(new ZonePoint(x, y));
break;
case draw:
zoneGUID = (GUID) parameters[0];
Pen pen = (Pen) parameters[1];
Drawable drawable = (Drawable) parameters[2];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.addDrawable(new DrawnElement(drawable, pen));
MapTool.getFrame().refresh();
break;
case undoDraw:
zoneGUID = (GUID) parameters[0];
GUID drawableId = (GUID)parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.removeDrawable(drawableId);
if (MapTool.getFrame().getCurrentZoneRenderer().getZone().getId().equals(zoneGUID) && zoneGUID != null) {
MapTool.getFrame().refresh();
}
break;
case setZoneVisibility:
zoneGUID = (GUID) parameters[0];
boolean visible = (Boolean) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.setVisible(visible);
ZoneRenderer currentRenderer = MapTool.getFrame().getCurrentZoneRenderer();
if (!visible && !MapTool.getPlayer().isGM() && currentRenderer != null && currentRenderer.getZone().getId().equals(zoneGUID)) {
MapTool.getFrame().setCurrentZoneRenderer(null);
}
if (visible && currentRenderer == null) {
currentRenderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
MapTool.getFrame().setCurrentZoneRenderer(currentRenderer);
}
MapTool.getFrame().getZoneSelectionPanel().flush();
MapTool.getFrame().refresh();
break;
case setZoneGridSize:
zoneGUID = (GUID) parameters[0];
int xOffset = ((Integer) parameters[1]).intValue();
int yOffset = ((Integer) parameters[2]).intValue();
int size = ((Integer) parameters[3]).intValue();
int color = ((Integer) parameters[4]).intValue();
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.getGrid().setSize(size);
zone.getGrid().setOffset(xOffset, yOffset);
zone.setGridColor(color);
MapTool.getFrame().refresh();
break;
case playerConnected:
MapTool.addPlayer((Player) parameters[0]);
MapTool.getFrame().refresh();
break;
case playerDisconnected:
MapTool.removePlayer((Player) parameters[0]);
MapTool.getFrame().refresh();
break;
case message:
TextMessage message = (TextMessage) parameters[0];
MapTool.addServerMessage(message);
break;
case showPointer:
MapTool.getFrame().getPointerOverlay().addPointer((String) parameters[0], (Pointer) parameters[1]);
MapTool.getFrame().refresh();
break;
case hidePointer:
MapTool.getFrame().getPointerOverlay().removePointer((String) parameters[0]);
MapTool.getFrame().refresh();
break;
case startTokenMove:
String playerId = (String) parameters[0];
zoneGUID = (GUID) parameters[1];
GUID keyToken = (GUID) parameters[2];
Set<GUID> selectedSet = (Set<GUID>) parameters[3];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.addMoveSelectionSet(playerId, keyToken, selectedSet, true);
break;
case stopTokenMove:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.removeMoveSelectionSet(keyToken);
break;
case updateTokenMove:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
x = ((Integer) parameters[2]).intValue();
y = ((Integer) parameters[3]).intValue();
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.updateMoveSelectionSet(keyToken, new ZonePoint(x, y));
break;
case toggleTokenMoveWaypoint:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
CellPoint cp = (CellPoint) parameters[2];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.toggleMoveSelectionSetWaypoint(keyToken, cp);
break;
case setServerPolicy:
ServerPolicy policy = (ServerPolicy) parameters[0];
MapTool.setServerPolicy(policy);
break;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMethod" | "public void handleMethod(String id, String method, Object[] parameters) {
ClientCommand.COMMAND cmd = Enum.valueOf(ClientCommand.COMMAND.class, method);
//System.out.println("ClientMethodHandler#handleMethod: " + cmd.name());
GUID zoneGUID;
Zone zone;
switch (cmd) {
case enforceZone:
zoneGUID = (GUID) parameters[0];
ZoneRenderer renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
if (renderer != null && renderer != MapTool.getFrame().getCurrentZoneRenderer() && (renderer.getZone().isVisible() || MapTool.getPlayer().isGM())) {
MapTool.getFrame().setCurrentZoneRenderer(renderer);
}
break;
case clearAllDrawings:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.getDrawnElements().clear();
MapTool.getFrame().refresh();
break;
case setZoneHasFoW:
zoneGUID = (GUID) parameters[0];
boolean hasFog = (Boolean) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.setHasFog(hasFog);
// In case we're looking at the zone
MapTool.getFrame().refresh();
break;
case exposeFoW:
zoneGUID = (GUID) parameters[0];
Area area = (Area) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.exposeArea(area);
MapTool.getFrame().getZoneRenderer(zoneGUID).updateFog();
break;
case hideFoW:
zoneGUID = (GUID) parameters[0];
area = (Area) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.hideArea(area);
MapTool.getFrame().getZoneRenderer(zoneGUID).updateFog();
break;
case setCampaign:
Campaign campaign = (Campaign) parameters[0];
MapTool.setCampaign(campaign);
break;
case putZone:
zone = (Zone) parameters[0];
MapTool.getCampaign().putZone(zone);
// TODO: combine this with MapTool.addZone()
renderer = ZoneRendererFactory.newRenderer(zone);
MapTool.getFrame().addZoneRenderer(renderer);
if (MapTool.getFrame().getCurrentZoneRenderer() == null && zone.isVisible()) {
MapTool.getFrame().setCurrentZoneRenderer(renderer);
}
AppListeners.fireZoneAdded(zone);
break;
case removeZone:
zoneGUID = (GUID)parameters[0];
MapTool.getCampaign().removeZone(zoneGUID);
MapTool.getFrame().removeZoneRenderer(MapTool.getFrame().getZoneRenderer(zoneGUID));
break;
case putAsset:
AssetManager.putAsset((Asset) parameters[0]);
MapTool.getFrame().refresh();
break;
case removeAsset:
break;
case putToken:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
Token token = (Token) parameters[1];
zone.putToken(token);
MapTool.getFrame().refresh();
break;
case putLabel:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
Label label = (Label) parameters[1];
zone.putLabel(label);
MapTool.getFrame().refresh();
break;
case removeToken:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
GUID tokenGUID = (GUID) parameters[1];
zone.removeToken(tokenGUID);
MapTool.getFrame().refresh();
break;
case removeLabel:
zoneGUID = (GUID) parameters[0];
zone = MapTool.getCampaign().getZone(zoneGUID);
GUID labelGUID = (GUID) parameters[1];
zone.removeLabel(labelGUID);
MapTool.getFrame().refresh();
break;
case enforceZoneView:
zoneGUID = (GUID) parameters[0];
int x = (Integer)parameters[1];
int y = (Integer)parameters[2];
int zoomIndex = (Integer)parameters[3];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
if (renderer == null) {
return;
}
<MASK>renderer.centerOn(new ZonePoint(x, y));</MASK>
renderer.setScaleIndex(zoomIndex);
break;
case draw:
zoneGUID = (GUID) parameters[0];
Pen pen = (Pen) parameters[1];
Drawable drawable = (Drawable) parameters[2];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.addDrawable(new DrawnElement(drawable, pen));
MapTool.getFrame().refresh();
break;
case undoDraw:
zoneGUID = (GUID) parameters[0];
GUID drawableId = (GUID)parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.removeDrawable(drawableId);
if (MapTool.getFrame().getCurrentZoneRenderer().getZone().getId().equals(zoneGUID) && zoneGUID != null) {
MapTool.getFrame().refresh();
}
break;
case setZoneVisibility:
zoneGUID = (GUID) parameters[0];
boolean visible = (Boolean) parameters[1];
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.setVisible(visible);
ZoneRenderer currentRenderer = MapTool.getFrame().getCurrentZoneRenderer();
if (!visible && !MapTool.getPlayer().isGM() && currentRenderer != null && currentRenderer.getZone().getId().equals(zoneGUID)) {
MapTool.getFrame().setCurrentZoneRenderer(null);
}
if (visible && currentRenderer == null) {
currentRenderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
MapTool.getFrame().setCurrentZoneRenderer(currentRenderer);
}
MapTool.getFrame().getZoneSelectionPanel().flush();
MapTool.getFrame().refresh();
break;
case setZoneGridSize:
zoneGUID = (GUID) parameters[0];
int xOffset = ((Integer) parameters[1]).intValue();
int yOffset = ((Integer) parameters[2]).intValue();
int size = ((Integer) parameters[3]).intValue();
int color = ((Integer) parameters[4]).intValue();
zone = MapTool.getCampaign().getZone(zoneGUID);
zone.getGrid().setSize(size);
zone.getGrid().setOffset(xOffset, yOffset);
zone.setGridColor(color);
MapTool.getFrame().refresh();
break;
case playerConnected:
MapTool.addPlayer((Player) parameters[0]);
MapTool.getFrame().refresh();
break;
case playerDisconnected:
MapTool.removePlayer((Player) parameters[0]);
MapTool.getFrame().refresh();
break;
case message:
TextMessage message = (TextMessage) parameters[0];
MapTool.addServerMessage(message);
break;
case showPointer:
MapTool.getFrame().getPointerOverlay().addPointer((String) parameters[0], (Pointer) parameters[1]);
MapTool.getFrame().refresh();
break;
case hidePointer:
MapTool.getFrame().getPointerOverlay().removePointer((String) parameters[0]);
MapTool.getFrame().refresh();
break;
case startTokenMove:
String playerId = (String) parameters[0];
zoneGUID = (GUID) parameters[1];
GUID keyToken = (GUID) parameters[2];
Set<GUID> selectedSet = (Set<GUID>) parameters[3];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.addMoveSelectionSet(playerId, keyToken, selectedSet, true);
break;
case stopTokenMove:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.removeMoveSelectionSet(keyToken);
break;
case updateTokenMove:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
x = ((Integer) parameters[2]).intValue();
y = ((Integer) parameters[3]).intValue();
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.updateMoveSelectionSet(keyToken, new ZonePoint(x, y));
break;
case toggleTokenMoveWaypoint:
zoneGUID = (GUID) parameters[0];
keyToken = (GUID) parameters[1];
CellPoint cp = (CellPoint) parameters[2];
renderer = MapTool.getFrame().getZoneRenderer(zoneGUID);
renderer.toggleMoveSelectionSetWaypoint(keyToken, cp);
break;
case setServerPolicy:
ServerPolicy policy = (ServerPolicy) parameters[0];
MapTool.setServerPolicy(policy);
break;
}
}" |
Inversion-Mutation | megadiff | "private void viewForm(HttpServletRequest req, HttpServletResponse resp,
List<String> errors, String success_message)
throws ServletException, IOException {
DataTrain train = DataTrain.depart();
User currentUser = train.auth().getCurrentUser(req.getSession());
Form form = null;
try {
long id = Long.parseLong(req.getParameter("id"));
form = train.forms().get(id);
PageBuilder page = new PageBuilder(Page.view, SERVLET_PATH);
if (form == null) {
log.warning("Could not find form number " + id + ".");
errors.add("Could not find form number " + id + ".");
page.setAttribute("error_messages", errors);
} else {
page.setPageTitle(form.getType().toString() + " Form");
page.setAttribute("form", form);
if (form.getType() == Form.Type.ClassConflict) {
page.setAttribute("formStartTime",
Util.formatTimeOnly(form.getStartTime()));
page.setAttribute("formEndTime",
Util.formatTimeOnly(form.getEndTime()));
page.setAttribute("day", form.getDayOfWeek().name());
}
page.setAttribute("isDirector", currentUser.getType()
.isDirector());
page.setAttribute("error_messages", errors);
page.setAttribute("success_message", success_message);
}
page.passOffToJsp(req, resp);
} catch (NumberFormatException nfe) {
log.warning("Could not parse view form id: "
+ req.getParameter("id"));
ErrorServlet.showError(req, resp, 500);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "viewForm" | "private void viewForm(HttpServletRequest req, HttpServletResponse resp,
List<String> errors, String success_message)
throws ServletException, IOException {
DataTrain train = DataTrain.depart();
User currentUser = train.auth().getCurrentUser(req.getSession());
Form form = null;
try {
long id = Long.parseLong(req.getParameter("id"));
form = train.forms().get(id);
PageBuilder page = new PageBuilder(Page.view, SERVLET_PATH);
if (form == null) {
log.warning("Could not find form number " + id + ".");
errors.add("Could not find form number " + id + ".");
page.setAttribute("error_messages", errors);
} else {
page.setPageTitle(form.getType().toString() + " Form");
page.setAttribute("form", form);
if (form.getType() == Form.Type.ClassConflict) {
page.setAttribute("formStartTime",
Util.formatTimeOnly(form.getStartTime()));
page.setAttribute("formEndTime",
Util.formatTimeOnly(form.getEndTime()));
}
<MASK>page.setAttribute("day", form.getDayOfWeek().name());</MASK>
page.setAttribute("isDirector", currentUser.getType()
.isDirector());
page.setAttribute("error_messages", errors);
page.setAttribute("success_message", success_message);
}
page.passOffToJsp(req, resp);
} catch (NumberFormatException nfe) {
log.warning("Could not parse view form id: "
+ req.getParameter("id"));
ErrorServlet.showError(req, resp, 500);
}
}" |
Inversion-Mutation | megadiff | "@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
//TODO: handle static triggers
JFXIdent id = tree.getId();
JFXOnReplace onr = tree.getOnReplace();
// let the owner of the environment be a freshly
// created BLOCK-method.
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
Type type = attribExpr(id, localEnv);
tree.type = type;
Symbol sym = id.sym;
if (onr != null) {
JFXVar oldValue = onr.getOldValue();
if (oldValue != null && oldValue.type == null) {
oldValue.type = type;
}
JFXVar newElements = onr.getNewElements();
if (newElements != null && newElements.type == null) {
newElements.type = type;
}
attribDecl(onr, localEnv);
}
// Must reference an attribute
if (sym.kind != VAR) {
log.error(id.pos(), MsgSym.MESSAGE_JAVAFX_MUST_BE_AN_ATTRIBUTE, id.name);
} else {
VarSymbol v = (VarSymbol) sym;
tree.sym = v;
finishOverrideAttribute(tree, env);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "visitOverrideClassVar" | "@Override
public void visitOverrideClassVar(JFXOverrideClassVar tree) {
//TODO: handle static triggers
JFXIdent id = tree.getId();
JFXOnReplace onr = tree.getOnReplace();
// let the owner of the environment be a freshly
// created BLOCK-method.
JavafxEnv<JavafxAttrContext> localEnv = newLocalEnv(tree);
Type type = attribExpr(id, localEnv);
tree.type = type;
Symbol sym = id.sym;
if (onr != null) {
<MASK>attribDecl(onr, localEnv);</MASK>
JFXVar oldValue = onr.getOldValue();
if (oldValue != null && oldValue.type == null) {
oldValue.type = type;
}
JFXVar newElements = onr.getNewElements();
if (newElements != null && newElements.type == null) {
newElements.type = type;
}
}
// Must reference an attribute
if (sym.kind != VAR) {
log.error(id.pos(), MsgSym.MESSAGE_JAVAFX_MUST_BE_AN_ATTRIBUTE, id.name);
} else {
VarSymbol v = (VarSymbol) sym;
tree.sym = v;
finishOverrideAttribute(tree, env);
}
}" |
Inversion-Mutation | megadiff | "public MendelDialog (HaploView h, String title) {
super(h,title);
JPanel contents = new JPanel();
JTable table;
contents.setLayout(new BoxLayout(contents,BoxLayout.Y_AXIS));
Vector results = h.theData.getPedFile().getResults();
Vector colNames = new Vector();
colNames.add("FamilyID");
colNames.add("ChildID");
colNames.add("Marker");
colNames.add("Position");
Vector data = new Vector();
for(int i=0;i<results.size();i++) {
MarkerResult currentResult = (MarkerResult)results.get(i);
if (currentResult.getMendErrNum() > 0){
Vector mendelErrors = currentResult.getMendelErrors();
for (int j = 0; j < mendelErrors.size(); j++){
MendelError error = (MendelError)mendelErrors.get(j);
Vector tmpVec = new Vector();
tmpVec.add(error.getFamilyID());
tmpVec.add(error.getChildID());
tmpVec.add(Chromosome.getUnfilteredMarker(i).getDisplayName());
tmpVec.add(new Long(Chromosome.getUnfilteredMarker(i).getPosition()));
data.add(tmpVec);
}
}
}
TableSorter sorter = new TableSorter(new BasicTableModel(colNames, data));
table = new JTable(sorter);
sorter.setTableHeader(table.getTableHeader());
table.getColumnModel().getColumn(2).setPreferredWidth(30);
JScrollPane tableScroller = new JScrollPane(table);
int tableHeight = (table.getRowHeight()+table.getRowMargin())*(table.getRowCount()+2);
if (tableHeight > 300){
tableScroller.setPreferredSize(new Dimension(400, 300));
}else{
tableScroller.setPreferredSize(new Dimension(400, tableHeight));
}
tableScroller.setBorder(BorderFactory.createEmptyBorder(2,5,2,5));
contents.add(tableScroller);
JButton okButton = new JButton("Close");
okButton.addActionListener(this);
okButton.setAlignmentX(Component.CENTER_ALIGNMENT);
contents.add(okButton);
setContentPane(contents);
this.setLocation(this.getParent().getX() + 100,
this.getParent().getY() + 100);
this.setModal(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "MendelDialog" | "public MendelDialog (HaploView h, String title) {
super(h,title);
JPanel contents = new JPanel();
JTable table;
contents.setLayout(new BoxLayout(contents,BoxLayout.Y_AXIS));
Vector results = h.theData.getPedFile().getResults();
Vector colNames = new Vector();
colNames.add("FamilyID");
colNames.add("ChildID");
colNames.add("Marker");
colNames.add("Position");
Vector data = new Vector();
for(int i=0;i<results.size();i++) {
MarkerResult currentResult = (MarkerResult)results.get(i);
if (currentResult.getMendErrNum() > 0){
<MASK>Vector tmpVec = new Vector();</MASK>
Vector mendelErrors = currentResult.getMendelErrors();
for (int j = 0; j < mendelErrors.size(); j++){
MendelError error = (MendelError)mendelErrors.get(j);
tmpVec.add(error.getFamilyID());
tmpVec.add(error.getChildID());
tmpVec.add(Chromosome.getUnfilteredMarker(i).getDisplayName());
tmpVec.add(new Long(Chromosome.getUnfilteredMarker(i).getPosition()));
data.add(tmpVec);
}
}
}
TableSorter sorter = new TableSorter(new BasicTableModel(colNames, data));
table = new JTable(sorter);
sorter.setTableHeader(table.getTableHeader());
table.getColumnModel().getColumn(2).setPreferredWidth(30);
JScrollPane tableScroller = new JScrollPane(table);
int tableHeight = (table.getRowHeight()+table.getRowMargin())*(table.getRowCount()+2);
if (tableHeight > 300){
tableScroller.setPreferredSize(new Dimension(400, 300));
}else{
tableScroller.setPreferredSize(new Dimension(400, tableHeight));
}
tableScroller.setBorder(BorderFactory.createEmptyBorder(2,5,2,5));
contents.add(tableScroller);
JButton okButton = new JButton("Close");
okButton.addActionListener(this);
okButton.setAlignmentX(Component.CENTER_ALIGNMENT);
contents.add(okButton);
setContentPane(contents);
this.setLocation(this.getParent().getX() + 100,
this.getParent().getY() + 100);
this.setModal(true);
}" |
Inversion-Mutation | megadiff | "protected KeyValueStore createStoreConnection(String uri)
throws IOException, KeyValueStoreUnavailable {
Matcher m = urlPattern.matcher(uri);
if (!m.matches())
throw new IllegalArgumentException(
String
.format(
"The url pattern %1$s does not match type://hostname:port?args...",
uri));
String type = m.group(1);
KeyValueStore store = openConnection(type);
try {
Map<String, String> configs = new HashMap<String, String>();
if (m.group(2) != null) {
configs.put("host", m.group(2));
}
if (m.group(4) != null) {
configs.put("port", m.group(4));
}
if (m.group(6) != null) {
String[] args = m.group(6).split("&");
for (String arg : args) {
String[] values = arg.split("=");
if (values.length == 2) {
configs.put(values[0], values[1]);
}
}
}
super.configureStore(store, configs);
} catch (Exception e) {
log.warn("Error parsing connection string:", e);
}
return store;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createStoreConnection" | "protected KeyValueStore createStoreConnection(String uri)
throws IOException, KeyValueStoreUnavailable {
Matcher m = urlPattern.matcher(uri);
if (!m.matches())
throw new IllegalArgumentException(
String
.format(
"The url pattern %1$s does not match type://hostname:port?args...",
uri));
String type = m.group(1);
KeyValueStore store = openConnection(type);
try {
Map<String, String> configs = new HashMap<String, String>();
if (m.group(2) != null) {
configs.put("host", m.group(2));
}
if (m.group(4) != null) {
configs.put("port", m.group(4));
}
if (m.group(6) != null) {
String[] args = m.group(6).split("&");
for (String arg : args) {
String[] values = arg.split("=");
if (values.length == 2) {
configs.put(values[0], values[1]);
}
}
<MASK>super.configureStore(store, configs);</MASK>
}
} catch (Exception e) {
log.warn("Error parsing connection string:", e);
}
return store;
}" |
Inversion-Mutation | megadiff | "void doGet( URL url, WagonExchange exchange, boolean doGet )
throws Exception
{
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty( "Accept-Encoding", "gzip" );
if ( !_wagon.getUseCache() )
{
urlConnection.setRequestProperty( "Pragma", "no-cache" );
}
addHeaders( urlConnection );
if ( doGet )
{
urlConnection.setRequestMethod( "GET" );
}
else
{
urlConnection.setRequestMethod( "HEAD" );
}
int responseCode = urlConnection.getResponseCode();
exchange.setResponseStatus( responseCode );
if ( responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED )
{
throw new AuthorizationException( "Access denied to: " + url );
}
if ( doGet )
{
InputStream is = urlConnection.getInputStream();
ByteArrayOutputStream content = new ByteArrayOutputStream();
IOUtil.copy( is, content );
exchange.setResponseContentBytes( content.toByteArray() );
exchange.setContentEncoding( urlConnection.getContentEncoding() );
}
exchange.setLastModified( urlConnection.getLastModified() );
exchange.setContentLength( urlConnection.getContentLength() );
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doGet" | "void doGet( URL url, WagonExchange exchange, boolean doGet )
throws Exception
{
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty( "Accept-Encoding", "gzip" );
if ( !_wagon.getUseCache() )
{
urlConnection.setRequestProperty( "Pragma", "no-cache" );
}
addHeaders( urlConnection );
if ( doGet )
{
urlConnection.setRequestMethod( "GET" );
}
else
{
urlConnection.setRequestMethod( "HEAD" );
}
int responseCode = urlConnection.getResponseCode();
if ( responseCode == HttpURLConnection.HTTP_FORBIDDEN || responseCode == HttpURLConnection.HTTP_UNAUTHORIZED )
{
throw new AuthorizationException( "Access denied to: " + url );
}
if ( doGet )
{
InputStream is = urlConnection.getInputStream();
ByteArrayOutputStream content = new ByteArrayOutputStream();
IOUtil.copy( is, content );
exchange.setResponseContentBytes( content.toByteArray() );
exchange.setContentEncoding( urlConnection.getContentEncoding() );
}
exchange.setLastModified( urlConnection.getLastModified() );
exchange.setContentLength( urlConnection.getContentLength() );
<MASK>exchange.setResponseStatus( responseCode );</MASK>
}" |
Inversion-Mutation | megadiff | "private static void testStatementRemembersTimeout(PreparedStatement ps)
throws SQLException, TestFailedException
{
String name = (ps instanceof CallableStatement) ?
"CallableStatement" : "PreparedStatement";
System.out.println("Testing that " + name + " remembers timeout.");
ps.setQueryTimeout(1);
for (int i = 0; i < 3; i++) {
long runTime=0;
try {
long startTime = System.currentTimeMillis();
ResultSet rs = ps.executeQuery();
while (rs.next());
long endTime = System.currentTimeMillis();
runTime = endTime - startTime;
throw new TestFailedException(
"Should have timed out, for " + name + ", on iteration "
+ i + ", runtime(millis): " + runTime);
} catch (SQLException sqle) {
expectException("XCL52", sqle, "Should have timed out, " +
"got unexpected exception, for " + name + ", on iteration "
+ i + ", runtime(millis): " + runTime);
}
}
ps.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testStatementRemembersTimeout" | "private static void testStatementRemembersTimeout(PreparedStatement ps)
throws SQLException, TestFailedException
{
String name = (ps instanceof CallableStatement) ?
"CallableStatement" : "PreparedStatement";
System.out.println("Testing that " + name + " remembers timeout.");
ps.setQueryTimeout(1);
for (int i = 0; i < 3; i++) {
long runTime=0;
try {
<MASK>ResultSet rs = ps.executeQuery();</MASK>
long startTime = System.currentTimeMillis();
while (rs.next());
long endTime = System.currentTimeMillis();
runTime = endTime - startTime;
throw new TestFailedException(
"Should have timed out, for " + name + ", on iteration "
+ i + ", runtime(millis): " + runTime);
} catch (SQLException sqle) {
expectException("XCL52", sqle, "Should have timed out, " +
"got unexpected exception, for " + name + ", on iteration "
+ i + ", runtime(millis): " + runTime);
}
}
ps.close();
}" |
Inversion-Mutation | megadiff | "protected Library readExternalLibraryFromFilename(String theFileName, FileType defaultType,
IconParameters iconParams)
{
// get the path to the library file
String legalLibName = TextUtils.getFileNameWithoutExtension(theFileName, true);
// Checking if the library is already open
Library elib = Library.findLibrary(legalLibName);
if (elib != null) return elib;
URL externalURL = searchExternalLibraryFromFilename(mainLibDirectory, theFileName, defaultType);
boolean exists = (externalURL != null);
// last option: let user pick library location
if (!exists)
{
String pt = null;
while (true) {
// continue to ask the user where the library is until they hit "cancel"
String description = "Reference library '" + theFileName + "'";
pt = OpenFile.chooseInputFile(FileType.LIBFILE, description);
if (pt == null) {
// user cancelled, break
break;
}
// see if user chose a file we can read
externalURL = TextUtils.makeURLToFile(pt);
if (externalURL != null) {
exists = TextUtils.URLExists(externalURL, null);
if (exists) {
// good pt, opened it, get out of here
break;
}
}
}
}
if (exists)
{
System.out.println("Reading referenced library " + externalURL.getFile());
elib = Library.newInstance(legalLibName, externalURL);
}
if (elib != null)
{
// read the external library
String oldNote = getProgressNote();
setProgressValue(0);
setProgressNote("Reading referenced library " + legalLibName + "...");
// get the library name
FileType importType = OpenFile.getOpenFileType(externalURL.getFile(), defaultType);
String eLibName = TextUtils.getFileNameWithoutExtension(externalURL);
elib = readALibrary(externalURL, elib, eLibName, importType, null, iconParams);
setProgressValue(100);
setProgressNote(oldNote);
}
if (elib == null)
{
System.out.println("Error: cannot find referenced library " + theFileName);
System.out.println("...Creating new "+legalLibName+" Library instead");
elib = Library.newInstance(legalLibName, null);
elib.setLibFile(TextUtils.makeURLToFile(theFileName));
elib.clearFromDisk();
}
// if (failed) elib->userbits |= UNWANTEDLIB; else
// {
// // queue this library for announcement through change control
// io_queuereadlibraryannouncement(elib);
// }
return elib;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "readExternalLibraryFromFilename" | "protected Library readExternalLibraryFromFilename(String theFileName, FileType defaultType,
IconParameters iconParams)
{
// get the path to the library file
String legalLibName = TextUtils.getFileNameWithoutExtension(theFileName, true);
// Checking if the library is already open
Library elib = Library.findLibrary(legalLibName);
if (elib != null) return elib;
URL externalURL = searchExternalLibraryFromFilename(mainLibDirectory, theFileName, defaultType);
boolean exists = (externalURL != null);
// last option: let user pick library location
if (!exists)
{
String pt = null;
while (true) {
// continue to ask the user where the library is until they hit "cancel"
String description = "Reference library '" + theFileName + "'";
pt = OpenFile.chooseInputFile(FileType.LIBFILE, description);
if (pt == null) {
// user cancelled, break
break;
}
// see if user chose a file we can read
externalURL = TextUtils.makeURLToFile(pt);
if (externalURL != null) {
exists = TextUtils.URLExists(externalURL, null);
if (exists) {
// good pt, opened it, get out of here
break;
}
}
}
}
if (exists)
{
System.out.println("Reading referenced library " + externalURL.getFile());
elib = Library.newInstance(legalLibName, externalURL);
}
<MASK>FileType importType = OpenFile.getOpenFileType(externalURL.getFile(), defaultType);</MASK>
if (elib != null)
{
// read the external library
String oldNote = getProgressNote();
setProgressValue(0);
setProgressNote("Reading referenced library " + legalLibName + "...");
// get the library name
String eLibName = TextUtils.getFileNameWithoutExtension(externalURL);
elib = readALibrary(externalURL, elib, eLibName, importType, null, iconParams);
setProgressValue(100);
setProgressNote(oldNote);
}
if (elib == null)
{
System.out.println("Error: cannot find referenced library " + theFileName);
System.out.println("...Creating new "+legalLibName+" Library instead");
elib = Library.newInstance(legalLibName, null);
elib.setLibFile(TextUtils.makeURLToFile(theFileName));
elib.clearFromDisk();
}
// if (failed) elib->userbits |= UNWANTEDLIB; else
// {
// // queue this library for announcement through change control
// io_queuereadlibraryannouncement(elib);
// }
return elib;
}" |
Inversion-Mutation | megadiff | "public void create() {
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(" CREATE TABLE waveformdb "+
" ( waveformeventid int, "+
" numnetworks int, "+
" CONSTRAINT nfkey FOREIGN KEY(waveformeventid) REFERENCES eventconfig(eventid)) ");
stmt.executeUpdate(" CREATE TABLE waveformnetworkdb "+
" ( waveformeventid int, "+
" waveformnetworkid int, "+
" numstations int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformstationdb "+
" ( waveformeventid int, "+
" waveformstationid int, "+
" waveformnetworkid int, "+
" numsites int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformsitedb "+
" ( waveformeventid int, "+
" waveformsiteid int, "+
" waveformstationid int, "+
" numchannels int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformchanneldb "+
" ( waveformid int IDENTITY PRIMARY KEY,"+
" waveformeventid int, "+
" waveformchannelid int, "+
" waveformsiteid int, "+
" qtime timestamp , "+
" status int, "+
" numretrys int, "+
" reason VARCHAR)");
} catch(SQLException sqle) {
logger.debug("one or more tables of waveformdatabase are already created");
}
try {
beginTransStmt = connection.prepareStatement("SET AUTOCOMMIT FALSE");
endTransStmt = connection.prepareStatement("COMMIT");
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "create" | "public void create() {
try {
Statement stmt = connection.createStatement();
stmt.executeUpdate(" CREATE TABLE waveformdb "+
" ( waveformeventid int, "+
" numnetworks int, "+
" CONSTRAINT nfkey FOREIGN KEY(waveformeventid) REFERENCES eventconfig(eventid)) ");
stmt.executeUpdate(" CREATE TABLE waveformnetworkdb "+
" ( waveformeventid int, "+
<MASK>" waveformnetworkid int, "+</MASK>
" numstations int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformstationdb "+
" ( waveformeventid int, "+
<MASK>" waveformnetworkid int, "+</MASK>
" waveformstationid int, "+
" numsites int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformsitedb "+
" ( waveformeventid int, "+
" waveformsiteid int, "+
" waveformstationid int, "+
" numchannels int, "+
" qtime timestamp) ");
stmt.executeUpdate(" CREATE TABLE waveformchanneldb "+
" ( waveformid int IDENTITY PRIMARY KEY,"+
" waveformeventid int, "+
" waveformchannelid int, "+
" waveformsiteid int, "+
" qtime timestamp , "+
" status int, "+
" numretrys int, "+
" reason VARCHAR)");
} catch(SQLException sqle) {
logger.debug("one or more tables of waveformdatabase are already created");
}
try {
beginTransStmt = connection.prepareStatement("SET AUTOCOMMIT FALSE");
endTransStmt = connection.prepareStatement("COMMIT");
} catch(SQLException sqle) {
sqle.printStackTrace();
}
}" |
Inversion-Mutation | megadiff | "public void start() {
try {
java.lang.Thread.sleep(1000);
origim.publish(origI);
origim.publish(procI);
} catch (Exception e) {
e.printStackTrace();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "public void start() {
try {
origim.publish(origI);
origim.publish(procI);
<MASK>java.lang.Thread.sleep(1000);</MASK>
} catch (Exception e) {
e.printStackTrace();
}
}" |
Inversion-Mutation | megadiff | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
Session session = context.getSession();
if (!session.getHasSender())
{
context.sendResponse("503 Error: need MAIL command");
return;
}
else if (session.getRecipientCount() == 0)
{
context.sendResponse("503 Error: need RCPT command");
return;
}
session.setDataMode(true);
context.sendResponse("354 End data with <CR><LF>.<CR><LF>");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "execute" | "@Override
public void execute(String commandString, ConnectionContext context) throws IOException
{
Session session = context.getSession();
if (!session.getHasSender())
{
context.sendResponse("503 Error: need MAIL command");
return;
}
else if (session.getRecipientCount() == 0)
{
context.sendResponse("503 Error: need RCPT command");
return;
}
<MASK>context.sendResponse("354 End data with <CR><LF>.<CR><LF>");</MASK>
session.setDataMode(true);
}" |
Inversion-Mutation | megadiff | "@Test
public void testJournalRecords() throws Exception {
store1();
_persistit.flush();
final Transaction txn = _persistit.getTransaction();
final Volume volume = _persistit.getVolume(_volumeName);
volume.resetHandle();
final JournalManager jman = new JournalManager(_persistit);
final String path = UnitTestProperties.DATA_PATH + "/JournalManagerTest_journal_";
jman.init(null, path, 100 * 1000 * 1000);
final BufferPool pool = _persistit.getBufferPool(16384);
final long pages = Math.min(1000, volume.getStorage().getNextAvailablePage() - 1);
for (int i = 0; i < 1000; i++) {
final Buffer buffer = pool.get(volume, i % pages, true, true);
if ((i % 400) == 0) {
jman.rollover();
}
buffer.setDirtyAtTimestamp(_persistit.getTimestampAllocator().updateTimestamp());
jman.writePageToJournal(buffer);
buffer.clearDirty();
buffer.releaseTouched();
}
final Checkpoint checkpoint1 = _persistit.getCheckpointManager().createCheckpoint();
jman.writeCheckpointToJournal(checkpoint1);
final Exchange exchange = _persistit.getExchange(_volumeName, "JournalManagerTest1", false);
volume.getTree("JournalManagerTest1", false).resetHandle();
assertTrue(exchange.next(true));
final long[] timestamps = new long[100];
for (int i = 0; i < 100; i++) {
assertTrue(exchange.next(true));
final int treeHandle = jman.handleForTree(exchange.getTree());
timestamps[i] = _persistit.getTimestampAllocator().updateTimestamp();
txn.writeStoreRecordToJournal(treeHandle, exchange.getKey(), exchange.getValue());
if (i % 50 == 0) {
jman.rollover();
}
jman.writeTransactionToJournal(txn.getTransactionBuffer(), timestamps[i], i % 4 == 1 ? timestamps[i] + 1
: 0, 0);
}
jman.rollover();
exchange.clear().append(Key.BEFORE);
int commitCount = 0;
long noPagesAfterThis = jman.getCurrentAddress();
Checkpoint checkpoint2 = null;
for (int i = 0; i < 100; i++) {
assertTrue(exchange.next(true));
final int treeHandle = jman.handleForTree(exchange.getTree());
timestamps[i] = _persistit.getTimestampAllocator().updateTimestamp();
txn.writeDeleteRecordToJournal(treeHandle, exchange.getKey(), exchange.getKey());
if (i == 66) {
jman.rollover();
}
if (i == 50) {
checkpoint2 = _persistit.getCheckpointManager().createCheckpoint();
jman.writeCheckpointToJournal(checkpoint2);
noPagesAfterThis = jman.getCurrentAddress();
commitCount = 0;
}
jman.writeTransactionToJournal(txn.getTransactionBuffer(), timestamps[i], i % 4 == 3 ? timestamps[i] + 1
: 0, 0);
if (i % 4 == 3) {
commitCount++;
}
}
store1();
/**
* These pages will have timestamps larger than the last valid
* checkpoint and therefore should not be represented in the recovered
* page map.
*/
for (int i = 0; i < 1000; i++) {
final Buffer buffer = pool.get(volume, i % pages, false, true);
if ((i % 400) == 0) {
jman.rollover();
}
if (buffer.getTimestamp() > checkpoint2.getTimestamp()) {
jman.writePageToJournal(buffer);
}
buffer.releaseTouched();
}
jman.close();
volume.resetHandle();
RecoveryManager rman = new RecoveryManager(_persistit);
rman.init(path);
rman.buildRecoveryPlan();
assertTrue(rman.getKeystoneAddress() != -1);
assertEquals(checkpoint2.getTimestamp(), rman.getLastValidCheckpoint().getTimestamp());
final Map<PageNode, PageNode> pageMap = new HashMap<PageNode, PageNode>();
final Map<PageNode, PageNode> branchMap = new HashMap<PageNode, PageNode>();
rman.collectRecoveredPages(pageMap, branchMap);
assertEquals(pages, pageMap.size());
for (final PageNode pn : pageMap.values()) {
assertTrue(pn.getJournalAddress() <= noPagesAfterThis);
}
final Set<Long> recoveryTimestamps = new HashSet<Long>();
final TransactionPlayerListener actor = new TransactionPlayerListener() {
@Override
public void store(final long address, final long timestamp, Exchange exchange) throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void removeKeyRange(final long address, final long timestamp, Exchange exchange, Key from, Key to)
throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void removeTree(final long address, final long timestamp, Exchange exchange)
throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void startRecovery(long address, long timestamp) throws PersistitException {
}
@Override
public void startTransaction(long address, long startTimestamp, long commitTimestamp)
throws PersistitException {
}
@Override
public void endTransaction(long address, long timestamp) throws PersistitException {
}
@Override
public void endRecovery(long address, long timestamp) throws PersistitException {
}
@Override
public void delta(long address, long timestamp, Tree tree, int index, int accumulatorTypeOrdinal, long value)
throws PersistitException {
}
@Override
public boolean requiresLongRecordConversion() {
return true;
}
};
rman.applyAllRecoveredTransactions(actor, rman.getDefaultRollbackListener());
assertEquals(commitCount, recoveryTimestamps.size());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testJournalRecords" | "@Test
public void testJournalRecords() throws Exception {
store1();
_persistit.flush();
final Transaction txn = _persistit.getTransaction();
final Volume volume = _persistit.getVolume(_volumeName);
volume.resetHandle();
<MASK>volume.getTree("JournalManagerTest1", false).resetHandle();</MASK>
final JournalManager jman = new JournalManager(_persistit);
final String path = UnitTestProperties.DATA_PATH + "/JournalManagerTest_journal_";
jman.init(null, path, 100 * 1000 * 1000);
final BufferPool pool = _persistit.getBufferPool(16384);
final long pages = Math.min(1000, volume.getStorage().getNextAvailablePage() - 1);
for (int i = 0; i < 1000; i++) {
final Buffer buffer = pool.get(volume, i % pages, true, true);
if ((i % 400) == 0) {
jman.rollover();
}
buffer.setDirtyAtTimestamp(_persistit.getTimestampAllocator().updateTimestamp());
jman.writePageToJournal(buffer);
buffer.clearDirty();
buffer.releaseTouched();
}
final Checkpoint checkpoint1 = _persistit.getCheckpointManager().createCheckpoint();
jman.writeCheckpointToJournal(checkpoint1);
final Exchange exchange = _persistit.getExchange(_volumeName, "JournalManagerTest1", false);
assertTrue(exchange.next(true));
final long[] timestamps = new long[100];
for (int i = 0; i < 100; i++) {
assertTrue(exchange.next(true));
final int treeHandle = jman.handleForTree(exchange.getTree());
timestamps[i] = _persistit.getTimestampAllocator().updateTimestamp();
txn.writeStoreRecordToJournal(treeHandle, exchange.getKey(), exchange.getValue());
if (i % 50 == 0) {
jman.rollover();
}
jman.writeTransactionToJournal(txn.getTransactionBuffer(), timestamps[i], i % 4 == 1 ? timestamps[i] + 1
: 0, 0);
}
jman.rollover();
exchange.clear().append(Key.BEFORE);
int commitCount = 0;
long noPagesAfterThis = jman.getCurrentAddress();
Checkpoint checkpoint2 = null;
for (int i = 0; i < 100; i++) {
assertTrue(exchange.next(true));
final int treeHandle = jman.handleForTree(exchange.getTree());
timestamps[i] = _persistit.getTimestampAllocator().updateTimestamp();
txn.writeDeleteRecordToJournal(treeHandle, exchange.getKey(), exchange.getKey());
if (i == 66) {
jman.rollover();
}
if (i == 50) {
checkpoint2 = _persistit.getCheckpointManager().createCheckpoint();
jman.writeCheckpointToJournal(checkpoint2);
noPagesAfterThis = jman.getCurrentAddress();
commitCount = 0;
}
jman.writeTransactionToJournal(txn.getTransactionBuffer(), timestamps[i], i % 4 == 3 ? timestamps[i] + 1
: 0, 0);
if (i % 4 == 3) {
commitCount++;
}
}
store1();
/**
* These pages will have timestamps larger than the last valid
* checkpoint and therefore should not be represented in the recovered
* page map.
*/
for (int i = 0; i < 1000; i++) {
final Buffer buffer = pool.get(volume, i % pages, false, true);
if ((i % 400) == 0) {
jman.rollover();
}
if (buffer.getTimestamp() > checkpoint2.getTimestamp()) {
jman.writePageToJournal(buffer);
}
buffer.releaseTouched();
}
jman.close();
volume.resetHandle();
RecoveryManager rman = new RecoveryManager(_persistit);
rman.init(path);
rman.buildRecoveryPlan();
assertTrue(rman.getKeystoneAddress() != -1);
assertEquals(checkpoint2.getTimestamp(), rman.getLastValidCheckpoint().getTimestamp());
final Map<PageNode, PageNode> pageMap = new HashMap<PageNode, PageNode>();
final Map<PageNode, PageNode> branchMap = new HashMap<PageNode, PageNode>();
rman.collectRecoveredPages(pageMap, branchMap);
assertEquals(pages, pageMap.size());
for (final PageNode pn : pageMap.values()) {
assertTrue(pn.getJournalAddress() <= noPagesAfterThis);
}
final Set<Long> recoveryTimestamps = new HashSet<Long>();
final TransactionPlayerListener actor = new TransactionPlayerListener() {
@Override
public void store(final long address, final long timestamp, Exchange exchange) throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void removeKeyRange(final long address, final long timestamp, Exchange exchange, Key from, Key to)
throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void removeTree(final long address, final long timestamp, Exchange exchange)
throws PersistitException {
recoveryTimestamps.add(timestamp);
}
@Override
public void startRecovery(long address, long timestamp) throws PersistitException {
}
@Override
public void startTransaction(long address, long startTimestamp, long commitTimestamp)
throws PersistitException {
}
@Override
public void endTransaction(long address, long timestamp) throws PersistitException {
}
@Override
public void endRecovery(long address, long timestamp) throws PersistitException {
}
@Override
public void delta(long address, long timestamp, Tree tree, int index, int accumulatorTypeOrdinal, long value)
throws PersistitException {
}
@Override
public boolean requiresLongRecordConversion() {
return true;
}
};
rman.applyAllRecoveredTransactions(actor, rman.getDefaultRollbackListener());
assertEquals(commitCount, recoveryTimestamps.size());
}" |
Inversion-Mutation | megadiff | "@Override
protected void onPostExecute(Cursor cursor) {
final Activity activity = mActivity.get();
showResult(cursor);
if (activity != null && dialog != null) {
dialog.dismiss();
dialog = null;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onPostExecute" | "@Override
protected void onPostExecute(Cursor cursor) {
final Activity activity = mActivity.get();
if (activity != null && dialog != null) {
dialog.dismiss();
dialog = null;
}
<MASK>showResult(cursor);</MASK>
}" |
Inversion-Mutation | megadiff | "public static void capture (Layer layer, Canvas canvas) {
if (!layer.visible()) return;
canvas.save();
concatTransform(canvas, layer.transform());
canvas.translate(-layer.originX(), -layer.originY());
if (layer instanceof GroupLayer) {
GroupLayer gl = (GroupLayer)layer;
for (int ii = 0, ll = gl.size(); ii < ll; ii++) {
capture(gl.get(ii), canvas);
}
} else if (layer instanceof ImageLayer) {
ImageLayer il = (ImageLayer)layer;
canvas.drawImage(il.image(), 0, 0);
} else if (layer instanceof ImmediateLayer) {
ImmediateLayer il = (ImmediateLayer)layer;
il.renderer().render(new CanvasSurface(canvas));
}
canvas.restore();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "capture" | "public static void capture (Layer layer, Canvas canvas) {
if (!layer.visible()) return;
canvas.save();
<MASK>canvas.translate(-layer.originX(), -layer.originY());</MASK>
concatTransform(canvas, layer.transform());
if (layer instanceof GroupLayer) {
GroupLayer gl = (GroupLayer)layer;
for (int ii = 0, ll = gl.size(); ii < ll; ii++) {
capture(gl.get(ii), canvas);
}
} else if (layer instanceof ImageLayer) {
ImageLayer il = (ImageLayer)layer;
canvas.drawImage(il.image(), 0, 0);
} else if (layer instanceof ImmediateLayer) {
ImmediateLayer il = (ImmediateLayer)layer;
il.renderer().render(new CanvasSurface(canvas));
}
canvas.restore();
}" |
Inversion-Mutation | megadiff | "public void castSpell(Player player)
{
if (checkInventoryRequirements(player.getInventory())) // They have the required items.
{
Block targetBlock = player.getTargetBlock(null, 101);
if ((targetBlock.getType() != Material.AIR) && (targetBlock.getType() != Material.BEDROCK)) // Can't do it to air or bedrock.
{
Location loc = targetBlock.getLocation();
Location playerLoc = player.getLocation();
// Distance formula.
double xdiff = loc.getX() - playerLoc.getX();
double ydiff = loc.getZ() - playerLoc.getZ();
double xdiffsq = xdiff * xdiff;
double ydiffsq = ydiff * ydiff;
double xyadd = xdiffsq + ydiffsq;
double distance = Math.sqrt(xyadd);
// Distance formula.
if (distance < 30) // Maximum distance is 31.
{
if (canPlaceCactus(targetBlock)) // If the space is compatable with a cactus
{
removeRequiredItemsFromInventory(player.getInventory()); // Remove required items here.
Material originalTargetMaterial = targetBlock.getType();
boolean sandstoneSupport = false;
if (targetBlock.getRelative(0, -1, 0).getType() == Material.AIR) // if said cactus would fall apart
{
targetBlock.getRelative(0, -1, 0).setType(Material.SANDSTONE); // Place a sandstone support
sandstoneSupport = true; // Set the sandstonesupport variable.
}
targetBlock.setType(Material.SAND); // Set the target block to sand.
for (int i = 1; i <= 3; i++) // For each space above it
{
targetBlock.getRelative(0, i, 0).setType(Material.CACTUS); // Make cactus. Go forth and make cactus.
}
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RunnableDestroyCactus(targetBlock, originalTargetMaterial, sandstoneSupport), 300);
player.sendMessage("SPIKES SPIKES SPIKES BABY");
}
else
{
player.sendMessage("Cannot cast! A cactus wouldn't fit there!");
}
}
else
{
player.sendMessage("Could not cast! Target is out of range!");
}
}
}
else
{
player.sendMessage("Could not cast! Requires 4 cacti and 1 sand.");
}
/*
Block targetBlock = player.getTargetBlock(null, 30); // Select the target block.
if (targetBlock.getType() != Material.AIR) // No placing bedrock midair!
{
Location loc = targetBlock.getLocation();
(player.getWorld().getBlockAt(loc)).setType(Material.SAND);
for (int i = 0; i < 3;i++)
{
loc.setY(loc.getY()+1);
(player.getWorld().getBlockAt(loc)).setType(Material.CACTUS);
}
player.getWorld().getBlockAt(loc);
}
*/
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "castSpell" | "public void castSpell(Player player)
{
if (checkInventoryRequirements(player.getInventory())) // They have the required items.
{
Block targetBlock = player.getTargetBlock(null, 101);
if ((targetBlock.getType() != Material.AIR) && (targetBlock.getType() != Material.BEDROCK)) // Can't do it to air or bedrock.
{
Location loc = targetBlock.getLocation();
Location playerLoc = player.getLocation();
// Distance formula.
double xdiff = loc.getX() - playerLoc.getX();
double ydiff = loc.getZ() - playerLoc.getZ();
double xdiffsq = xdiff * xdiff;
double ydiffsq = ydiff * ydiff;
double xyadd = xdiffsq + ydiffsq;
double distance = Math.sqrt(xyadd);
// Distance formula.
if (distance < 30) // Maximum distance is 31.
{
<MASK>removeRequiredItemsFromInventory(player.getInventory()); // Remove required items here.</MASK>
if (canPlaceCactus(targetBlock)) // If the space is compatable with a cactus
{
Material originalTargetMaterial = targetBlock.getType();
boolean sandstoneSupport = false;
if (targetBlock.getRelative(0, -1, 0).getType() == Material.AIR) // if said cactus would fall apart
{
targetBlock.getRelative(0, -1, 0).setType(Material.SANDSTONE); // Place a sandstone support
sandstoneSupport = true; // Set the sandstonesupport variable.
}
targetBlock.setType(Material.SAND); // Set the target block to sand.
for (int i = 1; i <= 3; i++) // For each space above it
{
targetBlock.getRelative(0, i, 0).setType(Material.CACTUS); // Make cactus. Go forth and make cactus.
}
player.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new RunnableDestroyCactus(targetBlock, originalTargetMaterial, sandstoneSupport), 300);
player.sendMessage("SPIKES SPIKES SPIKES BABY");
}
else
{
player.sendMessage("Cannot cast! A cactus wouldn't fit there!");
}
}
else
{
player.sendMessage("Could not cast! Target is out of range!");
}
}
}
else
{
player.sendMessage("Could not cast! Requires 4 cacti and 1 sand.");
}
/*
Block targetBlock = player.getTargetBlock(null, 30); // Select the target block.
if (targetBlock.getType() != Material.AIR) // No placing bedrock midair!
{
Location loc = targetBlock.getLocation();
(player.getWorld().getBlockAt(loc)).setType(Material.SAND);
for (int i = 0; i < 3;i++)
{
loc.setY(loc.getY()+1);
(player.getWorld().getBlockAt(loc)).setType(Material.CACTUS);
}
player.getWorld().getBlockAt(loc);
}
*/
}" |
Inversion-Mutation | megadiff | "public void run() {
try {
serverLog.logInfo("URLDBCLEANER", "UrldbCleaner-Thread startet");
final Iterator eiter = entries(true, false, null);
while (eiter.hasNext() && run) {
synchronized (this) {
if (this.pause) {
try {
this.wait();
} catch (InterruptedException e) {
serverLog.logWarning("URLDBCLEANER", "InterruptedException", e);
this.run = false;
return;
}
}
}
final indexURLEntry entry = (indexURLEntry) eiter.next();
if (entry == null) {
serverLog.logFine("URLDBCLEANER", "entry == null");
} else if (entry.hash() == null) {
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + "hash == null");
} else {
final indexURLEntry.Components comp = entry.comp();
totalSearchedUrls++;
if (comp.url() == null) {
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + entry.hash() + "URL == null");
remove(entry.hash());
} else if (plasmaSwitchboard.urlBlacklist.isListed(plasmaURLPattern.BLACKLIST_CRAWLER, comp.url()) ||
plasmaSwitchboard.urlBlacklist.isListed(plasmaURLPattern.BLACKLIST_DHT, comp.url())) {
lastBlacklistedUrl = comp.url().toNormalform();
lastBlacklistedHash = entry.hash();
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + entry.hash() + " " + comp.url().toNormalform());
remove(entry.hash());
if (blacklistedUrls % 100 == 0) {
serverLog.logInfo("URLDBCLEANER", "Deleted " + blacklistedUrls + " URLs until now. Last deleted URL-Hash: " + lastBlacklistedUrl);
}
}
lastUrl = comp.url().toNormalform();
lastHash = entry.hash();
}
}
} catch (RuntimeException e) {
if (e.getMessage() != null && e.getMessage().indexOf("not found in LURL") != -1) {
serverLog.logWarning("URLDBCLEANER", "urlHash not found in LURL", e);
}
else {
serverLog.logWarning("URLDBCLEANER", "RuntimeException", e);
run = false;
}
} catch (IOException e) {
e.printStackTrace();
run = false;
}
serverLog.logInfo("URLDBCLEANER", "UrldbCleaner-Thread stopped");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run() {
try {
serverLog.logInfo("URLDBCLEANER", "UrldbCleaner-Thread startet");
final Iterator eiter = entries(true, false, null);
while (eiter.hasNext() && run) {
synchronized (this) {
if (this.pause) {
try {
this.wait();
} catch (InterruptedException e) {
serverLog.logWarning("URLDBCLEANER", "InterruptedException", e);
this.run = false;
return;
}
}
}
final indexURLEntry entry = (indexURLEntry) eiter.next();
if (entry == null) {
serverLog.logFine("URLDBCLEANER", "entry == null");
} else if (entry.hash() == null) {
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + "hash == null");
} else {
final indexURLEntry.Components comp = entry.comp();
totalSearchedUrls++;
if (comp.url() == null) {
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + entry.hash() + "URL == null");
remove(entry.hash());
} else if (plasmaSwitchboard.urlBlacklist.isListed(plasmaURLPattern.BLACKLIST_CRAWLER, comp.url()) ||
plasmaSwitchboard.urlBlacklist.isListed(plasmaURLPattern.BLACKLIST_DHT, comp.url())) {
lastBlacklistedUrl = comp.url().toNormalform();
lastBlacklistedHash = entry.hash();
serverLog.logFine("URLDBCLEANER", ++blacklistedUrls + " blacklisted (" + ((double) blacklistedUrls / totalSearchedUrls) * 100 + "%): " + entry.hash() + " " + comp.url().toNormalform());
remove(entry.hash());
if (blacklistedUrls % 100 == 0) {
serverLog.logInfo("URLDBCLEANER", "Deleted " + blacklistedUrls + " URLs until now. Last deleted URL-Hash: " + lastBlacklistedUrl);
}
<MASK>lastUrl = comp.url().toNormalform();</MASK>
}
lastHash = entry.hash();
}
}
} catch (RuntimeException e) {
if (e.getMessage() != null && e.getMessage().indexOf("not found in LURL") != -1) {
serverLog.logWarning("URLDBCLEANER", "urlHash not found in LURL", e);
}
else {
serverLog.logWarning("URLDBCLEANER", "RuntimeException", e);
run = false;
}
} catch (IOException e) {
e.printStackTrace();
run = false;
}
serverLog.logInfo("URLDBCLEANER", "UrldbCleaner-Thread stopped");
}" |
Inversion-Mutation | megadiff | "public HSSFSheet cloneSheet(int sheetIndex) {
validateSheetIndex(sheetIndex);
HSSFSheet srcSheet = (HSSFSheet) _sheets.get(sheetIndex);
String srcName = workbook.getSheetName(sheetIndex);
HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
clonedSheet.setSelected(false);
clonedSheet.setActive(false);
String name = getUniqueSheetName(srcName);
int newSheetIndex = _sheets.size();
_sheets.add(clonedSheet);
workbook.setSheetName(newSheetIndex, name);
// Check this sheet has an autofilter, (which has a built-in NameRecord at workbook level)
int filterDbNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_FILTER_DB);
if (filterDbNameIndex >=0) {
NameRecord origNameRecord = workbook.getNameRecord(filterDbNameIndex);
// copy original formula but adjust 3D refs to the new external sheet index
int newExtSheetIx = workbook.checkExternSheet(newSheetIndex);
Ptg[] ptgs = origNameRecord.getNameDefinition();
for (int i=0; i< ptgs.length; i++) {
Ptg ptg = ptgs[i];
ptg = ptg.copy();
if (ptg instanceof Area3DPtg) {
Area3DPtg a3p = (Area3DPtg) ptg;
a3p.setExternSheetIndex(newExtSheetIx);
} else if (ptg instanceof Ref3DPtg) {
Ref3DPtg r3p = (Ref3DPtg) ptg;
r3p.setExternSheetIndex(newExtSheetIx);
}
ptgs[i] = ptg;
}
NameRecord newNameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, newSheetIndex+1);
newNameRecord.setNameDefinition(ptgs);
newNameRecord.setHidden(true);
HSSFName newName = new HSSFName(this, newNameRecord);
names.add(newName);
workbook.cloneDrawings(clonedSheet.getSheet());
}
// TODO - maybe same logic required for other/all built-in name records
return clonedSheet;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cloneSheet" | "public HSSFSheet cloneSheet(int sheetIndex) {
validateSheetIndex(sheetIndex);
HSSFSheet srcSheet = (HSSFSheet) _sheets.get(sheetIndex);
String srcName = workbook.getSheetName(sheetIndex);
HSSFSheet clonedSheet = srcSheet.cloneSheet(this);
clonedSheet.setSelected(false);
clonedSheet.setActive(false);
String name = getUniqueSheetName(srcName);
int newSheetIndex = _sheets.size();
_sheets.add(clonedSheet);
workbook.setSheetName(newSheetIndex, name);
// Check this sheet has an autofilter, (which has a built-in NameRecord at workbook level)
int filterDbNameIndex = findExistingBuiltinNameRecordIdx(sheetIndex, NameRecord.BUILTIN_FILTER_DB);
if (filterDbNameIndex >=0) {
NameRecord origNameRecord = workbook.getNameRecord(filterDbNameIndex);
// copy original formula but adjust 3D refs to the new external sheet index
int newExtSheetIx = workbook.checkExternSheet(newSheetIndex);
Ptg[] ptgs = origNameRecord.getNameDefinition();
for (int i=0; i< ptgs.length; i++) {
Ptg ptg = ptgs[i];
ptg = ptg.copy();
if (ptg instanceof Area3DPtg) {
Area3DPtg a3p = (Area3DPtg) ptg;
a3p.setExternSheetIndex(newExtSheetIx);
} else if (ptg instanceof Ref3DPtg) {
Ref3DPtg r3p = (Ref3DPtg) ptg;
r3p.setExternSheetIndex(newExtSheetIx);
}
ptgs[i] = ptg;
}
NameRecord newNameRecord = workbook.createBuiltInName(NameRecord.BUILTIN_FILTER_DB, newSheetIndex+1);
newNameRecord.setNameDefinition(ptgs);
newNameRecord.setHidden(true);
HSSFName newName = new HSSFName(this, newNameRecord);
names.add(newName);
}
<MASK>workbook.cloneDrawings(clonedSheet.getSheet());</MASK>
// TODO - maybe same logic required for other/all built-in name records
return clonedSheet;
}" |
Inversion-Mutation | megadiff | "private void verifyBlock(Block block) {
BlockSender blockSender = null;
/* In case of failure, attempt to read second time to reduce
* transient errors. How do we flush block data from kernel
* buffers before the second read?
*/
for (int i=0; i<2; i++) {
boolean second = (i > 0);
try {
adjustThrottler();
blockSender = new BlockSender(block, 0, -1, false,
false, true, datanode);
DataOutputStream out =
new DataOutputStream(new IOUtils.NullOutputStream());
blockSender.sendBlock(out, null, throttler);
LOG.info((second ? "Second " : "") +
"Verification succeeded for " + block);
if ( second ) {
totalTransientErrors++;
}
updateScanStatus(block, ScanType.VERIFICATION_SCAN, true);
return;
} catch (IOException e) {
updateScanStatus(block, ScanType.VERIFICATION_SCAN, false);
// If the block does not exists anymore, then its not an error
if ( dataset.getFile(block) == null ) {
LOG.info("Verification failed for " + block + ". Its ok since " +
"it not in datanode dataset anymore.");
deleteBlock(block);
return;
}
LOG.warn((second ? "Second " : "First ") +
"Verification failed for " + block + ". Exception : " +
StringUtils.stringifyException(e));
if (second) {
totalScanErrors++;
datanode.getMetrics().blockVerificationFailures.inc();
handleScanFailure(block);
return;
}
} finally {
IOUtils.closeStream(blockSender);
datanode.getMetrics().blocksVerified.inc();
totalScans++;
totalVerifications++;
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "verifyBlock" | "private void verifyBlock(Block block) {
BlockSender blockSender = null;
/* In case of failure, attempt to read second time to reduce
* transient errors. How do we flush block data from kernel
* buffers before the second read?
*/
for (int i=0; i<2; i++) {
boolean second = (i > 0);
try {
adjustThrottler();
blockSender = new BlockSender(block, 0, -1, false,
false, true, datanode);
DataOutputStream out =
new DataOutputStream(new IOUtils.NullOutputStream());
blockSender.sendBlock(out, null, throttler);
LOG.info((second ? "Second " : "") +
"Verification succeeded for " + block);
if ( second ) {
totalTransientErrors++;
}
updateScanStatus(block, ScanType.VERIFICATION_SCAN, true);
return;
} catch (IOException e) {
<MASK>totalScanErrors++;</MASK>
updateScanStatus(block, ScanType.VERIFICATION_SCAN, false);
// If the block does not exists anymore, then its not an error
if ( dataset.getFile(block) == null ) {
LOG.info("Verification failed for " + block + ". Its ok since " +
"it not in datanode dataset anymore.");
deleteBlock(block);
return;
}
LOG.warn((second ? "Second " : "First ") +
"Verification failed for " + block + ". Exception : " +
StringUtils.stringifyException(e));
if (second) {
datanode.getMetrics().blockVerificationFailures.inc();
handleScanFailure(block);
return;
}
} finally {
IOUtils.closeStream(blockSender);
datanode.getMetrics().blocksVerified.inc();
totalScans++;
totalVerifications++;
}
}
}" |
Inversion-Mutation | megadiff | "void doShutdown() {
if (active.compareAndSet(true, false)) {
logger.log(Level.INFO, "HazelcastClient[" + this.id + "] is shutting down.");
out.shutdown();
in.shutdown();
connectionManager.shutdown();
listenerManager.shutdown();
ClientThreadContext.shutdown();
lsClients.remove(HazelcastClient.this);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doShutdown" | "void doShutdown() {
if (active.compareAndSet(true, false)) {
logger.log(Level.INFO, "HazelcastClient[" + this.id + "] is shutting down.");
<MASK>connectionManager.shutdown();</MASK>
out.shutdown();
in.shutdown();
listenerManager.shutdown();
ClientThreadContext.shutdown();
lsClients.remove(HazelcastClient.this);
}
}" |
Inversion-Mutation | megadiff | "public String toHTML() {
StringBuffer text = new StringBuffer();
text.append("<table id=\"toc\">\n<tr>\n<td>\n");
TableOfContentsEntry entry = null;
int adjustedLevel = 0;
int previousLevel = 0;
Iterator tocIterator = this.entries.values().iterator();
while (tocIterator.hasNext()) {
entry = (TableOfContentsEntry)tocIterator.next();
// adjusted level determines how far to indent the list
adjustedLevel = ((entry.level - minLevel) + 1);
// cannot increase TOC indent level more than one level at a time
if (adjustedLevel > (previousLevel + 1)) {
adjustedLevel = previousLevel + 1;
}
if (adjustedLevel <= Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH)) {
// only display if not nested deeper than max
closeList(adjustedLevel, text, previousLevel);
openList(adjustedLevel, text, previousLevel);
text.append("<a href=\"#").append(Utilities.encodeAndEscapeTopicName(entry.name)).append("\">");
text.append("<span class=\"tocnumber\">").append(this.nextTocPrefix(adjustedLevel - 1)).append("</span> ");
text.append("<span class=\"toctext\">").append(entry.text).append("</span></a>");
previousLevel = adjustedLevel;
}
}
closeList(0, text, previousLevel);
text.append("\n</td>\n</tr>\n</table>\n");
return text.toString();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toHTML" | "public String toHTML() {
StringBuffer text = new StringBuffer();
text.append("<table id=\"toc\">\n<tr>\n<td>\n");
TableOfContentsEntry entry = null;
int adjustedLevel = 0;
int previousLevel = 0;
Iterator tocIterator = this.entries.values().iterator();
while (tocIterator.hasNext()) {
entry = (TableOfContentsEntry)tocIterator.next();
// adjusted level determines how far to indent the list
adjustedLevel = ((entry.level - minLevel) + 1);
// cannot increase TOC indent level more than one level at a time
if (adjustedLevel > (previousLevel + 1)) {
adjustedLevel = previousLevel + 1;
}
if (adjustedLevel <= Environment.getIntValue(Environment.PROP_PARSER_TOC_DEPTH)) {
// only display if not nested deeper than max
closeList(adjustedLevel, text, previousLevel);
openList(adjustedLevel, text, previousLevel);
text.append("<a href=\"#").append(Utilities.encodeAndEscapeTopicName(entry.name)).append("\">");
text.append("<span class=\"tocnumber\">").append(this.nextTocPrefix(adjustedLevel - 1)).append("</span> ");
text.append("<span class=\"toctext\">").append(entry.text).append("</span></a>");
}
<MASK>previousLevel = adjustedLevel;</MASK>
}
closeList(0, text, previousLevel);
text.append("\n</td>\n</tr>\n</table>\n");
return text.toString();
}" |
Inversion-Mutation | megadiff | "private void setText(String value) {
Element divChild;
if (getElement().getChild(0).getNodeType() == Node.ELEMENT_NODE) {
divChild = (Element) getElement().getChild(0);
} else {
divChild = DOM.createDiv();
divChild.addClassName(css().wrap("DayValue"));
getElement().appendChild(divChild);
}
DOM.setInnerText(getElement(), "");
DOM.setInnerText(divChild, value);
DOM.appendChild(getElement(), divChild);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setText" | "private void setText(String value) {
Element divChild;
if (getElement().getChild(0).getNodeType() == Node.ELEMENT_NODE) {
divChild = (Element) getElement().getChild(0);
} else {
divChild = DOM.createDiv();
divChild.addClassName(css().wrap("DayValue"));
getElement().appendChild(divChild);
}
<MASK>DOM.setInnerText(divChild, value);</MASK>
DOM.setInnerText(getElement(), "");
DOM.appendChild(getElement(), divChild);
}" |
Inversion-Mutation | megadiff | "public CombinedTool(DrawingEditor editor, Game game) {
tools = new ArrayList<Tool>();
tools.add(new EndTurnTool(editor, game));
tools.add(new ActionTool(editor, game));
tools.add(new InspectTool(editor, game));
tools.add(new MoveTool(editor, game));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "CombinedTool" | "public CombinedTool(DrawingEditor editor, Game game) {
tools = new ArrayList<Tool>();
<MASK>tools.add(new MoveTool(editor, game));</MASK>
tools.add(new EndTurnTool(editor, game));
tools.add(new ActionTool(editor, game));
tools.add(new InspectTool(editor, game));
}" |
Inversion-Mutation | megadiff | "@Override
public void onCreate() {
mConnectivityManager = new EmailConnectivityManager(this, TAG);
// Start up our service thread
new Thread(this, "AttachmentDownloadService").start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
public void onCreate() {
// Start up our service thread
new Thread(this, "AttachmentDownloadService").start();
<MASK>mConnectivityManager = new EmailConnectivityManager(this, TAG);</MASK>
}" |
Inversion-Mutation | megadiff | "void doMouseClicked(MouseEvent me)
{
TreePath path = arbre.getPathForLocation(me.getX(), me.getY());
/*
* Exemple path
* [null, site, test.html, titre 1]
*/
if (path != null)
{
Object[] tabObj = path.getPath();
int location = path.getPathCount();
/*
* Exemple Location :
* 1 2 3 4
* /home
* site
* test1.html
* Titre 1
* Paragraphe 1
* test2.html
* Titre 1
* Paragraphe 1
*/
if (location == 2)
{
parentNodeProjet = arbre.getLastSelectedPathComponent();
}
else if (location == 3)
{
Generateur.fenetre.getMenu().activerAjout();
// on selectionne le dernier noeud selectionnee
parentNodeFichier = arbre.getLastSelectedPathComponent();
// on selectionne la page pour mettre les paragraphes, ect..
pageSelectionnee = Generateur.alProjet.get(0).getPage(path.getLastPathComponent().toString());
Generateur.alProjet.get(0).setPageSelectionne(pageSelectionnee);
}
else if (location > 3)
{
// on recupere la page et le noeud grace a path
parentNodeFichier = tabObj[2];
pageSelectionnee = Generateur.alProjet.get(0).getPage(parentNodeFichier.toString());
Scanner sc = new Scanner(path.getLastPathComponent().toString()).useDelimiter(" ");
String str = sc.next();
int indice = Integer.parseInt(sc.next());
if (str.equals("Titre"))
{
String ancienTitre = Generateur.alProjet.get(0).getPage(pageSelectionnee).getAlTitre().get(indice-1);
Generateur.creerFenetreAjouterTitre(pageSelectionnee, 1, ancienTitre, indice);
}
if (str.equals("Paragraphe"))
{
String ancienParagraphe = Generateur.alProjet.get(0).getPage(pageSelectionnee).getAlParagraphe().get(indice-1);
Generateur.creerFenetreAjouterParagraphe(pageSelectionnee, 1, ancienParagraphe, indice);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doMouseClicked" | "void doMouseClicked(MouseEvent me)
{
TreePath path = arbre.getPathForLocation(me.getX(), me.getY());
/*
* Exemple path
* [null, site, test.html, titre 1]
*/
<MASK>Object[] tabObj = path.getPath();</MASK>
if (path != null)
{
int location = path.getPathCount();
/*
* Exemple Location :
* 1 2 3 4
* /home
* site
* test1.html
* Titre 1
* Paragraphe 1
* test2.html
* Titre 1
* Paragraphe 1
*/
if (location == 2)
{
parentNodeProjet = arbre.getLastSelectedPathComponent();
}
else if (location == 3)
{
Generateur.fenetre.getMenu().activerAjout();
// on selectionne le dernier noeud selectionnee
parentNodeFichier = arbre.getLastSelectedPathComponent();
// on selectionne la page pour mettre les paragraphes, ect..
pageSelectionnee = Generateur.alProjet.get(0).getPage(path.getLastPathComponent().toString());
Generateur.alProjet.get(0).setPageSelectionne(pageSelectionnee);
}
else if (location > 3)
{
// on recupere la page et le noeud grace a path
parentNodeFichier = tabObj[2];
pageSelectionnee = Generateur.alProjet.get(0).getPage(parentNodeFichier.toString());
Scanner sc = new Scanner(path.getLastPathComponent().toString()).useDelimiter(" ");
String str = sc.next();
int indice = Integer.parseInt(sc.next());
if (str.equals("Titre"))
{
String ancienTitre = Generateur.alProjet.get(0).getPage(pageSelectionnee).getAlTitre().get(indice-1);
Generateur.creerFenetreAjouterTitre(pageSelectionnee, 1, ancienTitre, indice);
}
if (str.equals("Paragraphe"))
{
String ancienParagraphe = Generateur.alProjet.get(0).getPage(pageSelectionnee).getAlParagraphe().get(indice-1);
Generateur.creerFenetreAjouterParagraphe(pageSelectionnee, 1, ancienParagraphe, indice);
}
}
}
}" |
Inversion-Mutation | megadiff | "public boolean matchOrder(Order newOrder) {
int i = 0;
for (Order oldOrder: orders) {
i += 1;
//log.info("oldOrder: " + oldOrder);
//log.info("newOrder: " + newOrder);
// Are they giving what anyone else wants?
if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) ||
!ItemQuery.isSameType(newOrder.want, oldOrder.give)) {
log.info("Not matched, different types");
continue;
}
double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount();
double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount();
// Offering a better or equal deal? (Quantity = relative value)
log.info("ratio " + newRatio + " >= " + oldRatio);
if (!(newRatio >= oldRatio)) {
log.info("Not matched, worse relative value");
continue;
}
// TODO: refactor into ItemStackX compareTo(), so can check if item is 'better than' other item
// Generalized to 'betterness'
// Is item less damaged or equally damaged than wanted? (Durability)
if (ItemQuery.isDurable(newOrder.give.getType())) {
if (newOrder.give.getDurability() > oldOrder.want.getDurability()) {
log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability());
continue;
}
}
if (ItemQuery.isDurable(oldOrder.give.getType())) {
if (oldOrder.give.getDurability() > newOrder.want.getDurability()) {
log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability());
continue;
}
}
// Does the item have at least the enchantments and levels that are wanted? (Enchantments)
if (ItemQuery.isEnchantable(newOrder.give.getType())) {
if (!EnchantQuery.equalOrBetter(newOrder.give, oldOrder.want)) {
log.info("Not matched, insufficient magic new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()));
continue;
}
} else {
// Not legitimately enchantmentable, means enchant is used as a 'subtype', just like
// damage is if !isDurable, so match exactly.
if (!EnchantQuery.nameEnchs(newOrder.give.getEnchantments()).equals(
EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()))) {
log.info("Not matched, non-identical enchantments new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) +
" != " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()));
continue;
}
}
if (ItemQuery.isEnchantable(oldOrder.give.getType())) {
if (!EnchantQuery.equalOrBetter(oldOrder.give, newOrder.want)) {
log.info("Not matched, insufficient magic old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments()));
continue;
}
} else {
if (!EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()).equals(
EnchantQuery.nameEnchs(newOrder.want.getEnchantments()))) {
log.info("Not matched, non-identical enchantments old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) +
" != " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments()));
continue;
}
}
// Determine how much of the order can be fulfilled
int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount();
int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount();
log.info("remaining want="+remainingWant+", give="+remainingGive);
// They get what they want!
// Calculate amount that can be exchanged
ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability());
ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability());
exchWant.addUnsafeEnchantments(newOrder.give.getEnchantments());
exchGive.addUnsafeEnchantments(oldOrder.give.getEnchantments());
log.info("exchWant="+ItemQuery.nameStack(exchWant));
log.info("exchGive="+ItemQuery.nameStack(exchGive));
transferItems(oldOrder.player, newOrder.player, exchGive);
transferItems(newOrder.player, oldOrder.player, exchWant);
Transaction t = new Transaction(plugin, oldOrder.player, exchWant, newOrder.player, exchGive);
t.log();
// Remove oldOrder from orders, if complete, or add partial if incomplete
if (remainingWant == 0) {
// This order is finished, old player got everything they wanted
log.info("remainingWant=0, this order is finished");
cancelOrder(oldOrder);
return true;
} else if (remainingWant > 0) {
// They still want more. Update the partial order.
oldOrder.want.setAmount(remainingWant);
oldOrder.give.setAmount(remainingGive);
Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder);
log.info("remainingWant>0, still want more");
return true;
}
// remainingWant can be negative if they got more than they bargained for
// (other player offered a better deal than expected). Either way, done deal.
else if (remainingWant < 0) {
if (remainingGive < 0) {
// test case:
// w foo 10d 10cobble
// w bar 6cobble 10d
// ->
// close w foo 6d 6cobble
// new w foo 4d 4cobble
// (and reverse)
cancelOrder(oldOrder);
newOrder.want.setAmount(-remainingGive);
newOrder.give.setAmount(-remainingWant);
log.info("remainingWant<0, Adding new partial order (remainingWant="+remainingWant+")");
log.info("remainingGive<0 ="+remainingGive);
return false;
} else {
// test case:
// w foo 1d 64cobble
// w bar 1cobble 64diamond
// Offered 64cob, but got it for 1cob. Better deal than expected. But everyone got what they want.
cancelOrder(oldOrder);
log.info("remainingWant<0, but remainingGive="+remainingGive+", got better deal than expected, closing");
return true;
}
}
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "matchOrder" | "public boolean matchOrder(Order newOrder) {
int i = 0;
for (Order oldOrder: orders) {
i += 1;
//log.info("oldOrder: " + oldOrder);
//log.info("newOrder: " + newOrder);
// Are they giving what anyone else wants?
if (!ItemQuery.isSameType(newOrder.give, oldOrder.want) ||
!ItemQuery.isSameType(newOrder.want, oldOrder.give)) {
log.info("Not matched, different types");
continue;
}
double newRatio = (double)newOrder.give.getAmount() / newOrder.want.getAmount();
double oldRatio = (double)oldOrder.want.getAmount() / oldOrder.give.getAmount();
// Offering a better or equal deal? (Quantity = relative value)
log.info("ratio " + newRatio + " >= " + oldRatio);
if (!(newRatio >= oldRatio)) {
log.info("Not matched, worse relative value");
continue;
}
// TODO: refactor into ItemStackX compareTo(), so can check if item is 'better than' other item
// Generalized to 'betterness'
// Is item less damaged or equally damaged than wanted? (Durability)
if (ItemQuery.isDurable(newOrder.give.getType())) {
if (newOrder.give.getDurability() > oldOrder.want.getDurability()) {
log.info("Not matched, worse damage new, " + newOrder.give.getDurability() + " < " + oldOrder.want.getDurability());
continue;
}
}
if (ItemQuery.isDurable(oldOrder.give.getType())) {
if (oldOrder.give.getDurability() > newOrder.want.getDurability()) {
log.info("Not matched, worse damage old, " + oldOrder.give.getDurability() + " < " + newOrder.want.getDurability());
continue;
}
}
// Does the item have at least the enchantments and levels that are wanted? (Enchantments)
if (ItemQuery.isEnchantable(newOrder.give.getType())) {
if (!EnchantQuery.equalOrBetter(newOrder.give, oldOrder.want)) {
log.info("Not matched, insufficient magic new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()));
continue;
}
} else {
// Not legitimately enchantmentable, means enchant is used as a 'subtype', just like
// damage is if !isDurable, so match exactly.
if (!EnchantQuery.nameEnchs(newOrder.give.getEnchantments()).equals(
EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()))) {
log.info("Not matched, non-identical enchantments new " + EnchantQuery.nameEnchs(newOrder.give.getEnchantments()) +
" != " + EnchantQuery.nameEnchs(oldOrder.want.getEnchantments()));
continue;
}
}
if (ItemQuery.isEnchantable(oldOrder.give.getType())) {
if (!EnchantQuery.equalOrBetter(oldOrder.give, newOrder.want)) {
log.info("Not matched, insufficient magic old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) +
" < " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments()));
continue;
}
} else {
if (!EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()).equals(
EnchantQuery.nameEnchs(newOrder.want.getEnchantments()))) {
log.info("Not matched, non-identical enchantments old " + EnchantQuery.nameEnchs(oldOrder.give.getEnchantments()) +
" != " + EnchantQuery.nameEnchs(newOrder.want.getEnchantments()));
continue;
}
}
// Determine how much of the order can be fulfilled
int remainingWant = oldOrder.want.getAmount() - newOrder.give.getAmount();
int remainingGive = oldOrder.give.getAmount() - newOrder.want.getAmount();
log.info("remaining want="+remainingWant+", give="+remainingGive);
// They get what they want!
// Calculate amount that can be exchanged
ItemStack exchWant = new ItemStack(oldOrder.want.getType(), Math.min(oldOrder.want.getAmount(), newOrder.give.getAmount()), newOrder.give.getDurability());
ItemStack exchGive = new ItemStack(oldOrder.give.getType(), Math.min(oldOrder.give.getAmount(), newOrder.want.getAmount()), oldOrder.give.getDurability());
exchWant.addUnsafeEnchantments(newOrder.give.getEnchantments());
exchGive.addUnsafeEnchantments(oldOrder.give.getEnchantments());
log.info("exchWant="+ItemQuery.nameStack(exchWant));
log.info("exchGive="+ItemQuery.nameStack(exchGive));
<MASK>transferItems(newOrder.player, oldOrder.player, exchWant);</MASK>
transferItems(oldOrder.player, newOrder.player, exchGive);
Transaction t = new Transaction(plugin, oldOrder.player, exchWant, newOrder.player, exchGive);
t.log();
// Remove oldOrder from orders, if complete, or add partial if incomplete
if (remainingWant == 0) {
// This order is finished, old player got everything they wanted
log.info("remainingWant=0, this order is finished");
cancelOrder(oldOrder);
return true;
} else if (remainingWant > 0) {
// They still want more. Update the partial order.
oldOrder.want.setAmount(remainingWant);
oldOrder.give.setAmount(remainingGive);
Bukkit.getServer().broadcastMessage("Updated order: " + oldOrder);
log.info("remainingWant>0, still want more");
return true;
}
// remainingWant can be negative if they got more than they bargained for
// (other player offered a better deal than expected). Either way, done deal.
else if (remainingWant < 0) {
if (remainingGive < 0) {
// test case:
// w foo 10d 10cobble
// w bar 6cobble 10d
// ->
// close w foo 6d 6cobble
// new w foo 4d 4cobble
// (and reverse)
cancelOrder(oldOrder);
newOrder.want.setAmount(-remainingGive);
newOrder.give.setAmount(-remainingWant);
log.info("remainingWant<0, Adding new partial order (remainingWant="+remainingWant+")");
log.info("remainingGive<0 ="+remainingGive);
return false;
} else {
// test case:
// w foo 1d 64cobble
// w bar 1cobble 64diamond
// Offered 64cob, but got it for 1cob. Better deal than expected. But everyone got what they want.
cancelOrder(oldOrder);
log.info("remainingWant<0, but remainingGive="+remainingGive+", got better deal than expected, closing");
return true;
}
}
}
return false;
}" |
Inversion-Mutation | megadiff | "public void start() {
InitClass initClass = new InitClass(this);
Thread t = new Thread(initClass);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
logger.getParent().addAppender(appender);
System.setProperty("java.security.auth.login.config", Thread.currentThread().getContextClassLoader().getResource("jaas.config").toExternalForm());
Frame f = new Frame();
Wizard wizard = new Wizard(f);
wizard.getDialog().setTitle("Semantic Integration Workbench");
WizardPanelDescriptor modeSelDesc = new ModeSelectionPanelDescriptor();
wizard.registerWizardPanel(ModeSelectionPanelDescriptor.IDENTIFIER, modeSelDesc);
WizardPanelDescriptor descriptor2 = new FileSelectionPanelDescriptor();
wizard.registerWizardPanel(FileSelectionPanelDescriptor.IDENTIFIER, descriptor2);
// WizardPanelDescriptor roundtrip = new RoundtripPanelDescriptor();
wizard.registerWizardPanel(RoundtripPanelDescriptor.IDENTIFIER, roundtripDesc);
WizardPanelDescriptor fileProgress = new ProgressFileSelectionPanelDescriptor();
wizard.registerWizardPanel(ProgressFileSelectionPanelDescriptor.IDENTIFIER, fileProgress);
WizardPanelDescriptor reportConfirmDesc = new ReportConfirmPanelDescriptor();
wizard.registerWizardPanel(ReportConfirmPanelDescriptor.IDENTIFIER, reportConfirmDesc);
WizardPanelDescriptor validationDesc = new ValidationPanelDescriptor();
wizard.registerWizardPanel(ValidationPanelDescriptor.IDENTIFIER, validationDesc);
WizardPanelDescriptor descriptor3 = new SemanticConnectorPanelDescriptor();
wizard.registerWizardPanel(SemanticConnectorPanelDescriptor.IDENTIFIER, descriptor3);
WizardPanelDescriptor descriptor4 = new ProgressSemanticConnectorPanelDescriptor();
wizard.registerWizardPanel(ProgressSemanticConnectorPanelDescriptor.IDENTIFIER, descriptor4);
wizard.setCurrentPanel(ModeSelectionPanelDescriptor.IDENTIFIER);
int wizResult = wizard.showModalDialog();
if(wizResult != 0) {
System.exit(0);
}
RunMode mode = (RunMode)userSelections.getProperty("MODE");
if(mode.equals(RunMode.GenerateReport))
System.exit(0);
mainFrame.init();
putToCenter(mainFrame);
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
mainFrame.exit();
}
});
mainFrame.setVisible(true);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "start" | "public void start() {
InitClass initClass = new InitClass(this);
Thread t = new Thread(initClass);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
logger.getParent().addAppender(appender);
System.setProperty("java.security.auth.login.config", Thread.currentThread().getContextClassLoader().getResource("jaas.config").toExternalForm());
Frame f = new Frame();
Wizard wizard = new Wizard(f);
wizard.getDialog().setTitle("Semantic Integration Workbench");
WizardPanelDescriptor modeSelDesc = new ModeSelectionPanelDescriptor();
wizard.registerWizardPanel(ModeSelectionPanelDescriptor.IDENTIFIER, modeSelDesc);
WizardPanelDescriptor descriptor2 = new FileSelectionPanelDescriptor();
wizard.registerWizardPanel(FileSelectionPanelDescriptor.IDENTIFIER, descriptor2);
// WizardPanelDescriptor roundtrip = new RoundtripPanelDescriptor();
wizard.registerWizardPanel(RoundtripPanelDescriptor.IDENTIFIER, roundtripDesc);
WizardPanelDescriptor fileProgress = new ProgressFileSelectionPanelDescriptor();
wizard.registerWizardPanel(ProgressFileSelectionPanelDescriptor.IDENTIFIER, fileProgress);
WizardPanelDescriptor reportConfirmDesc = new ReportConfirmPanelDescriptor();
wizard.registerWizardPanel(ReportConfirmPanelDescriptor.IDENTIFIER, reportConfirmDesc);
WizardPanelDescriptor validationDesc = new ValidationPanelDescriptor();
wizard.registerWizardPanel(ValidationPanelDescriptor.IDENTIFIER, validationDesc);
WizardPanelDescriptor descriptor3 = new SemanticConnectorPanelDescriptor();
wizard.registerWizardPanel(SemanticConnectorPanelDescriptor.IDENTIFIER, descriptor3);
WizardPanelDescriptor descriptor4 = new ProgressSemanticConnectorPanelDescriptor();
wizard.registerWizardPanel(ProgressSemanticConnectorPanelDescriptor.IDENTIFIER, descriptor4);
wizard.setCurrentPanel(ModeSelectionPanelDescriptor.IDENTIFIER);
int wizResult = wizard.showModalDialog();
if(wizResult != 0) {
System.exit(0);
}
RunMode mode = (RunMode)userSelections.getProperty("MODE");
if(mode.equals(RunMode.GenerateReport))
System.exit(0);
putToCenter(mainFrame);
mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
mainFrame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
mainFrame.exit();
}
});
<MASK>mainFrame.init();</MASK>
mainFrame.setVisible(true);
}" |
Inversion-Mutation | megadiff | "public void reviewNotifications(Date today)
throws NamingException, FinderException, SQLException, Exception {
NotificationSessionLocalHome notificationHome =
(NotificationSessionLocalHome) EJBFactory.lookUpLocalHome(
NotificationSessionLocalHome.class,
NotificationSessionLocalHome.JNDI_NAME);
NotificationSessionLocal notificationSess =
notificationHome.create();
EntityBL entity = new EntityBL();
Collection entities = entity.getHome().findEntities();
for (Iterator it = entities.iterator(); it.hasNext(); ) {
EntityEntityLocal ent = (EntityEntityLocal) it.next();
// find the orders for this entity
prepareStatement(OrderSQL.getAboutToExpire);
cachedResults.setDate(1, new java.sql.Date(today.getTime()));
// calculate the until date
// get the this entity preferences for each of the steps
PreferenceBL pref = new PreferenceBL();
int totalSteps = 3;
int stepDays[] = new int[totalSteps];
boolean config = false;
int minStep = -1;
for (int f = 0; f < totalSteps; f++) {
try {
pref.set(ent.getId(), new Integer(
Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1.intValue() +
f));
if (pref.isNull()) {
stepDays[f] = -1;
} else {
stepDays[f] = pref.getInt();
config = true;
if (minStep == -1) {
minStep = f;
}
}
} catch (FinderException e) {
stepDays[f] = -1;
}
}
if (!config) {
log.warn("Preference missing to send a notification for " +
"entity " + ent.getId());
continue;
}
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, stepDays[minStep]);
cachedResults.setDate(2, new java.sql.Date(
cal.getTime().getTime()));
// the entity
cachedResults.setInt(3, ent.getId().intValue());
// the total number of steps
cachedResults.setInt(4, totalSteps);
execute();
while (cachedResults.next()) {
int orderId = cachedResults.getInt(1);
Date activeUntil = cachedResults.getDate(2);
int currentStep = cachedResults.getInt(3);
int days = -1;
// find out how many days apply for this order step
for (int f = currentStep; f < totalSteps; f++) {
if (stepDays[f] >= 0) {
days = stepDays[f];
currentStep = f + 1;
break;
}
}
if (days == -1) {
throw new SessionInternalError("There are no more steps " +
"configured, but the order was selected. Order " +
" id = " + orderId);
}
// check that this order requires a notification
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, days);
if (activeUntil.compareTo(today) >= 0 &&
activeUntil.compareTo(cal.getTime()) <= 0) {
/*/ ok
log.debug("Selecting order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
} else {
/*
log.debug("Skipping order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
continue;
}
set(new Integer(orderId));
UserBL user = new UserBL(order.getUser());
try {
NotificationBL notification = new NotificationBL();
ContactBL contact = new ContactBL();
contact.set(user.getEntity().getUserId());
OrderDTOEx dto = DTOFactory.getOrderDTOEx(
new Integer(orderId), new Integer(1));
MessageDTO message = notification.getOrderNotification(
ent.getId(),
new Integer(currentStep),
user.getEntity().getLanguageIdField(),
order.getActiveSince(),
order.getActiveUntil(),
user.getEntity().getUserId(),
dto.getTotal(), order.getCurrencyId());
// update the order record only if the message is sent
if (notificationSess.notify(user.getEntity(), message).
booleanValue()) {
// if in the last step, turn the notification off, so
// it is skiped in the next process
if (currentStep >= totalSteps) {
order.setNotify(new Integer(0));
}
order.setNotificationStep(new Integer(currentStep));
order.setLastNotified(Calendar.getInstance().getTime());
}
} catch (NotificationNotFoundException e) {
log.warn("Without a message to send, this entity can't" +
" notify about orders. Skipping");
break;
}
}
cachedResults.close();
}
// The connection was found null when testing on Oracle
if (conn != null) {
conn.close();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "reviewNotifications" | "public void reviewNotifications(Date today)
throws NamingException, FinderException, SQLException, Exception {
NotificationSessionLocalHome notificationHome =
(NotificationSessionLocalHome) EJBFactory.lookUpLocalHome(
NotificationSessionLocalHome.class,
NotificationSessionLocalHome.JNDI_NAME);
NotificationSessionLocal notificationSess =
notificationHome.create();
EntityBL entity = new EntityBL();
Collection entities = entity.getHome().findEntities();
for (Iterator it = entities.iterator(); it.hasNext(); ) {
EntityEntityLocal ent = (EntityEntityLocal) it.next();
// find the orders for this entity
prepareStatement(OrderSQL.getAboutToExpire);
cachedResults.setDate(1, new java.sql.Date(today.getTime()));
// calculate the until date
// get the this entity preferences for each of the steps
PreferenceBL pref = new PreferenceBL();
int totalSteps = 3;
int stepDays[] = new int[totalSteps];
boolean config = false;
int minStep = -1;
for (int f = 0; f < totalSteps; f++) {
try {
pref.set(ent.getId(), new Integer(
Constants.PREFERENCE_DAYS_ORDER_NOTIFICATION_S1.intValue() +
f));
if (pref.isNull()) {
stepDays[f] = -1;
} else {
stepDays[f] = pref.getInt();
config = true;
if (minStep == -1) {
minStep = f;
}
}
} catch (FinderException e) {
stepDays[f] = -1;
}
}
if (!config) {
log.warn("Preference missing to send a notification for " +
"entity " + ent.getId());
continue;
}
Calendar cal = Calendar.getInstance();
cal.clear();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, stepDays[minStep]);
cachedResults.setDate(2, new java.sql.Date(
cal.getTime().getTime()));
// the entity
cachedResults.setInt(3, ent.getId().intValue());
// the total number of steps
cachedResults.setInt(4, totalSteps);
execute();
while (cachedResults.next()) {
int orderId = cachedResults.getInt(1);
Date activeUntil = cachedResults.getDate(2);
int currentStep = cachedResults.getInt(3);
int days = -1;
// find out how many days apply for this order step
for (int f = currentStep; f < totalSteps; f++) {
if (stepDays[f] >= 0) {
days = stepDays[f];
currentStep = f + 1;
break;
}
}
if (days == -1) {
throw new SessionInternalError("There are no more steps " +
"configured, but the order was selected. Order " +
" id = " + orderId);
}
// check that this order requires a notification
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, days);
if (activeUntil.compareTo(today) >= 0 &&
activeUntil.compareTo(cal.getTime()) <= 0) {
/*/ ok
log.debug("Selecting order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
} else {
/*
log.debug("Skipping order " + orderId + " today = " +
today + " active unitl = " + activeUntil +
" days = " + days);
*/
continue;
}
set(new Integer(orderId));
UserBL user = new UserBL(order.getUser());
try {
NotificationBL notification = new NotificationBL();
ContactBL contact = new ContactBL();
contact.set(user.getEntity().getUserId());
OrderDTOEx dto = DTOFactory.getOrderDTOEx(
new Integer(orderId), new Integer(1));
MessageDTO message = notification.getOrderNotification(
ent.getId(),
new Integer(currentStep),
user.getEntity().getLanguageIdField(),
order.getActiveSince(),
order.getActiveUntil(),
user.getEntity().getUserId(),
dto.getTotal(), order.getCurrencyId());
// update the order record only if the message is sent
if (notificationSess.notify(user.getEntity(), message).
booleanValue()) {
// if in the last step, turn the notification off, so
// it is skiped in the next process
if (currentStep >= totalSteps) {
order.setNotify(new Integer(0));
}
order.setNotificationStep(new Integer(currentStep));
order.setLastNotified(Calendar.getInstance().getTime());
}
} catch (NotificationNotFoundException e) {
log.warn("Without a message to send, this entity can't" +
" notify about orders. Skipping");
break;
}
}
}
<MASK>cachedResults.close();</MASK>
// The connection was found null when testing on Oracle
if (conn != null) {
conn.close();
}
}" |
Inversion-Mutation | megadiff | "public void run()
{
try
{
log.info("Starting Thread " + threadId);
synchronized (startSemaphore)
{
if (!started)
{
startSemaphore.wait();
}
}
//log.info("Thread " + threadId + "Opening valve");
if (!valve.open())
{
//log.info("Valve couldn't be opened at thread " + threadId);
synchronized (VeryBasicValveTest.class)
{
counterWait ++;
}
} else
{
//log.info("Thread " + threadId + " could open the valve");
//Thread.sleep(1000);
synchronized (VeryBasicValveTest.class)
{
counter ++;
}
valve.close();
}
//log.info("Thread " + threadId + " is now closing the valve");
}
catch (Exception e)
{
e.printStackTrace();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "run" | "public void run()
{
try
{
log.info("Starting Thread " + threadId);
synchronized (startSemaphore)
{
if (!started)
{
startSemaphore.wait();
}
}
//log.info("Thread " + threadId + "Opening valve");
if (!valve.open())
{
//log.info("Valve couldn't be opened at thread " + threadId);
synchronized (VeryBasicValveTest.class)
{
counterWait ++;
}
} else
{
//log.info("Thread " + threadId + " could open the valve");
//Thread.sleep(1000);
synchronized (VeryBasicValveTest.class)
{
counter ++;
}
}
//log.info("Thread " + threadId + " is now closing the valve");
<MASK>valve.close();</MASK>
}
catch (Exception e)
{
e.printStackTrace();
}
}" |
Inversion-Mutation | megadiff | "public void remove() throws IllegalStateException {
if (this.sipHeader == null)
throw new IllegalStateException();
if (toRemove) {
this.sipMessage.removeHeader(sipHeader.getName());
this.sipHeader = null;
} else {
throw new IllegalStateException();
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "remove" | "public void remove() throws IllegalStateException {
if (this.sipHeader == null)
throw new IllegalStateException();
if (toRemove) {
<MASK>this.sipHeader = null;</MASK>
this.sipMessage.removeHeader(sipHeader.getName());
} else {
throw new IllegalStateException();
}
}" |
Inversion-Mutation | megadiff | "public Gson create() {
List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>();
factories.addAll(this.factories);
Collections.reverse(factories);
factories.addAll(this.hierarchyFactories);
addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
return new Gson(excluder, fieldNamingPolicy, instanceCreators,
serializeNulls, complexMapKeySerialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting,
serializeSpecialFloatingPointValues, longSerializationPolicy, factories);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "create" | "public Gson create() {
List<TypeAdapter.Factory> factories = new ArrayList<TypeAdapter.Factory>();
<MASK>factories.addAll(this.hierarchyFactories);</MASK>
factories.addAll(this.factories);
Collections.reverse(factories);
addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories);
return new Gson(excluder, fieldNamingPolicy, instanceCreators,
serializeNulls, complexMapKeySerialization,
generateNonExecutableJson, escapeHtmlChars, prettyPrinting,
serializeSpecialFloatingPointValues, longSerializationPolicy, factories);
}" |
Inversion-Mutation | megadiff | "private Template buildTemplate(ComputeService computeService, BrooklynJcloudsSetupHolder setup) {
TemplateBuilder templateBuilder = (TemplateBuilder) setup.get("templateBuilder");
if (templateBuilder==null)
templateBuilder = new PortableTemplateBuilder();
else
LOG.debug("jclouds using templateBuilder {} as base for provisioning in {} for {}", new Object[] {templateBuilder, this, setup.getCallerContext()});
if (setup.providerLocationId!=null) {
templateBuilder.locationId(setup.providerLocationId);
}
for (Map.Entry<String, CustomizeTemplateBuilder> entry : SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateBuilder code = entry.getValue();
if (setup.use(name))
code.apply(templateBuilder, setup.allconf, setup.get(name));
}
if (templateBuilder instanceof PortableTemplateBuilder) {
((PortableTemplateBuilder)templateBuilder).attachComputeService(computeService);
// do the default last, and only if nothing else specified (guaranteed to be a PTB if nothing else specified)
if (setup.use("defaultImageId")) {
if (((PortableTemplateBuilder)templateBuilder).isBlank()) {
CharSequence defaultImageId = (CharSequence) setup.get("defaultImageId");
templateBuilder.imageId(defaultImageId.toString());
}
}
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, templateBuilder);
}
Template template;
try {
template = templateBuilder.build();
if (template==null) throw new NullPointerException("No template found (templateBuilder.build returned null)");
LOG.debug(""+this+" got template "+template+" (image "+template.getImage()+")");
if (template.getImage()==null) throw new NullPointerException("Template does not contain an image (templateBuilder.build returned invalid template)");
if (isBadTemplate(template.getImage())) {
// release candidates might break things :( TODO get the list and score them
if (templateBuilder instanceof PortableTemplateBuilder) {
if (((PortableTemplateBuilder)templateBuilder).getOsFamily()==null) {
templateBuilder.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04").os64Bit(true);
Template template2 = templateBuilder.build();
if (template2!=null) {
LOG.debug(""+this+" preferring template {} over {}", template2, template);
template = template2;
}
}
}
}
} catch (AuthorizationException e) {
LOG.warn("Error resolving template: not authorized (rethrowing: "+e+")");
throw new IllegalStateException("Not authorized to access cloud "+this+" to resolve "+templateBuilder, e);
} catch (Exception e) {
try {
synchronized (this) {
// delay subsequent log.warns (put in synch block) so the "Loading..." message is obvious
LOG.warn("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+" (rethrowing): "+e);
if (!listedAvailableTemplatesOnNoSuchTemplate) {
listedAvailableTemplatesOnNoSuchTemplate = true;
LOG.info("Loading available images at "+this+" for reference...");
Map m1 = new LinkedHashMap(setup.allconf);
if (m1.remove("imageId")!=null)
// don't apply default filters if user has tried to specify an image ID
m1.put("anyOwner", true);
ComputeService computeServiceLessRestrictive = JcloudsUtil.buildOrFindComputeService(m1, new MutableMap());
Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
LOG.info(""+imgs.size()+" available images at "+this);
for (Image img: imgs) {
LOG.info(" Image: "+img);
}
}
}
} catch (Exception e2) {
LOG.warn("Error loading available images to report (following original error matching template which will be rethrown): "+e2, e2);
throw new IllegalStateException("Unable to access cloud "+this+" to resolve "+templateBuilder, e);
}
throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);
}
TemplateOptions options = template.getOptions();
for (Map.Entry<String, CustomizeTemplateOptions> entry : SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateOptions code = entry.getValue();
if (setup.use(name))
code.apply(options, setup.allconf, setup.get(name));
}
// Setup the user
//NB: we ignore private key here because, by default we probably should not be installing it remotely;
//also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
//but not elsewhere, e.g. on rackspace)
if (truth(setup.user) && !NON_ADDABLE_USERS.contains(setup.user) &&
!setup.user.equals(setup.loginUser) && !truth(setup.isDontCreateUser())) {
// create the user, if it's not the login user and not a known root-level user
// by default we now give these users sudo privileges.
// if you want something else, that can be specified manually,
// e.g. using jclouds UserAdd.Builder, with RunScriptOnNode, or template.options.runScript(xxx)
// (if that is a common use case, we could expose a property here)
// note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
AdminAccess.Builder adminBuilder = AdminAccess.builder().
adminUsername(setup.user).
grantSudoToAdminUser(true);
adminBuilder.adminPassword(setup.use("password") ? setup.password : Identifiers.makeRandomId(12));
if (setup.publicKeyData!=null)
adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(setup.publicKeyData);
else
adminBuilder.authorizeAdminPublicKey(false).adminPublicKey("ignored").lockSsh(true);
adminBuilder.installAdminPrivateKey(false).adminPrivateKey("ignored");
adminBuilder.resetLoginPassword(true).loginPassword(Identifiers.makeRandomId(12));
adminBuilder.lockSsh(true);
options.runScript(adminBuilder.build());
} else if (truth(setup.publicKeyData)) {
// don't create the user, but authorize the public key for the default user
options.authorizePublicKey(setup.publicKeyData);
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, options);
}
LOG.debug("jclouds using template {} / options {} to provision machine in {} for {}", new Object[] {template, options, this, setup.getCallerContext()});
return template;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildTemplate" | "private Template buildTemplate(ComputeService computeService, BrooklynJcloudsSetupHolder setup) {
TemplateBuilder templateBuilder = (TemplateBuilder) setup.get("templateBuilder");
if (templateBuilder==null)
templateBuilder = new PortableTemplateBuilder();
else
LOG.debug("jclouds using templateBuilder {} as base for provisioning in {} for {}", new Object[] {templateBuilder, this, setup.getCallerContext()});
if (setup.providerLocationId!=null) {
templateBuilder.locationId(setup.providerLocationId);
}
for (Map.Entry<String, CustomizeTemplateBuilder> entry : SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateBuilder code = entry.getValue();
if (setup.use(name))
code.apply(templateBuilder, setup.allconf, setup.get(name));
}
if (templateBuilder instanceof PortableTemplateBuilder) {
((PortableTemplateBuilder)templateBuilder).attachComputeService(computeService);
// do the default last, and only if nothing else specified (guaranteed to be a PTB if nothing else specified)
if (setup.use("defaultImageId")) {
if (((PortableTemplateBuilder)templateBuilder).isBlank()) {
CharSequence defaultImageId = (CharSequence) setup.get("defaultImageId");
templateBuilder.imageId(defaultImageId.toString());
}
}
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, templateBuilder);
}
Template template;
try {
template = templateBuilder.build();
if (template==null) throw new NullPointerException("No template found (templateBuilder.build returned null)");
LOG.debug(""+this+" got template "+template+" (image "+template.getImage()+")");
if (template.getImage()==null) throw new NullPointerException("Template does not contain an image (templateBuilder.build returned invalid template)");
if (isBadTemplate(template.getImage())) {
// release candidates might break things :( TODO get the list and score them
if (templateBuilder instanceof PortableTemplateBuilder) {
if (((PortableTemplateBuilder)templateBuilder).getOsFamily()==null) {
templateBuilder.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04").os64Bit(true);
Template template2 = templateBuilder.build();
if (template2!=null) {
LOG.debug(""+this+" preferring template {} over {}", template2, template);
template = template2;
}
}
}
}
} catch (AuthorizationException e) {
LOG.warn("Error resolving template: not authorized (rethrowing: "+e+")");
throw new IllegalStateException("Not authorized to access cloud "+this+" to resolve "+templateBuilder, e);
} catch (Exception e) {
try {
synchronized (this) {
// delay subsequent log.warns (put in synch block) so the "Loading..." message is obvious
LOG.warn("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+" (rethrowing): "+e);
if (!listedAvailableTemplatesOnNoSuchTemplate) {
listedAvailableTemplatesOnNoSuchTemplate = true;
LOG.info("Loading available images at "+this+" for reference...");
Map m1 = new LinkedHashMap(setup.allconf);
if (m1.remove("imageId")!=null)
// don't apply default filters if user has tried to specify an image ID
m1.put("anyOwner", true);
ComputeService computeServiceLessRestrictive = JcloudsUtil.buildOrFindComputeService(m1, new MutableMap());
Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
LOG.info(""+imgs.size()+" available images at "+this);
for (Image img: imgs) {
LOG.info(" Image: "+img);
}
}
}
<MASK>throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);</MASK>
} catch (Exception e2) {
LOG.warn("Error loading available images to report (following original error matching template which will be rethrown): "+e2, e2);
throw new IllegalStateException("Unable to access cloud "+this+" to resolve "+templateBuilder, e);
}
}
TemplateOptions options = template.getOptions();
for (Map.Entry<String, CustomizeTemplateOptions> entry : SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateOptions code = entry.getValue();
if (setup.use(name))
code.apply(options, setup.allconf, setup.get(name));
}
// Setup the user
//NB: we ignore private key here because, by default we probably should not be installing it remotely;
//also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
//but not elsewhere, e.g. on rackspace)
if (truth(setup.user) && !NON_ADDABLE_USERS.contains(setup.user) &&
!setup.user.equals(setup.loginUser) && !truth(setup.isDontCreateUser())) {
// create the user, if it's not the login user and not a known root-level user
// by default we now give these users sudo privileges.
// if you want something else, that can be specified manually,
// e.g. using jclouds UserAdd.Builder, with RunScriptOnNode, or template.options.runScript(xxx)
// (if that is a common use case, we could expose a property here)
// note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
AdminAccess.Builder adminBuilder = AdminAccess.builder().
adminUsername(setup.user).
grantSudoToAdminUser(true);
adminBuilder.adminPassword(setup.use("password") ? setup.password : Identifiers.makeRandomId(12));
if (setup.publicKeyData!=null)
adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(setup.publicKeyData);
else
adminBuilder.authorizeAdminPublicKey(false).adminPublicKey("ignored").lockSsh(true);
adminBuilder.installAdminPrivateKey(false).adminPrivateKey("ignored");
adminBuilder.resetLoginPassword(true).loginPassword(Identifiers.makeRandomId(12));
adminBuilder.lockSsh(true);
options.runScript(adminBuilder.build());
} else if (truth(setup.publicKeyData)) {
// don't create the user, but authorize the public key for the default user
options.authorizePublicKey(setup.publicKeyData);
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, options);
}
LOG.debug("jclouds using template {} / options {} to provision machine in {} for {}", new Object[] {template, options, this, setup.getCallerContext()});
return template;
}" |
Inversion-Mutation | megadiff | "@Override
public void handleMessage(Message msg) {
BluetoothAudioGateway.IncomingConnectionInfo info =
(BluetoothAudioGateway.IncomingConnectionInfo)msg.obj;
int type = BluetoothHandsfree.TYPE_UNKNOWN;
switch(msg.what) {
case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION:
type = BluetoothHandsfree.TYPE_HEADSET;
break;
case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION:
type = BluetoothHandsfree.TYPE_HANDSFREE;
break;
}
Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) +
") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan);
int priority = BluetoothHeadset.PRIORITY_OFF;
HeadsetBase headset;
try {
priority = mBinder.getPriority(info.mRemoteDevice);
} catch (RemoteException e) {}
if (priority <= BluetoothHeadset.PRIORITY_OFF) {
Log.i(TAG, "Rejecting incoming connection because priority = " + priority);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
return;
}
switch (mState) {
case BluetoothHeadset.STATE_DISCONNECTED:
// headset connecting us, lets join
mRemoteDevice = info.mRemoteDevice;
setState(BluetoothHeadset.STATE_CONNECTING);
headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd,
info.mRfcommChan, mConnectedStatusHandler);
mHeadsetType = type;
mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget();
break;
case BluetoothHeadset.STATE_CONNECTING:
if (!info.mRemoteDevice.equals(mRemoteDevice)) {
// different headset, ignoring
Log.i(TAG, "Already attempting connect to " + mRemoteDevice +
", disconnecting " + info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
}
// If we are here, we are in danger of a race condition
// incoming rfcomm connection, but we are also attempting an
// outgoing connection. Lets try and interrupt the outgoing
// connection.
Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice +
". Cancel outgoing connection.");
if (mConnectThread != null) {
mConnectThread.interrupt();
}
// Now continue with new connection, including calling callback
mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice,
info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler);
mHeadsetType = type;
setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS);
mBtHandsfree.connectHeadset(mHeadset, mHeadsetType);
// Make sure that old outgoing connect thread is dead.
if (mConnectThread != null) {
try {
// TODO: Don't block in the main thread
Log.w(TAG, "Block in main thread to join stale outgoing connection thread");
mConnectThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Connection cancelled twice eh?", e);
}
mConnectThread = null;
}
if (DBG) log("Successfully used incoming connection, and cancelled outgoing " +
" connection");
break;
case BluetoothHeadset.STATE_CONNECTED:
Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " +
info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
break;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "handleMessage" | "@Override
public void handleMessage(Message msg) {
BluetoothAudioGateway.IncomingConnectionInfo info =
(BluetoothAudioGateway.IncomingConnectionInfo)msg.obj;
int type = BluetoothHandsfree.TYPE_UNKNOWN;
switch(msg.what) {
case BluetoothAudioGateway.MSG_INCOMING_HEADSET_CONNECTION:
type = BluetoothHandsfree.TYPE_HEADSET;
break;
case BluetoothAudioGateway.MSG_INCOMING_HANDSFREE_CONNECTION:
type = BluetoothHandsfree.TYPE_HANDSFREE;
break;
}
Log.i(TAG, "Incoming rfcomm (" + BluetoothHandsfree.typeToString(type) +
") connection from " + info.mRemoteDevice + "on channel " + info.mRfcommChan);
int priority = BluetoothHeadset.PRIORITY_OFF;
HeadsetBase headset;
try {
priority = mBinder.getPriority(info.mRemoteDevice);
} catch (RemoteException e) {}
if (priority <= BluetoothHeadset.PRIORITY_OFF) {
Log.i(TAG, "Rejecting incoming connection because priority = " + priority);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
return;
}
switch (mState) {
case BluetoothHeadset.STATE_DISCONNECTED:
// headset connecting us, lets join
<MASK>setState(BluetoothHeadset.STATE_CONNECTING);</MASK>
mRemoteDevice = info.mRemoteDevice;
headset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice, info.mSocketFd,
info.mRfcommChan, mConnectedStatusHandler);
mHeadsetType = type;
mConnectingStatusHandler.obtainMessage(RFCOMM_CONNECTED, headset).sendToTarget();
break;
case BluetoothHeadset.STATE_CONNECTING:
if (!info.mRemoteDevice.equals(mRemoteDevice)) {
// different headset, ignoring
Log.i(TAG, "Already attempting connect to " + mRemoteDevice +
", disconnecting " + info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
}
// If we are here, we are in danger of a race condition
// incoming rfcomm connection, but we are also attempting an
// outgoing connection. Lets try and interrupt the outgoing
// connection.
Log.i(TAG, "Incoming and outgoing connections to " + info.mRemoteDevice +
". Cancel outgoing connection.");
if (mConnectThread != null) {
mConnectThread.interrupt();
}
// Now continue with new connection, including calling callback
mHeadset = new HeadsetBase(mPowerManager, mAdapter, mRemoteDevice,
info.mSocketFd, info.mRfcommChan, mConnectedStatusHandler);
mHeadsetType = type;
setState(BluetoothHeadset.STATE_CONNECTED, BluetoothHeadset.RESULT_SUCCESS);
mBtHandsfree.connectHeadset(mHeadset, mHeadsetType);
// Make sure that old outgoing connect thread is dead.
if (mConnectThread != null) {
try {
// TODO: Don't block in the main thread
Log.w(TAG, "Block in main thread to join stale outgoing connection thread");
mConnectThread.join();
} catch (InterruptedException e) {
Log.e(TAG, "Connection cancelled twice eh?", e);
}
mConnectThread = null;
}
if (DBG) log("Successfully used incoming connection, and cancelled outgoing " +
" connection");
break;
case BluetoothHeadset.STATE_CONNECTED:
Log.i(TAG, "Already connected to " + mRemoteDevice + ", disconnecting " +
info.mRemoteDevice);
headset = new HeadsetBase(mPowerManager, mAdapter, info.mRemoteDevice,
info.mSocketFd, info.mRfcommChan, null);
headset.disconnect();
break;
}
}" |
Inversion-Mutation | megadiff | "public void testInstrumentClass() throws Exception {
assertEquals(6, MyClass.staticSix());
final MyClass c1 = new MyClass();
assertEquals(0, c1.getA());
m_recorderStubFactory.assertNoMoreCalls();
m_instrumenter.createInstrumentedProxy(null, m_recorder, MyClass.class);
m_recorderStubFactory.assertNoMoreCalls();
MyClass.staticSix();
m_recorderStubFactory.assertSuccess("start");
m_recorderStubFactory.assertSuccess("end", true);
m_recorderStubFactory.assertNoMoreCalls();
assertEquals(0, c1.getA());
m_recorderStubFactory.assertNoMoreCalls();
final MyClass c2 = new MyClass();
m_recorderStubFactory.assertSuccess("start");
m_recorderStubFactory.assertSuccess("start");
m_recorderStubFactory.assertSuccess("end", true);
m_recorderStubFactory.assertSuccess("end", true);
assertEquals(0, c1.getA());
assertEquals(0, c2.getA());
m_recorderStubFactory.assertNoMoreCalls();
m_instrumenter.createInstrumentedProxy(null,
m_recorder,
MyExtendedClass.class);
m_recorderStubFactory.assertNoMoreCalls();
MyClass.staticSix();
// Single call - instrumenting extension shouldn't instrument superclass
// statics.
m_recorderStubFactory.assertSuccess("start");
m_recorderStubFactory.assertSuccess("end", true);
m_recorderStubFactory.assertNoMoreCalls();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testInstrumentClass" | "public void testInstrumentClass() throws Exception {
assertEquals(6, MyClass.staticSix());
final MyClass c1 = new MyClass();
assertEquals(0, c1.getA());
m_recorderStubFactory.assertNoMoreCalls();
m_instrumenter.createInstrumentedProxy(null, m_recorder, MyClass.class);
m_recorderStubFactory.assertNoMoreCalls();
MyClass.staticSix();
m_recorderStubFactory.assertSuccess("start");
<MASK>m_recorderStubFactory.assertSuccess("end", true);</MASK>
m_recorderStubFactory.assertNoMoreCalls();
assertEquals(0, c1.getA());
m_recorderStubFactory.assertNoMoreCalls();
final MyClass c2 = new MyClass();
m_recorderStubFactory.assertSuccess("start");
<MASK>m_recorderStubFactory.assertSuccess("end", true);</MASK>
m_recorderStubFactory.assertSuccess("start");
<MASK>m_recorderStubFactory.assertSuccess("end", true);</MASK>
assertEquals(0, c1.getA());
assertEquals(0, c2.getA());
m_recorderStubFactory.assertNoMoreCalls();
m_instrumenter.createInstrumentedProxy(null,
m_recorder,
MyExtendedClass.class);
m_recorderStubFactory.assertNoMoreCalls();
MyClass.staticSix();
// Single call - instrumenting extension shouldn't instrument superclass
// statics.
m_recorderStubFactory.assertSuccess("start");
<MASK>m_recorderStubFactory.assertSuccess("end", true);</MASK>
m_recorderStubFactory.assertNoMoreCalls();
}" |
Inversion-Mutation | megadiff | "@Override
public synchronized void onFailure(FetchException e, ClientGetter state, ObjectContainer container) {
try {
switch(e.getMode()) {
case FetchException.DATA_NOT_FOUND:
try {
WoTMessageList list = (WoTMessageList)mMessageManager.getMessageList(mMessageLists.get(state));
mMessageManager.onMessageFetchFailed(list.getReference(state.getURI()), MessageList.MessageFetchFailedReference.Reason.DataNotFound);
} catch (Exception ex) { /* NoSuchMessageList / NoSuchMessage */
Logger.error(this, "SHOULD NOT HAPPEN", ex);
assert(false);
}
finally {
Logger.error(this, "DNF for message " + state.getURI());
}
break;
case FetchException.CANCELLED:
Logger.debug(this, "Cancelled downloading Message " + state.getURI());
break;
default:
Logger.error(this, "Downloading message " + state.getURI() + " failed.", e);
break;
}
}
finally {
removeFetch(state);
/* FIXME: this will wake up the loop over and over again. we need to store the previous parallel fetch count and if waking
* up does not increase the fetch count do not wake up again
if(fetchCount() < MIN_PARALLEL_MESSAGE_FETCH_COUNT)
nextIteration();
*/
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onFailure" | "@Override
public synchronized void onFailure(FetchException e, ClientGetter state, ObjectContainer container) {
try {
switch(e.getMode()) {
case FetchException.DATA_NOT_FOUND:
try {
WoTMessageList list = (WoTMessageList)mMessageManager.getMessageList(mMessageLists.get(state));
mMessageManager.onMessageFetchFailed(list.getReference(state.getURI()), MessageList.MessageFetchFailedReference.Reason.DataNotFound);
} catch (Exception ex) { /* NoSuchMessageList / NoSuchMessage */
<MASK>assert(false);</MASK>
Logger.error(this, "SHOULD NOT HAPPEN", ex);
}
finally {
Logger.error(this, "DNF for message " + state.getURI());
}
break;
case FetchException.CANCELLED:
Logger.debug(this, "Cancelled downloading Message " + state.getURI());
break;
default:
Logger.error(this, "Downloading message " + state.getURI() + " failed.", e);
break;
}
}
finally {
removeFetch(state);
/* FIXME: this will wake up the loop over and over again. we need to store the previous parallel fetch count and if waking
* up does not increase the fetch count do not wake up again
if(fetchCount() < MIN_PARALLEL_MESSAGE_FETCH_COUNT)
nextIteration();
*/
}
}" |
Inversion-Mutation | megadiff | "@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
Sign s = (Sign)block.getState();
if(!plugin.loc.containsKey(block.getLocation())){
for(int i = 0; i<s.getLines().length; i++){
if(s.getLine(i).toLowerCase().contains("[sortal]") || s.getLine(i).toLowerCase().contains(plugin.signContains)){
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a [Sortal] sign!");
event.setCancelled(true);
}
}
}
return;
}
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!");
event.setCancelled(true);
return;
}
delLoc(block.getLocation());
plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onBlockBreak" | "@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(BlockBreakEvent event){
Block block = event.getBlock();
<MASK>Sign s = (Sign)block.getState();</MASK>
if ((block.getType() == Material.SIGN_POST || block.getType() == Material.WALL_SIGN)) {
if(!plugin.loc.containsKey(block.getLocation())){
for(int i = 0; i<s.getLines().length; i++){
if(s.getLine(i).toLowerCase().contains("[sortal]") || s.getLine(i).toLowerCase().contains(plugin.signContains)){
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a [Sortal] sign!");
event.setCancelled(true);
}
}
}
return;
}
if(!event.getPlayer().hasPermission("sortal.delsign")){
event.getPlayer().sendMessage("[Sortal] You do not have permissions to destroy a registered sign!");
event.setCancelled(true);
return;
}
delLoc(block.getLocation());
plugin.log.info("Registered sign destroyed by " + event.getPlayer().getDisplayName() + ", AKA " + event.getPlayer().getName() + "!");
}
}" |
Inversion-Mutation | megadiff | "@Override
final QueryPart getFunction0(Configuration configuration) {
switch (configuration.getDialect()) {
// Some databases don't accept predicates where column expressions
// are expected.
case CUBRID:
case DB2:
case FIREBIRD:
case ORACLE:
case SQLSERVER:
case SYBASE:
return Factory.decode().when(condition, inline(true)).otherwise(inline(false));
// These databases can inline predicates in column expression contexts
case DERBY:
case H2:
case HSQLDB:
case MYSQL:
case POSTGRES:
case SQLITE:
// Unknown (to be evaluated):
case ASE:
case INGRES:
return condition;
}
// The default, for new dialects
return condition;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getFunction0" | "@Override
final QueryPart getFunction0(Configuration configuration) {
switch (configuration.getDialect()) {
// Some databases don't accept predicates where column expressions
// are expected.
case CUBRID:
case DB2:
case FIREBIRD:
case ORACLE:
case SQLSERVER:
return Factory.decode().when(condition, inline(true)).otherwise(inline(false));
// These databases can inline predicates in column expression contexts
case DERBY:
case H2:
case HSQLDB:
case MYSQL:
case POSTGRES:
case SQLITE:
// Unknown (to be evaluated):
case ASE:
case INGRES:
<MASK>case SYBASE:</MASK>
return condition;
}
// The default, for new dialects
return condition;
}" |
Inversion-Mutation | megadiff | "protected void cleanup(Context ctx) throws IOException, InterruptedException {
super.cleanup(ctx);
instance.maybeCallMethod("cleanup", ctx);
instance.cleanup(ctx.getConfiguration());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "cleanup" | "protected void cleanup(Context ctx) throws IOException, InterruptedException {
super.cleanup(ctx);
<MASK>instance.cleanup(ctx.getConfiguration());</MASK>
instance.maybeCallMethod("cleanup", ctx);
}" |
Inversion-Mutation | megadiff | "public void testInspectionWithEqualityNotCountingOnNilParameter() throws Exception {
final RubyDebuggerProxy proxy = prepareProxy(
"class A",
" def ==(obj)",
" obj.non_existent",
" end",
"end",
"a = A.new",
"puts a");
final IRubyBreakpoint[] breakpoints = new IRubyBreakpoint[] {
new TestBreakpoint("test.rb", 7)
};
startDebugging(proxy, breakpoints, 1);
RubyFrame[] frames = suspendedThread.getFrames();
assertEquals("one frames", 1, frames.length);
RubyFrame frame = frames[0];
assertEquals(7, frame.getLine());
RubyVariable[] variables = frames[0].getVariables();
assertEquals("a", 1, variables.length);
variables[0].getValue().getVariables();
resumeSuspendedThread(proxy); // finish main thread
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testInspectionWithEqualityNotCountingOnNilParameter" | "public void testInspectionWithEqualityNotCountingOnNilParameter() throws Exception {
final RubyDebuggerProxy proxy = prepareProxy(
"class A",
" def ==(obj)",
" obj.non_existent",
" end",
"end",
"a = A.new",
"puts a");
final IRubyBreakpoint[] breakpoints = new IRubyBreakpoint[] {
new TestBreakpoint("test.rb", 7)
};
startDebugging(proxy, breakpoints, 1);
RubyFrame[] frames = suspendedThread.getFrames();
assertEquals("one frames", 1, frames.length);
RubyFrame frame = frames[0];
assertEquals(7, frame.getLine());
RubyVariable[] variables = frames[0].getVariables();
assertEquals("a", 1, variables.length);
<MASK>resumeSuspendedThread(proxy); // finish main thread</MASK>
variables[0].getValue().getVariables();
}" |
Inversion-Mutation | megadiff | "public void returnConnection(Channel c)
{
stateCheck(State.RUNNING, State.SHUTTING_DOWN, State.SHUTDOWN, State.HEALTH_CHECKING);
if (!inUse.remove(c))
{
throw new IllegalArgumentException("Channel not managed by this pool");
}
switch(state)
{
case SHUTTING_DOWN:
case SHUTDOWN:
closeConnection(c);
break;
case RUNNING:
case HEALTH_CHECKING:
default:
if (c.isOpen())
{
available.offerFirst(new ChannelWithIdleTime(c));
}
permits.release();
break;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "returnConnection" | "public void returnConnection(Channel c)
{
stateCheck(State.RUNNING, State.SHUTTING_DOWN, State.SHUTDOWN, State.HEALTH_CHECKING);
if (!inUse.remove(c))
{
throw new IllegalArgumentException("Channel not managed by this pool");
}
switch(state)
{
case SHUTTING_DOWN:
case SHUTDOWN:
closeConnection(c);
break;
case RUNNING:
case HEALTH_CHECKING:
default:
<MASK>permits.release();</MASK>
if (c.isOpen())
{
available.offerFirst(new ChannelWithIdleTime(c));
}
break;
}
}" |
Inversion-Mutation | megadiff | "public void configFile(String filename, String newconfig, boolean ignoreErrors) {
this.configname = filename;
Properties props = new Properties();
try {
props.load(new FileInputStream(filename));
long totsize = getSizeProperty(props, "totalsize");
TotalSizer totals = new TotalSizer(filename, totsize);
String applist = props.getProperty("apps");
if (applist == null) {
throw new IOException(filename + ": expected 'apps' property");
}
StringTokenizer tokens = new StringTokenizer(applist, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
long appsize = getSizeProperty(props, token + ".size");
AppSizer app = new AppSizer(totals, token, appsize);
for (int i=1; ;i++) {
String pname = token + "." + i;
String path = props.getProperty(pname + ".path");
if (path == null)
break;
long usize = getSizeProperty(props, pname + ".size");
new UrlSizer(app, urlBase, prefix, path, verbose, usize, ignoreErrors);
}
}
totals.connect();
totals.report();
if (newconfig != null) {
BufferedWriter bw = new BufferedWriter(new FileWriter(newconfig));
totals.generatePropertiesFile(bw);
bw.close();
}
}
catch (IOException ioe) {
System.err.println("Exception: " + ioe);
ioe.printStackTrace();
System.exit(1);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "configFile" | "public void configFile(String filename, String newconfig, boolean ignoreErrors) {
this.configname = filename;
Properties props = new Properties();
try {
long totsize = getSizeProperty(props, "totalsize");
TotalSizer totals = new TotalSizer(filename, totsize);
<MASK>props.load(new FileInputStream(filename));</MASK>
String applist = props.getProperty("apps");
if (applist == null) {
throw new IOException(filename + ": expected 'apps' property");
}
StringTokenizer tokens = new StringTokenizer(applist, ",");
while (tokens.hasMoreTokens()) {
String token = tokens.nextToken();
long appsize = getSizeProperty(props, token + ".size");
AppSizer app = new AppSizer(totals, token, appsize);
for (int i=1; ;i++) {
String pname = token + "." + i;
String path = props.getProperty(pname + ".path");
if (path == null)
break;
long usize = getSizeProperty(props, pname + ".size");
new UrlSizer(app, urlBase, prefix, path, verbose, usize, ignoreErrors);
}
}
totals.connect();
totals.report();
if (newconfig != null) {
BufferedWriter bw = new BufferedWriter(new FileWriter(newconfig));
totals.generatePropertiesFile(bw);
bw.close();
}
}
catch (IOException ioe) {
System.err.println("Exception: " + ioe);
ioe.printStackTrace();
System.exit(1);
}
}" |
Inversion-Mutation | megadiff | "public void testServerTcpClose() throws Exception {
final CountDownLatch latch = new CountDownLatch(2);
final AtomicBoolean clientOK = new AtomicBoolean(false);
final AtomicBoolean serverOK = new AtomicBoolean(false);
doConnectionTest(new Runnable() {
public void run() {
try {
assertTrue(latch.await(1200L, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
try {
channel.resumeReads();
} catch (Throwable t) {
try {
channel.close();
} catch (Throwable t2) {
t.printStackTrace();
latch.countDown();
throw new RuntimeException(t);
}
throw new RuntimeException(t);
}
}
public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
try {
final int c = channel.read(ByteBuffer.allocate(100));
if (c == -1) {
clientOK.set(true);
}
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
latch.countDown();
}
}, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
try {
channel.close();
} catch (Throwable t) {
t.printStackTrace();
latch.countDown();
throw new RuntimeException(t);
}
}
public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
serverOK.set(true);
latch.countDown();
}
});
assertTrue(serverOK.get());
assertTrue(clientOK.get());
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "testServerTcpClose" | "public void testServerTcpClose() throws Exception {
final CountDownLatch latch = new CountDownLatch(2);
final AtomicBoolean clientOK = new AtomicBoolean(false);
final AtomicBoolean serverOK = new AtomicBoolean(false);
doConnectionTest(new Runnable() {
public void run() {
try {
assertTrue(latch.await(1200L, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
try {
channel.resumeReads();
} catch (Throwable t) {
try {
channel.close();
} catch (Throwable t2) {
t.printStackTrace();
latch.countDown();
throw new RuntimeException(t);
}
throw new RuntimeException(t);
}
}
public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
try {
final int c = channel.read(ByteBuffer.allocate(100));
if (c == -1) {
clientOK.set(true);
}
channel.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
latch.countDown();
}
}, new IoHandler<ConnectedStreamChannel<SocketAddress>>() {
public void handleOpened(final ConnectedStreamChannel<SocketAddress> channel) {
try {
channel.close();
<MASK>serverOK.set(true);</MASK>
} catch (Throwable t) {
t.printStackTrace();
latch.countDown();
throw new RuntimeException(t);
}
}
public void handleReadable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleWritable(final ConnectedStreamChannel<SocketAddress> channel) {
}
public void handleClosed(final ConnectedStreamChannel<SocketAddress> channel) {
latch.countDown();
}
});
assertTrue(serverOK.get());
assertTrue(clientOK.get());
}" |
Inversion-Mutation | megadiff | "@Override
public void executeBatch(List<Tuple> inputs) {
ArrayList<Tuple> tuplesToAck = new ArrayList<Tuple>();
try {
Mutator<String> mutator = HFactory.createMutator(this.keyspace,
new StringSerializer());
for (Tuple input : inputs) {
String columnFamily = this.cfDeterminable
.determineColumnFamily(input);
Object rowKey = this.rkDeterminable.determineRowKey(input);
Fields fields = input.getFields();
for (int i = 0; i < fields.size(); i++) {
mutator.addInsertion(rowKey.toString(), columnFamily,
HFactory.createStringColumn(fields.get(i), input
.getValue(i).toString()));
}
tuplesToAck.add(input);
}
mutator.execute();
} catch (Throwable e) {
LOG.warn("Unable to write batch.", e);
} finally {
if (this.ackStrategy == AckStrategy.ACK_ON_WRITE) {
for (Tuple tupleToAck : tuplesToAck) {
this.collector.ack(tupleToAck);
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "executeBatch" | "@Override
public void executeBatch(List<Tuple> inputs) {
ArrayList<Tuple> tuplesToAck = new ArrayList<Tuple>();
try {
Mutator<String> mutator = HFactory.createMutator(this.keyspace,
new StringSerializer());
for (Tuple input : inputs) {
String columnFamily = this.cfDeterminable
.determineColumnFamily(input);
Object rowKey = this.rkDeterminable.determineRowKey(input);
Fields fields = input.getFields();
for (int i = 0; i < fields.size(); i++) {
mutator.addInsertion(rowKey.toString(), columnFamily,
HFactory.createStringColumn(fields.get(i), input
.getValue(i).toString()));
<MASK>tuplesToAck.add(input);</MASK>
}
}
mutator.execute();
} catch (Throwable e) {
LOG.warn("Unable to write batch.", e);
} finally {
if (this.ackStrategy == AckStrategy.ACK_ON_WRITE) {
for (Tuple tupleToAck : tuplesToAck) {
this.collector.ack(tupleToAck);
}
}
}
}" |
Inversion-Mutation | megadiff | "public DataSourceTableModel(TableEditableElement element) {
this.element = element;
dataSource = element.getDataSource();
dataSourceListener = new ModificationListener();
if(dataSource.isEditable()) {
try {
dataSource.addEditionListener(dataSourceListener);
dataSource.addMetadataEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
LOGGER.warn(I18N.tr("The TableEditor cannot listen to source modifications"), ex);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "DataSourceTableModel" | "public DataSourceTableModel(TableEditableElement element) {
this.element = element;
dataSource = element.getDataSource();
dataSourceListener = new ModificationListener();
if(dataSource.isEditable()) {
try {
dataSource.addEditionListener(dataSourceListener);
} catch (UnsupportedOperationException ex) {
LOGGER.warn(I18N.tr("The TableEditor cannot listen to source modifications"), ex);
}
}
<MASK>dataSource.addMetadataEditionListener(dataSourceListener);</MASK>
}" |
Inversion-Mutation | megadiff | "protected boolean perRequestFilter(AtmosphereResource r, Entry msg, boolean cache) {
// A broadcaster#broadcast(msg,Set) may contains null value.
if (r == null) {
logger.trace("Null AtmosphereResource passed inside a Set");
return false;
}
if (isAtmosphereResourceValid(r)) {
if (bc.hasPerRequestFilters()) {
BroadcastAction a = bc.filter(r, msg.message, msg.originalMessage);
if (a.action() == BroadcastAction.ACTION.ABORT) {
return false;
}
msg.message = a.message();
}
} else {
if (cache) {
logger.warn("Request is no longer valid {}, Message {} will be cached", r.uuid(), msg.originalMessage);
bc.getBroadcasterCache().addToCache(getID(), r, new BroadcastMessage(msg.originalMessage));
}
return false;
}
return true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "perRequestFilter" | "protected boolean perRequestFilter(AtmosphereResource r, Entry msg, boolean cache) {
// A broadcaster#broadcast(msg,Set) may contains null value.
if (r == null) {
logger.trace("Null AtmosphereResource passed inside a Set");
return false;
}
if (isAtmosphereResourceValid(r)) {
if (bc.hasPerRequestFilters()) {
BroadcastAction a = bc.filter(r, msg.message, msg.originalMessage);
if (a.action() == BroadcastAction.ACTION.ABORT) {
return false;
}
msg.message = a.message();
}
} else {
<MASK>logger.warn("Request is no longer valid {}, Message {} will be cached", r.uuid(), msg.originalMessage);</MASK>
if (cache) {
bc.getBroadcasterCache().addToCache(getID(), r, new BroadcastMessage(msg.originalMessage));
}
return false;
}
return true;
}" |
Inversion-Mutation | megadiff | "public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
System.in.read();
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "main" | "public static void main(String[] args) throws IOException {
int seat_num=0;
int[] one_TwoTogether;
one_TwoTogether = new int[300];
int index=1;
int all=0;
int info=0;
int alone=0;
int seatNum_alone_cp=0;
int placeOnlyFor_1=0;
int placeOnlyFor_1SeatNum=0;
for (;all<=162;){
<MASK>System.in.read();</MASK>
seat_num+=1;
ArrayList<Integer> l = new ArrayList<Integer>();
Passengers newPassenger = new Passengers();
int countOfPassengers=0;
if (newPassenger.passengers==2){
countOfPassengers+=2;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==3){
countOfPassengers+=3;
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
l.add(newPassenger.passengers);
} else if (newPassenger.passengers==1){
countOfPassengers++;
l.add(newPassenger.passengers);
}
if (countOfPassengers==3) {
System.out.println("seat N: "+(seat_num)+" "+(seat_num+1)+" "+(seat_num+2));
seat_num=seat_num+2;
}else if (countOfPassengers==2){
System.out.println("seat N: "+seat_num+" "+ (seat_num+1));
info++;
if (info>0){
index+=1;
one_TwoTogether[index]=seat_num+2;
}
seat_num=seat_num+2;
}else if (countOfPassengers==1){
if (alone==1){
System.out.println("seat N: "+(seatNum_alone_cp+1));
alone=0;
placeOnlyFor_1++;
placeOnlyFor_1SeatNum=seatNum_alone_cp+2;
seat_num-=1;
} else if (info==0 && placeOnlyFor_1!=1){
System.out.println("seat N: "+seat_num);
seatNum_alone_cp=seat_num;
alone++;
seat_num+=2;
} else if (info>0){
System.out.println("seat N: "+one_TwoTogether[index]);
index--;
info--;
seat_num-=1;
} else if (placeOnlyFor_1==1){
System.out.println("seat N: "+placeOnlyFor_1SeatNum);
placeOnlyFor_1--;
seat_num-=1;
}
}
System.out.println(l+"\n");
if (seat_num>=162){
break;
}
}
System.out.println("Free seats: "+((alone*2)+info+placeOnlyFor_1));
}" |
Inversion-Mutation | megadiff | "private void findRandomItem(TreeMap<Double, String> randomTreeMap)
{
if(randomTreeMap.size() > 1)
{
randomTreeMap.remove(randomTreeMap.ceilingEntry(Math.random()).getKey());
findRandomItem(randomTreeMap);
}
else
{
return;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "findRandomItem" | "private void findRandomItem(TreeMap<Double, String> randomTreeMap)
{
<MASK>randomTreeMap.remove(randomTreeMap.ceilingEntry(Math.random()).getKey());</MASK>
if(randomTreeMap.size() > 1)
{
findRandomItem(randomTreeMap);
}
else
{
return;
}
}" |
Inversion-Mutation | megadiff | "public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
input = container.getInput();
GameState state = game.getCurrentState();
if (!(state instanceof IWorld)) return;
world = (IWorld) game.getCurrentState();
prevMotionX = motionX;
prevMotionY = motionY;
if (getMenu() != null) {
readFromOptions();
writeToOptions();
}
x += motionX;
y += motionY;
onEdgeX = false;
onEdgeY = false;
if (x < 0) {
x = 0;
motionX = -motionX * 0.4F;
onEdgeX = true;
}
if (y < 0) {
y = 0;
motionY = -motionY * 0.4F;
onEdgeY = true;
}
if (x > Game.width - width) {
x = Game.width - width;
motionX = -motionX * 0.4F;
onEdgeX = true;
}
if (y > Game.height - height) {
y = Game.height - height;
motionY = -motionY * 0.4F;
onEdgeY = true;
}
for (int i = 0; i < world.getEntities().size(); i++) {
Entity e = world.getEntities().get(i);
if (e != this && intersects(e)) {
onHit(e);
float xOverlap = 0;
float yOverlap = 0;
if (e.x + e.width > x && x + width > e.x + e.width) {
xOverlap = e.x + e.width - x;
}
if (x + width > e.x && x < e.x) {
xOverlap = e.x - (x + width);
}
if (x == e.x) {
xOverlap = width;
}
if (e.y + e.height > y && y + height > e.y + e.height) {
yOverlap = e.y + e.height - y;
}
if (y + height > e.y && y < e.y) {
yOverlap = e.y - (y + height);
}
if (y == e.y) {
yOverlap = height;
}
if (xOverlap != 0 && yOverlap != 0) {
if (Math.abs(xOverlap) < Math.abs(yOverlap)) {
x += xOverlap + xOverlap / Math.abs(xOverlap) * 0.1 + -prevMotionX * 0.1;
if (e.onEdgeX) {
motionX = -prevMotionX * 0.8F;
} else {
e.motionX = prevMotionX * 0.8F;
motionX = e.prevMotionX * 0.8F;
}
} else {
y += yOverlap + yOverlap / Math.abs(yOverlap) * 0.1 + -prevMotionY * 0.1;
if (e.onEdgeY) {
motionY = -prevMotionY * 0.8F;
} else {
e.motionY = prevMotionY * 0.8F;
motionY = e.prevMotionY * 0.8F;
}
}
}
}
}
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON) || input.isMouseButtonDown(Input.MOUSE_RIGHT_BUTTON)) {
int mouseX = Mouse.getX();
int mouseY = Game.height - Mouse.getY();
if (getMenu() != null) {
if (!(mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height)
&& !(mouseX >= getMenu().x1 && mouseX <= getMenu().x2 && mouseY >= getMenu().y1 && mouseY <= getMenu().y2)) {
getMenu().close();
}
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "update" | "public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
input = container.getInput();
GameState state = game.getCurrentState();
if (!(state instanceof IWorld)) return;
world = (IWorld) game.getCurrentState();
prevMotionX = motionX;
prevMotionY = motionY;
if (getMenu() != null) {
<MASK>writeToOptions();</MASK>
readFromOptions();
}
x += motionX;
y += motionY;
onEdgeX = false;
onEdgeY = false;
if (x < 0) {
x = 0;
motionX = -motionX * 0.4F;
onEdgeX = true;
}
if (y < 0) {
y = 0;
motionY = -motionY * 0.4F;
onEdgeY = true;
}
if (x > Game.width - width) {
x = Game.width - width;
motionX = -motionX * 0.4F;
onEdgeX = true;
}
if (y > Game.height - height) {
y = Game.height - height;
motionY = -motionY * 0.4F;
onEdgeY = true;
}
for (int i = 0; i < world.getEntities().size(); i++) {
Entity e = world.getEntities().get(i);
if (e != this && intersects(e)) {
onHit(e);
float xOverlap = 0;
float yOverlap = 0;
if (e.x + e.width > x && x + width > e.x + e.width) {
xOverlap = e.x + e.width - x;
}
if (x + width > e.x && x < e.x) {
xOverlap = e.x - (x + width);
}
if (x == e.x) {
xOverlap = width;
}
if (e.y + e.height > y && y + height > e.y + e.height) {
yOverlap = e.y + e.height - y;
}
if (y + height > e.y && y < e.y) {
yOverlap = e.y - (y + height);
}
if (y == e.y) {
yOverlap = height;
}
if (xOverlap != 0 && yOverlap != 0) {
if (Math.abs(xOverlap) < Math.abs(yOverlap)) {
x += xOverlap + xOverlap / Math.abs(xOverlap) * 0.1 + -prevMotionX * 0.1;
if (e.onEdgeX) {
motionX = -prevMotionX * 0.8F;
} else {
e.motionX = prevMotionX * 0.8F;
motionX = e.prevMotionX * 0.8F;
}
} else {
y += yOverlap + yOverlap / Math.abs(yOverlap) * 0.1 + -prevMotionY * 0.1;
if (e.onEdgeY) {
motionY = -prevMotionY * 0.8F;
} else {
e.motionY = prevMotionY * 0.8F;
motionY = e.prevMotionY * 0.8F;
}
}
}
}
}
if (input.isMouseButtonDown(Input.MOUSE_LEFT_BUTTON) || input.isMouseButtonDown(Input.MOUSE_RIGHT_BUTTON)) {
int mouseX = Mouse.getX();
int mouseY = Game.height - Mouse.getY();
if (getMenu() != null) {
if (!(mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height)
&& !(mouseX >= getMenu().x1 && mouseX <= getMenu().x2 && mouseY >= getMenu().y1 && mouseY <= getMenu().y2)) {
getMenu().close();
}
}
}
}" |
Inversion-Mutation | megadiff | "private void getAnagrams(String rack, String start, String contains, String end) {
// Set up the callback object.
AsyncCallback<Result> callback = new AsyncCallback<Result>() {
public void onFailure(Throwable caught) {
view.setError("failure!");
}
public void onSuccess(Result results) {
if (results.getError()) {
view.setError("Invalid query. You may only have letters and wildcard characters. "
+ "Wildcard characters may only be placed in the rack and there can be a maximum of 10 "
+ "characters.");
} else {
view.setError("");
view.setResults(results.getWords());
}
}
};
// Make the call to the solve service.
if (validateInput()) {
view.setError("Loading...");
wwfSolveService.findAnagrams(rack, start, contains, end, callback);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getAnagrams" | "private void getAnagrams(String rack, String start, String contains, String end) {
// Set up the callback object.
<MASK>view.setError("Loading...");</MASK>
AsyncCallback<Result> callback = new AsyncCallback<Result>() {
public void onFailure(Throwable caught) {
view.setError("failure!");
}
public void onSuccess(Result results) {
if (results.getError()) {
view.setError("Invalid query. You may only have letters and wildcard characters. "
+ "Wildcard characters may only be placed in the rack and there can be a maximum of 10 "
+ "characters.");
} else {
view.setError("");
view.setResults(results.getWords());
}
}
};
// Make the call to the solve service.
if (validateInput()) {
wwfSolveService.findAnagrams(rack, start, contains, end, callback);
}
}" |
Inversion-Mutation | megadiff | "private void connect() throws IOException {
try {
socket = new Socket();
socket.setSoTimeout(timeout); // the timeout value to be used in milliseconds
socket.connect(server);
out = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
throw e;
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "connect" | "private void connect() throws IOException {
try {
socket = new Socket();
<MASK>socket.connect(server);</MASK>
socket.setSoTimeout(timeout); // the timeout value to be used in milliseconds
out = new BufferedOutputStream(socket.getOutputStream());
} catch (IOException e) {
throw e;
}
}" |
Inversion-Mutation | megadiff | "protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
UrlMappingsHolder holder = lookupUrlMappings();
GrailsApplication application = lookupApplication();
GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST);
GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE);
if(controllers == null || controllers.length == 0 || holder == null) {
processFilterChain(request, response, filterChain);
return;
}
if(LOG.isDebugEnabled()) {
LOG.debug("Executing URL mapping filter...");
LOG.debug(holder);
}
String uri = urlHelper.getPathWithinApplication(request);
UrlMappingInfo[] urlInfos = holder.matchAll(uri);
WrappedResponseHolder.setWrappedResponse(response);
boolean dispatched = false;
try {
for (int i = 0; i < urlInfos.length; i++) {
UrlMappingInfo info = urlInfos[i];
if(info!=null) {
String action = info.getActionName() == null ? "" : info.getActionName();
info.configure(webRequest);
GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action);
if(controller == null) {
continue;
}
dispatched = true;
String forwardUrl = buildDispatchUrlForMapping(request, info);
if(LOG.isDebugEnabled()) {
LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]");
}
//populateParamsForMapping(info);
RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl);
populateWebRequestWithInfo(webRequest, info);
WebUtils.exposeForwardRequestAttributes(request);
dispatcher.forward(request, response);
break;
}
}
}
finally {
WrappedResponseHolder.setWrappedResponse(null);
}
if(!dispatched) {
if(LOG.isDebugEnabled()) {
LOG.debug("No match found, processing remaining filter chain.");
}
processFilterChain(request, response, filterChain);
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doFilterInternal" | "protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
UrlMappingsHolder holder = lookupUrlMappings();
GrailsApplication application = lookupApplication();
GrailsWebRequest webRequest = (GrailsWebRequest)request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST);
GrailsClass[] controllers = application.getArtefacts(ControllerArtefactHandler.TYPE);
if(controllers == null || controllers.length == 0 || holder == null) {
processFilterChain(request, response, filterChain);
return;
}
if(LOG.isDebugEnabled()) {
LOG.debug("Executing URL mapping filter...");
LOG.debug(holder);
}
String uri = urlHelper.getPathWithinApplication(request);
UrlMappingInfo[] urlInfos = holder.matchAll(uri);
WrappedResponseHolder.setWrappedResponse(response);
boolean dispatched = false;
try {
for (int i = 0; i < urlInfos.length; i++) {
UrlMappingInfo info = urlInfos[i];
if(info!=null) {
String action = info.getActionName() == null ? "" : info.getActionName();
GrailsClass controller = application.getArtefactForFeature(ControllerArtefactHandler.TYPE, SLASH + info.getControllerName() + SLASH + action);
if(controller == null) {
continue;
}
dispatched = true;
<MASK>info.configure(webRequest);</MASK>
String forwardUrl = buildDispatchUrlForMapping(request, info);
if(LOG.isDebugEnabled()) {
LOG.debug("Matched URI ["+uri+"] to URL mapping ["+info+"], forwarding to ["+forwardUrl+"] with response ["+response.getClass()+"]");
}
//populateParamsForMapping(info);
RequestDispatcher dispatcher = request.getRequestDispatcher(forwardUrl);
populateWebRequestWithInfo(webRequest, info);
WebUtils.exposeForwardRequestAttributes(request);
dispatcher.forward(request, response);
break;
}
}
}
finally {
WrappedResponseHolder.setWrappedResponse(null);
}
if(!dispatched) {
if(LOG.isDebugEnabled()) {
LOG.debug("No match found, processing remaining filter chain.");
}
processFilterChain(request, response, filterChain);
}
}" |
Inversion-Mutation | megadiff | "@Override
protected JComponent createRightComponent() {
JPanel p = new JPanel();
btnSetAdminPass = new JButton("Set Admin Password");
btnSetAdminPass.setOpaque(false);
btnSetLockPass = new JButton("Set Unlock Password");
btnSetLockPass.setOpaque(false);
p.setLayout(new MigLayout(
(System.getProperty("DEBUG_UI") == null ? "" : "debug,") +
"al 50% 50%, gapy 10"));
p.add(btnSetLockPass, "align center, growx, wrap");
p.add(btnSetAdminPass, "align center, growx, wrap");
return p;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createRightComponent" | "@Override
protected JComponent createRightComponent() {
JPanel p = new JPanel();
btnSetAdminPass = new JButton("Set Admin Password");
btnSetAdminPass.setOpaque(false);
btnSetLockPass = new JButton("Set Unlock Password");
btnSetLockPass.setOpaque(false);
p.setLayout(new MigLayout(
(System.getProperty("DEBUG_UI") == null ? "" : "debug,") +
"al 50% 50%, gapy 10"));
<MASK>p.add(btnSetAdminPass, "align center, growx, wrap");</MASK>
p.add(btnSetLockPass, "align center, growx, wrap");
return p;
}" |
Inversion-Mutation | megadiff | "@Override
public void toggleState(Context context) {
boolean enabled = getDataState(context);
SharedPreferences preferences = context.getSharedPreferences(WidgetSettings.WIDGET_PREF_MAIN,
Context.MODE_PRIVATE);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (enabled) {
cm.setMobileDataEnabled(false);
if (preferences.getBoolean(WidgetSettings.AUTO_DISABLE_3G, false)) {
NetworkModeButton.getInstance().toggleState(context,SettingsAppWidgetProvider.STATE_DISABLED);
}
} else {
if (preferences.getBoolean(WidgetSettings.AUTO_ENABLE_3G, false) &&
NetworkModeButton.getInstance().isDisabled(context)) {
SettingsAppWidgetProvider.logD("MobileData: Will enable 3G first");
NetworkModeButton.getInstance().toggleState(context,SettingsAppWidgetProvider.STATE_ENABLED);
stateChangeRequest=true;
} else {
cm.setMobileDataEnabled(true);
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "toggleState" | "@Override
public void toggleState(Context context) {
boolean enabled = getDataState(context);
SharedPreferences preferences = context.getSharedPreferences(WidgetSettings.WIDGET_PREF_MAIN,
Context.MODE_PRIVATE);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (enabled) {
if (preferences.getBoolean(WidgetSettings.AUTO_DISABLE_3G, false)) {
<MASK>cm.setMobileDataEnabled(false);</MASK>
NetworkModeButton.getInstance().toggleState(context,SettingsAppWidgetProvider.STATE_DISABLED);
}
} else {
if (preferences.getBoolean(WidgetSettings.AUTO_ENABLE_3G, false) &&
NetworkModeButton.getInstance().isDisabled(context)) {
SettingsAppWidgetProvider.logD("MobileData: Will enable 3G first");
NetworkModeButton.getInstance().toggleState(context,SettingsAppWidgetProvider.STATE_ENABLED);
stateChangeRequest=true;
} else {
cm.setMobileDataEnabled(true);
}
}
}" |
Inversion-Mutation | megadiff | "public Graphemeui() {
description = new Description();
canvas = new Canvas(this);
chat = Chat.getInstance(this);
drawing = new DrawingImpl();
tools = new Toolbox(this);
graphManagerFactory = GraphManager2dFactory.getInstance();
graphManager = graphManagerFactory.makeDefaultGraphManager();
drawing.setOffset(0, 0);
drawing.setZoom(1);
graphManager.addRedrawCallback(new Runnable() {
@Override
public void run() {
drawing.renderGraph(canvas.canvasPanel, graphManager.getEdgeDrawables(),
graphManager.getVertexDrawables());// graph
// goes
// here!
}
});
graphInfo = GraphInfo.getInstance(this);
selectedVertices = new ArrayList<VertexDrawable>();
selectedEdges = new ArrayList<EdgeDrawable>();
isHotkeysEnabled = true;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Graphemeui" | "public Graphemeui() {
description = new Description();
<MASK>tools = new Toolbox(this);</MASK>
canvas = new Canvas(this);
chat = Chat.getInstance(this);
drawing = new DrawingImpl();
graphManagerFactory = GraphManager2dFactory.getInstance();
graphManager = graphManagerFactory.makeDefaultGraphManager();
drawing.setOffset(0, 0);
drawing.setZoom(1);
graphManager.addRedrawCallback(new Runnable() {
@Override
public void run() {
drawing.renderGraph(canvas.canvasPanel, graphManager.getEdgeDrawables(),
graphManager.getVertexDrawables());// graph
// goes
// here!
}
});
graphInfo = GraphInfo.getInstance(this);
selectedVertices = new ArrayList<VertexDrawable>();
selectedEdges = new ArrayList<EdgeDrawable>();
isHotkeysEnabled = true;
}" |
Inversion-Mutation | megadiff | "protected void scanPIData(String target, XMLString data)
throws IOException, XNIException {
// check target
if (target.length() == 3) {
char c0 = Character.toLowerCase(target.charAt(0));
char c1 = Character.toLowerCase(target.charAt(1));
char c2 = Character.toLowerCase(target.charAt(2));
if (c0 == 'x' && c1 == 'm' && c2 == 'l') {
reportFatalError("ReservedPITarget", null);
}
}
// spaces
if (!fEntityScanner.skipSpaces()) {
if (fEntityScanner.skipString("?>")) {
// we found the end, there is no data
data.clear();
return;
}
else {
// if there is data there should be some space
reportFatalError("SpaceRequiredInPI", null);
}
}
fStringBuffer.clear();
// data
if (fEntityScanner.scanData("?>", fStringBuffer)) {
do {
int c = fEntityScanner.peekChar();
if (c != -1) {
if (XMLChar.isHighSurrogate(c)) {
scanSurrogates(fStringBuffer);
}
else if (XMLChar.isInvalid(c)) {
reportFatalError("InvalidCharInPI",
new Object[]{Integer.toHexString(c)});
fEntityScanner.scanChar();
}
}
} while (fEntityScanner.scanData("?>", fStringBuffer));
}
data.setValues(fStringBuffer);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "scanPIData" | "protected void scanPIData(String target, XMLString data)
throws IOException, XNIException {
// check target
if (target.length() == 3) {
char c0 = Character.toLowerCase(target.charAt(0));
char c1 = Character.toLowerCase(target.charAt(1));
char c2 = Character.toLowerCase(target.charAt(2));
if (c0 == 'x' && c1 == 'm' && c2 == 'l') {
reportFatalError("ReservedPITarget", null);
}
}
// spaces
if (!fEntityScanner.skipSpaces()) {
if (fEntityScanner.skipString("?>")) {
// we found the end, there is no data
data.clear();
return;
}
else {
// if there is data there should be some space
reportFatalError("SpaceRequiredInPI", null);
}
}
fStringBuffer.clear();
// data
if (fEntityScanner.scanData("?>", fStringBuffer)) {
do {
int c = fEntityScanner.peekChar();
if (c != -1) {
if (XMLChar.isHighSurrogate(c)) {
scanSurrogates(fStringBuffer);
}
else if (XMLChar.isInvalid(c)) {
reportFatalError("InvalidCharInPI",
new Object[]{Integer.toHexString(c)});
fEntityScanner.scanChar();
}
}
} while (fEntityScanner.scanData("?>", fStringBuffer));
<MASK>data.setValues(fStringBuffer);</MASK>
}
}" |
Inversion-Mutation | megadiff | "public void drawAllOverlays(boolean flare) {
userLocation = getUserLocation();
if (userLocation == null) {
printErrorAndExit("3: NULL userLocation in drawMap");
}
if (mapController == null) {
printErrorAndExit("4: NULL mapController in drawMap");
}
if (mapView == null) {
printErrorAndExit("5: NULL mapView in drawMap");
}
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays = addPlayers(listOfOverlays);
listOfOverlays = reportPlayer(listOfOverlays);
if (flare) {
listOfOverlays = reportFlare(listOfOverlays);
}
listOfOverlays = addFlares(listOfOverlays);
mapView.invalidate(); // Calls onDraw()
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "drawAllOverlays" | "public void drawAllOverlays(boolean flare) {
userLocation = getUserLocation();
if (userLocation == null) {
printErrorAndExit("3: NULL userLocation in drawMap");
}
if (mapController == null) {
printErrorAndExit("4: NULL mapController in drawMap");
}
if (mapView == null) {
printErrorAndExit("5: NULL mapView in drawMap");
}
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays = addPlayers(listOfOverlays);
<MASK>listOfOverlays = addFlares(listOfOverlays);</MASK>
listOfOverlays = reportPlayer(listOfOverlays);
if (flare) {
listOfOverlays = reportFlare(listOfOverlays);
}
mapView.invalidate(); // Calls onDraw()
}" |
Inversion-Mutation | megadiff | "private static void launchGui() throws SQLException, IOException {
//run Mac OS X customizations if user is on a Mac
//this code must run before *anything* else graphics-related
Image appIcon = ImageManager.getAppIcon().getImage();
MacSupport.initIfMac("EMC Shopkeeper", false, appIcon, new MacHandler() {
@Override
public void handleQuit(Object applicationEvent) {
mainFrame.exit();
}
@Override
public void handleAbout(Object applicationEvent) {
AboutDialog.show(mainFrame);
}
});
//show splash screen
final SplashFrame splash = new SplashFrame();
splash.setVisible(true);
//set uncaught exception handler
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable thrown) {
ErrorDialog.show(null, "An error occurred.", thrown);
}
});
//init the cache
File cacheDir = new File(profileDir, "cache");
initCacheDir(cacheDir);
//start the profile image loader
ProfileImageLoader profileImageLoader = new ProfileImageLoader(cacheDir, settings);
DbListener listener = new DbListener() {
@Override
public void onCreate() {
splash.setMessage("Creating database...");
}
@Override
public void onBackup(int oldVersion, int newVersion) {
splash.setMessage("Preparing for database update...");
}
@Override
public void onMigrate(int oldVersion, int newVersion) {
splash.setMessage("Updating database...");
}
};
//connect to database
splash.setMessage("Starting database...");
DbDao dao;
try {
dao = new DirbyEmbeddedDbDao(dbDir, listener);
} catch (SQLException e) {
if ("XJ040".equals(e.getSQLState())) {
splash.dispose();
JOptionPane.showMessageDialog(null, "EMC Shopkeeper is already running.", "Already running", JOptionPane.ERROR_MESSAGE);
return;
}
throw e;
}
//update database schema
ReportSender reportSender = ReportSender.instance();
reportSender.setDatabaseVersion(dao.selectDbVersion());
dao.updateToLatestVersion(listener);
reportSender.setDatabaseVersion(dao.selectDbVersion());
//tweak tooltip settings
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.setInitialDelay(0);
toolTipManager.setDismissDelay(30000);
//pre-load the labels for the item suggest fields
splash.setMessage("Loading item icons...");
ItemSuggestField.init(dao);
mainFrame = new MainFrame(settings, dao, logManager, profileImageLoader, profileDir.getName());
mainFrame.setVisible(true);
splash.dispose();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "launchGui" | "private static void launchGui() throws SQLException, IOException {
//run Mac OS X customizations if user is on a Mac
//this code must run before *anything* else graphics-related
Image appIcon = ImageManager.getAppIcon().getImage();
MacSupport.initIfMac("EMC Shopkeeper", false, appIcon, new MacHandler() {
@Override
public void handleQuit(Object applicationEvent) {
mainFrame.exit();
}
@Override
public void handleAbout(Object applicationEvent) {
AboutDialog.show(mainFrame);
}
});
//show splash screen
final SplashFrame splash = new SplashFrame();
splash.setVisible(true);
//set uncaught exception handler
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable thrown) {
ErrorDialog.show(null, "An error occurred.", thrown);
}
});
//init the cache
File cacheDir = new File(profileDir, "cache");
initCacheDir(cacheDir);
//start the profile image loader
ProfileImageLoader profileImageLoader = new ProfileImageLoader(cacheDir, settings);
DbListener listener = new DbListener() {
@Override
public void onCreate() {
splash.setMessage("Creating database...");
}
@Override
public void onBackup(int oldVersion, int newVersion) {
splash.setMessage("Preparing for database update...");
}
@Override
public void onMigrate(int oldVersion, int newVersion) {
splash.setMessage("Updating database...");
}
};
//connect to database
splash.setMessage("Starting database...");
DbDao dao;
try {
dao = new DirbyEmbeddedDbDao(dbDir, listener);
} catch (SQLException e) {
if ("XJ040".equals(e.getSQLState())) {
<MASK>JOptionPane.showMessageDialog(null, "EMC Shopkeeper is already running.", "Already running", JOptionPane.ERROR_MESSAGE);</MASK>
splash.dispose();
return;
}
throw e;
}
//update database schema
ReportSender reportSender = ReportSender.instance();
reportSender.setDatabaseVersion(dao.selectDbVersion());
dao.updateToLatestVersion(listener);
reportSender.setDatabaseVersion(dao.selectDbVersion());
//tweak tooltip settings
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.setInitialDelay(0);
toolTipManager.setDismissDelay(30000);
//pre-load the labels for the item suggest fields
splash.setMessage("Loading item icons...");
ItemSuggestField.init(dao);
mainFrame = new MainFrame(settings, dao, logManager, profileImageLoader, profileDir.getName());
mainFrame.setVisible(true);
splash.dispose();
}" |
Inversion-Mutation | megadiff | "@Override
@SuppressWarnings("unchecked")
protected void setBundles(List<VersionedClause> bundles) {
this.bundles = bundles;
@SuppressWarnings("rawtypes")
List displayList;
if (projectBuilders.isEmpty())
displayList = bundles;
else {
displayList = new ArrayList<Object>(projectBuilders.size() + bundles.size());
displayList.addAll(bundles);
displayList.addAll(projectBuilders);
}
viewer.setInput(displayList);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setBundles" | "@Override
@SuppressWarnings("unchecked")
protected void setBundles(List<VersionedClause> bundles) {
this.bundles = bundles;
@SuppressWarnings("rawtypes")
List displayList;
if (projectBuilders.isEmpty())
displayList = bundles;
else {
displayList = new ArrayList<Object>(projectBuilders.size() + bundles.size());
<MASK>displayList.addAll(projectBuilders);</MASK>
displayList.addAll(bundles);
}
viewer.setInput(displayList);
}" |
Inversion-Mutation | megadiff | "private void createNewAttribute(final String type) {
final String[] existingAttrs = CyAttributesUtils.getVisibleAttributeNames(attributes).toArray(new String[0]);
String newAttribName = null;
do {
newAttribName = JOptionPane.showInputDialog(this, "Please enter new attribute name: ",
"Create New " + type + " Attribute",
JOptionPane.QUESTION_MESSAGE);
if (newAttribName == null)
return;
if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) {
JOptionPane.showMessageDialog(Cytoscape.getDesktop(),
"Attribute " + newAttribName + " already exists.",
"Error!", JOptionPane.ERROR_MESSAGE);
newAttribName = null;
}
} while (newAttribName == null);
final String testVal = "dummy";
if (type.equals("String"))
attributes.setAttribute(testVal, newAttribName, new String());
else if (type.equals("Floating Point"))
attributes.setAttribute(testVal, newAttribName, new Double(0));
else if (type.equals("Integer"))
attributes.setAttribute(testVal, newAttribName, new Integer(0));
else if (type.equals("Boolean"))
attributes.setAttribute(testVal, newAttribName, new Boolean(false));
else if (type.equals("String List")) {
final List<String> newStringList = new ArrayList<String>();
newStringList.add("dummy");
attributes.setListAttribute(testVal, newAttribName, newStringList);
} else if (type.equals("Floating Point List")) {
final List<Double> newDoubleList = new ArrayList<Double>();
newDoubleList.add(0.0);
attributes.setListAttribute(testVal, newAttribName, newDoubleList);
} else if (type.equals("Integer List")) {
final List<Integer> newIntList = new ArrayList<Integer>();
newIntList.add(0);
attributes.setListAttribute(testVal, newAttribName, newIntList);
} else if (type.equals("Boolean List")) {
final List<Boolean> newBooleanList = new ArrayList<Boolean>();
newBooleanList.add(true);
attributes.setListAttribute(testVal, newAttribName, newBooleanList);
} else
throw new IllegalArgumentException("unknown attribute type \"" + type + "\"!");
attributes.deleteAttribute(testVal, newAttribName);
// Update list selection
orderedCol.add(newAttribName);
Cytoscape.getSwingPropertyChangeSupport()
.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null);
Cytoscape.getPropertyChangeSupport().firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null);
tableModel.setTableData(null, orderedCol);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createNewAttribute" | "private void createNewAttribute(final String type) {
final String[] existingAttrs = CyAttributesUtils.getVisibleAttributeNames(attributes).toArray(new String[0]);
String <MASK>newAttribName = null;</MASK>
do {
newAttribName = JOptionPane.showInputDialog(this, "Please enter new attribute name: ",
"Create New " + type + " Attribute",
JOptionPane.QUESTION_MESSAGE);
if (newAttribName == null)
return;
if (Arrays.binarySearch(existingAttrs, newAttribName) >= 0) {
<MASK>newAttribName = null;</MASK>
JOptionPane.showMessageDialog(Cytoscape.getDesktop(),
"Attribute " + newAttribName + " already exists.",
"Error!", JOptionPane.ERROR_MESSAGE);
}
} while (newAttribName == null);
final String testVal = "dummy";
if (type.equals("String"))
attributes.setAttribute(testVal, newAttribName, new String());
else if (type.equals("Floating Point"))
attributes.setAttribute(testVal, newAttribName, new Double(0));
else if (type.equals("Integer"))
attributes.setAttribute(testVal, newAttribName, new Integer(0));
else if (type.equals("Boolean"))
attributes.setAttribute(testVal, newAttribName, new Boolean(false));
else if (type.equals("String List")) {
final List<String> newStringList = new ArrayList<String>();
newStringList.add("dummy");
attributes.setListAttribute(testVal, newAttribName, newStringList);
} else if (type.equals("Floating Point List")) {
final List<Double> newDoubleList = new ArrayList<Double>();
newDoubleList.add(0.0);
attributes.setListAttribute(testVal, newAttribName, newDoubleList);
} else if (type.equals("Integer List")) {
final List<Integer> newIntList = new ArrayList<Integer>();
newIntList.add(0);
attributes.setListAttribute(testVal, newAttribName, newIntList);
} else if (type.equals("Boolean List")) {
final List<Boolean> newBooleanList = new ArrayList<Boolean>();
newBooleanList.add(true);
attributes.setListAttribute(testVal, newAttribName, newBooleanList);
} else
throw new IllegalArgumentException("unknown attribute type \"" + type + "\"!");
attributes.deleteAttribute(testVal, newAttribName);
// Update list selection
orderedCol.add(newAttribName);
Cytoscape.getSwingPropertyChangeSupport()
.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null);
Cytoscape.getPropertyChangeSupport().firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null);
tableModel.setTableData(null, orderedCol);
}" |
Inversion-Mutation | megadiff | "@Override
public int processLineContent(String line, int offset) {
if (blockLineCount == 0) {
setOptions(matcher.group(1));
offset = matcher.start(2);
beginBlock();
}
int end = line.length();
int segmentEnd = end;
boolean terminating = false;
if (offset < end) {
Matcher endMatcher = endPattern.matcher(line);
if (blockLineCount == 0) {
endMatcher.region(offset, end);
}
if (endMatcher.find()) {
terminating = true;
end = endMatcher.start(2);
segmentEnd = endMatcher.start(1);
}
}
if (end < line.length()) {
state.setLineSegmentEndOffset(end);
}
++blockLineCount;
final String content = line.substring(offset, segmentEnd);
handleBlockContent(content);
if (terminating) {
setClosed(true);
}
return end == line.length() ? -1 : end;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "processLineContent" | "@Override
public int processLineContent(String line, int offset) {
if (blockLineCount == 0) {
setOptions(matcher.group(1));
offset = matcher.start(2);
beginBlock();
}
int end = line.length();
int segmentEnd = end;
boolean terminating = false;
<MASK>Matcher endMatcher = endPattern.matcher(line);</MASK>
if (offset < end) {
if (blockLineCount == 0) {
endMatcher.region(offset, end);
}
if (endMatcher.find()) {
terminating = true;
end = endMatcher.start(2);
segmentEnd = endMatcher.start(1);
}
}
if (end < line.length()) {
state.setLineSegmentEndOffset(end);
}
++blockLineCount;
final String content = line.substring(offset, segmentEnd);
handleBlockContent(content);
if (terminating) {
setClosed(true);
}
return end == line.length() ? -1 : end;
}" |
Inversion-Mutation | megadiff | "@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0 && fromUser)
progress = 1;
mNwkInfo.setTimes(progress, 0);
updateFdText();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onProgressChanged" | "@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (progress == 0 && fromUser)
progress = 1;
<MASK>updateFdText();</MASK>
mNwkInfo.setTimes(progress, 0);
}" |
Inversion-Mutation | megadiff | "@Override
protected void finalize() throws Throwable {
mOpenHelper.close();
mDatabase.close();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "finalize" | "@Override
protected void finalize() throws Throwable {
<MASK>mDatabase.close();</MASK>
mOpenHelper.close();
}" |
Inversion-Mutation | megadiff | "public void onLogout(LoginEvent.Logout event) {
finishActivityIfPermissionDenied();
setUserid();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onLogout" | "public void onLogout(LoginEvent.Logout event) {
<MASK>setUserid();</MASK>
finishActivityIfPermissionDenied();
}" |
Inversion-Mutation | megadiff | "public boolean addValue(String key, double value) {
GenericDataElement logElement = this.get(key);
if(key.equals(firstKey)){
lineCountElement.add((double)lineCount);
lineCount++;
}
return logElement.add(value);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addValue" | "public boolean addValue(String key, double value) {
GenericDataElement logElement = this.get(key);
if(key.equals(firstKey)){
<MASK>lineCount++;</MASK>
lineCountElement.add((double)lineCount);
}
return logElement.add(value);
}" |
Inversion-Mutation | megadiff | "public void setValues() {
Settings settings = Settings.getInstance();
setTitle(getString(R.string.preferencesType).replaceAll("%s", settings.getSettingsName(this)));
SharedPreferences preferences = settings.getSharedPreferences(this);
automaticUpdate.setChecked(preferences.getBoolean(Settings.AUTOMATIC_UPDATE, Settings.AUTOMATIC_UPDATE_DEFAULT));
updateInterval.setEnabled(automaticUpdate.isChecked());
updateInterval.setValue(preferences.getString(Settings.UPDATE_INTERVAL, Settings.UPDATE_INTERVAL_DEFAULT));
filter.setText(preferences.getString(Settings.FILTER, ""));
showAvatar.setChecked(preferences.getBoolean(Settings.SHOW_AVATAR, Settings.SHOW_AVATAR_DEFAULT));
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setValues" | "public void setValues() {
Settings settings = Settings.getInstance();
setTitle(getString(R.string.preferencesType).replaceAll("%s", settings.getSettingsName(this)));
SharedPreferences preferences = settings.getSharedPreferences(this);
<MASK>updateInterval.setEnabled(automaticUpdate.isChecked());</MASK>
automaticUpdate.setChecked(preferences.getBoolean(Settings.AUTOMATIC_UPDATE, Settings.AUTOMATIC_UPDATE_DEFAULT));
updateInterval.setValue(preferences.getString(Settings.UPDATE_INTERVAL, Settings.UPDATE_INTERVAL_DEFAULT));
filter.setText(preferences.getString(Settings.FILTER, ""));
showAvatar.setChecked(preferences.getBoolean(Settings.SHOW_AVATAR, Settings.SHOW_AVATAR_DEFAULT));
}" |
Inversion-Mutation | megadiff | "@Override
protected void onNodeDestroy(Node node) {
if (dashboard != null) {
dashboard.stop();
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
}});
dashboard = null;
}
if (twistPub != null) {
twistPub.shutdown();
twistPub = null;
}
if (cameraView != null) {
cameraView.stop();
cameraView = null;
}
if (statusSub != null) {
statusSub.shutdown();
statusSub = null;
}
if (pubThread != null) {
pubThread.interrupt();
pubThread = null;
}
super.onNodeDestroy(node);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onNodeDestroy" | "@Override
protected void onNodeDestroy(Node node) {
if (dashboard != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
LinearLayout top = (LinearLayout)findViewById(R.id.top_bar);
top.removeView((View)dashboard);
}});
dashboard = null;
}
if (twistPub != null) {
twistPub.shutdown();
twistPub = null;
}
if (cameraView != null) {
cameraView.stop();
cameraView = null;
}
if (statusSub != null) {
statusSub.shutdown();
statusSub = null;
}
if (pubThread != null) {
pubThread.interrupt();
pubThread = null;
}
<MASK>dashboard.stop();</MASK>
super.onNodeDestroy(node);
}" |
Inversion-Mutation | megadiff | "@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY);
business = getIntent().getStringExtra(KEY_BUSINESS);
// this next part will wait indefinitely for the data from the server.
getServerData(ServerInterface.getPuzzleData(business, getString(R.string.server_url)));
String mystring = getResources().getString(R.string.game_title);
setTitle(mystring + " Key " + getAlphaSub());
puzzle = getPuzzle(diff);
calculateUsedTiles();
puzzleView = new PuzzleView(this);
setContentView(puzzleView);
puzzleView.requestFocus();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "onCreate" | "@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY);
business = getIntent().getStringExtra(KEY_BUSINESS);
// this next part will wait indefinitely for the data from the server.
getServerData(ServerInterface.getPuzzleData(business, getString(R.string.server_url)));
<MASK>calculateUsedTiles();</MASK>
String mystring = getResources().getString(R.string.game_title);
setTitle(mystring + " Key " + getAlphaSub());
puzzle = getPuzzle(diff);
puzzleView = new PuzzleView(this);
setContentView(puzzleView);
puzzleView.requestFocus();
}" |
Inversion-Mutation | megadiff | "public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) {
if (mGlSurfaceView != null) {
mRenderer.deleteImage();
mRenderer.runOnDraw(new Runnable() {
@Override
public void run() {
synchronized(mFilter) {
mFilter.destroy();
mFilter.notify();
}
}
});
synchronized(mFilter) {
requestRender();
try {
mFilter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPUImageRenderer renderer = new GPUImageRenderer(mFilter);
renderer.setRotation(Rotation.NORMAL,
mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically());
renderer.setScaleType(mScaleType);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
renderer.setImageBitmap(bitmap, false);
Bitmap result = buffer.getBitmap();
mFilter.destroy();
renderer.deleteImage();
buffer.destroy();
mRenderer.setFilter(mFilter);
if (mCurrentBitmap != null) {
mRenderer.setImageBitmap(mCurrentBitmap, false);
}
requestRender();
return result;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "getBitmapWithFilterApplied" | "public Bitmap getBitmapWithFilterApplied(final Bitmap bitmap) {
if (mGlSurfaceView != null) {
mRenderer.deleteImage();
mRenderer.runOnDraw(new Runnable() {
@Override
public void run() {
synchronized(mFilter) {
mFilter.destroy();
mFilter.notify();
}
}
});
<MASK>requestRender();</MASK>
synchronized(mFilter) {
try {
mFilter.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPUImageRenderer renderer = new GPUImageRenderer(mFilter);
renderer.setRotation(Rotation.NORMAL,
mRenderer.isFlippedHorizontally(), mRenderer.isFlippedVertically());
renderer.setScaleType(mScaleType);
PixelBuffer buffer = new PixelBuffer(bitmap.getWidth(), bitmap.getHeight());
buffer.setRenderer(renderer);
renderer.setImageBitmap(bitmap, false);
Bitmap result = buffer.getBitmap();
mFilter.destroy();
renderer.deleteImage();
buffer.destroy();
mRenderer.setFilter(mFilter);
if (mCurrentBitmap != null) {
mRenderer.setImageBitmap(mCurrentBitmap, false);
}
<MASK>requestRender();</MASK>
return result;
}" |
Inversion-Mutation | megadiff | "public void doDeleteUser(FormEvent evt)
throws PortletException {
PortletRequest req = evt.getPortletRequest();
HiddenFieldBean hf = evt.getHiddenFieldBean("userID");
String userId = hf.getValue();
User user = this.userManagerService.getUser(userId);
if (user != null) {
req.setAttribute("user", user);
this.passwordManagerService.deletePassword(user);
List userRoles = this.roleManagerService.getRolesForUser(user);
Iterator ur = userRoles.iterator();
while (ur.hasNext()) {
PortletRole pr = (PortletRole)ur.next();
this.roleManagerService.deleteUserInRole(user, pr);
}
this.userManagerService.deleteUser(user);
createSuccessMessage(evt, this.getLocalizedText(req, "USER_DELETE_SUCCESS"));
}
setNextState(req, "doListUsers");
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "doDeleteUser" | "public void doDeleteUser(FormEvent evt)
throws PortletException {
PortletRequest req = evt.getPortletRequest();
HiddenFieldBean hf = evt.getHiddenFieldBean("userID");
String userId = hf.getValue();
User user = this.userManagerService.getUser(userId);
if (user != null) {
req.setAttribute("user", user);
<MASK>this.userManagerService.deleteUser(user);</MASK>
this.passwordManagerService.deletePassword(user);
List userRoles = this.roleManagerService.getRolesForUser(user);
Iterator ur = userRoles.iterator();
while (ur.hasNext()) {
PortletRole pr = (PortletRole)ur.next();
this.roleManagerService.deleteUserInRole(user, pr);
}
createSuccessMessage(evt, this.getLocalizedText(req, "USER_DELETE_SUCCESS"));
}
setNextState(req, "doListUsers");
}" |
Inversion-Mutation | megadiff | "public PData(String userName, String nickName, ArrayList<IPLogin> logIns, ArrayList<Long> logOuts, long timePlayed, Data[] data) {
this.username = userName;
this.displayname = nickName;
if (this.displayname == null || this.displayname.length() == 0) {
this.displayname = this.username;
}
this.logIns.addAll(logIns);
this.logOuts.addAll(logOuts);
this.timePlayed = timePlayed;
this.data.addAll(Arrays.asList(data));
setDataOwners();
currentSession = System.currentTimeMillis();
sortTimes();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "PData" | "public PData(String userName, String nickName, ArrayList<IPLogin> logIns, ArrayList<Long> logOuts, long timePlayed, Data[] data) {
this.username = userName;
this.displayname = nickName;
if (this.displayname == null || this.displayname.length() == 0) {
this.displayname = this.username;
}
this.logIns.addAll(logIns);
this.logOuts.addAll(logOuts);
this.timePlayed = timePlayed;
<MASK>setDataOwners();</MASK>
this.data.addAll(Arrays.asList(data));
currentSession = System.currentTimeMillis();
sortTimes();
}" |
Inversion-Mutation | megadiff | "protected void pingTimerTask(final Timer timer) {
if (!pingTimer.equals(timer)) { return; }
if (pingNeeded) {
if (!callPingFailed()) {
pingTimer.cancel();
disconnect("Server not responding.");
}
} else {
--pingCountDown;
if (pingCountDown < 1) {
pingTime = System.currentTimeMillis();
setPingNeeded(true);
pingCountDown = pingCountDownLength;
sendLine("PING "+System.currentTimeMillis());
}
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "pingTimerTask" | "protected void pingTimerTask(final Timer timer) {
if (!pingTimer.equals(timer)) { return; }
if (pingNeeded) {
if (!callPingFailed()) {
pingTimer.cancel();
disconnect("Server not responding.");
}
} else {
--pingCountDown;
if (pingCountDown < 1) {
<MASK>sendLine("PING "+System.currentTimeMillis());</MASK>
pingTime = System.currentTimeMillis();
setPingNeeded(true);
pingCountDown = pingCountDownLength;
}
}
}" |
Inversion-Mutation | megadiff | "public boolean waitForPending() {
for (int i = 0; i < Timing.REPEAT;i++) {
if (!isPending()) {
return true;
}
refresh();
tasks.waitFor(Timing.TIME_10S);
}
return false;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "waitForPending" | "public boolean waitForPending() {
for (int i = 0; i < Timing.REPEAT;i++) {
if (!isPending()) {
return true;
}
<MASK>tasks.waitFor(Timing.TIME_10S);</MASK>
refresh();
}
return false;
}" |
Inversion-Mutation | megadiff | "private void setUpUIComponents() {
Resources r = getResources();
// set up tab host
TabHost tabHost = getTabHost();
tabHost.setPadding(0, 4, 0, 0);
LayoutInflater.from(this).inflate(R.layout.task_edit_activity,
tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_basic)).
setIndicator(r.getString(R.string.TEA_tab_basic),
r.getDrawable(R.drawable.tab_edit)).setContent(
R.id.tab_basic));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_extra)).
setIndicator(r.getString(R.string.TEA_tab_extra),
r.getDrawable(R.drawable.tab_advanced)).setContent(
R.id.tab_extra));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_addons)).
setIndicator(r.getString(R.string.TEA_tab_addons),
r.getDrawable(R.drawable.tab_addons)).setContent(
R.id.tab_addons));
getTabWidget().setBackgroundColor(Color.BLACK);
// populate control set
title = (EditText) findViewById(R.id.title);
controls.add(new EditTextControlSet(Task.TITLE, R.id.title));
controls.add(new ImportanceControlSet(R.id.importance_container));
controls.add(new UrgencyControlSet(R.id.urgency));
notesEditText = (EditText) findViewById(R.id.notes);
// prepare and set listener for voice-button
if(addOnService.hasPowerPack()) {
voiceAddNoteButton = (ImageButton) findViewById(R.id.voiceAddNoteButton);
voiceAddNoteButton.setVisibility(View.VISIBLE);
int prompt = R.string.voice_edit_note_prompt;
voiceNoteAssistant = new VoiceInputAssistant(this, voiceAddNoteButton,
notesEditText);
voiceNoteAssistant.setAppend(true);
voiceNoteAssistant.setLanguageModel(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voiceNoteAssistant.configureMicrophoneButton(prompt);
}
new Thread() {
@Override
public void run() {
AndroidUtilities.sleepDeep(500L);
runOnUiThread(new Runnable() {
public void run() {
// internal add-ins
controls.add(new TagsControlSet(TaskEditActivity.this, R.id.tags_container));
LinearLayout extrasAddons = (LinearLayout) findViewById(R.id.tab_extra_addons);
controls.add(new RepeatControlSet(TaskEditActivity.this, extrasAddons));
controls.add(new GCalControlSet(TaskEditActivity.this, extrasAddons));
LinearLayout addonsAddons = (LinearLayout) findViewById(R.id.tab_addons_addons);
try {
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
controls.add(new ProducteevControlSet(TaskEditActivity.this, addonsAddons));
notesEditText.setHint(R.string.producteev_TEA_notes);
((TextView)findViewById(R.id.notes_label)).setHint(R.string.producteev_TEA_notes);
}
} catch (Exception e) {
Log.e("astrid-error", "loading-control-set", e); //$NON-NLS-1$ //$NON-NLS-2$
}
controls.add(new TimerControlSet(TaskEditActivity.this, addonsAddons));
controls.add(new AlarmControlSet(TaskEditActivity.this, addonsAddons));
if(!addOnService.hasPowerPack()) {
// show add-on help if necessary
View addonsEmpty = findViewById(R.id.addons_empty);
addonsEmpty.setVisibility(View.VISIBLE);
addonsAddons.removeView(addonsEmpty);
addonsAddons.addView(addonsEmpty);
((Button)findViewById(R.id.addons_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addOnActivity = new Intent(TaskEditActivity.this, AddOnActivity.class);
addOnActivity.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true);
startActivity(addOnActivity);
}
});
}
controls.add( new ReminderControlSet(R.id.reminder_due,
R.id.reminder_overdue, R.id.reminder_alarm));
controls.add(new RandomReminderControlSet(R.id.reminder_random,
R.id.reminder_random_interval));
controls.add(new HideUntilControlSet(R.id.hideUntil));
// re-read all
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
});
notesControlSet = new EditTextControlSet(Task.NOTES, R.id.notes);
controls.add(notesControlSet);
// set up listeners
setUpListeners();
}
}.start();
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "setUpUIComponents" | "private void setUpUIComponents() {
Resources r = getResources();
// set up tab host
TabHost tabHost = getTabHost();
tabHost.setPadding(0, 4, 0, 0);
LayoutInflater.from(this).inflate(R.layout.task_edit_activity,
tabHost.getTabContentView(), true);
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_basic)).
setIndicator(r.getString(R.string.TEA_tab_basic),
r.getDrawable(R.drawable.tab_edit)).setContent(
R.id.tab_basic));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_extra)).
setIndicator(r.getString(R.string.TEA_tab_extra),
r.getDrawable(R.drawable.tab_advanced)).setContent(
R.id.tab_extra));
tabHost.addTab(tabHost.newTabSpec(r.getString(R.string.TEA_tab_addons)).
setIndicator(r.getString(R.string.TEA_tab_addons),
r.getDrawable(R.drawable.tab_addons)).setContent(
R.id.tab_addons));
getTabWidget().setBackgroundColor(Color.BLACK);
// populate control set
title = (EditText) findViewById(R.id.title);
controls.add(new EditTextControlSet(Task.TITLE, R.id.title));
controls.add(new ImportanceControlSet(R.id.importance_container));
controls.add(new UrgencyControlSet(R.id.urgency));
// prepare and set listener for voice-button
if(addOnService.hasPowerPack()) {
voiceAddNoteButton = (ImageButton) findViewById(R.id.voiceAddNoteButton);
voiceAddNoteButton.setVisibility(View.VISIBLE);
<MASK>notesEditText = (EditText) findViewById(R.id.notes);</MASK>
int prompt = R.string.voice_edit_note_prompt;
voiceNoteAssistant = new VoiceInputAssistant(this, voiceAddNoteButton,
notesEditText);
voiceNoteAssistant.setAppend(true);
voiceNoteAssistant.setLanguageModel(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
voiceNoteAssistant.configureMicrophoneButton(prompt);
}
new Thread() {
@Override
public void run() {
AndroidUtilities.sleepDeep(500L);
runOnUiThread(new Runnable() {
public void run() {
// internal add-ins
controls.add(new TagsControlSet(TaskEditActivity.this, R.id.tags_container));
LinearLayout extrasAddons = (LinearLayout) findViewById(R.id.tab_extra_addons);
controls.add(new RepeatControlSet(TaskEditActivity.this, extrasAddons));
controls.add(new GCalControlSet(TaskEditActivity.this, extrasAddons));
LinearLayout addonsAddons = (LinearLayout) findViewById(R.id.tab_addons_addons);
try {
if(ProducteevUtilities.INSTANCE.isLoggedIn()) {
controls.add(new ProducteevControlSet(TaskEditActivity.this, addonsAddons));
notesEditText.setHint(R.string.producteev_TEA_notes);
((TextView)findViewById(R.id.notes_label)).setHint(R.string.producteev_TEA_notes);
}
} catch (Exception e) {
Log.e("astrid-error", "loading-control-set", e); //$NON-NLS-1$ //$NON-NLS-2$
}
controls.add(new TimerControlSet(TaskEditActivity.this, addonsAddons));
controls.add(new AlarmControlSet(TaskEditActivity.this, addonsAddons));
if(!addOnService.hasPowerPack()) {
// show add-on help if necessary
View addonsEmpty = findViewById(R.id.addons_empty);
addonsEmpty.setVisibility(View.VISIBLE);
addonsAddons.removeView(addonsEmpty);
addonsAddons.addView(addonsEmpty);
((Button)findViewById(R.id.addons_button)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent addOnActivity = new Intent(TaskEditActivity.this, AddOnActivity.class);
addOnActivity.putExtra(AddOnActivity.TOKEN_START_WITH_AVAILABLE, true);
startActivity(addOnActivity);
}
});
}
controls.add( new ReminderControlSet(R.id.reminder_due,
R.id.reminder_overdue, R.id.reminder_alarm));
controls.add(new RandomReminderControlSet(R.id.reminder_random,
R.id.reminder_random_interval));
controls.add(new HideUntilControlSet(R.id.hideUntil));
// re-read all
for(TaskEditControlSet controlSet : controls)
controlSet.readFromTask(model);
}
});
notesControlSet = new EditTextControlSet(Task.NOTES, R.id.notes);
controls.add(notesControlSet);
// set up listeners
setUpListeners();
}
}.start();
}" |
Inversion-Mutation | megadiff | "@SuppressLint("NewApi")
public static void Recreate(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
activity.recreate();
else{
activity.finish();
activity.startActivity(activity.getIntent());
}
CheckScreenRotation(activity);
CheckKeepAwake(activity);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "Recreate" | "@SuppressLint("NewApi")
public static void Recreate(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB )
activity.recreate();
else{
<MASK>activity.startActivity(activity.getIntent());</MASK>
activity.finish();
}
CheckScreenRotation(activity);
CheckKeepAwake(activity);
}" |
Inversion-Mutation | megadiff | "public void addRecipe(Player player, RecipeTemplate recipeTemplate)
{
int recipeId = recipeTemplate.getId();
if (!player.getRecipeList().isRecipePresent(recipeId))
{
recipeList.add(recipeId);
DAOManager.getDAO(PlayerRecipesDAO.class).addRecipe(player.getObjectId(), recipeId);
PacketSendUtility.sendPacket(player, new SM_LEARN_RECIPE(recipeId));
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.CRAFT_RECIPE_LEARN(new DescriptionId(recipeTemplate.getNameid())));
}
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "addRecipe" | "public void addRecipe(Player player, RecipeTemplate recipeTemplate)
{
int recipeId = recipeTemplate.getId();
<MASK>recipeList.add(recipeId);</MASK>
if (!player.getRecipeList().isRecipePresent(recipeId))
{
DAOManager.getDAO(PlayerRecipesDAO.class).addRecipe(player.getObjectId(), recipeId);
PacketSendUtility.sendPacket(player, new SM_LEARN_RECIPE(recipeId));
PacketSendUtility.sendPacket(player, SM_SYSTEM_MESSAGE.CRAFT_RECIPE_LEARN(new DescriptionId(recipeTemplate.getNameid())));
}
}" |
Inversion-Mutation | megadiff | "private static RuleBase createRuleBase() throws DroolsParserException {
System.out.println("Generating "+RULE_COUNT+" rules");
StringBuilder sb = new StringBuilder(LargeRuleBase.getHeader());
for (int i = 0; i < RULE_COUNT; i++) {
sb.append(LargeRuleBase.getTemplate1("testRule"+i, i));
}
System.out.println("Parsing "+RULE_COUNT+" rules");
PackageBuilder pkgBuilder = new PackageBuilder();
DrlParser ps = new DrlParser();
PackageDescr pkgDescr = ps.parse(new StringReader(sb.toString()));
pkgBuilder.addPackage(pkgDescr);
Package pkg = pkgBuilder.getPackage();
ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(pkg);
return ruleBase;
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "createRuleBase" | "private static RuleBase createRuleBase() throws DroolsParserException {
System.out.println("Generating "+RULE_COUNT+" rules");
StringBuilder sb = new StringBuilder(LargeRuleBase.getHeader());
for (int i = 0; i < RULE_COUNT; i++) {
sb.append(LargeRuleBase.getTemplate1("testRule"+i, i));
}
System.out.println("Parsing "+RULE_COUNT+" rules");
DrlParser ps = new DrlParser();
PackageDescr pkgDescr = ps.parse(new StringReader(sb.toString()));
<MASK>PackageBuilder pkgBuilder = new PackageBuilder();</MASK>
pkgBuilder.addPackage(pkgDescr);
Package pkg = pkgBuilder.getPackage();
ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(pkg);
return ruleBase;
}" |
Inversion-Mutation | megadiff | "@NotNull
protected GlobalTemplateContext buildGlobalContext(
@NotNull final List<TemplateDef<String>> templateDefs,
@NotNull final QueryJCommand parameters)
{
@NotNull final String templateName = retrieveTemplateName(parameters);
@NotNull final String outputPackage = retrieveOutputPackage(parameters);
@NotNull final File rootDir = retrieveRootDir(parameters);
return
new GlobalTemplateContextImpl(
templateName,
buildFilename(templateDefs, templateName),
outputPackage,
rootDir,
new File(rootDir.getAbsolutePath()
+ File.separator + outputPackage.replaceAll("\\.", File.separator)),
templateDefs);
}" | You are a Java Developer and you want to perform "Inversion-Mutation" by changing order of statementsfor provided "buildGlobalContext" | "@NotNull
protected GlobalTemplateContext buildGlobalContext(
@NotNull final List<TemplateDef<String>> templateDefs,
@NotNull final QueryJCommand parameters)
{
@NotNull final String templateName = retrieveTemplateName(parameters);
@NotNull final String outputPackage = retrieveOutputPackage(parameters);
@NotNull final File rootDir = retrieveRootDir(parameters);
return
new GlobalTemplateContextImpl(
templateName,
<MASK>outputPackage,</MASK>
buildFilename(templateDefs, templateName),
rootDir,
new File(rootDir.getAbsolutePath()
+ File.separator + outputPackage.replaceAll("\\.", File.separator)),
templateDefs);
}" |